@checksum-ai/runtime 4.15.0 → 4.16.0

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,63 +1,163 @@
1
- "use strict";var gd=Object.create;var Mt=Object.defineProperty;var _d=Object.getOwnPropertyDescriptor;var yd=Object.getOwnPropertyNames;var bd=Object.getPrototypeOf,wd=Object.prototype.hasOwnProperty;var o=(t,e)=>Mt(t,"name",{value:e,configurable:!0});var M=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},vd=(t,e)=>{for(var r in e)Mt(t,r,{get:e[r],enumerable:!0})},Ei=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of yd(e))!wd.call(t,a)&&a!==r&&Mt(t,a,{get:()=>e[a],enumerable:!(n=_d(e,a))||n.enumerable});return t};var xe=(t,e,r)=>(r=t!=null?gd(bd(t)):{},Ei(e||!t||!t.__esModule?Mt(r,"default",{value:t,enumerable:!0}):r,t)),Ed=t=>Ei(Mt({},"__esModule",{value:!0}),t);var bs=M((Gv,kn)=>{"use strict";var sp=Object.prototype.hasOwnProperty,fe="~";function Nt(){}o(Nt,"Events");Object.create&&(Nt.prototype=Object.create(null),new Nt().__proto__||(fe=!1));function op(t,e,r){this.fn=t,this.context=e,this.once=r||!1}o(op,"EE");function ys(t,e,r,n,a){if(typeof r!="function")throw new TypeError("The listener must be a function");var i=new op(r,n||t,a),s=fe?fe+e:e;return t._events[s]?t._events[s].fn?t._events[s]=[t._events[s],i]:t._events[s].push(i):(t._events[s]=i,t._eventsCount++),t}o(ys,"addListener");function br(t,e){--t._eventsCount===0?t._events=new Nt:delete t._events[e]}o(br,"clearEvent");function ce(){this._events=new Nt,this._eventsCount=0}o(ce,"EventEmitter");ce.prototype.eventNames=o(function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)sp.call(r,n)&&e.push(fe?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e},"eventNames");ce.prototype.listeners=o(function(e){var r=fe?fe+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var a=0,i=n.length,s=new Array(i);a<i;a++)s[a]=n[a].fn;return s},"listeners");ce.prototype.listenerCount=o(function(e){var r=fe?fe+e:e,n=this._events[r];return n?n.fn?1:n.length:0},"listenerCount");ce.prototype.emit=o(function(e,r,n,a,i,s){var l=fe?fe+e:e;if(!this._events[l])return!1;var c=this._events[l],u=arguments.length,p,m;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,a),!0;case 5:return c.fn.call(c.context,r,n,a,i),!0;case 6:return c.fn.call(c.context,r,n,a,i,s),!0}for(m=1,p=new Array(u-1);m<u;m++)p[m-1]=arguments[m];c.fn.apply(c.context,p)}else{var g=c.length,h;for(m=0;m<g;m++)switch(c[m].once&&this.removeListener(e,c[m].fn,void 0,!0),u){case 1:c[m].fn.call(c[m].context);break;case 2:c[m].fn.call(c[m].context,r);break;case 3:c[m].fn.call(c[m].context,r,n);break;case 4:c[m].fn.call(c[m].context,r,n,a);break;default:if(!p)for(h=1,p=new Array(u-1);h<u;h++)p[h-1]=arguments[h];c[m].fn.apply(c[m].context,p)}}return!0},"emit");ce.prototype.on=o(function(e,r,n){return ys(this,e,r,n,!1)},"on");ce.prototype.once=o(function(e,r,n){return ys(this,e,r,n,!0)},"once");ce.prototype.removeListener=o(function(e,r,n,a){var i=fe?fe+e:e;if(!this._events[i])return this;if(!r)return br(this,i),this;var s=this._events[i];if(s.fn)s.fn===r&&(!a||s.once)&&(!n||s.context===n)&&br(this,i);else{for(var l=0,c=[],u=s.length;l<u;l++)(s[l].fn!==r||a&&!s[l].once||n&&s[l].context!==n)&&c.push(s[l]);c.length?this._events[i]=c.length===1?c[0]:c:br(this,i)}return this},"removeListener");ce.prototype.removeAllListeners=o(function(e){var r;return e?(r=fe?fe+e:e,this._events[r]&&br(this,r)):(this._events=new Nt,this._eventsCount=0),this},"removeAllListeners");ce.prototype.off=ce.prototype.removeListener;ce.prototype.addListener=ce.prototype.on;ce.prefixed=fe;ce.EventEmitter=ce;typeof kn<"u"&&(kn.exports=ce)});var vs=M((zv,ws)=>{"use strict";ws.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 Ts=M((Vv,vr)=>{"use strict";var lp=vs(),wr=class extends Error{static{o(this,"TimeoutError")}constructor(e){super(e),this.name="TimeoutError"}},Es=o((t,e,r)=>new Promise((n,a)=>{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(c){a(c)}return}let s=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,l=r instanceof Error?r:new wr(s);typeof t.cancel=="function"&&t.cancel(),a(l)},e);lp(t.then(n,a),()=>{clearTimeout(i)})}),"pTimeout");vr.exports=Es;vr.exports.default=Es;vr.exports.TimeoutError=wr});var xs=M(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});function cp(t,e,r){let n=0,a=t.length;for(;a>0;){let i=a/2|0,s=n+i;r(t[s],e)<=0?(n=++s,a-=i+1):a=i}return n}o(cp,"lowerBound");Nn.default=cp});var Ss=M($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});var up=xs(),Pn=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 a=up.default(this._queue,n,(i,s)=>s.priority-i.priority);this._queue.splice(a,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}};$n.default=Pn});var Tr=M(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});var dp=bs(),As=Ts(),pp=Ss(),Er=o(()=>{},"empty"),fp=new As.TimeoutError,Ln=class extends dp{static{o(this,"PQueue")}constructor(e){var r,n,a,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=Er,this._resolveIdle=Er,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:pp.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=(a=e.interval)===null||a===void 0?void 0:a.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=Er,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=Er,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,a)=>{let i=o(async()=>{this._pendingCount++,this._intervalCount++;try{let s=this._timeout===void 0&&r.timeout===void 0?e():As.default(Promise.resolve(e()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&a(fp)});n(await s)}catch(s){a(s)}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}};Dn.default=Ln});var Ht=M((dS,Qo)=>{"use strict";var kf="2.0.0",Nf=Number.MAX_SAFE_INTEGER||9007199254740991,Pf=16,$f=250,Lf=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Qo.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Pf,MAX_SAFE_BUILD_LENGTH:$f,MAX_SAFE_INTEGER:Nf,RELEASE_TYPES:Lf,SEMVER_SPEC_VERSION:kf,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var zt=M((pS,el)=>{"use strict";var Df=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};el.exports=Df});var At=M((Be,tl)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:_a,MAX_SAFE_BUILD_LENGTH:Ff,MAX_LENGTH:Uf}=Ht(),jf=zt();Be=tl.exports={};var Bf=Be.re=[],Gf=Be.safeRe=[],S=Be.src=[],Hf=Be.safeSrc=[],A=Be.t={},zf=0,ya="[a-zA-Z0-9-]",Vf=[["\\s",1],["\\d",Uf],[ya,Ff]],qf=o(t=>{for(let[e,r]of Vf)t=t.split(`${e}*`).join(`${e}{0,${r}}`).split(`${e}+`).join(`${e}{1,${r}}`);return t},"makeSafeRegex"),D=o((t,e,r)=>{let n=qf(e),a=zf++;jf(t,a,e),A[t]=a,S[a]=e,Hf[a]=n,Bf[a]=new RegExp(e,r?"g":void 0),Gf[a]=new RegExp(n,r?"g":void 0)},"createToken");D("NUMERICIDENTIFIER","0|[1-9]\\d*");D("NUMERICIDENTIFIERLOOSE","\\d+");D("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${ya}*`);D("MAINVERSION",`(${S[A.NUMERICIDENTIFIER]})\\.(${S[A.NUMERICIDENTIFIER]})\\.(${S[A.NUMERICIDENTIFIER]})`);D("MAINVERSIONLOOSE",`(${S[A.NUMERICIDENTIFIERLOOSE]})\\.(${S[A.NUMERICIDENTIFIERLOOSE]})\\.(${S[A.NUMERICIDENTIFIERLOOSE]})`);D("PRERELEASEIDENTIFIER",`(?:${S[A.NONNUMERICIDENTIFIER]}|${S[A.NUMERICIDENTIFIER]})`);D("PRERELEASEIDENTIFIERLOOSE",`(?:${S[A.NONNUMERICIDENTIFIER]}|${S[A.NUMERICIDENTIFIERLOOSE]})`);D("PRERELEASE",`(?:-(${S[A.PRERELEASEIDENTIFIER]}(?:\\.${S[A.PRERELEASEIDENTIFIER]})*))`);D("PRERELEASELOOSE",`(?:-?(${S[A.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${S[A.PRERELEASEIDENTIFIERLOOSE]})*))`);D("BUILDIDENTIFIER",`${ya}+`);D("BUILD",`(?:\\+(${S[A.BUILDIDENTIFIER]}(?:\\.${S[A.BUILDIDENTIFIER]})*))`);D("FULLPLAIN",`v?${S[A.MAINVERSION]}${S[A.PRERELEASE]}?${S[A.BUILD]}?`);D("FULL",`^${S[A.FULLPLAIN]}$`);D("LOOSEPLAIN",`[v=\\s]*${S[A.MAINVERSIONLOOSE]}${S[A.PRERELEASELOOSE]}?${S[A.BUILD]}?`);D("LOOSE",`^${S[A.LOOSEPLAIN]}$`);D("GTLT","((?:<|>)?=?)");D("XRANGEIDENTIFIERLOOSE",`${S[A.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);D("XRANGEIDENTIFIER",`${S[A.NUMERICIDENTIFIER]}|x|X|\\*`);D("XRANGEPLAIN",`[v=\\s]*(${S[A.XRANGEIDENTIFIER]})(?:\\.(${S[A.XRANGEIDENTIFIER]})(?:\\.(${S[A.XRANGEIDENTIFIER]})(?:${S[A.PRERELEASE]})?${S[A.BUILD]}?)?)?`);D("XRANGEPLAINLOOSE",`[v=\\s]*(${S[A.XRANGEIDENTIFIERLOOSE]})(?:\\.(${S[A.XRANGEIDENTIFIERLOOSE]})(?:\\.(${S[A.XRANGEIDENTIFIERLOOSE]})(?:${S[A.PRERELEASELOOSE]})?${S[A.BUILD]}?)?)?`);D("XRANGE",`^${S[A.GTLT]}\\s*${S[A.XRANGEPLAIN]}$`);D("XRANGELOOSE",`^${S[A.GTLT]}\\s*${S[A.XRANGEPLAINLOOSE]}$`);D("COERCEPLAIN",`(^|[^\\d])(\\d{1,${_a}})(?:\\.(\\d{1,${_a}}))?(?:\\.(\\d{1,${_a}}))?`);D("COERCE",`${S[A.COERCEPLAIN]}(?:$|[^\\d])`);D("COERCEFULL",S[A.COERCEPLAIN]+`(?:${S[A.PRERELEASE]})?(?:${S[A.BUILD]})?(?:$|[^\\d])`);D("COERCERTL",S[A.COERCE],!0);D("COERCERTLFULL",S[A.COERCEFULL],!0);D("LONETILDE","(?:~>?)");D("TILDETRIM",`(\\s*)${S[A.LONETILDE]}\\s+`,!0);Be.tildeTrimReplace="$1~";D("TILDE",`^${S[A.LONETILDE]}${S[A.XRANGEPLAIN]}$`);D("TILDELOOSE",`^${S[A.LONETILDE]}${S[A.XRANGEPLAINLOOSE]}$`);D("LONECARET","(?:\\^)");D("CARETTRIM",`(\\s*)${S[A.LONECARET]}\\s+`,!0);Be.caretTrimReplace="$1^";D("CARET",`^${S[A.LONECARET]}${S[A.XRANGEPLAIN]}$`);D("CARETLOOSE",`^${S[A.LONECARET]}${S[A.XRANGEPLAINLOOSE]}$`);D("COMPARATORLOOSE",`^${S[A.GTLT]}\\s*(${S[A.LOOSEPLAIN]})$|^$`);D("COMPARATOR",`^${S[A.GTLT]}\\s*(${S[A.FULLPLAIN]})$|^$`);D("COMPARATORTRIM",`(\\s*)${S[A.GTLT]}\\s*(${S[A.LOOSEPLAIN]}|${S[A.XRANGEPLAIN]})`,!0);Be.comparatorTrimReplace="$1$2$3";D("HYPHENRANGE",`^\\s*(${S[A.XRANGEPLAIN]})\\s+-\\s+(${S[A.XRANGEPLAIN]})\\s*$`);D("HYPHENRANGELOOSE",`^\\s*(${S[A.XRANGEPLAINLOOSE]})\\s+-\\s+(${S[A.XRANGEPLAINLOOSE]})\\s*$`);D("STAR","(<|>)?=?\\s*\\*");D("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");D("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Gr=M((mS,rl)=>{"use strict";var Wf=Object.freeze({loose:!0}),Kf=Object.freeze({}),Jf=o(t=>t?typeof t!="object"?Wf:t:Kf,"parseOptions");rl.exports=Jf});var ba=M((gS,il)=>{"use strict";var nl=/^[0-9]+$/,al=o((t,e)=>{if(typeof t=="number"&&typeof e=="number")return t===e?0:t<e?-1:1;let r=nl.test(t),n=nl.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:t<e?-1:1},"compareIdentifiers"),Zf=o((t,e)=>al(e,t),"rcompareIdentifiers");il.exports={compareIdentifiers:al,rcompareIdentifiers:Zf}});var ue=M((yS,ol)=>{"use strict";var Hr=zt(),{MAX_LENGTH:sl,MAX_SAFE_INTEGER:zr}=Ht(),{safeRe:Vr,t:qr}=At(),Yf=Gr(),{compareIdentifiers:wa}=ba(),va=class t{static{o(this,"SemVer")}constructor(e,r){if(r=Yf(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>sl)throw new TypeError(`version is longer than ${sl} characters`);Hr("SemVer",e,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=e.trim().match(r.loose?Vr[qr.LOOSE]:Vr[qr.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>zr||this.major<0)throw new TypeError("Invalid major version");if(this.minor>zr||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>zr||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(a=>{if(/^[0-9]+$/.test(a)){let i=+a;if(i>=0&&i<zr)return i}return a}):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(Hr("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],a=e.prerelease[r];if(Hr("prerelease compare",r,n,a),n===void 0&&a===void 0)return 0;if(a===void 0)return 1;if(n===void 0)return-1;if(n===a)continue;return wa(n,a)}while(++r)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let r=0;do{let n=this.build[r],a=e.build[r];if(Hr("build compare",r,n,a),n===void 0&&a===void 0)return 0;if(a===void 0)return 1;if(n===void 0)return-1;if(n===a)continue;return wa(n,a)}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 a=`-${r}`.match(this.options.loose?Vr[qr.PRERELEASELOOSE]:Vr[qr.PRERELEASE]);if(!a||a[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 a=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[a];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(a)}}if(r){let i=[r,a];n===!1&&(i=[r]),wa(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}};ol.exports=va});var pt=M((wS,cl)=>{"use strict";var ll=ue(),Xf=o((t,e,r=!1)=>{if(t instanceof ll)return t;try{return new ll(t,e)}catch(n){if(!r)return null;throw n}},"parse");cl.exports=Xf});var dl=M((ES,ul)=>{"use strict";var Qf=pt(),em=o((t,e)=>{let r=Qf(t,e);return r?r.version:null},"valid");ul.exports=em});var fl=M((xS,pl)=>{"use strict";var tm=pt(),rm=o((t,e)=>{let r=tm(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null},"clean");pl.exports=rm});var gl=M((AS,hl)=>{"use strict";var ml=ue(),nm=o((t,e,r,n,a)=>{typeof r=="string"&&(a=n,n=r,r=void 0);try{return new ml(t instanceof ml?t.version:t,r).inc(e,n,a).version}catch{return null}},"inc");hl.exports=nm});var bl=M((CS,yl)=>{"use strict";var _l=pt(),am=o((t,e)=>{let r=_l(t,null,!0),n=_l(e,null,!0),a=r.compare(n);if(a===0)return null;let i=a>0,s=i?r:n,l=i?n:r,c=!!s.prerelease.length;if(!!l.prerelease.length&&!c){if(!l.patch&&!l.minor)return"major";if(l.compareMain(s)===0)return l.minor&&!l.patch?"minor":"patch"}let p=c?"pre":"";return r.major!==n.major?p+"major":r.minor!==n.minor?p+"minor":r.patch!==n.patch?p+"patch":"prerelease"},"diff");yl.exports=am});var vl=M((RS,wl)=>{"use strict";var im=ue(),sm=o((t,e)=>new im(t,e).major,"major");wl.exports=sm});var Tl=M((kS,El)=>{"use strict";var om=ue(),lm=o((t,e)=>new om(t,e).minor,"minor");El.exports=lm});var Sl=M((PS,xl)=>{"use strict";var cm=ue(),um=o((t,e)=>new cm(t,e).patch,"patch");xl.exports=um});var Il=M((LS,Al)=>{"use strict";var dm=pt(),pm=o((t,e)=>{let r=dm(t,e);return r&&r.prerelease.length?r.prerelease:null},"prerelease");Al.exports=pm});var Ae=M((FS,Ol)=>{"use strict";var Cl=ue(),fm=o((t,e,r)=>new Cl(t,r).compare(new Cl(e,r)),"compare");Ol.exports=fm});var Ml=M((jS,Rl)=>{"use strict";var mm=Ae(),hm=o((t,e,r)=>mm(e,t,r),"rcompare");Rl.exports=hm});var Nl=M((GS,kl)=>{"use strict";var gm=Ae(),_m=o((t,e)=>gm(t,e,!0),"compareLoose");kl.exports=_m});var Wr=M((zS,$l)=>{"use strict";var Pl=ue(),ym=o((t,e,r)=>{let n=new Pl(t,r),a=new Pl(e,r);return n.compare(a)||n.compareBuild(a)},"compareBuild");$l.exports=ym});var Dl=M((qS,Ll)=>{"use strict";var bm=Wr(),wm=o((t,e)=>t.sort((r,n)=>bm(r,n,e)),"sort");Ll.exports=wm});var Ul=M((KS,Fl)=>{"use strict";var vm=Wr(),Em=o((t,e)=>t.sort((r,n)=>vm(n,r,e)),"rsort");Fl.exports=Em});var Vt=M((ZS,jl)=>{"use strict";var Tm=Ae(),xm=o((t,e,r)=>Tm(t,e,r)>0,"gt");jl.exports=xm});var Kr=M((XS,Bl)=>{"use strict";var Sm=Ae(),Am=o((t,e,r)=>Sm(t,e,r)<0,"lt");Bl.exports=Am});var Ea=M((eA,Gl)=>{"use strict";var Im=Ae(),Cm=o((t,e,r)=>Im(t,e,r)===0,"eq");Gl.exports=Cm});var Ta=M((rA,Hl)=>{"use strict";var Om=Ae(),Rm=o((t,e,r)=>Om(t,e,r)!==0,"neq");Hl.exports=Rm});var Jr=M((aA,zl)=>{"use strict";var Mm=Ae(),km=o((t,e,r)=>Mm(t,e,r)>=0,"gte");zl.exports=km});var Zr=M((sA,Vl)=>{"use strict";var Nm=Ae(),Pm=o((t,e,r)=>Nm(t,e,r)<=0,"lte");Vl.exports=Pm});var xa=M((lA,ql)=>{"use strict";var $m=Ea(),Lm=Ta(),Dm=Vt(),Fm=Jr(),Um=Kr(),jm=Zr(),Bm=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 $m(t,r,n);case"!=":return Lm(t,r,n);case">":return Dm(t,r,n);case">=":return Fm(t,r,n);case"<":return Um(t,r,n);case"<=":return jm(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}},"cmp");ql.exports=Bm});var Kl=M((uA,Wl)=>{"use strict";var Gm=ue(),Hm=pt(),{safeRe:Yr,t:Xr}=At(),zm=o((t,e)=>{if(t instanceof Gm)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?Yr[Xr.COERCEFULL]:Yr[Xr.COERCE]);else{let c=e.includePrerelease?Yr[Xr.COERCERTLFULL]:Yr[Xr.COERCERTL],u;for(;(u=c.exec(t))&&(!r||r.index+r[0].length!==t.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),c.lastIndex=u.index+u[1].length+u[2].length;c.lastIndex=-1}if(r===null)return null;let n=r[2],a=r[3]||"0",i=r[4]||"0",s=e.includePrerelease&&r[5]?`-${r[5]}`:"",l=e.includePrerelease&&r[6]?`+${r[6]}`:"";return Hm(`${n}.${a}.${i}${s}${l}`,e)},"coerce");Wl.exports=zm});var Zl=M((pA,Jl)=>{"use strict";var Sa=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 a=this.map.keys().next().value;this.delete(a)}this.map.set(e,r)}return this}};Jl.exports=Sa});var Ie=M((mA,ec)=>{"use strict";var Vm=/\s+/g,Aa=class t{static{o(this,"Range")}constructor(e,r){if(r=Wm(r),e instanceof t)return e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease?e:new t(e.raw,r);if(e instanceof Ia)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(Vm," "),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(a=>!Xl(a[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let a of this.set)if(a.length===1&&eh(a[0])){this.set=[a];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&&Xm)|(this.options.loose&&Qm))+":"+e,a=Yl.get(n);if(a)return a;let i=this.options.loose,s=i?me[de.HYPHENRANGELOOSE]:me[de.HYPHENRANGE];e=e.replace(s,uh(this.options.includePrerelease)),K("hyphen replace",e),e=e.replace(me[de.COMPARATORTRIM],Jm),K("comparator trim",e),e=e.replace(me[de.TILDETRIM],Zm),K("tilde trim",e),e=e.replace(me[de.CARETTRIM],Ym),K("caret trim",e);let l=e.split(" ").map(m=>th(m,this.options)).join(" ").split(/\s+/).map(m=>ch(m,this.options));i&&(l=l.filter(m=>(K("loose invalid filter",m,this.options),!!m.match(me[de.COMPARATORLOOSE])))),K("range list",l);let c=new Map,u=l.map(m=>new Ia(m,this.options));for(let m of u){if(Xl(m))return[m];c.set(m.value,m)}c.size>1&&c.has("")&&c.delete("");let p=[...c.values()];return Yl.set(n,p),p}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(n=>Ql(n,r)&&e.set.some(a=>Ql(a,r)&&n.every(i=>a.every(s=>i.intersects(s,r)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new Km(e,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(dh(this.set[r],e,this.options))return!0;return!1}};ec.exports=Aa;var qm=Zl(),Yl=new qm,Wm=Gr(),Ia=qt(),K=zt(),Km=ue(),{safeRe:me,t:de,comparatorTrimReplace:Jm,tildeTrimReplace:Zm,caretTrimReplace:Ym}=At(),{FLAG_INCLUDE_PRERELEASE:Xm,FLAG_LOOSE:Qm}=Ht(),Xl=o(t=>t.value==="<0.0.0-0","isNullSet"),eh=o(t=>t.value==="","isAny"),Ql=o((t,e)=>{let r=!0,n=t.slice(),a=n.pop();for(;r&&n.length;)r=n.every(i=>a.intersects(i,e)),a=n.pop();return r},"isSatisfiable"),th=o((t,e)=>(t=t.replace(me[de.BUILD],""),K("comp",t,e),t=ah(t,e),K("caret",t),t=rh(t,e),K("tildes",t),t=sh(t,e),K("xrange",t),t=lh(t,e),K("stars",t),t),"parseComparator"),he=o(t=>!t||t.toLowerCase()==="x"||t==="*","isX"),rh=o((t,e)=>t.trim().split(/\s+/).map(r=>nh(r,e)).join(" "),"replaceTildes"),nh=o((t,e)=>{let r=e.loose?me[de.TILDELOOSE]:me[de.TILDE];return t.replace(r,(n,a,i,s,l)=>{K("tilde",t,n,a,i,s,l);let c;return he(a)?c="":he(i)?c=`>=${a}.0.0 <${+a+1}.0.0-0`:he(s)?c=`>=${a}.${i}.0 <${a}.${+i+1}.0-0`:l?(K("replaceTilde pr",l),c=`>=${a}.${i}.${s}-${l} <${a}.${+i+1}.0-0`):c=`>=${a}.${i}.${s} <${a}.${+i+1}.0-0`,K("tilde return",c),c})},"replaceTilde"),ah=o((t,e)=>t.trim().split(/\s+/).map(r=>ih(r,e)).join(" "),"replaceCarets"),ih=o((t,e)=>{K("caret",t,e);let r=e.loose?me[de.CARETLOOSE]:me[de.CARET],n=e.includePrerelease?"-0":"";return t.replace(r,(a,i,s,l,c)=>{K("caret",t,a,i,s,l,c);let u;return he(i)?u="":he(s)?u=`>=${i}.0.0${n} <${+i+1}.0.0-0`:he(l)?i==="0"?u=`>=${i}.${s}.0${n} <${i}.${+s+1}.0-0`:u=`>=${i}.${s}.0${n} <${+i+1}.0.0-0`:c?(K("replaceCaret pr",c),i==="0"?s==="0"?u=`>=${i}.${s}.${l}-${c} <${i}.${s}.${+l+1}-0`:u=`>=${i}.${s}.${l}-${c} <${i}.${+s+1}.0-0`:u=`>=${i}.${s}.${l}-${c} <${+i+1}.0.0-0`):(K("no pr"),i==="0"?s==="0"?u=`>=${i}.${s}.${l}${n} <${i}.${s}.${+l+1}-0`:u=`>=${i}.${s}.${l}${n} <${i}.${+s+1}.0-0`:u=`>=${i}.${s}.${l} <${+i+1}.0.0-0`),K("caret return",u),u})},"replaceCaret"),sh=o((t,e)=>(K("replaceXRanges",t,e),t.split(/\s+/).map(r=>oh(r,e)).join(" ")),"replaceXRanges"),oh=o((t,e)=>{t=t.trim();let r=e.loose?me[de.XRANGELOOSE]:me[de.XRANGE];return t.replace(r,(n,a,i,s,l,c)=>{K("xRange",t,n,a,i,s,l,c);let u=he(i),p=u||he(s),m=p||he(l),g=m;return a==="="&&g&&(a=""),c=e.includePrerelease?"-0":"",u?a===">"||a==="<"?n="<0.0.0-0":n="*":a&&g?(p&&(s=0),l=0,a===">"?(a=">=",p?(i=+i+1,s=0,l=0):(s=+s+1,l=0)):a==="<="&&(a="<",p?i=+i+1:s=+s+1),a==="<"&&(c="-0"),n=`${a+i}.${s}.${l}${c}`):p?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:m&&(n=`>=${i}.${s}.0${c} <${i}.${+s+1}.0-0`),K("xRange return",n),n})},"replaceXRange"),lh=o((t,e)=>(K("replaceStars",t,e),t.trim().replace(me[de.STAR],"")),"replaceStars"),ch=o((t,e)=>(K("replaceGTE0",t,e),t.trim().replace(me[e.includePrerelease?de.GTE0PRE:de.GTE0],"")),"replaceGTE0"),uh=o(t=>(e,r,n,a,i,s,l,c,u,p,m,g)=>(he(n)?r="":he(a)?r=`>=${n}.0.0${t?"-0":""}`:he(i)?r=`>=${n}.${a}.0${t?"-0":""}`:s?r=`>=${r}`:r=`>=${r}${t?"-0":""}`,he(u)?c="":he(p)?c=`<${+u+1}.0.0-0`:he(m)?c=`<${u}.${+p+1}.0-0`:g?c=`<=${u}.${p}.${m}-${g}`:t?c=`<${u}.${p}.${+m+1}-0`:c=`<=${c}`,`${r} ${c}`.trim()),"hyphenReplace"),dh=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(K(t[n].semver),t[n].semver!==Ia.ANY&&t[n].semver.prerelease.length>0){let a=t[n].semver;if(a.major===e.major&&a.minor===e.minor&&a.patch===e.patch)return!0}return!1}return!0},"testSet")});var qt=M((gA,sc)=>{"use strict";var Wt=Symbol("SemVer ANY"),Ra=class t{static{o(this,"Comparator")}static get ANY(){return Wt}constructor(e,r){if(r=tc(r),e instanceof t){if(e.loose===!!r.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Oa("comparator",e,r),this.options=r,this.loose=!!r.loose,this.parse(e),this.semver===Wt?this.value="":this.value=this.operator+this.semver.version,Oa("comp",this)}parse(e){let r=this.options.loose?rc[nc.COMPARATORLOOSE]:rc[nc.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 ac(n[2],this.options.loose):this.semver=Wt}toString(){return this.value}test(e){if(Oa("Comparator.test",e,this.options.loose),this.semver===Wt||e===Wt)return!0;if(typeof e=="string")try{e=new ac(e,this.options)}catch{return!1}return Ca(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 ic(e.value,r).test(this.value):e.operator===""?e.value===""?!0:new ic(this.value,r).test(e.semver):(r=tc(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("=")||Ca(this.semver,"<",e.semver,r)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Ca(this.semver,">",e.semver,r)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};sc.exports=Ra;var tc=Gr(),{safeRe:rc,t:nc}=At(),Ca=xa(),Oa=zt(),ac=ue(),ic=Ie()});var Kt=M((yA,oc)=>{"use strict";var ph=Ie(),fh=o((t,e,r)=>{try{e=new ph(e,r)}catch{return!1}return e.test(t)},"satisfies");oc.exports=fh});var cc=M((wA,lc)=>{"use strict";var mh=Ie(),hh=o((t,e)=>new mh(t,e).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" ")),"toComparators");lc.exports=hh});var dc=M((EA,uc)=>{"use strict";var gh=ue(),_h=Ie(),yh=o((t,e,r)=>{let n=null,a=null,i=null;try{i=new _h(e,r)}catch{return null}return t.forEach(s=>{i.test(s)&&(!n||a.compare(s)===-1)&&(n=s,a=new gh(n,r))}),n},"maxSatisfying");uc.exports=yh});var fc=M((xA,pc)=>{"use strict";var bh=ue(),wh=Ie(),vh=o((t,e,r)=>{let n=null,a=null,i=null;try{i=new wh(e,r)}catch{return null}return t.forEach(s=>{i.test(s)&&(!n||a.compare(s)===1)&&(n=s,a=new bh(n,r))}),n},"minSatisfying");pc.exports=vh});var gc=M((AA,hc)=>{"use strict";var Ma=ue(),Eh=Ie(),mc=Vt(),Th=o((t,e)=>{t=new Eh(t,e);let r=new Ma("0.0.0");if(t.test(r)||(r=new Ma("0.0.0-0"),t.test(r)))return r;r=null;for(let n=0;n<t.set.length;++n){let a=t.set[n],i=null;a.forEach(s=>{let l=new Ma(s.semver.version);switch(s.operator){case">":l.prerelease.length===0?l.patch++:l.prerelease.push(0),l.raw=l.format();case"":case">=":(!i||mc(l,i))&&(i=l);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${s.operator}`)}}),i&&(!r||mc(r,i))&&(r=i)}return r&&t.test(r)?r:null},"minVersion");hc.exports=Th});var yc=M((CA,_c)=>{"use strict";var xh=Ie(),Sh=o((t,e)=>{try{return new xh(t,e).range||"*"}catch{return null}},"validRange");_c.exports=Sh});var Qr=M((RA,Ec)=>{"use strict";var Ah=ue(),vc=qt(),{ANY:Ih}=vc,Ch=Ie(),Oh=Kt(),bc=Vt(),wc=Kr(),Rh=Zr(),Mh=Jr(),kh=o((t,e,r,n)=>{t=new Ah(t,n),e=new Ch(e,n);let a,i,s,l,c;switch(r){case">":a=bc,i=Rh,s=wc,l=">",c=">=";break;case"<":a=wc,i=Mh,s=bc,l="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Oh(t,e,n))return!1;for(let u=0;u<e.set.length;++u){let p=e.set[u],m=null,g=null;if(p.forEach(h=>{h.semver===Ih&&(h=new vc(">=0.0.0")),m=m||h,g=g||h,a(h.semver,m.semver,n)?m=h:s(h.semver,g.semver,n)&&(g=h)}),m.operator===l||m.operator===c||(!g.operator||g.operator===l)&&i(t,g.semver))return!1;if(g.operator===c&&s(t,g.semver))return!1}return!0},"outside");Ec.exports=kh});var xc=M((kA,Tc)=>{"use strict";var Nh=Qr(),Ph=o((t,e,r)=>Nh(t,e,">",r),"gtr");Tc.exports=Ph});var Ac=M((PA,Sc)=>{"use strict";var $h=Qr(),Lh=o((t,e,r)=>$h(t,e,"<",r),"ltr");Sc.exports=Lh});var Oc=M((LA,Cc)=>{"use strict";var Ic=Ie(),Dh=o((t,e,r)=>(t=new Ic(t,r),e=new Ic(e,r),t.intersects(e,r)),"intersects");Cc.exports=Dh});var Mc=M((FA,Rc)=>{"use strict";var Fh=Kt(),Uh=Ae();Rc.exports=(t,e,r)=>{let n=[],a=null,i=null,s=t.sort((p,m)=>Uh(p,m,r));for(let p of s)Fh(p,e,r)?(i=p,a||(a=p)):(i&&n.push([a,i]),i=null,a=null);a&&n.push([a,null]);let l=[];for(let[p,m]of n)p===m?l.push(p):!m&&p===s[0]?l.push("*"):m?p===s[0]?l.push(`<=${m}`):l.push(`${p} - ${m}`):l.push(`>=${p}`);let c=l.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return c.length<u.length?c:e}});var Dc=M((UA,Lc)=>{"use strict";var kc=Ie(),Na=qt(),{ANY:ka}=Na,Jt=Kt(),Pa=Ae(),jh=o((t,e,r={})=>{if(t===e)return!0;t=new kc(t,r),e=new kc(e,r);let n=!1;e:for(let a of t.set){for(let i of e.set){let s=Gh(a,i,r);if(n=n||s!==null,s)continue e}if(n)return!1}return!0},"subset"),Bh=[new Na(">=0.0.0-0")],Nc=[new Na(">=0.0.0")],Gh=o((t,e,r)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===ka){if(e.length===1&&e[0].semver===ka)return!0;r.includePrerelease?t=Bh:t=Nc}if(e.length===1&&e[0].semver===ka){if(r.includePrerelease)return!0;e=Nc}let n=new Set,a,i;for(let h of t)h.operator===">"||h.operator===">="?a=Pc(a,h,r):h.operator==="<"||h.operator==="<="?i=$c(i,h,r):n.add(h.semver);if(n.size>1)return null;let s;if(a&&i){if(s=Pa(a.semver,i.semver,r),s>0)return null;if(s===0&&(a.operator!==">="||i.operator!=="<="))return null}for(let h of n){if(a&&!Jt(h,String(a),r)||i&&!Jt(h,String(i),r))return null;for(let E of e)if(!Jt(h,String(E),r))return!1;return!0}let l,c,u,p,m=i&&!r.includePrerelease&&i.semver.prerelease.length?i.semver:!1,g=a&&!r.includePrerelease&&a.semver.prerelease.length?a.semver:!1;m&&m.prerelease.length===1&&i.operator==="<"&&m.prerelease[0]===0&&(m=!1);for(let h of e){if(p=p||h.operator===">"||h.operator===">=",u=u||h.operator==="<"||h.operator==="<=",a){if(g&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===g.major&&h.semver.minor===g.minor&&h.semver.patch===g.patch&&(g=!1),h.operator===">"||h.operator===">="){if(l=Pc(a,h,r),l===h&&l!==a)return!1}else if(a.operator===">="&&!Jt(a.semver,String(h),r))return!1}if(i){if(m&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===m.major&&h.semver.minor===m.minor&&h.semver.patch===m.patch&&(m=!1),h.operator==="<"||h.operator==="<="){if(c=$c(i,h,r),c===h&&c!==i)return!1}else if(i.operator==="<="&&!Jt(i.semver,String(h),r))return!1}if(!h.operator&&(i||a)&&s!==0)return!1}return!(a&&u&&!i&&s!==0||i&&p&&!a&&s!==0||g||m)},"simpleSubset"),Pc=o((t,e,r)=>{if(!t)return e;let n=Pa(t.semver,e.semver,r);return n>0?t:n<0||e.operator===">"&&t.operator===">="?e:t},"higherGT"),$c=o((t,e,r)=>{if(!t)return e;let n=Pa(t.semver,e.semver,r);return n<0?t:n>0||e.operator==="<"&&t.operator==="<="?e:t},"lowerLT");Lc.exports=jh});var Bc=M((BA,jc)=>{"use strict";var $a=At(),Fc=Ht(),Hh=ue(),Uc=ba(),zh=pt(),Vh=dl(),qh=fl(),Wh=gl(),Kh=bl(),Jh=vl(),Zh=Tl(),Yh=Sl(),Xh=Il(),Qh=Ae(),eg=Ml(),tg=Nl(),rg=Wr(),ng=Dl(),ag=Ul(),ig=Vt(),sg=Kr(),og=Ea(),lg=Ta(),cg=Jr(),ug=Zr(),dg=xa(),pg=Kl(),fg=qt(),mg=Ie(),hg=Kt(),gg=cc(),_g=dc(),yg=fc(),bg=gc(),wg=yc(),vg=Qr(),Eg=xc(),Tg=Ac(),xg=Oc(),Sg=Mc(),Ag=Dc();jc.exports={parse:zh,valid:Vh,clean:qh,inc:Wh,diff:Kh,major:Jh,minor:Zh,patch:Yh,prerelease:Xh,compare:Qh,rcompare:eg,compareLoose:tg,compareBuild:rg,sort:ng,rsort:ag,gt:ig,lt:sg,eq:og,neq:lg,gte:cg,lte:ug,cmp:dg,coerce:pg,Comparator:fg,Range:mg,satisfies:hg,toComparators:gg,maxSatisfying:_g,minSatisfying:yg,minVersion:bg,validRange:wg,outside:vg,gtr:Eg,ltr:Tg,intersects:xg,simplifyRange:Sg,subset:Ag,SemVer:Hh,re:$a.re,src:$a.src,tokens:$a.t,SEMVER_SPEC_VERSION:Fc.SEMVER_SPEC_VERSION,RELEASE_TYPES:Fc.RELEASE_TYPES,compareIdentifiers:Uc.compareIdentifiers,rcompareIdentifiers:Uc.rcompareIdentifiers}});var Lu=M(hn=>{"use strict";hn.byteLength=Y_;hn.toByteArray=Q_;hn.fromByteArray=ry;var Ve=[],Oe=[],Z_=typeof Uint8Array<"u"?Uint8Array:Array,ii="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(gt=0,Pu=ii.length;gt<Pu;++gt)Ve[gt]=ii[gt],Oe[ii.charCodeAt(gt)]=gt;var gt,Pu;Oe[45]=62;Oe[95]=63;function $u(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($u,"getLens");function Y_(t){var e=$u(t),r=e[0],n=e[1];return(r+n)*3/4-n}o(Y_,"byteLength");function X_(t,e,r){return(e+r)*3/4-r}o(X_,"_byteLength");function Q_(t){var e,r=$u(t),n=r[0],a=r[1],i=new Z_(X_(t,n,a)),s=0,l=a>0?n-4:n,c;for(c=0;c<l;c+=4)e=Oe[t.charCodeAt(c)]<<18|Oe[t.charCodeAt(c+1)]<<12|Oe[t.charCodeAt(c+2)]<<6|Oe[t.charCodeAt(c+3)],i[s++]=e>>16&255,i[s++]=e>>8&255,i[s++]=e&255;return a===2&&(e=Oe[t.charCodeAt(c)]<<2|Oe[t.charCodeAt(c+1)]>>4,i[s++]=e&255),a===1&&(e=Oe[t.charCodeAt(c)]<<10|Oe[t.charCodeAt(c+1)]<<4|Oe[t.charCodeAt(c+2)]>>2,i[s++]=e>>8&255,i[s++]=e&255),i}o(Q_,"toByteArray");function ey(t){return Ve[t>>18&63]+Ve[t>>12&63]+Ve[t>>6&63]+Ve[t&63]}o(ey,"tripletToBase64");function ty(t,e,r){for(var n,a=[],i=e;i<r;i+=3)n=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),a.push(ey(n));return a.join("")}o(ty,"encodeChunk");function ry(t){for(var e,r=t.length,n=r%3,a=[],i=16383,s=0,l=r-n;s<l;s+=i)a.push(ty(t,s,s+i>l?l:s+i));return n===1?(e=t[r-1],a.push(Ve[e>>2]+Ve[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],a.push(Ve[e>>10]+Ve[e>>4&63]+Ve[e<<2&63]+"=")),a.join("")}o(ry,"fromByteArray")});var Qu=M((i4,Ze)=>{var pi=require("fs"),_n=require("path"),Ay=require("os"),Iy=require("crypto"),Ku=["\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 Cy(){return Ku[Math.floor(Math.random()*Ku.length)]}o(Cy,"_getRandomTip");function Rt(t){return typeof t=="string"?!["false","0","no","off",""].includes(t.toLowerCase()):!!t}o(Rt,"parseBoolean");function Oy(){return process.stdout.isTTY}o(Oy,"supportsAnsi");function Ry(t){return Oy()?`\x1B[2m${t}\x1B[0m`:t}o(Ry,"dim");var My=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function ky(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
2
- `);let n;for(;(n=My.exec(r))!=null;){let a=n[1],i=n[2]||"";i=i.trim();let s=i[0];i=i.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),s==='"'&&(i=i.replace(/\\n/g,`
3
- `),i=i.replace(/\\r/g,"\r")),e[a]=i}return e}o(ky,"parse");function Ny(t){t=t||{};let e=Xu(t);t.path=e;let r=ne.configDotenv(t);if(!r.parsed){let s=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw s.code="MISSING_DATA",s}let n=Yu(t).split(","),a=n.length,i;for(let s=0;s<a;s++)try{let l=n[s].trim(),c=$y(r,l);i=ne.decrypt(c.ciphertext,c.key);break}catch(l){if(s+1>=a)throw l}return ne.parse(i)}o(Ny,"_parseVault");function Py(t){console.error(`\u26A0 ${t}`)}o(Py,"_warn");function ir(t){console.log(`\u2506 ${t}`)}o(ir,"_debug");function Zu(t){console.log(`\u25C7 ${t}`)}o(Zu,"_log");function Yu(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(Yu,"_dotenvKey");function $y(t,e){let r;try{r=new URL(e)}catch(l){if(l.code==="ERR_INVALID_URL"){let c=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 c.code="INVALID_DOTENV_KEY",c}throw l}let n=r.password;if(!n){let l=new Error("INVALID_DOTENV_KEY: Missing key part");throw l.code="INVALID_DOTENV_KEY",l}let a=r.searchParams.get("environment");if(!a){let l=new Error("INVALID_DOTENV_KEY: Missing environment part");throw l.code="INVALID_DOTENV_KEY",l}let i=`DOTENV_VAULT_${a.toUpperCase()}`,s=t.parsed[i];if(!s){let l=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${i} in your .env.vault file.`);throw l.code="NOT_FOUND_DOTENV_ENVIRONMENT",l}return{ciphertext:s,key:n}}o($y,"_instructions");function Xu(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)pi.existsSync(r)&&(e=r.endsWith(".vault")?r:`${r}.vault`);else e=t.path.endsWith(".vault")?t.path:`${t.path}.vault`;else e=_n.resolve(process.cwd(),".env.vault");return pi.existsSync(e)?e:null}o(Xu,"_vaultPath");function Ju(t){return t[0]==="~"?_n.join(Ay.homedir(),t.slice(1)):t}o(Ju,"_resolveHome");function Ly(t){let e=Rt(process.env.DOTENV_CONFIG_DEBUG||t&&t.debug),r=Rt(process.env.DOTENV_CONFIG_QUIET||t&&t.quiet);(e||!r)&&Zu("loading env from encrypted .env.vault");let n=ne._parseVault(t),a=process.env;return t&&t.processEnv!=null&&(a=t.processEnv),ne.populate(a,n,t),{parsed:n}}o(Ly,"_configVault");function Dy(t){let e=_n.resolve(process.cwd(),".env"),r="utf8",n=process.env;t&&t.processEnv!=null&&(n=t.processEnv);let a=Rt(n.DOTENV_CONFIG_DEBUG||t&&t.debug),i=Rt(n.DOTENV_CONFIG_QUIET||t&&t.quiet);t&&t.encoding?r=t.encoding:a&&ir("no encoding is specified (UTF-8 is used by default)");let s=[e];if(t&&t.path)if(!Array.isArray(t.path))s=[Ju(t.path)];else{s=[];for(let p of t.path)s.push(Ju(p))}let l,c={};for(let p of s)try{let m=ne.parse(pi.readFileSync(p,{encoding:r}));ne.populate(c,m,t)}catch(m){a&&ir(`failed to load ${p} ${m.message}`),l=m}let u=ne.populate(n,c,t);if(a=Rt(n.DOTENV_CONFIG_DEBUG||a),i=Rt(n.DOTENV_CONFIG_QUIET||i),a||!i){let p=Object.keys(u).length,m=[];for(let g of s)try{let h=_n.relative(process.cwd(),g);m.push(h)}catch(h){a&&ir(`failed to load ${g} ${h.message}`),l=h}Zu(`injected env (${p}) from ${m.join(",")} ${Ry(`// tip: ${Cy()}`)}`)}return l?{parsed:c,error:l}:{parsed:c}}o(Dy,"configDotenv");function Fy(t){if(Yu(t).length===0)return ne.configDotenv(t);let e=Xu(t);return e?ne._configVault(t):(Py(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),ne.configDotenv(t))}o(Fy,"config");function Uy(t,e){let r=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(t,"base64"),a=n.subarray(0,12),i=n.subarray(-16);n=n.subarray(12,-16);try{let s=Iy.createDecipheriv("aes-256-gcm",r,a);return s.setAuthTag(i),`${s.update(n)}${s.final()}`}catch(s){let l=s instanceof RangeError,c=s.message==="Invalid key length",u=s.message==="Unsupported state or unable to authenticate data";if(l||c){let p=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw p.code="INVALID_DOTENV_KEY",p}else if(u){let p=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw p.code="DECRYPTION_FAILED",p}else throw s}}o(Uy,"decrypt");function jy(t,e,r={}){let n=!!(r&&r.debug),a=!!(r&&r.override),i={};if(typeof e!="object"){let s=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw s.code="OBJECT_REQUIRED",s}for(let s of Object.keys(e))Object.prototype.hasOwnProperty.call(t,s)?(a===!0&&(t[s]=e[s],i[s]=e[s]),n&&ir(a===!0?`"${s}" is already defined and WAS overwritten`:`"${s}" is already defined and was NOT overwritten`)):(t[s]=e[s],i[s]=e[s]);return i}o(jy,"populate");var ne={configDotenv:Dy,_configVault:Ly,_parseVault:Ny,config:Fy,decrypt:Uy,parse:ky,populate:jy};Ze.exports.configDotenv=ne.configDotenv;Ze.exports._configVault=ne._configVault;Ze.exports._parseVault=ne._parseVault;Ze.exports.config=ne.config;Ze.exports.decrypt=ne.decrypt;Ze.exports.parse=ne.parse;Ze.exports.populate=ne.populate;Ze.exports=ne});var pb={};vd(pb,{default:()=>bn});module.exports=Ed(pb);var pd=require("path");var w4=require("@playwright/test");var UU=require("@playwright/test");var zb=require("@playwright/test");var jb=require("@playwright/test");var Ti=Object.defineProperty,j=o((t,e)=>{let r={};for(var n in t)Ti(r,n,{get:t[n],enumerable:!0});return e||Ti(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll");function xi(t){let e=Symbol.for(t);return{brand(r,n){let a=n?Symbol.for(`${t}.${n}`):e;class i extends r{static{o(this,"_Branded")}[a]=!0;constructor(...l){super(...l)}static isInstance(l){return typeof l=="object"&&l!==null&&a in l&&l[a]===!0}}return Object.defineProperty(i,"name",{value:r.name}),i},sub(r){return xi(`${t}.${r}`)},isInstance(r){return typeof r=="object"&&r!==null&&e in r&&r[e]===!0}}}o(xi,"createNamespace");var Si=xi("langchain");var xn=Si.sub("error"),Ai=class extends xn.brand(Error){static{o(this,"LangChainError")}name="LangChainError";constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},Td=class extends xn.brand(Ai,"model-abort"){static{o(this,"ModelAbortError")}name="ModelAbortError";partialOutput;constructor(t,e){super(t),this.partialOutput=e}},ew=class Ii extends xn.brand(Ai,"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 Ii(e.message);return r.cause=e,r}};var xd=/([A-Z]+)([A-Z][a-z0-9]+)/g,Sd=/([a-z0-9])([A-Z])/g,Ad=/[-_\s]+/g;function Id(t){return t.replace(xd,"$1_$2").replace(Sd,"$1_$2").replace(Ad,"_").toLowerCase()}o(Id,"snakeCase");function Ci(t,e){return e?.[t]||Id(t)}o(Ci,"keyToJson");function Oi(t,e,r){let n={};for(let a in t)Object.hasOwn(t,a)&&(n[e(a,r)]=t[a]);return n}o(Oi,"mapKeys");var Cd="__lc_escaped__";function Od(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}o(Od,"needsEscaping");function Rd(t){return{[Cd]:t}}o(Rd,"escapeObject");function Md(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}o(Md,"isSerializableLike");function kd(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(kd,"createNotImplemented");function lr(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return kd(t);if(Md(t))return t;e.add(t);let r=t;if(Od(r))return e.delete(t),Rd(r);let n={};for(let[a,i]of Object.entries(r))n[a]=lr(i,e);return e.delete(t),n}return Array.isArray(t)?t.map(r=>lr(r,e)):t}o(lr,"escapeIfNeeded");function Ri(t){return Array.isArray(t)?[...t]:{...t}}o(Ri,"shallowCopy");function Nd(t,e){let r=Ri(t);for(let[n,a]of Object.entries(e)){let[i,...s]=n.split(".").reverse(),l=r;for(let c of s.reverse()){if(l[c]===void 0)break;l[c]=Ri(l[c]),l=l[c]}l[i]!==void 0&&(l[i]={lc:1,type:"secret",id:[a]})}return r}o(Nd,"replaceSecrets");function Sn(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(Sn,"get_lc_unique_name");var st=class Mi{static{o(this,"Serializable")}lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Sn(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 Mi||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},r={},n=Object.keys(this.lc_kwargs).reduce((l,c)=>(l[c]=c in this?this[c]:this.lc_kwargs[c],l),{});for(let l=Object.getPrototypeOf(this);l;l=Object.getPrototypeOf(l))Object.assign(e,Reflect.get(l,"lc_aliases",this)),Object.assign(r,Reflect.get(l,"lc_secrets",this)),Object.assign(n,Reflect.get(l,"lc_attributes",this));Object.keys(r).forEach(l=>{let c=this,u=n,[p,...m]=l.split(".").reverse();for(let g of m.reverse()){if(!(g in c)||c[g]===void 0)return;(!(g in u)||u[g]===void 0)&&(typeof c[g]=="object"&&c[g]!=null?u[g]={}:Array.isArray(c[g])&&(u[g]=[])),c=c[g],u=u[g]}p in c&&c[p]!==void 0&&(u[p]=u[p]||c[p])});let a={},i=new WeakSet;i.add(this);for(let[l,c]of Object.entries(n))a[l]=lr(c,i);let s=Oi(Object.keys(r).length?Nd(a,r):a,Ci,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:s}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function kt(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(kt,"isDataContentBlock");function cr(t){return kt(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}o(cr,"isURLContentBlock");function ur(t){return kt(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}o(ur,"isBase64ContentBlock");function An(t){return kt(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}o(An,"isIDContentBlock");function dr({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 a=e?Uint8Array.from(atob(r[2]),i=>i.charCodeAt(0)):r[2];return{mime_type:n,data:a}}}o(dr,"parseBase64DataUrl");function T(t,e){return R(t)&&t.type===e}o(T,"_isContentBlock");function R(t){return typeof t=="object"&&t!==null}o(R,"_isObject");function re(t){return Array.isArray(t)}o(re,"_isArray");function b(t){return typeof t=="string"}o(b,"_isString");function ve(t){return typeof t=="number"}o(ve,"_isNumber");function pr(t){return t instanceof Uint8Array}o(pr,"_isBytesArray");function In(t){try{return JSON.parse(t)}catch{return}}o(In,"safeParseJson");var Ee=o(t=>t(),"iife");function Pd(t){if(t.type==="char_location"&&b(t.document_title)&&ve(t.start_char_index)&&ve(t.end_char_index)&&b(t.cited_text)){let{document_title:e,start_char_index:r,end_char_index:n,cited_text:a,...i}=t;return{...i,type:"citation",source:"char",title:e??void 0,startIndex:r,endIndex:n,citedText:a}}if(t.type==="page_location"&&b(t.document_title)&&ve(t.start_page_number)&&ve(t.end_page_number)&&b(t.cited_text)){let{document_title:e,start_page_number:r,end_page_number:n,cited_text:a,...i}=t;return{...i,type:"citation",source:"page",title:e??void 0,startIndex:r,endIndex:n,citedText:a}}if(t.type==="content_block_location"&&b(t.document_title)&&ve(t.start_block_index)&&ve(t.end_block_index)&&b(t.cited_text)){let{document_title:e,start_block_index:r,end_block_index:n,cited_text:a,...i}=t;return{...i,type:"citation",source:"block",title:e??void 0,startIndex:r,endIndex:n,citedText:a}}if(t.type==="web_search_result_location"&&b(t.url)&&b(t.title)&&b(t.encrypted_index)&&b(t.cited_text)){let{url:e,title:r,encrypted_index:n,cited_text:a,...i}=t;return{...i,type:"citation",source:"url",url:e,title:r,startIndex:Number(n),endIndex:Number(n),citedText:a}}if(t.type==="search_result_location"&&b(t.source)&&b(t.title)&&ve(t.start_block_index)&&ve(t.end_block_index)&&b(t.cited_text)){let{source:e,title:r,start_block_index:n,end_block_index:a,cited_text:i,...s}=t;return{...s,type:"citation",source:"search",url:e,title:r??void 0,startIndex:n,endIndex:a,citedText:i}}}o(Pd,"convertAnthropicAnnotation");function Ni(t){if(T(t,"document")&&R(t.source)&&"type"in t.source){if(t.source.type==="base64"&&b(t.source.media_type)&&b(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&b(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&b(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&b(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(T(t,"image")&&R(t.source)&&"type"in t.source){if(t.source.type==="base64"&&b(t.source.media_type)&&b(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&b(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&b(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}o(Ni,"convertToV1FromAnthropicContentBlock");function Pi(t){function*e(){for(let r of t){let n=Ni(r);n?yield n:yield r}}return o(e,"iterateContent"),Array.from(e())}o(Pi,"convertToV1FromAnthropicInput");function ki(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(T(n,"text")&&b(n.text)){let{text:a,citations:i,...s}=n;if(re(i)&&i.length){let l=i.reduce((c,u)=>{let p=Pd(u);return p?[...c,p]:c},[]);yield{...s,type:"text",text:a,annotations:l};continue}else{yield{...s,type:"text",text:a};continue}}else if(T(n,"thinking")&&b(n.thinking)){let{thinking:a,signature:i,...s}=n;yield{...s,type:"reasoning",reasoning:a,signature:i};continue}else if(T(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(T(n,"tool_use")&&b(n.name)&&b(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(T(n,"input_json_delta")){if($d(t)&&t.tool_call_chunks?.length){let a=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:a.id,name:a.name,args:a.args,index:a.index};continue}}else if(T(n,"server_tool_use")&&b(n.name)&&b(n.id)){let{name:a,id:i}=n;if(a==="web_search"){yield{id:i,type:"server_tool_call",name:"web_search",args:{query:Ee(()=>{if(typeof n.input=="string")return n.input;if(R(n.input)&&b(n.input.query))return n.input.query;if(b(n.partial_json)){let s=In(n.partial_json);if(s?.query)return s.query}return""})}};continue}else if(n.name==="code_execution"){yield{id:i,type:"server_tool_call",name:"code_execution",args:{code:Ee(()=>{if(typeof n.input=="string")return n.input;if(R(n.input)&&b(n.input.code))return n.input.code;if(b(n.partial_json)){let s=In(n.partial_json);if(s?.code)return s.code}return""})}};continue}}else if(T(n,"web_search_tool_result")&&b(n.tool_use_id)&&re(n.content)){let{content:a,tool_use_id:i}=n;yield{type:"server_tool_call_result",name:"web_search",toolCallId:i,status:"success",output:{urls:a.reduce((s,l)=>T(l,"web_search_result")?[...s,l.url]:s,[])}};continue}else if(T(n,"code_execution_tool_result")&&b(n.tool_use_id)&&R(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(T(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(T(n,"mcp_tool_result")&&b(n.tool_use_id)&&R(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(T(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(T(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(T(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}else{let a=Ni(n);if(a){yield a;continue}}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(ki,"convertToV1FromAnthropicMessage");var $i={translateContent:ki,translateContentChunk:ki};function $d(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}o($d,"_isAIMessageChunk");function Ld(t){return cr(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:ur(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:An(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}o(Ld,"convertToV1FromDataContentBlock");function Li(t){return t.map(Ld)}o(Li,"convertToV1FromDataContent");function Di(t){return!!(T(t,"image_url")&&R(t.image_url)||T(t,"input_audio")&&R(t.input_audio)||T(t,"file")&&R(t.file))}o(Di,"isOpenAIDataBlock");function Fi(t){if(T(t,"image_url")&&R(t.image_url)&&b(t.image_url.url)){let e=dr({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(T(t,"input_audio")&&R(t.input_audio)&&b(t.input_audio.data)&&b(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(T(t,"file")&&R(t.file)&&b(t.file.data)){let e=dr({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(b(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}o(Fi,"convertToV1FromOpenAIDataBlock");function Dd(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...fr(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(Dd,"convertToV1FromChatCompletions");function Fd(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...fr(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(Fd,"convertToV1FromChatCompletionsChunk");function fr(t){let e=[];for(let r of t)Di(r)?e.push(Fi(r)):e.push(r);return e}o(fr,"convertToV1FromChatCompletionsInput");function Ud(t){if(t.type==="url_citation"){let{url:e,title:r,start_index:n,end_index:a}=t;return{type:"citation",url:e,title:r,startIndex:n,endIndex:a}}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(Ud,"convertResponsesAnnotation");function Ui(t){function*e(){R(t.additional_kwargs?.reasoning)&&re(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((n,a)=>R(a)&&b(a.text)?`${n}${a.text}`:n,"")});let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r)if(T(n,"text")){let{text:a,annotations:i,phase:s,extras:l,...c}=n,u=R(l)?{...l}:{};b(s)&&(u.phase=s);let p=Object.keys(u).length>0?{extras:u}:{};Array.isArray(i)?yield{...c,...p,type:"text",text:String(a),annotations:i.map(Ud)}:yield{...c,...p,type:"text",text:String(a)}}for(let n of t.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if(R(t.additional_kwargs)&&re(t.additional_kwargs.tool_outputs))for(let n of t.additional_kwargs.tool_outputs){if(T(n,"web_search_call")){let a={};if(R(n.action)&&b(n.action.query)&&(a.query=n.action.query),yield{id:n.id,type:"server_tool_call",name:"web_search",args:a},n.status==="completed"||n.status==="failed"){let i={};R(n.action)&&(i.action=n.action),yield{type:"server_tool_call_result",toolCallId:b(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:i}}continue}else if(T(n,"file_search_call")){yield{id:n.id,type:"server_tool_call",name:"file_search",args:{queries:re(n.queries)?n.queries:[]}},(n.status==="completed"||n.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:b(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:re(n.results)?{results:n.results}:{}});continue}else if(T(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(T(n,"code_interpreter_call")){if(b(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),re(n.outputs)){let a=Ee(()=>{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(T(i,"logs")){yield{type:"server_tool_call_result",toolCallId:n.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:a??0,stderr:[0,void 0].includes(a)?void 0:String(i.logs),stdout:[0,void 0].includes(a)?String(i.logs):void 0}};continue}}continue}else if(T(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(T(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(T(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(T(n,"tool_search_call")){let a={};R(n.arguments)&&Object.assign(a,n.arguments);let i={};b(n.execution)&&(i.execution=n.execution),b(n.status)&&(i.status=n.status),b(n.call_id)&&(i.call_id=n.call_id),yield{id:b(n.id)?n.id:"",type:"server_tool_call",name:"tool_search",args:a,...Object.keys(i).length>0?{extras:i}:{}};continue}else if(T(n,"tool_search_output")){let a={name:"tool_search"};b(n.execution)&&(a.execution=n.execution),yield{type:"server_tool_call_result",toolCallId:b(n.id)?n.id:"",status:n.status==="completed"?"success":n.status==="failed"?"error":"success",output:{tools:re(n.tools)?n.tools:[]},extras:a};continue}else if(T(n,"image_generation_call")){b(n.result)&&(yield{type:"image",mimeType:"image/png",data:n.result,id:b(n.id)?n.id:void 0,metadata:{status:b(n.status)?n.status:void 0}}),yield{type:"non_standard",value:n};continue}R(n)&&(yield{type:"non_standard",value:n})}}return o(e,"iterateContent"),Array.from(e())}o(Ui,"convertToV1FromResponses");function jd(t){function*e(){yield*Ui(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(jd,"convertToV1FromResponsesChunk");var ji={translateContent:o(t=>typeof t.content=="string"?Dd(t):Ui(t),"translateContent"),translateContentChunk:o(t=>typeof t.content=="string"?Fd(t):jd(t),"translateContentChunk")};function Cn(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}o(Cn,"isMessage");function Bi(t,e="pretty"){return e==="pretty"?Bd(t):JSON.stringify(t)}o(Bi,"convertToFormattedString");function Bd(t){let e=[],r=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),a="=".repeat(n),i=r.length%2===0?a:`${a}=`;if(e.push(`${a}${r}${i}`),t.type==="ai"){let s=t;if(s.tool_calls&&s.tool_calls.length>0){e.push("Tool Calls:");for(let l of s.tool_calls){e.push(` ${l.name} (${l.id})`),e.push(` Call ID: ${l.id}`),e.push(" Args:");for(let[c,u]of Object.entries(l.args))e.push(` ${c}: ${typeof u=="object"?JSON.stringify(u):u}`)}}}if(t.type==="tool"){let s=t;s.name&&e.push(`Name: ${s.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
4
- `)}o(Bd,"convertToPrettyString");var On=Symbol.for("langchain.message");function Gd(t,e){function r(n,a){if(typeof n!="object"||n===null||n===void 0)return n;if(a>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(s=>r(s,a+1));let i={};for(let s of Object.keys(n))i[s]=r(n[s],a+1);return i}return o(r,"helper"),JSON.stringify(r(t,0),null,2)}o(Gd,"stringifyWithDepthLimit");var qe=class extends st{static{o(this,"BaseMessage")}lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[On]=!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[Li,fr,Pi].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&&On in t&&t[On]===!0&&Cn(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=Gd(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return Bi(this,t)}};function Rn(t){let e=[],r=[];for(let n of t)if(n.function){let a=n.function.name;try{let i=JSON.parse(n.function.arguments);e.push({name:a||"",args:i||{},id:n.id})}catch{r.push({name:a,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}o(Rn,"defaultToolCallParser");function Mn(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(Mn,"convertFileFormatToMimeType");function Vd(t){if(R(t.document)&&R(t.document.source)){let e=Mn(R(t.document)&&b(t.document.format)?t.document.format:"");if(R(t.document.source)){if(R(t.document.source.s3Location)&&b(t.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:t.document.source.s3Location.uri};if(pr(t.document.source.bytes))return{type:"file",mimeType:e,data:t.document.source.bytes};if(b(t.document.source.text))return{type:"file",mimeType:e,data:Buffer.from(t.document.source.text).toString("base64")};if(re(t.document.source.content))return{type:"file",mimeType:e,data:t.document.source.content.reduce((r,n)=>R(n)&&b(n.text)?r+n.text:r,"")}}}return{type:"non_standard",value:t}}o(Vd,"convertConverseDocumentBlock");function qd(t){if(T(t,"image")&&R(t.image)){let e=Mn(R(t.image)&&b(t.image.format)?t.image.format:"");if(R(t.image.source)){if(R(t.image.source.s3Location)&&b(t.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:t.image.source.s3Location.uri};if(pr(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}o(qd,"convertConverseImageBlock");function Wd(t){if(T(t,"video")&&R(t.video)){let e=Mn(R(t.video)&&b(t.video.format)?t.video.format:"");if(R(t.video.source)){if(R(t.video.source.s3Location)&&b(t.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:t.video.source.s3Location.uri};if(pr(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}o(Wd,"convertConverseVideoBlock");function Gi(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(T(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(T(n,"citations_content")&&R(n.citationsContent)){yield{type:"text",text:re(n.citationsContent.content)?n.citationsContent.content.reduce((a,i)=>R(i)&&b(i.text)?a+i.text:a,""):"",annotations:re(n.citationsContent.citations)?n.citationsContent.citations.reduce((a,i)=>{if(R(i)){let s=re(i.sourceContent)?i.sourceContent.reduce((c,u)=>R(u)&&b(u.text)?c+u.text:c,""):"",l=Ee(()=>{if(R(i.location)){let c=i.location.documentChar||i.location.documentPage||i.location.documentChunk;if(R(c))return{source:ve(c.documentIndex)?c.documentIndex.toString():void 0,startIndex:ve(c.start)?c.start:void 0,endIndex:ve(c.end)?c.end:void 0}}return{}});a.push({type:"citation",citedText:s,...l})}return a},[]):[]};continue}else if(T(n,"document")&&R(n.document)){yield Vd(n);continue}else if(T(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(T(n,"image")&&R(n.image)){yield qd(n);continue}else if(T(n,"reasoning_content")&&b(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(T(n,"text")&&b(n.text)){yield{type:"text",text:n.text};continue}else if(T(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(T(n,"tool_call"))continue;if(T(n,"video")&&R(n.video)){yield Wd(n);continue}}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(Gi,"convertToV1FromChatBedrockConverseMessage");var Hi={translateContent:Gi,translateContentChunk:Gi};function zi(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(b(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&&b(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(zi,"convertToV1FromDeepSeekMessage");var Vi={translateContent:zi,translateContentChunk:zi};function qi(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(T(n,"text")&&b(n.text)){yield{type:"text",text:n.text};continue}else if(T(n,"thinking")&&b(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(T(n,"inlineData")&&R(n.inlineData)&&b(n.inlineData.mimeType)&&b(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(T(n,"functionCall")&&R(n.functionCall)&&b(n.functionCall.name)&&R(n.functionCall.args)){yield{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(T(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(T(n,"fileData")&&R(n.fileData)&&b(n.fileData.mimeType)&&b(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(T(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(T(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(qi,"convertToV1FromChatGoogleMessage");var Wi={translateContent:qi,translateContentChunk:qi};function Ki(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(T(n,"reasoning")&&b(n.reasoning)){let a=Ee(()=>{let i=r.indexOf(n);if(re(t.additional_kwargs?.signatures)&&i>=0)return t.additional_kwargs.signatures.at(i)});b(a)?yield{type:"reasoning",reasoning:n.reasoning,signature:a}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(T(n,"thinking")&&b(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(T(n,"text")&&b(n.text)){yield{type:"text",text:n.text};continue}else if(T(n,"image_url")){if(b(n.image_url))if(n.image_url.startsWith("data:")){let a=n.image_url.match(/^data:([^;]+);base64,(.+)$/);a?yield{type:"image",data:a[2],mimeType:a[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(T(n,"media")&&b(n.mimeType)&&b(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(Ki,"convertToV1FromChatVertexMessage");var Ji={translateContent:Ki,translateContentChunk:Ki};function Zi(t){let e=[],r=t.additional_kwargs?.reasoning;if(b(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string"){let n=t.content,a=n.match(/<think>([\s\S]*?)<\/think>/);if(a){let i=a[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&&b(n.text)){let a=n.text,i=a.match(/<think>([\s\S]*?)<\/think>/);if(i){let s=i[1].trim();s.length>0&&e.push({type:"reasoning",reasoning:s}),a=a.replace(/<think>[\s\S]*?<\/think>/,"").trim()}a.length>0&&e.push({type:"text",text:a})}for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(Zi,"convertToV1FromGroqMessage");var Yi={translateContent:Zi,translateContentChunk:Zi};function Xi(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(b(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&&b(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(Xi,"convertToV1FromOllamaMessage");var Qi={translateContent:Xi,translateContentChunk:Xi};function es(t){let e=[],r=t.additional_kwargs?.reasoning_details,n=!1;if(Array.isArray(r)&&r.length>0)for(let a of r){if(a==null||typeof a!="object")continue;let i=a.type;if(i==="reasoning.summary"){let s=a.summary;b(s)&&s.length>0&&(e.push({type:"reasoning",reasoning:s}),n=!0)}else if(i==="reasoning.text"){let s=a.text;b(s)&&s.length>0&&(e.push({type:"reasoning",reasoning:s}),n=!0)}}if(!n){let a=t.additional_kwargs?.reasoning_content;b(a)&&a.length>0&&e.push({type:"reasoning",reasoning:a})}if(typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let a of t.content)typeof a=="object"&&"type"in a&&a.type==="text"&&"text"in a&&b(a.text)&&e.push({type:"text",text:a.text});for(let a of t.tool_calls??[])e.push({type:"tool_call",id:a.id,name:a.name,args:a.args});return e}o(es,"convertToV1FromOpenRouterMessage");var ts={translateContent:es,translateContentChunk:es};function rs(t){let e=[];if(R(t.additional_kwargs?.reasoning)){let n=t.additional_kwargs.reasoning;if(re(n.summary)){let a=n.summary.reduce((i,s)=>R(s)&&b(s.text)?`${i}${s.text}`:i,"");a.length>0&&e.push({type:"reasoning",reasoning:a})}}let r=t.additional_kwargs?.reasoning_content;if(b(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&&b(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(rs,"convertToV1FromXAIMessage");var ns={translateContent:rs,translateContentChunk:rs};function as(t){function*e(){let r=Ee(()=>{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(a=>"thoughtSignature"in a)){let a=[...t.content];for(let i=a.length-1;i>=0;i--){let s=a[i];if(s.type==="text"&&!s.thought)return s.thoughtSignature=n.thoughtSignature,a}}return t.content}});for(let n of r){let a=Ee(()=>T(n,"text")&&b(n.text)?{type:"text",text:n.text}:T(n,"inlineData")&&R(n.inlineData)&&b(n.inlineData.mimeType)&&b(n.inlineData.data)?{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data}:T(n,"functionCall")&&R(n.functionCall)&&b(n.functionCall.name)&&R(n.functionCall.args)?{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args}:T(n,"functionResponse")?{type:"non_standard",value:n}:T(n,"fileData")&&R(n.fileData)&&b(n.fileData.mimeType)&&b(n.fileData.fileUri)?{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri}:T(n,"executableCode")?{type:"non_standard",value:n}:T(n,"codeExecutionResult")?{type:"non_standard",value:n}:{type:"non_standard",value:n}),i=Ee(()=>"thought"in n&&n.thought?{type:"reasoning",reasoning:a.type==="text"?a.text:"",reasoningContentBlock:a}:a),s={thought:n.thought,thoughtSignature:n.thoughtSignature,partMetadata:n.partMetadata,...i};for(let l in s)s[l]===void 0&&delete s[l];yield s}}return o(e,"iterateContent"),Array.from(e())}o(as,"convertToV1FromChatGoogleMessage");var is={translateContent:as,translateContentChunk:as};globalThis.lc_block_translators_registry??=new Map([["anthropic",$i],["bedrock-converse",Hi],["deepseek",Vi],["google",is],["google-genai",Wi],["google-vertexai",Ji],["groq",Yi],["ollama",Qi],["openai",ji],["openrouter",ts],["xai",ns]]);function ss(t){return globalThis.lc_block_translators_registry.get(t)}o(ss,"getTranslator");function os(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(os,"mergeModalitiesTokenDetails");function Kd(t,e){let r={...os(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(Kd,"mergeInputTokenDetails");function Jd(t,e){let r={...os(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}o(Jd,"mergeOutputTokenDetails");function mr(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:Kd(t?.input_token_details,e?.input_token_details),output_token_details:Jd(t?.output_token_details,e?.output_token_details)}}o(mr,"mergeUsageMetadata");var Ye=class extends qe{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.
1
+ "use strict";var id=Object.create;var xr=Object.defineProperty;var ad=Object.getOwnPropertyDescriptor;var sd=Object.getOwnPropertyNames;var od=Object.getPrototypeOf,ld=Object.prototype.hasOwnProperty;var s=(t,e)=>xr(t,"name",{value:e,configurable:!0});var nt=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},cd=(t,e)=>{for(var r in e)xr(t,r,{get:e[r],enumerable:!0})},fs=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of sd(e))!ld.call(t,i)&&i!==r&&xr(t,i,{get:()=>e[i],enumerable:!(n=ad(e,i))||n.enumerable});return t};var it=(t,e,r)=>(r=t!=null?id(od(t)):{},fs(e||!t||!t.__esModule?xr(r,"default",{value:t,enumerable:!0}):r,t)),ud=t=>fs(xr({},"__esModule",{value:!0}),t);var uo=nt((Uw,_i)=>{"use strict";var Kd=Object.prototype.hasOwnProperty,_e="~";function Sr(){}s(Sr,"Events");Object.create&&(Sr.prototype=Object.create(null),new Sr().__proto__||(_e=!1));function Jd(t,e,r){this.fn=t,this.context=e,this.once=r||!1}s(Jd,"EE");function co(t,e,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var a=new Jd(r,n||t,i),o=_e?_e+e:e;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],a]:t._events[o].push(a):(t._events[o]=a,t._eventsCount++),t}s(co,"addListener");function an(t,e){--t._eventsCount===0?t._events=new Sr:delete t._events[e]}s(an,"clearEvent");function fe(){this._events=new Sr,this._eventsCount=0}s(fe,"EventEmitter");fe.prototype.eventNames=s(function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)Kd.call(r,n)&&e.push(_e?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e},"eventNames");fe.prototype.listeners=s(function(e){var r=_e?_e+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=new Array(a);i<a;i++)o[i]=n[i].fn;return o},"listeners");fe.prototype.listenerCount=s(function(e){var r=_e?_e+e:e,n=this._events[r];return n?n.fn?1:n.length:0},"listenerCount");fe.prototype.emit=s(function(e,r,n,i,a,o){var l=_e?_e+e:e;if(!this._events[l])return!1;var c=this._events[l],u=arguments.length,d,p;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,i),!0;case 5:return c.fn.call(c.context,r,n,i,a),!0;case 6:return c.fn.call(c.context,r,n,i,a,o),!0}for(p=1,d=new Array(u-1);p<u;p++)d[p-1]=arguments[p];c.fn.apply(c.context,d)}else{var h=c.length,g;for(p=0;p<h;p++)switch(c[p].once&&this.removeListener(e,c[p].fn,void 0,!0),u){case 1:c[p].fn.call(c[p].context);break;case 2:c[p].fn.call(c[p].context,r);break;case 3:c[p].fn.call(c[p].context,r,n);break;case 4:c[p].fn.call(c[p].context,r,n,i);break;default:if(!d)for(g=1,d=new Array(u-1);g<u;g++)d[g-1]=arguments[g];c[p].fn.apply(c[p].context,d)}}return!0},"emit");fe.prototype.on=s(function(e,r,n){return co(this,e,r,n,!1)},"on");fe.prototype.once=s(function(e,r,n){return co(this,e,r,n,!0)},"once");fe.prototype.removeListener=s(function(e,r,n,i){var a=_e?_e+e:e;if(!this._events[a])return this;if(!r)return an(this,a),this;var o=this._events[a];if(o.fn)o.fn===r&&(!i||o.once)&&(!n||o.context===n)&&an(this,a);else{for(var l=0,c=[],u=o.length;l<u;l++)(o[l].fn!==r||i&&!o[l].once||n&&o[l].context!==n)&&c.push(o[l]);c.length?this._events[a]=c.length===1?c[0]:c:an(this,a)}return this},"removeListener");fe.prototype.removeAllListeners=s(function(e){var r;return e?(r=_e?_e+e:e,this._events[r]&&an(this,r)):(this._events=new Sr,this._eventsCount=0),this},"removeAllListeners");fe.prototype.off=fe.prototype.removeListener;fe.prototype.addListener=fe.prototype.on;fe.prefixed=_e;fe.EventEmitter=fe;typeof _i<"u"&&(_i.exports=fe)});var fo=nt((jw,po)=>{"use strict";po.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 ho=nt((Bw,on)=>{"use strict";var Zd=fo(),sn=class extends Error{static{s(this,"TimeoutError")}constructor(e){super(e),this.name="TimeoutError"}},mo=s((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 a=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(c){i(c)}return}let o=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,l=r instanceof Error?r:new sn(o);typeof t.cancel=="function"&&t.cancel(),i(l)},e);Zd(t.then(n,i),()=>{clearTimeout(a)})}),"pTimeout");on.exports=mo;on.exports.default=mo;on.exports.TimeoutError=sn});var go=nt(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});function Yd(t,e,r){let n=0,i=t.length;for(;i>0;){let a=i/2|0,o=n+a;r(t[o],e)<=0?(n=++o,i-=a+1):i=a}return n}s(Yd,"lowerBound");bi.default=Yd});var yo=nt(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});var Xd=go(),wi=class{static{s(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=Xd.default(this._queue,n,(a,o)=>o.priority-a.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}};vi.default=wi});var cn=nt(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});var Qd=uo(),_o=ho(),ep=yo(),ln=s(()=>{},"empty"),tp=new _o.TimeoutError,xi=class extends Qd{static{s(this,"PQueue")}constructor(e){var r,n,i,a;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=ln,this._resolveIdle=ln,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:ep.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 \`${(a=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&a!==void 0?a:""}\` (${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=ln,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=ln,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 a=s(async()=>{this._pendingCount++,this._intervalCount++;try{let o=this._timeout===void 0&&r.timeout===void 0?e():_o.default(Promise.resolve(e()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&i(tp)});n(await o)}catch(o){i(o)}this._next()},"run");this._queue.enqueue(a,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}};Ei.default=xi});var Su=nt(ti=>{"use strict";ti.byteLength=Wh;ti.toByteArray=Jh;ti.fromByteArray=Xh;var qe=[],Oe=[],qh=typeof Uint8Array<"u"?Uint8Array:Array,Ya="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Vt=0,xu=Ya.length;Vt<xu;++Vt)qe[Vt]=Ya[Vt],Oe[Ya.charCodeAt(Vt)]=Vt;var Vt,xu;Oe[45]=62;Oe[95]=63;function Eu(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]}s(Eu,"getLens");function Wh(t){var e=Eu(t),r=e[0],n=e[1];return(r+n)*3/4-n}s(Wh,"byteLength");function Kh(t,e,r){return(e+r)*3/4-r}s(Kh,"_byteLength");function Jh(t){var e,r=Eu(t),n=r[0],i=r[1],a=new qh(Kh(t,n,i)),o=0,l=i>0?n-4:n,c;for(c=0;c<l;c+=4)e=Oe[t.charCodeAt(c)]<<18|Oe[t.charCodeAt(c+1)]<<12|Oe[t.charCodeAt(c+2)]<<6|Oe[t.charCodeAt(c+3)],a[o++]=e>>16&255,a[o++]=e>>8&255,a[o++]=e&255;return i===2&&(e=Oe[t.charCodeAt(c)]<<2|Oe[t.charCodeAt(c+1)]>>4,a[o++]=e&255),i===1&&(e=Oe[t.charCodeAt(c)]<<10|Oe[t.charCodeAt(c+1)]<<4|Oe[t.charCodeAt(c+2)]>>2,a[o++]=e>>8&255,a[o++]=e&255),a}s(Jh,"toByteArray");function Zh(t){return qe[t>>18&63]+qe[t>>12&63]+qe[t>>6&63]+qe[t&63]}s(Zh,"tripletToBase64");function Yh(t,e,r){for(var n,i=[],a=e;a<r;a+=3)n=(t[a]<<16&16711680)+(t[a+1]<<8&65280)+(t[a+2]&255),i.push(Zh(n));return i.join("")}s(Yh,"encodeChunk");function Xh(t){for(var e,r=t.length,n=r%3,i=[],a=16383,o=0,l=r-n;o<l;o+=a)i.push(Yh(t,o,o+a>l?l:o+a));return n===1?(e=t[r-1],i.push(qe[e>>2]+qe[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(qe[e>>10]+qe[e>>4&63]+qe[e<<2&63]+"=")),i.join("")}s(Xh,"fromByteArray")});var Bu=nt(($j,et)=>{var is=require("fs"),ni=require("path"),xg=require("os"),Eg=require("crypto"),$u=["\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 Sg(){return $u[Math.floor(Math.random()*$u.length)]}s(Sg,"_getRandomTip");function wr(t){return typeof t=="string"?!["false","0","no","off",""].includes(t.toLowerCase()):!!t}s(wr,"parseBoolean");function Tg(){return process.stdout.isTTY}s(Tg,"supportsAnsi");function Ag(t){return Tg()?`\x1B[2m${t}\x1B[0m`:t}s(Ag,"dim");var Ig=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Cg(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
2
+ `);let n;for(;(n=Ig.exec(r))!=null;){let i=n[1],a=n[2]||"";a=a.trim();let o=a[0];a=a.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),o==='"'&&(a=a.replace(/\\n/g,`
3
+ `),a=a.replace(/\\r/g,"\r")),e[i]=a}return e}s(Cg,"parse");function kg(t){t=t||{};let e=ju(t);t.path=e;let r=ne.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=Fu(t).split(","),i=n.length,a;for(let o=0;o<i;o++)try{let l=n[o].trim(),c=Pg(r,l);a=ne.decrypt(c.ciphertext,c.key);break}catch(l){if(o+1>=i)throw l}return ne.parse(a)}s(kg,"_parseVault");function Og(t){console.error(`\u26A0 ${t}`)}s(Og,"_warn");function Vr(t){console.log(`\u2506 ${t}`)}s(Vr,"_debug");function Uu(t){console.log(`\u25C7 ${t}`)}s(Uu,"_log");function Fu(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:""}s(Fu,"_dotenvKey");function Pg(t,e){let r;try{r=new URL(e)}catch(l){if(l.code==="ERR_INVALID_URL"){let c=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 c.code="INVALID_DOTENV_KEY",c}throw l}let n=r.password;if(!n){let l=new Error("INVALID_DOTENV_KEY: Missing key part");throw l.code="INVALID_DOTENV_KEY",l}let i=r.searchParams.get("environment");if(!i){let l=new Error("INVALID_DOTENV_KEY: Missing environment part");throw l.code="INVALID_DOTENV_KEY",l}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=t.parsed[a];if(!o){let l=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw l.code="NOT_FOUND_DOTENV_ENVIRONMENT",l}return{ciphertext:o,key:n}}s(Pg,"_instructions");function ju(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)is.existsSync(r)&&(e=r.endsWith(".vault")?r:`${r}.vault`);else e=t.path.endsWith(".vault")?t.path:`${t.path}.vault`;else e=ni.resolve(process.cwd(),".env.vault");return is.existsSync(e)?e:null}s(ju,"_vaultPath");function Du(t){return t[0]==="~"?ni.join(xg.homedir(),t.slice(1)):t}s(Du,"_resolveHome");function Rg(t){let e=wr(process.env.DOTENV_CONFIG_DEBUG||t&&t.debug),r=wr(process.env.DOTENV_CONFIG_QUIET||t&&t.quiet);(e||!r)&&Uu("loading env from encrypted .env.vault");let n=ne._parseVault(t),i=process.env;return t&&t.processEnv!=null&&(i=t.processEnv),ne.populate(i,n,t),{parsed:n}}s(Rg,"_configVault");function Mg(t){let e=ni.resolve(process.cwd(),".env"),r="utf8",n=process.env;t&&t.processEnv!=null&&(n=t.processEnv);let i=wr(n.DOTENV_CONFIG_DEBUG||t&&t.debug),a=wr(n.DOTENV_CONFIG_QUIET||t&&t.quiet);t&&t.encoding?r=t.encoding:i&&Vr("no encoding is specified (UTF-8 is used by default)");let o=[e];if(t&&t.path)if(!Array.isArray(t.path))o=[Du(t.path)];else{o=[];for(let d of t.path)o.push(Du(d))}let l,c={};for(let d of o)try{let p=ne.parse(is.readFileSync(d,{encoding:r}));ne.populate(c,p,t)}catch(p){i&&Vr(`failed to load ${d} ${p.message}`),l=p}let u=ne.populate(n,c,t);if(i=wr(n.DOTENV_CONFIG_DEBUG||i),a=wr(n.DOTENV_CONFIG_QUIET||a),i||!a){let d=Object.keys(u).length,p=[];for(let h of o)try{let g=ni.relative(process.cwd(),h);p.push(g)}catch(g){i&&Vr(`failed to load ${h} ${g.message}`),l=g}Uu(`injected env (${d}) from ${p.join(",")} ${Ag(`// tip: ${Sg()}`)}`)}return l?{parsed:c,error:l}:{parsed:c}}s(Mg,"configDotenv");function Ng(t){if(Fu(t).length===0)return ne.configDotenv(t);let e=ju(t);return e?ne._configVault(t):(Og(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),ne.configDotenv(t))}s(Ng,"config");function Lg(t,e){let r=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(t,"base64"),i=n.subarray(0,12),a=n.subarray(-16);n=n.subarray(12,-16);try{let o=Eg.createDecipheriv("aes-256-gcm",r,i);return o.setAuthTag(a),`${o.update(n)}${o.final()}`}catch(o){let l=o instanceof RangeError,c=o.message==="Invalid key length",u=o.message==="Unsupported state or unable to authenticate data";if(l||c){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}}s(Lg,"decrypt");function $g(t,e,r={}){let n=!!(r&&r.debug),i=!!(r&&r.override),a={};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],a[o]=e[o]),n&&Vr(i===!0?`"${o}" is already defined and WAS overwritten`:`"${o}" is already defined and was NOT overwritten`)):(t[o]=e[o],a[o]=e[o]);return a}s($g,"populate");var ne={configDotenv:Mg,_configVault:Rg,_parseVault:kg,config:Ng,decrypt:Lg,parse:Cg,populate:$g};et.exports.configDotenv=ne.configDotenv;et.exports._configVault=ne._configVault;et.exports._parseVault=ne._parseVault;et.exports.config=ne.config;et.exports.decrypt=ne.decrypt;et.exports.parse=ne.parse;et.exports.populate=ne.populate;et.exports=ne});var ly={};cd(ly,{default:()=>ai});module.exports=ud(ly);var ed=require("path");var Yj=require("@playwright/test");var gj=require("@playwright/test");var jy=require("@playwright/test");var $y=require("@playwright/test");var ms=Object.defineProperty,H=s((t,e)=>{let r={};for(var n in t)ms(r,n,{get:t[n],enumerable:!0});return e||ms(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll");function hs(t){let e=Symbol.for(t);return{brand(r,n){let i=n?Symbol.for(`${t}.${n}`):e;class a extends r{static{s(this,"_Branded")}[i]=!0;constructor(...l){super(...l)}static isInstance(l){return typeof l=="object"&&l!==null&&i in l&&l[i]===!0}}return Object.defineProperty(a,"name",{value:r.name}),a},sub(r){return hs(`${t}.${r}`)},isInstance(r){return typeof r=="object"&&r!==null&&e in r&&r[e]===!0}}}s(hs,"createNamespace");var gs=hs("langchain");var ui=gs.sub("error"),ys=class extends ui.brand(Error){static{s(this,"LangChainError")}name="LangChainError";constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},dd=class extends ui.brand(ys,"model-abort"){static{s(this,"ModelAbortError")}name="ModelAbortError";partialOutput;constructor(t,e){super(t),this.partialOutput=e}},Zy=class _s extends ui.brand(ys,"context-overflow"){static{s(this,"ContextOverflowError")}name="ContextOverflowError";cause;constructor(e){super(e??"Input exceeded the model's context window.")}static fromError(e){let r=new _s(e.message);return r.cause=e,r}};var pd=/([A-Z]+)([A-Z][a-z0-9]+)/g,fd=/([a-z0-9])([A-Z])/g,md=/[-_\s]+/g;function hd(t){return t.replace(pd,"$1_$2").replace(fd,"$1_$2").replace(md,"_").toLowerCase()}s(hd,"snakeCase");function bs(t,e){return e?.[t]||hd(t)}s(bs,"keyToJson");function ws(t,e,r){let n={};for(let i in t)Object.hasOwn(t,i)&&(n[e(i,r)]=t[i]);return n}s(ws,"mapKeys");var gd="__lc_escaped__";function yd(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}s(yd,"needsEscaping");function _d(t){return{[gd]:t}}s(_d,"escapeObject");function bd(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}s(bd,"isSerializableLike");function wd(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}}s(wd,"createNotImplemented");function Wr(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return wd(t);if(bd(t))return t;e.add(t);let r=t;if(yd(r))return e.delete(t),_d(r);let n={};for(let[i,a]of Object.entries(r))n[i]=Wr(a,e);return e.delete(t),n}return Array.isArray(t)?t.map(r=>Wr(r,e)):t}s(Wr,"escapeIfNeeded");function vs(t){return Array.isArray(t)?[...t]:{...t}}s(vs,"shallowCopy");function vd(t,e){let r=vs(t);for(let[n,i]of Object.entries(e)){let[a,...o]=n.split(".").reverse(),l=r;for(let c of o.reverse()){if(l[c]===void 0)break;l[c]=vs(l[c]),l=l[c]}l[a]!==void 0&&(l[a]={lc:1,type:"secret",id:[i]})}return r}s(vd,"replaceSecrets");function di(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}s(di,"get_lc_unique_name");var wt=class xs{static{s(this,"Serializable")}lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,di(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 xs||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},r={},n=Object.keys(this.lc_kwargs).reduce((l,c)=>(l[c]=c in this?this[c]:this.lc_kwargs[c],l),{});for(let l=Object.getPrototypeOf(this);l;l=Object.getPrototypeOf(l))Object.assign(e,Reflect.get(l,"lc_aliases",this)),Object.assign(r,Reflect.get(l,"lc_secrets",this)),Object.assign(n,Reflect.get(l,"lc_attributes",this));Object.keys(r).forEach(l=>{let c=this,u=n,[d,...p]=l.split(".").reverse();for(let h of p.reverse()){if(!(h in c)||c[h]===void 0)return;(!(h in u)||u[h]===void 0)&&(typeof c[h]=="object"&&c[h]!=null?u[h]={}:Array.isArray(c[h])&&(u[h]=[])),c=c[h],u=u[h]}d in c&&c[d]!==void 0&&(u[d]=u[d]||c[d])});let i={},a=new WeakSet;a.add(this);for(let[l,c]of Object.entries(n))i[l]=Wr(c,a);let o=ws(Object.keys(r).length?vd(i,r):i,bs,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:o}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function Er(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")}s(Er,"isDataContentBlock");function Kr(t){return Er(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}s(Kr,"isURLContentBlock");function Jr(t){return Er(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}s(Jr,"isBase64ContentBlock");function pi(t){return Er(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}s(pi,"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 i=e?Uint8Array.from(atob(r[2]),a=>a.charCodeAt(0)):r[2];return{mime_type:n,data:i}}}s(Zr,"parseBase64DataUrl");function T(t,e){return M(t)&&t.type===e}s(T,"_isContentBlock");function M(t){return typeof t=="object"&&t!==null}s(M,"_isObject");function te(t){return Array.isArray(t)}s(te,"_isArray");function w(t){return typeof t=="string"}s(w,"_isString");function Ae(t){return typeof t=="number"}s(Ae,"_isNumber");function Yr(t){return t instanceof Uint8Array}s(Yr,"_isBytesArray");function fi(t){try{return JSON.parse(t)}catch{return}}s(fi,"safeParseJson");var Ie=s(t=>t(),"iife");function xd(t){if(t.type==="char_location"&&w(t.document_title)&&Ae(t.start_char_index)&&Ae(t.end_char_index)&&w(t.cited_text)){let{document_title:e,start_char_index:r,end_char_index:n,cited_text:i,...a}=t;return{...a,type:"citation",source:"char",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="page_location"&&w(t.document_title)&&Ae(t.start_page_number)&&Ae(t.end_page_number)&&w(t.cited_text)){let{document_title:e,start_page_number:r,end_page_number:n,cited_text:i,...a}=t;return{...a,type:"citation",source:"page",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="content_block_location"&&w(t.document_title)&&Ae(t.start_block_index)&&Ae(t.end_block_index)&&w(t.cited_text)){let{document_title:e,start_block_index:r,end_block_index:n,cited_text:i,...a}=t;return{...a,type:"citation",source:"block",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="web_search_result_location"&&w(t.url)&&w(t.title)&&w(t.encrypted_index)&&w(t.cited_text)){let{url:e,title:r,encrypted_index:n,cited_text:i,...a}=t;return{...a,type:"citation",source:"url",url:e,title:r,startIndex:Number(n),endIndex:Number(n),citedText:i}}if(t.type==="search_result_location"&&w(t.source)&&w(t.title)&&Ae(t.start_block_index)&&Ae(t.end_block_index)&&w(t.cited_text)){let{source:e,title:r,start_block_index:n,end_block_index:i,cited_text:a,...o}=t;return{...o,type:"citation",source:"search",url:e,title:r??void 0,startIndex:n,endIndex:i,citedText:a}}}s(xd,"convertAnthropicAnnotation");function Ss(t){if(T(t,"document")&&M(t.source)&&"type"in t.source){if(t.source.type==="base64"&&w(t.source.media_type)&&w(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&w(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&w(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&w(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(T(t,"image")&&M(t.source)&&"type"in t.source){if(t.source.type==="base64"&&w(t.source.media_type)&&w(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&w(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&w(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}s(Ss,"convertToV1FromAnthropicContentBlock");function Ts(t){function*e(){for(let r of t){let n=Ss(r);n?yield n:yield r}}return s(e,"iterateContent"),Array.from(e())}s(Ts,"convertToV1FromAnthropicInput");function Es(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(T(n,"text")&&w(n.text)){let{text:i,citations:a,...o}=n;if(te(a)&&a.length){let l=a.reduce((c,u)=>{let d=xd(u);return d?[...c,d]:c},[]);yield{...o,type:"text",text:i,annotations:l};continue}else{yield{...o,type:"text",text:i};continue}}else if(T(n,"thinking")&&w(n.thinking)){let{thinking:i,signature:a,...o}=n;yield{...o,type:"reasoning",reasoning:i,signature:a};continue}else if(T(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(T(n,"tool_use")&&w(n.name)&&w(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(T(n,"input_json_delta")){if(Ed(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(T(n,"server_tool_use")&&w(n.name)&&w(n.id)){let{name:i,id:a}=n;if(i==="web_search"){yield{id:a,type:"server_tool_call",name:"web_search",args:{query:Ie(()=>{if(typeof n.input=="string")return n.input;if(M(n.input)&&w(n.input.query))return n.input.query;if(w(n.partial_json)){let o=fi(n.partial_json);if(o?.query)return o.query}return""})}};continue}else if(n.name==="code_execution"){yield{id:a,type:"server_tool_call",name:"code_execution",args:{code:Ie(()=>{if(typeof n.input=="string")return n.input;if(M(n.input)&&w(n.input.code))return n.input.code;if(w(n.partial_json)){let o=fi(n.partial_json);if(o?.code)return o.code}return""})}};continue}}else if(T(n,"web_search_tool_result")&&w(n.tool_use_id)&&te(n.content)){let{content:i,tool_use_id:a}=n;yield{type:"server_tool_call_result",name:"web_search",toolCallId:a,status:"success",output:{urls:i.reduce((o,l)=>T(l,"web_search_result")?[...o,l.url]:o,[])}};continue}else if(T(n,"code_execution_tool_result")&&w(n.tool_use_id)&&M(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(T(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(T(n,"mcp_tool_result")&&w(n.tool_use_id)&&M(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(T(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(T(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(T(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}else{let i=Ss(n);if(i){yield i;continue}}yield{type:"non_standard",value:n}}}return s(e,"iterateContent"),Array.from(e())}s(Es,"convertToV1FromAnthropicMessage");var As={translateContent:Es,translateContentChunk:Es};function Ed(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}s(Ed,"_isAIMessageChunk");function Sd(t){return Kr(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:Jr(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:pi(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}s(Sd,"convertToV1FromDataContentBlock");function Is(t){return t.map(Sd)}s(Is,"convertToV1FromDataContent");function Cs(t){return!!(T(t,"image_url")&&M(t.image_url)||T(t,"input_audio")&&M(t.input_audio)||T(t,"file")&&M(t.file))}s(Cs,"isOpenAIDataBlock");function ks(t){if(T(t,"image_url")&&M(t.image_url)&&w(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(T(t,"input_audio")&&M(t.input_audio)&&w(t.input_audio.data)&&w(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(T(t,"file")&&M(t.file)&&w(t.file.data)){let e=Zr({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(w(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}s(ks,"convertToV1FromOpenAIDataBlock");function Td(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Xr(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}s(Td,"convertToV1FromChatCompletions");function Ad(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Xr(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}s(Ad,"convertToV1FromChatCompletionsChunk");function Xr(t){let e=[];for(let r of t)Cs(r)?e.push(ks(r)):e.push(r);return e}s(Xr,"convertToV1FromChatCompletionsInput");function Id(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}s(Id,"convertResponsesAnnotation");function Os(t){function*e(){M(t.additional_kwargs?.reasoning)&&te(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((n,i)=>M(i)&&w(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(T(n,"text")){let{text:i,annotations:a,phase:o,extras:l,...c}=n,u=M(l)?{...l}:{};w(o)&&(u.phase=o);let d=Object.keys(u).length>0?{extras:u}:{};Array.isArray(a)?yield{...c,...d,type:"text",text:String(i),annotations:a.map(Id)}:yield{...c,...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(M(t.additional_kwargs)&&te(t.additional_kwargs.tool_outputs))for(let n of t.additional_kwargs.tool_outputs){if(T(n,"web_search_call")){let i={};if(M(n.action)&&w(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 a={};M(n.action)&&(a.action=n.action),yield{type:"server_tool_call_result",toolCallId:w(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:a}}continue}else if(T(n,"file_search_call")){yield{id:n.id,type:"server_tool_call",name:"file_search",args:{queries:te(n.queries)?n.queries:[]}},(n.status==="completed"||n.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:w(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:te(n.results)?{results:n.results}:{}});continue}else if(T(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(T(n,"code_interpreter_call")){if(w(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),te(n.outputs)){let i=Ie(()=>{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 a of n.outputs)if(T(a,"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(a.logs),stdout:[0,void 0].includes(i)?String(a.logs):void 0}};continue}}continue}else if(T(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(T(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(T(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(T(n,"tool_search_call")){let i={};M(n.arguments)&&Object.assign(i,n.arguments);let a={};w(n.execution)&&(a.execution=n.execution),w(n.status)&&(a.status=n.status),w(n.call_id)&&(a.call_id=n.call_id),yield{id:w(n.id)?n.id:"",type:"server_tool_call",name:"tool_search",args:i,...Object.keys(a).length>0?{extras:a}:{}};continue}else if(T(n,"tool_search_output")){let i={name:"tool_search"};w(n.execution)&&(i.execution=n.execution),yield{type:"server_tool_call_result",toolCallId:w(n.id)?n.id:"",status:n.status==="completed"?"success":n.status==="failed"?"error":"success",output:{tools:te(n.tools)?n.tools:[]},extras:i};continue}else if(T(n,"image_generation_call")){w(n.result)&&(yield{type:"image",mimeType:"image/png",data:n.result,id:w(n.id)?n.id:void 0,metadata:{status:w(n.status)?n.status:void 0}}),yield{type:"non_standard",value:n};continue}M(n)&&(yield{type:"non_standard",value:n})}}return s(e,"iterateContent"),Array.from(e())}s(Os,"convertToV1FromResponses");function Cd(t){function*e(){yield*Os(t);for(let r of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return s(e,"iterateContent"),Array.from(e())}s(Cd,"convertToV1FromResponsesChunk");var Ps={translateContent:s(t=>typeof t.content=="string"?Td(t):Os(t),"translateContent"),translateContentChunk:s(t=>typeof t.content=="string"?Ad(t):Cd(t),"translateContentChunk")};function mi(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}s(mi,"isMessage");function Rs(t,e="pretty"){return e==="pretty"?kd(t):JSON.stringify(t)}s(Rs,"convertToFormattedString");function kd(t){let e=[],r=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),i="=".repeat(n),a=r.length%2===0?i:`${i}=`;if(e.push(`${i}${r}${a}`),t.type==="ai"){let o=t;if(o.tool_calls&&o.tool_calls.length>0){e.push("Tool Calls:");for(let l of o.tool_calls){e.push(` ${l.name} (${l.id})`),e.push(` Call ID: ${l.id}`),e.push(" Args:");for(let[c,u]of Object.entries(l.args))e.push(` ${c}: ${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
+ `)}s(kd,"convertToPrettyString");var hi=Symbol.for("langchain.message");function Od(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 a={};for(let o of Object.keys(n))a[o]=r(n[o],i+1);return a}return s(r,"helper"),JSON.stringify(r(t,0),null,2)}s(Od,"stringifyWithDepthLimit");var We=class extends wt{static{s(this,"BaseMessage")}lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[hi]=!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[Is,Xr,Ts].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&&hi in t&&t[hi]===!0&&mi(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=Od(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return Rs(this,t)}};function gi(t){let e=[],r=[];for(let n of t)if(n.function){let i=n.function.name;try{let a=JSON.parse(n.function.arguments);e.push({name:i||"",args:a||{},id:n.id})}catch{r.push({name:i,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}s(gi,"defaultToolCallParser");function yi(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"}}s(yi,"convertFileFormatToMimeType");function Md(t){if(M(t.document)&&M(t.document.source)){let e=yi(M(t.document)&&w(t.document.format)?t.document.format:"");if(M(t.document.source)){if(M(t.document.source.s3Location)&&w(t.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:t.document.source.s3Location.uri};if(Yr(t.document.source.bytes))return{type:"file",mimeType:e,data:t.document.source.bytes};if(w(t.document.source.text))return{type:"file",mimeType:e,data:Buffer.from(t.document.source.text).toString("base64")};if(te(t.document.source.content))return{type:"file",mimeType:e,data:t.document.source.content.reduce((r,n)=>M(n)&&w(n.text)?r+n.text:r,"")}}}return{type:"non_standard",value:t}}s(Md,"convertConverseDocumentBlock");function Nd(t){if(T(t,"image")&&M(t.image)){let e=yi(M(t.image)&&w(t.image.format)?t.image.format:"");if(M(t.image.source)){if(M(t.image.source.s3Location)&&w(t.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:t.image.source.s3Location.uri};if(Yr(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}s(Nd,"convertConverseImageBlock");function Ld(t){if(T(t,"video")&&M(t.video)){let e=yi(M(t.video)&&w(t.video.format)?t.video.format:"");if(M(t.video.source)){if(M(t.video.source.s3Location)&&w(t.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:t.video.source.s3Location.uri};if(Yr(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}s(Ld,"convertConverseVideoBlock");function Ms(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(T(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(T(n,"citations_content")&&M(n.citationsContent)){yield{type:"text",text:te(n.citationsContent.content)?n.citationsContent.content.reduce((i,a)=>M(a)&&w(a.text)?i+a.text:i,""):"",annotations:te(n.citationsContent.citations)?n.citationsContent.citations.reduce((i,a)=>{if(M(a)){let o=te(a.sourceContent)?a.sourceContent.reduce((c,u)=>M(u)&&w(u.text)?c+u.text:c,""):"",l=Ie(()=>{if(M(a.location)){let c=a.location.documentChar||a.location.documentPage||a.location.documentChunk;if(M(c))return{source:Ae(c.documentIndex)?c.documentIndex.toString():void 0,startIndex:Ae(c.start)?c.start:void 0,endIndex:Ae(c.end)?c.end:void 0}}return{}});i.push({type:"citation",citedText:o,...l})}return i},[]):[]};continue}else if(T(n,"document")&&M(n.document)){yield Md(n);continue}else if(T(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(T(n,"image")&&M(n.image)){yield Nd(n);continue}else if(T(n,"reasoning_content")&&w(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(T(n,"text")&&w(n.text)){yield{type:"text",text:n.text};continue}else if(T(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(T(n,"tool_call"))continue;if(T(n,"video")&&M(n.video)){yield Ld(n);continue}}yield{type:"non_standard",value:n}}}return s(e,"iterateContent"),Array.from(e())}s(Ms,"convertToV1FromChatBedrockConverseMessage");var Ns={translateContent:Ms,translateContentChunk:Ms};function Ls(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(w(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&&w(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}s(Ls,"convertToV1FromDeepSeekMessage");var $s={translateContent:Ls,translateContentChunk:Ls};function Ds(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(T(n,"text")&&w(n.text)){yield{type:"text",text:n.text};continue}else if(T(n,"thinking")&&w(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(T(n,"inlineData")&&M(n.inlineData)&&w(n.inlineData.mimeType)&&w(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(T(n,"functionCall")&&M(n.functionCall)&&w(n.functionCall.name)&&M(n.functionCall.args)){yield{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(T(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(T(n,"fileData")&&M(n.fileData)&&w(n.fileData.mimeType)&&w(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(T(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(T(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return s(e,"iterateContent"),Array.from(e())}s(Ds,"convertToV1FromChatGoogleMessage");var Us={translateContent:Ds,translateContentChunk:Ds};function Fs(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(T(n,"reasoning")&&w(n.reasoning)){let i=Ie(()=>{let a=r.indexOf(n);if(te(t.additional_kwargs?.signatures)&&a>=0)return t.additional_kwargs.signatures.at(a)});w(i)?yield{type:"reasoning",reasoning:n.reasoning,signature:i}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(T(n,"thinking")&&w(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(T(n,"text")&&w(n.text)){yield{type:"text",text:n.text};continue}else if(T(n,"image_url")){if(w(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(T(n,"media")&&w(n.mimeType)&&w(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return s(e,"iterateContent"),Array.from(e())}s(Fs,"convertToV1FromChatVertexMessage");var js={translateContent:Fs,translateContentChunk:Fs};function Bs(t){let e=[],r=t.additional_kwargs?.reasoning;if(w(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 a=i[1].trim();a.length>0&&e.push({type:"reasoning",reasoning:a}),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&&w(n.text)){let i=n.text,a=i.match(/<think>([\s\S]*?)<\/think>/);if(a){let o=a[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}s(Bs,"convertToV1FromGroqMessage");var Hs={translateContent:Bs,translateContentChunk:Bs};function zs(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(w(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&&w(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}s(zs,"convertToV1FromOllamaMessage");var Gs={translateContent:zs,translateContentChunk:zs};function Vs(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 a=i.type;if(a==="reasoning.summary"){let o=i.summary;w(o)&&o.length>0&&(e.push({type:"reasoning",reasoning:o}),n=!0)}else if(a==="reasoning.text"){let o=i.text;w(o)&&o.length>0&&(e.push({type:"reasoning",reasoning:o}),n=!0)}}if(!n){let i=t.additional_kwargs?.reasoning_content;w(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&&w(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}s(Vs,"convertToV1FromOpenRouterMessage");var qs={translateContent:Vs,translateContentChunk:Vs};function Ws(t){let e=[];if(M(t.additional_kwargs?.reasoning)){let n=t.additional_kwargs.reasoning;if(te(n.summary)){let i=n.summary.reduce((a,o)=>M(o)&&w(o.text)?`${a}${o.text}`:a,"");i.length>0&&e.push({type:"reasoning",reasoning:i})}}let r=t.additional_kwargs?.reasoning_content;if(w(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&&w(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}s(Ws,"convertToV1FromXAIMessage");var Ks={translateContent:Ws,translateContentChunk:Ws};function Js(t){function*e(){let r=Ie(()=>{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 a=i.length-1;a>=0;a--){let o=i[a];if(o.type==="text"&&!o.thought)return o.thoughtSignature=n.thoughtSignature,i}}return t.content}});for(let n of r){let i=Ie(()=>T(n,"text")&&w(n.text)?{type:"text",text:n.text}:T(n,"inlineData")&&M(n.inlineData)&&w(n.inlineData.mimeType)&&w(n.inlineData.data)?{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data}:T(n,"functionCall")&&M(n.functionCall)&&w(n.functionCall.name)&&M(n.functionCall.args)?{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args}:T(n,"functionResponse")?{type:"non_standard",value:n}:T(n,"fileData")&&M(n.fileData)&&w(n.fileData.mimeType)&&w(n.fileData.fileUri)?{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri}:T(n,"executableCode")?{type:"non_standard",value:n}:T(n,"codeExecutionResult")?{type:"non_standard",value:n}:{type:"non_standard",value:n}),a=Ie(()=>"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,...a};for(let l in o)o[l]===void 0&&delete o[l];yield o}}return s(e,"iterateContent"),Array.from(e())}s(Js,"convertToV1FromChatGoogleMessage");var Zs={translateContent:Js,translateContentChunk:Js};globalThis.lc_block_translators_registry??=new Map([["anthropic",As],["bedrock-converse",Ns],["deepseek",$s],["google",Zs],["google-genai",Us],["google-vertexai",js],["groq",Hs],["ollama",Gs],["openai",Ps],["openrouter",qs],["xai",Ks]]);function Ys(t){return globalThis.lc_block_translators_registry.get(t)}s(Ys,"getTranslator");function Xs(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}s(Xs,"mergeModalitiesTokenDetails");function $d(t,e){let r={...Xs(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}s($d,"mergeInputTokenDetails");function Dd(t,e){let r={...Xs(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}s(Dd,"mergeOutputTokenDetails");function Qr(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:$d(t?.input_token_details,e?.input_token_details),output_token_details:Dd(t?.output_token_details,e?.output_token_details)}}s(Qr,"mergeUsageMetadata");var at=class extends We{static{s(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
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[a,i]=Rn(r);e.tool_calls=a??[],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(s=>!e.contentBlocks?.some(l=>l.type==="tool_call"&&l.id===s.id&&l.name===s.name));e.contentBlocks.push(...i.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})))}let a=e.contentBlocks.filter(i=>i.type==="tool_call").filter(i=>!e.tool_calls?.some(s=>s.id===i.id&&s.name===i.name));a.length>0&&(e.tool_calls=[...e.tool_calls??[],...a.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=ss(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 rp(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(rp,"_contentBlockToString");function _r(t,e="Human",r="AI"){let n=[];for(let a of t){let i;if(a.type==="human")i=e;else if(a.type==="ai")i=r;else if(a.type==="system")i="System";else if(a.type==="tool")i="Tool";else if(a.type==="generic")i=a.role;else throw new Error(`Got unsupported message type: ${a.type}`);let s=a.name?`${a.name}, `:"",l=typeof a.content=="string"?a.content:Array.isArray(a.content)?a.content.map(rp).filter(Boolean).join(""):"",c=`${i}: ${s}${l}`;if(a.type==="ai"){let u=a;u.tool_calls&&u.tool_calls.length>0?c+=JSON.stringify(u.tool_calls):u.additional_kwargs&&"function_call"in u.additional_kwargs&&(c+=JSON.stringify(u.additional_kwargs.function_call))}n.push(c)}return n.join(`
7
- `)}o(_r,"getBufferString");var I="0123456789abcdef".split(""),np=[-2147483648,8388608,32768,128],Me=[24,16,8,0],yr=[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],ae=[];function Le(t,e){e?(ae[0]=ae[16]=ae[1]=ae[2]=ae[3]=ae[4]=ae[5]=ae[6]=ae[7]=ae[8]=ae[9]=ae[10]=ae[11]=ae[12]=ae[13]=ae[14]=ae[15]=0,this.blocks=ae):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(Le,"Sha256");Le.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,a=0,i,s=t.length,l=this.blocks;a<s;){if(this.hashed&&(this.hashed=!1,l[0]=this.block,this.block=l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0),e)for(i=this.start;a<s&&i<64;++a)l[i>>>2]|=t[a]<<Me[i++&3];else for(i=this.start;a<s&&i<64;++a)n=t.charCodeAt(a),n<128?l[i>>>2]|=n<<Me[i++&3]:n<2048?(l[i>>>2]|=(192|n>>>6)<<Me[i++&3],l[i>>>2]|=(128|n&63)<<Me[i++&3]):n<55296||n>=57344?(l[i>>>2]|=(224|n>>>12)<<Me[i++&3],l[i>>>2]|=(128|n>>>6&63)<<Me[i++&3],l[i>>>2]|=(128|n&63)<<Me[i++&3]):(n=65536+((n&1023)<<10|t.charCodeAt(++a)&1023),l[i>>>2]|=(240|n>>>18)<<Me[i++&3],l[i>>>2]|=(128|n>>>12&63)<<Me[i++&3],l[i>>>2]|=(128|n>>>6&63)<<Me[i++&3],l[i>>>2]|=(128|n&63)<<Me[i++&3]);this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.block=l[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}};Le.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=np[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()}};Le.prototype.hash=function(){var t=this.h0,e=this.h1,r=this.h2,n=this.h3,a=this.h4,i=this.h5,s=this.h6,l=this.h7,c=this.blocks,u,p,m,g,h,E,x,P,N,L,C;for(u=16;u<64;++u)h=c[u-15],p=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3,h=c[u-2],m=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10,c[u]=c[u-16]+p+c[u-7]+m<<0;for(C=e&r,u=0;u<64;u+=4)this.first?(this.is224?(P=300032,h=c[0]-1413257819,l=h-150054599<<0,n=h+24177077<<0):(P=704751109,h=c[0]-210244248,l=h-1521486534<<0,n=h+143694565<<0),this.first=!1):(p=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),m=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),P=t&e,g=P^t&r^C,x=a&i^~a&s,h=l+m+x+yr[u]+c[u],E=p+g,l=n+h<<0,n=h+E<<0),p=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),m=(l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7),N=n&t,g=N^n&e^P,x=s&l^~s&a,h=i+m+x+yr[u+1]+c[u+1],E=p+g,s=r+h<<0,r=h+E<<0,p=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),m=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),L=r&n,g=L^r&t^N,x=i&s^~i&l,h=a+m+x+yr[u+2]+c[u+2],E=p+g,i=e+h<<0,e=h+E<<0,p=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),m=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),C=e&r,g=C^e&n^L,x=i&s^~i&l,h=a+m+x+yr[u+3]+c[u+3],E=p+g,a=t+h<<0,t=h+E<<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+a<<0,this.h5=this.h5+i<<0,this.h6=this.h6+s<<0,this.h7=this.h7+l<<0};Le.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,a=this.h4,i=this.h5,s=this.h6,l=this.h7,c=I[t>>>28&15]+I[t>>>24&15]+I[t>>>20&15]+I[t>>>16&15]+I[t>>>12&15]+I[t>>>8&15]+I[t>>>4&15]+I[t&15]+I[e>>>28&15]+I[e>>>24&15]+I[e>>>20&15]+I[e>>>16&15]+I[e>>>12&15]+I[e>>>8&15]+I[e>>>4&15]+I[e&15]+I[r>>>28&15]+I[r>>>24&15]+I[r>>>20&15]+I[r>>>16&15]+I[r>>>12&15]+I[r>>>8&15]+I[r>>>4&15]+I[r&15]+I[n>>>28&15]+I[n>>>24&15]+I[n>>>20&15]+I[n>>>16&15]+I[n>>>12&15]+I[n>>>8&15]+I[n>>>4&15]+I[n&15]+I[a>>>28&15]+I[a>>>24&15]+I[a>>>20&15]+I[a>>>16&15]+I[a>>>12&15]+I[a>>>8&15]+I[a>>>4&15]+I[a&15]+I[i>>>28&15]+I[i>>>24&15]+I[i>>>20&15]+I[i>>>16&15]+I[i>>>12&15]+I[i>>>8&15]+I[i>>>4&15]+I[i&15]+I[s>>>28&15]+I[s>>>24&15]+I[s>>>20&15]+I[s>>>16&15]+I[s>>>12&15]+I[s>>>8&15]+I[s>>>4&15]+I[s&15];return this.is224||(c+=I[l>>>28&15]+I[l>>>24&15]+I[l>>>20&15]+I[l>>>16&15]+I[l>>>12&15]+I[l>>>8&15]+I[l>>>4&15]+I[l&15]),c};Le.prototype.toString=Le.prototype.hex;Le.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,a=this.h4,i=this.h5,s=this.h6,l=this.h7,c=[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,a>>>24&255,a>>>16&255,a>>>8&255,a&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255];return this.is224||c.push(l>>>24&255,l>>>16&255,l>>>8&255,l&255),c};Le.prototype.array=Le.prototype.digest;Le.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 gp=xe(Tr(),1);var Is=/^(?:[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 Pt(t){return typeof t=="string"&&Is.test(t)}o(Pt,"validate");function $t(t){if(!Pt(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($t,"parse");var ie=[];for(let t=0;t<256;++t)ie.push((t+256).toString(16).slice(1));function Xe(t,e=0){return(ie[t[e+0]]+ie[t[e+1]]+ie[t[e+2]]+ie[t[e+3]]+"-"+ie[t[e+4]]+ie[t[e+5]]+"-"+ie[t[e+6]]+ie[t[e+7]]+"-"+ie[t[e+8]]+ie[t[e+9]]+"-"+ie[t[e+10]]+ie[t[e+11]]+ie[t[e+12]]+ie[t[e+13]]+ie[t[e+14]]+ie[t[e+15]]).toLowerCase()}o(Xe,"unsafeStringify");var _p=new Uint8Array(16);function Lt(){return crypto.getRandomValues(_p)}o(Lt,"rng");function yp(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(yp,"f");function Fn(t,e){return t<<e|t>>>32-e}o(Fn,"ROTL");function Cs(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 a=t.length/4+2,i=Math.ceil(a/16),s=new Array(i);for(let l=0;l<i;++l){let c=new Uint32Array(16);for(let u=0;u<16;++u)c[u]=t[l*64+u*4]<<24|t[l*64+u*4+1]<<16|t[l*64+u*4+2]<<8|t[l*64+u*4+3];s[l]=c}s[i-1][14]=(t.length-1)*8/2**32,s[i-1][14]=Math.floor(s[i-1][14]),s[i-1][15]=(t.length-1)*8&4294967295;for(let l=0;l<i;++l){let c=new Uint32Array(80);for(let E=0;E<16;++E)c[E]=s[l][E];for(let E=16;E<80;++E)c[E]=Fn(c[E-3]^c[E-8]^c[E-14]^c[E-16],1);let u=r[0],p=r[1],m=r[2],g=r[3],h=r[4];for(let E=0;E<80;++E){let x=Math.floor(E/20),P=Fn(u,5)+yp(x,p,m,g)+h+e[x]+c[E]>>>0;h=g,g=m,m=Fn(p,30)>>>0,p=u,u=P}r[0]=r[0]+u>>>0,r[1]=r[1]+p>>>0,r[2]=r[2]+m>>>0,r[3]=r[3]+g>>>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])}o(Cs,"sha1");function bp(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(bp,"stringToBytes");var Os="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Rs="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Ms(t,e,r,n,a,i){let s=typeof r=="string"?bp(r):r,l=typeof n=="string"?$t(n):n;if(typeof n=="string"&&(n=$t(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+s.length);if(c.set(l),c.set(s,l.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,a){if(i??=0,i<0||i+16>a.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);for(let u=0;u<16;++u)a[i+u]=c[u];return a}return Xe(c)}o(Ms,"v35");function Un(t,e,r,n){return Ms(80,Cs,t,e,r,n)}o(Un,"v5");Un.DNS=Os;Un.URL=Rs;var jn={};function Ns(t,e,r){let n;if(t)n=ks(t.random??t.rng?.()??Lt(),t.msecs,t.seq,e,r);else{let a=Date.now(),i=Lt();vp(jn,a,i),n=ks(i,jn.msecs,jn.seq,e,r)}return e??Xe(n)}o(Ns,"v7");function vp(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(vp,"updateV7State");function ks(t,e,r,n,a=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),a=0;else if(a<0||a+16>n.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);return e??=Date.now(),r??=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9],n[a++]=e/1099511627776&255,n[a++]=e/4294967296&255,n[a++]=e/16777216&255,n[a++]=e/65536&255,n[a++]=e/256&255,n[a++]=e&255,n[a++]=112|r>>>28&15,n[a++]=r>>>20&255,n[a++]=128|r>>>14&63,n[a++]=r>>>6&255,n[a++]=r<<2&255|t[10]&3,n[a++]=t[11],n[a++]=t[12],n[a++]=t[13],n[a++]=t[14],n[a++]=t[15],n}o(ks,"v7Bytes");var De=Ns;var Ps=Symbol.for("ls:tracing_async_local_storage"),lt=Symbol.for("lc:context_variables"),$s=o(t=>{globalThis[Ps]=t},"setGlobalAsyncLocalStorageInstance"),Qe=o(()=>globalThis[Ps],"getGlobalAsyncLocalStorageInstance");var Ep=o(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),Tp=o(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),xp=o(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),Gn=o(()=>typeof Deno<"u","isDeno"),Sp=o(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Gn(),"isNode"),Ap=o(()=>{let t;return Ep()?t="browser":Sp()?t="node":Tp()?t="webworker":xp()?t="jsdom":Gn()?t="deno":t="other",t},"getEnv"),Bn;function Ls(){return Bn===void 0&&(Bn={library:"langchain-js",runtime:Ap()}),Bn}o(Ls,"getRuntimeEnvironment");function ke(t){try{return typeof process<"u"?process.env?.[t]:Gn()?Deno?.env.get(t):void 0}catch{return}}o(ke,"getEnvironmentVariable");var Ip=class{static{o(this,"BaseCallbackHandlerMethodsClass")}};var vt=class extends Ip{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,Sn(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=ke("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 st.prototype.toJSON.call(this)}toJSONNotImplemented(){return st.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends vt{static{o(this,"Handler")}name=De();constructor(){super(),Object.assign(this,t)}}return new e}},Ds=o(t=>{let e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},"isBaseCallbackHandler");var Fs=/^(?:[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 Cp(t){return typeof t=="string"&&Fs.test(t)}o(Cp,"validate");var Us=Cp;function Op(t){if(!Us(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(Op,"parse");var js=Op;var se=[];for(let t=0;t<256;++t)se.push((t+256).toString(16).slice(1));function Et(t,e=0){return(se[t[e+0]]+se[t[e+1]]+se[t[e+2]]+se[t[e+3]]+"-"+se[t[e+4]]+se[t[e+5]]+"-"+se[t[e+6]]+se[t[e+7]]+"-"+se[t[e+8]]+se[t[e+9]]+"-"+se[t[e+10]]+se[t[e+11]]+se[t[e+12]]+se[t[e+13]]+se[t[e+14]]+se[t[e+15]]).toLowerCase()}o(Et,"unsafeStringify");var Bs=xe(require("node:crypto"));var Sr=new Uint8Array(256),xr=Sr.length;function Dt(){return xr>Sr.length-16&&(Bs.default.randomFillSync(Sr),xr=0),Sr.slice(xr,xr+=16)}o(Dt,"rng");function Rp(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}o(Rp,"stringToBytes");var Mp="6ba7b810-9dad-11d1-80b4-00c04fd430c8",kp="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Hn(t,e,r){function n(a,i,s,l){var c;if(typeof a=="string"&&(a=Rp(a)),typeof i=="string"&&(i=js(i)),((c=i)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let u=new Uint8Array(16+a.length);if(u.set(i),u.set(a,i.length),u=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,s){l=l||0;for(let p=0;p<16;++p)s[l+p]=u[p];return s}return Et(u)}o(n,"generateUUID");try{n.name=t}catch{}return n.DNS=Mp,n.URL=kp,n}o(Hn,"v35");var Gs=xe(require("node:crypto")),zn={randomUUID:Gs.default.randomUUID};function Np(t,e,r){if(zn.randomUUID&&!e&&!t)return zn.randomUUID();t=t||{};let n=t.random||(t.rng||Dt)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(let a=0;a<16;++a)e[r+a]=n[a];return e}return Et(n)}o(Np,"v4");var ct=Np;var Hs=xe(require("node:crypto"));function Pp(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),Hs.default.createHash("sha1").update(t).digest()}o(Pp,"sha1");var zs=Pp;var $p=Hn("v5",80,zs),Vn=$p;var Vs=null,qs=null,Ne=0;function Lp(t,e,r){t=t||{};let n=e&&r||0,a=e||new Uint8Array(16),i=t.random||(t.rng||Dt)(),s=t.msecs!==void 0?t.msecs:Date.now(),l=t.seq!==void 0?t.seq:null,c=qs,u=Vs;return s>Ne&&t.msecs===void 0&&(Ne=s,l!==null&&(c=null,u=null)),l!==null&&(l>2147483647&&(l=2147483647),c=l>>>19&4095,u=l&524287),(c===null||u===null)&&(c=i[6]&127,c=c<<8|i[7],u=i[8]&63,u=u<<8|i[9],u=u<<5|i[10]>>>3),s+1e4>Ne&&l===null?++u>524287&&(u=0,++c>4095&&(c=0,Ne++)):Ne=s,qs=c,Vs=u,a[n++]=Ne/1099511627776&255,a[n++]=Ne/4294967296&255,a[n++]=Ne/16777216&255,a[n++]=Ne/65536&255,a[n++]=Ne/256&255,a[n++]=Ne&255,a[n++]=c>>>4&15|112,a[n++]=c&255,a[n++]=u>>>13&63|128,a[n++]=u>>>5&255,a[n++]=u<<3&255|i[10]&7,a[n++]=i[11],a[n++]=i[12],a[n++]=i[13],a[n++]=i[14],a[n++]=i[15],e||Et(a)}o(Lp,"v7");var Ft=Lp;var Ws="gen_ai.operation.name",Ks="gen_ai.system",qn="gen_ai.request.model",Js="gen_ai.response.model",Wn="gen_ai.usage.input_tokens",Kn="gen_ai.usage.output_tokens",Jn="gen_ai.usage.total_tokens",Zs="gen_ai.request.max_tokens",Ys="gen_ai.request.temperature",Xs="gen_ai.request.top_p",Qs="gen_ai.request.frequency_penalty",eo="gen_ai.request.presence_penalty",to="gen_ai.response.finish_reasons",ro="gen_ai.prompt",no="gen_ai.completion",ao="gen_ai.request.extra_query",io="gen_ai.request.extra_body",so="gen_ai.serialized.name",oo="gen_ai.serialized.signature",lo="gen_ai.serialized.doc",co="gen_ai.response.id",uo="gen_ai.response.service_tier",po="gen_ai.response.system_fingerprint",fo="gen_ai.usage.input_token_details",mo="gen_ai.usage.output_token_details",ho="langsmith.trace.session_id",go="langsmith.trace.session_name",_o="langsmith.span.kind",yo="langsmith.trace.name",bo="langsmith.metadata",Zn="langsmith.span.tags";var wo="langsmith.request.streaming",vo="langsmith.request.headers";var Up=o((...t)=>fetch(...t),"DEFAULT_FETCH_IMPLEMENTATION"),jp,Eo=Symbol.for("ls:fetch_implementation");var To=o(()=>globalThis[Eo]===void 0?!0:jp??!1,"_shouldStreamForGlobalFetchImplementation"),xo=o(t=>async(...e)=>{if(t||J("DEBUG")==="true"){let[n,a]=e;console.log(`\u2192 ${a?.method||"GET"} ${n}`)}let r=await(globalThis[Eo]??Up)(...e);return(t||J("DEBUG")==="true")&&console.log(`\u2190 ${r.status} ${r.statusText} ${r.url}`),r},"_getFetchImplementation");var Ut=o(()=>J("PROJECT")??Te("LANGCHAIN_SESSION")??"default","getDefaultProjectName");var So={};function ut(t){So[t]||(console.warn(t),So[t]=!0)}o(ut,"warnOnce");var v=o(t=>BigInt(t),"n"),Oo=v("0x9E3779B1"),Ro=v("0x85EBCA77"),Bp=v("0xC2B2AE3D"),et=v("0x9E3779B185EBCA87"),dt=v("0xC2B2AE3D27D4EB4F"),Mo=v("0x165667B19E3779F9"),ea=v("0x85EBCA77C2B2AE63"),Gp=v("0x27D4EB2F165667C5"),Hp=v("0x165667919E3779F9"),zp=v("0x9FB21C651E98DF25");function Vp(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(Vp,"hexToBytes");var Fe=Vp("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),xt=(v(1)<<v(128))-v(1),U=(v(1)<<v(64))-v(1),Or=(v(1)<<v(32))-v(1),We=64,ko=We/8,qp=8,Ar=4;function q(t,e=0){return new Uint8Array(t.buffer,t.byteOffset+e,t.length-e)}o(q,"getView");function W(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getBigUint64(0,!0)}o(W,"readBigUInt64LE");function Tt(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getUint32(0,!0)}o(Tt,"readUInt32LE");function Yn(t,e=0){return t[e]}o(Yn,"readUInt8");var Wp=o(t=>(t&v(255))<<v(56)|(t&v(65280))<<v(40)|(t&v(16711680))<<v(24)|(t&v(4278190080))<<v(8)|(t&v(0xff00000000))>>v(8)|(t&v(0xff0000000000))>>v(24)|(t&v(0xff000000000000))>>v(40)|(t&v(0xff00000000000000))>>v(56),"bswap64"),Kp=o(t=>(t=(t&v(65535))<<v(16)|(t&v(4294901760))>>v(16),t=(t&v(16711935))<<v(8)|(t&v(4278255360))>>v(8),t),"bswap32"),Jp=o((t,e)=>(t&Or)*(e&Or)&U,"XXH_mult32to64"),St=o(t=>{if(!t)throw new Error("Assert failed")},"assert");function Zp(t,e){return(t<<e|t>>v(32)-e)&Or}o(Zp,"rotl32");function No(t,e,r){for(let n=0;n<ko;n++){let a=W(e,n*8),i=a^W(r,n*8);t[n^1]+=a,t[n]+=Jp(i,i>>v(32))}return t}o(No,"XXH3_accumulate_512");function Ao(t,e,r,n){for(let a=0;a<n;a++)No(t,q(e,a*We),q(r,a*8));return t}o(Ao,"XXH3_accumulate");function Yp(t,e){for(let r=0;r<ko;r++){let n=W(e,r*8),a=t[r];a=Xn(a,v(47)),a^=n,a*=Oo,t[r]=a&U}return t}o(Yp,"XXH3_scrambleAcc");function Ir(t,e){return Po(t[0]^W(e,0),t[1]^W(e,qp))}o(Ir,"XXH3_mix2Accs");function Io(t,e,r){let n=r;return n+=Ir(t.slice(0),q(e,0*Ar)),n+=Ir(t.slice(2),q(e,4*Ar)),n+=Ir(t.slice(4),q(e,8*Ar)),n+=Ir(t.slice(6),q(e,12*Ar)),Ue(n&U)}o(Io,"XXH3_mergeAccs");function Xp(t,e,r,n,a){let i=Math.floor((r.byteLength-We)/8),s=We*i,l=Math.floor((e.byteLength-1)/s);for(let c=0;c<l;c++)t=Ao(t,q(e,c*s),r,i),t=a(t,q(r,r.byteLength-We));{let c=Math.floor((e.byteLength-1-s*l)/We);t=Ao(t,q(e,l*s),r,c),t=n(t,q(e,e.byteLength-We),q(r,r.byteLength-We-7))}return t}o(Xp,"XXH3_hashLong");function Qp(t,e,r){let n=new BigUint64Array([Bp,et,dt,Mo,ea,Ro,Gp,Oo]);St(t.length>128),n=Xp(n,t,e,No,Yp),St(n.length*8==64);{let a=Io(n,q(e,11),v(t.byteLength)*et&U);return Io(n,q(e,e.byteLength-We-11),~(v(t.byteLength)*dt)&U)<<v(64)|a}}o(Qp,"XXH3_hashLong_128b");function Po(t,e){let r=t*e&xt;return r&U^r>>v(64)}o(Po,"XXH3_mul128_fold64");function Co(t,e,r){return Po((W(t,0)^W(e,0)+r)&U,(W(t,8)^W(e,8)-r)&U)}o(Co,"XXH3_mix16B");function Cr(t,e,r,n,a){let i=t&U,s=t>>v(64)&U;return i+=Co(e,n,a),i^=W(r,0)+W(r,8),i&=U,s+=Co(r,q(n,16),a),s^=W(e,0)+W(e,8),s&=U,s<<v(64)|i}o(Cr,"XXH3_mix32B");function Ue(t){return t^=t>>v(37),t*=Hp,t&=U,t^=t>>v(32),t}o(Ue,"XXH3_avalanche");function Rr(t){return t^=t>>v(33),t*=dt,t&=U,t^=t>>v(29),t*=Mo,t&=U,t^=t>>v(32),t}o(Rr,"XXH3_avalanche64");function ef(t,e,r){let n=t.byteLength;St(n>0&&n<=3);let a=v(Yn(t,n-1))|v(n<<8)|v(Yn(t,0)<<16)|v(Yn(t,n>>1)<<24),i=(v(Tt(e,0))^v(Tt(e,4)))+r,s=(a^i)&U,l=(v(Tt(e,8))^v(Tt(e,12)))-r,c=(Zp(Kp(a),v(13))^l)&U;return(Rr(c)&U)<<v(64)|Rr(s)}o(ef,"XXH3_len_1to3_128b");function Xn(t,e){return t^t>>e}o(Xn,"xorshift64");function tf(t,e,r){let n=t.byteLength;St(n>=4&&n<=8);{let a=Tt(t,0),i=Tt(t,n-4),s=v(a)|v(i)<<v(32),l=(W(e,16)^W(e,24))+r&U,u=(s^l)*(et+(v(n)<<v(2)))&xt;return u+=(u&U)<<v(65),u&=xt,u^=u>>v(67),Xn(Xn(u&U,v(35))*zp&U,v(28))|Ue(u>>v(64))<<v(64)}}o(tf,"XXH3_len_4to8_128b");function rf(t,e,r){let n=t.byteLength;St(n>=9&&n<=16);{let a=(W(e,32)^W(e,40))+r&U,i=(W(e,48)^W(e,56))-r&U,s=W(t),l=W(t,n-8),c=(s^l^a)*et,u=(c&U)+(v(n-1)<<v(54));c=c&(xt^U)|u,l^=i,c+=l+(l&Or)*(Ro-v(1))<<v(64),c&=xt,c^=Wp(c>>v(64));let p=(c&U)*dt;return p+=(c>>v(64))*dt<<v(64),p&=xt,Ue(p&U)|Ue(p>>v(64))<<v(64)}}o(rf,"XXH3_len_9to16_128b");function nf(t,e){let r=t.byteLength;return St(r<=16),r>8?rf(t,Fe,e):r>=4?tf(t,Fe,e):r>0?ef(t,Fe,e):Rr(e^W(Fe,64)^W(Fe,72))|Rr(e^W(Fe,80)^W(Fe,88))<<v(64)}o(nf,"XXH3_len_0to16_128b");function Qn(t){return~t+v(1)&U}o(Qn,"inv64");function af(t,e,r){let n=v(t.byteLength)*et&U,a=v(t.byteLength-1)/v(32);for(;a>=0;){let l=Number(a);n=Cr(n,q(t,16*l),q(t,t.byteLength-16*(l+1)),q(e,32*l),r),a--}let i=n+(n>>v(64))&U;i=Ue(i);let s=(n&U)*et+(n>>v(64))*ea+(v(t.byteLength)-r&U)*dt;return s&=U,s=Qn(Ue(s)),i|s<<v(64)}o(af,"XXH3_len_17to128_128b");function sf(t,e,r){let n=v(t.byteLength)*et&U;for(let s=32;s<160;s+=32)n=Cr(n,q(t,s-32),q(t,s-16),q(e,s-32),r);n=Ue(n&U)|Ue(n>>v(64))<<v(64);for(let s=160;s<=t.byteLength;s+=32)n=Cr(n,q(t,s-32),q(t,s-16),q(e,3+s-160),r);n=Cr(n,q(t,t.byteLength-16),q(t,t.byteLength-32),q(e,103),Qn(r));let a=n+(n>>v(64))&U;a=Ue(a);let i=(n&U)*et+(n>>v(64))*ea+(v(t.byteLength)-r&U)*dt;return i&=U,i=Qn(Ue(i)),a|i<<v(64)}o(sf,"XXH3_len_129to240_128b");function $o(t,e=v(0)){let r=t.byteLength;return r<=16?nf(t,e):r<=128?af(t,Fe,e):r<=240?sf(t,Fe,e):Qp(t,Fe,e)}o($o,"XXH3_128");function Lo(t){let e=new Uint8Array(16),r=new DataView(e.buffer),n=t&U,a=t>>v(64);return r.setBigUint64(0,a,!1),r.setBigUint64(8,n,!1),e}o(Lo,"xxh128ToBytes");var Do=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function $(t,e){if(!Do.test(t)){let r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}o($,"assertUuid");function Mr(t){let e=typeof t=="string"?Date.parse(t):t;return Ft({msecs:e,seq:0})}o(Mr,"uuid7FromTime");function of(t){if(!Do.test(t))return null;let e=t[14];return parseInt(e,16)}o(of,"getUuidVersion");function lf(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(lf,"uuidToBytes");function cf(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(cf,"bytesToUuid");var uf=new TextEncoder;function df(t){let e=uf.encode(t),r=$o(e);return Lo(r)}o(df,"_fastHash128");function jt(t,e){let r=`${t}:${e}`,n=df(r),a=new Uint8Array(16);if(of(t)===7){let s=lf(t);a.set(s.slice(0,6),0)}else{let s=Date.now();a[0]=s/1099511627776&255,a[1]=s/4294967296&255,a[2]=s/16777216&255,a[3]=s/65536&255,a[4]=s/256&255,a[5]=s&255}return a[6]=112|n[0]&15,a[7]=n[1],a[8]=128|n[2]&63,a.set(n.slice(3,10),9),cf(a)}o(jt,"nonCryptographicUuid7Deterministic");var Se=xe(require("node:fs"),1),Pe=xe(require("node:fs/promises"),1),pf=xe(require("node:path"),1);var Bt=pf;async function Fo(t){await Pe.mkdir(t,{recursive:!0})}o(Fo,"mkdir");async function Uo(t,e){let r=`${t}.tmp`;await Pe.writeFile(r,e,{encoding:"utf8",mode:384}),await Pe.rename(r,t)}o(Uo,"writeFileAtomic");async function jo(t){return Pe.readdir(t)}o(jo,"readdir");async function Bo(t){return Pe.stat(t)}o(Bo,"stat");function kr(t){return Se.existsSync(t)}o(kr,"existsSync");function Go(t){Se.mkdirSync(t,{recursive:!0})}o(Go,"mkdirSync");function Ho(t,e){Se.writeFileSync(t,e)}o(Ho,"writeFileSync");function zo(t,e){Se.renameSync(t,e)}o(zo,"renameSync");function Vo(t){Se.unlinkSync(t)}o(Vo,"unlinkSync");function qo(t){return Se.readFileSync(t,"utf-8")}o(qo,"readFileSync");function mf(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}o(mf,"isStale");var Nr=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 a={value:r,createdAt:Date.now(),refreshFunc:n};this.cache.delete(e),this.cache.set(e,a)}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,s]of this.cache.entries())r[i]=s.value;let n=Bt.dirname(e);kr(n)||Go(n);let a=`${e}.tmp`;try{Ho(a,JSON.stringify({entries:r},null,2)),zo(a,e)}catch(i){throw kr(a)&&Vo(a),i}}load(e){if(!kr(e))return 0;let r;try{let i=qo(e);r=JSON.parse(i).entries??null}catch{return 0}if(!r)return 0;let n=0,a=Date.now();for(let[i,s]of Object.entries(r)){if(this.cache.size>=this.maxSize)break;let l={value:s,createdAt:a};this.cache.set(i,l),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())mf(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 a=await n.refreshFunc();this.set(r,a,n.refreshFunc),this._metrics.refreshes+=1}catch(a){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${r}:`,a)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}},Pr=new Nr;var $r="0.5.16";var je,hf=o(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),gf=o(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),_f=o(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),Wo=o(()=>typeof Deno<"u","isDeno"),yf=o(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Wo(),"isNode"),na=o(()=>je||(typeof Bun<"u"?je="bun":hf()?je="browser":yf()?je="node":gf()?je="webworker":_f()?je="jsdom":Wo()?je="deno":je="other",je),"getEnv"),ta;function Lr(){if(ta===void 0){let t=na(),e=wf();ta={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:$r,...e}}return ta}o(Lr,"getRuntimeEnvironment");function aa(){let t=bf(),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,a]of Object.entries(t))typeof a=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=a:e[n]=a);return e}o(aa,"getLangSmithEnvVarsMetadata");function bf(){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(bf,"getLangSmithEnvironmentVariables");function Te(t){try{return typeof process<"u"?process.env?.[t]:void 0}catch{return}}o(Te,"getEnvironmentVariable");function J(t){return Te(`LANGSMITH_${t}`)||Te(`LANGCHAIN_${t}`)}o(J,"getLangSmithEnvironmentVariable");var ra;function wf(){if(ra!==void 0)return ra;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=Te(r);n!==void 0&&(e[r]=n)}return ra=e,e}o(wf,"getShas");function Dr(){return Te("OTEL_ENABLED")==="true"||J("OTEL_ENABLED")==="true"}o(Dr,"getOtelEnabled");var oa=class{static{o(this,"MockTracer")}constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&Dr()&&(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()}},la=class{static{o(this,"MockOTELTrace")}constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new oa})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},ca=class{static{o(this,"MockOTELContext")}active(){return{}}with(e,r){return r()}},ia=Symbol.for("ls:otel_trace"),sa=Symbol.for("ls:otel_context"),Ko=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),vf=new la,Ef=new ca,ua=class{static{o(this,"OTELProvider")}getTraceInstance(){return globalThis[ia]??vf}getContextInstance(){return globalThis[sa]??Ef}initializeGlobalInstances(e){globalThis[ia]===void 0&&(globalThis[ia]=e.trace),globalThis[sa]===void 0&&(globalThis[sa]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[Ko]=e}getDefaultOTLPTracerComponents(){return globalThis[Ko]??void 0}},da=new ua;function Fr(){return da.getTraceInstance()}o(Fr,"getOTELTrace");function Jo(){return da.getContextInstance()}o(Jo,"getOTELContext");function Zo(){return da.getDefaultOTLPTracerComponents()}o(Zo,"getDefaultOTLPTracerComponents");var Tf={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function xf(t){return Tf[t]||t}o(xf,"getOperationName");var Ur=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 a=this.createSpanForRun(n,n.run,r.get(n.id));a&&!n.run.end_time&&this.spans.set(n.id,a)}else this.updateSpanForRun(n,n.run)}catch(a){console.error(`Error processing operation ${n.id}:`,a)}}createSpanForRun(e,r,n){let a=n&&Fr().getSpan(n);if(a)try{return this.finishSpanSetup(a,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 a=r.end_time;a&&(n.end(new Date(a)),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(_o,r.run_type);let l=xf(r.run_type||"chain");e.setAttribute(Ws,l)}"name"in r&&r.name&&e.setAttribute(yo,r.name),"session_id"in r&&r.session_id&&e.setAttribute(ho,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(go,r.session_name),this.setGenAiSystem(e,r);let a=this.extractModelName(r);a&&e.setAttribute(qn,a),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(Wn,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(Kn,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(Jn,r.total_tokens),this.setInvocationParameters(e,r);let i=r.extra?.metadata||{};for(let[l,c]of Object.entries(i))c!=null&&e.setAttribute(`${bo}.${l}`,String(c));let s=r.tags;if(s&&Array.isArray(s)?e.setAttribute(Zn,s.join(", ")):s&&e.setAttribute(Zn,String(s)),"serialized"in r&&typeof r.serialized=="object"){let l=r.serialized;l.name&&e.setAttribute(so,String(l.name)),l.signature&&e.setAttribute(oo,String(l.signature)),l.doc&&e.setAttribute(lo,String(l.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,r){let n="langchain",a=this.extractModelName(r);if(a){let i=a.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(Ks,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(Zs,n.max_tokens),n.temperature!==void 0&&e.setAttribute(Ys,n.temperature),n.top_p!==void 0&&e.setAttribute(Xs,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(Qs,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(eo,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(qn,n.model),n.stream!==void 0&&e.setAttribute(wo,n.stream),n.extra_headers&&e.setAttribute(vo,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(ao,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(io,JSON.stringify(n.extra_body))),e.setAttribute(ro,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,a=this.getUnifiedRunTokens(n);if(a&&(e.setAttribute(Wn,a[0]),e.setAttribute(Kn,a[1]),e.setAttribute(Jn,a[0]+a[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(Js,String(n.model)),n.id&&e.setAttribute(co,n.id),n.choices&&Array.isArray(n.choices)){let i=n.choices.map(s=>s.finish_reason).filter(s=>s).map(String);i.length>0&&e.setAttribute(to,i.join(", "))}if(n.service_tier&&e.setAttribute(uo,n.service_tier),n.system_fingerprint&&e.setAttribute(po,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let i=n.usage_metadata;i.input_token_details&&e.setAttribute(fo,JSON.stringify(i.input_token_details)),i.output_token_details&&e.setAttribute(mo,JSON.stringify(i.output_token_details))}}e.setAttribute(no,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 s of n){let l=e[s];if(!(!l||typeof l!="object")&&(r=this.extractUnifiedRunTokens(l.usage_metadata),r||l.lc===1&&l.kwargs&&typeof l.kwargs=="object"&&(r=this.extractUnifiedRunTokens(l.kwargs.usage_metadata),r)))return r}let a=e.generations||[];if(!Array.isArray(a))return null;let i=Array.isArray(a[0])?a.flat():a;for(let s of i)if(typeof s=="object"&&s.message&&typeof s.message=="object"&&s.message.kwargs&&typeof s.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(s.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 Sf=Object.prototype.toString,Af=o(t=>Sf.call(t)==="[object Error]","isError"),If=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 pa(t){if(!(t&&Af(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:If.has(r)}o(pa,"isNetworkError");function Cf(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(Cf,"validateRetries");function jr(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(jr,"validateNumberOption");var fa=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 Of(t,e){let r=Math.max(1,t+1),n=e.randomize?Math.random()+1:1,a=Math.round(n*e.minTimeout*e.factor**(r-1));return a=Math.min(a,e.maxTimeout),a}o(Of,"calculateDelay");function Yo(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}o(Yo,"calculateRemainingTime");async function Rf({error:t,attemptNumber:e,retriesConsumed:r,startTime:n,options:a}){let i=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(i instanceof fa)throw i.originalError;let s=Number.isFinite(a.retries)?Math.max(0,a.retries-r):a.retries,l=a.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:i,attemptNumber:e,retriesLeft:s,retriesConsumed:r});if(await a.onFailedAttempt(c),Yo(n,l)<=0)throw i;let u=await a.shouldConsumeRetry(c),p=Yo(n,l);if(p<=0||s<=0)throw i;if(i instanceof TypeError&&!pa(i)){if(u)throw i;return a.signal?.throwIfAborted(),!1}if(!await a.shouldRetry(c))throw i;if(!u)return a.signal?.throwIfAborted(),!1;let m=Of(r,a),g=Math.min(m,p);return g>0&&await new Promise((h,E)=>{let x=o(()=>{clearTimeout(P),a.signal?.removeEventListener("abort",x),E(a.signal.reason)},"onAbort"),P=setTimeout(()=>{a.signal?.removeEventListener("abort",x),h()},g);a.unref&&P.unref?.(),a.signal?.addEventListener("abort",x,{once:!0})}),a.signal?.throwIfAborted(),!0}o(Rf,"onAttemptFailure");async function ma(t,e={}){if(e={...e},Cf(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,jr("factor",e.factor,{min:0,allowInfinity:!1}),jr("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),jr("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),jr("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let r=0,n=0,a=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 Rf({error:i,attemptNumber:r,retriesConsumed:n,startTime:a,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}o(ma,"pRetry");var Br=xe(Tr(),1),Xo="default"in Br.default?Br.default.default:Br.default;var Mf=[408,425,429,500,502,503,504],Gt=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 Xo({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...r){return this.callWithOptions({},e,...r)}callWithOptions(e,r,...n){let a=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&a>0&&this.queueSizeBytes+a>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${a} bytes.`));a>0&&(this.queueSizeBytes+=a);let i=this.onFailedResponseHook,s=this.queue.add(()=>ma(()=>r(...n).catch(l=>{throw l instanceof Error?l:new Error(l)}),{async onFailedAttempt({error:l}){if(typeof l!="object"||l==null)throw l;let c="message"in l&&typeof l.message=="string"?l.message:void 0;if(c?.startsWith("Cancel")||c?.startsWith("TimeoutError")||c?.startsWith("AbortError")||"name"in l&&l.name==="TimeoutError"||"code"in l&&l.code==="ECONNABORTED")throw l;let u="response"in l?l.response:void 0;if(i&&await i(u))return;let p=u?.status??("status"in l?l.status:void 0);if(p!=null&&(typeof p=="number"||typeof p=="string")&&!Mf.includes(+p))throw l},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return a>0&&(s=s.finally(()=>{this.queueSizeBytes-=a})),e.signal?Promise.race([s,new Promise((l,c)=>{e.signal?.addEventListener("abort",()=>{c(new Error("AbortError"))})})]):s}};function ha(t){return typeof t?._getType=="function"}o(ha,"isLangChainMessage");function ga(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(ga,"convertLangChainMessageToExample");var Ig=xe(Bc(),1);function tn(t){return`Invalid prompt identifier format: "${t}". Expected one of:
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,a]=gi(r);e.tool_calls=i??[],e.invalid_tool_calls=a??[]}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 a=e.tool_calls.filter(o=>!e.contentBlocks?.some(l=>l.type==="tool_call"&&l.id===o.id&&l.name===o.name));e.contentBlocks.push(...a.map(o=>({type:"tool_call",id:o.id,name:o.name,args:o.args})))}let i=e.contentBlocks.filter(a=>a.type==="tool_call").filter(a=>!e.tool_calls?.some(o=>o.id===a.id&&o.name===a.name));i.length>0&&(e.tool_calls=[...e.tool_calls??[],...i.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.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=Ys(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 Gd(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}]`:""}}s(Gd,"_contentBlockToString");function rn(t,e="Human",r="AI"){let n=[];for(let i of t){let a;if(i.type==="human")a=e;else if(i.type==="ai")a=r;else if(i.type==="system")a="System";else if(i.type==="tool")a="Tool";else if(i.type==="generic")a=i.role;else throw new Error(`Got unsupported message type: ${i.type}`);let o=i.name?`${i.name}, `:"",l=typeof i.content=="string"?i.content:Array.isArray(i.content)?i.content.map(Gd).filter(Boolean).join(""):"",c=`${a}: ${o}${l}`;if(i.type==="ai"){let u=i;u.tool_calls&&u.tool_calls.length>0?c+=JSON.stringify(u.tool_calls):u.additional_kwargs&&"function_call"in u.additional_kwargs&&(c+=JSON.stringify(u.additional_kwargs.function_call))}n.push(c)}return n.join(`
7
+ `)}s(rn,"getBufferString");var k="0123456789abcdef".split(""),Vd=[-2147483648,8388608,32768,128],Re=[24,16,8,0],nn=[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],ie=[];function $e(t,e){e?(ie[0]=ie[16]=ie[1]=ie[2]=ie[3]=ie[4]=ie[5]=ie[6]=ie[7]=ie[8]=ie[9]=ie[10]=ie[11]=ie[12]=ie[13]=ie[14]=ie[15]=0,this.blocks=ie):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}s($e,"Sha256");$e.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,a,o=t.length,l=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,l[0]=this.block,this.block=l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0),e)for(a=this.start;i<o&&a<64;++i)l[a>>>2]|=t[i]<<Re[a++&3];else for(a=this.start;i<o&&a<64;++i)n=t.charCodeAt(i),n<128?l[a>>>2]|=n<<Re[a++&3]:n<2048?(l[a>>>2]|=(192|n>>>6)<<Re[a++&3],l[a>>>2]|=(128|n&63)<<Re[a++&3]):n<55296||n>=57344?(l[a>>>2]|=(224|n>>>12)<<Re[a++&3],l[a>>>2]|=(128|n>>>6&63)<<Re[a++&3],l[a>>>2]|=(128|n&63)<<Re[a++&3]):(n=65536+((n&1023)<<10|t.charCodeAt(++i)&1023),l[a>>>2]|=(240|n>>>18)<<Re[a++&3],l[a>>>2]|=(128|n>>>12&63)<<Re[a++&3],l[a>>>2]|=(128|n>>>6&63)<<Re[a++&3],l[a>>>2]|=(128|n&63)<<Re[a++&3]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=l[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};$e.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=Vd[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()}};$e.prototype.hash=function(){var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,a=this.h5,o=this.h6,l=this.h7,c=this.blocks,u,d,p,h,g,b,v,P,I,S,A;for(u=16;u<64;++u)g=c[u-15],d=(g>>>7|g<<25)^(g>>>18|g<<14)^g>>>3,g=c[u-2],p=(g>>>17|g<<15)^(g>>>19|g<<13)^g>>>10,c[u]=c[u-16]+d+c[u-7]+p<<0;for(A=e&r,u=0;u<64;u+=4)this.first?(this.is224?(P=300032,g=c[0]-1413257819,l=g-150054599<<0,n=g+24177077<<0):(P=704751109,g=c[0]-210244248,l=g-1521486534<<0,n=g+143694565<<0),this.first=!1):(d=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),p=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),P=t&e,h=P^t&r^A,v=i&a^~i&o,g=l+p+v+nn[u]+c[u],b=d+h,l=n+g<<0,n=g+b<<0),d=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),p=(l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7),I=n&t,h=I^n&e^P,v=o&l^~o&i,g=a+p+v+nn[u+1]+c[u+1],b=d+h,o=r+g<<0,r=g+b<<0,d=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),p=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),S=r&n,h=S^r&t^I,v=a&o^~a&l,g=i+p+v+nn[u+2]+c[u+2],b=d+h,a=e+g<<0,e=g+b<<0,d=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),p=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),A=e&r,h=A^e&n^S,v=a&o^~a&l,g=i+p+v+nn[u+3]+c[u+3],b=d+h,i=t+g<<0,t=g+b<<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+a<<0,this.h6=this.h6+o<<0,this.h7=this.h7+l<<0};$e.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,a=this.h5,o=this.h6,l=this.h7,c=k[t>>>28&15]+k[t>>>24&15]+k[t>>>20&15]+k[t>>>16&15]+k[t>>>12&15]+k[t>>>8&15]+k[t>>>4&15]+k[t&15]+k[e>>>28&15]+k[e>>>24&15]+k[e>>>20&15]+k[e>>>16&15]+k[e>>>12&15]+k[e>>>8&15]+k[e>>>4&15]+k[e&15]+k[r>>>28&15]+k[r>>>24&15]+k[r>>>20&15]+k[r>>>16&15]+k[r>>>12&15]+k[r>>>8&15]+k[r>>>4&15]+k[r&15]+k[n>>>28&15]+k[n>>>24&15]+k[n>>>20&15]+k[n>>>16&15]+k[n>>>12&15]+k[n>>>8&15]+k[n>>>4&15]+k[n&15]+k[i>>>28&15]+k[i>>>24&15]+k[i>>>20&15]+k[i>>>16&15]+k[i>>>12&15]+k[i>>>8&15]+k[i>>>4&15]+k[i&15]+k[a>>>28&15]+k[a>>>24&15]+k[a>>>20&15]+k[a>>>16&15]+k[a>>>12&15]+k[a>>>8&15]+k[a>>>4&15]+k[a&15]+k[o>>>28&15]+k[o>>>24&15]+k[o>>>20&15]+k[o>>>16&15]+k[o>>>12&15]+k[o>>>8&15]+k[o>>>4&15]+k[o&15];return this.is224||(c+=k[l>>>28&15]+k[l>>>24&15]+k[l>>>20&15]+k[l>>>16&15]+k[l>>>12&15]+k[l>>>8&15]+k[l>>>4&15]+k[l&15]),c};$e.prototype.toString=$e.prototype.hex;$e.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,a=this.h5,o=this.h6,l=this.h7,c=[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,a>>>24&255,a>>>16&255,a>>>8&255,a&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||c.push(l>>>24&255,l>>>16&255,l>>>8&255,l&255),c};$e.prototype.array=$e.prototype.digest;$e.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 ip=it(cn(),1);var bo=/^(?:[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 Tr(t){return typeof t=="string"&&bo.test(t)}s(Tr,"validate");function Ar(t){if(!Tr(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)}s(Ar,"parse");var oe=[];for(let t=0;t<256;++t)oe.push((t+256).toString(16).slice(1));function st(t,e=0){return(oe[t[e+0]]+oe[t[e+1]]+oe[t[e+2]]+oe[t[e+3]]+"-"+oe[t[e+4]]+oe[t[e+5]]+"-"+oe[t[e+6]]+oe[t[e+7]]+"-"+oe[t[e+8]]+oe[t[e+9]]+"-"+oe[t[e+10]]+oe[t[e+11]]+oe[t[e+12]]+oe[t[e+13]]+oe[t[e+14]]+oe[t[e+15]]).toLowerCase()}s(st,"unsafeStringify");var ap=new Uint8Array(16);function Ir(){return crypto.getRandomValues(ap)}s(Ir,"rng");function sp(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}}s(sp,"f");function Si(t,e){return t<<e|t>>>32-e}s(Si,"ROTL");function wo(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,a=Math.ceil(i/16),o=new Array(a);for(let l=0;l<a;++l){let c=new Uint32Array(16);for(let u=0;u<16;++u)c[u]=t[l*64+u*4]<<24|t[l*64+u*4+1]<<16|t[l*64+u*4+2]<<8|t[l*64+u*4+3];o[l]=c}o[a-1][14]=(t.length-1)*8/2**32,o[a-1][14]=Math.floor(o[a-1][14]),o[a-1][15]=(t.length-1)*8&4294967295;for(let l=0;l<a;++l){let c=new Uint32Array(80);for(let b=0;b<16;++b)c[b]=o[l][b];for(let b=16;b<80;++b)c[b]=Si(c[b-3]^c[b-8]^c[b-14]^c[b-16],1);let u=r[0],d=r[1],p=r[2],h=r[3],g=r[4];for(let b=0;b<80;++b){let v=Math.floor(b/20),P=Si(u,5)+sp(v,d,p,h)+g+e[v]+c[b]>>>0;g=h,h=p,p=Si(d,30)>>>0,d=u,u=P}r[0]=r[0]+u>>>0,r[1]=r[1]+d>>>0,r[2]=r[2]+p>>>0,r[3]=r[3]+h>>>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])}s(wo,"sha1");function op(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}s(op,"stringToBytes");var vo="6ba7b810-9dad-11d1-80b4-00c04fd430c8",xo="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Eo(t,e,r,n,i,a){let o=typeof r=="string"?op(r):r,l=typeof n=="string"?Ar(n):n;if(typeof n=="string"&&(n=Ar(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+o.length);if(c.set(l),c.set(o,l.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,i){if(a??=0,a<0||a+16>i.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let u=0;u<16;++u)i[a+u]=c[u];return i}return st(c)}s(Eo,"v35");function Ti(t,e,r,n){return Eo(80,wo,t,e,r,n)}s(Ti,"v5");Ti.DNS=vo;Ti.URL=xo;var Ai={};function To(t,e,r){let n;if(t)n=So(t.random??t.rng?.()??Ir(),t.msecs,t.seq,e,r);else{let i=Date.now(),a=Ir();cp(Ai,i,a),n=So(a,Ai.msecs,Ai.seq,e,r)}return e??st(n)}s(To,"v7");function cp(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}s(cp,"updateV7State");function So(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}s(So,"v7Bytes");var De=To;var Ao=Symbol.for("ls:tracing_async_local_storage"),xt=Symbol.for("lc:context_variables"),Io=s(t=>{globalThis[Ao]=t},"setGlobalAsyncLocalStorageInstance"),ot=s(()=>globalThis[Ao],"getGlobalAsyncLocalStorageInstance");var up=s(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),dp=s(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),pp=s(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),Ci=s(()=>typeof Deno<"u","isDeno"),fp=s(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Ci(),"isNode"),mp=s(()=>{let t;return up()?t="browser":fp()?t="node":dp()?t="webworker":pp()?t="jsdom":Ci()?t="deno":t="other",t},"getEnv"),Ii;function Co(){return Ii===void 0&&(Ii={library:"langchain-js",runtime:mp()}),Ii}s(Co,"getRuntimeEnvironment");function Me(t){try{return typeof process<"u"?process.env?.[t]:Ci()?Deno?.env.get(t):void 0}catch{return}}s(Me,"getEnvironmentVariable");var hp=class{static{s(this,"BaseCallbackHandlerMethodsClass")}};var Jt=class extends hp{static{s(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,di(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Me("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 wt.prototype.toJSON.call(this)}toJSONNotImplemented(){return wt.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends Jt{static{s(this,"Handler")}name=De();constructor(){super(),Object.assign(this,t)}}return new e}},ko=s(t=>{let e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},"isBaseCallbackHandler");var Oo=/^(?:[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 gp(t){return typeof t=="string"&&Oo.test(t)}s(gp,"validate");var Cr=gp;function yp(t){if(!Cr(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)}s(yp,"parse");var un=yp;var le=[];for(let t=0;t<256;++t)le.push((t+256).toString(16).slice(1));function Zt(t,e=0){return(le[t[e+0]]+le[t[e+1]]+le[t[e+2]]+le[t[e+3]]+"-"+le[t[e+4]]+le[t[e+5]]+"-"+le[t[e+6]]+le[t[e+7]]+"-"+le[t[e+8]]+le[t[e+9]]+"-"+le[t[e+10]]+le[t[e+11]]+le[t[e+12]]+le[t[e+13]]+le[t[e+14]]+le[t[e+15]]).toLowerCase()}s(Zt,"unsafeStringify");var _p=new Uint8Array(16);function Yt(){return crypto.getRandomValues(_p)}s(Yt,"rng");function bp(t,e,r){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():wp(t,e,r)}s(bp,"v4");function wp(t,e,r){t=t||{};let n=t.random??t.rng?.()??Yt();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 Zt(n)}s(wp,"_v4");var Et=bp;function vp(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}}s(vp,"f");function ki(t,e){return t<<e|t>>>32-e}s(ki,"ROTL");function xp(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,a=Math.ceil(i/16),o=new Array(a);for(let l=0;l<a;++l){let c=new Uint32Array(16);for(let u=0;u<16;++u)c[u]=t[l*64+u*4]<<24|t[l*64+u*4+1]<<16|t[l*64+u*4+2]<<8|t[l*64+u*4+3];o[l]=c}o[a-1][14]=(t.length-1)*8/2**32,o[a-1][14]=Math.floor(o[a-1][14]),o[a-1][15]=(t.length-1)*8&4294967295;for(let l=0;l<a;++l){let c=new Uint32Array(80);for(let b=0;b<16;++b)c[b]=o[l][b];for(let b=16;b<80;++b)c[b]=ki(c[b-3]^c[b-8]^c[b-14]^c[b-16],1);let u=r[0],d=r[1],p=r[2],h=r[3],g=r[4];for(let b=0;b<80;++b){let v=Math.floor(b/20),P=ki(u,5)+vp(v,d,p,h)+g+e[v]+c[b]>>>0;g=h,h=p,p=ki(d,30)>>>0,d=u,u=P}r[0]=r[0]+u>>>0,r[1]=r[1]+d>>>0,r[2]=r[2]+p>>>0,r[3]=r[3]+h>>>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])}s(xp,"sha1");var Po=xp;function Ep(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}s(Ep,"stringToBytes");var Oi="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Pi="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Ri(t,e,r,n,i,a){let o=typeof r=="string"?Ep(r):r,l=typeof n=="string"?un(n):n;if(typeof n=="string"&&(n=un(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+o.length);if(c.set(l),c.set(o,l.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,i){if(a??=0,a<0||a+16>i.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let u=0;u<16;++u)i[a+u]=c[u];return i}return Zt(c)}s(Ri,"v35");function Mi(t,e,r,n){return Ri(80,Po,t,e,r,n)}s(Mi,"v5");Mi.DNS=Oi;Mi.URL=Pi;var Ni=Mi;var Li={};function Sp(t,e,r){let n;if(t)n=Ro(t.random??t.rng?.()??Yt(),t.msecs,t.seq,e,r);else{let i=Date.now(),a=Yt();Tp(Li,i,a),n=Ro(a,Li.msecs,Li.seq,e,r)}return e??Zt(n)}s(Sp,"v7");function Tp(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}s(Tp,"updateV7State");function Ro(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}s(Ro,"v7Bytes");var Xt=Sp;var Mo="gen_ai.operation.name",No="gen_ai.system",$i="gen_ai.request.model",Lo="gen_ai.response.model",Di="gen_ai.usage.input_tokens",Ui="gen_ai.usage.output_tokens",Fi="gen_ai.usage.total_tokens",$o="gen_ai.request.max_tokens",Do="gen_ai.request.temperature",Uo="gen_ai.request.top_p",Fo="gen_ai.request.frequency_penalty",jo="gen_ai.request.presence_penalty",Bo="gen_ai.response.finish_reasons",Ho="gen_ai.prompt",zo="gen_ai.completion",Go="gen_ai.request.extra_query",Vo="gen_ai.request.extra_body",qo="gen_ai.serialized.name",Wo="gen_ai.serialized.signature",Ko="gen_ai.serialized.doc",Jo="gen_ai.response.id",Zo="gen_ai.response.service_tier",Yo="gen_ai.response.system_fingerprint",Xo="gen_ai.usage.input_token_details",Qo="gen_ai.usage.output_token_details",el="langsmith.trace.session_id",tl="langsmith.trace.session_name",rl="langsmith.span.kind",nl="langsmith.trace.name",il="langsmith.metadata",ji="langsmith.span.tags";var al="langsmith.request.streaming",sl="langsmith.request.headers";var Bi="langsmith.usage_metadata";var Cp=s((...t)=>fetch(...t),"DEFAULT_FETCH_IMPLEMENTATION"),kp,ol=Symbol.for("ls:fetch_implementation");var ll=s(()=>globalThis[ol]===void 0?!0:kp??!1,"_shouldStreamForGlobalFetchImplementation"),cl=s(t=>async(...e)=>{if(t||q("DEBUG")==="true"){let[n,i]=e;console.log(`\u2192 ${i?.method||"GET"} ${n}`)}let r=await(globalThis[ol]??Cp)(...e);return(t||q("DEBUG")==="true")&&console.log(`\u2190 ${r.status} ${r.statusText} ${r.url}`),r},"_getFetchImplementation");var kr=s(()=>q("PROJECT")??ae("LANGCHAIN_SESSION")??"default","getDefaultProjectName");var ul={};function se(t,e){let r=e?.code??t;ul[r]||(ul[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))}s(se,"warnOnce");var E=s(t=>BigInt(t),"n"),ml=E("0x9E3779B1"),hl=E("0x85EBCA77"),Op=E("0xC2B2AE3D"),lt=E("0x9E3779B185EBCA87"),St=E("0xC2B2AE3D27D4EB4F"),gl=E("0x165667B19E3779F9"),Vi=E("0x85EBCA77C2B2AE63"),Pp=E("0x27D4EB2F165667C5"),Rp=E("0x165667919E3779F9"),Mp=E("0x9FB21C651E98DF25");function Np(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}s(Np,"hexToBytes");var Ue=Np("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),er=(E(1)<<E(128))-E(1),D=(E(1)<<E(64))-E(1),mn=(E(1)<<E(32))-E(1),Ke=64,yl=Ke/8,Lp=8,dn=4;function W(t,e=0){return new Uint8Array(t.buffer,t.byteOffset+e,t.length-e)}s(W,"getView");function J(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getBigUint64(0,!0)}s(J,"readBigUInt64LE");function Qt(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getUint32(0,!0)}s(Qt,"readUInt32LE");function Hi(t,e=0){return t[e]}s(Hi,"readUInt8");var $p=s(t=>(t&E(255))<<E(56)|(t&E(65280))<<E(40)|(t&E(16711680))<<E(24)|(t&E(4278190080))<<E(8)|(t&E(0xff00000000))>>E(8)|(t&E(0xff0000000000))>>E(24)|(t&E(0xff000000000000))>>E(40)|(t&E(0xff00000000000000))>>E(56),"bswap64"),Dp=s(t=>(t=(t&E(65535))<<E(16)|(t&E(4294901760))>>E(16),t=(t&E(16711935))<<E(8)|(t&E(4278255360))>>E(8),t),"bswap32"),Up=s((t,e)=>(t&mn)*(e&mn)&D,"XXH_mult32to64"),tr=s(t=>{if(!t)throw new Error("Assert failed")},"assert");function Fp(t,e){return(t<<e|t>>E(32)-e)&mn}s(Fp,"rotl32");function _l(t,e,r){for(let n=0;n<yl;n++){let i=J(e,n*8),a=i^J(r,n*8);t[n^1]+=i,t[n]+=Up(a,a>>E(32))}return t}s(_l,"XXH3_accumulate_512");function dl(t,e,r,n){for(let i=0;i<n;i++)_l(t,W(e,i*Ke),W(r,i*8));return t}s(dl,"XXH3_accumulate");function jp(t,e){for(let r=0;r<yl;r++){let n=J(e,r*8),i=t[r];i=zi(i,E(47)),i^=n,i*=ml,t[r]=i&D}return t}s(jp,"XXH3_scrambleAcc");function pn(t,e){return bl(t[0]^J(e,0),t[1]^J(e,Lp))}s(pn,"XXH3_mix2Accs");function pl(t,e,r){let n=r;return n+=pn(t.slice(0),W(e,0*dn)),n+=pn(t.slice(2),W(e,4*dn)),n+=pn(t.slice(4),W(e,8*dn)),n+=pn(t.slice(6),W(e,12*dn)),Fe(n&D)}s(pl,"XXH3_mergeAccs");function Bp(t,e,r,n,i){let a=Math.floor((r.byteLength-Ke)/8),o=Ke*a,l=Math.floor((e.byteLength-1)/o);for(let c=0;c<l;c++)t=dl(t,W(e,c*o),r,a),t=i(t,W(r,r.byteLength-Ke));{let c=Math.floor((e.byteLength-1-o*l)/Ke);t=dl(t,W(e,l*o),r,c),t=n(t,W(e,e.byteLength-Ke),W(r,r.byteLength-Ke-7))}return t}s(Bp,"XXH3_hashLong");function Hp(t,e,r){let n=new BigUint64Array([Op,lt,St,gl,Vi,hl,Pp,ml]);tr(t.length>128),n=Bp(n,t,e,_l,jp),tr(n.length*8==64);{let i=pl(n,W(e,11),E(t.byteLength)*lt&D);return pl(n,W(e,e.byteLength-Ke-11),~(E(t.byteLength)*St)&D)<<E(64)|i}}s(Hp,"XXH3_hashLong_128b");function bl(t,e){let r=t*e&er;return r&D^r>>E(64)}s(bl,"XXH3_mul128_fold64");function fl(t,e,r){return bl((J(t,0)^J(e,0)+r)&D,(J(t,8)^J(e,8)-r)&D)}s(fl,"XXH3_mix16B");function fn(t,e,r,n,i){let a=t&D,o=t>>E(64)&D;return a+=fl(e,n,i),a^=J(r,0)+J(r,8),a&=D,o+=fl(r,W(n,16),i),o^=J(e,0)+J(e,8),o&=D,o<<E(64)|a}s(fn,"XXH3_mix32B");function Fe(t){return t^=t>>E(37),t*=Rp,t&=D,t^=t>>E(32),t}s(Fe,"XXH3_avalanche");function hn(t){return t^=t>>E(33),t*=St,t&=D,t^=t>>E(29),t*=gl,t&=D,t^=t>>E(32),t}s(hn,"XXH3_avalanche64");function zp(t,e,r){let n=t.byteLength;tr(n>0&&n<=3);let i=E(Hi(t,n-1))|E(n<<8)|E(Hi(t,0)<<16)|E(Hi(t,n>>1)<<24),a=(E(Qt(e,0))^E(Qt(e,4)))+r,o=(i^a)&D,l=(E(Qt(e,8))^E(Qt(e,12)))-r,c=(Fp(Dp(i),E(13))^l)&D;return(hn(c)&D)<<E(64)|hn(o)}s(zp,"XXH3_len_1to3_128b");function zi(t,e){return t^t>>e}s(zi,"xorshift64");function Gp(t,e,r){let n=t.byteLength;tr(n>=4&&n<=8);{let i=Qt(t,0),a=Qt(t,n-4),o=E(i)|E(a)<<E(32),l=(J(e,16)^J(e,24))+r&D,u=(o^l)*(lt+(E(n)<<E(2)))&er;return u+=(u&D)<<E(65),u&=er,u^=u>>E(67),zi(zi(u&D,E(35))*Mp&D,E(28))|Fe(u>>E(64))<<E(64)}}s(Gp,"XXH3_len_4to8_128b");function Vp(t,e,r){let n=t.byteLength;tr(n>=9&&n<=16);{let i=(J(e,32)^J(e,40))+r&D,a=(J(e,48)^J(e,56))-r&D,o=J(t),l=J(t,n-8),c=(o^l^i)*lt,u=(c&D)+(E(n-1)<<E(54));c=c&(er^D)|u,l^=a,c+=l+(l&mn)*(hl-E(1))<<E(64),c&=er,c^=$p(c>>E(64));let d=(c&D)*St;return d+=(c>>E(64))*St<<E(64),d&=er,Fe(d&D)|Fe(d>>E(64))<<E(64)}}s(Vp,"XXH3_len_9to16_128b");function qp(t,e){let r=t.byteLength;return tr(r<=16),r>8?Vp(t,Ue,e):r>=4?Gp(t,Ue,e):r>0?zp(t,Ue,e):hn(e^J(Ue,64)^J(Ue,72))|hn(e^J(Ue,80)^J(Ue,88))<<E(64)}s(qp,"XXH3_len_0to16_128b");function Gi(t){return~t+E(1)&D}s(Gi,"inv64");function Wp(t,e,r){let n=E(t.byteLength)*lt&D,i=E(t.byteLength-1)/E(32);for(;i>=0;){let l=Number(i);n=fn(n,W(t,16*l),W(t,t.byteLength-16*(l+1)),W(e,32*l),r),i--}let a=n+(n>>E(64))&D;a=Fe(a);let o=(n&D)*lt+(n>>E(64))*Vi+(E(t.byteLength)-r&D)*St;return o&=D,o=Gi(Fe(o)),a|o<<E(64)}s(Wp,"XXH3_len_17to128_128b");function Kp(t,e,r){let n=E(t.byteLength)*lt&D;for(let o=32;o<160;o+=32)n=fn(n,W(t,o-32),W(t,o-16),W(e,o-32),r);n=Fe(n&D)|Fe(n>>E(64))<<E(64);for(let o=160;o<=t.byteLength;o+=32)n=fn(n,W(t,o-32),W(t,o-16),W(e,3+o-160),r);n=fn(n,W(t,t.byteLength-16),W(t,t.byteLength-32),W(e,103),Gi(r));let i=n+(n>>E(64))&D;i=Fe(i);let a=(n&D)*lt+(n>>E(64))*Vi+(E(t.byteLength)-r&D)*St;return a&=D,a=Gi(Fe(a)),i|a<<E(64)}s(Kp,"XXH3_len_129to240_128b");function wl(t,e=E(0)){let r=t.byteLength;return r<=16?qp(t,e):r<=128?Wp(t,Ue,e):r<=240?Kp(t,Ue,e):Hp(t,Ue,e)}s(wl,"XXH3_128");function vl(t){let e=new Uint8Array(16),r=new DataView(e.buffer),n=t&D,i=t>>E(64);return r.setBigUint64(0,i,!1),r.setBigUint64(8,n,!1),e}s(vl,"xxh128ToBytes");var xl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function L(t,e){if(!xl.test(t)){let r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}s(L,"assertUuid");function gn(t){let e=typeof t=="string"?Date.parse(t):t;return Xt({msecs:e,seq:0})}s(gn,"uuid7FromTime");function El(t){if(!xl.test(t))return null;let e=t[14];return parseInt(e,16)}s(El,"getUuidVersion");function Jp(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}s(Jp,"uuidToBytes");function Zp(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)}`}s(Zp,"bytesToUuid");var Yp=new TextEncoder;function Xp(t){let e=Yp.encode(t),r=wl(e);return vl(r)}s(Xp,"_fastHash128");function rr(t,e){let r=`${t}:${e}`,n=Xp(r),i=new Uint8Array(16);if(El(t)===7){let o=Jp(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),Zp(i)}s(rr,"nonCryptographicUuid7Deterministic");var qi=s(t=>t!==void 0?t:!!["TRACING_V2","TRACING"].find(r=>q(r)==="true"),"isEnvTracingEnabled");var Ki=class{static{s(this,"MockAsyncLocalStorage")}getStore(){}run(e,r){return r()}},Wi=Symbol.for("ls:tracing_async_local_storage"),Qp=new Ki,Ji=class{static{s(this,"AsyncLocalStorageProvider")}getInstance(){return globalThis[Wi]??Qp}initializeGlobalInstance(e){globalThis[Wi]===void 0&&(globalThis[Wi]=e)}},ef=new Ji;function Zi(t=!1){let e=ef.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}s(Zi,"getCurrentRunTree");var ve=it(require("node:fs"),1),xe=it(require("node:fs/promises"),1),tf=it(require("node:path"),1);var Ne=tf;async function yn(t){await xe.mkdir(t,{recursive:!0})}s(yn,"mkdir");async function nr(t,e){let r=`${t}.tmp`;await xe.writeFile(r,e,{encoding:"utf8",mode:384}),await xe.rename(r,t)}s(nr,"writeFileAtomic");async function Sl(t){return xe.readdir(t)}s(Sl,"readdir");async function Tl(t){return xe.stat(t)}s(Tl,"stat");function ir(t){return ve.existsSync(t)}s(ir,"existsSync");function Al(t){ve.mkdirSync(t,{recursive:!0})}s(Al,"mkdirSync");function Il(t,e){ve.writeFileSync(t,e)}s(Il,"writeFileSync");function Cl(t,e){ve.renameSync(t,e)}s(Cl,"renameSync");function kl(t){ve.unlinkSync(t)}s(kl,"unlinkSync");function Tt(t){return ve.readFileSync(t,"utf-8")}s(Tt,"readFileSync");async function Ol(t){await xe.mkdir(t,{mode:448})}s(Ol,"mkdirExclusive");function Pl(t){try{return ve.statSync(t).mtimeMs}catch{return}}s(Pl,"statMtimeMs");async function _n(t){await xe.rm(t,{recursive:!0,force:!0})}s(_n,"rmRecursive");function rf(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}s(rf,"isStale");var bn=class{static{s(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 a=this.cache.keys().next().value;a!==void 0&&this.cache.delete(a)}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[a,o]of this.cache.entries())r[a]=o.value;let n=Ne.dirname(e);ir(n)||Al(n);let i=`${e}.tmp`;try{Il(i,JSON.stringify({entries:r},null,2)),Cl(i,e)}catch(a){throw ir(i)&&kl(i),a}}load(e){if(!ir(e))return 0;let r;try{let a=Tt(e);r=JSON.parse(a).entries??null}catch{return 0}if(!r)return 0;let n=0,i=Date.now();for(let[a,o]of Object.entries(r)){if(this.cache.size>=this.maxSize)break;let l={value:o,createdAt:i};this.cache.set(a,l),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())rf(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}},wn=new bn;function Rl(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}s(Rl,"isAbortError");var Or=s(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 Ee=class extends Error{static{s(this,"LangsmithError")}},ce=class t extends Ee{static{s(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 Je({message:n,cause:Or(r)});let a=r;return e===400?new It(e,a,n,i):e===401?new Ct(e,a,n,i):e===403?new kt(e,a,n,i):e===404?new Ot(e,a,n,i):e===409?new Pt(e,a,n,i):e===422?new Rt(e,a,n,i):e===429?new Mt(e,a,n,i):e>=500?new Nt(e,a,n,i):new t(e,a,n,i)}},ct=class extends ce{static{s(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Je=class extends ce{static{s(this,"APIConnectionError")}constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},At=class extends Je{static{s(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}},It=class extends ce{static{s(this,"BadRequestError")}},Ct=class extends ce{static{s(this,"AuthenticationError")}},kt=class extends ce{static{s(this,"PermissionDeniedError")}},Ot=class extends ce{static{s(this,"NotFoundError")}},Pt=class extends ce{static{s(this,"ConflictError")}},Rt=class extends ce{static{s(this,"UnprocessableEntityError")}},Mt=class extends ce{static{s(this,"RateLimitError")}},Nt=class extends ce{static{s(this,"InternalServerError")}};var vn="0.8.9";var je,af=s(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),sf=s(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),of=s(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),Ll=s(()=>typeof globalThis.Deno<"u","isDeno"),lf=s(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Ll(),"isNode"),Pr=s(()=>je||(typeof Bun<"u"?je="bun":af()?je="browser":lf()?je="node":sf()?je="webworker":of()?je="jsdom":Ll()?je="deno":je="other",je),"getEnv"),Xi;function xn(){if(Xi===void 0){let t=Pr(),e=uf();Xi={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:vn,...e}}return Xi}s(xn,"getRuntimeEnvironment");function ea(){let t=cf(),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}s(ea,"getLangSmithEnvVarsMetadata");function cf(){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}s(cf,"getLangSmithEnvironmentVariables");function ae(t){try{return typeof process<"u"?process.env?.[t]:void 0}catch{return}}s(ae,"getEnvironmentVariable");function q(t){return ae(`LANGSMITH_${t}`)||ae(`LANGCHAIN_${t}`)}s(q,"getLangSmithEnvironmentVariable");var Qi;function uf(){if(Qi!==void 0)return Qi;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=ae(r);n!==void 0&&(e[r]=n)}return Qi=e,e}s(uf,"getShas");function Ml(){return ae("OTEL_ENABLED")==="true"||q("OTEL_ENABLED")==="true"}s(Ml,"getOtelEnabled");var Nl=new Set(["langsmith","otel"]);function En(t){if(t!==void 0)return t;let e=q("TRACING_MODE");if(e!==void 0&&e!==""){let r=e.toLowerCase();if(!Nl.has(r))throw new Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(e)}. Must be one of: ${[...Nl].sort().join(", ")}`);return Ml()&&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 Ml()?"otel":"langsmith"}s(En,"resolveTracingMode");var na=class{static{s(this,"MockTracer")}constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&En()==="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()}},ia=class{static{s(this,"MockOTELTrace")}constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new na})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},aa=class{static{s(this,"MockOTELContext")}active(){return{}}with(e,r){return r()}},ta=Symbol.for("ls:otel_trace"),ra=Symbol.for("ls:otel_context"),$l=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),df=new ia,pf=new aa,sa=class{static{s(this,"OTELProvider")}getTraceInstance(){return globalThis[ta]??df}getContextInstance(){return globalThis[ra]??pf}initializeGlobalInstances(e){globalThis[ta]===void 0&&(globalThis[ta]=e.trace),globalThis[ra]===void 0&&(globalThis[ra]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[$l]=e}getDefaultOTLPTracerComponents(){return globalThis[$l]??void 0}},oa=new sa;function Sn(){return oa.getTraceInstance()}s(Sn,"getOTELTrace");function Dl(){return oa.getContextInstance()}s(Dl,"getOTELContext");function Ul(){return oa.getDefaultOTLPTracerComponents()}s(Ul,"getDefaultOTLPTracerComponents");var ff={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function mf(t){return ff[t]||t}s(mf,"getOperationName");function hf(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}s(hf,"isPrimitive");var Tn=class{static{s(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&&Sn().getSpan(n);if(i)try{return this.finishSpanSetup(i,r,e)}catch(a){console.error(`Failed to create span for run ${e.id}:`,a);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(rl,r.run_type);let l=mf(r.run_type||"chain");e.setAttribute(Mo,l)}"name"in r&&r.name&&e.setAttribute(nl,r.name),"session_id"in r&&r.session_id&&e.setAttribute(el,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(tl,r.session_name),this.setGenAiSystem(e,r);let i=this.extractModelName(r);i&&e.setAttribute($i,i),r.extra?.metadata?.usage_metadata&&typeof r.extra.metadata.usage_metadata=="object"&&e.setAttribute(Bi,JSON.stringify(r.extra.metadata.usage_metadata)),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(Di,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(Ui,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(Fi,r.total_tokens),this.setInvocationParameters(e,r);let a=r.extra?.metadata||{};for(let[l,c]of Object.entries(a))c!=null&&e.setAttribute(`${il}.${l}`,hf(c)?String(c):JSON.stringify(c));let o=r.tags;if(o&&Array.isArray(o)?e.setAttribute(ji,o.join(", ")):o&&e.setAttribute(ji,String(o)),"serialized"in r&&typeof r.serialized=="object"){let l=r.serialized;l.name&&e.setAttribute(qo,String(l.name)),l.signature&&e.setAttribute(Wo,String(l.signature)),l.doc&&e.setAttribute(Ko,String(l.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,r){let n="langchain",i=this.extractModelName(r);if(i){let a=i.toLowerCase();a.includes("anthropic")||a.startsWith("claude")?n="anthropic":a.includes("bedrock")?n="aws.bedrock":a.includes("azure")&&a.includes("openai")?n="az.ai.openai":a.includes("azure")&&a.includes("inference")?n="az.ai.inference":a.includes("cohere")?n="cohere":a.includes("deepseek")?n="deepseek":a.includes("gemini")?n="gemini":a.includes("groq")?n="groq":a.includes("watson")||a.includes("ibm")?n="ibm.watsonx.ai":a.includes("mistral")?n="mistral_ai":a.includes("gpt")||a.includes("openai")?n="openai":a.includes("perplexity")||a.includes("sonar")?n="perplexity":a.includes("vertex")?n="vertex_ai":(a.includes("xai")||a.includes("grok"))&&(n="xai")}e.setAttribute(No,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($o,n.max_tokens),n.temperature!==void 0&&e.setAttribute(Do,n.temperature),n.top_p!==void 0&&e.setAttribute(Uo,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(Fo,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(jo,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($i,n.model),n.stream!==void 0&&e.setAttribute(al,n.stream),n.extra_headers&&e.setAttribute(sl,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(Go,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(Vo,JSON.stringify(n.extra_body))),e.setAttribute(Ho,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(Di,i[0]),e.setAttribute(Ui,i[1]),e.setAttribute(Fi,i[0]+i[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(Lo,String(n.model)),n.id&&e.setAttribute(Jo,n.id),n.choices&&Array.isArray(n.choices)){let a=n.choices.map(o=>o.finish_reason).filter(o=>o).map(String);a.length>0&&e.setAttribute(Bo,a.join(", "))}if(n.service_tier&&e.setAttribute(Zo,n.service_tier),n.system_fingerprint&&e.setAttribute(Yo,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let a=n.usage_metadata;e.setAttribute(Bi,JSON.stringify(a)),a.input_token_details&&e.setAttribute(Xo,JSON.stringify(a.input_token_details)),a.output_token_details&&e.setAttribute(Qo,JSON.stringify(a.output_token_details))}}e.setAttribute(zo,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 l=e[o];if(!(!l||typeof l!="object")&&(r=this.extractUnifiedRunTokens(l.usage_metadata),r||l.lc===1&&l.kwargs&&typeof l.kwargs=="object"&&(r=this.extractUnifiedRunTokens(l.kwargs.usage_metadata),r)))return r}let i=e.generations||[];if(!Array.isArray(i))return null;let a=Array.isArray(i[0])?i.flat():i;for(let o of a)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 gf=Object.prototype.toString,yf=s(t=>gf.call(t)==="[object Error]","isError"),_f=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 la(t){if(!(t&&yf(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:_f.has(r)}s(la,"isNetworkError");function bf(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.")}s(bf,"validateRetries");function An(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}.`)}}s(An,"validateNumberOption");var ca=class extends Error{static{s(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 wf(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}s(wf,"calculateDelay");function Fl(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}s(Fl,"calculateRemainingTime");async function vf({error:t,attemptNumber:e,retriesConsumed:r,startTime:n,options:i}){let a=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(a instanceof ca)throw a.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-r):i.retries,l=i.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:a,attemptNumber:e,retriesLeft:o,retriesConsumed:r});if(await i.onFailedAttempt(c),Fl(n,l)<=0)throw a;let u=await i.shouldConsumeRetry(c),d=Fl(n,l);if(d<=0||o<=0)throw a;if(a instanceof TypeError&&!la(a)){if(u)throw a;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw a;if(!u)return i.signal?.throwIfAborted(),!1;let p=wf(r,i),h=Math.min(p,d);return h>0&&await new Promise((g,b)=>{let v=s(()=>{clearTimeout(P),i.signal?.removeEventListener("abort",v),b(i.signal.reason)},"onAbort"),P=setTimeout(()=>{i.signal?.removeEventListener("abort",v),g()},h);i.unref&&P.unref?.(),i.signal?.addEventListener("abort",v,{once:!0})}),i.signal?.throwIfAborted(),!0}s(vf,"onAttemptFailure");async function ua(t,e={}){if(e={...e},bf(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,An("factor",e.factor,{min:0,allowInfinity:!1}),An("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),An("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),An("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 a=await t(r);return e.signal?.throwIfAborted(),a}catch(a){await vf({error:a,attemptNumber:r,retriesConsumed:n,startTime:i,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}s(ua,"pRetry");var In=it(cn(),1),jl="default"in In.default?In.default.default:In.default;var xf=[408,425,429,500,502,503,504],Rr=class{static{s(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 jl({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 a=this.onFailedResponseHook,o=this.queue.add(()=>ua(()=>r(...n).catch(l=>{throw l instanceof Error?l:new Error(l)}),{async onFailedAttempt({error:l}){if(typeof l!="object"||l==null)throw l;let c="message"in l&&typeof l.message=="string"?l.message:void 0;if(c?.startsWith("Cancel")||c?.startsWith("TimeoutError")||c?.startsWith("AbortError")||"name"in l&&l.name==="TimeoutError"||"code"in l&&l.code==="ECONNABORTED")throw l;let u="response"in l?l.response:void 0;if(a&&await a(u))return;let d=u?.status??("status"in l?l.status:void 0);if(d!=null&&(typeof d=="number"||typeof d=="string")&&!xf.includes(+d))throw l},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return i>0&&(o=o.finally(()=>{this.queueSizeBytes-=i})),e.signal?Promise.race([o,new Promise((l,c)=>{e.signal?.addEventListener("abort",()=>{c(new Error("AbortError"))})})]):o}};function da(t){return typeof t?._getType=="function"}s(da,"isLangChainMessage");function pa(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}s(pa,"convertLangChainMessageToExample");var fa=s(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 Ef=/^[a-z][a-z0-9+.-]*:/i,Bl=s(t=>Ef.test(t),"isAbsoluteURL"),me=s(t=>(me=Array.isArray,me(t)),"isArray"),ma=me;function ar(t){return typeof t!="object"?{}:t??{}}s(ar,"maybeObj");function ha(t){if(!t)return!0;for(let e in t)return!1;return!0}s(ha,"isEmptyObj");function Hl(t,e){return Object.prototype.hasOwnProperty.call(t,e)}s(Hl,"hasOwn");var zl=s((t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Ee(`${t} must be an integer`);if(e<0)throw new Ee(`${t} must be a positive integer`);return e},"validatePositiveInteger");var Gl=s(t=>{try{return JSON.parse(t)}catch{return}},"safeJSON");var Vl=s(t=>new Promise(e=>setTimeout(e,t)),"sleep");var dt="0.0.1";function Sf(){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"}s(Sf,"getDetectedPlatform");var Tf=s(()=>{let t=Sf();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":Wl(Deno.build.os),"X-Stainless-Arch":ql(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":dt,"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":dt,"X-Stainless-OS":Wl(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ql(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Af();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"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":dt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function Af(){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,a=n[2]||0,o=n[3]||0;return{browser:e,version:`${i}.${a}.${o}`}}}return null}s(Af,"getBrowserInfo");var ql=s(t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown","normalizeArch"),Wl=s(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"),If,Kl=s(()=>If??=Tf(),"getPlatformHeaders");function Jl(){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`")}s(Jl,"getDefaultFetch");function Cf(...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)}s(Cf,"makeReadableStream");function ga(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Cf({start(){},async pull(r){let{done:n,value:i}=await e.next();n?r.close():r.enqueue(i)},async cancel(){await e.return?.()}})}s(ga,"ReadableStreamFrom");async function Zl(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}s(Zl,"CancelReadableStream");var Yl=s(({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");var ya="RFC3986",_a=s(t=>String(t),"default_formatter"),ba={RFC1738:s(t=>String(t).replace(/%20/g,"+"),"RFC1738"),RFC3986:_a},Xl="RFC1738";var Cn=s((t,e)=>(Cn=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Cn(t,e)),"has"),Be=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var wa=1024,Ql=s((t,e,r,n,i)=>{if(t.length===0)return t;let a=t;if(typeof t=="symbol"?a=Symbol.prototype.toString.call(t):typeof t!="string"&&(a=String(t)),r==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let o="";for(let l=0;l<a.length;l+=wa){let c=a.length>=wa?a.slice(l,l+wa):a,u=[];for(let d=0;d<c.length;++d){let p=c.charCodeAt(d);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||i===Xl&&(p===40||p===41)){u[u.length]=c.charAt(d);continue}if(p<128){u[u.length]=Be[p];continue}if(p<2048){u[u.length]=Be[192|p>>6]+Be[128|p&63];continue}if(p<55296||p>=57344){u[u.length]=Be[224|p>>12]+Be[128|p>>6&63]+Be[128|p&63];continue}d+=1,p=65536+((p&1023)<<10|c.charCodeAt(d)&1023),u[u.length]=Be[240|p>>18]+Be[128|p>>12&63]+Be[128|p>>6&63]+Be[128|p&63]}o+=u.join("")}return o},"encode");function ec(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}s(ec,"is_buffer");function va(t,e){if(me(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}s(va,"maybe_map");var tc={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},rc=s(function(t,e){Array.prototype.push.apply(t,me(e)?e:[e])},"push_to_array"),Pf,re={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ql,encodeValuesOnly:!1,format:ya,formatter:_a,indices:!1,serializeDate(t){return(Pf??=Function.prototype.call.bind(Date.prototype.toISOString))(t)},skipNulls:!1,strictNullHandling:!1};function Rf(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}s(Rf,"is_non_nullish_primitive");var xa={};function nc(t,e,r,n,i,a,o,l,c,u,d,p,h,g,b,v,P,I){let S=t,A=I,R=0,$=!1;for(;(A=A.get(xa))!==void 0&&!$;){let B=A.get(t);if(R+=1,typeof B<"u"){if(B===R)throw new RangeError("Cyclic object value");$=!0}typeof A.get(xa)>"u"&&(R=0)}if(typeof u=="function"?S=u(e,S):S instanceof Date?S=h?.(S):r==="comma"&&me(S)&&(S=va(S,function(B){return B instanceof Date?h?.(B):B})),S===null){if(a)return c&&!v?c(e,re.encoder,P,"key",g):e;S=""}if(Rf(S)||ec(S)){if(c){let B=v?e:c(e,re.encoder,P,"key",g);return[b?.(B)+"="+b?.(c(S,re.encoder,P,"value",g))]}return[b?.(e)+"="+b?.(String(S))]}let N=[];if(typeof S>"u")return N;let j;if(r==="comma"&&me(S))v&&c&&(S=va(S,c)),j=[{value:S.length>0?S.join(",")||null:void 0}];else if(me(u))j=u;else{let B=Object.keys(S);j=d?B.sort(d):B}let y=l?String(e).replace(/\./g,"%2E"):String(e),K=n&&me(S)&&S.length===1?y+"[]":y;if(i&&me(S)&&S.length===0)return K+"[]";for(let B=0;B<j.length;++B){let F=j[B],de=typeof F=="object"&&typeof F.value<"u"?F.value:S[F];if(o&&de===null)continue;let tt=p&&l?F.replace(/\./g,"%2E"):F,rt=me(S)?typeof r=="function"?r(K,tt):K:K+(p?"."+tt:"["+tt+"]");I.set(t,R);let vr=new WeakMap;vr.set(xa,I),rc(N,nc(de,rt,r,n,i,a,o,l,r==="comma"&&v&&me(S)?null:c,u,d,p,h,g,b,v,P,vr))}return N}s(nc,"inner_stringify");function Mf(t=re){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||re.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=ya;if(typeof t.format<"u"){if(!Cn(ba,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=ba[r],i=re.filter;(typeof t.filter=="function"||me(t.filter))&&(i=t.filter);let a;if(t.arrayFormat&&t.arrayFormat in tc?a=t.arrayFormat:"indices"in t?a=t.indices?"indices":"repeat":a=re.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:re.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:re.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:re.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:re.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?re.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:re.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:re.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:re.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:re.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:re.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:re.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:re.strictNullHandling}}s(Mf,"normalize_stringify_options");function ic(t,e={}){let r=t,n=Mf(e),i,a;typeof n.filter=="function"?(a=n.filter,r=a("",r)):me(n.filter)&&(a=n.filter,i=a);let o=[];if(typeof r!="object"||r===null)return"";let l=tc[n.arrayFormat],c=l==="comma"&&n.commaRoundTrip;i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);let u=new WeakMap;for(let h=0;h<i.length;++h){let g=i[h];n.skipNulls&&r[g]===null||rc(o,nc(r[g],g,l,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,u))}let d=o.join(n.delimiter),p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),d.length>0?p+d:""}s(ic,"stringify");function ac(t){return ic(t,{arrayFormat:"repeat"})}s(ac,"stringifyQuery");var On={off:0,error:200,warn:300,info:400,debug:500},Ea=s((t,e,r)=>{if(t){if(Hl(On,t))return t;be(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(On))}`)}},"parseLogLevel");function Mr(){}s(Mr,"noop");function kn(t,e,r){return!e||On[t]>On[r]?Mr:e[t].bind(e)}s(kn,"makeLogFn");var Lf={error:Mr,warn:Mr,info:Mr,debug:Mr},sc=new WeakMap;function be(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Lf;let n=sc.get(e);if(n&&n[0]===r)return n[1];let i={error:kn("error",e,r),warn:kn("warn",e,r),info:kn("info",e,r),debug:kn("debug",e,r)};return sc.set(e,[r,i]),i}s(be,"loggerFor");var Ze=s(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 Pn(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:a}=e,o=await(async()=>{if(r.status===204)return null;if(e.options.__binaryResponse)return r;let c=r.headers.get("content-type")?.split(";")[0]?.trim();return c?.includes("application/json")||c?.endsWith("+json")?r.headers.get("content-length")==="0"?void 0:await r.json():await r.text()})();return be(t).debug(`[${n}] response parsed`,Ze({retryOfRequestLogID:i,url:r.url,status:r.status,body:o,durationMs:Date.now()-a})),o}s(Pn,"defaultParseResponse");var $f=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},oc=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)},Nr,Lt=class t extends Promise{static{s(this,"APIPromise")}constructor(e,r,n=Pn){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}),Nr.set(this,void 0),$f(this,Nr,e,"f")}_thenUnwrap(e){return new t(oc(this,Nr,"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(oc(this,Nr,"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)}};Nr=new WeakMap;var Df=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},Uf=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)},Rn,$t=class{static{s(this,"AbstractPage")}constructor(e,r,n,i){Rn.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}),Df(this,Rn,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 Ee("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Uf(this,Rn,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Rn=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Lr=class extends Lt{static{s(this,"PagePromise")}constructor(e,r,n){super(e,r,async(i,a)=>new n(i,a.response,await Pn(i,a),a.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},Mn=class extends $t{static{s(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:{...ar(this.options.query),offset:n}}}},Nn=class extends $t{static{s(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:{...ar(this.options.query),offset:n}}}};var Ln=class extends $t{static{s(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:{...ar(this.options.query),offset:n}}}};var He=class extends $t{static{s(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:{...ar(this.options.body),cursor:e}}:null}},sr=class extends $t{static{s(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:{...ar(this.options.query),cursor:e}}:null}};var Sa=s(()=>{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 $n(t,e,r){return Sa(),new File(t,e??"unknown_file",r)}s($n,"makeFile");function lc(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}s(lc,"getName");var cc=s(t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function","isAsyncIterable");var uc=s(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"),jf=s(t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&uc(t),"isFileLike"),Bf=s(t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function","isResponseLike");async function Dn(t,e,r){if(Sa(),t=await t,jf(t))return t instanceof File?t:$n([await t.arrayBuffer()],t.name);if(Bf(t)){let i=await t.blob();return e||=new URL(t.url).pathname.split(/[\\/]/).pop(),$n(await Ta(i),e,r)}let n=await Ta(t);if(e||=lc(t),!r?.type){let i=n.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof i=="string"&&(r={...r,type:i})}return $n(n,e,r)}s(Dn,"toFile");async function Ta(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(uc(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(cc(t))for await(let r of t)e.push(...await Ta(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${Hf(t)}`)}return e}s(Ta,"getBytes");function Hf(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}s(Hf,"propsForError");var U=class{static{s(this,"APIResource")}constructor(e){Object.defineProperty(this,"_client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._client=e}};function pc(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}s(pc,"encodeURIPath");var dc=Object.freeze(Object.create(null)),Gf=s((t=pc)=>s(function(r,...n){if(r.length===1)return r[0];let i=!1,a=[],o=r.reduce((d,p,h)=>{/[?#]/.test(p)&&(i=!0);let g=n[h],b=(i?encodeURIComponent:t)(""+g);return h!==n.length&&(g==null||typeof g=="object"&&g.toString===Object.getPrototypeOf(Object.getPrototypeOf(g.hasOwnProperty??dc)??dc)?.toString)&&(b=g+"",a.push({start:d.length+p.length,length:b.length,error:`Value of type ${Object.prototype.toString.call(g).slice(8,-1)} is not a valid path parameter`})),d+p+(h===n.length?"":b)},""),l=o.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=c.exec(l))!==null;)a.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(a.sort((d,p)=>d.start-p.start),a.length>0){let d=0,p=a.reduce((h,g)=>{let b=" ".repeat(g.start-d),v="^".repeat(g.length);return d=g.start+g.length,h+b+v},"");throw new Ee(`Path parameters result in path with invalid segments:
10
+ ${a.map(h=>h.error).join(`
11
+ `)}
12
+ ${o}
13
+ ${p}`)}return o},"path"),"createPathTagFunction"),O=Gf(pc);var or=class extends U{static{s(this,"Items")}create(e,r,n){let{extend_trace_retention:i,...a}=r;return this._client.post(O`/api/v1/platform/annotation-queues/${e}/items`,{query:{extend_trace_retention:i},body:a,...n})}update(e,r,n){let{queue_id:i,...a}=r;return this._client.patch(O`/api/v1/platform/annotation-queues/${i}/items/${e}`,{body:a,...n})}list(e,r,n){return this._client.getAPIList(O`/api/v1/platform/annotation-queues/${e}/items`,sr,{query:r,...n})}createStatus(e,r,n){return this._client.post(O`/api/v1/platform/annotation-queues/items/${e}/status`,{body:r,...n})}deleteAll(e,r,n){return this._client.post(O`/api/v1/platform/annotation-queues/${e}/items/delete`,{body:r,...n})}retrieveCount(e,r,n){return this._client.get(O`/api/v1/platform/annotation-queues/${e}/items/count`,{query:r,...n})}retrievePlacement(e,r,n){let{queue_id:i}=r;return this._client.get(O`/api/v1/platform/annotation-queues/${i}/items/${e}/placement`,n)}};var lr=class extends U{static{s(this,"Runs")}create(e,r,n){let{body:i,extend_trace_retention:a}=r;return this._client.post(O`/api/v1/annotation-queues/${e}/runs`,{query:{extend_trace_retention:a},body:i,...n})}update(e,r,n){let{queue_id:i,...a}=r;return this._client.patch(O`/api/v1/annotation-queues/${i}/runs/${e}`,{body:a,...n})}list(e,r={},n){return this._client.get(O`/api/v1/annotation-queues/${e}/runs`,{query:r,...n})}createByKey(e,r,n){let{body:i,extend_trace_retention:a}=r;return this._client.post(O`/api/v1/annotation-queues/${e}/runs/by-key`,{query:{extend_trace_retention:a},body:i,...n})}deleteAll(e,r,n){return this._client.post(O`/api/v1/annotation-queues/${e}/runs/delete`,{body:r,...n})}deleteQueue(e,r,n){let{queue_id:i}=r;return this._client.delete(O`/api/v1/annotation-queues/${i}/runs/${e}`,n)}};var Ye=class extends U{static{s(this,"AnnotationQueues")}constructor(){super(...arguments),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new lr(this._client)}),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:new or(this._client)})}retrieve(e,r){return this._client.get(O`/api/v1/annotation-queues/${e}`,r)}update(e,r,n){return this._client.patch(O`/api/v1/annotation-queues/${e}`,{body:r,...n})}delete(e,r){return this._client.delete(O`/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(O`/api/v1/annotation-queues/status/${e}`,{body:r,...n})}export(e,r,n){return this._client.post(O`/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",Mn,{query:e,...r})}retrieveQueues(e,r){return this._client.get(O`/api/v1/annotation-queues/${e}/queues`,r)}retrieveRun(e,r,n){let{queue_id:i,...a}=r;return this._client.get(O`/api/v1/annotation-queues/${i}/run/${e}`,{query:a,...n})}retrieveSize(e,r={},n){return this._client.get(O`/api/v1/annotation-queues/${e}/size`,{query:r,...n})}retrieveTotalArchived(e,r={},n){return this._client.get(O`/api/v1/annotation-queues/${e}/total_archived`,{query:r,...n})}retrieveTotalSize(e,r){return this._client.get(O`/api/v1/annotation-queues/${e}/total_size`,r)}};Ye.Runs=lr;Ye.Items=or;var cr=class extends U{static{s(this,"ExperimentRuns")}query(e,r,n){return this._client.getAPIList(O`/api/v2/datasets/${e}/experiment-runs`,He,{body:r,method:"post",...n})}};var pt=class extends U{static{s(this,"Datasets")}constructor(){super(...arguments),Object.defineProperty(this,"experimentRuns",{enumerable:!0,configurable:!0,writable:!0,value:new cr(this._client)})}};pt.ExperimentRuns=cr;var Dt=class extends U{static{s(this,"Info")}list(e){return this._client.get("/api/v1/info",e)}};var Ut=class extends U{static{s(this,"Issues")}retrieve(e,r){return this._client.get(O`/api/v1/platform/issues/${e}`,r)}list(e={},r){return this._client.getAPIList("/api/v1/platform/issues",Nn,{query:e,...r})}};var fc=Symbol("brand.privateNullableHeaders");function*Kf(t){if(!t)return;if(fc in t){let{values:n,nulls:i}=t;yield*n.entries();for(let a of i)yield[a,null];return}let e=!1,r;t instanceof Headers?r=t.entries():ma(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 a=ma(n[1])?n[1]:[n[1]],o=!1;for(let l of a)l!==void 0&&(e&&!o&&(o=!0,yield[i,null]),yield[i,l])}}s(Kf,"iterateHeaders");var Z=s(t=>{let e=new Headers,r=new Set;for(let n of t){let i=new Set;for(let[a,o]of Kf(n)){let l=a.toLowerCase();i.has(l)||(e.delete(a),i.add(l)),o===null?(e.delete(a),r.add(l)):(e.append(a,o),r.delete(l))}}return{[fc]:!0,values:e,nulls:r}},"buildHeaders");var Ft=class extends U{static{s(this,"OnlineEvaluators")}create(e,r){return this._client.post("/api/v1/platform/evaluators",{body:e,...r})}retrieve(e,r){return this._client.get(O`/api/v1/platform/evaluators/${e}`,r)}update(e,r,n){return this._client.patch(O`/api/v1/platform/evaluators/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/api/v1/platform/evaluators",Ln,{query:e,...r})}delete(e,r={},n){let{delete_run_rules:i}=r??{};return this._client.delete(O`/api/v1/platform/evaluators/${e}`,{query:{delete_run_rules:i},...n,headers:Z([{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 ur=class extends U{static{s(this,"Runs")}retrieve(e,r,n){let{share_token:i,Accept:a,...o}=r;return this._client.get(O`/api/v2/public/${i}/run/${e}`,{query:o,...n,headers:Z([{...a!=null?{Accept:a}:void 0},n?.headers])})}query(e,r,n){let{Accept:i,...a}=r;return this._client.post(O`/api/v2/public/${e}/runs/query`,{body:a,...n,headers:Z([{...i!=null?{Accept:i}:void 0},n?.headers])})}};var ft=class extends U{static{s(this,"Public")}constructor(){super(...arguments),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new ur(this._client)})}};ft.Runs=ur;var dr=class extends U{static{s(this,"Share")}create(e,r,n){return this._client.post(O`/api/v2/runs/${e}/share`,{body:r,...n})}delete(e,r,n){return this._client.delete(O`/api/v2/runs/${e}/share`,{body:r,...n,headers:Z([{Accept:"*/*"},n?.headers])})}};var mt=class extends U{static{s(this,"Runs")}constructor(){super(...arguments),Object.defineProperty(this,"share",{enumerable:!0,configurable:!0,writable:!0,value:new dr(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(O`/api/v2/runs/${e}/url`,{query:r,...n})}queryV2(e,r){let{Accept:n,...i}=e;return this._client.getAPIList("/api/v2/runs/query",He,{body:i,method:"post",...r,headers:Z([{...n!=null?{Accept:n}:void 0},r?.headers])})}retrieveV2(e,r,n){let{Accept:i,...a}=r;return this._client.get(O`/api/v2/runs/${e}`,{query:a,...n,headers:Z([{...i!=null?{Accept:i}:void 0},n?.headers])})}};mt.Share=dr;var pr=class extends U{static{s(this,"Boxes")}create(e,r){return this._client.post("/api/v2/sandboxes/boxes",{body:e,...r})}retrieve(e,r){return this._client.get(O`/api/v2/sandboxes/boxes/${e}`,r)}update(e,r,n){return this._client.patch(O`/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(O`/api/v2/sandboxes/boxes/${e}`,{...r,headers:Z([{Accept:"*/*"},r?.headers])})}createSnapshot(e,r,n){return this._client.post(O`/api/v2/sandboxes/boxes/${e}/snapshot`,{body:r,...n})}generateServiceURL(e,r,n){return this._client.post(O`/api/v2/sandboxes/boxes/${e}/service-url`,{body:r,...n})}getStatus(e,r){return this._client.get(O`/api/v2/sandboxes/boxes/${e}/status`,r)}start(e,r){return this._client.post(O`/api/v2/sandboxes/boxes/${e}/start`,r)}stop(e,r){return this._client.post(O`/api/v2/sandboxes/boxes/${e}/stop`,{...r,headers:Z([{Accept:"*/*"},r?.headers])})}};var fr=class extends U{static{s(this,"Registries")}create(e,r){return this._client.post("/api/v2/sandboxes/registries",{body:e,...r})}retrieve(e,r){return this._client.get(O`/api/v2/sandboxes/registries/${e}`,r)}update(e,r,n){return this._client.patch(O`/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(O`/api/v2/sandboxes/registries/${e}`,{...r,headers:Z([{Accept:"*/*"},r?.headers])})}};var mr=class extends U{static{s(this,"Snapshots")}create(e,r){return this._client.post("/api/v2/sandboxes/snapshots",{body:e,...r})}retrieve(e,r){return this._client.get(O`/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(O`/api/v2/sandboxes/snapshots/${e}`,{...r,headers:Z([{Accept:"*/*"},r?.headers])})}};var ze=class extends U{static{s(this,"Sandboxes")}constructor(){super(...arguments),Object.defineProperty(this,"boxes",{enumerable:!0,configurable:!0,writable:!0,value:new pr(this._client)}),Object.defineProperty(this,"registries",{enumerable:!0,configurable:!0,writable:!0,value:new fr(this._client)}),Object.defineProperty(this,"snapshots",{enumerable:!0,configurable:!0,writable:!0,value:new mr(this._client)})}};ze.Boxes=pr;ze.Registries=fr;ze.Snapshots=mr;var jt=class extends U{static{s(this,"Threads")}listTraces(e,r,n){return this._client.getAPIList(O`/api/v2/threads/${e}/traces`,sr,{query:r,...n})}query(e,r){return this._client.getAPIList("/api/v2/threads/query",He,{body:e,method:"post",...r})}stats(e,r,n){return this._client.get(O`/api/v2/threads/${e}/stats`,{query:r,...n})}};var Bt=class extends U{static{s(this,"Traces")}listRuns(e,r,n){let{Accept:i,...a}=r;return this._client.get(O`/api/v2/traces/${e}/runs`,{query:a,...n,headers:Z([{...i!=null?{Accept:i}:void 0},n?.headers])})}query(e,r){return this._client.getAPIList("/api/v2/traces/query",He,{body:e,method:"post",...r})}};var hr=s(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 tm=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},mc=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)},Aa,Ia,Un,hc,z=class{static{s(this,"Langsmith")}constructor({baseURL:e=hr("LANGCHAIN_BASE_URL"),apiKey:r=hr("LANGSMITH_API_KEY")??null,tenantID:n=hr("LANGSMITH_TENANT_ID")??null,...i}={}){Aa.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}),Un.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 pt(this)}),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new mt(this)}),Object.defineProperty(this,"threads",{enumerable:!0,configurable:!0,writable:!0,value:new jt(this)}),Object.defineProperty(this,"traces",{enumerable:!0,configurable:!0,writable:!0,value:new Bt(this)}),Object.defineProperty(this,"onlineEvaluators",{enumerable:!0,configurable:!0,writable:!0,value:new Ft(this)}),Object.defineProperty(this,"public",{enumerable:!0,configurable:!0,writable:!0,value:new ft(this)}),Object.defineProperty(this,"annotationQueues",{enumerable:!0,configurable:!0,writable:!0,value:new Ye(this)}),Object.defineProperty(this,"info",{enumerable:!0,configurable:!0,writable:!0,value:new Dt(this)}),Object.defineProperty(this,"issues",{enumerable:!0,configurable:!0,writable:!0,value:new Ut(this)}),Object.defineProperty(this,"sandboxes",{enumerable:!0,configurable:!0,writable:!0,value:new ze(this)});let a={apiKey:r,tenantID:n,...i,baseURL:e||"https://api.smith.langchain.com/"};this.baseURL=a.baseURL,this.timeout=a.timeout??Ia.DEFAULT_TIMEOUT,this.logger=a.logger??console;let o="warn";this.logLevel=o,this.logLevel=Ea(a.logLevel,"ClientOptions.logLevel",this)??Ea(hr("LANGCHAIN_LOG"),"process.env['LANGCHAIN_LOG']",this)??o,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Jl(),tm(this,Un,Yl,"f");let l=hr("LANGCHAIN_CUSTOM_HEADERS");if(l){let c={};for(let u of l.split(`
14
+ `)){let d=u.indexOf(":");d>=0&&(c[u.substring(0,d).trim()]=u.substring(d+1).trim())}a.defaultHeaders={...c,...a.defaultHeaders}}this._options=a,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 Z([await this.apiKeyAuth(e),await this.tenantIDAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return Z([{"X-API-Key":this.apiKey}])}async tenantIDAuth(e){if(this.tenantID!=null)return Z([{"X-Tenant-Id":this.tenantID}])}stringifyQuery(e){return ac(e)}getUserAgent(){return`${this.constructor.name}/JS ${dt}`}defaultIdempotencyKey(){return`stainless-node-retry-${fa()}`}makeStatusError(e,r,n,i){return ce.generate(e,r,n,i)}buildURL(e,r,n){let i=!mc(this,Aa,"m",hc).call(this)&&n||this.baseURL,a=Bl(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),l=Object.fromEntries(a.searchParams);return(!ha(o)||!ha(l))&&(r={...l,...o,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(a.search=this.stringifyQuery(r)),a.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 Lt(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let i=await e,a=i.maxRetries??this.maxRetries;r==null&&(r=a),await this.prepareOptions(i);let{req:o,url:l,timeout:c}=await this.buildRequest(i,{retryCount:a-r});await this.prepareRequest(o,{url:l,options:i});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=n===void 0?"":`, retryOf: ${n}`,p=Date.now();if(be(this).debug(`[${u}] sending request`,Ze({retryOfRequestLogID:n,method:i.method,url:l,options:i,headers:o.headers})),i.signal?.aborted)throw new ct;let h=new AbortController,g=await this.fetchWithTimeout(l,o,c,h).catch(Or),b=Date.now();if(g instanceof globalThis.Error){let P=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new ct;let I=Rl(g)||/timed? ?out/i.test(String(g)+("cause"in g?String(g.cause):""));if(r)return be(this).info(`[${u}] connection ${I?"timed out":"failed"} - ${P}`),be(this).debug(`[${u}] connection ${I?"timed out":"failed"} (${P})`,Ze({retryOfRequestLogID:n,url:l,durationMs:b-p,message:g.message})),this.retryRequest(i,r,n??u);throw be(this).info(`[${u}] connection ${I?"timed out":"failed"} - error; no more retries left`),be(this).debug(`[${u}] connection ${I?"timed out":"failed"} (error; no more retries left)`,Ze({retryOfRequestLogID:n,url:l,durationMs:b-p,message:g.message})),I?new At:new Je({cause:g})}let v=`[${u}${d}] ${o.method} ${l} ${g.ok?"succeeded":"failed"} with status ${g.status} in ${b-p}ms`;if(!g.ok){let P=await this.shouldRetry(g);if(r&&P){let N=`retrying, ${r} attempts remaining`;return await Zl(g.body),be(this).info(`${v} - ${N}`),be(this).debug(`[${u}] response error (${N})`,Ze({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:b-p})),this.retryRequest(i,r,n??u,g.headers)}let I=P?"error; no more retries left":"error; not retryable";be(this).info(`${v} - ${I}`);let S=await g.text().catch(N=>Or(N).message),A=Gl(S),R=A?void 0:S;throw be(this).debug(`[${u}] response error (${I})`,Ze({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,message:R,durationMs:Date.now()-p})),this.makeStatusError(g.status,A,R,g.headers)}return be(this).info(v),be(this).debug(`[${u}] response start`,Ze({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:b-p})),{response:g,options:i,controller:h,requestLogID:u,retryOfRequestLogID:n,startTime:p}}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 Lr(this,n,e)}async fetchWithTimeout(e,r,n,i){let{signal:a,method:o,...l}=r||{},c=this._makeAbort(i);a&&a.addEventListener("abort",c,{once:!0});let u=setTimeout(c,n),d=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,p={signal:i.signal,...d?{duplex:"half"}:{},method:"GET",...l};o&&(p.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,p)}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 a,o=i?.get("retry-after-ms");if(o){let c=parseFloat(o);Number.isNaN(c)||(a=c)}let l=i?.get("retry-after");if(l&&!a){let c=parseFloat(l);Number.isNaN(c)?a=Date.parse(l)-Date.now():a=c*1e3}if(a===void 0){let c=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(r,c)}return await Vl(a),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let a=r-e,o=Math.min(.5*Math.pow(2,a),16),l=1-Math.random()*.25;return o*l*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:i,path:a,query:o,defaultBaseURL:l}=n,c=this.buildURL(a,o,l);"timeout"in n&&zl("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:u,body:d}=this.buildBody({options:n}),p=await this.buildHeaders({options:e,method:i,bodyHeaders:u,retryCount:r});return{req:{method:i,headers:p,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let a={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);let o=Z([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Kl()},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=Z([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:ga(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)}:mc(this,Un,"f").call(this,{body:e,headers:n})}};Ia=z,Un=new WeakMap,Aa=new WeakSet,hc=s(function(){return this.baseURL!=="https://api.smith.langchain.com/"},"_Langsmith_baseURLOverridden");Object.defineProperty(z,"Langsmith",{enumerable:!0,configurable:!0,writable:!0,value:Ia});Object.defineProperty(z,"DEFAULT_TIMEOUT",{enumerable:!0,configurable:!0,writable:!0,value:9e4});Object.defineProperty(z,"LangsmithError",{enumerable:!0,configurable:!0,writable:!0,value:Ee});Object.defineProperty(z,"APIError",{enumerable:!0,configurable:!0,writable:!0,value:ce});Object.defineProperty(z,"APIConnectionError",{enumerable:!0,configurable:!0,writable:!0,value:Je});Object.defineProperty(z,"APIConnectionTimeoutError",{enumerable:!0,configurable:!0,writable:!0,value:At});Object.defineProperty(z,"APIUserAbortError",{enumerable:!0,configurable:!0,writable:!0,value:ct});Object.defineProperty(z,"NotFoundError",{enumerable:!0,configurable:!0,writable:!0,value:Ot});Object.defineProperty(z,"ConflictError",{enumerable:!0,configurable:!0,writable:!0,value:Pt});Object.defineProperty(z,"RateLimitError",{enumerable:!0,configurable:!0,writable:!0,value:Mt});Object.defineProperty(z,"BadRequestError",{enumerable:!0,configurable:!0,writable:!0,value:It});Object.defineProperty(z,"AuthenticationError",{enumerable:!0,configurable:!0,writable:!0,value:Ct});Object.defineProperty(z,"InternalServerError",{enumerable:!0,configurable:!0,writable:!0,value:Nt});Object.defineProperty(z,"PermissionDeniedError",{enumerable:!0,configurable:!0,writable:!0,value:kt});Object.defineProperty(z,"UnprocessableEntityError",{enumerable:!0,configurable:!0,writable:!0,value:Rt});Object.defineProperty(z,"toFile",{enumerable:!0,configurable:!0,writable:!0,value:Dn});z.Datasets=pt;z.Runs=mt;z.Threads=jt;z.Traces=Bt;z.OnlineEvaluators=Ft;z.Public=ft;z.AnnotationQueues=Ye;z.Info=Dt;z.Issues=Ut;z.Sandboxes=ze;var $r={CLICKHOUSE_ONLY:"clickhouse_only",SMITHDB_ONLY:"smithdb_only",DUAL:"dual"};function gc(t){let e=t??{},r=!!(e.ch_query_enabled??!0),n=!!(e.sdb_query_enabled??!1);return!r&&n?$r.SMITHDB_ONLY:r&&n?$r.DUAL:$r.CLICKHOUSE_ONLY}s(gc,"getQueryBackend");function jn(t){return`Invalid prompt identifier format: "${t}". Expected one of:
8
15
  - "prompt-name" (for private prompts)
9
16
  - "owner/prompt-name" (for prompts with explicit owner)
10
17
  - "prompt-name:commit-hash" (with commit reference)
11
- - "owner/prompt-name:commit-hash" (with owner and commit)`}o(tn,"getInvalidPromptIdentifierMsg");var La=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}},Da=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 Fa(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}o(Fa,"isLangSmithNotFoundError");async function O(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 l=new Error(`${t.status} ${t.statusText}`);throw l.status=t?.status,l}if(n===void 0)try{n=await t.text()}catch{n=""}let a=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${n}`;if(t.status===404)throw new Da(a);if(t.status===409)throw new La(a);let i=new Error(a);throw i.status=t.status,i}o(O,"raiseForStatus");var Gc="ERR_CONFLICTING_ENDPOINTS",en=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:Gc}),this.name="ConflictingEndpointsError"}};function Hc(t){return typeof t=="object"&&t!==null&&t.code===Gc}o(Hc,"isConflictingEndpointsError");function Ge(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(tn(t));let[e,r]=t.split(":"),n=r||"latest";if(e.includes("/")){let[a,i]=e.split("/",2);if(!a||!i)throw new Error(tn(t));return[a,i,n]}else{if(!e)throw new Error(tn(t));return["-",e,n]}}o(Ge,"parsePromptIdentifier");var zc="[...]",Cg={result:"[Circular]"},nn=[],It=[],Og=new TextEncoder;function Rg(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}o(Rg,"defaultOptions");function rn(t){return Og.encode(t)}o(rn,"encodeString");function Vc(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(Vc,"serializeWellKnownTypes");function Mg(t){return function(e,r){if(t){let n=t.call(this,e,r);if(n!==void 0)return n}return Vc(r)}}o(Mg,"createDefaultReplacer");function _e(t,e,r,n,a){try{let i=JSON.stringify(t,Mg(r),n);return rn(i)}catch(i){if(!i.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
12
- Context: ${e}`:""}`),rn("[Unserializable]");J("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
13
- Context: ${e}`:""}`),typeof a>"u"&&(a=Rg()),ja(t,"",0,[],void 0,0,a);let s;try{It.length===0?s=JSON.stringify(t,r,n):s=JSON.stringify(t,kg(r),n)}catch{return rn("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;nn.length!==0;){let l=nn.pop();l.length===4?Object.defineProperty(l[0],l[1],l[3]):l[0][l[1]]=l[2]}}return rn(s)}}o(_e,"serialize");function Ua(t,e,r,n){var a=Object.getOwnPropertyDescriptor(n,r);a.get!==void 0?a.configurable?(Object.defineProperty(n,r,{value:t}),nn.push([n,r,e,a])):It.push([e,r,t]):(n[r]=t,nn.push([n,r,e]))}o(Ua,"setReplace");function ja(t,e,r,n,a,i,s){i+=1;var l;if(typeof t=="object"&&t!==null){for(l=0;l<n.length;l++)if(n[l]===t){Ua(Cg,t,e,a);return}if(typeof s.depthLimit<"u"&&i>s.depthLimit){Ua(zc,t,e,a);return}if(typeof s.edgesLimit<"u"&&r+1>s.edgesLimit){Ua(zc,t,e,a);return}if(n.push(t),Array.isArray(t))for(l=0;l<t.length;l++)ja(t[l],l,l,n,t,i,s);else{t=Vc(t);var c=Object.keys(t);for(l=0;l<c.length;l++){var u=c[l];ja(t[u],u,l,n,t,i,s)}}n.pop()}}o(ja,"decirc");function kg(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(It.length>0)for(var n=0;n<It.length;n++){var a=It[n];if(a[1]===e&&a[0]===r){r=a[2],It.splice(n,1);break}}return t.call(this,e,r)}}o(kg,"replaceGetterValues");function qc(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}o(qc,"_ensureUTCTimestamp");function Zt(t){return{...t,start_time:qc(t.start_time),end_time:qc(t.end_time)}}o(Zt,"_normalizeRunTimestamps");function Wc(t,e,r){if(r)return t;let n=Lr(),a=e??aa(),i=t.extra??{},s=i.metadata;return t.extra={...i,runtime:{...n,...i?.runtime},metadata:{...a,...a.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??a.revision_id}:{},...s}},t}o(Wc,"mergeRuntimeEnvIntoRun");var Ng=o(t=>{let e=t?.toString()??J("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"),Pg=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 $g(t){let e=[];for await(let r of t)e.push(r);return e}o($g,"toArray");function an(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}o(an,"trimQuotes");var Lg=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 Kc(t){return typeof t=="number"?Number(t.toFixed(4)):t}o(Kc,"_formatFeedbackScore");var Dg=24*1024*1024,Yc=1024*1024*1024,Fg=1e4,Ug=100,Jc="https://api.smith.langchain.com",Ba=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??Yc}peek(){return this.items[0]}push(e){let r,n=new Promise(i=>{r=i}),a=_e(e.item,`Serializing run with id: ${e.item.id}`).length;return this.sizeBytes+a>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: ${a} 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:a}),this.sizeBytes+=a,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=[],a=0;for(;a+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){let i=this.items.shift();i&&(n.push(i),a+=i.size,this.sizeBytes-=i.size)}if(n.length===0&&this.items.length>0){let i=this.items.shift();n.push(i),a+=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())]}},tt=class t{static{o(this,"Client")}get _fetch(){return this.fetchImplementation||xo(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:Te("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:J("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:Te("LANGSMITH_DEBUG")==="true"});let r=t.getDefaultClientConfig();if(this.tracingSampleRate=Ng(e.tracingSamplingRate),this.apiUrl=an(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=an(e.apiKey??r.apiKey),this.webUrl=an(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=an(e.workspaceId??J("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Gt({...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=J("FAILED_TRACES_DIR")||void 0;let n=J("FAILED_TRACES_MAX_MB");if(n){let i=parseInt(n,10);Number.isFinite(i)&&i>0&&(this.failedTracesMaxBytes=i*1024*1024)}let a=e.maxIngestMemoryBytes??Yc;this.batchIngestCaller=new Gt({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:a,...e.callerOptions??{},onFailedResponseHook:Lg,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 Ba(a),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,Dr()&&(this.langSmithToOTELTranslator=new Ur),this.cachedLSEnvVarsForMetadata=aa(),e.cache!==void 0&&e.disablePromptCache&&ut("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?(ut("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=Pr:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=Pr)}static getDefaultClientConfig(){let e=J("API_KEY"),r=J("ENDPOINT")??Jc,n=J("HIDE_INPUTS")==="true",a=J("HIDE_OUTPUTS")==="true";return{apiUrl:r,apiKey:e,webUrl:void 0,hideInputs:n,hideOutputs:a}}getHostUrl(){return this.webUrl?this.webUrl:Pg(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/${$r}`};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()??"",a=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{let s=await this._fetch(a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(s,`fetch ${e}`),s})}async _get(e,r){return(await this._getResponse(e,r)).json()}async*_getPaginated(e,r=new URLSearchParams,n){let a=Number(r.get("offset"))||0,i=Number(r.get("limit"))||100;for(;;){r.set("offset",String(a)),r.set("limit",String(i));let s=`${this.apiUrl}${e}?${r}`,l=await this.caller.call(async()=>{let u=await this._fetch(s,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(u,`fetch ${e}`),u}),c=n?n(await l.json()):await l.json();if(c.length===0||(yield c,c.length<i))break;a+=c.length}}async*_getCursorPaginatedList(e,r=null,n="POST",a="runs"){let i=r?{...r}:{};for(;;){let s=JSON.stringify(i),c=await(await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await O(p,`fetch ${e}`),p})).json();if(!c||!c[a])break;yield c[a];let u=c.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 a of e)this.filteredPostUuids.has(a.trace_id)?a.id===a.trace_id&&this.filteredPostUuids.delete(a.trace_id):n.push(a);return n}else{let n=[];for(let a of e){let i=a.trace_id??a.id;this.filteredPostUuids.has(i)||(a.id===i?this._shouldSample()?n.push(a):this.filteredPostUuids.add(i):n.push(a))}return n}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??Dg}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??Ug}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[a,i]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:r});if(!a.length){i();break}let s=a.reduce((u,p)=>{let m=p.apiUrl??this.apiUrl,g=p.apiKey??this.apiKey,E=p.apiKey===this.apiKey&&p.apiUrl===this.apiUrl?"default":`${m}|${g}`;return u[E]||(u[E]=[]),u[E].push(p),u},{}),l=[];for(let[u,p]of Object.entries(s)){let m=this._processBatch(p,{apiUrl:u==="default"?void 0:u.split("|")[0],apiKey:u==="default"?void 0:u.split("|")[1]});l.push(m)}let c=Promise.all(l).finally(i);n.push(c)}return Promise.all(n)}static async _writeTraceToFallbackDir(e,r,n,a,i){try{let s=typeof r=="string"?Buffer.from(r,"utf8"):Buffer.from(r),l=JSON.stringify({version:1,endpoint:a,headers:n,body_base64:s.toString("base64")}),c=`trace_${Date.now()}_${ct().slice(0,8)}.json`,u=Bt.join(e,c);if(t._fallbackDirsCreated.has(e)||(await Fo(e),t._fallbackDirsCreated.add(e)),i!==void 0&&i>0)try{let m=(await jo(e)).filter(h=>h.startsWith("trace_")&&h.endsWith(".json")),g=0;for(let h of m){let{size:E}=await Bo(Bt.join(e,h));g+=E}if(g>=i){console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${g} bytes >= ${i} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await Uo(u,l),console.warn(`LangSmith trace upload failed; data saved to ${u} for later replay.`)}catch(s){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,s)}}async _processBatch(e,r){if(!e.length)return;let n=e.reduce((a,i)=>a+(i.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let a={runCreates:e.filter(l=>l.action==="create").map(l=>l.item),runUpdates:e.filter(l=>l.action==="update").map(l=>l.item)},i=await this._ensureServerInfo();if(!this._multipartDisabled&&(i?.batch_ingest_config?.use_multipart_endpoint??!0)){let l=!this._runCompressionDisabled&&i?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(a,{...r,useGzip:l,sizeBytes:n})}catch(c){if(Fa(c))this._multipartDisabled=!0,await this.batchIngestRuns(a,{...r,sizeBytes:n});else throw c}}else await this.batchIngestRuns(a,{...r,sizeBytes:n})}}catch(a){console.error("Error exporting batch:",a)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let r=new Map,n=[];for(let a of e)a.item.id&&a.otelContext&&(r.set(a.item.id,a.otelContext),a.action==="create"?n.push({operation:"post",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}):n.push({operation:"patch",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=Wc(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let r=this.autoBatchQueue.push(e);if(this.manualFlushMode)return r;let n=await this._getBatchSizeLimitBytes(),a=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>a)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:a}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:a})},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(Fg),...this.fetchOptions});return await O(n,"get server info"),n})).json();return this.debug&&console.log(`
18
+ - "owner/prompt-name:commit-hash" (with owner and commit)`}s(jn,"getInvalidPromptIdentifierMsg");var Ca=class extends Error{static{s(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}},ka=class extends Error{static{s(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 Bn(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}s(Bn,"isLangSmithNotFoundError");function yc(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithConflictError"}s(yc,"isLangSmithConflictError");async function C(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 l=new Error(`${t.status} ${t.statusText}`);throw l.status=t?.status,l}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 ka(i);if(t.status===409)throw new Ca(i);let a=new Error(i);throw a.status=t.status,a}s(C,"raiseForStatus");var _c="ERR_CONFLICTING_ENDPOINTS",Fn=class extends Error{static{s(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:_c}),this.name="ConflictingEndpointsError"}};function bc(t){return typeof t=="object"&&t!==null&&t.code===_c}s(bc,"isConflictingEndpointsError");function he(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(jn(t));let[e,r]=t.split(":"),n=r||"latest";if(e.includes("/")){let[i,a]=e.split("/",2);if(!i||!a)throw new Error(jn(t));return[i,a,n]}else{if(!e)throw new Error(jn(t));return["-",e,n]}}s(he,"parseHubIdentifier");var rm=10,nm=1e4,wc="created_at";function im(t){return new Promise(e=>setTimeout(e,t))}s(im,"sleep");function am(t){return typeof t=="object"&&t!==null&&t.code==="EEXIST"}s(am,"isEEXIST");function vc(t){try{return Tt(Ne.join(t,wc)).split(`
19
+ `)}catch{return}}s(vc,"lockMetadataLines");function sm(t){let e=vc(t);if(e&&e[0]&&e[0].trim()){let r=Date.parse(e[0].trim());if(!Number.isNaN(r))return r}return Pl(t)}s(sm,"lockCreatedAtMs");function om(t){let e=vc(t);if(e&&e.length>=2&&e[1].trim())return e[1].trim()}s(om,"lockOwner");async function lm(t){let e=sm(t);return e===void 0||Date.now()-e<=nm?!1:(await _n(t),!0)}s(lm,"removeStaleLock");async function xc(t,e){let r=`${t}.oauth.lock.lock`,n=Ne.dirname(r);n&&await yn(n);let i=globalThis.crypto.randomUUID();for(;;){try{await Ol(r)}catch(a){if(!am(a))throw a;if(!await lm(r)){if(Date.now()>=e)throw new Error("timed out acquiring OAuth refresh lock");await im(Math.min(rm,Math.max(0,e-Date.now())))}continue}try{await nr(Ne.join(r,wc),`${new Date().toISOString()}
20
+ ${i}
21
+ `)}catch(a){throw await _n(r),a}break}return{async release(){om(r)===i&&await _n(r)}}}s(xc,"acquireOAuthRefreshLock");var Hn="https://api.smith.langchain.com",cm="langsmith-cli",um=6e4,dm=1e4;function pm(){let t=Pr();return t==="browser"||t==="webworker"}s(pm,"isBrowserLikeRuntime");function fm(){let t=ae("LANGSMITH_CONFIG_FILE");if(t)return t;let e=ae("HOME")??ae("USERPROFILE");if(e)return Ne.join(e,".langsmith","config.json")}s(fm,"getProfileConfigPath");function mm(t){let e=ae("LANGSMITH_PROFILE");if(e)return e;if(t.current_profile)return t.current_profile;if(t.profiles?.default)return"default"}s(mm,"resolveProfileName");function hm(){if(pm())return;let t=fm();if(!(!t||!ir(t)))try{let e=JSON.parse(Tt(t)),r=mm(e),n=r?e.profiles?.[r]:void 0;return!r||!n?void 0:{configPath:t,config:e,profileName:r,profile:n}}catch{return}}s(hm,"loadProfileState");function Ce(t){return t!=null&&t.trim()!==""}s(Ce,"hasValue");function ht(t){return t?.trim().replace(/^["']|["']$/g,"")}s(ht,"trimConfigValue");function Ec(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()+um}s(Ec,"shouldRefreshProfileToken");function gm(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}s(gm,"normalizeConfigUrl");function ym(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())}s(ym,"applyTokenResponse");function Sc(t){return t.reason??new Error("The operation was aborted.")}s(Sc,"getAbortReason");async function _m(t,e){if(!e)return t;if(e.aborted)throw Sc(e);let r,n=new Promise((i,a)=>{let o=s(()=>{a(Sc(e))},"onAbort");e.addEventListener("abort",o,{once:!0}),r=s(()=>{e.removeEventListener("abort",o)},"cleanup")});try{return await Promise.race([t,n])}finally{r?.()}}s(_m,"waitForAbortSignal");function Tc(){let t=hm(),e=t?.profile;if(!t||!e)return{};let r=ht(e.api_key),n=ht(e.oauth?.access_token),i=ht(e.oauth?.refresh_token);return{apiUrl:e.api_url,apiKey:r,workspaceId:e.workspace_id,oauthAccessToken:n,oauthRefreshToken:i,profileAuth:r||n||i?new Oa(t):void 0}}s(Tc,"loadProfileClientConfig");var Oa=class{static{s(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=bm(this.state.profile);return this.rememberProfileAuthHeader(e),e}async getAuthHeader(e,r){Ec(this.state.profile)&&(this.refreshPromise||(this.refreshPromise=this.refreshOAuthToken(e).finally(()=>{this.refreshPromise=void 0})),await _m(this.refreshPromise,r));let n=Ac(this.state.profile);return this.rememberProfileAuthHeader(n),n}isProfileAuthorizationHeader(e){return e===this.managedAuthorizationValue}reloadProfile(){try{let e=JSON.parse(Tt(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=ht(this.state.profile.api_url)??Hn,i=Date.now()+dm,a;try{if(a=await xc(this.state.configPath,i),this.reloadProfile()&&!Ec(this.state.profile))return;let l=new URLSearchParams({grant_type:"refresh_token",client_id:cm,refresh_token:this.state.profile.oauth?.refresh_token??r}),c=await e(`${gm(n)}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString(),signal:AbortSignal.timeout(Math.max(0,i-Date.now()))});if(!c.ok)return;let u=await c.json();if(!u.access_token)return;ym(this.state.profile,u),this.state.config.profiles??={},this.state.config.profiles[this.state.profileName]=this.state.profile,await nr(this.state.configPath,`${JSON.stringify(this.state.config,null,2)}
22
+ `)}catch{return}finally{await a?.release()}}rememberProfileAuthHeader(e){this.managedAuthorizationValue=e?.name==="Authorization"?e.value:void 0}};function bm(t){let e=ht(t.oauth?.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};if(!ht(t.oauth?.refresh_token))return Ac(t)}s(bm,"currentAuthHeaderFromProfile");function Ac(t){let e=ht(t.oauth?.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};let r=ht(t.api_key);if(r)return{name:"x-api-key",value:r}}s(Ac,"authHeaderFromProfile");var Ic="[...]",wm={result:"[Circular]"},Gn=[],gr=[],vm=new TextEncoder;function xm(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}s(xm,"defaultOptions");function zn(t){return vm.encode(t)}s(zn,"encodeString");function Cc(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}s(Cc,"serializeWellKnownTypes");function Em(t){return function(e,r){if(t){let n=t.call(this,e,r);if(n!==void 0)return n}return Cc(r)}}s(Em,"createDefaultReplacer");function kc(t){try{let i=function(d){let p=n(d);return p>r&&(r=p),p+2},a=function(d){return d===0?2:2+d*4},o=function(d){return d===void 0||typeof d=="function"||typeof d=="symbol"},l=function(d){return d===void 0||typeof d=="function"||typeof d=="symbol"?4:c(d)},c=function(d){if(d===null)return 4;if(d===void 0)return 0;let p=typeof d;if(p==="boolean")return 5;if(p==="number")return Number.isFinite(d)?d.toString().length:4;if(p==="bigint")return d.toString().length+2;if(p==="string")return i(d);if(p==="function"||p==="symbol")return 0;let h=d;if(h instanceof Date)return 26;if(h instanceof RegExp)return n(h.toString())+2;if(h instanceof Error){let b=h.name??"",v=h.message??"";return 22+n(b)+n(v)}if(typeof Buffer<"u"&&h instanceof Buffer)return 28+a(h.byteLength);if(ArrayBuffer.isView(h)){if(h instanceof DataView)return 2;let b=h.length??0,P=h instanceof Float32Array||h instanceof Float64Array?30:12;return 2+b*P}if(h instanceof ArrayBuffer)return 2;if(e.has(h))return 24;if(typeof h.toJSON=="function"){let b;try{b=h.toJSON("")}catch{return 16}e.add(h);let v=c(b);return e.delete(h),v}e.add(h);let g;if(Array.isArray(h)){g=2;let b=h.length;for(let v=0;v<b;v++)g+=l(h[v]),v<b-1&&(g+=1)}else if(h instanceof Map){g=2;let b=0;for(let[v,P]of h){if(o(P))continue;b>0&&(g+=1);let I=typeof v=="string"?v:String(v);g+=n(I)+3,g+=c(P),b++}}else if(h instanceof Set){g=2;let b=0;for(let v of h)b>0&&(g+=1),g+=l(v),b++}else{g=2;let b=0,v=Object.keys(h);for(let P=0;P<v.length;P++){let I=v[P],S=h[I];o(S)||(b>0&&(g+=1),g+=n(I)+3,g+=c(S),b++)}}return e.delete(h),g};s(i,"estimateString"),s(a,"estimateByteArrayJson"),s(o,"isDropped"),s(l,"estimateInArray"),s(c,"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:c(t),maxStringLen:r}}catch{return{size:ge(t).length,maxStringLen:0}}}s(kc,"estimateSerializedSize");function ge(t,e,r,n,i){try{let a=JSON.stringify(t,Em(r),n);return zn(a)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
23
+ Context: ${e}`:""}`),zn("[Unserializable]");q("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=xm()),Ra(t,"",0,[],void 0,0,i);let o;try{gr.length===0?o=JSON.stringify(t,r,n):o=JSON.stringify(t,Sm(r),n)}catch{return zn("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Gn.length!==0;){let l=Gn.pop();l.length===4?Object.defineProperty(l[0],l[1],l[3]):l[0][l[1]]=l[2]}}return zn(o)}}s(ge,"serialize");function Pa(t,e,r,n){var i=Object.getOwnPropertyDescriptor(n,r);i.get!==void 0?i.configurable?(Object.defineProperty(n,r,{value:t}),Gn.push([n,r,e,i])):gr.push([e,r,t]):(n[r]=t,Gn.push([n,r,e]))}s(Pa,"setReplace");function Ra(t,e,r,n,i,a,o){a+=1;var l;if(typeof t=="object"&&t!==null){for(l=0;l<n.length;l++)if(n[l]===t){Pa(wm,t,e,i);return}if(typeof o.depthLimit<"u"&&a>o.depthLimit){Pa(Ic,t,e,i);return}if(typeof o.edgesLimit<"u"&&r+1>o.edgesLimit){Pa(Ic,t,e,i);return}if(n.push(t),Array.isArray(t))for(l=0;l<t.length;l++)Ra(t[l],l,l,n,t,a,o);else{t=Cc(t);var c=Object.keys(t);for(l=0;l<c.length;l++){var u=c[l];Ra(t[u],u,l,n,t,a,o)}}n.pop()}}s(Ra,"decirc");function Sm(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(gr.length>0)for(var n=0;n<gr.length;n++){var i=gr[n];if(i[1]===e&&i[0]===r){r=i[2],gr.splice(n,1);break}}return t.call(this,e,r)}}s(Sm,"replaceGetterValues");var Oc=require("node:worker_threads"),Ma=Oc.Worker,Pc=!0;var Tm=`
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
+ `,La=class{static{s(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(!Pc||Ma===null)return this.disabled=!0,!1;try{let e=new Ma(Tm,{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,a)=>{this.pending.set(n,{resolve:i,reject:a});try{this.worker.postMessage({id:n,op:"serialize",payload:e})}catch(o){this.pending.delete(n),a(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()}},Na=null;function Rc(){return Na===null&&(Na=new La),Na}s(Rc,"getSharedSerializeWorker");var Am=64*1024,Im=2048;function Mc(t,e=Am,r=Im){if(t===null||typeof t!="object")return typeof t=="string"&&t.length>=e;let n=[t],i=new Set,a=0;for(;n.length>0;){if(a++>=r)return!1;let o=n.pop();if(o==null)continue;let l=typeof o;if(l==="string"){if(o.length>=e)return!0;continue}if(l!=="object")continue;let c=o;if(i.has(c)||(i.add(c),c instanceof Date||c instanceof RegExp||c instanceof Error||c instanceof ArrayBuffer||ArrayBuffer.isView(c)))continue;if(Array.isArray(c)){for(let d=c.length-1;d>=0;d--)n.push(c[d]);continue}if(c instanceof Map){for(let[,d]of c)n.push(d);continue}if(c instanceof Set){for(let d of c)n.push(d);continue}let u=Object.keys(c);for(let d=u.length-1;d>=0;d--)n.push(c[u[d]])}return!1}s(Mc,"hasLargeString");function Cm(t,e){let[r]=he(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.")}s(Cm,"assertPullPublicPromptAllowed");function Nc(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}s(Nc,"_ensureUTCTimestamp");function yr(t){return{...t,start_time:Nc(t.start_time),end_time:Nc(t.end_time)}}s(yr,"_normalizeRunTimestamps");function Lc(t,e,r){if(r)return t;let n=xn(),i=e??ea(),a=t.extra??{},o=a.metadata;return t.extra={...a,runtime:{...n,...a?.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}s(Lc,"mergeRuntimeEnvIntoRun");var km=s(t=>{let e=t?.toString()??q("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"),Om=s(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 Pm(t){let e=[];for await(let r of t)e.push(r);return e}s(Pm,"toArray");function Vn(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}s(Vn,"trimQuotes");var Rm=s(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 $c(t){return typeof t=="number"?Number(t.toFixed(4)):t}s($c,"_formatFeedbackScore");function Mm(t,e){if(!t)return;let r=s(u=>u.split(".").map(d=>parseInt(d,10)),"parse"),[n,i,a]=r(t),[o,l,c]=r(e);if(isNaN(n)||isNaN(i)||isNaN(a)||isNaN(o)||isNaN(l)||isNaN(c)){console.warn(`[LANGSMITH]: Could not parse backend version ${JSON.stringify(t)} for compatibility check.`);return}(n<o||n===o&&i<l||n===o&&i===l&&a<c)&&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`)}s(Mm,"_checkBackendVersion");var Nm=24*1024*1024,jc=1024*1024*1024,Lm=1e4,$m=100;function Bc(t,e){new Headers({[t]:e})}s(Bc,"assertValidHeader");function Dc(t){for(let[e,r]of Object.entries(t??{}))Bc(e,r)}s(Dc,"assertValidHeaders");function Uc(t){if(!t)return{};let e=t instanceof Headers?[...t.entries()]:Array.isArray(t)?t.map(([i,a])=>[i,a]):Object.entries(t),r={},n=new Map;for(let[i,a]of e){Bc(i,a);let o=i.toLowerCase(),l=n.get(o);l===void 0?(n.set(o,i),r[i]=a):r[l]=a}return r}s(Uc,"normalizeHeaders");function Dm(t,e,r){let n={...t},i=new Map(Object.keys(n).map(a=>[a.toLowerCase(),a]));for(let[a,o]of Object.entries(e)){let l=a.toLowerCase();n[i.get(l)??a]=o}for(let a of Object.keys(n))r.has(a.toLowerCase())&&delete n[a];return n}s(Dm,"mergeCallerHeaders");var $a=class{static{s(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??jc}peek(){return this.items[0]}push(e){let r,n=new Promise(a=>{r=a}),i=kc(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 a=this.items.shift();a&&(n.push(a),i+=a.size,this.sizeBytes-=a.size)}if(n.length===0&&this.items.length>0){let a=this.items.shift();n.push(a),i+=a.size,this.sizeBytes-=a.size}return[n.map(a=>({action:a.action,item:a.payload,otelContext:a.otelContext,apiKey:a.apiKey,apiUrl:a.apiUrl,workspaceId:a.workspaceId,size:a.size})),()=>n.forEach(a=>a.itemPromiseResolve())]}},ut=class t{static{s(this,"Client")}get tracingMode(){return this._tracingMode}get _fetch(){let e=this.fetchImplementation||cl(this.debug);return(async(r,n)=>{let i,a=this.getProfileManagedAuthorizationHeader(n);return this.apiKey!==void 0?i={name:"x-api-key",value:`${this.apiKey}`}:this.hasExplicitAuthHeader(n,a)||(i=await this.profileAuth?.getAuthHeader(e,n?.signal)),e(r,this.applyCurrentAuthHeaders(n,i,a))})}getProfileManagedAuthorizationHeader(e){if(!e?.headers||!this.profileAuth)return;let r=new Headers(e.headers).get("Authorization");if(Ce(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(Ce(n.get("x-api-key")))return!0;let i=n.get("Authorization");return Ce(i)?!this.isProfileManagedAuthorizationHeader(i??"",r):!1}applyCurrentAuthHeaders(e,r,n){if(!r)return e;let i=s(p=>{if(this.apiKey!==void 0&&r.name==="x-api-key")return p.delete("Authorization"),p.has("x-api-key")||p.set("x-api-key",r.value),p;if(r.name==="Authorization"){if(Ce(p.get("x-api-key")))return p;let g=p.get("Authorization");return Ce(g)&&!this.isProfileManagedAuthorizationHeader(g??"",n)||p.set("Authorization",r.value),p}let h=p.get("Authorization");return Ce(h)&&!this.isProfileManagedAuthorizationHeader(h??"",n)||(Ce(h)&&p.delete("Authorization"),p.has("x-api-key")||p.set("x-api-key",r.value)),p},"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 a={...e.headers??{}},o=s(p=>Object.keys(a).find(h=>h.toLowerCase()===p),"getHeaderKey"),l=s(p=>{let h=o(p);return h?a[h]:void 0},"getHeader"),c=Ce(l("x-api-key")),u=l("authorization"),d=Ce(u)&&!this.isProfileManagedAuthorizationHeader(u??"",n);if(this.apiKey!==void 0&&r.name==="x-api-key"){let p=o("authorization");return p&&delete a[p],c||(a["x-api-key"]=r.value),{...e,headers:a}}if(r.name==="Authorization"){if(!c&&!d){let p=o("authorization");p&&p!=="Authorization"&&delete a[p],a.Authorization=r.value}return{...e,headers:a}}if(!d){let p=o("authorization");p&&delete a[p],c||(a["x-api-key"]=r.value)}return{...e,headers:a}}_trackDrain(e){this._pendingDrains.add(e),e.finally(()=>{this._pendingDrains.delete(e)})}async _serializeBody(e,r){if(this.manualFlushMode)return ge(e,r);if(!Mc(e))return ge(e,r);if(this._serializeWorker===void 0&&(this._serializeWorker=Rc()),this._serializeWorker===null)return ge(e,r);try{let n=await this._serializeWorker.serialize(e);return n===null?(this._serializeWorker=null,ge(e,r)):n}catch{return ge(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:ae("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:q("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:q("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:ae("LANGSMITH_DEBUG")==="true"});let r=t.getDefaultClientConfig();this.tracingSampleRate=km(e.tracingSamplingRate),this.apiUrl=Vn(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1));let n=Vn(e.apiKey??r.apiKey);if(this.apiKey=Ce(n)?n:void 0,this.profileAuth=this.apiKey!==void 0?void 0:r.profileAuth,this.webUrl=Vn(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Vn(e.workspaceId??r.workspaceId),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Rr({...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=q("FAILED_TRACES_DIR")||void 0;let i=q("FAILED_TRACES_MAX_MB");if(i){let c=parseInt(i,10);Number.isFinite(c)&&c>0&&(this.failedTracesMaxBytes=c*1024*1024)}let a=e.maxIngestMemoryBytes??jc;this.batchIngestCaller=new Rr({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:a,...e.callerOptions??{},onFailedResponseHook:Rm,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 $a(a),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit;let{headers:o,...l}=e.fetchOptions||{};this.fetchOptions=l,this._fetchOptionsHeaders=Uc(o),Dc(e.headers),this._customHeaders=e.headers??{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,this._tracingMode=En(e.tracingMode),this._tracingMode==="otel"&&(this.langSmithToOTELTranslator=new Tn),this.cachedLSEnvVarsForMetadata=ea(),e.cache!==void 0&&e.disablePromptCache&&se("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?(se("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=wn:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=wn)}static getDefaultClientConfig(){let e=Tc(),r=q("API_KEY"),n=q("ENDPOINT"),i=q("WORKSPACE_ID"),a=Ce(r),o=n??e.apiUrl??Hn,l=i??e.workspaceId,c=q("HIDE_INPUTS")==="true",u=q("HIDE_OUTPUTS")==="true",d=q("HIDE_METADATA")==="true";return{apiUrl:o,apiKey:r,webUrl:void 0,hideInputs:c,hideOutputs:u,hideMetadata:d,workspaceId:l,oauthAccessToken:a?void 0:e.oauthAccessToken,oauthRefreshToken:a?void 0:e.oauthRefreshToken,profileAuth:a?void 0:e.profileAuth}}getHostUrl(){return this.webUrl?this.webUrl:Om(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 Dm(Uc(this._customHeaders),this._fetchOptionsHeaders,this._sdkControlledHeaders)}get _mergedHeaders(){let e={"User-Agent":`langsmith-js/${vn}`,...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){Dc(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,...a}=this.fetchOptions;return new z({apiKey:e.apiKey,tenantID:this.workspaceId,baseURL:this._getOpenAPIBaseUrl(),timeout:this.timeout_ms,fetch:this._fetch,fetchOptions:a,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 C(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,a=Number(r.get("limit"))||100;for(;;){r.set("offset",String(i)),r.set("limit",String(a));let o=`${this.apiUrl}${e}?${r}`,l=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 C(u,`fetch ${e}`),u}),c=n?n(await l.json()):await l.json();if(c.length===0||(yield c,c.length<a))break;i+=c.length}}async*_getCursorPaginatedList(e,r=null,n="POST",i="runs"){let a=r?{...r}:{};for(;;){let o=JSON.stringify(a),c=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 C(d,`fetch ${e}`),d})).json();if(!c||!c[i])break;yield c[i];let u=c.cursors;if(!u||!u.next)break;a.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 a=i.trace_id??i.id;this.filteredPostUuids.has(a)||(i.id===a?this._shouldSample()?n.push(i):this.filteredPostUuids.add(a):n.push(i))}return n}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??Nm}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??$m}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,a]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:r});if(!i.length){a();break}let o=i.reduce((u,d)=>{let p=d.apiUrl??this.apiUrl,h=d.apiKey??this.apiKey,g=d.workspaceId??this.workspaceId,v=d.apiKey===this.apiKey&&d.apiUrl===this.apiUrl&&d.workspaceId===this.workspaceId?"default":`${p}|${h}|${g??""}`;return u[v]||(u[v]=[]),u[v].push(d),u},{}),l=[];for(let[u,d]of Object.entries(o)){let p=u==="default",h=p?[]:u.split("|"),g=h[2],b=this._processBatch(d,{apiUrl:p?void 0:h[0],apiKey:p?void 0:h[1],workspaceId:p||!g?void 0:g});l.push(b)}let c=Promise.all(l).finally(a);n.push(c)}return Promise.all(n)}static async _writeTraceToFallbackDir(e,r,n,i,a){try{let o=typeof r=="string"?Buffer.from(r,"utf8"):Buffer.from(r),l=JSON.stringify({version:1,endpoint:i,headers:n,body_base64:o.toString("base64")}),c=`trace_${Date.now()}_${Et().slice(0,8)}.json`,u=Ne.join(e,c);if(t._fallbackDirsCreated.has(e)||(await yn(e),t._fallbackDirsCreated.add(e)),a!==void 0&&a>0)try{let p=(await Sl(e)).filter(g=>g.startsWith("trace_")&&g.endsWith(".json")),h=0;for(let g of p){let{size:b}=await Tl(Ne.join(e,g));h+=b}if(h>=a){console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${h} bytes >= ${a} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await nr(u,l),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,a)=>i+(a.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let i={runCreates:e.filter(l=>l.action==="create").map(l=>l.item),runUpdates:e.filter(l=>l.action==="update").map(l=>l.item)},a=await this._ensureServerInfo();if(!this._multipartDisabled&&(a?.batch_ingest_config?.use_multipart_endpoint??!0)){let l=!this._runCompressionDisabled&&a?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(i,{...r,useGzip:l,sizeBytes:n})}catch(c){if(Bn(c))this._multipartDisabled=!0,await this.batchIngestRuns(i,{...r,sizeBytes:n});else throw c}}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=Lc(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(Lm),...this.fetchOptions});return await C(n,"get server info"),n})).json();return this.debug&&console.log(`
14
116
  === LangSmith Server Configuration ===
15
117
  `+JSON.stringify(r,null,2)+`
16
- `),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=Fr(),r=Jo();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"},a=e.project_name;delete e.project_name;let i=await this.prepareRunCreateOrUpdateInputs({session_name:a,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:c,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}let s=Wc(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 l=_e(s,`Creating run with id: ${s.id}`);await this.caller.call(async()=>{let c=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await O(c,"create run",!0),c})}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let a=await Promise.all(e?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]),i=await Promise.all(r?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]);if(a.length>0&&i.length>0){let c=a.reduce((p,m)=>(m.id&&(p[m.id]=m),p),{}),u=[];for(let p of i)p.id!==void 0&&c[p.id]?c[p.id]={...c[p.id],...p}:u.push(p);a=Object.values(c),i=u}let s={post:a,patch:i};if(!s.post.length&&!s.patch.length)return;let l={post:[],patch:[]};for(let c of["post","patch"]){let u=c,p=s[u].reverse(),m=p.pop();for(;m!==void 0;)l[u].push(m),m=p.pop()}if(l.post.length>0||l.patch.length>0){let c=l.post.map(u=>u.id).concat(l.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(_e(l,`Ingesting runs with ids: ${c}`),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 a=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 O(a,"batch create run",!0),a})}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let a={},i=[];for(let m of e??[]){let g=await this.prepareRunCreateOrUpdateInputs(m);g.id!==void 0&&g.attachments!==void 0&&(a[g.id]=g.attachments),delete g.attachments,i.push(g)}let s=[];for(let m of r??[])s.push(await this.prepareRunCreateOrUpdateInputs(m));if(i.find(m=>m.trace_id===void 0||m.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(s.find(m=>m.trace_id===void 0||m.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&&s.length>0){let m=i.reduce((h,E)=>(E.id&&(h[E.id]=E),h),{}),g=[];for(let h of s)h.id!==void 0&&m[h.id]?m[h.id]={...m[h.id],...h}:g.push(h);i=Object.values(m),s=g}if(i.length===0&&s.length===0)return;let u=[],p=[];for(let[m,g]of[["post",i],["patch",s]])for(let h of g){let{inputs:E,outputs:x,events:P,extra:N,error:L,serialized:C,attachments:k,...F}=h,B={inputs:E,outputs:x,events:P,extra:N,error:L,serialized:C},V=_e(F,`Serializing for multipart ingestion of run with id: ${F.id}`);p.push({name:`${m}.${F.id}`,payload:new Blob([V],{type:`application/json; length=${V.length}`})});for(let[_,X]of Object.entries(B)){if(X===void 0)continue;let te=_e(X,`Serializing ${_} for multipart ingestion of run with id: ${F.id}`);p.push({name:`${m}.${F.id}.${_}`,payload:new Blob([te],{type:`application/json; length=${te.length}`})})}if(F.id!==void 0){let _=a[F.id];if(_){delete a[F.id];for(let[X,te]of Object.entries(_)){let G,be;if(Array.isArray(te)?[G,be]=te:(G=te.mimeType,be=te.data),X.includes(".")){console.warn(`Skipping attachment '${X}' for run ${F.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}p.push({name:`attachment.${F.id}.${X}`,payload:new Blob([be],{type:`${G}; length=${be.byteLength}`})})}}}u.push(`trace=${F.trace_id},id=${F.id}`)}await this._sendMultipartRequest(p,u.join("; "),n)}async _createNodeFetchBody(e,r){let n=[];for(let s of e)n.push(new Blob([`--${r}\r
17
- `])),n.push(new Blob([`Content-Disposition: form-data; name="${s.name}"\r
18
- `,`Content-Type: ${s.payload.type}\r
118
+ `),r}_checkStainlessVersion(e){this._stainlessVersionsChecked.has(e)||(this._stainlessVersionsChecked.add(e),this._ensureServerInfo().then(r=>{Mm(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(gc(r.instance_flags)===$r.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}`);se(`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=Sn(),r=Dl();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 a=await this.prepareRunCreateOrUpdateInputs({session_name:i,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){let c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:a,otelContext:c,apiKey:r?.apiKey,apiUrl:r?.apiUrl,workspaceId:r?.workspaceId}).catch(console.error);return}let o=Lc(a,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 l=ge(o,`Creating run with id: ${o.id}`);await this.caller.call(async()=>{let c=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await C(c,"create run",!0),c})}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let i=await Promise.all(e?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]),a=await Promise.all(r?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]);if(i.length>0&&a.length>0){let c=i.reduce((d,p)=>(p.id&&(d[p.id]=p),d),{}),u=[];for(let d of a)d.id!==void 0&&c[d.id]?c[d.id]={...c[d.id],...d}:u.push(d);i=Object.values(c),a=u}let o={post:i,patch:a};if(!o.post.length&&!o.patch.length)return;let l={post:[],patch:[]};for(let c of["post","patch"]){let u=c,d=o[u].reverse(),p=d.pop();for(;p!==void 0;)l[u].push(p),p=d.pop()}if(l.post.length>0||l.patch.length>0){let c=l.post.map(u=>u.id).concat(l.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(await this._serializeBody(l,`Ingesting runs with ids: ${c}`),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 C(i,"batch create run",!0),i})}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let i={},a=[];for(let p of e??[]){let h=await this.prepareRunCreateOrUpdateInputs(p);h.id!==void 0&&h.attachments!==void 0&&(i[h.id]=h.attachments),delete h.attachments,a.push(h)}let o=[];for(let p of r??[])o.push(await this.prepareRunCreateOrUpdateInputs(p));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 creating a run');if(o.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(a.length>0&&o.length>0){let p=a.reduce((g,b)=>(b.id&&(g[b.id]=b),g),{}),h=[];for(let g of o)g.id!==void 0&&p[g.id]?p[g.id]={...p[g.id],...g}:h.push(g);a=Object.values(p),o=h}if(a.length===0&&o.length===0)return;let u=[],d=[];for(let[p,h]of[["post",a],["patch",o]])for(let g of h){let{inputs:b,outputs:v,events:P,extra:I,error:S,serialized:A,attachments:R,...$}=g,N={inputs:b,outputs:v,events:P,extra:I,error:S,serialized:A},j=await this._serializeBody($,`Serializing for multipart ingestion of run with id: ${$.id}`);d.push({name:`${p}.${$.id}`,payload:new Blob([j],{type:`application/json; length=${j.length}`})});for(let[y,K]of Object.entries(N)){if(K===void 0)continue;let B=await this._serializeBody(K,`Serializing ${y} for multipart ingestion of run with id: ${$.id}`);d.push({name:`${p}.${$.id}.${y}`,payload:new Blob([B],{type:`application/json; length=${B.length}`})})}if($.id!==void 0){let y=i[$.id];if(y){delete i[$.id];for(let[K,B]of Object.entries(y)){let F,de;if(Array.isArray(B)?[F,de]=B:(F=B.mimeType,de=B.data),K.includes(".")){console.warn(`Skipping attachment '${K}' for run ${$.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}d.push({name:`attachment.${$.id}.${K}`,payload:new Blob([de],{type:`${F}; length=${de.byteLength}`})})}}}u.push(`trace=${$.trace_id},id=${$.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
19
121
  \r
20
- `])),n.push(s.payload),n.push(new Blob([`\r
122
+ `])),n.push(o.payload),n.push(new Blob([`\r
21
123
  `]));return n.push(new Blob([`--${r}--\r
22
- `])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,r){let n=new TextEncoder;return new ReadableStream({async start(i){let s=o(async l=>{typeof l=="string"?i.enqueue(n.encode(l)):i.enqueue(l)},"writeChunk");for(let l of e){await s(`--${r}\r
23
- `),await s(`Content-Disposition: form-data; name="${l.name}"\r
24
- `),await s(`Content-Type: ${l.payload.type}\r
124
+ `])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,r){let n=new TextEncoder;return new ReadableStream({async start(a){let o=s(async l=>{typeof l=="string"?a.enqueue(n.encode(l)):a.enqueue(l)},"writeChunk");for(let l of e){await o(`--${r}\r
125
+ `),await o(`Content-Disposition: form-data; name="${l.name}"\r
126
+ `),await o(`Content-Type: ${l.payload.type}\r
25
127
  \r
26
- `);let u=l.payload.stream().getReader();try{let p;for(;!(p=await u.read()).done;)i.enqueue(p.value)}finally{u.releaseLock()}await s(`\r
27
- `)}await s(`--${r}--\r
28
- `),i.close()}})}async _sendMultipartRequest(e,r,n){let a="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=o(()=>this._createNodeFetchBody(e,a),"buildBuffered"),s=o(()=>this._createMultipartStream(e,a),"buildStream"),l=o(async c=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let u=await c(),p={...this.headers,"Content-Type":`multipart/form-data; boundary=${a}`};n?.apiKey!==void 0&&(p["x-api-key"]=n.apiKey);let m=u;n?.useGzip&&typeof u=="object"&&"pipeThrough"in u&&(m=u.pipeThrough(new CompressionStream("gzip")),p["Content-Encoding"]="gzip");let g=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:p,body:m,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(g,"Failed to send multipart request",!0),g}),"sendWithRetry");try{let c,u=!1;To()&&!this.multipartStreamingDisabled&&na()!=="bun"?(u=!0,c=await l(s)):c=await l(i),(!this.multipartStreamingDisabled||u)&&c.status===422&&(n?.apiUrl??this.apiUrl)!==Jc&&(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,c=await l(i))}catch(c){if(Fa(c))throw c;if(console.warn(`${c.message.trim()}
128
+ `);let u=l.payload.stream().getReader();try{let d;for(;!(d=await u.read()).done;)a.enqueue(d.value)}finally{u.releaseLock()}await o(`\r
129
+ `)}await o(`--${r}--\r
130
+ `),a.close()}})}async _sendMultipartRequest(e,r,n){let i="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=s(()=>this._createNodeFetchBody(e,i),"buildBuffered"),o=s(()=>this._createMultipartStream(e,i),"buildStream"),l=s(async c=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let u=await c(),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 p=u;n?.useGzip&&typeof u=="object"&&"pipeThrough"in u&&(p=u.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");let h=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 C(h,"Failed to send multipart request",!0),h}),"sendWithRetry");try{let c,u=!1;ll()&&!this.multipartStreamingDisabled&&Pr()!=="bun"?(u=!0,c=await l(o)):c=await l(a),(!this.multipartStreamingDisabled||u)&&c.status===422&&(n?.apiUrl??this.apiUrl)!==Hn&&(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,c=await l(a))}catch(c){if(Bn(c))throw c;if(console.warn(`${c.message.trim()}
29
131
 
30
- Context: ${r}`),this.failedTracesDir){let u=await this._createNodeFetchBody(e,a).catch(()=>null);u&&await t._writeTraceToFallbackDir(this.failedTracesDir,u,{"Content-Type":`multipart/form-data; boundary=${a}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,r,n){$(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));let a={...r,id:e};if(!this._filterForSampling([a],!0).length)return;if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){let l=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&a.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:a,otelContext:l,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:a,otelContext:l,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 s=_e(r,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let l=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await O(l,"update run",!0),l})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){$(e);let n=Zt(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 a;r.session_id?a=r.session_id:n?.projectName?a=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?a=n?.projectId:a=(await this.readProject({projectName:J("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${a}/r/${r.id}?poll=true`}else if(e!==void 0){let a=await this.readRun(e);if(!a.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${a.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){let r=await $g(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},a={};r.sort((i,s)=>(i?.dotted_order??"").localeCompare(s?.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),a[i.id]=i)}e.child_runs=n[e.id]||[];for(let i in n)i!==e.id&&(a[i].child_runs=n[i]);return e}async*listRuns(e){let{projectId:r,projectName:n,parentRunId:a,traceId:i,referenceExampleId:s,startTime:l,executionOrder:c,isRoot:u,runType:p,error:m,id:g,query:h,filter:E,traceFilter:x,treeFilter:P,limit:N,select:L,order:C}=e,k=[];if(r&&(k=Array.isArray(r)?r:[r]),n){let _=Array.isArray(n)?n:[n],X=await Promise.all(_.map(te=>this.readProject({projectName:te}).then(G=>G.id)));k.push(...X)}let F=["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"],B={session:k.length?k:null,run_type:p,reference_example:s,query:h,filter:E,trace_filter:x,tree_filter:P,execution_order:c,parent_run:a,start_time:l?l.toISOString():null,error:m,id:g,limit:N,trace:i,select:L||F,is_root:u,order:C};B.select.includes("child_run_ids")&&ut("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let V=0;for await(let _ of this._getCursorPaginatedList("/runs/query",B)){let X=_.map(Zt);if(N){if(V>=N)break;if(X.length+V>N){yield*X.slice(0,N-V);break}V+=X.length,yield*X}else yield*X}}async*listGroupRuns(e){let{projectId:r,projectName:n,groupBy:a,filter:i,startTime:s,endTime:l,limit:c,offset:u}=e,m={session_id:r||(await this.readProject({projectName:n})).id,group_by:a,filter:i,start_time:s?s.toISOString():null,end_time:l?l.toISOString():null,limit:Number(c)||100},g=Number(u)||0,h="/runs/group",E=`${this.apiUrl}${h}`;for(;;){let x={...m,offset:g},P=Object.fromEntries(Object.entries(x).filter(([B,V])=>V!==void 0)),N=JSON.stringify(P),C=await(await this.caller.call(async()=>{let B=await this._fetch(E,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:N});return await O(B,`Failed to fetch ${h}`),B})).json(),{groups:k,total:F}=C;if(k.length===0)break;for(let B of k)yield B;if(g+=k.length,g>=F)break}}async*readThread(e){let{threadId:r,projectId:n,projectName:a,isRoot:i=!0,limit:s,filter:l,order:c="asc"}=e;if(!n&&!a)throw new Error("threadId requires projectId or projectName");let u=`eq(thread_id, ${JSON.stringify(r)})`,p=l?`and(${u}, ${l})`:u;yield*this.listRuns({projectId:n??void 0,projectName:a??void 0,isRoot:i,limit:s,filter:p,order:c})}async listThreads(e){let{projectId:r,projectName:n,limit:a,offset:i=0,filter:s,startTime:l,isRoot:c=!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,p=l??new Date(Date.now()-1440*60*1e3),g={session:[u],is_root:c,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:p.toISOString()};s!=null&&(g.filter=s);let h=new Map;for await(let N of this._getCursorPaginatedList("/runs/query",g))for(let L of N){let C=Zt(L),k=C.thread_id;if(k){let F=h.get(k)??[];F.push(C),h.set(k,F)}}let E=[];for(let[N,L]of h.entries()){L.sort((V,_)=>{let X=V,te=_,G=X.start_time??"",be=te.start_time??"";if(G!==be)return G.localeCompare(be);let or=X.dotted_order??"",_t=te.dotted_order??"";return or.localeCompare(_t)});let k=[...L.map(V=>V.start_time).filter(Boolean)].sort(),F=k.length?k[0]:"",B=k.length?k[k.length-1]:"";E.push({thread_id:N,runs:L,count:L.length,filter:"",total_tokens:0,total_cost:null,min_start_time:F,max_start_time:B,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}E.sort((N,L)=>{let C=N.max_start_time??"";return(L.max_start_time??"").localeCompare(C)});let x=i>0?E.slice(i):E;return a!==void 0?x.slice(0,a):x}async getRunStats({id:e,trace:r,parentRun:n,runType:a,projectNames:i,projectIds:s,referenceExampleIds:l,startTime:c,endTime:u,error:p,query:m,filter:g,traceFilter:h,treeFilter:E,isRoot:x,dataSourceType:P}){let N=s||[];i&&(N=[...s||[],...await Promise.all(i.map(V=>this.readProject({projectName:V}).then(_=>_.id)))]);let C=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:a,session:N,reference_example:l,start_time:c,end_time:u,error:p,query:m,filter:g,trace_filter:h,tree_filter:E,is_root:x,data_source_type:P}).filter(([V,_])=>_!==void 0)),k=JSON.stringify(C);return await(await this.caller.call(async()=>{let V=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:k});return await O(V,"get run stats"),V})).json()}async shareRun(e,{shareId:r}={}){let n={run_id:e,share_token:r||ct()};$(e);let a=JSON.stringify(n),s=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await O(l,"share run"),l})).json();if(s===null||!("share_token"in s))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${s.share_token}/r`}async unshareRun(e){$(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 O(r,"unshare run",!0),r})}async readRunSharedLink(e){$(e);let n=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(a,"read run shared link"),a})).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 s of r)n.append("id",s);return $(e),(await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(s,"list shared runs"),s})).json()).map(Zt)}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),$(e);let a=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 O(i,"read dataset shared schema"),i})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}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};$(e);let a=JSON.stringify(n),s=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await O(l,"share dataset"),l})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async unshareDataset(e){$(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 O(r,"unshare dataset",!0),r})}async readSharedDataset(e){return $(e),await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(a,"read shared dataset"),a})).json()}async listSharedExamples(e,r){let n={};r?.exampleIds&&(n.id=r.exampleIds);let a=new URLSearchParams;Object.entries(n).forEach(([l,c])=>{Array.isArray(c)?c.forEach(u=>a.append(l,u)):a.append(l,c)});let i=await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/public/${e}/examples?${a.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(l,"list shared examples"),l}),s=await i.json();if(!i.ok)throw"detail"in s?new Error(`Failed to list shared examples.
31
- Status: ${i.status}
32
- Message: ${Array.isArray(s.detail)?s.detail.join(`
33
- `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return s.map(l=>({...l,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:a=!1,projectExtra:i=null,referenceDatasetId:s=null}){let l=a?"?upsert=true":"",c=`${this.apiUrl}/sessions${l}`,u=i||{};n&&(u.metadata=n);let p={name:e,extra:u,description:r};s!==null&&(p.reference_dataset_id=s);let m=JSON.stringify(p);return await(await this.caller.call(async()=>{let E=await this._fetch(c,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:m});return await O(E,"create project"),E})).json()}async updateProject(e,{name:r=null,description:n=null,metadata:a=null,projectExtra:i=null,endTime:s=null}){let l=`${this.apiUrl}/sessions/${e}`,c=i;a&&(c={...c||{},metadata:a});let u=JSON.stringify({name:r,extra:c,description:n,end_time:s?new Date(s).toISOString():null});return await(await this.caller.call(async()=>{let g=await this._fetch(l,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await O(g,"update project"),g})).json()}async hasProject({projectId:e,projectName:r}){let n="/sessions",a=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)$(e),n+=`/${e}`;else if(r!==void 0)a.append("name",r);else throw new Error("Must provide projectName or projectId");let i=await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${n}?${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(s,"has project"),s});try{let s=await i.json();return i.ok?Array.isArray(s)?s.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let a="/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)$(e),a+=`/${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 s=await this._get(a,i),l;if(Array.isArray(s)){if(s.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);l=s[0]}else l=s;return l}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}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/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}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/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:a,referenceDatasetName:i,includeStats:s,datasetVersion:l,referenceFree:c,metadata:u}={}){let p=new URLSearchParams;if(e!==void 0)for(let m of e)p.append("id",m);if(r!==void 0&&p.append("name",r),n!==void 0&&p.append("name_contains",n),a!==void 0)p.append("reference_dataset",a);else if(i!==void 0){let m=await this.readDataset({datasetName:i});p.append("reference_dataset",m.id)}s!==void 0&&p.append("include_stats",s.toString()),l!==void 0&&p.append("dataset_version",l),c!==void 0&&p.append("reference_free",c.toString()),u!==void 0&&p.append("metadata",JSON.stringify(u));for await(let m of this._getPaginated("/sessions",p))yield*m}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,$(n),await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(a,`delete session ${n} (${r})`,!0),a})}async uploadCsv({csvFile:e,fileName:r,inputKeys:n,outputKeys:a,description:i,dataType:s,name:l}){let c=`${this.apiUrl}/datasets/upload`,u=new FormData,p=new Blob([e],{type:"text/csv"});return u.append("file",p,r),n.forEach(h=>{u.append("input_keys",h)}),a.forEach(h=>{u.append("output_keys",h)}),i&&u.append("description",i),s&&u.append("data_type",s),l&&u.append("name",l),await(await this.caller.call(async()=>{let h=await this._fetch(c,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await O(h,"upload CSV"),h})).json()}async createDataset(e,{description:r,dataType:n,inputsSchema:a,outputsSchema:i,metadata:s}={}){let l={name:e,description:r,extra:{source:"sdk",...s?{metadata:s}:{}}};n&&(l.data_type=n),a&&(l.inputs_schema_definition=a),i&&(l.outputs_schema_definition=i);let c=JSON.stringify(l);return await(await this.caller.call(async()=>{let m=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await O(m,"create dataset"),m})).json()}async readDataset({datasetId:e,datasetName:r}){let n="/datasets",a=new URLSearchParams({limit:"1"});if(e&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(e)$(e),n+=`/${e}`;else if(r)a.append("name",r);else throw new Error("Must provide datasetName or datasetId");let i=await this._get(n,a),s;if(Array.isArray(i)){if(i.length===0)throw new Error(`Dataset[id=${e}, name=${r}] not found`);s=i[0]}else s=i;return s}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:a}){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 s=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof a=="string"?a:a.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,s)}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(`
34
- `).map(l=>JSON.parse(l))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:a,datasetNameContains:i,metadata:s}={}){let l="/datasets",c=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(let u of n)c.append("id",u);a!==void 0&&c.append("name",a),i!==void 0&&c.append("name_contains",i),s!==void 0&&c.append("metadata",JSON.stringify(s));for await(let u of this._getPaginated(l,c))yield*u}async updateDataset(e){let{datasetId:r,datasetName:n,...a}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let i=r??(await this.readDataset({datasetName:n})).id;$(i);let s=JSON.stringify(a);return await(await this.caller.call(async()=>{let c=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:s});return await O(c,"update dataset"),c})).json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:a,tag:i}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let s=r??(await this.readDataset({datasetName:n})).id;$(s);let l=JSON.stringify({as_of:typeof a=="string"?a:a.toISOString(),tag:i});await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${s}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await O(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",a=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(a=(await this.readDataset({datasetName:r})).id),a!==void 0)$(a),n+=`/${a}`;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 O(i,`delete ${n}`,!0),i})}async indexDataset({datasetId:e,datasetName:r,tag:n}){let a=e;if(!a&&!r)throw new Error("Must provide either datasetName or datasetId");if(a&&r)throw new Error("Must provide either datasetName or datasetId, not both");a||(a=(await this.readDataset({datasetName:r})).id),$(a);let s=JSON.stringify({tag:n});await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${a}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await O(c,"index dataset"),c})).json()}async similarExamples(e,r,n,{filter:a}={}){let i={limit:n,inputs:e};a!==void 0&&(i.filter=a),$(r);let s=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:s});return await O(u,"fetch similar examples"),u})).json()).examples}async createExample(e,r,n){if(Zc(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let a=r?n?.datasetId:e.dataset_id,i=r?n?.datasetName:e.dataset_name;if(a===void 0&&i===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&i!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(await this.readDataset({datasetName:i})).id);let s=(r?n?.createdAt:e.created_at)||new Date,l;Zc(e)?l=e:l={inputs:e,outputs:r,created_at:s?.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 c=await this._uploadExamplesMultipart(a,[l]);return await this.readExample(c.example_ids?.[0]??ct())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let L=e,C=L[0].dataset_id,k=L[0].dataset_name;if(C===void 0&&k===void 0)throw new Error("Must provide either datasetName or datasetId");if(C!==void 0&&k!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");C===void 0&&(C=(await this.readDataset({datasetName:k})).id);let F=await this._uploadExamplesMultipart(C,L);return await Promise.all(F.example_ids.map(V=>this.readExample(V)))}let{inputs:r,outputs:n,metadata:a,splits:i,sourceRunIds:s,useSourceRunIOs:l,useSourceRunAttachments:c,attachments:u,exampleIds:p,datasetId:m,datasetName:g}=e;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let h=m,E=g;if(h===void 0&&E===void 0)throw new Error("Must provide either datasetName or datasetId");if(h!==void 0&&E!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");h===void 0&&(h=(await this.readDataset({datasetName:E})).id);let x=r.map((L,C)=>({dataset_id:h,inputs:L,outputs:n?.[C],metadata:a?.[C],split:i?.[C],id:p?.[C],attachments:u?.[C],source_run_id:s?.[C],use_source_run_io:l?.[C],use_source_run_attachments:c?.[C]})),P=await this._uploadExamplesMultipart(h,x);return await Promise.all(P.example_ids.map(L=>this.readExample(L)))}async createLLMExample(e,r,n){return this.createExample({input:e},{output:r},n)}async createChatExample(e,r,n){let a=e.map(s=>ha(s)?ga(s):s),i=ha(r)?ga(r):r;return this.createExample({input:a},{output:i},n)}async readExample(e){$(e);let r=`/examples/${e}`,n=await this._get(r),{attachment_urls:a,...i}=n,s=i;return a&&(s.attachments=Object.entries(a).reduce((l,[c,u])=>(l[c.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},l),{})),s}async*listExamples({datasetId:e,datasetName:r,exampleIds:n,asOf:a,splits:i,inlineS3Urls:s,metadata:l,limit:c,offset:u,filter:p,includeAttachments:m}={}){let g;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)g=e;else if(r!==void 0)g=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");let h=new URLSearchParams({dataset:g}),E=a?typeof a=="string"?a:a?.toISOString():void 0;E&&h.append("as_of",E);let x=s??!0;if(h.append("inline_s3_urls",x.toString()),n!==void 0)for(let N of n)h.append("id",N);if(i!==void 0)for(let N of i)h.append("splits",N);if(l!==void 0){let N=JSON.stringify(l);h.append("metadata",N)}c!==void 0&&h.append("limit",c.toString()),u!==void 0&&h.append("offset",u.toString()),p!==void 0&&h.append("filter",p),m===!0&&["attachment_urls","outputs","metadata"].forEach(N=>h.append("select",N));let P=0;for await(let N of this._getPaginated("/examples",h)){for(let L of N){let{attachment_urls:C,...k}=L,F=k;C&&(F.attachments=Object.entries(C).reduce((B,[V,_])=>(B[V.slice(11)]={presigned_url:_.presigned_url,mime_type:_.mime_type||void 0},B),{})),yield F,P++}if(c!==void 0&&P>=c)break}}async deleteExample(e){$(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 O(n,`delete ${r}`,!0),n})}async deleteExamples(e,r){if(e.forEach(n=>$(n)),r?.hardDelete){let n=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let a=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 O(a,"hard delete examples",!0),a})}else{let n=new URLSearchParams;e.forEach(a=>n.append("example_ids",a)),await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/examples?${n.toString()}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(a,"delete examples",!0),a})}}async updateExample(e,r){let n;r?n=e:n=e.id,$(n);let a;r?a={id:n,...r}:a=e;let i;return a.dataset_id!==void 0?i=a.dataset_id:i=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(i,[a])}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:a}){let i;if(e?i=e:i=(await this.readDataset({datasetName:r})).id,$(i),n&&a||!n&&!a)throw new Error("Exactly one of asOf and tag must be specified.");let s=new URLSearchParams;return n!==void 0&&s.append("as_of",typeof n=="string"?n:n.toISOString()),a!==void 0&&s.append("tag",a),await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${i}/version?${s.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:e,datasetName:r,asOf:n}){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,$(a);let i=new URLSearchParams,s=n?typeof n=="string"?n:n?.toISOString():void 0;return s&&i.append("as_of",s),await this._get(`/datasets/${a}/splits`,i)}async updateDatasetSplits({datasetId:e,datasetName:r,splitName:n,exampleIds:a,remove:i=!1}){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,$(s);let l={split_name:n,examples:a.map(u=>($(u),u)),remove:i},c=JSON.stringify(l);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${s}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await O(u,"update dataset splits",!0),u})}async createFeedback(e,r,{score:n,value:a,correction:i,comment:s,sourceInfo:l,feedbackSourceType:c="api",sourceRunId:u,feedbackId:p,feedbackConfig:m,projectId:g,comparativeExperimentId:h,sessionId:E,startTime:x}){if(!e&&!g)throw new Error("One of runId or projectId must be provided");if(e&&g)throw new Error("Only one of runId or projectId can be provided");let P={type:c??"api",metadata:l??{}};u!==void 0&&P?.metadata!==void 0&&!P.metadata.__run&&(P.metadata.__run={run_id:u}),P?.metadata!==void 0&&P.metadata.__run?.run_id!==void 0&&$(P.metadata.__run.run_id);let N={id:p??Ft(),run_id:e,key:r,score:Kc(n),value:a,correction:i,comment:s,feedback_source:P,comparative_experiment_id:h,feedbackConfig:m,session_id:E??g,start_time:x},L=JSON.stringify(N),C=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let k=await this._fetch(C,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:L});return await O(k,"create feedback",!0),k}),N}async updateFeedback(e,{score:r,value:n,correction:a,comment:i}){let s={};r!=null&&(s.score=Kc(r)),n!=null&&(s.value=n),a!=null&&(s.correction=a),i!=null&&(s.comment=i),$(e);let l=JSON.stringify(s);await this.caller.call(async()=>{let c=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:l});return await O(c,"update feedback",!0),c})}async readFeedback(e){$(e);let r=`/feedback/${e}`;return await this._get(r)}async deleteFeedback(e){$(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 O(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:r,feedbackSourceTypes:n}={}){let a=new URLSearchParams;if(e)for(let i of e)$(i),a.append("run",i);if(r)for(let i of r)a.append("key",i);if(n)for(let i of n)a.append("source",i);for await(let i of this._getPaginated("/feedback",a))yield*i}async createPresignedFeedbackToken(e,r,{expiration:n,feedbackConfig:a}={}){let i={run_id:e,feedback_key:r,feedback_config:a};n?typeof n=="string"?i.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(i.expires_in=n):i.expires_in={hours:3};let s=JSON.stringify(i);return await(await this.caller.call(async()=>{let c=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:s});return await O(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:e,experimentIds:r,referenceDatasetId:n,createdAt:a,description:i,metadata:s,id:l}){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 c={id:l,name:e,experiment_ids:r,reference_dataset_id:n,description:i,created_at:(a??new Date)?.toISOString(),extra:{}};s&&(c.extra.metadata=s);let u=JSON.stringify(c);return(await this.caller.call(async()=>{let m=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 O(m,"create comparative experiment"),m})).json()}async*listPresignedFeedbackTokens(e){$(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 a=this._selectEvalResults(e),i=[];for(let s of a){let l=n||{};s.evaluatorInfo&&(l={...s.evaluatorInfo,...l});let c=null;s.targetRunId?c=s.targetRunId:r&&(c=r.id),i.push(await this.createFeedback(c,s.key,{score:s.score,value:s.value,comment:s.comment,correction:s.correction,sourceInfo:l,sourceRunId:s.sourceRunId,feedbackConfig:s.feedbackConfig,feedbackSourceType:"model",sessionId:r?.session_id,startTime:r?.start_time}))}return[a,i]}async logEvaluationFeedback(e,r,n){let[a]=await this._logEvaluationFeedback(e,r,n);return a}async createFeedbackConfig(e){let{feedbackKey:r,feedbackConfig:n,isLowerScoreBetter:a=!1}=e,i={feedback_key:r,feedback_config:n,is_lower_score_better:a};return(await this.caller.call(async()=>{let l=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 O(l,"create feedback config"),l})).json()}async*listFeedbackConfigs(e={}){let{feedbackKeys:r,nameContains:n,limit:a}=e,i=new URLSearchParams;r&&r.forEach(l=>{i.append("key",l)}),n&&i.append("name_contains",n),i.append("limit",(a!==void 0?Math.min(a,100):100).toString());let s=0;for await(let l of this._getPaginated("/feedback-configs",i))if(yield*l,s+=l.length,a!==void 0&&s>=a)break}async updateFeedbackConfig(e,r={}){let{feedbackConfig:n,isLowerScoreBetter:a}=r,i={feedback_key:e};return n!==void 0&&(i.feedback_config=n),a!==void 0&&(i.is_lower_score_better=a),(await this.caller.call(async()=>{let l=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 O(l,"update feedback config"),l})).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 O(n,"delete feedback config",!0),n})}async*listAnnotationQueues(e={}){let{queueIds:r,name:n,nameContains:a,limit:i}=e,s=new URLSearchParams;r&&r.forEach((c,u)=>{$(c,`queueIds[${u}]`),s.append("ids",c)}),n&&s.append("name",n),a&&s.append("name_contains",a),s.append("limit",(i!==void 0?Math.min(i,100):100).toString());let l=0;for await(let c of this._getPaginated("/annotation-queues",s))if(yield*c,l++,i!==void 0&&l>=i)break}async createAnnotationQueue(e){let{name:r,description:n,queueId:a,rubricInstructions:i,rubricItems:s}=e,l={name:r,description:n,id:a||ct(),rubric_instructions:i,rubric_items:s},c=JSON.stringify(Object.fromEntries(Object.entries(l).filter(([p,m])=>m!==void 0)));return(await this.caller.call(async()=>{let p=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:c});return await O(p,"create annotation queue"),p})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${$(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,r){let{name:n,description:a,rubricInstructions:i,rubricItems:s}=r,l={};n!==void 0&&(l.name=n),a!==void 0&&(l.description=a),i!==void 0&&(l.rubric_instructions=i),s!==void 0&&(l.rubric_items=s);let c=JSON.stringify(l);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/annotation-queues/${$(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await O(u,"update annotation queue",!0),u})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${$(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(e,r){let n=JSON.stringify(r.map((a,i)=>$(a,`runIds[${i}]`).toString()));await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/annotation-queues/${$(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await O(a,"add runs to annotation queue",!0),a})}async getRunFromAnnotationQueue(e,r){let n=`/annotation-queues/${$(e,"queueId")}/run`,i=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(s,"get run from annotation queue"),s})).json();return Zt(i)}async deleteRunFromAnnotationQueue(e,r){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${$(e,"queueId")}/runs/${$(r,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(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/${$(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(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){L(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 l=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:l,apiKey:n?.apiKey,apiUrl:n?.apiUrl,workspaceId:n?.workspaceId}).catch(console.error);return}else this.processRunOperation({action:"update",item:i,otelContext:l,apiKey:n?.apiKey,apiUrl:n?.apiUrl,workspaceId:n?.workspaceId}).catch(console.error);return}let a={...this._mergedHeaders,"Content-Type":"application/json"};n?.apiKey!==void 0&&(a["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(a["x-tenant-id"]=n.workspaceId);let o=ge(r,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let l=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await C(l,"update run",!0),l})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){return se("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}){L(e);let n=yr(await this._get(`/runs/${e}`));return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(se("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:q("PROJECT")||"default"})).id;let a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/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 Pm(this._listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},i={};r.sort((a,o)=>(a?.dotted_order??"").localeCompare(o?.dotted_order??""));for(let a of r){if(a.parent_run_id===null||a.parent_run_id===void 0)throw new Error(`Child run ${a.id} has no parent`);a.dotted_order?.startsWith(e.dotted_order??"")&&a.id!==e.id&&(a.parent_run_id in n||(n[a.parent_run_id]=[]),n[a.parent_run_id].push(a),i[a.id]=a)}e.child_runs=n[e.id]||[];for(let a in n)a!==e.id&&(i[a].child_runs=n[a]);return e}async*listRuns(e){se("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:a,referenceExampleId:o,startTime:l,executionOrder:c,isRoot:u,runType:d,error:p,id:h,query:g,filter:b,traceFilter:v,treeFilter:P,limit:I,select:S,order:A}=e,R=[];if(r&&(R=Array.isArray(r)?r:[r]),n){let y=Array.isArray(n)?n:[n],K=await Promise.all(y.map(B=>this.readProject({projectName:B}).then(F=>F.id)));R.push(...K)}let $=["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:R.length?R:null,run_type:d,reference_example:o,query:g,filter:b,trace_filter:v,tree_filter:P,execution_order:c,parent_run:i,start_time:l?l.toISOString():null,error:p,id:h,limit:I,trace:a,select:S||$,is_root:u,order:A};N.select.includes("child_run_ids")&&se("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let j=0;for await(let y of this._getCursorPaginatedList("/runs/query",N)){let K=y.map(yr);if(I){if(j>=I)break;if(K.length+j>I){yield*K.slice(0,I-j);break}j+=K.length,yield*K}else yield*K}}async*listGroupRuns(e){let{projectId:r,projectName:n,groupBy:i,filter:a,startTime:o,endTime:l,limit:c,offset:u}=e,p={session_id:r||(await this.readProject({projectName:n})).id,group_by:i,filter:a,start_time:o?o.toISOString():null,end_time:l?l.toISOString():null,limit:Number(c)||100},h=Number(u)||0,g="/runs/group",b=`${this.apiUrl}${g}`;for(;;){let v={...p,offset:h},P=Object.fromEntries(Object.entries(v).filter(([N,j])=>j!==void 0)),I=JSON.stringify(P),A=await(await this.caller.call(async()=>{let N=await this._fetch(b,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:I});return await C(N,`Failed to fetch ${g}`),N})).json(),{groups:R,total:$}=A;if(R.length===0)break;for(let N of R)yield N;if(h+=R.length,h>=$)break}}async*readThread(e){se("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:a=!0,limit:o,filter:l,order:c="asc"}=e;if(!n&&!i)throw new Error("threadId requires projectId or projectName");let u=`eq(thread_id, ${JSON.stringify(r)})`,d=l?`and(${u}, ${l})`:u;yield*this._listRuns({projectId:n??void 0,projectName:i??void 0,isRoot:a,limit:o,filter:d,order:c})}async listThreads(e){se("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:a=0,filter:o,startTime:l,isRoot:c=!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=l??new Date(Date.now()-1440*60*1e3),h={session:[u],is_root:c,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&&(h.filter=o);let g=new Map;for await(let I of this._getCursorPaginatedList("/runs/query",h))for(let S of I){let A=yr(S),R=A.thread_id;if(R){let $=g.get(R)??[];$.push(A),g.set(R,$)}}let b=[];for(let[I,S]of g.entries()){S.sort((j,y)=>{let K=j,B=y,F=K.start_time??"",de=B.start_time??"";if(F!==de)return F.localeCompare(de);let tt=K.dotted_order??"",rt=B.dotted_order??"";return tt.localeCompare(rt)});let R=[...S.map(j=>j.start_time).filter(Boolean)].sort(),$=R.length?R[0]:"",N=R.length?R[R.length-1]:"";b.push({thread_id:I,runs:S,count:S.length,filter:"",total_tokens:0,total_cost:null,min_start_time:$,max_start_time:N,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}b.sort((I,S)=>{let A=I.max_start_time??"";return(S.max_start_time??"").localeCompare(A)});let v=a>0?b.slice(a):b;return i!==void 0?v.slice(0,i):v}async getRunStats({id:e,trace:r,parentRun:n,runType:i,projectNames:a,projectIds:o,referenceExampleIds:l,startTime:c,endTime:u,error:d,query:p,filter:h,traceFilter:g,treeFilter:b,isRoot:v,dataSourceType:P}){let I=o||[];if(a&&(I=[...o||[],...await Promise.all(a.map(j=>this.readProject({projectName:j}).then(y=>y.id)))]),I.length===0)throw new Error("At least one of projectNames or projectIds must be provided.");let A=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:i,session:I,reference_example:l,start_time:c,end_time:u,error:d,query:p,filter:h,trace_filter:g,tree_filter:b,is_root:v,data_source_type:P}).filter(([j,y])=>y!==void 0)),R=JSON.stringify(A);return await(await this.caller.call(async()=>{let j=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:R});return await C(j,"get run stats"),j})).json()}async shareRun(e,{shareId:r}={}){se("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||Et()};L(e);let i=JSON.stringify(n),o=await(await this.caller.call(async()=>{let l=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 C(l,"share run"),l})).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){se("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"}),L(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 C(r,"unshare run",!0),r})}async readRunSharedLink(e){se('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"}),L(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 C(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}={}){se("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 L(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 C(o,"list shared runs"),o})).json()).map(yr)}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),L(e);let i=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(a,"read dataset shared schema"),a})).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};L(e);let i=JSON.stringify(n),o=await(await this.caller.call(async()=>{let l=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 C(l,"share dataset"),l})).json();return o.url=`${this.getHostUrl()}/public/${o.share_token}/d`,o}async unshareDataset(e){L(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 C(r,"unshare dataset",!0),r})}async readSharedDataset(e){return L(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 C(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(([l,c])=>{Array.isArray(c)?c.forEach(u=>i.append(l,u)):i.append(l,c)});let a=await this.caller.call(async()=>{let l=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 C(l,"list shared examples"),l}),o=await a.json();if(!a.ok)throw"detail"in o?new Error(`Failed to list shared examples.
133
+ Status: ${a.status}
134
+ Message: ${Array.isArray(o.detail)?o.detail.join(`
135
+ `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${a.status} ${a.statusText}`);return o.map(l=>({...l,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:i=!1,projectExtra:a=null,referenceDatasetId:o=null,numExamples:l=null,numRepetitions:c=null,evaluatorKeys:u=null}){let d=i?"?upsert=true":"",p=`${this.apiUrl}/sessions${d}`,h=a||{};n&&(h.metadata=n);let g={name:e,extra:h,description:r};o!==null&&(g.reference_dataset_id=o),l!=null&&(g.num_examples=l),c!=null&&(g.num_repetitions=c),u!=null&&u.length>0&&(g.evaluator_keys=u);let b=JSON.stringify(g);return await(await this.caller.call(async()=>{let I=await this._fetch(p,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:b});return await C(I,"create project"),I})).json()}async updateProject(e,{name:r=null,description:n=null,metadata:i=null,projectExtra:a=null,endTime:o=null}){let l=`${this.apiUrl}/sessions/${e}`,c=a;i&&(c={...c||{},metadata:i});let u=JSON.stringify({name:r,extra:c,description:n,end_time:o?new Date(o).toISOString():null});return await(await this.caller.call(async()=>{let h=await this._fetch(l,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await C(h,"update project"),h})).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)L(e),n+=`/${e}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");let a=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 C(o,"has project"),o});try{let o=await a.json();return a.ok?Array.isArray(o)?o.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let i="/sessions",a=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)L(e),i+=`/${e}`;else if(r!==void 0)a.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&a.append("include_stats",n.toString());let o=await this._get(i,a),l;if(Array.isArray(o)){if(o.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);l=o[0]}else l=o;return l}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:a,includeStats:o,datasetVersion:l,referenceFree:c,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),i!==void 0)d.append("reference_dataset",i);else if(a!==void 0){let p=await this.readDataset({datasetName:a});d.append("reference_dataset",p.id)}o!==void 0&&d.append("include_stats",o.toString()),l!==void 0&&d.append("dataset_version",l),c!==void 0&&d.append("reference_free",c.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,L(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 C(i,`delete session ${n} (${r})`,!0),i})}async uploadCsv({csvFile:e,fileName:r,inputKeys:n,outputKeys:i,description:a,dataType:o,name:l}){let c=`${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)}),i.forEach(g=>{u.append("output_keys",g)}),a&&u.append("description",a),o&&u.append("data_type",o),l&&u.append("name",l),await(await this.caller.call(async()=>{let g=await this._fetch(c,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await C(g,"upload CSV"),g})).json()}async createDataset(e,{description:r,dataType:n,inputsSchema:i,outputsSchema:a,metadata:o}={}){let l={name:e,description:r,extra:{source:"sdk",...o?{metadata:o}:{}}};n&&(l.data_type=n),i&&(l.inputs_schema_definition=i),a&&(l.outputs_schema_definition=a);let c=JSON.stringify(l);return await(await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await C(p,"create dataset"),p})).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)L(e),n+=`/${e}`;else if(r)i.append("name",r);else throw new Error("Must provide datasetName or datasetId");let a=await this._get(n,i),o;if(Array.isArray(a)){if(a.length===0)throw new Error(`Dataset[id=${e}, name=${r}] not found`);o=a[0]}else o=a;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 a=e;if(a===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(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/${a}/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(l=>JSON.parse(l))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:i,datasetNameContains:a,metadata:o}={}){let l="/datasets",c=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(let u of n)c.append("id",u);i!==void 0&&c.append("name",i),a!==void 0&&c.append("name_contains",a),o!==void 0&&c.append("metadata",JSON.stringify(o));for await(let u of this._getPaginated(l,c))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 a=r??(await this.readDataset({datasetName:n})).id;L(a);let o=JSON.stringify(i);return await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${a}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await C(c,"update dataset"),c})).json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:i,tag:a}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let o=r??(await this.readDataset({datasetName:n})).id;L(o);let l=JSON.stringify({as_of:typeof i=="string"?i:i.toISOString(),tag:a});await this.caller.call(async()=>{let c=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:l});return await C(c,"update dataset tags",!0),c})}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)L(i),n+=`/${i}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let a=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(a,`delete ${n}`,!0),a})}async createExample(e,r,n){if(Fc(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,a=r?n?.datasetName:e.dataset_name;if(i===void 0&&a===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&a!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:a})).id);let o=(r?n?.createdAt:e.created_at)||new Date,l;Fc(e)?l=e:l={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 c=await this._uploadExamplesMultipart(i,[l]);return await this.readExample(c.example_ids?.[0]??Et())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let S=e,A=S[0].dataset_id,R=S[0].dataset_name;if(A===void 0&&R===void 0)throw new Error("Must provide either datasetName or datasetId");if(A!==void 0&&R!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");A===void 0&&(A=(await this.readDataset({datasetName:R})).id);let $=await this._uploadExamplesMultipart(A,S);return await Promise.all($.example_ids.map(j=>this.readExample(j)))}let{inputs:r,outputs:n,metadata:i,splits:a,sourceRunIds:o,useSourceRunIOs:l,useSourceRunAttachments:c,attachments:u,exampleIds:d,datasetId:p,datasetName:h}=e;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let g=p,b=h;if(g===void 0&&b===void 0)throw new Error("Must provide either datasetName or datasetId");if(g!==void 0&&b!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");g===void 0&&(g=(await this.readDataset({datasetName:b})).id);let v=r.map((S,A)=>({dataset_id:g,inputs:S,outputs:n?.[A],metadata:i?.[A],split:a?.[A],id:d?.[A],attachments:u?.[A],source_run_id:o?.[A],use_source_run_io:l?.[A],use_source_run_attachments:c?.[A]})),P=await this._uploadExamplesMultipart(g,v);return await Promise.all(P.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=>da(o)?pa(o):o),a=da(r)?pa(r):r;return this.createExample({input:i},{output:a},n)}async readExample(e){L(e);let r=`/examples/${e}`,n=await this._get(r),{attachment_urls:i,...a}=n,o=a;return i&&(o.attachments=Object.entries(i).reduce((l,[c,u])=>(l[c.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},l),{})),o}async*listExamples({datasetId:e,datasetName:r,exampleIds:n,asOf:i,splits:a,inlineS3Urls:o,metadata:l,limit:c,offset:u,filter:d,includeAttachments:p}={}){let h;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)h=e;else if(r!==void 0)h=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");let g=new URLSearchParams({dataset:h}),b=i?typeof i=="string"?i:i?.toISOString():void 0;b&&g.append("as_of",b);let v=o??!0;if(g.append("inline_s3_urls",v.toString()),n!==void 0)for(let I of n)g.append("id",I);if(a!==void 0)for(let I of a)g.append("splits",I);if(l!==void 0){let I=JSON.stringify(l);g.append("metadata",I)}c!==void 0&&g.append("limit",c.toString()),u!==void 0&&g.append("offset",u.toString()),d!==void 0&&g.append("filter",d),p===!0&&["attachment_urls","outputs","metadata"].forEach(I=>g.append("select",I));let P=0;for await(let I of this._getPaginated("/examples",g)){for(let S of I){let{attachment_urls:A,...R}=S,$=R;A&&($.attachments=Object.entries(A).reduce((N,[j,y])=>(N[j.slice(11)]={presigned_url:y.presigned_url,mime_type:y.mime_type||void 0},N),{})),yield $,P++}if(c!==void 0&&P>=c)break}}async deleteExample(e){L(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 C(n,`delete ${r}`,!0),n})}async deleteExamples(e,r){if(e.forEach(n=>L(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 C(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 C(i,"delete examples",!0),i})}}async updateExample(e,r){let n;r?n=e:n=e.id,L(n);let i;r?i={id:n,...r}:i=e;let a;return i.dataset_id!==void 0?a=i.dataset_id:a=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(a,[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 a;if(e?a=e:a=(await this.readDataset({datasetName:r})).id,L(a),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 c=await this._fetch(`${this.apiUrl}/datasets/${a}/version?${o.toString()}`,{method:"GET",headers:{...this._mergedHeaders},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(c,"read dataset version"),c})).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,L(i);let a=new URLSearchParams,o=n?typeof n=="string"?n:n?.toISOString():void 0;return o&&a.append("as_of",o),await this._get(`/datasets/${i}/splits`,a)}async updateDatasetSplits({datasetId:e,datasetName:r,splitName:n,exampleIds:i,remove:a=!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,L(o);let l={split_name:n,examples:i.map(u=>(L(u),u)),remove:a},c=JSON.stringify(l);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:c});return await C(u,"update dataset splits",!0),u})}async createFeedback(e,r,n){let{runId:i=null,key:a,score:o,value:l,correction:c,comment:u,sourceInfo:d,feedbackSourceType:p="api",sourceRunId:h,feedbackId:g,feedbackConfig:b,projectId:v,comparativeExperimentId:P,sessionId:I,startTime:S,extendTraceRetention:A}=typeof e=="object"&&e!==null?e:{runId:e,key:r,...n};if(!i&&!v)throw new Error("One of runId or projectId must be provided");if(i&&v)throw new Error("Only one of runId or projectId can be provided");i&&I===void 0&&await this._checkFeedbackSessionId();let R={type:p??"api",metadata:d??{}};h!==void 0&&R?.metadata!==void 0&&!R.metadata.__run&&(R.metadata.__run={run_id:h}),R?.metadata!==void 0&&R.metadata.__run?.run_id!==void 0&&L(R.metadata.__run.run_id);let $={id:g??Xt(),run_id:i,key:a,score:$c(o),value:l,correction:c,comment:u,feedback_source:R,comparative_experiment_id:P,feedbackConfig:b,session_id:I??v,start_time:S,extend_trace_retention:A},N=JSON.stringify($),j=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let y=await this._fetch(j,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:N});return await C(y,"create feedback",!0),y}),$}async updateFeedback(e,{score:r,value:n,correction:i,comment:a}){let o={};r!=null&&(o.score=$c(r)),n!=null&&(o.value=n),i!=null&&(o.correction=i),a!=null&&(o.comment=a),L(e);let l=JSON.stringify(o);await this.caller.call(async()=>{let c=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:l});return await C(c,"update feedback",!0),c})}async readFeedback(e){L(e);let r=`/feedback/${e}`;return await this._get(r)}async deleteFeedback(e){L(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 C(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:r,feedbackSourceTypes:n}={}){let i=new URLSearchParams;if(e)for(let a of e)L(a),i.append("run",a);if(r)for(let a of r)i.append("key",a);if(n)for(let a of n)i.append("source",a);for await(let a of this._getPaginated("/feedback",i))yield*a}async createPresignedFeedbackToken(e,r,{expiration:n,feedbackConfig:i}={}){let a={run_id:e,feedback_key:r,feedback_config:i};n?typeof n=="string"?a.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(a.expires_in=n):a.expires_in={hours:3};let o=JSON.stringify(a);return await(await this.caller.call(async()=>{let c=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 C(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:e,experimentIds:r,referenceDatasetId:n,createdAt:i,description:a,metadata:o,id:l}){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 c={id:l,name:e,experiment_ids:r,reference_dataset_id:n,description:a,created_at:(i??new Date)?.toISOString(),extra:{}};o&&(c.extra.metadata=o);let u=JSON.stringify(c);return(await this.caller.call(async()=>{let p=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 C(p,"create comparative experiment"),p})).json()}async*listPresignedFeedbackTokens(e){L(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 a=this._selectEvalResults(e),o=[];for(let l of a){let c=n||{};l.evaluatorInfo&&(c={...l.evaluatorInfo,...c});let u=null;l.targetRunId?u=l.targetRunId:r&&(u=r.id),o.push(await this.createFeedback(u,l.key,{score:l.score,value:l.value,comment:l.comment,correction:l.correction,sourceInfo:c,sourceRunId:l.sourceRunId,feedbackConfig:l.feedbackConfig,feedbackSourceType:"model",sessionId:r?.session_id??i,startTime:r?.start_time}))}return[a,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[a]=await this._logEvaluationFeedback(e,r,n,i);return a}async createFeedbackConfig(e){let{feedbackKey:r,feedbackConfig:n,isLowerScoreBetter:i=!1}=e,a={feedback_key:r,feedback_config:n,is_lower_score_better:i};return(await this.caller.call(async()=>{let l=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(a)});return await C(l,"create feedback config"),l})).json()}async*listFeedbackConfigs(e={}){let{feedbackKeys:r,nameContains:n,limit:i}=e,a=new URLSearchParams;r&&r.forEach(l=>{a.append("key",l)}),n&&a.append("name_contains",n),a.append("limit",(i!==void 0?Math.min(i,100):100).toString());let o=0;for await(let l of this._getPaginated("/feedback-configs",a))if(yield*l,o+=l.length,i!==void 0&&o>=i)break}async updateFeedbackConfig(e,r={}){let{feedbackConfig:n,isLowerScoreBetter:i}=r,a={feedback_key:e};return n!==void 0&&(a.feedback_config=n),i!==void 0&&(a.is_lower_score_better=i),(await this.caller.call(async()=>{let l=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(a)});return await C(l,"update feedback config"),l})).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 C(n,"delete feedback config",!0),n})}async*listAnnotationQueues(e={}){let{queueIds:r,name:n,nameContains:i,limit:a}=e,o=new URLSearchParams;r&&r.forEach((c,u)=>{L(c,`queueIds[${u}]`),o.append("ids",c)}),n&&o.append("name",n),i&&o.append("name_contains",i),o.append("limit",(a!==void 0?Math.min(a,100):100).toString());let l=0;for await(let c of this._getPaginated("/annotation-queues",o))if(yield*c,l++,a!==void 0&&l>=a)break}async createAnnotationQueue(e){let{name:r,description:n,queueId:i,rubricInstructions:a,rubricItems:o}=e,l={name:r,description:n,id:i||Et(),rubric_instructions:a,rubric_items:o},c=JSON.stringify(Object.fromEntries(Object.entries(l).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._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await C(d,"create annotation queue"),d})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${L(e,"queueId")}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,r){let{name:n,description:i,rubricInstructions:a,rubricItems:o}=r,l={};n!==void 0&&(l.name=n),i!==void 0&&(l.description=i),a!==void 0&&(l.rubric_instructions=a),o!==void 0&&(l.rubric_items=o);let c=JSON.stringify(l);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/annotation-queues/${L(e,"queueId")}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await C(u,"update annotation queue",!0),u})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${L(e,"queueId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(e,r){let n=`${this.apiUrl}/annotation-queues/${L(e,"queueId")}/runs`,i=r.every(l=>typeof l=="string"),a,o;i?(se("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"}),a=n,o=JSON.stringify(r.map((l,c)=>L(l,`runs[${c}]`).toString()))):(a=`${n}/by-key`,o=JSON.stringify(r.map((l,c)=>{let u={run_id:L(l.runId,`runs[${c}].runId`).toString(),session_id:L(l.sessionId,`runs[${c}].sessionId`).toString(),start_time:typeof l.startTime=="string"?l.startTime:new Date(l.startTime).toISOString()};return l.sourceProposedExampleId!=null&&(u.source_proposed_example_id=L(l.sourceProposedExampleId,`runs[${c}].sourceProposedExampleId`).toString()),u}))),await this.caller.call(async()=>{let l=await this._fetch(a,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await C(l,"add runs to annotation queue",!0),l})}async getRunFromAnnotationQueue(e,r){let n=`/annotation-queues/${L(e,"queueId")}/run`,a=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 C(o,"get run from annotation queue"),o})).json();return yr(a)}async*listRunsFromAnnotationQueue(e,r={}){let{status:n,limit:i}=r,a=new URLSearchParams,o=i!==void 0&&Number.isFinite(i)?Math.min(i,100):100;n&&a.append("status",n),a.append("limit",o.toString());let l=0,c=`/annotation-queues/${L(e,"queueId")}/runs`;for await(let u of this._getPaginated(c,a))for(let d of u)if(yield yr(d),l++,l>=o)return}async deleteRunFromAnnotationQueue(e,r){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${L(e,"queueId")}/runs/${L(r,"queueRunId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(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/${L(e,"queueId")}/size`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(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.
35
137
 
36
138
  Current tenant: ${n.tenant_handle}
37
139
 
38
- Requested tenant: ${r}`)}async _getLatestCommitHash(e){let n=await(await this.caller.call(async()=>{let a=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 O(a,"get latest commit hash"),a})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,r){let[n,a,i]=Ge(e),s=JSON.stringify({like:r});return(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/likes/${n}/${a}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await O(c,`${r?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(e){let[r,n,a]=Ge(e);if(await this._currentTenantIsOwner(r)){let i=await this._getSettings();return a!=="latest"?`${this.getHostUrl()}/prompts/${n}/${a.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${i.id}`}else return a!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${a.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,a]=Ge(e);for await(let i of this._getPaginated(`/commits/${r}/${n}/`,new URLSearchParams,s=>s.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,a=>a.repos))yield*n}async getPrompt(e){let[r,n,a]=Ge(e),s=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return l?.status===404?null:(await O(l,"get prompt"),l)}))?.json();return s?.repo?s.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 C(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 a=>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:a,commit_id:r})});return await C(o,"create commit tag"),o})))}async _likeOrUnlikePrompt(e,r){let[n,i,a]=he(e),o=JSON.stringify({like:r});return(await this.caller.call(async()=>{let c=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 C(c,`${r?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(e){let[r,n,i]=he(e);if(await this._currentTenantIsOwner(r)){let a=await this._getSettings();return i!=="latest"?`${this.getHostUrl()}/prompts/${n}/${i.substring(0,8)}?organizationId=${a.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${a.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]=he(e);for await(let a of this._getPaginated(`/commits/${r}/${n}/`,new URLSearchParams,o=>o.commits))yield*a}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]=he(e),o=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return l?.status===404?null:(await C(l,"get prompt"),l)}))?.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
39
141
 
40
142
  creating a LangChain Hub handle.
41
143
  You can add a handle by creating a public prompt at:
42
144
 
43
- https://smith.langchain.com/prompts`);let[a,i,s]=Ge(e);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("create a prompt",a);let l={repo_handle:i,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},c=JSON.stringify(l),u=await this.caller.call(async()=>{let m=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await O(m,"create prompt"),m}),{repo:p}=await u.json();return p}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[a,i,s]=Ge(e),l=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${a}/${i}`):n?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(r)),parent_commit:l},u=JSON.stringify(c),m=await(await this.caller.call(async()=>{let g=await this._fetch(`${this.apiUrl}/commits/${a}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await O(g,"create commit"),g})).json();return this._getPromptUrl(`${a}/${i}${m.commit_hash?`:${m.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 s of r){let l=s.id,c={...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split}},u=_e(c,`Serializing body for example with id: ${l}`),p=new Blob([u],{type:"application/json"});if(n.append(l,p),s.inputs){let m=_e(s.inputs,`Serializing inputs for example with id: ${l}`),g=new Blob([m],{type:"application/json"});n.append(`${l}.inputs`,g)}if(s.outputs){let m=_e(s.outputs,`Serializing outputs whle updating example with id: ${l}`),g=new Blob([m],{type:"application/json"});n.append(`${l}.outputs`,g)}if(s.attachments)for(let[m,g]of Object.entries(s.attachments)){let h,E;Array.isArray(g)?[h,E]=g:(h=g.mimeType,E=g.data);let x=new Blob([E],{type:`${h}; length=${E.byteLength}`});n.append(`${l}.attachment.${m}`,x)}if(s.attachments_operations){let m=_e(s.attachments_operations,`Serializing attachments while updating example with id: ${l}`),g=new Blob([m],{type:"application/json"});n.append(`${l}.attachments_operations`,g)}}let a=e??r[0]?.dataset_id;return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${a}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await O(s,"update examples"),s})).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 s=(i.id??ct()).toString(),l={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}},c=_e(l,`Serializing body for uploaded example with id: ${s}`),u=new Blob([c],{type:"application/json"});if(n.append(s,u),i.inputs){let p=_e(i.inputs,`Serializing inputs for uploaded example with id: ${s}`),m=new Blob([p],{type:"application/json"});n.append(`${s}.inputs`,m)}if(i.outputs){let p=_e(i.outputs,`Serializing outputs for uploaded example with id: ${s}`),m=new Blob([p],{type:"application/json"});n.append(`${s}.outputs`,m)}if(i.attachments)for(let[p,m]of Object.entries(i.attachments)){let g,h;Array.isArray(m)?[g,h]=m:(g=m.mimeType,h=m.data);let E=new Blob([h],{type:`${g}; length=${h.byteLength}`});n.append(`${s}.attachment.${p}`,E)}}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 O(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,a]=Ge(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 s=JSON.stringify(i);return(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/repos/${n}/${a}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await O(c,"update prompt"),c})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[r,n,a]=Ge(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(s,"delete prompt"),s})).json()}_getPromptCacheKey(e,r){return`${e}${r?":with_model":""}`}async _fetchPromptFromApi(e,r){let[n,a,i]=Ge(e),l=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/commits/${n}/${a}/${i}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(c,"pull prompt commit"),c})).json();return{owner:n,repo:a,commit_hash:l.commit_hash,manifest:l.manifest,examples:l.examples}}async pullPromptCommit(e,r){let n=this._fetchPromptFromApi.bind(this,e,r);if(!r?.skipCache&&this._promptCache){let a=this._getPromptCacheKey(e,r?.includeModel),i=this._promptCache.get(a,n);if(i)return i;let s=await n();return this._promptCache.set(a,s,n),s}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(a=>a!=="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:a}=r,[i,s]=this.parseTokenOrUrl(e,n),l=new t({apiUrl:i,apiKey:"placeholder"}),c=await l.readSharedDataset(s),u=a||c.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}let p=await l.listSharedExamples(s),m=await this.createDataset(u,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:p.map(g=>g.inputs),outputs:p.flatMap(g=>g.outputs?[g.outputs]:[]),datasetId:m.id})}catch(g){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),g}}parseTokenOrUrl(e,r,n=2,a="dataset"){try{return $(e),[r,e]}catch{}try{let s=new URL(e).pathname.split("/").filter(l=>l!=="");if(s.length>=n){let l=s[s.length-n];return[r,l]}else throw new Error(`Invalid public ${a} URL: ${e}`)}catch{throw new Error(`Invalid public ${a} 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 Zo()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}};Object.defineProperty(tt,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function Zc(t){return"dataset_id"in t||"dataset_name"in t}o(Zc,"isExampleCreate");var Xc=o(t=>t!==void 0?t:!!["TRACING_V2","TRACING"].find(r=>J(r)==="true"),"isTracingEnabled");var He=Symbol.for("lc:context_variables");var sn=Symbol.for("langsmith:replica_trace_roots");function Ga(t,e){if(He in t)return t[He][e]}o(Ga,"getContextVar");function Qc(t,e,r){let n=He in t?t[He]:{};n[e]=r,t[He]=n}o(Qc,"setContextVar");var Yt=36,jg="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function eu(t){let r=Object.keys(t).sort().map(n=>`${n}:${t[n]??""}`).join("|");return Vn(r,jg)}o(eu,"getReplicaKey");function Bg(t){return t.replace(/[-:.]/g,"")}o(Bg,"stripNonAlphanumeric");function ru(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(ru,"getMicrosecondPrecisionDatestring");function Ha(t,e,r=1){let n=ru(t,r);return{dottedOrder:Bg(n)+e,microsecondPrecisionDatestring:n}}o(Ha,"convertToDottedOrderFormat");var Gg=new Set(["projectName","updates","reroot"]);function Hg(t){let e={};for(let r of Object.keys(t))Gg.has(r)&&(e[r]=t[r]);return e}o(Hg,"filterReplicaForHeaders");var on=class t{static{o(this,"Baggage")}constructor(e,r,n,a){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=a}static fromHeader(e){let r=e.split(","),n={},a=[],i,s;for(let l of r){let[c,u]=l.split("="),p=decodeURIComponent(u);c==="langsmith-metadata"?n=JSON.parse(p):c==="langsmith-tags"?a=p.split(","):c==="langsmith-project"?i=p:c==="langsmith-replicas"&&(s=JSON.parse(p).map(g=>Array.isArray(g)?g:Hg(g)))}return new t(n,a,i,s)}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(",")}},$e=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}),nu(e)){Object.assign(this,{...e});return}let r=t.getDefaultConfig(),{metadata:n,...a}=e,i=a.client??t.getSharedClient(),s={...n,...a?.extra?.metadata};if(a.extra={...a.extra,metadata:s},"id"in a&&a.id==null&&delete a.id,Object.assign(this,{...r,...a,client:i}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=ru(this.start_time,this.execution_order)),this.id||(this.id=Mr(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=Wg(this.replicas),!this.dotted_order){let{dottedOrder:l}=Ha(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+l:this.dotted_order=l}}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:Ut(),child_runs:[],api_url:Te("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Te("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return t.sharedClient||(t.sharedClient=new tt),t.sharedClient}createChild(e){let r=this.child_execution_order+1,n=this.replicas?.map(g=>{let{reroot:h,...E}=g;return E}),a=e.replicas??n,i=new t({...e,parent_run:this,project_name:this.project_name,replicas:a,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r}),s=this.extra?.metadata??{},l=i.extra?.metadata??{};Object.keys(s).length>0&&(i.extra={...i.extra,metadata:{...s,...l}}),He in this&&(i[He]=this[He]);let c=Symbol.for("lc:child_config"),u=e.extra?.[c]??this.extra[c];if(Vg(u)){let g={...u},h=zg(g.callbacks)?g.callbacks.copy?.():void 0;h&&(Object.assign(h,{_parentRunId:i.id}),h.handlers?.find(au)?.updateFromRunTree?.(i),g.callbacks=h),i.extra[c]=g}let p=new Set,m=this;for(;m!=null&&!p.has(m.id);)p.add(m.id),m.child_execution_order=Math.max(m.child_execution_order,r),m=m.parent_run;return this.child_runs.push(i),i}async end(e,r,n=Date.now(),a){this.outputs=this.outputs??e,this.error=this.error??r,this.end_time=this.end_time??n,a&&Object.keys(a).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...a}}:{metadata:a})}_convertToCreate(e,r,n=!0){let a=e.extra??{};if(a?.runtime?.library===void 0&&(a.runtime||(a.runtime={}),r))for(let[l,c]of Object.entries(r))a.runtime[l]||(a.runtime[l]=c);let i=e.parent_run?.id??e.parent_run_id,s;return n?s=[]:s=e.child_runs.map(l=>this._convertToCreate(l,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:a,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:s,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("."),a=null;for(let i=0;i<n.length;i++)if(n[i].slice(-Yt)===e){a=i;break}if(a!==null){let i=n.slice(a+1);r.dotted_order=i.join("."),i.length>0?r.trace_id=i[0].slice(-Yt):r.trace_id=r.id}}r.parent_run_id===e&&(r.parent_run_id=void 0)}_setReplicaTraceRoot(e,r){let n=Ga(this,sn)??{};n[e]=r,Qc(this,sn,n);for(let a of this.child_runs)a._setReplicaTraceRoot(e,r)}_remapForProject(e){let{projectName:r,runtimeEnv:n,excludeChildRuns:a=!0,reroot:i=!1,distributedParentId:s,apiUrl:l,apiKey:c,workspaceId:u}=e,p=this._convertToCreate(this,n,a);if(r===this.project_name)return{...p,session_name:r};if(i){if(s)this._sliceParentId(s,p);else if(p.parent_run_id=void 0,p.dotted_order){let L=p.dotted_order.split(".");L.length>0&&(p.dotted_order=L[L.length-1],p.trace_id=p.id)}let N=eu({projectName:r,apiUrl:l,apiKey:c,workspaceId:u});this._setReplicaTraceRoot(N,p.id)}let m;if(!i){let N=Ga(this,sn)??{},L=eu({projectName:r,apiUrl:l,apiKey:c,workspaceId:u});if(m=N[L],m&&(p.trace_id=m,p.dotted_order)){let C=p.dotted_order.split("."),k=null;for(let F=0;F<C.length;F++)if(C[F].slice(-Yt)===m){k=F;break}if(k!==null){let F=C.slice(k);p.dotted_order=F.join(".")}}}let g=p.id,h=jt(g,r),E;p.trace_id?E=jt(p.trace_id,r):E=h;let x;p.parent_run_id&&(x=jt(p.parent_run_id,r));let P;return p.dotted_order&&(P=p.dotted_order.split(".").map(C=>{let k=C.slice(-Yt),F=jt(k,r);return C.slice(0,-Yt)+F}).join(".")),{...p,id:h,trace_id:E,parent_run_id:x,dotted_order:P,session_name:r}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let r=Lr();if(this.replicas&&this.replicas.length>0)for(let{projectName:n,apiKey:a,apiUrl:i,workspaceId:s,reroot:l}of this.replicas){let c=this._remapForProject({projectName:n??this.project_name,runtimeEnv:r,excludeChildRuns:!0,reroot:l,distributedParentId:this.distributedParentId,apiUrl:i,apiKey:a,workspaceId:s});await this.client.createRun(c,{apiKey:a,apiUrl:i,workspaceId:s})}else{let n=this._convertToCreate(this,r,e);await this.client.createRun(n)}if(!e){ut("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:a,workspaceId:i,updates:s,reroot:l}of this.replicas){let c=this._remapForProject({projectName:r??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:l,distributedParentId:this.distributedParentId,apiUrl:a,apiKey:n,workspaceId:i}),u={id:c.id,name:c.name,run_type:c.run_type,start_time:c.start_time,outputs:c.outputs,error:c.error,parent_run_id:c.parent_run_id,session_name:c.session_name,reference_example_id:c.reference_example_id,end_time:c.end_time,dotted_order:c.dotted_order,trace_id:c.trace_id,events:c.events,tags:c.tags,extra:c.extra,attachments:this.attachments,...s};e?.excludeInputs||(u.inputs=c.inputs),await this.client.updateRun(c.id,u,{apiKey:n,apiUrl:a,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,a,i,s,l=Xc();if(n){let u=n?.getParentRunId?.()??"",p=n?.handlers?.find(m=>m?.name=="langchain_tracer");a=p?.getRun?.(u),i=p?.projectName,s=p?.client,l=l||!!p}return a?new t({name:a.name,id:a.id,trace_id:a.trace_id,dotted_order:a.dotted_order,client:s,tracingEnabled:l,project_name:i,tags:[...new Set((a?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...a?.extra?.metadata,...e?.metadata}}}).createChild(r):new t({...r,client:s,tracingEnabled:l,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,a=n["langsmith-trace"];if(!a||typeof a!="string")return;let i=a.trim(),s=i.split(".").map(p=>{let[m,g]=p.split("Z");return{strTime:m,time:Date.parse(m+"Z"),uuid:g}}),l=s[0].uuid,c={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:s.at(-1)?.uuid,trace_id:l,dotted_order:i};if(n.baggage&&typeof n.baggage=="string"){let p=on.fromHeader(n.baggage);c.metadata=p.metadata,c.tags=p.tags,c.project_name=p.project_name,c.replicas=p.replicas}let u=new t(c);return u.distributedParentId=u.id,u}toHeaders(e){let r={"langsmith-trace":this.dotted_order,baggage:new on(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[n,a]of Object.entries(r))e.set(n,a);return r}};Object.defineProperty($e,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function nu(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}o(nu,"isRunTree");function au(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}o(au,"isLangChainTracerLike");function tu(t){return Array.isArray(t)&&t.some(e=>au(e))}o(tu,"containsLangChainTracerLike");function zg(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}o(zg,"isCallbackManagerLike");function Vg(t){let e=t?.callbacks;return t!=null&&typeof e=="object"&&(tu(e?.handlers)||tu(e))}o(Vg,"isRunnableConfigLike");function qg(){let t=Te("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){Kg(e);let r=[];for(let[n,a]of Object.entries(e)){let i=n.replace(/\/$/,"");if(typeof a=="string")r.push({apiUrl:i,apiKey:a});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof a}`);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(Hc(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(qg,"_getWriteReplicasFromEnv");function Wg(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):qg()}o(Wg,"_ensureWriteReplicas");function Kg(t){if(Object.keys(t).length>0&&J("ENDPOINT"))throw new en}o(Kg,"_checkEndpointEnvUnset");var Jg=o(t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t},"convertRunTreeToRun");function Va(t,e){if(t)return new $e({...t,start_time:t._serialized_start_time??t.start_time,parent_run:Va(e),child_runs:t.child_runs.map(r=>Va(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:Ls()},tracingEnabled:!1})}o(Va,"convertRunToRunTree");function za(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}o(za,"_coerceToDict");function Ct(t){return typeof t._addRunToRunMap=="function"}o(Ct,"isBaseTracer");var ft=class extends vt{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?Jg(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`
44
-
45
- ${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,e){t.child_runs.push(e)}_addRunToRunMap(t){let{dottedOrder:e,microsecondPrecisionDatestring:r}=Ha(new Date(t.start_time).getTime(),t.id,t.execution_order),n={...t},a=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?a?(this._addChildRun(a,n),a.child_execution_order=Math.max(a.child_execution_order,n.child_execution_order),n.trace_id=a.trace_id,a.dotted_order!==void 0&&(n.dotted_order=[a.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=Va(n,a);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,a,i,s,l){let c=this._getExecutionOrder(n),u=Date.now(),p=s?{...a,metadata:s}:a,m={id:r,name:l??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:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:p??{},tags:i||[]};return this._addRunToRunMap(m)}async handleLLMStart(t,e,r,n,a,i,s,l){let c=this.getRunById(r)??this._createRunForLLMStart(t,e,r,n,a,i,s,l);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(t,e,r,n,a,i,s,l){let c=this._getExecutionOrder(n),u=Date.now(),p=s?{...a,metadata:s}:a,m={id:r,name:l??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:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:p??{},tags:i||[]};return this._addRunToRunMap(m)}async handleChatModelStart(t,e,r,n,a,i,s,l){let c=this.getRunById(r)??this._createRunForChatModelStart(t,e,r,n,a,i,s,l);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(t,e,r,n,a){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,...a},await this.onLLMEnd?.(i),await this._endTrace(i),i}async handleLLMError(t,e,r,n,a){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,...a},await this.onLLMError?.(i),await this._endTrace(i),i}_createRunForChainStart(t,e,r,n,a,i,s,l,c){let u=this._getExecutionOrder(n),p=Date.now(),m={id:r,name:l??t.id[t.id.length-1],parent_run_id:n,start_time:p,serialized:t,events:[{name:"start",time:new Date(p).toISOString()}],inputs:e,execution_order:u,child_execution_order:u,run_type:s??"chain",child_runs:[],extra:i?{...c,metadata:i}:{...c},tags:a||[]};return this._addRunToRunMap(m)}async handleChainStart(t,e,r,n,a,i,s,l){let c=this.getRunById(r)??this._createRunForChainStart(t,e,r,n,a,i,s,l);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(t,e,r,n,a){let i=this.getRunById(e);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=za(t,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),a?.inputs!==void 0&&(i.inputs=za(a.inputs,"input")),await this.onChainEnd?.(i),await this._endTrace(i),i}async handleChainError(t,e,r,n,a){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()}),a?.inputs!==void 0&&(i.inputs=za(a.inputs,"input")),await this.onChainError?.(i),await this._endTrace(i),i}_createRunForToolStart(t,e,r,n,a,i,s){let l=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:s??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:e},execution_order:l,child_execution_order:l,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(u)}async handleToolStart(t,e,r,n,a,i,s){let l=this.getRunById(r)??this._createRunForToolStart(t,e,r,n,a,i,s);return await this.onRunCreate?.(l),await this.onToolStart?.(l),l}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,a,i,s){let l=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:s??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:e},execution_order:l,child_execution_order:l,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(t,e,r,n,a,i,s){let l=this.getRunById(r)??this._createRunForRetrieverStart(t,e,r,n,a,i,s);return await this.onRunCreate?.(l),await this.onRetrieverStart?.(l),l}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,a,i){let s=this.getRunById(r);if(!s||s?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return s.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:t,idx:e,chunk:i?.chunk}}),await this.onLLMNewToken?.(s,t,{chunk:i?.chunk}),s}};var su={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 ge(t,e){return`${t.open}${e}${t.close}`}o(ge,"wrap");function Ce(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}o(Ce,"tryJsonStringify");function iu(t){return typeof t=="string"?t.trim():t==null?t:Ce(t,t.toString())}o(iu,"formatKVMapItem");function rt(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(rt,"elapsed");var{color:ye}=su,qa=class extends ft{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,a)=>{let i=`${r.execution_order}:${r.run_type}:${r.name}`;return n===a.length-1?ge(su.bold,i):i}).join(" > ");return ge(ye.grey,e)}onChainStart(t){let e=this.getBreadcrumbs(t);console.log(`${ge(ye.green,"[chain/start]")} [${e}] Entering Chain run with input: ${Ce(t.inputs,"[inputs]")}`)}onChainEnd(t){let e=this.getBreadcrumbs(t);console.log(`${ge(ye.cyan,"[chain/end]")} [${e}] [${rt(t)}] Exiting Chain run with output: ${Ce(t.outputs,"[outputs]")}`)}onChainError(t){let e=this.getBreadcrumbs(t);console.log(`${ge(ye.red,"[chain/error]")} [${e}] [${rt(t)}] Chain run errored with error: ${Ce(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(`${ge(ye.green,"[llm/start]")} [${e}] Entering LLM run with input: ${Ce(r,"[inputs]")}`)}onLLMEnd(t){let e=this.getBreadcrumbs(t);console.log(`${ge(ye.cyan,"[llm/end]")} [${e}] [${rt(t)}] Exiting LLM run with output: ${Ce(t.outputs,"[response]")}`)}onLLMError(t){let e=this.getBreadcrumbs(t);console.log(`${ge(ye.red,"[llm/error]")} [${e}] [${rt(t)}] LLM run errored with error: ${Ce(t.error,"[error]")}`)}onToolStart(t){let e=this.getBreadcrumbs(t);console.log(`${ge(ye.green,"[tool/start]")} [${e}] Entering Tool run with input: "${iu(t.inputs.input)}"`)}onToolEnd(t){let e=this.getBreadcrumbs(t);console.log(`${ge(ye.cyan,"[tool/end]")} [${e}] [${rt(t)}] Exiting Tool run with output: "${iu(t.outputs?.output)}"`)}onToolError(t){let e=this.getBreadcrumbs(t);console.log(`${ge(ye.red,"[tool/error]")} [${e}] [${rt(t)}] Tool run errored with error: ${Ce(t.error,"[error]")}`)}onRetrieverStart(t){let e=this.getBreadcrumbs(t);console.log(`${ge(ye.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${Ce(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){let e=this.getBreadcrumbs(t);console.log(`${ge(ye.cyan,"[retriever/end]")} [${e}] [${rt(t)}] Exiting Retriever run with output: ${Ce(t.outputs,"[outputs]")}`)}onRetrieverError(t){let e=this.getBreadcrumbs(t);console.log(`${ge(ye.red,"[retriever/error]")} [${e}] [${rt(t)}] Retriever run errored with error: ${Ce(t.error,"[error]")}`)}onAgentAction(t){let e=t,r=this.getBreadcrumbs(t);console.log(`${ge(ye.blue,"[agent/action]")} [${r}] Agent selected action: ${Ce(e.actions[e.actions.length-1],"[action]")}`)}};var Wa,Ka=o(()=>(Wa===void 0&&(Wa=new tt(ke("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),Wa),"getDefaultLangChainClientSingleton");var Za=class{static{o(this,"MockAsyncLocalStorage")}getStore(){}run(e,r){return r()}},Ja=Symbol.for("ls:tracing_async_local_storage"),Zg=new Za,Ya=class{static{o(this,"AsyncLocalStorageProvider")}getInstance(){return globalThis[Ja]??Zg}initializeGlobalInstance(e){globalThis[Ja]===void 0&&(globalThis[Ja]=e)}},Yg=new Ya;function ou(t=!1){let e=Yg.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
46
-
47
- Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}o(ou,"getCurrentRunTree");var cu=new Set(["ls_agent_type"]);function Xg(t){let e;for(let r of t)for(let n of r)Ye.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=mr(e,n.message.usage_metadata));return e}o(Xg,"_getUsageMetadataFromGenerations");var Xt=class Xa extends ft{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:a,replicas:i,metadata:s,tags:l}=e;this.projectName=n??Ut(),this.replicas=i,this.exampleId=r,this.client=a??Ka(),this.tracingMetadata=s?{...s}:void 0,this.tracingTags=l??[];let c=Xa.getTraceableRunTree();c&&this.updateFromRunTree(c)}async persistRun(e){}async onRunCreate(e){lu(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){lu(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=Xg(r.generations);if(n!==void 0){e.extra=e.extra??{};let a=e.extra.metadata??{};a.usage_metadata=n,e.extra.metadata=a}}}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[s,l]of Object.entries(e))(!Object.prototype.hasOwnProperty.call(n,s)||cu.has(s))&&(n[s]=l)}let a=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],i=new Xa({...this.fields,metadata:n,tags:a});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 a=[r];for(;a.length>0;){let i=a.shift();!i||n.has(i.id)||(n.add(i.id),this.runTreeMap.set(i.id,i),i.child_runs&&a.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 $e({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return ou(!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 lu(t,e){if(t.tracingMetadata){e.extra??={};let r=e.extra.metadata??{},n=!1;for(let[a,i]of Object.entries(t.tracingMetadata))(!Object.prototype.hasOwnProperty.call(r,a)||cu.has(a))&&r[a]!==i&&(r[a]=i,n=!0);n&&(e.extra.metadata=r)}t.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...t.tracingTags])))}o(lu,"_patchMissingTracingDefaults");var ln=xe(Tr(),1);var Qt;function Qg(){return new("default"in ln.default?ln.default.default:ln.default)({autoStart:!0,concurrency:1})}o(Qg,"createQueue");function e_(){return typeof Qt>"u"&&(Qt=Qg()),Qt}o(e_,"getQueue");async function Z(t,e){if(e===!0){let r=Qe();r!==void 0?await r.run(void 0,async()=>t()):await t()}else Qt=e_(),Qt.add(async()=>{let r=Qe();r!==void 0?await r.run(void 0,async()=>t()):await t()})}o(Z,"consumeCallback");var uu=o(t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>ke(e)==="true"),"isTracingEnabled");function Qa(t){let e=Qe();if(e!==void 0)return e.getStore()?.[lt]?.[t]}o(Qa,"getContextVariable");var t_=Symbol("lc:configure_hooks"),du=o(()=>Qa(t_)||[],"_getConfigureHooks");var r_=class{static{o(this,"BaseCallbackManager")}setHandler(t){return this.setHandlers([t])}},cn=class{static{o(this,"BaseRunManager")}constructor(t,e,r,n,a,i,s,l){this.runId=t,this.handlers=e,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=a,this.metadata=i,this.inheritableMetadata=s,this._parentRunId=l}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>Z(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,a){await Promise.all(this.handlers.map(i=>Z(async()=>{try{await i.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}},n_=class extends cn{static{o(this,"CallbackManagerForRetrieverRun")}getChild(t){let e=new mt(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=>Z(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=>Z(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)))}},pu=class extends cn{static{o(this,"CallbackManagerForLLMRun")}async handleLLMNewToken(t,e,r,n,a,i){await Promise.all(this.handlers.map(s=>Z(async()=>{if(!s.ignoreLLM)try{await s.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i)}catch(l){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMNewToken: ${l}`),s.raiseError)throw l}},s.awaitHandlers)))}async handleChatModelStreamEvent(t){await Promise.all(this.handlers.map(e=>Z(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,a){await Promise.all(this.handlers.map(i=>Z(async()=>{if(!i.ignoreLLM)try{await i.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,a)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMError: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}async handleLLMEnd(t,e,r,n,a){await Promise.all(this.handlers.map(i=>Z(async()=>{if(!i.ignoreLLM)try{await i.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,a)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMEnd: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}},a_=class extends cn{static{o(this,"CallbackManagerForChainRun")}getChild(t){let e=new mt(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,a){await Promise.all(this.handlers.map(i=>Z(async()=>{if(!i.ignoreChain)try{await i.handleChainError?.(t,this.runId,this._parentRunId,this.tags,a)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainError: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}async handleChainEnd(t,e,r,n,a){await Promise.all(this.handlers.map(i=>Z(async()=>{if(!i.ignoreChain)try{await i.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,a)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainEnd: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>Z(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=>Z(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)))}},i_=class extends cn{static{o(this,"CallbackManagerForToolRun")}getChild(t){let e=new mt(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=>Z(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=>Z(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=>Z(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)))}},mt=class er extends r_{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,a=void 0,i=void 0,s=void 0,l=void 0,c=void 0){return Promise.all(r.map(async(u,p)=>{let m=p===0&&n?n:De();return await Promise.all(this.handlers.map(g=>{if(!g.ignoreLLM)return Ct(g)&&g._createRunForLLMStart(e,[u],m,this._parentRunId,i,this.tags,this.metadata,c),Z(async()=>{try{await g.handleLLMStart?.(e,[u],m,this._parentRunId,i,this.tags,this.metadata,c)}catch(h){if((g.raiseError?console.error:console.warn)(`Error in handler ${g.constructor.name}, handleLLMStart: ${h}`),g.raiseError)throw h}},g.awaitHandlers)})),new pu(m,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,r,n=void 0,a=void 0,i=void 0,s=void 0,l=void 0,c=void 0){return Promise.all(r.map(async(u,p)=>{let m=p===0&&n?n:De();return await Promise.all(this.handlers.map(g=>{if(!g.ignoreLLM)return Ct(g)&&g._createRunForChatModelStart(e,[u],m,this._parentRunId,i,this.tags,this.metadata,c),Z(async()=>{try{if(g.handleChatModelStart)await g.handleChatModelStart?.(e,[u],m,this._parentRunId,i,this.tags,this.metadata,c);else if(g.handleLLMStart){let h=_r(u);await g.handleLLMStart?.(e,[h],m,this._parentRunId,i,this.tags,this.metadata,c)}}catch(h){if((g.raiseError?console.error:console.warn)(`Error in handler ${g.constructor.name}, handleLLMStart: ${h}`),g.raiseError)throw h}},g.awaitHandlers)})),new pu(m,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,r,n=De(),a=void 0,i=void 0,s=void 0,l=void 0,c=void 0,u=void 0){return await Promise.all(this.handlers.map(p=>{if(!p.ignoreChain)return Ct(p)&&p._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,a,l,u),Z(async()=>{try{await p.handleChainStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,a,l,u)}catch(m){if((p.raiseError?console.error:console.warn)(`Error in handler ${p.constructor.name}, handleChainStart: ${m}`),p.raiseError)throw m}},p.awaitHandlers)})),new a_(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,r,n=De(),a=void 0,i=void 0,s=void 0,l=void 0,c=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return Ct(u)&&u._createRunForToolStart(e,r,n,this._parentRunId,this.tags,this.metadata,l),Z(async()=>{try{await u.handleToolStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,l,c)}catch(p){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${p}`),u.raiseError)throw p}},u.awaitHandlers)})),new i_(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,r,n=De(),a=void 0,i=void 0,s=void 0,l=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return Ct(c)&&c._createRunForRetrieverStart(e,r,n,this._parentRunId,this.tags,this.metadata,l),Z(async()=>{try{await c.handleRetrieverStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,l)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new n_(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,r,n,a,i){await Promise.all(this.handlers.map(s=>Z(async()=>{if(!s.ignoreCustomEvent)try{await s.handleCustomEvent?.(e,r,n,this.tags,this.metadata)}catch(l){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleCustomEvent: ${l}`),s.raiseError)throw l}},s.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 er(this._parentRunId);for(let a of this.handlers){let i=this.inheritableHandlers.includes(a);n.addHandler(a,i)}for(let a of this.tags){let i=this.inheritableTags.includes(a);n.addTags([a],i)}for(let a of Object.keys(this.metadata)){let i=Object.keys(this.inheritableMetadata).includes(a);n.addMetadata({[a]:this.metadata[a]},i)}for(let a of e)n.handlers.filter(i=>i.name==="console_callback_handler").some(i=>i.name===a.name)||n.addHandler(a,r);return n}static fromHandlers(e){class r extends vt{static{o(this,"Handler")}name=De();constructor(){super(),Object.assign(this,e)}}let n=new this;return n.addHandler(new r),n}static configure(e,r,n,a,i,s,l){return this._configureSync(e,r,n,a,i,s,l)}static _configureSync(e,r,n,a,i,s,l){let c;(e||r)&&(Array.isArray(e)||!e?(c=new er,c.setHandlers(e?.map(ei)??[],!0)):c=e,c=c.copy(Array.isArray(r)?r.map(ei):r?.handlers,!1));let u=ke("LANGCHAIN_VERBOSE")==="true"||l?.verbose,p=Xt.getTraceableRunTree(),m=p?.tracingEnabled??uu();if(p?.tracingEnabled===!1&&c){let x=c.handlers.filter(P=>P.name==="langchain_tracer");for(let P of x)c.removeHandler(P)}let g=m||(ke("LANGCHAIN_TRACING")??!1);if(u||g){if(c||(c=new er),u&&!c.handlers.some(x=>x.name===qa.prototype.name)){let x=new qa;c.addHandler(x,!0)}if(g&&!c.handlers.some(x=>x.name==="langchain_tracer")&&m){let x=new Xt;c.addHandler(x,!0)}m&&p&&c._parentRunId===void 0&&(c._parentRunId=p.id,c.handlers.find(x=>x.name==="langchain_tracer")?.updateFromRunTree(p))}for(let{contextVar:x,inheritable:P=!0,handlerClass:N,envVar:L}of du()){let C=L&&ke(L)==="true"&&N,k,F=x!==void 0?Qa(x):void 0;F&&Ds(F)?k=F:C&&(k=new N({})),k!==void 0&&(c||(c=new er),c.handlers.some(B=>B.name===k.name)||c.addHandler(k,P))}(n||a)&&c&&(c.addTags(n??[]),c.addTags(a??[],!1)),(i||s)&&c&&(c.addMetadata(i??{}),c.addMetadata(s??{},!1));let h=l?.tracerInheritableMetadata,E=l?.tracerInheritableTags;return c&&(h||E)&&(c.handlers=c.handlers.map(x=>x instanceof Xt?x.copyWithTracingConfig({metadata:h,tags:E}):x),c.inheritableHandlers=c.inheritableHandlers.map(x=>x instanceof Xt?x.copyWithTracingConfig({metadata:h,tags:E}):x)),c}};function ei(t){return"name"in t?t:vt.fromMethods(t)}o(ei,"ensureHandler");var mu=class{static{o(this,"MockAsyncLocalStorage")}getStore(){}run(t,e){return e()}enterWith(t){}},s_=new mu,fu=Symbol.for("lc:child_config"),o_=class{static{o(this,"AsyncLocalStorageProvider")}getInstance(){return Qe()??s_}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[fu]}runWithConfig(t,e,r){let n=mt._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),a=this.getInstance(),i=a.getStore(),s=n?.getParentRunId(),l=n?.handlers?.find(u=>u?.name==="langchain_tracer"),c;return l&&s?c=l.getRunTreeWithTracingConfig(s):r||(c=new $e({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[fu]:t}),i!==void 0&&i[lt]!==void 0&&(c===void 0&&(c={}),c[lt]=i[lt]),a.run(c,e)}initializeGlobalInstance(t){Qe()===void 0&&$s(t)}},tr=new o_;var l_=Object.prototype.hasOwnProperty;function _u(t,e){return l_.call(t,e)}o(_u,"hasOwnProperty");function yu(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)_u(t,r)&&e.push(r);return e}o(yu,"_objectKeys");function Ke(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}o(Ke,"_deepClone");function dn(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(dn,"isInteger");function bu(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}o(bu,"unescapePathComponent");function un(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(un(t[r]))return!0}else if(typeof t=="object"){let r=yu(t),n=r.length;for(var e=0;e<n;e++)if(un(t[r[e]]))return!0}}return!1}o(un,"hasUndefined");function gu(t,e){let r=[t];for(let n in e){let a=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof a<"u"&&r.push(`${n}: ${a}`)}return r.join(`
48
- `)}o(gu,"patchErrorMessageFormatter");var wu=class extends Error{static{o(this,"PatchError")}constructor(t,e,r,n,a){super(gu(t,{name:e,index:r,operation:n,tree:a})),this.name=e,this.index=r,this.operation=n,this.tree=a,Object.setPrototypeOf(this,new.target.prototype),this.message=gu(t,{name:e,index:r,operation:n,tree:a})}};var vu=j({JsonPatchError:o(()=>Y,"JsonPatchError"),_areEquals:o(()=>rr,"_areEquals"),applyOperation:o(()=>ht,"applyOperation"),applyPatch:o(()=>mn,"applyPatch"),applyReducer:o(()=>d_,"applyReducer"),deepClone:o(()=>c_,"deepClone"),getValueByPointer:o(()=>pn,"getValueByPointer"),validate:o(()=>Eu,"validate"),validator:o(()=>fn,"validator")}),Y=wu,c_=Ke,Ot={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=pn(r,this.path);n&&(n=Ke(n));let a=ht(r,{op:"remove",path:this.from}).removed;return ht(r,{op:"add",path:this.path,value:a}),{newDocument:r,removed:n}},"move"),copy:o(function(t,e,r){let n=pn(r,this.from);return ht(r,{op:"add",path:this.path,value:Ke(n)}),{newDocument:r}},"copy"),test:o(function(t,e,r){return{newDocument:r,test:rr(t[e],this.value)}},"test"),_get:o(function(t,e,r){return this.value=t[e],{newDocument:r}},"_get")},u_={add:o(function(t,e,r){return dn(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:Ot.move,copy:Ot.copy,test:Ot.test,_get:Ot._get};function pn(t,e){if(e=="")return t;var r={op:"_get",path:e};return ht(t,r),r.value}o(pn,"getValueByPointer");function ht(t,e,r=!1,n=!0,a=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):fn(e,0)),e.path===""){let s={newDocument:t};if(e.op==="add")return s.newDocument=e.value,s;if(e.op==="replace")return s.newDocument=e.value,s.removed=t,s;if(e.op==="move"||e.op==="copy")return s.newDocument=pn(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=rr(t,e.value),s.test===!1)throw new Y("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s.newDocument=t,s}else{if(e.op==="remove")return s.removed=t,s.newDocument=null,s;if(e.op==="_get")return e.value=t,s;if(r)throw new Y("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return s}}else{n||(t=Ke(t));let s=(e.path||"").split("/"),l=t,c=1,u=s.length,p,m,g;for(typeof r=="function"?g=r:g=fn;;){if(m=s[c],m&&m.indexOf("~")!=-1&&(m=bu(m)),a&&(m=="__proto__"||m=="prototype"&&c>0&&s[c-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&p===void 0&&(l[m]===void 0?p=s.slice(0,c).join("/"):c==u-1&&(p=e.path),p!==void 0&&g(e,0,t,p)),c++,Array.isArray(l)){if(m==="-")m=l.length;else{if(r&&!dn(m))throw new Y("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);dn(m)&&(m=~~m)}if(c>=u){if(r&&e.op==="add"&&m>l.length)throw new Y("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let h=u_[e.op].call(e,l,m,t);if(h.test===!1)throw new Y("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return h}}else if(c>=u){let h=Ot[e.op].call(e,l,m,t);if(h.test===!1)throw new Y("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return h}if(l=l[m],r&&c<u&&(!l||typeof l!="object"))throw new Y("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}o(ht,"applyOperation");function mn(t,e,r,n=!0,a=!0){if(r&&!Array.isArray(e))throw new Y("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=Ke(t));let i=new Array(e.length);for(let s=0,l=e.length;s<l;s++)i[s]=ht(t,e[s],r,!0,a,s),t=i[s].newDocument;return i.newDocument=t,i}o(mn,"applyPatch");function d_(t,e,r){let n=ht(t,e);if(n.test===!1)throw new Y("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}o(d_,"applyReducer");function fn(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new Y("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(Ot[t.op]){if(typeof t.path!="string")throw new Y("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new Y('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 Y("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 Y("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")&&un(t.value))throw new Y("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 a=t.path.split("/").length,i=n.split("/").length;if(a!==i+1&&a!==i)throw new Y("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 Y("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 s=Eu([{op:"_get",path:t.from,value:void 0}],r);if(s&&s.name==="OPERATION_PATH_UNRESOLVABLE")throw new Y("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new Y("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}o(fn,"validator");function Eu(t,e,r){try{if(!Array.isArray(t))throw new Y("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)mn(Ke(e),Ke(t),r||!0);else{r=r||fn;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(a){if(a instanceof Y)return a;throw a}}o(Eu,"validate");function rr(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),a,i,s;if(r&&n){if(i=t.length,i!=e.length)return!1;for(a=i;a--!==0;)if(!rr(t[a],e[a]))return!1;return!0}if(r!=n)return!1;var l=Object.keys(t);if(i=l.length,i!==Object.keys(e).length)return!1;for(a=i;a--!==0;)if(!e.hasOwnProperty(l[a]))return!1;for(a=i;a--!==0;)if(s=l[a],!rr(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}o(rr,"_areEquals");({...vu});var mN=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 y_=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,b_=[0,31,28,31,30,31,30,31,31,30,31,30,31],w_=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,v_=/^(?=.{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,E_=/^(?:[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,T_=/^(?:(?:[^\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,x_=/^(?:(?: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,S_=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,A_=/^(?:\/(?:[^~/]|~0|~1)*)*$/,I_=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,C_=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,O_=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(a=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(a))},"EMAIL"),R_=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,M_=/^((([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,k_=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 ze(t){return t.test.bind(t)}o(ze,"bind");var N_={date:Tu,time:xu.bind(void 0,!1),"date-time":L_,duration:k_,uri:U_,"uri-reference":ze(E_),"uri-template":ze(T_),url:ze(x_),email:O_,hostname:ze(v_),ipv4:ze(R_),ipv6:ze(M_),regex:B_,uuid:ze(S_),"json-pointer":ze(A_),"json-pointer-uri-fragment":ze(I_),"relative-json-pointer":ze(C_)};function P_(t){return t%4===0&&(t%100!==0||t%400===0)}o(P_,"isLeapYear");function Tu(t){let e=t.match(y_);if(!e)return!1;let r=+e[1],n=+e[2],a=+e[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&P_(r)?29:b_[n])}o(Tu,"date");function xu(t,e){let r=e.match(w_);if(!r)return!1;let n=+r[1],a=+r[2],i=+r[3],s=!!r[5];return(n<=23&&a<=59&&i<=59||n==23&&a==59&&i==60)&&(!t||s)}o(xu,"time");var $_=/t|\s/i;function L_(t){let e=t.split($_);return e.length==2&&Tu(e[0])&&xu(!0,e[1])}o(L_,"date_time");var D_=/\/|:/,F_=/^(?:[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 D_.test(t)&&F_.test(t)}o(U_,"uri");var j_=/[^\\]\\Z/;function B_(t){if(j_.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}o(B_,"regex");var Su;(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(Su||(Su={}));var Du=xe(Lu(),1);var ny=Object.defineProperty,ay=o((t,e,r)=>e in t?ny(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,"__defNormalProp"),iy=o((t,e,r)=>(ay(t,typeof e!="symbol"?e+"":e,r),r),"__publicField");function sy(t,e){let r=Array.from({length:t.length},(n,a)=>({start:a,end:a+1}));for(;r.length>1;){let n=null;for(let a=0;a<r.length-1;a++){let i=t.slice(r[a].start,r[a+1].end),s=e.get(i.join(","));s!=null&&(n==null||s<n[0])&&(n=[s,a])}if(n!=null){let a=n[1];r[a]={start:r[a].start,end:r[a+1].end},r.splice(a+1,1)}else break}return r}o(sy,"bytePairMerge");function oy(t,e){return t.length===1?[e.get(t.join(","))]:sy(t,e).map(r=>e.get(t.slice(r.start,r.end).join(","))).filter(r=>r!=null)}o(oy,"bytePairEncode");function ly(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}o(ly,"escapeRegex");var si=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(`
49
- `).filter(Boolean).reduce((n,a)=>{let[i,s,...l]=a.split(" "),c=Number.parseInt(s,10);return l.forEach((u,p)=>n[u]=c+p),n},{});for(let[n,a]of Object.entries(r)){let i=Du.default.toByteArray(n);this.rankMap.set(i.join(","),a),this.textMap.set(a,i)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[a,i])=>(n[i]=this.textEncoder.encode(a),n),{})}encode(t,e=[],r="all"){let n=new RegExp(this.patStr,"ug"),a=si.specialTokenRegex(Object.keys(this.specialTokens)),i=[],s=new Set(e==="all"?Object.keys(this.specialTokens):e),l=new Set(r==="all"?Object.keys(this.specialTokens).filter(u=>!s.has(u)):r);if(l.size>0){let u=si.specialTokenRegex([...l]),p=t.match(u);if(p!=null)throw new Error(`The text contains a special token that is not allowed: ${p[0]}`)}let c=0;for(;;){let u=null,p=c;for(;a.lastIndex=p,u=a.exec(t),!(u==null||s.has(u[0]));)p=u.index+1;let m=u?.index??t.length;for(let h of t.substring(c,m).matchAll(n)){let E=this.textEncoder.encode(h[0]),x=this.rankMap.get(E.join(","));if(x!=null){i.push(x);continue}i.push(...oy(E,this.rankMap))}if(u==null)break;let g=this.specialTokens[u[0]];i.push(g),c=u.index+u[0].length}return i}decode(t){let e=[],r=0;for(let i=0;i<t.length;++i){let s=t[i],l=this.textMap.get(s)??this.inverseSpecialTokens[s];l!=null&&(e.push(l),r+=l.length)}let n=new Uint8Array(r),a=0;for(let i of e)n.set(i,a),a+=i.length;return this.textDecoder.decode(n)}},oi=si;iy(oi,"specialTokenRegex",t=>new RegExp(t.map(e=>ly(e)).join("|"),"g"));var Bu=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"];var Gu=["image","video","audio","text-plain","file"];var dy=["text","reasoning",...Bu,...Gu];var by=o(function(){let t={};t.parser=function(f,d){return new r(f,d)},t.SAXParser=r,t.SAXStream=u,t.createStream=c,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(f,d){if(!(this instanceof r))return new r(f,d);var w=this;a(w),w.q=w.c="",w.bufferCheckPosition=t.MAX_BUFFER_LENGTH,w.opt=d||{},w.opt.lowercase=w.opt.lowercase||w.opt.lowercasetags,w.looseCase=w.opt.lowercase?"toLowerCase":"toUpperCase",w.tags=[],w.closed=w.closedRoot=w.sawRoot=!1,w.tag=w.error=null,w.strict=!!f,w.noscript=!!(f||w.opt.noscript),w.state=_.BEGIN,w.strictEntities=w.opt.strictEntities,w.ENTITIES=w.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),w.attribList=[],w.opt.xmlns&&(w.ns=Object.create(E)),w.trackPosition=w.opt.position!==!1,w.trackPosition&&(w.position=w.line=w.column=0),te(w,"onready")}o(r,"SAXParser"),Object.create||(Object.create=function(f){function d(){}return o(d,"F"),d.prototype=f,new d}),Object.keys||(Object.keys=function(f){var d=[];for(var w in f)f.hasOwnProperty(w)&&d.push(w);return d});function n(f){for(var d=Math.max(t.MAX_BUFFER_LENGTH,10),w=0,y=0,H=e.length;y<H;y++){var Q=f[e[y]].length;if(Q>d)switch(e[y]){case"textNode":be(f);break;case"cdata":G(f,"oncdata",f.cdata),f.cdata="";break;case"script":G(f,"onscript",f.script),f.script="";break;default:_t(f,"Max buffer length exceeded: "+e[y])}w=Math.max(w,Q)}f.bufferCheckPosition=t.MAX_BUFFER_LENGTH-w+f.position}o(n,"checkBufferLength");function a(f){for(var d=0,w=e.length;d<w;d++)f[e[d]]=""}o(a,"clearBuffers");function i(f){be(f),f.cdata!==""&&(G(f,"oncdata",f.cdata),f.cdata=""),f.script!==""&&(G(f,"onscript",f.script),f.script="")}o(i,"flushBuffers"),r.prototype={end:o(function(){gi(this)},"end"),write:md,resume:o(function(){return this.error=null,this},"resume"),close:o(function(){return this.write(null)},"close"),flush:o(function(){i(this)},"flush")};var s=ReadableStream;s||(s=o(function(){},"Stream"));var l=t.EVENTS.filter(function(f){return f!=="error"&&f!=="end"});function c(f,d){return new u(f,d)}o(c,"createStream");function u(f,d){if(!(this instanceof u))return new u(f,d);s.apply(this),this._parser=new r(f,d),this.writable=!0,this.readable=!0;var w=this;this._parser.onend=function(){w.emit("end")},this._parser.onerror=function(y){w.emit("error",y),w._parser.error=null},this._decoder=null,l.forEach(function(y){Object.defineProperty(w,"on"+y,{get:o(function(){return w._parser["on"+y]},"get"),set:o(function(H){if(!H)return w.removeAllListeners(y),w._parser["on"+y]=H,H;w.on(y,H)},"set"),enumerable:!0,configurable:!1})})}o(u,"SAXStream"),u.prototype=Object.create(s.prototype,{constructor:{value:u}}),u.prototype.write=function(f){return this._parser.write(f.toString()),this.emit("data",f),!0},u.prototype.end=function(f){return f&&f.length&&this.write(f),this._parser.end(),!0},u.prototype.on=function(f,d){var w=this;return!w._parser["on"+f]&&l.indexOf(f)!==-1&&(w._parser["on"+f]=function(){var y=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);y.splice(0,0,f),w.emit.apply(w,y)}),s.prototype.on.call(w,f,d)};var p="[CDATA[",m="DOCTYPE",g="http://www.w3.org/XML/1998/namespace",h="http://www.w3.org/2000/xmlns/",E={xml:g,xmlns:h},x=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,P=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,N=/[#:_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]/,L=/[#:_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 C(f){return f===" "||f===`
50
- `||f==="\r"||f===" "}o(C,"isWhitespace");function k(f){return f==='"'||f==="'"}o(k,"isQuote");function F(f){return f===">"||C(f)}o(F,"isAttribEnd");function B(f,d){return f.test(d)}o(B,"isMatch");function V(f,d){return!B(f,d)}o(V,"notMatch");var _=0;t.STATE={BEGIN:_++,BEGIN_WHITESPACE:_++,TEXT:_++,TEXT_ENTITY:_++,OPEN_WAKA:_++,SGML_DECL:_++,SGML_DECL_QUOTED:_++,DOCTYPE:_++,DOCTYPE_QUOTED:_++,DOCTYPE_DTD:_++,DOCTYPE_DTD_QUOTED:_++,COMMENT_STARTING:_++,COMMENT:_++,COMMENT_ENDING:_++,COMMENT_ENDED:_++,CDATA:_++,CDATA_ENDING:_++,CDATA_ENDING_2:_++,PROC_INST:_++,PROC_INST_BODY:_++,PROC_INST_ENDING:_++,OPEN_TAG:_++,OPEN_TAG_SLASH:_++,ATTRIB:_++,ATTRIB_NAME:_++,ATTRIB_NAME_SAW_WHITE:_++,ATTRIB_VALUE:_++,ATTRIB_VALUE_QUOTED:_++,ATTRIB_VALUE_CLOSED:_++,ATTRIB_VALUE_UNQUOTED:_++,ATTRIB_VALUE_ENTITY_Q:_++,ATTRIB_VALUE_ENTITY_U:_++,CLOSE_TAG:_++,CLOSE_TAG_SAW_WHITE:_++,SCRIPT:_++,SCRIPT_ENDING:_++},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(f){var d=t.ENTITIES[f],w=typeof d=="number"?String.fromCharCode(d):d;t.ENTITIES[f]=w});for(var X in t.STATE)t.STATE[t.STATE[X]]=X;_=t.STATE;function te(f,d,w){f[d]&&f[d](w)}o(te,"emit");function G(f,d,w){f.textNode&&be(f),te(f,d,w)}o(G,"emitNode");function be(f){f.textNode=or(f.opt,f.textNode),f.textNode&&te(f,"ontext",f.textNode),f.textNode=""}o(be,"closeText");function or(f,d){return f.trim&&(d=d.trim()),f.normalize&&(d=d.replace(/\s+/g," ")),d}o(or,"textopts");function _t(f,d){return be(f),f.trackPosition&&(d+=`
51
- Line: `+f.line+`
52
- Column: `+f.column+`
53
- Char: `+f.c),d=new Error(d),f.error=d,te(f,"onerror",d),f}o(_t,"error");function gi(f){return f.sawRoot&&!f.closedRoot&&z(f,"Unclosed root tag"),f.state!==_.BEGIN&&f.state!==_.BEGIN_WHITESPACE&&f.state!==_.TEXT&&_t(f,"Unexpected end"),be(f),f.c="",f.closed=!0,te(f,"onend"),r.call(f,f.strict,f.opt),f}o(gi,"end");function z(f,d){if(typeof f!="object"||!(f instanceof r))throw new Error("bad call to strictFail");f.strict&&_t(f,d)}o(z,"strictFail");function fd(f){f.strict||(f.tagName=f.tagName[f.looseCase]());var d=f.tags[f.tags.length-1]||f,w=f.tag={name:f.tagName,attributes:{}};f.opt.xmlns&&(w.ns=d.ns),f.attribList.length=0,G(f,"onopentagstart",w)}o(fd,"newTag");function wn(f,d){var w=f.indexOf(":")<0?["",f]:f.split(":"),y=w[0],H=w[1];return d&&f==="xmlns"&&(y="xmlns",H=""),{prefix:y,local:H}}o(wn,"qname");function vn(f){if(f.strict||(f.attribName=f.attribName[f.looseCase]()),f.attribList.indexOf(f.attribName)!==-1||f.tag.attributes.hasOwnProperty(f.attribName)){f.attribName=f.attribValue="";return}if(f.opt.xmlns){var d=wn(f.attribName,!0),w=d.prefix,y=d.local;if(w==="xmlns")if(y==="xml"&&f.attribValue!==g)z(f,"xml: prefix must be bound to "+g+`
54
- Actual: `+f.attribValue);else if(y==="xmlns"&&f.attribValue!==h)z(f,"xmlns: prefix must be bound to "+h+`
55
- Actual: `+f.attribValue);else{var H=f.tag,Q=f.tags[f.tags.length-1]||f;H.ns===Q.ns&&(H.ns=Object.create(Q.ns)),H.ns[y]=f.attribValue}f.attribList.push([f.attribName,f.attribValue])}else f.tag.attributes[f.attribName]=f.attribValue,G(f,"onattribute",{name:f.attribName,value:f.attribValue});f.attribName=f.attribValue=""}o(vn,"attrib");function nt(f,d){if(f.opt.xmlns){var w=f.tag,y=wn(f.tagName);w.prefix=y.prefix,w.local=y.local,w.uri=w.ns[y.prefix]||"",w.prefix&&!w.uri&&(z(f,"Unbound namespace prefix: "+JSON.stringify(f.tagName)),w.uri=y.prefix);var H=f.tags[f.tags.length-1]||f;w.ns&&H.ns!==w.ns&&Object.keys(w.ns).forEach(function(vi){G(f,"onopennamespace",{prefix:vi,uri:w.ns[vi]})});for(var Q=0,we=f.attribList.length;Q<we;Q++){var pe=f.attribList[Q],Re=pe[0],at=pe[1],le=wn(Re,!0),it=le.prefix,hd=le.local,wi=it===""?"":w.ns[it]||"",Tn={name:Re,value:at,prefix:it,local:hd,uri:wi};it&&it!=="xmlns"&&!wi&&(z(f,"Unbound namespace prefix: "+JSON.stringify(it)),Tn.uri=it),f.tag.attributes[Re]=Tn,G(f,"onattribute",Tn)}f.attribList.length=0}f.tag.isSelfClosing=!!d,f.sawRoot=!0,f.tags.push(f.tag),G(f,"onopentag",f.tag),d||(!f.noscript&&f.tagName.toLowerCase()==="script"?f.state=_.SCRIPT:f.state=_.TEXT,f.tag=null,f.tagName=""),f.attribName=f.attribValue="",f.attribList.length=0}o(nt,"openTag");function En(f){if(!f.tagName){z(f,"Weird empty close tag."),f.textNode+="</>",f.state=_.TEXT;return}if(f.script){if(f.tagName!=="script"){f.script+="</"+f.tagName+">",f.tagName="",f.state=_.SCRIPT;return}G(f,"onscript",f.script),f.script=""}var d=f.tags.length,w=f.tagName;f.strict||(w=w[f.looseCase]());for(var y=w;d--&&f.tags[d].name!==y;)z(f,"Unexpected close tag");if(d<0){z(f,"Unmatched closing tag: "+f.tagName),f.textNode+="</"+f.tagName+">",f.state=_.TEXT;return}f.tagName=w;for(var H=f.tags.length;H-- >d;){var Q=f.tag=f.tags.pop();f.tagName=f.tag.name,G(f,"onclosetag",f.tagName);var we={};for(var pe in Q.ns)we[pe]=Q.ns[pe];var Re=f.tags[f.tags.length-1]||f;f.opt.xmlns&&Q.ns!==Re.ns&&Object.keys(Q.ns).forEach(function(at){var le=Q.ns[at];G(f,"onclosenamespace",{prefix:at,uri:le})})}d===0&&(f.closedRoot=!0),f.tagName=f.attribValue=f.attribName="",f.attribList.length=0,f.state=_.TEXT}o(En,"closeTag");function _i(f){var d=f.entity,w=d.toLowerCase(),y,H="";return f.ENTITIES[d]?f.ENTITIES[d]:f.ENTITIES[w]?f.ENTITIES[w]:(d=w,d.charAt(0)==="#"&&(d.charAt(1)==="x"?(d=d.slice(2),y=parseInt(d,16),H=y.toString(16)):(d=d.slice(1),y=parseInt(d,10),H=y.toString(10))),d=d.replace(/^0+/,""),isNaN(y)||H.toLowerCase()!==d?(z(f,"Invalid character entity"),"&"+f.entity+";"):String.fromCodePoint(y))}o(_i,"parseEntity");function yi(f,d){d==="<"?(f.state=_.OPEN_WAKA,f.startTagPosition=f.position):C(d)||(z(f,"Non-whitespace before first tag."),f.textNode=d,f.state=_.TEXT)}o(yi,"beginWhiteSpace");function bi(f,d){var w="";return d<f.length&&(w=f.charAt(d)),w}o(bi,"charAt");function md(f){var d=this;if(this.error)throw this.error;if(d.closed)return _t(d,"Cannot write after close. Assign an onready handler.");if(f===null)return gi(d);typeof f=="object"&&(f=f.toString());for(var w=0,y="";y=bi(f,w++),d.c=y,!!y;)switch(d.trackPosition&&(d.position++,y===`
56
- `?(d.line++,d.column=0):d.column++),d.state){case _.BEGIN:if(d.state=_.BEGIN_WHITESPACE,y==="\uFEFF")continue;yi(d,y);continue;case _.BEGIN_WHITESPACE:yi(d,y);continue;case _.TEXT:if(d.sawRoot&&!d.closedRoot){for(var H=w-1;y&&y!=="<"&&y!=="&";)y=bi(f,w++),y&&d.trackPosition&&(d.position++,y===`
57
- `?(d.line++,d.column=0):d.column++);d.textNode+=f.substring(H,w-1)}y==="<"&&!(d.sawRoot&&d.closedRoot&&!d.strict)?(d.state=_.OPEN_WAKA,d.startTagPosition=d.position):(!C(y)&&(!d.sawRoot||d.closedRoot)&&z(d,"Text data outside of root node."),y==="&"?d.state=_.TEXT_ENTITY:d.textNode+=y);continue;case _.SCRIPT:y==="<"?d.state=_.SCRIPT_ENDING:d.script+=y;continue;case _.SCRIPT_ENDING:y==="/"?d.state=_.CLOSE_TAG:(d.script+="<"+y,d.state=_.SCRIPT);continue;case _.OPEN_WAKA:if(y==="!")d.state=_.SGML_DECL,d.sgmlDecl="";else if(!C(y))if(B(x,y))d.state=_.OPEN_TAG,d.tagName=y;else if(y==="/")d.state=_.CLOSE_TAG,d.tagName="";else if(y==="?")d.state=_.PROC_INST,d.procInstName=d.procInstBody="";else{if(z(d,"Unencoded <"),d.startTagPosition+1<d.position){var Q=d.position-d.startTagPosition;y=new Array(Q).join(" ")+y}d.textNode+="<"+y,d.state=_.TEXT}continue;case _.SGML_DECL:(d.sgmlDecl+y).toUpperCase()===p?(G(d,"onopencdata"),d.state=_.CDATA,d.sgmlDecl="",d.cdata=""):d.sgmlDecl+y==="--"?(d.state=_.COMMENT,d.comment="",d.sgmlDecl=""):(d.sgmlDecl+y).toUpperCase()===m?(d.state=_.DOCTYPE,(d.doctype||d.sawRoot)&&z(d,"Inappropriately located doctype declaration"),d.doctype="",d.sgmlDecl=""):y===">"?(G(d,"onsgmldeclaration",d.sgmlDecl),d.sgmlDecl="",d.state=_.TEXT):(k(y)&&(d.state=_.SGML_DECL_QUOTED),d.sgmlDecl+=y);continue;case _.SGML_DECL_QUOTED:y===d.q&&(d.state=_.SGML_DECL,d.q=""),d.sgmlDecl+=y;continue;case _.DOCTYPE:y===">"?(d.state=_.TEXT,G(d,"ondoctype",d.doctype),d.doctype=!0):(d.doctype+=y,y==="["?d.state=_.DOCTYPE_DTD:k(y)&&(d.state=_.DOCTYPE_QUOTED,d.q=y));continue;case _.DOCTYPE_QUOTED:d.doctype+=y,y===d.q&&(d.q="",d.state=_.DOCTYPE);continue;case _.DOCTYPE_DTD:d.doctype+=y,y==="]"?d.state=_.DOCTYPE:k(y)&&(d.state=_.DOCTYPE_DTD_QUOTED,d.q=y);continue;case _.DOCTYPE_DTD_QUOTED:d.doctype+=y,y===d.q&&(d.state=_.DOCTYPE_DTD,d.q="");continue;case _.COMMENT:y==="-"?d.state=_.COMMENT_ENDING:d.comment+=y;continue;case _.COMMENT_ENDING:y==="-"?(d.state=_.COMMENT_ENDED,d.comment=or(d.opt,d.comment),d.comment&&G(d,"oncomment",d.comment),d.comment=""):(d.comment+="-"+y,d.state=_.COMMENT);continue;case _.COMMENT_ENDED:y!==">"?(z(d,"Malformed comment"),d.comment+="--"+y,d.state=_.COMMENT):d.state=_.TEXT;continue;case _.CDATA:y==="]"?d.state=_.CDATA_ENDING:d.cdata+=y;continue;case _.CDATA_ENDING:y==="]"?d.state=_.CDATA_ENDING_2:(d.cdata+="]"+y,d.state=_.CDATA);continue;case _.CDATA_ENDING_2:y===">"?(d.cdata&&G(d,"oncdata",d.cdata),G(d,"onclosecdata"),d.cdata="",d.state=_.TEXT):y==="]"?d.cdata+="]":(d.cdata+="]]"+y,d.state=_.CDATA);continue;case _.PROC_INST:y==="?"?d.state=_.PROC_INST_ENDING:C(y)?d.state=_.PROC_INST_BODY:d.procInstName+=y;continue;case _.PROC_INST_BODY:if(!d.procInstBody&&C(y))continue;y==="?"?d.state=_.PROC_INST_ENDING:d.procInstBody+=y;continue;case _.PROC_INST_ENDING:y===">"?(G(d,"onprocessinginstruction",{name:d.procInstName,body:d.procInstBody}),d.procInstName=d.procInstBody="",d.state=_.TEXT):(d.procInstBody+="?"+y,d.state=_.PROC_INST_BODY);continue;case _.OPEN_TAG:B(P,y)?d.tagName+=y:(fd(d),y===">"?nt(d):y==="/"?d.state=_.OPEN_TAG_SLASH:(C(y)||z(d,"Invalid character in tag name"),d.state=_.ATTRIB));continue;case _.OPEN_TAG_SLASH:y===">"?(nt(d,!0),En(d)):(z(d,"Forward-slash in opening tag not followed by >"),d.state=_.ATTRIB);continue;case _.ATTRIB:if(C(y))continue;y===">"?nt(d):y==="/"?d.state=_.OPEN_TAG_SLASH:B(x,y)?(d.attribName=y,d.attribValue="",d.state=_.ATTRIB_NAME):z(d,"Invalid attribute name");continue;case _.ATTRIB_NAME:y==="="?d.state=_.ATTRIB_VALUE:y===">"?(z(d,"Attribute without value"),d.attribValue=d.attribName,vn(d),nt(d)):C(y)?d.state=_.ATTRIB_NAME_SAW_WHITE:B(P,y)?d.attribName+=y:z(d,"Invalid attribute name");continue;case _.ATTRIB_NAME_SAW_WHITE:if(y==="=")d.state=_.ATTRIB_VALUE;else{if(C(y))continue;z(d,"Attribute without value"),d.tag.attributes[d.attribName]="",d.attribValue="",G(d,"onattribute",{name:d.attribName,value:""}),d.attribName="",y===">"?nt(d):B(x,y)?(d.attribName=y,d.state=_.ATTRIB_NAME):(z(d,"Invalid attribute name"),d.state=_.ATTRIB)}continue;case _.ATTRIB_VALUE:if(C(y))continue;k(y)?(d.q=y,d.state=_.ATTRIB_VALUE_QUOTED):(z(d,"Unquoted attribute value"),d.state=_.ATTRIB_VALUE_UNQUOTED,d.attribValue=y);continue;case _.ATTRIB_VALUE_QUOTED:if(y!==d.q){y==="&"?d.state=_.ATTRIB_VALUE_ENTITY_Q:d.attribValue+=y;continue}vn(d),d.q="",d.state=_.ATTRIB_VALUE_CLOSED;continue;case _.ATTRIB_VALUE_CLOSED:C(y)?d.state=_.ATTRIB:y===">"?nt(d):y==="/"?d.state=_.OPEN_TAG_SLASH:B(x,y)?(z(d,"No whitespace between attributes"),d.attribName=y,d.attribValue="",d.state=_.ATTRIB_NAME):z(d,"Invalid attribute name");continue;case _.ATTRIB_VALUE_UNQUOTED:if(!F(y)){y==="&"?d.state=_.ATTRIB_VALUE_ENTITY_U:d.attribValue+=y;continue}vn(d),y===">"?nt(d):d.state=_.ATTRIB;continue;case _.CLOSE_TAG:if(d.tagName)y===">"?En(d):B(P,y)?d.tagName+=y:d.script?(d.script+="</"+d.tagName,d.tagName="",d.state=_.SCRIPT):(C(y)||z(d,"Invalid tagname in closing tag"),d.state=_.CLOSE_TAG_SAW_WHITE);else{if(C(y))continue;V(x,y)?d.script?(d.script+="</"+y,d.state=_.SCRIPT):z(d,"Invalid tagname in closing tag."):d.tagName=y}continue;case _.CLOSE_TAG_SAW_WHITE:if(C(y))continue;y===">"?En(d):z(d,"Invalid characters in closing tag");continue;case _.TEXT_ENTITY:case _.ATTRIB_VALUE_ENTITY_Q:case _.ATTRIB_VALUE_ENTITY_U:var we,pe;switch(d.state){case _.TEXT_ENTITY:we=_.TEXT,pe="textNode";break;case _.ATTRIB_VALUE_ENTITY_Q:we=_.ATTRIB_VALUE_QUOTED,pe="attribValue";break;case _.ATTRIB_VALUE_ENTITY_U:we=_.ATTRIB_VALUE_UNQUOTED,pe="attribValue";break}if(y===";")if(d.opt.unparsedEntities){var Re=_i(d);d.entity="",d.state=we,d.write(Re)}else d[pe]+=_i(d),d.entity="",d.state=we;else B(d.entity.length?L:N,y)?d.entity+=y:(z(d,"Invalid character in entity name"),d[pe]+="&"+d.entity+y,d.entity="",d.state=we);continue;default:throw new Error(d,"Unknown state: "+d.state)}return d.position>=d.bufferCheckPosition&&n(d),d}o(md,"write");return String.fromCodePoint||(function(){var f=String.fromCharCode,d=Math.floor,w=o(function(){var y=16384,H=[],Q,we,pe=-1,Re=arguments.length;if(!Re)return"";for(var at="";++pe<Re;){var le=Number(arguments[pe]);if(!isFinite(le)||le<0||le>1114111||d(le)!==le)throw RangeError("Invalid code point: "+le);le<=65535?H.push(le):(le-=65536,Q=(le>>10)+55296,we=le%1024+56320,H.push(Q,we)),(pe+1===Re||H.length>y)&&(at+=f.apply(null,H),H.length=0)}return at},"fromCodePoint");Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:w,configurable:!0,writable:!0}):String.fromCodePoint=w})(),t},"initializeSax"),wy=by();var f4=require("@playwright/test");var n4={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 ed=xe(Qu());ed.default.config({path:[`${__dirname}/.env`,`${__dirname}/../../.env`]});var By="claude_4",Gy={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}},Hy=o(()=>({nodeEnv:process.env.NODE_ENV??"production",selectedModel:{name:By},models:Gy,langsmith:{enabled:process.env.LANGSMITH_TRACING==="true",endpoint:process.env.LANGSMITH_ENDPOINT??"",apiKey:process.env.LANGSMITH_API_KEY??"",project:process.env.LANGSMITH_PROJECT??""}}),"make"),ee=Hy();var u4={claude_4:ee.models.claude4sonnet,"claude_3.7":ee.models.claude37sonnet,claude_sonnet_4_6:ee.models.claudeSonnet46,claude_sonnet_5:ee.models.claudeSonnet5,claude_opus_4_8:ee.models.claudeOpus48,"gemini_2.5_pro":ee.models.gemini25pro,"gemini_2.0_flash":ee.models.gemini20flash,"gemini_2.5_flash_lite":ee.models.gemini25flash_lite,"gemini_2.5_flash":ee.models.gemini25flash,"gemini_3.5_flash":ee.models.gemini35flash,"gemini_3.1_flash_lite":ee.models.gemini31flashLite,gpt_4o_mini:ee.models.gpt4omini,gpt_4o_nano:ee.models.gpt4onano,gpt_41_nano:ee.models.gpt41nano,gpt_5_mini:ee.models.gpt5mini,gpt_5_nano:ee.models.gpt5nano,gpt_41_mini:ee.models.gpt41mini,gpt_41:ee.models.gpt41,o4_mini:ee.models.o4mini,o3_mini:ee.models.o3mini};var td=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 fi=require("fs");var rd="\x1B[31m",zy="\x1B[33m",Vy="\x1B[32m",qy="\x1B[36m",Wy="\x1B[2m",Ky="\x1B[1m",sr="\x1B[0m",Jy=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"),Zy=new Set(["severity","message","kind","timestamp","_startedAtMs"]),Yy=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"),Xy=o(t=>t==="ERROR"||t==="CRITICAL"?rd:t==="WARNING"?zy:Vy,"colorForSeverity"),Qy=o(t=>{let e=String(t.severity??"INFO"),r=`${Xy(e)}${e.padEnd(5)}${sr}`,n=t.kind?`${qy}${t.kind}${sr}`:"",a=String(t.message??""),i=t.error&&typeof t.error=="object"?(()=>{let p=t.error;return` ${rd}${p.type??"Error"}: ${p.message??""}${sr}`})():"",s=["outcome","test_suite_run_id","status"],l=Object.entries(t).filter(([p,m])=>!Zy.has(p)&&m!=null&&p!=="error"&&typeof m!="object"),c=o(p=>{let m=s.indexOf(p);return m===-1?s.length:m},"rank"),u=l.sort(([p],[m])=>c(p)-c(m)).slice(0,8).map(([p,m])=>`${Wy}${p}=${sr}${m}`).join(" ");return[r,Ky+n+sr,a,u,i].filter(p=>p&&p.trim()!=="").join(" ")},"formatPretty"),eb=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"),nd=o(t=>{let e=Jy()?Qy(t):Yy(eb(t));(0,fi.writeSync)(1,e+`
58
- `)},"emitEvent");var ad=o(t=>{(0,fi.writeSync)(2,t.endsWith(`
145
+ https://smith.langchain.com/prompts`);let[i,a,o]=he(e);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError("create a prompt",i);let l={repo_handle:a,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},c=JSON.stringify(l),u=await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await C(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[i,a,o]=he(e),l=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${i}/${a}`):n?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(r)),parent_commit:l,...n?.description!==void 0&&{description:n.description}},u=JSON.stringify(c),p=await(await this.caller.call(async()=>{let g=await this._fetch(`${this.apiUrl}/commits/${i}/${a}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await C(g,"create commit"),g})).json(),h=p.commit??p;return n?.tags&&await this._createCommitTags(`${i}/${a}`,h.id,n.tags),this._getPromptUrl(`${i}/${a}${h.commit_hash?`:${h.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 l=o.id,c={...o.metadata&&{metadata:o.metadata},...o.split&&{split:o.split}},u=ge(c,`Serializing body for example with id: ${l}`),d=new Blob([u],{type:"application/json"});if(n.append(l,d),o.inputs){let p=ge(o.inputs,`Serializing inputs for example with id: ${l}`),h=new Blob([p],{type:"application/json"});n.append(`${l}.inputs`,h)}if(o.outputs){let p=ge(o.outputs,`Serializing outputs whle updating example with id: ${l}`),h=new Blob([p],{type:"application/json"});n.append(`${l}.outputs`,h)}if(o.attachments)for(let[p,h]of Object.entries(o.attachments)){let g,b;Array.isArray(h)?[g,b]=h:(g=h.mimeType,b=h.data);let v=new Blob([b],{type:`${g}; length=${b.byteLength}`});n.append(`${l}.attachment.${p}`,v)}if(o.attachments_operations){let p=ge(o.attachments_operations,`Serializing attachments while updating example with id: ${l}`),h=new Blob([p],{type:"application/json"});n.append(`${l}.attachments_operations`,h)}}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 C(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 a of r){let o=(a.id??Et()).toString(),l={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split},...a.source_run_id&&{source_run_id:a.source_run_id},...a.use_source_run_io&&{use_source_run_io:a.use_source_run_io},...a.use_source_run_attachments&&{use_source_run_attachments:a.use_source_run_attachments}},c=ge(l,`Serializing body for uploaded example with id: ${o}`),u=new Blob([c],{type:"application/json"});if(n.append(o,u),a.inputs){let d=ge(a.inputs,`Serializing inputs for uploaded example with id: ${o}`),p=new Blob([d],{type:"application/json"});n.append(`${o}.inputs`,p)}if(a.outputs){let d=ge(a.outputs,`Serializing outputs for uploaded example with id: ${o}`),p=new Blob([d],{type:"application/json"});n.append(`${o}.outputs`,p)}if(a.attachments)for(let[d,p]of Object.entries(a.attachments)){let h,g;Array.isArray(p)?[h,g]=p:(h=p.mimeType,g=p.data);let b=new Blob([g],{type:`${h}; length=${g.byteLength}`});n.append(`${o}.attachment.${d}`,b)}}return(await this.caller.call(async()=>{let a=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 C(a,"upload examples"),a})).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]=he(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let a={};if(r?.description!==void 0&&(a.description=r.description),r?.readme!==void 0&&(a.readme=r.readme),r?.tags!==void 0&&(a.tags=r.tags),r?.isPublic!==void 0&&(a.is_public=r.isPublic),r?.isArchived!==void 0&&(a.is_archived=r.isArchived),Object.keys(a).length===0)throw new Error("No valid update options provided");let o=JSON.stringify(a);return(await this.caller.call(async()=>{let c=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 C(c,"update prompt"),c})).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]=he(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 C(o,"delete prompt"),o})).json()}_getPromptCacheKey(e,r){return`${e}${r?":with_model":""}`}async _fetchPromptFromApi(e,r){let[n,i,a]=he(e),l=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/commits/${n}/${i}/${a}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(c,"pull prompt commit"),c})).json();return{owner:n,repo:i,commit_hash:l.commit_hash,manifest:l.manifest,examples:l.examples,hub_model_config:l.model_config,hub_model_provider:l.model_provider}}async pullPromptCommit(e,r){Cm(e,r?.dangerouslyPullPublicPrompt);let n=this._fetchPromptFromApi.bind(this,e,r);if(!r?.skipCache&&this._promptCache){let i=this._getPromptCacheKey(e,r?.includeModel),a=this._promptCache.get(i,n);if(a)return a;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]=he(e);return this._repoExists(r,n)}async skillExists(e){let[r,n]=he(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,a=>a.repos))yield*i}async _pullDirectory(e,r,n){let[i,a,o]=he(e),l=n??(o!=="latest"?o:void 0),c=new URL(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${i}/${a}/directories`)}`);return c.searchParams.set("repo_type",r),l&&c.searchParams.set("commit",l),await(await this.caller.call(async()=>{let d=await this._fetch(c.toString(),{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(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,a]=he(e);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError(`push ${r}`,i);if(await this._repoExists(i,a))(n.description!==void 0||n.readme!==void 0||n.tags!==void 0||n.isPublic!==void 0)&&await this._updateRepoMetadata(i,a,n);else{let h=/^[a-z][a-z0-9-_]*$/;if(!h.test(a))throw new Error(`Invalid repo_handle ${JSON.stringify(a)}: must match ${h}`);await this._createRepo(a,r,n)}let o={files:n.files};n.parentCommit&&(o.parent_commit=n.parentCommit);let u=(await(await this.caller.call(async()=>{let h=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${i}/${a}/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 C(h,`push ${r}`),h})).json()).commit.commit_hash,d=await this._getSettings(),p=new URLSearchParams({organizationId:d.id});return`${this.getHostUrl()}/context/${a}/${u.slice(0,8)}?${p.toString()}`}async _deleteDirectory(e){let[r,n]=he(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 C(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 C(n,"check repo exists"),n}),!0}catch(n){if(Bn(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 a=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 C(a,`create ${r}`),a})}catch(a){if(yc(a))return;throw a}}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 a=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 C(a,"update repo metadata"),a})}async clonePublicDataset(e,r={}){let{sourceApiUrl:n=this.apiUrl,datasetName:i}=r,[a,o]=this.parseTokenOrUrl(e,n),l=new t({apiUrl:a,apiKey:"placeholder"}),c=await l.readSharedDataset(o),u=i||c.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}let d=await l.listSharedExamples(o),p=await this.createDataset(u,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:d.map(h=>h.inputs),outputs:d.flatMap(h=>h.outputs?[h.outputs]:[]),datasetId:p.id})}catch(h){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),h}}parseTokenOrUrl(e,r,n=2,i="dataset"){try{return L(e),[r,e]}catch{}try{let o=new URL(e).pathname.split("/").filter(l=>l!=="");if(o.length>=n){let l=o[o.length-n];return[r,l]}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 Ul()?.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(ut,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function Fc(t){return"dataset_id"in t||"dataset_name"in t}s(Fc,"isExampleCreate");var Ge=Symbol.for("lc:context_variables");var qn=Symbol.for("langsmith:replica_trace_roots");function Da(t,e){if(Ge in t)return t[Ge][e]}s(Da,"getContextVar");function Hc(t,e,r){let n=Ge in t?t[Ge]:{};n[e]=r,t[Ge]=n}s(Hc,"setContextVar");var Dr=36,Um="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function zc(t){let r=Object.keys(t).sort().map(n=>`${n}:${t[n]??""}`).join("|");return Ni(r,Um)}s(zc,"getReplicaKey");function Fm(t){return t.replace(/[-:.]/g,"")}s(Fm,"stripNonAlphanumeric");function Vc(t,e=1){let r=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${r}Z`}s(Vc,"getMicrosecondPrecisionDatestring");function Ua(t,e,r=1){let n=Vc(t,r);return{dottedOrder:Fm(n)+e,microsecondPrecisionDatestring:n}}s(Ua,"convertToDottedOrderFormat");var jm=new Set(["projectName","primary","updates","reroot"]);function Bm(t){let e={};for(let r of Object.keys(t))r==="primary"&&typeof t[r]!="boolean"||jm.has(r)&&(e[r]=t[r]);return e}s(Bm,"filterReplicaForHeaders");var Wn=class t{static{s(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=[],a,o;for(let l of r){let[c,u]=l.split("="),d=decodeURIComponent(u);c==="langsmith-metadata"?n=JSON.parse(d):c==="langsmith-tags"?i=d.split(","):c==="langsmith-project"?a=d:c==="langsmith-replicas"&&(o=JSON.parse(d).map(h=>Array.isArray(h)?h:Bm(h)))}return new t(n,i,a,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(",")}},Le=class t{static{s(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}),qc(e)){Object.assign(this,{...e});return}let r=t.getDefaultConfig(),{metadata:n,...i}=e,a=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:a}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=Vc(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=Vm(this.replicas),!this.dotted_order){let{dottedOrder:l}=Ua(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+l:this.dotted_order=l}}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:kr(),child_runs:[],api_url:ae("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:ae("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return t.sharedClient||(t.sharedClient=new ut),t.sharedClient}createChild(e){let r=this.child_execution_order+1,n=this.replicas?.map(h=>{let{reroot:g,...b}=h;return b}),i=e.replicas??n,a=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??{},l=a.extra?.metadata??{};Object.keys(o).length>0&&(a.extra={...a.extra,metadata:{...o,...l}}),Ge in this&&(a[Ge]=this[Ge]);let c=Symbol.for("lc:child_config"),u=e.extra?.[c]??this.extra[c];if(zm(u)){let h={...u},g=Hm(h.callbacks)?h.callbacks.copy?.():void 0;g&&(Object.assign(g,{_parentRunId:a.id}),g.handlers?.find(Wc)?.updateFromRunTree?.(a),h.callbacks=g),a.extra[c]=h}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(a),a}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[l,c]of Object.entries(r))i.runtime[l]||(i.runtime[l]=c);let a=e.parent_run?.id??e.parent_run_id,o;return n?o=[]:o=e.child_runs.map(l=>this._convertToCreate(l,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:a,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 a=0;a<n.length;a++)if(n[a].slice(-Dr)===e){i=a;break}if(i!==null){let a=n.slice(i+1);r.dotted_order=a.join("."),a.length>0?r.trace_id=a[0].slice(-Dr):r.trace_id=r.id}}r.parent_run_id===e&&(r.parent_run_id=void 0)}_setReplicaTraceRoot(e,r){let n=Da(this,qn)??{};n[e]=r,Hc(this,qn,n);for(let i of this.child_runs)i._setReplicaTraceRoot(e,r)}_remapForProject(e){let{projectName:r,primary:n,runtimeEnv:i,excludeChildRuns:a=!0,reroot:o=!1,distributedParentId:l,apiUrl:c,apiKey:u,workspaceId:d}=e,p=this._convertToCreate(this,i,a);if(n===void 0&&r===this.project_name)return{...p,session_name:r};if(o){if(l)this._sliceParentId(l,p);else if(p.parent_run_id=void 0,p.dotted_order){let A=p.dotted_order.split(".");A.length>0&&(p.dotted_order=A[A.length-1],p.trace_id=p.id)}let S=zc({projectName:r,apiUrl:c,apiKey:u,workspaceId:d});this._setReplicaTraceRoot(S,p.id)}let h;if(!o){let S=Da(this,qn)??{},A=zc({projectName:r,apiUrl:c,apiKey:u,workspaceId:d});if(h=S[A],h&&(p.trace_id=h,p.dotted_order)){let R=p.dotted_order.split("."),$=null;for(let N=0;N<R.length;N++)if(R[N].slice(-Dr)===h){$=N;break}if($!==null){let N=R.slice($);p.dotted_order=N.join(".")}}}if(n)return{...p,session_name:r};let g=p.id,b=rr(g,r),v;p.trace_id?v=rr(p.trace_id,r):v=b;let P;p.parent_run_id&&(P=rr(p.parent_run_id,r));let I;return p.dotted_order&&(I=p.dotted_order.split(".").map(R=>{let $=R.slice(-Dr),N=rr($,r);return R.slice(0,-Dr)+N}).join(".")),{...p,id:b,trace_id:v,parent_run_id:P,dotted_order:I,session_name:r}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let r=xn();if(this.replicas&&this.replicas.length>0)for(let{projectName:n,primary:i,apiKey:a,apiUrl:o,workspaceId:l,reroot:c,client:u}of this.replicas){let d=this._remapForProject({projectName:n??this.project_name,primary:i,runtimeEnv:r,excludeChildRuns:!0,reroot:c,distributedParentId:this.distributedParentId,apiUrl:o,apiKey:a,workspaceId:l});await(u??this.client).createRun(d,{apiKey:a,apiUrl:o,workspaceId:l})}else{let n=this._convertToCreate(this,r,e);await this.client.createRun(n)}if(!e){se("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:a,workspaceId:o,updates:l,reroot:c,client:u}of this.replicas){let d=this._remapForProject({projectName:r??this.project_name,primary:n,runtimeEnv:void 0,excludeChildRuns:!0,reroot:c,distributedParentId:this.distributedParentId,apiUrl:a,apiKey:i,workspaceId:o}),p={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,...l};e?.excludeInputs||(p.inputs=d.inputs),await(u??this.client).updateRun(d.id,p,{apiKey:i,apiUrl:a,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,a,o,l=qi();if(n){let u=n?.getParentRunId?.()??"",d=n?.handlers?.find(p=>p?.name=="langchain_tracer");i=d?.getRun?.(u),a=d?.projectName,o=d?.client,l=l||!!d}return i?new t({name:i.name,id:i.id,trace_id:i.trace_id,dotted_order:i.dotted_order,client:o,tracingEnabled:l,project_name:a,tags:[...new Set((i?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...i?.extra?.metadata,...e?.metadata}}}).createChild(r):new t({...r,client:o,tracingEnabled:l,project_name:a})}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 a=i.trim(),o=a.split(".").map(d=>{let[p,h]=d.split("Z");return{strTime:p,time:Date.parse(p+"Z"),uuid:h}}),l=o[0].uuid,c={...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:l,dotted_order:a};if(n.baggage&&typeof n.baggage=="string"){let d=Wn.fromHeader(n.baggage);c.metadata=d.metadata,c.tags=d.tags,c.project_name=d.project_name,c.replicas=d.replicas}let u=new t(c);return u.distributedParentId=u.id,u}toHeaders(e){let r={"langsmith-trace":this.dotted_order,baggage:new Wn(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(Le,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function qc(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}s(qc,"isRunTree");function Wc(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}s(Wc,"isLangChainTracerLike");function Gc(t){return Array.isArray(t)&&t.some(e=>Wc(e))}s(Gc,"containsLangChainTracerLike");function Hm(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}s(Hm,"isCallbackManagerLike");function zm(t){let e=t?.callbacks;return t!=null&&typeof e=="object"&&(Gc(e?.handlers)||Gc(e))}s(zm,"isRunnableConfigLike");function Gm(){let t=ae("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){qm(e);let r=[];for(let[n,i]of Object.entries(e)){let a=n.replace(/\/$/,"");if(typeof i=="string")r.push({apiUrl:a,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(bc(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"),[]}}s(Gm,"_getWriteReplicasFromEnv");function Vm(t){let e=t?t.map(r=>Array.isArray(r)?{projectName:r[0],updates:r[1]}:r):Gm();if(e.filter(r=>r.primary===!0).length>1)throw new Error("Only one replica can be marked as primary.");return e}s(Vm,"_ensureWriteReplicas");function qm(t){if(Object.keys(t).length>0&&q("ENDPOINT"))throw new Fn}s(qm,"_checkEndpointEnvUnset");var Wm=s(t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t},"convertRunTreeToRun");function ja(t,e){if(t)return new Le({...t,start_time:t._serialized_start_time??t.start_time,parent_run:ja(e),child_runs:t.child_runs.map(r=>ja(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:Co()},tracingEnabled:!1})}s(ja,"convertRunToRunTree");function Fa(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}s(Fa,"_coerceToDict");function _r(t){return typeof t._addRunToRunMap=="function"}s(_r,"isBaseTracer");var Ht=class extends Jt{static{s(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?Wm(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`
146
+
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 a=ja(n,i);a!==void 0&&this.runTreeMap.set(n.id,a)}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,a,o,l){let c=this._getExecutionOrder(n),u=Date.now(),d=o?{...i,metadata:o}:i,p={id:r,name:l??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:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(p)}async handleLLMStart(t,e,r,n,i,a,o,l){let c=this.getRunById(r)??this._createRunForLLMStart(t,e,r,n,i,a,o,l);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(t,e,r,n,i,a,o,l){let c=this._getExecutionOrder(n),u=Date.now(),d=o?{...i,metadata:o}:i,p={id:r,name:l??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:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(p)}async handleChatModelStart(t,e,r,n,i,a,o,l){let c=this.getRunById(r)??this._createRunForChatModelStart(t,e,r,n,i,a,o,l);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(t,e,r,n,i){let a=this.getRunById(e);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=t,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMEnd?.(a),await this._endTrace(a),a}async handleLLMError(t,e,r,n,i){let a=this.getRunById(e);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(t),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMError?.(a),await this._endTrace(a),a}_createRunForChainStart(t,e,r,n,i,a,o,l,c){let u=this._getExecutionOrder(n),d=Date.now(),p={id:r,name:l??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:a?{...c,metadata:a}:{...c},tags:i||[]};return this._addRunToRunMap(p)}async handleChainStart(t,e,r,n,i,a,o,l){let c=this.getRunById(r)??this._createRunForChainStart(t,e,r,n,i,a,o,l);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(t,e,r,n,i){let a=this.getRunById(e);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=Fa(t,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=Fa(i.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(t,e,r,n,i){let a=this.getRunById(e);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(t),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=Fa(i.inputs,"input")),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(t,e,r,n,i,a,o){let l=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:e},execution_order:l,child_execution_order:l,run_type:"tool",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleToolStart(t,e,r,n,i,a,o){let l=this.getRunById(r)??this._createRunForToolStart(t,e,r,n,i,a,o);return await this.onRunCreate?.(l),await this.onToolStart?.(l),l}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,a,o){let l=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:e},execution_order:l,child_execution_order:l,run_type:"retriever",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(t,e,r,n,i,a,o){let l=this.getRunById(r)??this._createRunForRetrieverStart(t,e,r,n,i,a,o);return await this.onRunCreate?.(l),await this.onRetrieverStart?.(l),l}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,a){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:a?.chunk}}),await this.onLLMNewToken?.(o,t,{chunk:a?.chunk}),o}};var Jc={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 we(t,e){return`${t.open}${e}${t.close}`}s(we,"wrap");function ke(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}s(ke,"tryJsonStringify");function Kc(t){return typeof t=="string"?t.trim():t==null?t:ke(t,t.toString())}s(Kc,"formatKVMapItem");function gt(t){if(!t.end_time)return"";let e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}s(gt,"elapsed");var{color:Se}=Jc,Ba=class extends Ht{static{s(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 a=`${r.execution_order}:${r.run_type}:${r.name}`;return n===i.length-1?we(Jc.bold,a):a}).join(" > ");return we(Se.grey,e)}onChainStart(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.green,"[chain/start]")} [${e}] Entering Chain run with input: ${ke(t.inputs,"[inputs]")}`)}onChainEnd(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.cyan,"[chain/end]")} [${e}] [${gt(t)}] Exiting Chain run with output: ${ke(t.outputs,"[outputs]")}`)}onChainError(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.red,"[chain/error]")} [${e}] [${gt(t)}] Chain run errored with error: ${ke(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(`${we(Se.green,"[llm/start]")} [${e}] Entering LLM run with input: ${ke(r,"[inputs]")}`)}onLLMEnd(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.cyan,"[llm/end]")} [${e}] [${gt(t)}] Exiting LLM run with output: ${ke(t.outputs,"[response]")}`)}onLLMError(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.red,"[llm/error]")} [${e}] [${gt(t)}] LLM run errored with error: ${ke(t.error,"[error]")}`)}onToolStart(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.green,"[tool/start]")} [${e}] Entering Tool run with input: "${Kc(t.inputs.input)}"`)}onToolEnd(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.cyan,"[tool/end]")} [${e}] [${gt(t)}] Exiting Tool run with output: "${Kc(t.outputs?.output)}"`)}onToolError(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.red,"[tool/error]")} [${e}] [${gt(t)}] Tool run errored with error: ${ke(t.error,"[error]")}`)}onRetrieverStart(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${ke(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.cyan,"[retriever/end]")} [${e}] [${gt(t)}] Exiting Retriever run with output: ${ke(t.outputs,"[outputs]")}`)}onRetrieverError(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.red,"[retriever/error]")} [${e}] [${gt(t)}] Retriever run errored with error: ${ke(t.error,"[error]")}`)}onAgentAction(t){let e=t,r=this.getBreadcrumbs(t);console.log(`${we(Se.blue,"[agent/action]")} [${r}] Agent selected action: ${ke(e.actions[e.actions.length-1],"[action]")}`)}};var Ha,za=s(()=>(Ha===void 0&&(Ha=new ut(Me("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),Ha),"getDefaultLangChainClientSingleton");var Yc=new Set(["ls_agent_type"]);function Km(t){let e;for(let r of t)for(let n of r)at.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=Qr(e,n.message.usage_metadata));return e}s(Km,"_getUsageMetadataFromGenerations");var Ur=class Ga extends Ht{static{s(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:a,metadata:o,tags:l}=e;this.projectName=n??kr(),this.replicas=a,this.exampleId=r,this.client=i??za(),this.tracingMetadata=o?{...o}:void 0,this.tracingTags=l??[];let c=Ga.getTraceableRunTree();c&&this.updateFromRunTree(c)}async persistRun(e){}async onRunCreate(e){Zc(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){Zc(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=Km(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,l]of Object.entries(e))(!Object.prototype.hasOwnProperty.call(n,o)||Yc.has(o))&&(n[o]=l)}let i=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],a=new Ga({...this.fields,metadata:n,tags:i});return a.runMap=this.runMap,a.runTreeMap=this.runTreeMap,a}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 a=i.shift();!a||n.has(a.id)||(n.add(a.id),this.runTreeMap.set(a.id,a),a.child_runs&&i.push(...a.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId,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 Le({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Zi(!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 Zc(t,e){if(t.tracingMetadata){e.extra??={};let r=e.extra.metadata??{},n=!1;for(let[i,a]of Object.entries(t.tracingMetadata))(!Object.prototype.hasOwnProperty.call(r,i)||Yc.has(i))&&r[i]!==a&&(r[i]=a,n=!0);n&&(e.extra.metadata=r)}t.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...t.tracingTags])))}s(Zc,"_patchMissingTracingDefaults");var Kn=it(cn(),1);var Fr;function Jm(){return new("default"in Kn.default?Kn.default.default:Kn.default)({autoStart:!0,concurrency:1})}s(Jm,"createQueue");function Zm(){return typeof Fr>"u"&&(Fr=Jm()),Fr}s(Zm,"getQueue");async function Y(t,e){if(e===!0){let r=ot();r!==void 0?await r.run(void 0,async()=>t()):await t()}else Fr=Zm(),Fr.add(async()=>{let r=ot();r!==void 0?await r.run(void 0,async()=>t()):await t()})}s(Y,"consumeCallback");var Xc=s(t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>Me(e)==="true"),"isTracingEnabled");function Va(t){let e=ot();if(e!==void 0)return e.getStore()?.[xt]?.[t]}s(Va,"getContextVariable");var Ym=Symbol("lc:configure_hooks"),Qc=s(()=>Va(Ym)||[],"_getConfigureHooks");var Xm=class{static{s(this,"BaseCallbackManager")}setHandler(t){return this.setHandlers([t])}},Jn=class{static{s(this,"BaseRunManager")}constructor(t,e,r,n,i,a,o,l){this.runId=t,this.handlers=e,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=i,this.metadata=a,this.inheritableMetadata=o,this._parentRunId=l}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>Y(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(a=>Y(async()=>{try{await a.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}},Qm=class extends Jn{static{s(this,"CallbackManagerForRetrieverRun")}getChild(t){let e=new zt(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=>Y(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=>Y(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)))}},eu=class extends Jn{static{s(this,"CallbackManagerForLLMRun")}async handleLLMNewToken(t,e,r,n,i,a){await Promise.all(this.handlers.map(o=>Y(async()=>{if(!o.ignoreLLM)try{await o.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a)}catch(l){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleLLMNewToken: ${l}`),o.raiseError)throw l}},o.awaitHandlers)))}async handleChatModelStreamEvent(t){await Promise.all(this.handlers.map(e=>Y(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(a=>Y(async()=>{if(!a.ignoreLLM)try{await a.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,i)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMError: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleLLMEnd(t,e,r,n,i){await Promise.all(this.handlers.map(a=>Y(async()=>{if(!a.ignoreLLM)try{await a.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,i)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMEnd: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}},eh=class extends Jn{static{s(this,"CallbackManagerForChainRun")}getChild(t){let e=new zt(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(a=>Y(async()=>{if(!a.ignoreChain)try{await a.handleChainError?.(t,this.runId,this._parentRunId,this.tags,i)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainError: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleChainEnd(t,e,r,n,i){await Promise.all(this.handlers.map(a=>Y(async()=>{if(!a.ignoreChain)try{await a.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,i)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainEnd: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>Y(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=>Y(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)))}},th=class extends Jn{static{s(this,"CallbackManagerForToolRun")}getChild(t){let e=new zt(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=>Y(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=>Y(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=>Y(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)))}},zt=class jr extends Xm{static{s(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,a=void 0,o=void 0,l=void 0,c=void 0){return Promise.all(r.map(async(u,d)=>{let p=d===0&&n?n:De();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return _r(h)&&h._createRunForLLMStart(e,[u],p,this._parentRunId,a,this.tags,this.metadata,c),Y(async()=>{try{await h.handleLLMStart?.(e,[u],p,this._parentRunId,a,this.tags,this.metadata,c)}catch(g){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${g}`),h.raiseError)throw g}},h.awaitHandlers)})),new eu(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,r,n=void 0,i=void 0,a=void 0,o=void 0,l=void 0,c=void 0){return Promise.all(r.map(async(u,d)=>{let p=d===0&&n?n:De();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return _r(h)&&h._createRunForChatModelStart(e,[u],p,this._parentRunId,a,this.tags,this.metadata,c),Y(async()=>{try{if(h.handleChatModelStart)await h.handleChatModelStart?.(e,[u],p,this._parentRunId,a,this.tags,this.metadata,c);else if(h.handleLLMStart){let g=rn(u);await h.handleLLMStart?.(e,[g],p,this._parentRunId,a,this.tags,this.metadata,c)}}catch(g){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${g}`),h.raiseError)throw g}},h.awaitHandlers)})),new eu(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,r,n=De(),i=void 0,a=void 0,o=void 0,l=void 0,c=void 0,u=void 0){return await Promise.all(this.handlers.map(d=>{if(!d.ignoreChain)return _r(d)&&d._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,i,l,u),Y(async()=>{try{await d.handleChainStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,i,l,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 eh(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,r,n=De(),i=void 0,a=void 0,o=void 0,l=void 0,c=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return _r(u)&&u._createRunForToolStart(e,r,n,this._parentRunId,this.tags,this.metadata,l),Y(async()=>{try{await u.handleToolStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,l,c)}catch(d){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${d}`),u.raiseError)throw d}},u.awaitHandlers)})),new th(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,r,n=De(),i=void 0,a=void 0,o=void 0,l=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return _r(c)&&c._createRunForRetrieverStart(e,r,n,this._parentRunId,this.tags,this.metadata,l),Y(async()=>{try{await c.handleRetrieverStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,l)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new Qm(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,r,n,i,a){await Promise.all(this.handlers.map(o=>Y(async()=>{if(!o.ignoreCustomEvent)try{await o.handleCustomEvent?.(e,r,n,this.tags,this.metadata)}catch(l){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleCustomEvent: ${l}`),o.raiseError)throw l}},o.awaitHandlers)))}addHandler(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 jr(this._parentRunId);for(let i of this.handlers){let a=this.inheritableHandlers.includes(i);n.addHandler(i,a)}for(let i of this.tags){let a=this.inheritableTags.includes(i);n.addTags([i],a)}for(let i of Object.keys(this.metadata)){let a=Object.keys(this.inheritableMetadata).includes(i);n.addMetadata({[i]:this.metadata[i]},a)}for(let i of e)n.handlers.filter(a=>a.name==="console_callback_handler").some(a=>a.name===i.name)||n.addHandler(i,r);return n}static fromHandlers(e){class r extends Jt{static{s(this,"Handler")}name=De();constructor(){super(),Object.assign(this,e)}}let n=new this;return n.addHandler(new r),n}static configure(e,r,n,i,a,o,l){return this._configureSync(e,r,n,i,a,o,l)}static _configureSync(e,r,n,i,a,o,l){let c;(e||r)&&(Array.isArray(e)||!e?(c=new jr,c.setHandlers(e?.map(qa)??[],!0)):c=e,c=c.copy(Array.isArray(r)?r.map(qa):r?.handlers,!1));let u=Me("LANGCHAIN_VERBOSE")==="true"||l?.verbose,d=Ur.getTraceableRunTree(),p=d?.tracingEnabled??Xc();if(d?.tracingEnabled===!1&&c){let v=c.handlers.filter(P=>P.name==="langchain_tracer");for(let P of v)c.removeHandler(P)}let h=p||(Me("LANGCHAIN_TRACING")??!1);if(u||h){if(c||(c=new jr),u&&!c.handlers.some(v=>v.name===Ba.prototype.name)){let v=new Ba;c.addHandler(v,!0)}if(h&&!c.handlers.some(v=>v.name==="langchain_tracer")&&p){let v=new Ur;c.addHandler(v,!0)}p&&d&&c._parentRunId===void 0&&(c._parentRunId=d.id,c.handlers.find(v=>v.name==="langchain_tracer")?.updateFromRunTree(d))}for(let{contextVar:v,inheritable:P=!0,handlerClass:I,envVar:S}of Qc()){let A=S&&Me(S)==="true"&&I,R,$=v!==void 0?Va(v):void 0;$&&ko($)?R=$:A&&(R=new I({})),R!==void 0&&(c||(c=new jr),c.handlers.some(N=>N.name===R.name)||c.addHandler(R,P))}(n||i)&&c&&(c.addTags(n??[]),c.addTags(i??[],!1)),(a||o)&&c&&(c.addMetadata(a??{}),c.addMetadata(o??{},!1));let g=l?.tracerInheritableMetadata,b=l?.tracerInheritableTags;return c&&(g||b)&&(c.handlers=c.handlers.map(v=>v instanceof Ur?v.copyWithTracingConfig({metadata:g,tags:b}):v),c.inheritableHandlers=c.inheritableHandlers.map(v=>v instanceof Ur?v.copyWithTracingConfig({metadata:g,tags:b}):v)),c}};function qa(t){return"name"in t?t:Jt.fromMethods(t)}s(qa,"ensureHandler");var ru=class{static{s(this,"MockAsyncLocalStorage")}getStore(){}run(t,e){return e()}enterWith(t){}},rh=new ru,tu=Symbol.for("lc:child_config"),nh=class{static{s(this,"AsyncLocalStorageProvider")}getInstance(){return ot()??rh}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[tu]}runWithConfig(t,e,r){let n=zt._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),i=this.getInstance(),a=i.getStore(),o=n?.getParentRunId(),l=n?.handlers?.find(u=>u?.name==="langchain_tracer"),c;return l&&o?c=l.getRunTreeWithTracingConfig(o):r||(c=new Le({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[tu]:t}),a!==void 0&&a[xt]!==void 0&&(c===void 0&&(c={}),c[xt]=a[xt]),i.run(c,e)}initializeGlobalInstance(t){ot()===void 0&&Io(t)}},Br=new nh;var ih=Object.prototype.hasOwnProperty;function au(t,e){return ih.call(t,e)}s(au,"hasOwnProperty");function su(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)au(t,r)&&e.push(r);return e}s(su,"_objectKeys");function Xe(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}s(Xe,"_deepClone");function Yn(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}s(Yn,"isInteger");function ou(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}s(ou,"unescapePathComponent");function Zn(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(Zn(t[r]))return!0}else if(typeof t=="object"){let r=su(t),n=r.length;for(var e=0;e<n;e++)if(Zn(t[r[e]]))return!0}}return!1}s(Zn,"hasUndefined");function iu(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
+ `)}s(iu,"patchErrorMessageFormatter");var lu=class extends Error{static{s(this,"PatchError")}constructor(t,e,r,n,i){super(iu(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=iu(t,{name:e,index:r,operation:n,tree:i})}};var cu=H({JsonPatchError:s(()=>X,"JsonPatchError"),_areEquals:s(()=>Hr,"_areEquals"),applyOperation:s(()=>Gt,"applyOperation"),applyPatch:s(()=>ei,"applyPatch"),applyReducer:s(()=>oh,"applyReducer"),deepClone:s(()=>ah,"deepClone"),getValueByPointer:s(()=>Xn,"getValueByPointer"),validate:s(()=>uu,"validate"),validator:s(()=>Qn,"validator")}),X=lu,ah=Xe,br={add:s(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:s(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:s(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:s(function(t,e,r){let n=Xn(r,this.path);n&&(n=Xe(n));let i=Gt(r,{op:"remove",path:this.from}).removed;return Gt(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},"move"),copy:s(function(t,e,r){let n=Xn(r,this.from);return Gt(r,{op:"add",path:this.path,value:Xe(n)}),{newDocument:r}},"copy"),test:s(function(t,e,r){return{newDocument:r,test:Hr(t[e],this.value)}},"test"),_get:s(function(t,e,r){return this.value=t[e],{newDocument:r}},"_get")},sh={add:s(function(t,e,r){return Yn(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},"add"),remove:s(function(t,e,r){return{newDocument:r,removed:t.splice(e,1)[0]}},"remove"),replace:s(function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},"replace"),move:br.move,copy:br.copy,test:br.test,_get:br._get};function Xn(t,e){if(e=="")return t;var r={op:"_get",path:e};return Gt(t,r),r.value}s(Xn,"getValueByPointer");function Gt(t,e,r=!1,n=!0,i=!0,a=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):Qn(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=Xn(t,e.from),e.op==="move"&&(o.removed=t),o;if(e.op==="test"){if(o.test=Hr(t,e.value),o.test===!1)throw new X("Test operation failed","TEST_OPERATION_FAILED",a,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 X("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",a,e,t);return o}}else{n||(t=Xe(t));let o=(e.path||"").split("/"),l=t,c=1,u=o.length,d,p,h;for(typeof r=="function"?h=r:h=Qn;;){if(p=o[c],p&&p.indexOf("~")!=-1&&(p=ou(p)),i&&(p=="__proto__"||p=="prototype"&&c>0&&o[c-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&d===void 0&&(l[p]===void 0?d=o.slice(0,c).join("/"):c==u-1&&(d=e.path),d!==void 0&&h(e,0,t,d)),c++,Array.isArray(l)){if(p==="-")p=l.length;else{if(r&&!Yn(p))throw new X("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",a,e,t);Yn(p)&&(p=~~p)}if(c>=u){if(r&&e.op==="add"&&p>l.length)throw new X("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,e,t);let g=sh[e.op].call(e,l,p,t);if(g.test===!1)throw new X("Test operation failed","TEST_OPERATION_FAILED",a,e,t);return g}}else if(c>=u){let g=br[e.op].call(e,l,p,t);if(g.test===!1)throw new X("Test operation failed","TEST_OPERATION_FAILED",a,e,t);return g}if(l=l[p],r&&c<u&&(!l||typeof l!="object"))throw new X("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",a,e,t)}}}s(Gt,"applyOperation");function ei(t,e,r,n=!0,i=!0){if(r&&!Array.isArray(e))throw new X("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=Xe(t));let a=new Array(e.length);for(let o=0,l=e.length;o<l;o++)a[o]=Gt(t,e[o],r,!0,i,o),t=a[o].newDocument;return a.newDocument=t,a}s(ei,"applyPatch");function oh(t,e,r){let n=Gt(t,e);if(n.test===!1)throw new X("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}s(oh,"applyReducer");function Qn(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new X("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(br[t.op]){if(typeof t.path!="string")throw new X("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new X('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 X("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 X("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")&&Zn(t.value))throw new X("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,a=n.split("/").length;if(i!==a+1&&i!==a)throw new X("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 X("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=uu([{op:"_get",path:t.from,value:void 0}],r);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new X("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new X("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}s(Qn,"validator");function uu(t,e,r){try{if(!Array.isArray(t))throw new X("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)ei(Xe(e),Xe(t),r||!0);else{r=r||Qn;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(i){if(i instanceof X)return i;throw i}}s(uu,"validate");function Hr(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,a,o;if(r&&n){if(a=t.length,a!=e.length)return!1;for(i=a;i--!==0;)if(!Hr(t[i],e[i]))return!1;return!0}if(r!=n)return!1;var l=Object.keys(t);if(a=l.length,a!==Object.keys(e).length)return!1;for(i=a;i--!==0;)if(!e.hasOwnProperty(l[i]))return!1;for(i=a;i--!==0;)if(o=l[i],!Hr(t[o],e[o]))return!1;return!0}return t!==t&&e!==e}s(Hr,"_areEquals");({...cu});var V1=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 mh=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,hh=[0,31,28,31,30,31,30,31,31,30,31,30,31],gh=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,yh=/^(?=.{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,_h=/^(?:[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,bh=/^(?:(?:[^\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,wh=/^(?:(?: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,vh=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,xh=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Eh=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Sh=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Th=s(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"),Ah=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Ih=/^((([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,Ch=s(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 Ve(t){return t.test.bind(t)}s(Ve,"bind");var kh={date:du,time:pu.bind(void 0,!1),"date-time":Rh,duration:Ch,uri:Lh,"uri-reference":Ve(_h),"uri-template":Ve(bh),url:Ve(wh),email:Th,hostname:Ve(yh),ipv4:Ve(Ah),ipv6:Ve(Ih),regex:Dh,uuid:Ve(vh),"json-pointer":Ve(xh),"json-pointer-uri-fragment":Ve(Eh),"relative-json-pointer":Ve(Sh)};function Oh(t){return t%4===0&&(t%100!==0||t%400===0)}s(Oh,"isLeapYear");function du(t){let e=t.match(mh);if(!e)return!1;let r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&Oh(r)?29:hh[n])}s(du,"date");function pu(t,e){let r=e.match(gh);if(!r)return!1;let n=+r[1],i=+r[2],a=+r[3],o=!!r[5];return(n<=23&&i<=59&&a<=59||n==23&&i==59&&a==60)&&(!t||o)}s(pu,"time");var Ph=/t|\s/i;function Rh(t){let e=t.split(Ph);return e.length==2&&du(e[0])&&pu(!0,e[1])}s(Rh,"date_time");var Mh=/\/|:/,Nh=/^(?:[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 Lh(t){return Mh.test(t)&&Nh.test(t)}s(Lh,"uri");var $h=/[^\\]\\Z/;function Dh(t){if($h.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}s(Dh,"regex");var fu;(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(fu||(fu={}));var Tu=it(Su(),1);var Qh=Object.defineProperty,eg=s((t,e,r)=>e in t?Qh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,"__defNormalProp"),tg=s((t,e,r)=>(eg(t,typeof e!="symbol"?e+"":e,r),r),"__publicField");function rg(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 a=t.slice(r[i].start,r[i+1].end),o=e.get(a.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}s(rg,"bytePairMerge");function ng(t,e){return t.length===1?[e.get(t.join(","))]:rg(t,e).map(r=>e.get(t.slice(r.start,r.end).join(","))).filter(r=>r!=null)}s(ng,"bytePairEncode");function ig(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}s(ig,"escapeRegex");var Xa=class{static{s(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[a,o,...l]=i.split(" "),c=Number.parseInt(o,10);return l.forEach((u,d)=>n[u]=c+d),n},{});for(let[n,i]of Object.entries(r)){let a=Tu.default.toByteArray(n);this.rankMap.set(a.join(","),i),this.textMap.set(i,a)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[i,a])=>(n[a]=this.textEncoder.encode(i),n),{})}encode(t,e=[],r="all"){let n=new RegExp(this.patStr,"ug"),i=Xa.specialTokenRegex(Object.keys(this.specialTokens)),a=[],o=new Set(e==="all"?Object.keys(this.specialTokens):e),l=new Set(r==="all"?Object.keys(this.specialTokens).filter(u=>!o.has(u)):r);if(l.size>0){let u=Xa.specialTokenRegex([...l]),d=t.match(u);if(d!=null)throw new Error(`The text contains a special token that is not allowed: ${d[0]}`)}let c=0;for(;;){let u=null,d=c;for(;i.lastIndex=d,u=i.exec(t),!(u==null||o.has(u[0]));)d=u.index+1;let p=u?.index??t.length;for(let g of t.substring(c,p).matchAll(n)){let b=this.textEncoder.encode(g[0]),v=this.rankMap.get(b.join(","));if(v!=null){a.push(v);continue}a.push(...ng(b,this.rankMap))}if(u==null)break;let h=this.specialTokens[u[0]];a.push(h),c=u.index+u[0].length}return a}decode(t){let e=[],r=0;for(let a=0;a<t.length;++a){let o=t[a],l=this.textMap.get(o)??this.inverseSpecialTokens[o];l!=null&&(e.push(l),r+=l.length)}let n=new Uint8Array(r),i=0;for(let a of e)n.set(a,i),i+=a.length;return this.textDecoder.decode(n)}},Qa=Xa;tg(Qa,"specialTokenRegex",t=>new RegExp(t.map(e=>ig(e)).join("|"),"g"));var ku=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"];var Ou=["image","video","audio","text-plain","file"];var og=["text","reasoning",...ku,...Ou];var hg=s(function(){let t={};t.parser=function(m,f){return new r(m,f)},t.SAXParser=r,t.SAXStream=u,t.createStream=c,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,f){if(!(this instanceof r))return new r(m,f);var x=this;i(x),x.q=x.c="",x.bufferCheckPosition=t.MAX_BUFFER_LENGTH,x.opt=f||{},x.opt.lowercase=x.opt.lowercase||x.opt.lowercasetags,x.looseCase=x.opt.lowercase?"toLowerCase":"toUpperCase",x.tags=[],x.closed=x.closedRoot=x.sawRoot=!1,x.tag=x.error=null,x.strict=!!m,x.noscript=!!(m||x.opt.noscript),x.state=y.BEGIN,x.strictEntities=x.opt.strictEntities,x.ENTITIES=x.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),x.attribList=[],x.opt.xmlns&&(x.ns=Object.create(b)),x.trackPosition=x.opt.position!==!1,x.trackPosition&&(x.position=x.line=x.column=0),B(x,"onready")}s(r,"SAXParser"),Object.create||(Object.create=function(m){function f(){}return s(f,"F"),f.prototype=m,new f}),Object.keys||(Object.keys=function(m){var f=[];for(var x in m)m.hasOwnProperty(x)&&f.push(x);return f});function n(m){for(var f=Math.max(t.MAX_BUFFER_LENGTH,10),x=0,_=0,G=e.length;_<G;_++){var Q=m[e[_]].length;if(Q>f)switch(e[_]){case"textNode":de(m);break;case"cdata":F(m,"oncdata",m.cdata),m.cdata="";break;case"script":F(m,"onscript",m.script),m.script="";break;default:rt(m,"Max buffer length exceeded: "+e[_])}x=Math.max(x,Q)}m.bufferCheckPosition=t.MAX_BUFFER_LENGTH-x+m.position}s(n,"checkBufferLength");function i(m){for(var f=0,x=e.length;f<x;f++)m[e[f]]=""}s(i,"clearBuffers");function a(m){de(m),m.cdata!==""&&(F(m,"oncdata",m.cdata),m.cdata=""),m.script!==""&&(F(m,"onscript",m.script),m.script="")}s(a,"flushBuffers"),r.prototype={end:s(function(){vr(this)},"end"),write:rd,resume:s(function(){return this.error=null,this},"resume"),close:s(function(){return this.write(null)},"close"),flush:s(function(){a(this)},"flush")};var o=ReadableStream;o||(o=s(function(){},"Stream"));var l=t.EVENTS.filter(function(m){return m!=="error"&&m!=="end"});function c(m,f){return new u(m,f)}s(c,"createStream");function u(m,f){if(!(this instanceof u))return new u(m,f);o.apply(this),this._parser=new r(m,f),this.writable=!0,this.readable=!0;var x=this;this._parser.onend=function(){x.emit("end")},this._parser.onerror=function(_){x.emit("error",_),x._parser.error=null},this._decoder=null,l.forEach(function(_){Object.defineProperty(x,"on"+_,{get:s(function(){return x._parser["on"+_]},"get"),set:s(function(G){if(!G)return x.removeAllListeners(_),x._parser["on"+_]=G,G;x.on(_,G)},"set"),enumerable:!0,configurable:!1})})}s(u,"SAXStream"),u.prototype=Object.create(o.prototype,{constructor:{value:u}}),u.prototype.write=function(m){return this._parser.write(m.toString()),this.emit("data",m),!0},u.prototype.end=function(m){return m&&m.length&&this.write(m),this._parser.end(),!0},u.prototype.on=function(m,f){var x=this;return!x._parser["on"+m]&&l.indexOf(m)!==-1&&(x._parser["on"+m]=function(){var _=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);_.splice(0,0,m),x.emit.apply(x,_)}),o.prototype.on.call(x,m,f)};var d="[CDATA[",p="DOCTYPE",h="http://www.w3.org/XML/1998/namespace",g="http://www.w3.org/2000/xmlns/",b={xml:h,xmlns:g},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]/,P=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,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]/,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 A(m){return m===" "||m===`
150
+ `||m==="\r"||m===" "}s(A,"isWhitespace");function R(m){return m==='"'||m==="'"}s(R,"isQuote");function $(m){return m===">"||A(m)}s($,"isAttribEnd");function N(m,f){return m.test(f)}s(N,"isMatch");function j(m,f){return!N(m,f)}s(j,"notMatch");var y=0;t.STATE={BEGIN:y++,BEGIN_WHITESPACE:y++,TEXT:y++,TEXT_ENTITY:y++,OPEN_WAKA:y++,SGML_DECL:y++,SGML_DECL_QUOTED:y++,DOCTYPE:y++,DOCTYPE_QUOTED:y++,DOCTYPE_DTD:y++,DOCTYPE_DTD_QUOTED:y++,COMMENT_STARTING:y++,COMMENT:y++,COMMENT_ENDING:y++,COMMENT_ENDED:y++,CDATA:y++,CDATA_ENDING:y++,CDATA_ENDING_2:y++,PROC_INST:y++,PROC_INST_BODY:y++,PROC_INST_ENDING:y++,OPEN_TAG:y++,OPEN_TAG_SLASH:y++,ATTRIB:y++,ATTRIB_NAME:y++,ATTRIB_NAME_SAW_WHITE:y++,ATTRIB_VALUE:y++,ATTRIB_VALUE_QUOTED:y++,ATTRIB_VALUE_CLOSED:y++,ATTRIB_VALUE_UNQUOTED:y++,ATTRIB_VALUE_ENTITY_Q:y++,ATTRIB_VALUE_ENTITY_U:y++,CLOSE_TAG:y++,CLOSE_TAG_SAW_WHITE:y++,SCRIPT:y++,SCRIPT_ENDING:y++},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(m){var f=t.ENTITIES[m],x=typeof f=="number"?String.fromCharCode(f):f;t.ENTITIES[m]=x});for(var K in t.STATE)t.STATE[t.STATE[K]]=K;y=t.STATE;function B(m,f,x){m[f]&&m[f](x)}s(B,"emit");function F(m,f,x){m.textNode&&de(m),B(m,f,x)}s(F,"emitNode");function de(m){m.textNode=tt(m.opt,m.textNode),m.textNode&&B(m,"ontext",m.textNode),m.textNode=""}s(de,"closeText");function tt(m,f){return m.trim&&(f=f.trim()),m.normalize&&(f=f.replace(/\s+/g," ")),f}s(tt,"textopts");function rt(m,f){return de(m),m.trackPosition&&(f+=`
151
+ Line: `+m.line+`
152
+ Column: `+m.column+`
153
+ Char: `+m.c),f=new Error(f),m.error=f,B(m,"onerror",f),m}s(rt,"error");function vr(m){return m.sawRoot&&!m.closedRoot&&V(m,"Unclosed root tag"),m.state!==y.BEGIN&&m.state!==y.BEGIN_WHITESPACE&&m.state!==y.TEXT&&rt(m,"Unexpected end"),de(m),m.c="",m.closed=!0,B(m,"onend"),r.call(m,m.strict,m.opt),m}s(vr,"end");function V(m,f){if(typeof m!="object"||!(m instanceof r))throw new Error("bad call to strictFail");m.strict&&rt(m,f)}s(V,"strictFail");function td(m){m.strict||(m.tagName=m.tagName[m.looseCase]());var f=m.tags[m.tags.length-1]||m,x=m.tag={name:m.tagName,attributes:{}};m.opt.xmlns&&(x.ns=f.ns),m.attribList.length=0,F(m,"onopentagstart",x)}s(td,"newTag");function si(m,f){var x=m.indexOf(":")<0?["",m]:m.split(":"),_=x[0],G=x[1];return f&&m==="xmlns"&&(_="xmlns",G=""),{prefix:_,local:G}}s(si,"qname");function oi(m){if(m.strict||(m.attribName=m.attribName[m.looseCase]()),m.attribList.indexOf(m.attribName)!==-1||m.tag.attributes.hasOwnProperty(m.attribName)){m.attribName=m.attribValue="";return}if(m.opt.xmlns){var f=si(m.attribName,!0),x=f.prefix,_=f.local;if(x==="xmlns")if(_==="xml"&&m.attribValue!==h)V(m,"xml: prefix must be bound to "+h+`
154
+ Actual: `+m.attribValue);else if(_==="xmlns"&&m.attribValue!==g)V(m,"xmlns: prefix must be bound to "+g+`
155
+ Actual: `+m.attribValue);else{var G=m.tag,Q=m.tags[m.tags.length-1]||m;G.ns===Q.ns&&(G.ns=Object.create(Q.ns)),G.ns[_]=m.attribValue}m.attribList.push([m.attribName,m.attribValue])}else m.tag.attributes[m.attribName]=m.attribValue,F(m,"onattribute",{name:m.attribName,value:m.attribValue});m.attribName=m.attribValue=""}s(oi,"attrib");function yt(m,f){if(m.opt.xmlns){var x=m.tag,_=si(m.tagName);x.prefix=_.prefix,x.local=_.local,x.uri=x.ns[_.prefix]||"",x.prefix&&!x.uri&&(V(m,"Unbound namespace prefix: "+JSON.stringify(m.tagName)),x.uri=_.prefix);var G=m.tags[m.tags.length-1]||m;x.ns&&G.ns!==x.ns&&Object.keys(x.ns).forEach(function(ps){F(m,"onopennamespace",{prefix:ps,uri:x.ns[ps]})});for(var Q=0,Te=m.attribList.length;Q<Te;Q++){var ye=m.attribList[Q],Pe=ye[0],_t=ye[1],pe=si(Pe,!0),bt=pe.prefix,nd=pe.local,ds=bt===""?"":x.ns[bt]||"",ci={name:Pe,value:_t,prefix:bt,local:nd,uri:ds};bt&&bt!=="xmlns"&&!ds&&(V(m,"Unbound namespace prefix: "+JSON.stringify(bt)),ci.uri=bt),m.tag.attributes[Pe]=ci,F(m,"onattribute",ci)}m.attribList.length=0}m.tag.isSelfClosing=!!f,m.sawRoot=!0,m.tags.push(m.tag),F(m,"onopentag",m.tag),f||(!m.noscript&&m.tagName.toLowerCase()==="script"?m.state=y.SCRIPT:m.state=y.TEXT,m.tag=null,m.tagName=""),m.attribName=m.attribValue="",m.attribList.length=0}s(yt,"openTag");function li(m){if(!m.tagName){V(m,"Weird empty close tag."),m.textNode+="</>",m.state=y.TEXT;return}if(m.script){if(m.tagName!=="script"){m.script+="</"+m.tagName+">",m.tagName="",m.state=y.SCRIPT;return}F(m,"onscript",m.script),m.script=""}var f=m.tags.length,x=m.tagName;m.strict||(x=x[m.looseCase]());for(var _=x;f--&&m.tags[f].name!==_;)V(m,"Unexpected close tag");if(f<0){V(m,"Unmatched closing tag: "+m.tagName),m.textNode+="</"+m.tagName+">",m.state=y.TEXT;return}m.tagName=x;for(var G=m.tags.length;G-- >f;){var Q=m.tag=m.tags.pop();m.tagName=m.tag.name,F(m,"onclosetag",m.tagName);var Te={};for(var ye in Q.ns)Te[ye]=Q.ns[ye];var Pe=m.tags[m.tags.length-1]||m;m.opt.xmlns&&Q.ns!==Pe.ns&&Object.keys(Q.ns).forEach(function(_t){var pe=Q.ns[_t];F(m,"onclosenamespace",{prefix:_t,uri:pe})})}f===0&&(m.closedRoot=!0),m.tagName=m.attribValue=m.attribName="",m.attribList.length=0,m.state=y.TEXT}s(li,"closeTag");function ls(m){var f=m.entity,x=f.toLowerCase(),_,G="";return m.ENTITIES[f]?m.ENTITIES[f]:m.ENTITIES[x]?m.ENTITIES[x]:(f=x,f.charAt(0)==="#"&&(f.charAt(1)==="x"?(f=f.slice(2),_=parseInt(f,16),G=_.toString(16)):(f=f.slice(1),_=parseInt(f,10),G=_.toString(10))),f=f.replace(/^0+/,""),isNaN(_)||G.toLowerCase()!==f?(V(m,"Invalid character entity"),"&"+m.entity+";"):String.fromCodePoint(_))}s(ls,"parseEntity");function cs(m,f){f==="<"?(m.state=y.OPEN_WAKA,m.startTagPosition=m.position):A(f)||(V(m,"Non-whitespace before first tag."),m.textNode=f,m.state=y.TEXT)}s(cs,"beginWhiteSpace");function us(m,f){var x="";return f<m.length&&(x=m.charAt(f)),x}s(us,"charAt");function rd(m){var f=this;if(this.error)throw this.error;if(f.closed)return rt(f,"Cannot write after close. Assign an onready handler.");if(m===null)return vr(f);typeof m=="object"&&(m=m.toString());for(var x=0,_="";_=us(m,x++),f.c=_,!!_;)switch(f.trackPosition&&(f.position++,_===`
156
+ `?(f.line++,f.column=0):f.column++),f.state){case y.BEGIN:if(f.state=y.BEGIN_WHITESPACE,_==="\uFEFF")continue;cs(f,_);continue;case y.BEGIN_WHITESPACE:cs(f,_);continue;case y.TEXT:if(f.sawRoot&&!f.closedRoot){for(var G=x-1;_&&_!=="<"&&_!=="&";)_=us(m,x++),_&&f.trackPosition&&(f.position++,_===`
157
+ `?(f.line++,f.column=0):f.column++);f.textNode+=m.substring(G,x-1)}_==="<"&&!(f.sawRoot&&f.closedRoot&&!f.strict)?(f.state=y.OPEN_WAKA,f.startTagPosition=f.position):(!A(_)&&(!f.sawRoot||f.closedRoot)&&V(f,"Text data outside of root node."),_==="&"?f.state=y.TEXT_ENTITY:f.textNode+=_);continue;case y.SCRIPT:_==="<"?f.state=y.SCRIPT_ENDING:f.script+=_;continue;case y.SCRIPT_ENDING:_==="/"?f.state=y.CLOSE_TAG:(f.script+="<"+_,f.state=y.SCRIPT);continue;case y.OPEN_WAKA:if(_==="!")f.state=y.SGML_DECL,f.sgmlDecl="";else if(!A(_))if(N(v,_))f.state=y.OPEN_TAG,f.tagName=_;else if(_==="/")f.state=y.CLOSE_TAG,f.tagName="";else if(_==="?")f.state=y.PROC_INST,f.procInstName=f.procInstBody="";else{if(V(f,"Unencoded <"),f.startTagPosition+1<f.position){var Q=f.position-f.startTagPosition;_=new Array(Q).join(" ")+_}f.textNode+="<"+_,f.state=y.TEXT}continue;case y.SGML_DECL:(f.sgmlDecl+_).toUpperCase()===d?(F(f,"onopencdata"),f.state=y.CDATA,f.sgmlDecl="",f.cdata=""):f.sgmlDecl+_==="--"?(f.state=y.COMMENT,f.comment="",f.sgmlDecl=""):(f.sgmlDecl+_).toUpperCase()===p?(f.state=y.DOCTYPE,(f.doctype||f.sawRoot)&&V(f,"Inappropriately located doctype declaration"),f.doctype="",f.sgmlDecl=""):_===">"?(F(f,"onsgmldeclaration",f.sgmlDecl),f.sgmlDecl="",f.state=y.TEXT):(R(_)&&(f.state=y.SGML_DECL_QUOTED),f.sgmlDecl+=_);continue;case y.SGML_DECL_QUOTED:_===f.q&&(f.state=y.SGML_DECL,f.q=""),f.sgmlDecl+=_;continue;case y.DOCTYPE:_===">"?(f.state=y.TEXT,F(f,"ondoctype",f.doctype),f.doctype=!0):(f.doctype+=_,_==="["?f.state=y.DOCTYPE_DTD:R(_)&&(f.state=y.DOCTYPE_QUOTED,f.q=_));continue;case y.DOCTYPE_QUOTED:f.doctype+=_,_===f.q&&(f.q="",f.state=y.DOCTYPE);continue;case y.DOCTYPE_DTD:f.doctype+=_,_==="]"?f.state=y.DOCTYPE:R(_)&&(f.state=y.DOCTYPE_DTD_QUOTED,f.q=_);continue;case y.DOCTYPE_DTD_QUOTED:f.doctype+=_,_===f.q&&(f.state=y.DOCTYPE_DTD,f.q="");continue;case y.COMMENT:_==="-"?f.state=y.COMMENT_ENDING:f.comment+=_;continue;case y.COMMENT_ENDING:_==="-"?(f.state=y.COMMENT_ENDED,f.comment=tt(f.opt,f.comment),f.comment&&F(f,"oncomment",f.comment),f.comment=""):(f.comment+="-"+_,f.state=y.COMMENT);continue;case y.COMMENT_ENDED:_!==">"?(V(f,"Malformed comment"),f.comment+="--"+_,f.state=y.COMMENT):f.state=y.TEXT;continue;case y.CDATA:_==="]"?f.state=y.CDATA_ENDING:f.cdata+=_;continue;case y.CDATA_ENDING:_==="]"?f.state=y.CDATA_ENDING_2:(f.cdata+="]"+_,f.state=y.CDATA);continue;case y.CDATA_ENDING_2:_===">"?(f.cdata&&F(f,"oncdata",f.cdata),F(f,"onclosecdata"),f.cdata="",f.state=y.TEXT):_==="]"?f.cdata+="]":(f.cdata+="]]"+_,f.state=y.CDATA);continue;case y.PROC_INST:_==="?"?f.state=y.PROC_INST_ENDING:A(_)?f.state=y.PROC_INST_BODY:f.procInstName+=_;continue;case y.PROC_INST_BODY:if(!f.procInstBody&&A(_))continue;_==="?"?f.state=y.PROC_INST_ENDING:f.procInstBody+=_;continue;case y.PROC_INST_ENDING:_===">"?(F(f,"onprocessinginstruction",{name:f.procInstName,body:f.procInstBody}),f.procInstName=f.procInstBody="",f.state=y.TEXT):(f.procInstBody+="?"+_,f.state=y.PROC_INST_BODY);continue;case y.OPEN_TAG:N(P,_)?f.tagName+=_:(td(f),_===">"?yt(f):_==="/"?f.state=y.OPEN_TAG_SLASH:(A(_)||V(f,"Invalid character in tag name"),f.state=y.ATTRIB));continue;case y.OPEN_TAG_SLASH:_===">"?(yt(f,!0),li(f)):(V(f,"Forward-slash in opening tag not followed by >"),f.state=y.ATTRIB);continue;case y.ATTRIB:if(A(_))continue;_===">"?yt(f):_==="/"?f.state=y.OPEN_TAG_SLASH:N(v,_)?(f.attribName=_,f.attribValue="",f.state=y.ATTRIB_NAME):V(f,"Invalid attribute name");continue;case y.ATTRIB_NAME:_==="="?f.state=y.ATTRIB_VALUE:_===">"?(V(f,"Attribute without value"),f.attribValue=f.attribName,oi(f),yt(f)):A(_)?f.state=y.ATTRIB_NAME_SAW_WHITE:N(P,_)?f.attribName+=_:V(f,"Invalid attribute name");continue;case y.ATTRIB_NAME_SAW_WHITE:if(_==="=")f.state=y.ATTRIB_VALUE;else{if(A(_))continue;V(f,"Attribute without value"),f.tag.attributes[f.attribName]="",f.attribValue="",F(f,"onattribute",{name:f.attribName,value:""}),f.attribName="",_===">"?yt(f):N(v,_)?(f.attribName=_,f.state=y.ATTRIB_NAME):(V(f,"Invalid attribute name"),f.state=y.ATTRIB)}continue;case y.ATTRIB_VALUE:if(A(_))continue;R(_)?(f.q=_,f.state=y.ATTRIB_VALUE_QUOTED):(V(f,"Unquoted attribute value"),f.state=y.ATTRIB_VALUE_UNQUOTED,f.attribValue=_);continue;case y.ATTRIB_VALUE_QUOTED:if(_!==f.q){_==="&"?f.state=y.ATTRIB_VALUE_ENTITY_Q:f.attribValue+=_;continue}oi(f),f.q="",f.state=y.ATTRIB_VALUE_CLOSED;continue;case y.ATTRIB_VALUE_CLOSED:A(_)?f.state=y.ATTRIB:_===">"?yt(f):_==="/"?f.state=y.OPEN_TAG_SLASH:N(v,_)?(V(f,"No whitespace between attributes"),f.attribName=_,f.attribValue="",f.state=y.ATTRIB_NAME):V(f,"Invalid attribute name");continue;case y.ATTRIB_VALUE_UNQUOTED:if(!$(_)){_==="&"?f.state=y.ATTRIB_VALUE_ENTITY_U:f.attribValue+=_;continue}oi(f),_===">"?yt(f):f.state=y.ATTRIB;continue;case y.CLOSE_TAG:if(f.tagName)_===">"?li(f):N(P,_)?f.tagName+=_:f.script?(f.script+="</"+f.tagName,f.tagName="",f.state=y.SCRIPT):(A(_)||V(f,"Invalid tagname in closing tag"),f.state=y.CLOSE_TAG_SAW_WHITE);else{if(A(_))continue;j(v,_)?f.script?(f.script+="</"+_,f.state=y.SCRIPT):V(f,"Invalid tagname in closing tag."):f.tagName=_}continue;case y.CLOSE_TAG_SAW_WHITE:if(A(_))continue;_===">"?li(f):V(f,"Invalid characters in closing tag");continue;case y.TEXT_ENTITY:case y.ATTRIB_VALUE_ENTITY_Q:case y.ATTRIB_VALUE_ENTITY_U:var Te,ye;switch(f.state){case y.TEXT_ENTITY:Te=y.TEXT,ye="textNode";break;case y.ATTRIB_VALUE_ENTITY_Q:Te=y.ATTRIB_VALUE_QUOTED,ye="attribValue";break;case y.ATTRIB_VALUE_ENTITY_U:Te=y.ATTRIB_VALUE_UNQUOTED,ye="attribValue";break}if(_===";")if(f.opt.unparsedEntities){var Pe=ls(f);f.entity="",f.state=Te,f.write(Pe)}else f[ye]+=ls(f),f.entity="",f.state=Te;else N(f.entity.length?S:I,_)?f.entity+=_:(V(f,"Invalid character in entity name"),f[ye]+="&"+f.entity+_,f.entity="",f.state=Te);continue;default:throw new Error(f,"Unknown state: "+f.state)}return f.position>=f.bufferCheckPosition&&n(f),f}s(rd,"write");return String.fromCodePoint||(function(){var m=String.fromCharCode,f=Math.floor,x=s(function(){var _=16384,G=[],Q,Te,ye=-1,Pe=arguments.length;if(!Pe)return"";for(var _t="";++ye<Pe;){var pe=Number(arguments[ye]);if(!isFinite(pe)||pe<0||pe>1114111||f(pe)!==pe)throw RangeError("Invalid code point: "+pe);pe<=65535?G.push(pe):(pe-=65536,Q=(pe>>10)+55296,Te=pe%1024+56320,G.push(Q,Te)),(ye+1===Pe||G.length>_)&&(_t+=m.apply(null,G),G.length=0)}return _t},"fromCodePoint");Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:x,configurable:!0,writable:!0}):String.fromCodePoint=x})(),t},"initializeSax"),gg=hg();var Gj=require("@playwright/test");var Nj={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 Hu=it(Bu());Hu.default.config({path:[`${__dirname}/.env`,`${__dirname}/../../.env`]});var Dg="claude_4",Ug={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}},Fg=s(()=>({nodeEnv:process.env.NODE_ENV??"production",selectedModel:{name:Dg},models:Ug,langsmith:{enabled:process.env.LANGSMITH_TRACING==="true",endpoint:process.env.LANGSMITH_ENDPOINT??"",apiKey:process.env.LANGSMITH_API_KEY??"",project:process.env.LANGSMITH_PROJECT??""}}),"make"),ee=Fg();var Bj={claude_4:ee.models.claude4sonnet,"claude_3.7":ee.models.claude37sonnet,claude_sonnet_4_6:ee.models.claudeSonnet46,claude_sonnet_5:ee.models.claudeSonnet5,claude_opus_4_8:ee.models.claudeOpus48,"gemini_2.5_pro":ee.models.gemini25pro,"gemini_2.0_flash":ee.models.gemini20flash,"gemini_2.5_flash_lite":ee.models.gemini25flash_lite,"gemini_2.5_flash":ee.models.gemini25flash,"gemini_3.5_flash":ee.models.gemini35flash,"gemini_3.1_flash_lite":ee.models.gemini31flashLite,gpt_4o_mini:ee.models.gpt4omini,gpt_4o_nano:ee.models.gpt4onano,gpt_41_nano:ee.models.gpt41nano,gpt_5_mini:ee.models.gpt5mini,gpt_5_nano:ee.models.gpt5nano,gpt_41_mini:ee.models.gpt41mini,gpt_41:ee.models.gpt41,o4_mini:ee.models.o4mini,o3_mini:ee.models.o3mini};var zu=s(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 as=require("fs");var Gu="\x1B[31m",jg="\x1B[33m",Bg="\x1B[32m",Hg="\x1B[36m",zg="\x1B[2m",Gg="\x1B[1m",qr="\x1B[0m",Vg=s(()=>{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"),qg=new Set(["severity","message","kind","timestamp","_startedAtMs"]),Wg=s(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"),Kg=s(t=>t==="ERROR"||t==="CRITICAL"?Gu:t==="WARNING"?jg:Bg,"colorForSeverity"),Jg=s(t=>{let e=String(t.severity??"INFO"),r=`${Kg(e)}${e.padEnd(5)}${qr}`,n=t.kind?`${Hg}${t.kind}${qr}`:"",i=String(t.message??""),a=t.error&&typeof t.error=="object"?(()=>{let d=t.error;return` ${Gu}${d.type??"Error"}: ${d.message??""}${qr}`})():"",o=["outcome","test_suite_run_id","status"],l=Object.entries(t).filter(([d,p])=>!qg.has(d)&&p!=null&&d!=="error"&&typeof p!="object"),c=s(d=>{let p=o.indexOf(d);return p===-1?o.length:p},"rank"),u=l.sort(([d],[p])=>c(d)-c(p)).slice(0,8).map(([d,p])=>`${zg}${d}=${qr}${p}`).join(" ");return[r,Gg+n+qr,i,u,a].filter(d=>d&&d.trim()!=="").join(" ")},"formatPretty"),Zg=s(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"),Vu=s(t=>{let e=Vg()?Jg(t):Wg(Zg(t));(0,as.writeSync)(1,e+`
158
+ `)},"emitEvent");var qu=s(t=>{(0,as.writeSync)(2,t.endsWith(`
59
159
  `)?t:`${t}
60
- `)},"writeStderrLine");var tb=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"),rb=o((t,e,r)=>{let n=Date.now(),a={timestamp:new Date().toISOString(),kind:t,...e},i=!1,s={set(l){return Object.assign(a,l),s},emit(l){i||(i=!0,l&&Object.assign(a,l),a.duration_ms===void 0&&(a.duration_ms=Date.now()-n),r(a))}};return s},"startHandle"),nb=o((t={})=>{let e=t.decide??(()=>!0),r=t.deriveMessage??tb,n=t.label??"[wide-event]",a=t.sink??(l=>nd(l)),i=o(l=>{if(!e(l))return;let c={severity:td(l),message:l.message??r(l),...l};try{a(c)}catch(u){try{ad(`${n} emit failed: ${String(u)}`)}catch{}}},"emit");return{emit:i,emitWideEvent:o((l,c={})=>{i({timestamp:new Date().toISOString(),kind:l,...c})},"emitWideEvent"),wideEvent:o((l,c={})=>rb(l,c,i),"wideEvent"),configureSink:o(l=>{a=l},"configureSink")}},"createWideEvents"),id=o(t=>t==="true"||t==="1","truthy"),sd=o(()=>id(process.env.CHECKSUM_WIDE_EVENTS)||id(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),od=nb({decide:o(()=>sd(),"decide")}),ab=od.configureSink;var mi=o((t,e={})=>{od.emitWideEvent(t,e)},"emitWideEvent");async function ld(t){await t.body?.cancel().catch(()=>{})}o(ld,"drainBody");var ib="http://127.0.0.1";async function cd(t,e){let r=e.fetchImpl??globalThis.fetch;try{let n=await r(`${ib}:${e.port}/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(e.timeoutMs)});return await ld(n),n.ok?!0:(e.onError?.(new Error(`monitor rejected message with status ${n.status}`)),!1)}catch(n){return e.onError?.(n),!1}}o(cd,"postToMonitor");async function ud(t,e){let r,n=new Promise(a=>{r=setTimeout(()=>a(!1),e),r.unref()});try{return await Promise.race([t.then(()=>!0).catch(()=>!0),n])}finally{r&&clearTimeout(r)}}o(ud,"settleWithin");var yn={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 sb(t,e,r,n){if(t===void 0||t.trim()==="")return e;let a=Number(t);return Number.isInteger(a)?Math.min(n,Math.max(r,a)):e}o(sb,"clampEnvInt");var ob=[["cliHardCapMs",["finalizeCeilingMs"],.9],["finalizeCeilingMs",["finalizeBudgetMs"],1],["finalizeBudgetMs",["stallTimeoutMs","assetDeadlineMs","watchTimeoutMs"],1],["assetDeadlineMs",["uploadTimeoutMs"],1],["uploadTimeoutMs",["noProgressAbortMs"],.5]];function lb(t){let e={...t},r=[];for(let[n,a,i]of ob)for(let s of a){let l=Math.floor(e[n]*i);e[s]>l&&(r.push(`${yn[s].env} (${e[s]}ms) exceeds its bound under ${yn[n].env} (${e[n]}ms); using ${l}ms`),e[s]=l)}return{tunables:e,warnings:r}}o(lb,"coerceScopeHierarchy");function cb(t){let e={};for(let r of Object.keys(yn)){let n=yn[r];e[r]=sb(t[n.env],n.fallback,n.min,n.max)}return e.resumableChunkBytes=Math.max(1,Math.floor(e.resumableChunkBytes/262144))*262144,lb(e)}o(cb,"resolveUploadTunablesDetailed");function hi(t){return cb(t).tunables}o(hi,"resolveUploadTunables");var q4=hi({});var dd=2e3;function db(t){switch(t){case"passed":return"passed";case"timedOut":return"timedOut";case"skipped":return"skipped";case"interrupted":return"interrupted";default:return"failed"}}o(db,"toProgressStatus");var bn=class{constructor(){this.monitorPort=process.env.CHECKSUM_UPLOAD_AGENT_PORT;this.tunables=hi(process.env);this.startedAt=Date.now();this.rootDir=process.cwd();this.testsById=new Map;this.lastFlushAt=0;this.sendChain=Promise.resolve()}static{o(this,"ChecksumProgressReporter")}printsToStdio(){return!1}onBegin(e,r){this.guard(()=>{e?.rootDir&&(this.rootDir=e.rootDir);for(let n of r?.allTests?.()??[])this.register(n);this.flush(!0)})}onTestBegin(e,r){this.guard(()=>{let n=this.itemFor(e);n.status="running",n.startedAt=r?.startTime?.getTime()??Date.now(),n.endedAt=null,n.durationMs=null,n.retry=r?.retry??0,this.flush()})}onTestEnd(e,r){this.guard(()=>{let n=this.itemFor(e);n.status=db(r?.status),n.endedAt=Date.now(),n.durationMs=r?.duration??null,n.retry=r?.retry??n.retry,n.startedAt??=r?.startTime?.getTime()??null,this.flush();let a=n.status==="passed"||n.status==="skipped";mi("test_result",{test_suite_run_id:process.env.CHECKSUM_TEST_SUITE_ID,outcome:a?"success":"error",test_id:n.id,status:n.status,retry:n.retry,duration_ms:n.durationMs??void 0,title:n.title,file:n.file,project:n.project||void 0})})}async onEnd(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),await ud(this.send(),this.tunables.onEndFlushTimeoutMs)}itemFor(e){return this.testsById.get(e.id)??this.register(e)}register(e){let r="";try{r=e.parent?.project?.()?.name??""}catch{}let n=e.location?.file??"";try{n&&(n=(0,pd.relative)(this.rootDir,n))}catch{}let a={id:e.id,title:e.title??"",titlePath:this.titlePathOf(e),file:n,line:e.location?.line??0,project:r,status:"pending",startedAt:null,endedAt:null,durationMs:null,retry:0};return this.testsById.set(a.id,a),a}titlePathOf(e){try{return(e.titlePath?.()??[]).filter(r=>!!r)}catch{return e.title?[e.title]:[]}}snapshot(){return{schemaVersion:1,source:"playwright",startedAt:this.startedAt,updatedAt:Date.now(),tests:[...this.testsById.values()]}}flush(e=!1){if(!this.monitorPort)return;let r=Date.now()-this.lastFlushAt;if(e||r>=dd){this.lastFlushAt=Date.now(),this.send();return}this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.lastFlushAt=Date.now(),this.send()},dd-r))}send(){return this.monitorPort?(this.sendChain=this.sendChain.then(()=>this.postSnapshot()),this.sendChain):Promise.resolve()}async postSnapshot(){this.monitorPort&&await cd({type:"runProgress",payload:this.snapshot()},{port:this.monitorPort,timeoutMs:this.tunables.ipcTimeoutMs})}guard(e){try{e()}catch{}}};
160
+ `)},"writeStderrLine");var Yg=s(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"),Xg=s((t,e,r)=>{let n=Date.now(),i={timestamp:new Date().toISOString(),kind:t,...e},a=!1,o={set(l){return Object.assign(i,l),o},emit(l){a||(a=!0,l&&Object.assign(i,l),i.duration_ms===void 0&&(i.duration_ms=Date.now()-n),r(i))}};return o},"startHandle"),Qg=s((t={})=>{let e=t.decide??(()=>!0),r=t.deriveMessage??Yg,n=t.label??"[wide-event]",i=t.sink??(l=>Vu(l)),a=s(l=>{if(!e(l))return;let c={severity:zu(l),message:l.message??r(l),...l};try{i(c)}catch(u){try{qu(`${n} emit failed: ${String(u)}`)}catch{}}},"emit");return{emit:a,emitWideEvent:s((l,c={})=>{a({timestamp:new Date().toISOString(),kind:l,...c})},"emitWideEvent"),wideEvent:s((l,c={})=>Xg(l,c,a),"wideEvent"),configureSink:s(l=>{i=l},"configureSink")}},"createWideEvents"),Wu=s(t=>t==="true"||t==="1","truthy"),Ku=s(()=>Wu(process.env.CHECKSUM_WIDE_EVENTS)||Wu(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),Ju=Qg({decide:s(()=>Ku(),"decide")}),ey=Ju.configureSink;var ss=s((t,e={})=>{Ju.emitWideEvent(t,e)},"emitWideEvent");async function Zu(t){await t.body?.cancel().catch(()=>{})}s(Zu,"drainBody");var ty="http://127.0.0.1";async function Yu(t,e){let r=e.fetchImpl??globalThis.fetch;try{let n=await r(`${ty}:${e.port}/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(e.timeoutMs)});return await Zu(n),n.ok?!0:(e.onError?.(new Error(`monitor rejected message with status ${n.status}`)),!1)}catch(n){return e.onError?.(n),!1}}s(Yu,"postToMonitor");async function Xu(t,e){let r,n=new Promise(i=>{r=setTimeout(()=>i(!1),e),r.unref()});try{return await Promise.race([t.then(()=>!0).catch(()=>!0),n])}finally{r&&clearTimeout(r)}}s(Xu,"settleWithin");var ii={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 ry(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}s(ry,"clampEnvInt");var ny=[["cliHardCapMs",["finalizeCeilingMs"],.9],["finalizeCeilingMs",["finalizeBudgetMs"],1],["finalizeBudgetMs",["stallTimeoutMs","assetDeadlineMs","watchTimeoutMs"],1],["assetDeadlineMs",["uploadTimeoutMs"],1],["uploadTimeoutMs",["noProgressAbortMs"],.5]];function iy(t){let e={...t},r=[];for(let[n,i,a]of ny)for(let o of i){let l=Math.floor(e[n]*a);e[o]>l&&(r.push(`${ii[o].env} (${e[o]}ms) exceeds its bound under ${ii[n].env} (${e[n]}ms); using ${l}ms`),e[o]=l)}return{tunables:e,warnings:r}}s(iy,"coerceScopeHierarchy");function ay(t){let e={};for(let r of Object.keys(ii)){let n=ii[r];e[r]=ry(t[n.env],n.fallback,n.min,n.max)}return e.resumableChunkBytes=Math.max(1,Math.floor(e.resumableChunkBytes/262144))*262144,iy(e)}s(ay,"resolveUploadTunablesDetailed");function os(t){return ay(t).tunables}s(os,"resolveUploadTunables");var E4=os({});var Qu=2e3;function oy(t){switch(t){case"passed":return"passed";case"timedOut":return"timedOut";case"skipped":return"skipped";case"interrupted":return"interrupted";default:return"failed"}}s(oy,"toProgressStatus");var ai=class{constructor(){this.monitorPort=process.env.CHECKSUM_UPLOAD_AGENT_PORT;this.tunables=os(process.env);this.startedAt=Date.now();this.rootDir=process.cwd();this.testsById=new Map;this.lastFlushAt=0;this.sendChain=Promise.resolve()}static{s(this,"ChecksumProgressReporter")}printsToStdio(){return!1}onBegin(e,r){this.guard(()=>{e.rootDir&&(this.rootDir=e.rootDir);for(let n of r.allTests?.()??[])this.register(n);this.flush(!0)})}onTestBegin(e,r){this.guard(()=>{let n=this.itemFor(e);n.status="running",n.startedAt=r.startTime?.getTime()??Date.now(),n.endedAt=null,n.durationMs=null,n.retry=r.retry??0,this.flush()})}onTestEnd(e,r){this.guard(()=>{let n=this.itemFor(e);n.status=oy(r.status),n.endedAt=Date.now(),n.durationMs=r.duration??null,n.retry=r.retry??n.retry,n.startedAt??=r.startTime?.getTime()??null,this.flush();let i=n.status==="passed"||n.status==="skipped";ss("test_result",{test_suite_run_id:process.env.CHECKSUM_TEST_SUITE_ID,outcome:i?"success":"error",test_id:n.id,status:n.status,retry:n.retry,duration_ms:n.durationMs??void 0,title:n.title,file:n.file,project:n.project||void 0})})}async onEnd(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),await Xu(this.send(),this.tunables.onEndFlushTimeoutMs)}itemFor(e){return this.testsById.get(e.id)??this.register(e)}register(e){let r="";try{r=e.parent?.project?.()?.name??""}catch{}let n=e.location?.file??"";try{n&&(n=(0,ed.relative)(this.rootDir,n))}catch{}let i={id:e.id,title:e.title??"",titlePath:this.titlePathOf(e),file:n,line:e.location?.line??0,project:r,status:"pending",startedAt:null,endedAt:null,durationMs:null,retry:0};return this.testsById.set(i.id,i),i}titlePathOf(e){try{return(e.titlePath?.()??[]).filter(r=>!!r)}catch{return e.title?[e.title]:[]}}snapshot(){return{schemaVersion:1,source:"playwright",startedAt:this.startedAt,updatedAt:Date.now(),tests:[...this.testsById.values()]}}flush(e=!1){if(!this.monitorPort)return;let r=Date.now()-this.lastFlushAt;if(e||r>=Qu){this.lastFlushAt=Date.now(),this.send();return}this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.lastFlushAt=Date.now(),this.send()},Qu-r))}send(){return this.monitorPort?(this.sendChain=this.sendChain.then(()=>this.postSnapshot()),this.sendChain):Promise.resolve()}async postSnapshot(){this.monitorPort&&await Yu({type:"runProgress",payload:this.snapshot()},{port:this.monitorPort,timeoutMs:this.tunables.ipcTimeoutMs})}guard(e){try{e()}catch{}}};
61
161
  /*! Bundled license information:
62
162
 
63
163
  @langchain/core/dist/utils/js-sha256/hash.js: