@checksum-ai/runtime 4.13.1-beta.1 → 4.14.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env +1 -1
- package/checksum-progress-reporter.js +89 -4
- package/checksumlib.js +43 -43
- package/cli.js +283 -171
- package/index.js +240 -128
- package/package.json +1 -1
- package/test-run-monitor.js +97 -12
|
@@ -1,4 +1,89 @@
|
|
|
1
|
-
"use strict";var m=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var w=Object.prototype.hasOwnProperty;var o=(e,t)=>m(e,"name",{value:t,configurable:!0});var C=(e,t)=>{for(var n in t)m(e,n,{get:t[n],enumerable:!0})},F=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of M(t))!w.call(e,i)&&i!==n&&m(e,i,{get:()=>t[i],enumerable:!(r=P(t,i))||r.enumerable});return e};var I=e=>F(m({},"__esModule",{value:!0}),e);var z={};C(z,{default:()=>g});module.exports=I(z);var R=require("path");var T=o(e=>{if(e.error!=null)return"ERROR";let t=e.status_code;if(typeof t=="number"&&t>=500)return"ERROR";let n=e.exit_code;return typeof n=="number"&&n!==0?"ERROR":"INFO"},"severityFor");var y=require("fs");var b="\x1B[31m",W="\x1B[33m",_="\x1B[32m",D="\x1B[36m",O="\x1B[2m",H="\x1B[1m",u="\x1B[0m",L=o(()=>{let e=process.env.WIDE_EVENT_PRETTY;return e==="true"||e==="1"?!0:e==="false"||e==="0"?!1:process.stdout.isTTY?!0:process.env.APP_ENV==="local"},"shouldPretty"),B=new Set(["severity","message","kind","timestamp","_startedAtMs"]),U=o(e=>{let t=new WeakSet;return JSON.stringify(e,(n,r)=>{if(typeof r=="bigint")return r.toString();if(typeof r=="object"&&r!==null){if(t.has(r))return"[Circular]";t.add(r)}return r})},"safeStringify"),N=o(e=>e==="ERROR"||e==="CRITICAL"?b:e==="WARNING"?W:_,"colorForSeverity"),$=o(e=>{let t=String(e.severity??"INFO"),n=`${N(t)}${t.padEnd(5)}${u}`,r=e.kind?`${D}${e.kind}${u}`:"",i=String(e.message??""),l=e.error&&typeof e.error=="object"?(()=>{let a=e.error;return` ${b}${a.type??"Error"}: ${a.message??""}${u}`})():"",c=["outcome","test_suite_run_id","status"],s=Object.entries(e).filter(([a,p])=>!B.has(a)&&p!=null&&a!=="error"&&typeof p!="object"),d=o(a=>{let p=c.indexOf(a);return p===-1?c.length:p},"rank"),f=s.sort(([a],[p])=>d(a)-d(p)).slice(0,8).map(([a,p])=>`${O}${a}=${u}${p}`).join(" ");return[n,H+r+u,i,f,l].filter(a=>a&&a.trim()!=="").join(" ")},"formatPretty"),j=o(e=>{let t=e.trace_id;if(typeof t!="string"||t==="")return e;let n=process.env.GCP_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT;return n?{...e,"logging.googleapis.com/trace":`projects/${n}/traces/${t}`}:e},"withGcpTraceField"),E=o(e=>{let t=L()?$(e):U(j(e));(0,y.writeSync)(1,t+`
|
|
2
|
-
`)
|
|
3
|
-
`)?e:`${e}
|
|
4
|
-
`)},"writeStderrLine");var G=o(e=>{let t=e.kind??"event",n=e.outcome?` ${e.outcome}`:"",r=typeof e.duration_ms=="number"?` ${e.duration_ms}ms`:"";return`${t}${n}${r}`.trim()},"defaultMessage"),V=o((e,t,n)=>{let r=Date.now(),i={timestamp:new Date().toISOString(),kind:e,...t},l=!1,c={set(s){return Object.assign(i,s),c},emit(s){l||(l=!0,s&&Object.assign(i,s),i.duration_ms===void 0&&(i.duration_ms=Date.now()-r),n(i))}};return c},"startHandle"),Y=o((e={})=>{let t=e.decide??(()=>!0),n=e.deriveMessage??G,r=e.label??"[wide-event]",i=e.sink??(s=>E(s)),l=o(s=>{if(!t(s))return;let d={severity:T(s),message:s.message??n(s),...s};try{i(d)}catch(f){try{x(`${r} emit failed: ${String(f)}`)}catch{}}},"emit");return{emit:l,emitWideEvent:o((s,d={})=>{l({timestamp:new Date().toISOString(),kind:s,...d})},"emitWideEvent"),wideEvent:o((s,d={})=>V(s,d,l),"wideEvent"),configureSink:o(s=>{i=s},"configureSink")}},"createWideEvents"),S=o(e=>e==="true"||e==="1","truthy"),v=o(()=>S(process.env.CHECKSUM_WIDE_EVENTS)||S(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),A=Y({decide:o(()=>v(),"decide")}),K=A.configureSink;var h=o((e,t={})=>{A.emitWideEvent(e,t)},"emitWideEvent");var k=2e3;function q(e){switch(e){case"passed":return"passed";case"timedOut":return"timedOut";case"skipped":return"skipped";case"interrupted":return"interrupted";default:return"failed"}}o(q,"toProgressStatus");var g=class{constructor(){this.monitorPort=process.env.CHECKSUM_UPLOAD_AGENT_PORT;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(t,n){this.guard(()=>{t?.rootDir&&(this.rootDir=t.rootDir);for(let r of n?.allTests?.()??[])this.register(r);this.flush(!0)})}onTestBegin(t,n){this.guard(()=>{let r=this.itemFor(t);r.status="running",r.startedAt=n?.startTime?.getTime()??Date.now(),r.endedAt=null,r.durationMs=null,r.retry=n?.retry??0,this.flush()})}onTestEnd(t,n){this.guard(()=>{let r=this.itemFor(t);r.status=q(n?.status),r.endedAt=Date.now(),r.durationMs=n?.duration??null,r.retry=n?.retry??r.retry,r.startedAt??=n?.startTime?.getTime()??null,this.flush();let i=r.status==="passed"||r.status==="skipped";h("test_result",{test_suite_run_id:process.env.CHECKSUM_TEST_SUITE_ID,outcome:i?"success":"error",test_id:r.id,status:r.status,retry:r.retry,duration_ms:r.durationMs??void 0,title:r.title,file:r.file,project:r.project||void 0})})}async onEnd(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),await this.send()}itemFor(t){return this.testsById.get(t.id)??this.register(t)}register(t){let n="";try{n=t.parent?.project?.()?.name??""}catch{}let r=t.location?.file??"";try{r&&(r=(0,R.relative)(this.rootDir,r))}catch{}let i={id:t.id,title:t.title??"",titlePath:this.titlePathOf(t),file:r,line:t.location?.line??0,project:n,status:"pending",startedAt:null,endedAt:null,durationMs:null,retry:0};return this.testsById.set(i.id,i),i}titlePathOf(t){try{return(t.titlePath?.()??[]).filter(n=>!!n)}catch{return t.title?[t.title]:[]}}snapshot(){return{schemaVersion:1,source:"playwright",startedAt:this.startedAt,updatedAt:Date.now(),tests:[...this.testsById.values()]}}flush(t=!1){if(!this.monitorPort)return;let n=Date.now()-this.lastFlushAt;if(t||n>=k){this.lastFlushAt=Date.now(),this.send();return}this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.lastFlushAt=Date.now(),this.send()},k-n))}send(){return this.monitorPort?(this.sendChain=this.sendChain.then(()=>this.postSnapshot()),this.sendChain):Promise.resolve()}async postSnapshot(){try{await fetch(`http://127.0.0.1:${this.monitorPort}/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"runProgress",payload:this.snapshot()})})}catch{}}guard(t){try{t()}catch{}}};
|
|
1
|
+
"use strict";var hd=Object.create;var kt=Object.defineProperty;var gd=Object.getOwnPropertyDescriptor;var _d=Object.getOwnPropertyNames;var yd=Object.getPrototypeOf,bd=Object.prototype.hasOwnProperty;var o=(t,e)=>kt(t,"name",{value:e,configurable:!0});var k=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},wd=(t,e)=>{for(var r in e)kt(t,r,{get:e[r],enumerable:!0})},vi=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of _d(e))!bd.call(t,a)&&a!==r&&kt(t,a,{get:()=>e[a],enumerable:!(n=gd(e,a))||n.enumerable});return t};var xe=(t,e,r)=>(r=t!=null?hd(yd(t)):{},vi(e||!t||!t.__esModule?kt(r,"default",{value:t,enumerable:!0}):r,t)),vd=t=>vi(kt({},"__esModule",{value:!0}),t);var ys=k((Fv,kn)=>{"use strict";var ip=Object.prototype.hasOwnProperty,fe="~";function Nt(){}o(Nt,"Events");Object.create&&(Nt.prototype=Object.create(null),new Nt().__proto__||(fe=!1));function sp(t,e,r){this.fn=t,this.context=e,this.once=r||!1}o(sp,"EE");function _s(t,e,r,n,a){if(typeof r!="function")throw new TypeError("The listener must be a function");var i=new sp(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(_s,"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)ip.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 _s(this,e,r,n,!1)},"on");ce.prototype.once=o(function(e,r,n){return _s(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 ws=k((jv,bs)=>{"use strict";bs.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 Es=k((Bv,vr)=>{"use strict";var op=ws(),wr=class extends Error{static{o(this,"TimeoutError")}constructor(e){super(e),this.name="TimeoutError"}},vs=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);op(t.then(n,a),()=>{clearTimeout(i)})}),"pTimeout");vr.exports=vs;vr.exports.default=vs;vr.exports.TimeoutError=wr});var Ts=k(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});function lp(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(lp,"lowerBound");Mn.default=lp});var xs=k(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});var cp=Ts(),Nn=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=cp.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}};Pn.default=Nn});var Tr=k(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});var up=ys(),Ss=Es(),dp=xs(),Er=o(()=>{},"empty"),pp=new Ss.TimeoutError,$n=class extends up{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:dp.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():Ss.default(Promise.resolve(e()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&a(pp)});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}};Ln.default=$n});var Ht=k((oS,Xo)=>{"use strict";var kf="2.0.0",Mf=Number.MAX_SAFE_INTEGER||9007199254740991,Nf=16,Pf=250,$f=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Xo.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Nf,MAX_SAFE_BUILD_LENGTH:Pf,MAX_SAFE_INTEGER:Mf,RELEASE_TYPES:$f,SEMVER_SPEC_VERSION:kf,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var zt=k((lS,Qo)=>{"use strict";var Lf=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};Qo.exports=Lf});var At=k((Be,el)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:ga,MAX_SAFE_BUILD_LENGTH:Df,MAX_LENGTH:Ff}=Ht(),Uf=zt();Be=el.exports={};var jf=Be.re=[],Bf=Be.safeRe=[],S=Be.src=[],Gf=Be.safeSrc=[],A=Be.t={},Hf=0,_a="[a-zA-Z0-9-]",zf=[["\\s",1],["\\d",Ff],[_a,Df]],Vf=o(t=>{for(let[e,r]of zf)t=t.split(`${e}*`).join(`${e}{0,${r}}`).split(`${e}+`).join(`${e}{1,${r}}`);return t},"makeSafeRegex"),D=o((t,e,r)=>{let n=Vf(e),a=Hf++;Uf(t,a,e),A[t]=a,S[a]=e,Gf[a]=n,jf[a]=new RegExp(e,r?"g":void 0),Bf[a]=new RegExp(n,r?"g":void 0)},"createToken");D("NUMERICIDENTIFIER","0|[1-9]\\d*");D("NUMERICIDENTIFIERLOOSE","\\d+");D("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${_a}*`);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",`${_a}+`);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,${ga}})(?:\\.(\\d{1,${ga}}))?(?:\\.(\\d{1,${ga}}))?`);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=k((uS,tl)=>{"use strict";var qf=Object.freeze({loose:!0}),Wf=Object.freeze({}),Kf=o(t=>t?typeof t!="object"?qf:t:Wf,"parseOptions");tl.exports=Kf});var ya=k((pS,al)=>{"use strict";var rl=/^[0-9]+$/,nl=o((t,e)=>{if(typeof t=="number"&&typeof e=="number")return t===e?0:t<e?-1:1;let r=rl.test(t),n=rl.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:t<e?-1:1},"compareIdentifiers"),Jf=o((t,e)=>nl(e,t),"rcompareIdentifiers");al.exports={compareIdentifiers:nl,rcompareIdentifiers:Jf}});var ue=k((mS,sl)=>{"use strict";var Hr=zt(),{MAX_LENGTH:il,MAX_SAFE_INTEGER:zr}=Ht(),{safeRe:Vr,t:qr}=At(),Zf=Gr(),{compareIdentifiers:ba}=ya(),wa=class t{static{o(this,"SemVer")}constructor(e,r){if(r=Zf(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>il)throw new TypeError(`version is longer than ${il} 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 ba(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 ba(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]),ba(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}};sl.exports=wa});var pt=k((gS,ll)=>{"use strict";var ol=ue(),Yf=o((t,e,r=!1)=>{if(t instanceof ol)return t;try{return new ol(t,e)}catch(n){if(!r)return null;throw n}},"parse");ll.exports=Yf});var ul=k((yS,cl)=>{"use strict";var Xf=pt(),Qf=o((t,e)=>{let r=Xf(t,e);return r?r.version:null},"valid");cl.exports=Qf});var pl=k((wS,dl)=>{"use strict";var em=pt(),tm=o((t,e)=>{let r=em(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null},"clean");dl.exports=tm});var hl=k((ES,ml)=>{"use strict";var fl=ue(),rm=o((t,e,r,n,a)=>{typeof r=="string"&&(a=n,n=r,r=void 0);try{return new fl(t instanceof fl?t.version:t,r).inc(e,n,a).version}catch{return null}},"inc");ml.exports=rm});var yl=k((xS,_l)=>{"use strict";var gl=pt(),nm=o((t,e)=>{let r=gl(t,null,!0),n=gl(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");_l.exports=nm});var wl=k((AS,bl)=>{"use strict";var am=ue(),im=o((t,e)=>new am(t,e).major,"major");bl.exports=im});var El=k((CS,vl)=>{"use strict";var sm=ue(),om=o((t,e)=>new sm(t,e).minor,"minor");vl.exports=om});var xl=k((RS,Tl)=>{"use strict";var lm=ue(),cm=o((t,e)=>new lm(t,e).patch,"patch");Tl.exports=cm});var Al=k((MS,Sl)=>{"use strict";var um=pt(),dm=o((t,e)=>{let r=um(t,e);return r&&r.prerelease.length?r.prerelease:null},"prerelease");Sl.exports=dm});var Ae=k((PS,Cl)=>{"use strict";var Il=ue(),pm=o((t,e,r)=>new Il(t,r).compare(new Il(e,r)),"compare");Cl.exports=pm});var Rl=k((LS,Ol)=>{"use strict";var fm=Ae(),mm=o((t,e,r)=>fm(e,t,r),"rcompare");Ol.exports=mm});var Ml=k((FS,kl)=>{"use strict";var hm=Ae(),gm=o((t,e)=>hm(t,e,!0),"compareLoose");kl.exports=gm});var Wr=k((jS,Pl)=>{"use strict";var Nl=ue(),_m=o((t,e,r)=>{let n=new Nl(t,r),a=new Nl(e,r);return n.compare(a)||n.compareBuild(a)},"compareBuild");Pl.exports=_m});var Ll=k((GS,$l)=>{"use strict";var ym=Wr(),bm=o((t,e)=>t.sort((r,n)=>ym(r,n,e)),"sort");$l.exports=bm});var Fl=k((zS,Dl)=>{"use strict";var wm=Wr(),vm=o((t,e)=>t.sort((r,n)=>wm(n,r,e)),"rsort");Dl.exports=vm});var Vt=k((qS,Ul)=>{"use strict";var Em=Ae(),Tm=o((t,e,r)=>Em(t,e,r)>0,"gt");Ul.exports=Tm});var Kr=k((KS,jl)=>{"use strict";var xm=Ae(),Sm=o((t,e,r)=>xm(t,e,r)<0,"lt");jl.exports=Sm});var va=k((ZS,Bl)=>{"use strict";var Am=Ae(),Im=o((t,e,r)=>Am(t,e,r)===0,"eq");Bl.exports=Im});var Ea=k((XS,Gl)=>{"use strict";var Cm=Ae(),Om=o((t,e,r)=>Cm(t,e,r)!==0,"neq");Gl.exports=Om});var Jr=k((eA,Hl)=>{"use strict";var Rm=Ae(),km=o((t,e,r)=>Rm(t,e,r)>=0,"gte");Hl.exports=km});var Zr=k((rA,zl)=>{"use strict";var Mm=Ae(),Nm=o((t,e,r)=>Mm(t,e,r)<=0,"lte");zl.exports=Nm});var Ta=k((aA,Vl)=>{"use strict";var Pm=va(),$m=Ea(),Lm=Vt(),Dm=Jr(),Fm=Kr(),Um=Zr(),jm=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 Pm(t,r,n);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);default:throw new TypeError(`Invalid operator: ${e}`)}},"cmp");Vl.exports=jm});var Wl=k((sA,ql)=>{"use strict";var Bm=ue(),Gm=pt(),{safeRe:Yr,t:Xr}=At(),Hm=o((t,e)=>{if(t instanceof Bm)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 Gm(`${n}.${a}.${i}${s}${l}`,e)},"coerce");ql.exports=Hm});var Jl=k((lA,Kl)=>{"use strict";var xa=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}};Kl.exports=xa});var Ie=k((uA,Ql)=>{"use strict";var zm=/\s+/g,Sa=class t{static{o(this,"Range")}constructor(e,r){if(r=qm(r),e instanceof t)return e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease?e:new t(e.raw,r);if(e instanceof Aa)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(zm," "),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=>!Yl(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&&Qm(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&&Ym)|(this.options.loose&&Xm))+":"+e,a=Zl.get(n);if(a)return a;let i=this.options.loose,s=i?me[de.HYPHENRANGELOOSE]:me[de.HYPHENRANGE];e=e.replace(s,ch(this.options.includePrerelease)),K("hyphen replace",e),e=e.replace(me[de.COMPARATORTRIM],Km),K("comparator trim",e),e=e.replace(me[de.TILDETRIM],Jm),K("tilde trim",e),e=e.replace(me[de.CARETTRIM],Zm),K("caret trim",e);let l=e.split(" ").map(m=>eh(m,this.options)).join(" ").split(/\s+/).map(m=>lh(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 Aa(m,this.options));for(let m of u){if(Yl(m))return[m];c.set(m.value,m)}c.size>1&&c.has("")&&c.delete("");let p=[...c.values()];return Zl.set(n,p),p}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(n=>Xl(n,r)&&e.set.some(a=>Xl(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 Wm(e,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(uh(this.set[r],e,this.options))return!0;return!1}};Ql.exports=Sa;var Vm=Jl(),Zl=new Vm,qm=Gr(),Aa=qt(),K=zt(),Wm=ue(),{safeRe:me,t:de,comparatorTrimReplace:Km,tildeTrimReplace:Jm,caretTrimReplace:Zm}=At(),{FLAG_INCLUDE_PRERELEASE:Ym,FLAG_LOOSE:Xm}=Ht(),Yl=o(t=>t.value==="<0.0.0-0","isNullSet"),Qm=o(t=>t.value==="","isAny"),Xl=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"),eh=o((t,e)=>(t=t.replace(me[de.BUILD],""),K("comp",t,e),t=nh(t,e),K("caret",t),t=th(t,e),K("tildes",t),t=ih(t,e),K("xrange",t),t=oh(t,e),K("stars",t),t),"parseComparator"),he=o(t=>!t||t.toLowerCase()==="x"||t==="*","isX"),th=o((t,e)=>t.trim().split(/\s+/).map(r=>rh(r,e)).join(" "),"replaceTildes"),rh=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"),nh=o((t,e)=>t.trim().split(/\s+/).map(r=>ah(r,e)).join(" "),"replaceCarets"),ah=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"),ih=o((t,e)=>(K("replaceXRanges",t,e),t.split(/\s+/).map(r=>sh(r,e)).join(" ")),"replaceXRanges"),sh=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"),oh=o((t,e)=>(K("replaceStars",t,e),t.trim().replace(me[de.STAR],"")),"replaceStars"),lh=o((t,e)=>(K("replaceGTE0",t,e),t.trim().replace(me[e.includePrerelease?de.GTE0PRE:de.GTE0],"")),"replaceGTE0"),ch=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"),uh=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!==Aa.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=k((pA,ic)=>{"use strict";var Wt=Symbol("SemVer ANY"),Oa=class t{static{o(this,"Comparator")}static get ANY(){return Wt}constructor(e,r){if(r=ec(r),e instanceof t){if(e.loose===!!r.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Ca("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,Ca("comp",this)}parse(e){let r=this.options.loose?tc[rc.COMPARATORLOOSE]:tc[rc.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 nc(n[2],this.options.loose):this.semver=Wt}toString(){return this.value}test(e){if(Ca("Comparator.test",e,this.options.loose),this.semver===Wt||e===Wt)return!0;if(typeof e=="string")try{e=new nc(e,this.options)}catch{return!1}return Ia(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 ac(e.value,r).test(this.value):e.operator===""?e.value===""?!0:new ac(this.value,r).test(e.semver):(r=ec(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("=")||Ia(this.semver,"<",e.semver,r)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Ia(this.semver,">",e.semver,r)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};ic.exports=Oa;var ec=Gr(),{safeRe:tc,t:rc}=At(),Ia=Ta(),Ca=zt(),nc=ue(),ac=Ie()});var Kt=k((mA,sc)=>{"use strict";var dh=Ie(),ph=o((t,e,r)=>{try{e=new dh(e,r)}catch{return!1}return e.test(t)},"satisfies");sc.exports=ph});var lc=k((gA,oc)=>{"use strict";var fh=Ie(),mh=o((t,e)=>new fh(t,e).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" ")),"toComparators");oc.exports=mh});var uc=k((yA,cc)=>{"use strict";var hh=ue(),gh=Ie(),_h=o((t,e,r)=>{let n=null,a=null,i=null;try{i=new gh(e,r)}catch{return null}return t.forEach(s=>{i.test(s)&&(!n||a.compare(s)===-1)&&(n=s,a=new hh(n,r))}),n},"maxSatisfying");cc.exports=_h});var pc=k((wA,dc)=>{"use strict";var yh=ue(),bh=Ie(),wh=o((t,e,r)=>{let n=null,a=null,i=null;try{i=new bh(e,r)}catch{return null}return t.forEach(s=>{i.test(s)&&(!n||a.compare(s)===1)&&(n=s,a=new yh(n,r))}),n},"minSatisfying");dc.exports=wh});var hc=k((EA,mc)=>{"use strict";var Ra=ue(),vh=Ie(),fc=Vt(),Eh=o((t,e)=>{t=new vh(t,e);let r=new Ra("0.0.0");if(t.test(r)||(r=new Ra("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 Ra(s.semver.version);switch(s.operator){case">":l.prerelease.length===0?l.patch++:l.prerelease.push(0),l.raw=l.format();case"":case">=":(!i||fc(l,i))&&(i=l);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${s.operator}`)}}),i&&(!r||fc(r,i))&&(r=i)}return r&&t.test(r)?r:null},"minVersion");mc.exports=Eh});var _c=k((xA,gc)=>{"use strict";var Th=Ie(),xh=o((t,e)=>{try{return new Th(t,e).range||"*"}catch{return null}},"validRange");gc.exports=xh});var Qr=k((AA,vc)=>{"use strict";var Sh=ue(),wc=qt(),{ANY:Ah}=wc,Ih=Ie(),Ch=Kt(),yc=Vt(),bc=Kr(),Oh=Zr(),Rh=Jr(),kh=o((t,e,r,n)=>{t=new Sh(t,n),e=new Ih(e,n);let a,i,s,l,c;switch(r){case">":a=yc,i=Oh,s=bc,l=">",c=">=";break;case"<":a=bc,i=Rh,s=yc,l="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Ch(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===Ah&&(h=new wc(">=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");vc.exports=kh});var Tc=k((CA,Ec)=>{"use strict";var Mh=Qr(),Nh=o((t,e,r)=>Mh(t,e,">",r),"gtr");Ec.exports=Nh});var Sc=k((RA,xc)=>{"use strict";var Ph=Qr(),$h=o((t,e,r)=>Ph(t,e,"<",r),"ltr");xc.exports=$h});var Cc=k((MA,Ic)=>{"use strict";var Ac=Ie(),Lh=o((t,e,r)=>(t=new Ac(t,r),e=new Ac(e,r),t.intersects(e,r)),"intersects");Ic.exports=Lh});var Rc=k((PA,Oc)=>{"use strict";var Dh=Kt(),Fh=Ae();Oc.exports=(t,e,r)=>{let n=[],a=null,i=null,s=t.sort((p,m)=>Fh(p,m,r));for(let p of s)Dh(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 Lc=k(($A,$c)=>{"use strict";var kc=Ie(),Ma=qt(),{ANY:ka}=Ma,Jt=Kt(),Na=Ae(),Uh=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=Bh(a,i,r);if(n=n||s!==null,s)continue e}if(n)return!1}return!0},"subset"),jh=[new Ma(">=0.0.0-0")],Mc=[new Ma(">=0.0.0")],Bh=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=jh:t=Mc}if(e.length===1&&e[0].semver===ka){if(r.includePrerelease)return!0;e=Mc}let n=new Set,a,i;for(let h of t)h.operator===">"||h.operator===">="?a=Nc(a,h,r):h.operator==="<"||h.operator==="<="?i=Pc(i,h,r):n.add(h.semver);if(n.size>1)return null;let s;if(a&&i){if(s=Na(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=Nc(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=Pc(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"),Nc=o((t,e,r)=>{if(!t)return e;let n=Na(t.semver,e.semver,r);return n>0?t:n<0||e.operator===">"&&t.operator===">="?e:t},"higherGT"),Pc=o((t,e,r)=>{if(!t)return e;let n=Na(t.semver,e.semver,r);return n<0?t:n>0||e.operator==="<"&&t.operator==="<="?e:t},"lowerLT");$c.exports=Uh});var jc=k((DA,Uc)=>{"use strict";var Pa=At(),Dc=Ht(),Gh=ue(),Fc=ya(),Hh=pt(),zh=ul(),Vh=pl(),qh=hl(),Wh=yl(),Kh=wl(),Jh=El(),Zh=xl(),Yh=Al(),Xh=Ae(),Qh=Rl(),eg=Ml(),tg=Wr(),rg=Ll(),ng=Fl(),ag=Vt(),ig=Kr(),sg=va(),og=Ea(),lg=Jr(),cg=Zr(),ug=Ta(),dg=Wl(),pg=qt(),fg=Ie(),mg=Kt(),hg=lc(),gg=uc(),_g=pc(),yg=hc(),bg=_c(),wg=Qr(),vg=Tc(),Eg=Sc(),Tg=Cc(),xg=Rc(),Sg=Lc();Uc.exports={parse:Hh,valid:zh,clean:Vh,inc:qh,diff:Wh,major:Kh,minor:Jh,patch:Zh,prerelease:Yh,compare:Xh,rcompare:Qh,compareLoose:eg,compareBuild:tg,sort:rg,rsort:ng,gt:ag,lt:ig,eq:sg,neq:og,gte:lg,lte:cg,cmp:ug,coerce:dg,Comparator:pg,Range:fg,satisfies:mg,toComparators:hg,maxSatisfying:gg,minSatisfying:_g,minVersion:yg,validRange:bg,outside:wg,gtr:vg,ltr:Eg,intersects:Tg,simplifyRange:xg,subset:Sg,SemVer:Gh,re:Pa.re,src:Pa.src,tokens:Pa.t,SEMVER_SPEC_VERSION:Dc.SEMVER_SPEC_VERSION,RELEASE_TYPES:Dc.RELEASE_TYPES,compareIdentifiers:Fc.compareIdentifiers,rcompareIdentifiers:Fc.rcompareIdentifiers}});var $u=k(hn=>{"use strict";hn.byteLength=Z_;hn.toByteArray=X_;hn.fromByteArray=ty;var Ve=[],Oe=[],J_=typeof Uint8Array<"u"?Uint8Array:Array,ai="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(gt=0,Nu=ai.length;gt<Nu;++gt)Ve[gt]=ai[gt],Oe[ai.charCodeAt(gt)]=gt;var gt,Nu;Oe[45]=62;Oe[95]=63;function Pu(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(Pu,"getLens");function Z_(t){var e=Pu(t),r=e[0],n=e[1];return(r+n)*3/4-n}o(Z_,"byteLength");function Y_(t,e,r){return(e+r)*3/4-r}o(Y_,"_byteLength");function X_(t){var e,r=Pu(t),n=r[0],a=r[1],i=new J_(Y_(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(X_,"toByteArray");function Q_(t){return Ve[t>>18&63]+Ve[t>>12&63]+Ve[t>>6&63]+Ve[t&63]}o(Q_,"tripletToBase64");function ey(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(Q_(n));return a.join("")}o(ey,"encodeChunk");function ty(t){for(var e,r=t.length,n=r%3,a=[],i=16383,s=0,l=r-n;s<l;s+=i)a.push(ey(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(ty,"fromByteArray")});var Xu=k((tU,Ze)=>{var di=require("fs"),_n=require("path"),Sy=require("os"),Ay=require("crypto"),Wu=["\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 Iy(){return Wu[Math.floor(Math.random()*Wu.length)]}o(Iy,"_getRandomTip");function Rt(t){return typeof t=="string"?!["false","0","no","off",""].includes(t.toLowerCase()):!!t}o(Rt,"parseBoolean");function Cy(){return process.stdout.isTTY}o(Cy,"supportsAnsi");function Oy(t){return Cy()?`\x1B[2m${t}\x1B[0m`:t}o(Oy,"dim");var Ry=/(?:^|^)\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=Ry.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 My(t){t=t||{};let e=Yu(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=Zu(t).split(","),a=n.length,i;for(let s=0;s<a;s++)try{let l=n[s].trim(),c=Py(r,l);i=ne.decrypt(c.ciphertext,c.key);break}catch(l){if(s+1>=a)throw l}return ne.parse(i)}o(My,"_parseVault");function Ny(t){console.error(`\u26A0 ${t}`)}o(Ny,"_warn");function ir(t){console.log(`\u2506 ${t}`)}o(ir,"_debug");function Ju(t){console.log(`\u25C7 ${t}`)}o(Ju,"_log");function Zu(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(Zu,"_dotenvKey");function Py(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(Py,"_instructions");function Yu(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)di.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 di.existsSync(e)?e:null}o(Yu,"_vaultPath");function Ku(t){return t[0]==="~"?_n.join(Sy.homedir(),t.slice(1)):t}o(Ku,"_resolveHome");function $y(t){let e=Rt(process.env.DOTENV_CONFIG_DEBUG||t&&t.debug),r=Rt(process.env.DOTENV_CONFIG_QUIET||t&&t.quiet);(e||!r)&&Ju("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($y,"_configVault");function Ly(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=[Ku(t.path)];else{s=[];for(let p of t.path)s.push(Ku(p))}let l,c={};for(let p of s)try{let m=ne.parse(di.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}Ju(`injected env (${p}) from ${m.join(",")} ${Oy(`// tip: ${Iy()}`)}`)}return l?{parsed:c,error:l}:{parsed:c}}o(Ly,"configDotenv");function Dy(t){if(Zu(t).length===0)return ne.configDotenv(t);let e=Yu(t);return e?ne._configVault(t):(Ny(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),ne.configDotenv(t))}o(Dy,"config");function Fy(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=Ay.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(Fy,"decrypt");function Uy(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(Uy,"populate");var ne={configDotenv:Ly,_configVault:$y,_parseVault:My,config:Dy,decrypt:Fy,parse:ky,populate:Uy};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 lb={};wd(lb,{default:()=>yn});module.exports=vd(lb);var dd=require("path");var gU=require("@playwright/test");var $4=require("@playwright/test");var jb=require("@playwright/test");var Lb=require("@playwright/test");var Ei=Object.defineProperty,j=o((t,e)=>{let r={};for(var n in t)Ei(r,n,{get:t[n],enumerable:!0});return e||Ei(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll");function Ti(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 Ti(`${t}.${r}`)},isInstance(r){return typeof r=="object"&&r!==null&&e in r&&r[e]===!0}}}o(Ti,"createNamespace");var xi=Ti("langchain");var Tn=xi.sub("error"),Si=class extends Tn.brand(Error){static{o(this,"LangChainError")}name="LangChainError";constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},Ed=class extends Tn.brand(Si,"model-abort"){static{o(this,"ModelAbortError")}name="ModelAbortError";partialOutput;constructor(t,e){super(t),this.partialOutput=e}},Zb=class Ai extends Tn.brand(Si,"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 Ai(e.message);return r.cause=e,r}};var Td=/([A-Z]+)([A-Z][a-z0-9]+)/g,xd=/([a-z0-9])([A-Z])/g,Sd=/[-_\s]+/g;function Ad(t){return t.replace(Td,"$1_$2").replace(xd,"$1_$2").replace(Sd,"_").toLowerCase()}o(Ad,"snakeCase");function Ii(t,e){return e?.[t]||Ad(t)}o(Ii,"keyToJson");function Ci(t,e,r){let n={};for(let a in t)Object.hasOwn(t,a)&&(n[e(a,r)]=t[a]);return n}o(Ci,"mapKeys");var Id="__lc_escaped__";function Cd(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}o(Cd,"needsEscaping");function Od(t){return{[Id]:t}}o(Od,"escapeObject");function Rd(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}o(Rd,"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(Rd(t))return t;e.add(t);let r=t;if(Cd(r))return e.delete(t),Od(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 Oi(t){return Array.isArray(t)?[...t]:{...t}}o(Oi,"shallowCopy");function Md(t,e){let r=Oi(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]=Oi(l[c]),l=l[c]}l[i]!==void 0&&(l[i]={lc:1,type:"secret",id:[a]})}return r}o(Md,"replaceSecrets");function xn(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(xn,"get_lc_unique_name");var st=class Ri{static{o(this,"Serializable")}lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,xn(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 Ri||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=Ci(Object.keys(r).length?Md(a,r):a,Ii,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:s}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function Mt(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(Mt,"isDataContentBlock");function cr(t){return Mt(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}o(cr,"isURLContentBlock");function ur(t){return Mt(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}o(ur,"isBase64ContentBlock");function Sn(t){return Mt(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}o(Sn,"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 An(t){try{return JSON.parse(t)}catch{return}}o(An,"safeParseJson");var Ee=o(t=>t(),"iife");function Nd(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(Nd,"convertAnthropicAnnotation");function Mi(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(Mi,"convertToV1FromAnthropicContentBlock");function Ni(t){function*e(){for(let r of t){let n=Mi(r);n?yield n:yield r}}return o(e,"iterateContent"),Array.from(e())}o(Ni,"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=Nd(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(Pd(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=An(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=An(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=Mi(n);if(a){yield a;continue}}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(ki,"convertToV1FromAnthropicMessage");var Pi={translateContent:ki,translateContentChunk:ki};function Pd(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}o(Pd,"_isAIMessageChunk");function $d(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}:Sn(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}o($d,"convertToV1FromDataContentBlock");function $i(t){return t.map($d)}o($i,"convertToV1FromDataContent");function Li(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(Li,"isOpenAIDataBlock");function Di(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(Di,"convertToV1FromOpenAIDataBlock");function Ld(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(Ld,"convertToV1FromChatCompletions");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,"convertToV1FromChatCompletionsChunk");function fr(t){let e=[];for(let r of t)Li(r)?e.push(Di(r)):e.push(r);return e}o(fr,"convertToV1FromChatCompletionsInput");function Fd(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(Fd,"convertResponsesAnnotation");function Fi(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(Fd)}: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(Fi,"convertToV1FromResponses");function Ud(t){function*e(){yield*Fi(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(Ud,"convertToV1FromResponsesChunk");var Ui={translateContent:o(t=>typeof t.content=="string"?Ld(t):Fi(t),"translateContent"),translateContentChunk:o(t=>typeof t.content=="string"?Dd(t):Ud(t),"translateContentChunk")};function In(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}o(In,"isMessage");function ji(t,e="pretty"){return e==="pretty"?jd(t):JSON.stringify(t)}o(ji,"convertToFormattedString");function jd(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(jd,"convertToPrettyString");var Cn=Symbol.for("langchain.message");function Bd(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(Bd,"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"}}[Cn]=!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[$i,fr,Ni].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&&Cn in t&&t[Cn]===!0&&In(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=Bd(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return ji(this,t)}};function On(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(On,"defaultToolCallParser");function Rn(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(Rn,"convertFileFormatToMimeType");function zd(t){if(R(t.document)&&R(t.document.source)){let e=Rn(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(zd,"convertConverseDocumentBlock");function Vd(t){if(T(t,"image")&&R(t.image)){let e=Rn(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(Vd,"convertConverseImageBlock");function qd(t){if(T(t,"video")&&R(t.video)){let e=Rn(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(qd,"convertConverseVideoBlock");function Bi(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 zd(n);continue}else if(T(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(T(n,"image")&&R(n.image)){yield Vd(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 qd(n);continue}}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(Bi,"convertToV1FromChatBedrockConverseMessage");var Gi={translateContent:Bi,translateContentChunk:Bi};function Hi(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(Hi,"convertToV1FromDeepSeekMessage");var zi={translateContent:Hi,translateContentChunk:Hi};function Vi(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(Vi,"convertToV1FromChatGoogleMessage");var qi={translateContent:Vi,translateContentChunk:Vi};function Wi(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(Wi,"convertToV1FromChatVertexMessage");var Ki={translateContent:Wi,translateContentChunk:Wi};function Ji(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(Ji,"convertToV1FromGroqMessage");var Zi={translateContent:Ji,translateContentChunk:Ji};function Yi(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(Yi,"convertToV1FromOllamaMessage");var Xi={translateContent:Yi,translateContentChunk:Yi};function Qi(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(Qi,"convertToV1FromOpenRouterMessage");var es={translateContent:Qi,translateContentChunk:Qi};function ts(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(ts,"convertToV1FromXAIMessage");var rs={translateContent:ts,translateContentChunk:ts};function ns(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(ns,"convertToV1FromChatGoogleMessage");var as={translateContent:ns,translateContentChunk:ns};globalThis.lc_block_translators_registry??=new Map([["anthropic",Pi],["bedrock-converse",Gi],["deepseek",zi],["google",as],["google-genai",qi],["google-vertexai",Ki],["groq",Zi],["ollama",Xi],["openai",Ui],["openrouter",es],["xai",rs]]);function is(t){return globalThis.lc_block_translators_registry.get(t)}o(is,"getTranslator");function ss(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(ss,"mergeModalitiesTokenDetails");function Wd(t,e){let r={...ss(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(Wd,"mergeInputTokenDetails");function Kd(t,e){let r={...ss(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}o(Kd,"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:Wd(t?.input_token_details,e?.input_token_details),output_token_details:Kd(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.
|
|
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]=On(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=is(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 tp(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(tp,"_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(tp).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(""),rp=[-2147483648,8388608,32768,128],ke=[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]<<ke[i++&3];else for(i=this.start;a<s&&i<64;++a)n=t.charCodeAt(a),n<128?l[i>>>2]|=n<<ke[i++&3]:n<2048?(l[i>>>2]|=(192|n>>>6)<<ke[i++&3],l[i>>>2]|=(128|n&63)<<ke[i++&3]):n<55296||n>=57344?(l[i>>>2]|=(224|n>>>12)<<ke[i++&3],l[i>>>2]|=(128|n>>>6&63)<<ke[i++&3],l[i>>>2]|=(128|n&63)<<ke[i++&3]):(n=65536+((n&1023)<<10|t.charCodeAt(++a)&1023),l[i>>>2]|=(240|n>>>18)<<ke[i++&3],l[i>>>2]|=(128|n>>>12&63)<<ke[i++&3],l[i>>>2]|=(128|n>>>6&63)<<ke[i++&3],l[i>>>2]|=(128|n&63)<<ke[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]|=rp[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 hp=xe(Tr(),1);var As=/^(?:[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"&&As.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 gp=new Uint8Array(16);function Lt(){return crypto.getRandomValues(gp)}o(Lt,"rng");function _p(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(_p,"f");function Dn(t,e){return t<<e|t>>>32-e}o(Dn,"ROTL");function Is(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]=Dn(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=Dn(u,5)+_p(x,p,m,g)+h+e[x]+c[E]>>>0;h=g,g=m,m=Dn(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(Is,"sha1");function yp(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(yp,"stringToBytes");var Cs="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Os="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Rs(t,e,r,n,a,i){let s=typeof r=="string"?yp(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(Rs,"v35");function Fn(t,e,r,n){return Rs(80,Is,t,e,r,n)}o(Fn,"v5");Fn.DNS=Cs;Fn.URL=Os;var Un={};function Ms(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();wp(Un,a,i),n=ks(i,Un.msecs,Un.seq,e,r)}return e??Xe(n)}o(Ms,"v7");function wp(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(wp,"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=Ms;var Ns=Symbol.for("ls:tracing_async_local_storage"),lt=Symbol.for("lc:context_variables"),Ps=o(t=>{globalThis[Ns]=t},"setGlobalAsyncLocalStorageInstance"),Qe=o(()=>globalThis[Ns],"getGlobalAsyncLocalStorageInstance");var vp=o(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),Ep=o(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),Tp=o(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),Bn=o(()=>typeof Deno<"u","isDeno"),xp=o(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Bn(),"isNode"),Sp=o(()=>{let t;return vp()?t="browser":xp()?t="node":Ep()?t="webworker":Tp()?t="jsdom":Bn()?t="deno":t="other",t},"getEnv"),jn;function $s(){return jn===void 0&&(jn={library:"langchain-js",runtime:Sp()}),jn}o($s,"getRuntimeEnvironment");function Me(t){try{return typeof process<"u"?process.env?.[t]:Bn()?Deno?.env.get(t):void 0}catch{return}}o(Me,"getEnvironmentVariable");var Ap=class{static{o(this,"BaseCallbackHandlerMethodsClass")}};var vt=class extends Ap{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,xn(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 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}},Ls=o(t=>{let e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},"isBaseCallbackHandler");var Ds=/^(?:[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 Ip(t){return typeof t=="string"&&Ds.test(t)}o(Ip,"validate");var Fs=Ip;function Cp(t){if(!Fs(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(Cp,"parse");var Us=Cp;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 js=xe(require("node:crypto"));var Sr=new Uint8Array(256),xr=Sr.length;function Dt(){return xr>Sr.length-16&&(js.default.randomFillSync(Sr),xr=0),Sr.slice(xr,xr+=16)}o(Dt,"rng");function Op(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}o(Op,"stringToBytes");var Rp="6ba7b810-9dad-11d1-80b4-00c04fd430c8",kp="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Gn(t,e,r){function n(a,i,s,l){var c;if(typeof a=="string"&&(a=Op(a)),typeof i=="string"&&(i=Us(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=Rp,n.URL=kp,n}o(Gn,"v35");var Bs=xe(require("node:crypto")),Hn={randomUUID:Bs.default.randomUUID};function Mp(t,e,r){if(Hn.randomUUID&&!e&&!t)return Hn.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(Mp,"v4");var ct=Mp;var Gs=xe(require("node:crypto"));function Np(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),Gs.default.createHash("sha1").update(t).digest()}o(Np,"sha1");var Hs=Np;var Pp=Gn("v5",80,Hs),zn=Pp;var zs=null,Vs=null,Ne=0;function $p(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=Vs,u=zs;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,Vs=c,zs=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($p,"v7");var Ft=$p;var qs="gen_ai.operation.name",Ws="gen_ai.system",Vn="gen_ai.request.model",Ks="gen_ai.response.model",qn="gen_ai.usage.input_tokens",Wn="gen_ai.usage.output_tokens",Kn="gen_ai.usage.total_tokens",Js="gen_ai.request.max_tokens",Zs="gen_ai.request.temperature",Ys="gen_ai.request.top_p",Xs="gen_ai.request.frequency_penalty",Qs="gen_ai.request.presence_penalty",eo="gen_ai.response.finish_reasons",to="gen_ai.prompt",ro="gen_ai.completion",no="gen_ai.request.extra_query",ao="gen_ai.request.extra_body",io="gen_ai.serialized.name",so="gen_ai.serialized.signature",oo="gen_ai.serialized.doc",lo="gen_ai.response.id",co="gen_ai.response.service_tier",uo="gen_ai.response.system_fingerprint",po="gen_ai.usage.input_token_details",fo="gen_ai.usage.output_token_details",mo="langsmith.trace.session_id",ho="langsmith.trace.session_name",go="langsmith.span.kind",_o="langsmith.trace.name",yo="langsmith.metadata",Jn="langsmith.span.tags";var bo="langsmith.request.streaming",wo="langsmith.request.headers";var Fp=o((...t)=>fetch(...t),"DEFAULT_FETCH_IMPLEMENTATION"),Up,vo=Symbol.for("ls:fetch_implementation");var Eo=o(()=>globalThis[vo]===void 0?!0:Up??!1,"_shouldStreamForGlobalFetchImplementation"),To=o(t=>async(...e)=>{if(t||J("DEBUG")==="true"){let[n,a]=e;console.log(`\u2192 ${a?.method||"GET"} ${n}`)}let r=await(globalThis[vo]??Fp)(...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 xo={};function ut(t){xo[t]||(console.warn(t),xo[t]=!0)}o(ut,"warnOnce");var v=o(t=>BigInt(t),"n"),Co=v("0x9E3779B1"),Oo=v("0x85EBCA77"),jp=v("0xC2B2AE3D"),et=v("0x9E3779B185EBCA87"),dt=v("0xC2B2AE3D27D4EB4F"),Ro=v("0x165667B19E3779F9"),Qn=v("0x85EBCA77C2B2AE63"),Bp=v("0x27D4EB2F165667C5"),Gp=v("0x165667919E3779F9"),Hp=v("0x9FB21C651E98DF25");function zp(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(zp,"hexToBytes");var Fe=zp("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,Vp=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 Zn(t,e=0){return t[e]}o(Zn,"readUInt8");var qp=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"),Wp=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"),Kp=o((t,e)=>(t&Or)*(e&Or)&U,"XXH_mult32to64"),St=o(t=>{if(!t)throw new Error("Assert failed")},"assert");function Jp(t,e){return(t<<e|t>>v(32)-e)&Or}o(Jp,"rotl32");function Mo(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]+=Kp(i,i>>v(32))}return t}o(Mo,"XXH3_accumulate_512");function So(t,e,r,n){for(let a=0;a<n;a++)Mo(t,q(e,a*We),q(r,a*8));return t}o(So,"XXH3_accumulate");function Zp(t,e){for(let r=0;r<ko;r++){let n=W(e,r*8),a=t[r];a=Yn(a,v(47)),a^=n,a*=Co,t[r]=a&U}return t}o(Zp,"XXH3_scrambleAcc");function Ir(t,e){return No(t[0]^W(e,0),t[1]^W(e,Vp))}o(Ir,"XXH3_mix2Accs");function Ao(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(Ao,"XXH3_mergeAccs");function Yp(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=So(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=So(t,q(e,l*s),r,c),t=n(t,q(e,e.byteLength-We),q(r,r.byteLength-We-7))}return t}o(Yp,"XXH3_hashLong");function Xp(t,e,r){let n=new BigUint64Array([jp,et,dt,Ro,Qn,Oo,Bp,Co]);St(t.length>128),n=Yp(n,t,e,Mo,Zp),St(n.length*8==64);{let a=Ao(n,q(e,11),v(t.byteLength)*et&U);return Ao(n,q(e,e.byteLength-We-11),~(v(t.byteLength)*dt)&U)<<v(64)|a}}o(Xp,"XXH3_hashLong_128b");function No(t,e){let r=t*e&xt;return r&U^r>>v(64)}o(No,"XXH3_mul128_fold64");function Io(t,e,r){return No((W(t,0)^W(e,0)+r)&U,(W(t,8)^W(e,8)-r)&U)}o(Io,"XXH3_mix16B");function Cr(t,e,r,n,a){let i=t&U,s=t>>v(64)&U;return i+=Io(e,n,a),i^=W(r,0)+W(r,8),i&=U,s+=Io(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*=Gp,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*=Ro,t&=U,t^=t>>v(32),t}o(Rr,"XXH3_avalanche64");function Qp(t,e,r){let n=t.byteLength;St(n>0&&n<=3);let a=v(Zn(t,n-1))|v(n<<8)|v(Zn(t,0)<<16)|v(Zn(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=(Jp(Wp(a),v(13))^l)&U;return(Rr(c)&U)<<v(64)|Rr(s)}o(Qp,"XXH3_len_1to3_128b");function Yn(t,e){return t^t>>e}o(Yn,"xorshift64");function ef(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),Yn(Yn(u&U,v(35))*Hp&U,v(28))|Ue(u>>v(64))<<v(64)}}o(ef,"XXH3_len_4to8_128b");function tf(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)*(Oo-v(1))<<v(64),c&=xt,c^=qp(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(tf,"XXH3_len_9to16_128b");function rf(t,e){let r=t.byteLength;return St(r<=16),r>8?tf(t,Fe,e):r>=4?ef(t,Fe,e):r>0?Qp(t,Fe,e):Rr(e^W(Fe,64)^W(Fe,72))|Rr(e^W(Fe,80)^W(Fe,88))<<v(64)}o(rf,"XXH3_len_0to16_128b");function Xn(t){return~t+v(1)&U}o(Xn,"inv64");function nf(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))*Qn+(v(t.byteLength)-r&U)*dt;return s&=U,s=Xn(Ue(s)),i|s<<v(64)}o(nf,"XXH3_len_17to128_128b");function af(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),Xn(r));let a=n+(n>>v(64))&U;a=Ue(a);let i=(n&U)*et+(n>>v(64))*Qn+(v(t.byteLength)-r&U)*dt;return i&=U,i=Xn(Ue(i)),a|i<<v(64)}o(af,"XXH3_len_129to240_128b");function Po(t,e=v(0)){let r=t.byteLength;return r<=16?rf(t,e):r<=128?nf(t,Fe,e):r<=240?af(t,Fe,e):Xp(t,Fe,e)}o(Po,"XXH3_128");function $o(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($o,"xxh128ToBytes");var Lo=/^[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(!Lo.test(t)){let r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}o($,"assertUuid");function kr(t){let e=typeof t=="string"?Date.parse(t):t;return Ft({msecs:e,seq:0})}o(kr,"uuid7FromTime");function sf(t){if(!Lo.test(t))return null;let e=t[14];return parseInt(e,16)}o(sf,"getUuidVersion");function of(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(of,"uuidToBytes");function lf(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(lf,"bytesToUuid");var cf=new TextEncoder;function uf(t){let e=cf.encode(t),r=Po(e);return $o(r)}o(uf,"_fastHash128");function jt(t,e){let r=`${t}:${e}`,n=uf(r),a=new Uint8Array(16);if(sf(t)===7){let s=of(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),lf(a)}o(jt,"nonCryptographicUuid7Deterministic");var Se=xe(require("node:fs"),1),Pe=xe(require("node:fs/promises"),1),df=xe(require("node:path"),1);var Bt=df;async function Do(t){await Pe.mkdir(t,{recursive:!0})}o(Do,"mkdir");async function Fo(t,e){let r=`${t}.tmp`;await Pe.writeFile(r,e,{encoding:"utf8",mode:384}),await Pe.rename(r,t)}o(Fo,"writeFileAtomic");async function Uo(t){return Pe.readdir(t)}o(Uo,"readdir");async function jo(t){return Pe.stat(t)}o(jo,"stat");function Mr(t){return Se.existsSync(t)}o(Mr,"existsSync");function Bo(t){Se.mkdirSync(t,{recursive:!0})}o(Bo,"mkdirSync");function Go(t,e){Se.writeFileSync(t,e)}o(Go,"writeFileSync");function Ho(t,e){Se.renameSync(t,e)}o(Ho,"renameSync");function zo(t){Se.unlinkSync(t)}o(zo,"unlinkSync");function Vo(t){return Se.readFileSync(t,"utf-8")}o(Vo,"readFileSync");function ff(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}o(ff,"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);Mr(n)||Bo(n);let a=`${e}.tmp`;try{Go(a,JSON.stringify({entries:r},null,2)),Ho(a,e)}catch(i){throw Mr(a)&&zo(a),i}}load(e){if(!Mr(e))return 0;let r;try{let i=Vo(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())ff(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,mf=o(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),hf=o(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),gf=o(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),qo=o(()=>typeof Deno<"u","isDeno"),_f=o(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!qo(),"isNode"),ra=o(()=>je||(typeof Bun<"u"?je="bun":mf()?je="browser":_f()?je="node":hf()?je="webworker":gf()?je="jsdom":qo()?je="deno":je="other",je),"getEnv"),ea;function Lr(){if(ea===void 0){let t=ra(),e=bf();ea={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:$r,...e}}return ea}o(Lr,"getRuntimeEnvironment");function na(){let t=yf(),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(na,"getLangSmithEnvVarsMetadata");function yf(){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(yf,"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 ta;function bf(){if(ta!==void 0)return ta;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 ta=e,e}o(bf,"getShas");function Dr(){return Te("OTEL_ENABLED")==="true"||J("OTEL_ENABLED")==="true"}o(Dr,"getOtelEnabled");var sa=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()}},oa=class{static{o(this,"MockOTELTrace")}constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new sa})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},la=class{static{o(this,"MockOTELContext")}active(){return{}}with(e,r){return r()}},aa=Symbol.for("ls:otel_trace"),ia=Symbol.for("ls:otel_context"),Wo=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),wf=new oa,vf=new la,ca=class{static{o(this,"OTELProvider")}getTraceInstance(){return globalThis[aa]??wf}getContextInstance(){return globalThis[ia]??vf}initializeGlobalInstances(e){globalThis[aa]===void 0&&(globalThis[aa]=e.trace),globalThis[ia]===void 0&&(globalThis[ia]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[Wo]=e}getDefaultOTLPTracerComponents(){return globalThis[Wo]??void 0}},ua=new ca;function Fr(){return ua.getTraceInstance()}o(Fr,"getOTELTrace");function Ko(){return ua.getContextInstance()}o(Ko,"getOTELContext");function Jo(){return ua.getDefaultOTLPTracerComponents()}o(Jo,"getDefaultOTLPTracerComponents");var Ef={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function Tf(t){return Ef[t]||t}o(Tf,"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(go,r.run_type);let l=Tf(r.run_type||"chain");e.setAttribute(qs,l)}"name"in r&&r.name&&e.setAttribute(_o,r.name),"session_id"in r&&r.session_id&&e.setAttribute(mo,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(ho,r.session_name),this.setGenAiSystem(e,r);let a=this.extractModelName(r);a&&e.setAttribute(Vn,a),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(qn,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(Wn,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(Kn,r.total_tokens),this.setInvocationParameters(e,r);let i=r.extra?.metadata||{};for(let[l,c]of Object.entries(i))c!=null&&e.setAttribute(`${yo}.${l}`,String(c));let s=r.tags;if(s&&Array.isArray(s)?e.setAttribute(Jn,s.join(", ")):s&&e.setAttribute(Jn,String(s)),"serialized"in r&&typeof r.serialized=="object"){let l=r.serialized;l.name&&e.setAttribute(io,String(l.name)),l.signature&&e.setAttribute(so,String(l.signature)),l.doc&&e.setAttribute(oo,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(Ws,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(Js,n.max_tokens),n.temperature!==void 0&&e.setAttribute(Zs,n.temperature),n.top_p!==void 0&&e.setAttribute(Ys,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(Xs,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(Qs,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(Vn,n.model),n.stream!==void 0&&e.setAttribute(bo,n.stream),n.extra_headers&&e.setAttribute(wo,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(no,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(ao,JSON.stringify(n.extra_body))),e.setAttribute(to,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(qn,a[0]),e.setAttribute(Wn,a[1]),e.setAttribute(Kn,a[0]+a[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(Ks,String(n.model)),n.id&&e.setAttribute(lo,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(eo,i.join(", "))}if(n.service_tier&&e.setAttribute(co,n.service_tier),n.system_fingerprint&&e.setAttribute(uo,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let i=n.usage_metadata;i.input_token_details&&e.setAttribute(po,JSON.stringify(i.input_token_details)),i.output_token_details&&e.setAttribute(fo,JSON.stringify(i.output_token_details))}}e.setAttribute(ro,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 xf=Object.prototype.toString,Sf=o(t=>xf.call(t)==="[object Error]","isError"),Af=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 da(t){if(!(t&&Sf(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:Af.has(r)}o(da,"isNetworkError");function If(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(If,"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 pa=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 Cf(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(Cf,"calculateDelay");function Zo(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}o(Zo,"calculateRemainingTime");async function Of({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 pa)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),Zo(n,l)<=0)throw i;let u=await a.shouldConsumeRetry(c),p=Zo(n,l);if(p<=0||s<=0)throw i;if(i instanceof TypeError&&!da(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=Cf(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(Of,"onAttemptFailure");async function fa(t,e={}){if(e={...e},If(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 Of({error:i,attemptNumber:r,retriesConsumed:n,startTime:a,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}o(fa,"pRetry");var Br=xe(Tr(),1),Yo="default"in Br.default?Br.default.default:Br.default;var Rf=[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 Yo({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(()=>fa(()=>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")&&!Rf.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 ma(t){return typeof t?._getType=="function"}o(ma,"isLangChainMessage");function ha(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(ha,"convertLangChainMessageToExample");var Ag=xe(jc(),1);function tn(t){return`Invalid prompt identifier format: "${t}". Expected one of:
|
|
8
|
+
- "prompt-name" (for private prompts)
|
|
9
|
+
- "owner/prompt-name" (for prompts with explicit owner)
|
|
10
|
+
- "prompt-name:commit-hash" (with commit reference)
|
|
11
|
+
- "owner/prompt-name:commit-hash" (with owner and commit)`}o(tn,"getInvalidPromptIdentifierMsg");var $a=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}},La=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 Da(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}o(Da,"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 La(a);if(t.status===409)throw new $a(a);let i=new Error(a);throw i.status=t.status,i}o(O,"raiseForStatus");var Bc="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:Bc}),this.name="ConflictingEndpointsError"}};function Gc(t){return typeof t=="object"&&t!==null&&t.code===Bc}o(Gc,"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 Hc="[...]",Ig={result:"[Circular]"},nn=[],It=[],Cg=new TextEncoder;function Og(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}o(Og,"defaultOptions");function rn(t){return Cg.encode(t)}o(rn,"encodeString");function zc(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(zc,"serializeWellKnownTypes");function Rg(t){return function(e,r){if(t){let n=t.call(this,e,r);if(n!==void 0)return n}return zc(r)}}o(Rg,"createDefaultReplacer");function _e(t,e,r,n,a){try{let i=JSON.stringify(t,Rg(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=Og()),Ua(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 Fa(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(Fa,"setReplace");function Ua(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){Fa(Ig,t,e,a);return}if(typeof s.depthLimit<"u"&&i>s.depthLimit){Fa(Hc,t,e,a);return}if(typeof s.edgesLimit<"u"&&r+1>s.edgesLimit){Fa(Hc,t,e,a);return}if(n.push(t),Array.isArray(t))for(l=0;l<t.length;l++)Ua(t[l],l,l,n,t,i,s);else{t=zc(t);var c=Object.keys(t);for(l=0;l<c.length;l++){var u=c[l];Ua(t[u],u,l,n,t,i,s)}}n.pop()}}o(Ua,"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 Vc(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}o(Vc,"_ensureUTCTimestamp");function Zt(t){return{...t,start_time:Vc(t.start_time),end_time:Vc(t.end_time)}}o(Zt,"_normalizeRunTimestamps");function qc(t,e,r){if(r)return t;let n=Lr(),a=e??na(),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(qc,"mergeRuntimeEnvIntoRun");var Mg=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"),Ng=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 Pg(t){let e=[];for await(let r of t)e.push(r);return e}o(Pg,"toArray");function an(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}o(an,"trimQuotes");var $g=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 Wc(t){return typeof t=="number"?Number(t.toFixed(4)):t}o(Wc,"_formatFeedbackScore");var Lg=24*1024*1024,Zc=1024*1024*1024,Dg=1e4,Fg=100,Kc="https://api.smith.langchain.com",ja=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??Zc}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||To(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=Mg(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??Zc;this.batchIngestCaller=new Gt({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:a,...e.callerOptions??{},onFailedResponseHook:$g,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 ja(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=na(),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")??Kc,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:Ng(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??Lg}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??Fg}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 Do(e),t._fallbackDirsCreated.add(e)),i!==void 0&&i>0)try{let m=(await Uo(e)).filter(h=>h.startsWith("trace_")&&h.endsWith(".json")),g=0;for(let h of m){let{size:E}=await jo(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 Fo(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(Da(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=qc(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(Dg),...this.fetchOptions});return await O(n,"get server info"),n})).json();return this.debug&&console.log(`
|
|
14
|
+
=== LangSmith Server Configuration ===
|
|
15
|
+
`+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=Ko();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=qc(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:M,...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
|
|
19
|
+
\r
|
|
20
|
+
`])),n.push(s.payload),n.push(new Blob([`\r
|
|
21
|
+
`]));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
|
|
25
|
+
\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;Eo()&&!this.multipartStreamingDisabled&&ra()!=="bun"?(u=!0,c=await l(s)):c=await l(i),(!this.multipartStreamingDisabled||u)&&c.status===422&&(n?.apiUrl??this.apiUrl)!==Kc&&(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(Da(c))throw c;if(console.warn(`${c.message.trim()}
|
|
29
|
+
|
|
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 Pg(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,M=[];if(r&&(M=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)));M.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:M.length?M: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:M,total:F}=C;if(M.length===0)break;for(let B of M)yield B;if(g+=M.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),M=C.thread_id;if(M){let F=h.get(M)??[];F.push(C),h.set(M,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 M=[...L.map(V=>V.start_time).filter(Boolean)].sort(),F=M.length?M[0]:"",B=M.length?M[M.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)),M=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:M});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(Jc(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;Jc(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,M=L[0].dataset_name;if(C===void 0&&M===void 0)throw new Error("Must provide either datasetName or datasetId");if(C!==void 0&&M!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");C===void 0&&(C=(await this.readDataset({datasetName:M})).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=>ma(s)?ha(s):s),i=ma(r)?ha(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,...M}=L,F=M;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:Wc(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 M=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(M,"create feedback",!0),M}),N}async updateFeedback(e,{score:r,value:n,correction:a,comment:i}){let s={};r!=null&&(s.score=Wc(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.
|
|
35
|
+
|
|
36
|
+
Current tenant: ${n.tenant_handle}
|
|
37
|
+
|
|
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
|
|
39
|
+
|
|
40
|
+
creating a LangChain Hub handle.
|
|
41
|
+
You can add a handle by creating a public prompt at:
|
|
42
|
+
|
|
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 Jo()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}};Object.defineProperty(tt,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function Jc(t){return"dataset_id"in t||"dataset_name"in t}o(Jc,"isExampleCreate");var Yc=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 Ba(t,e){if(He in t)return t[He][e]}o(Ba,"getContextVar");function Xc(t,e,r){let n=He in t?t[He]:{};n[e]=r,t[He]=n}o(Xc,"setContextVar");var Yt=36,Ug="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function Qc(t){let r=Object.keys(t).sort().map(n=>`${n}:${t[n]??""}`).join("|");return zn(r,Ug)}o(Qc,"getReplicaKey");function jg(t){return t.replace(/[-:.]/g,"")}o(jg,"stripNonAlphanumeric");function tu(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(tu,"getMicrosecondPrecisionDatestring");function Ga(t,e,r=1){let n=tu(t,r);return{dottedOrder:jg(n)+e,microsecondPrecisionDatestring:n}}o(Ga,"convertToDottedOrderFormat");var Bg=new Set(["projectName","updates","reroot"]);function Gg(t){let e={};for(let r of Object.keys(t))Bg.has(r)&&(e[r]=t[r]);return e}o(Gg,"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:Gg(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}),ru(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=tu(this.start_time,this.execution_order)),this.id||(this.id=kr(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=qg(this.replicas),!this.dotted_order){let{dottedOrder:l}=Ga(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(zg(u)){let g={...u},h=Hg(g.callbacks)?g.callbacks.copy?.():void 0;h&&(Object.assign(h,{_parentRunId:i.id}),h.handlers?.find(nu)?.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=Ba(this,sn)??{};n[e]=r,Xc(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=Qc({projectName:r,apiUrl:l,apiKey:c,workspaceId:u});this._setReplicaTraceRoot(N,p.id)}let m;if(!i){let N=Ba(this,sn)??{},L=Qc({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("."),M=null;for(let F=0;F<C.length;F++)if(C[F].slice(-Yt)===m){M=F;break}if(M!==null){let F=C.slice(M);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 M=C.slice(-Yt),F=jt(M,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=Yc();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 ru(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}o(ru,"isRunTree");function nu(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}o(nu,"isLangChainTracerLike");function eu(t){return Array.isArray(t)&&t.some(e=>nu(e))}o(eu,"containsLangChainTracerLike");function Hg(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}o(Hg,"isCallbackManagerLike");function zg(t){let e=t?.callbacks;return t!=null&&typeof e=="object"&&(eu(e?.handlers)||eu(e))}o(zg,"isRunnableConfigLike");function Vg(){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){Wg(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(Gc(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(Vg,"_getWriteReplicasFromEnv");function qg(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):Vg()}o(qg,"_ensureWriteReplicas");function Wg(t){if(Object.keys(t).length>0&&J("ENDPOINT"))throw new en}o(Wg,"_checkEndpointEnvUnset");var Kg=o(t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t},"convertRunTreeToRun");function za(t,e){if(t)return new $e({...t,start_time:t._serialized_start_time??t.start_time,parent_run:za(e),child_runs:t.child_runs.map(r=>za(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:$s()},tracingEnabled:!1})}o(za,"convertRunToRunTree");function Ha(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}o(Ha,"_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?Kg(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}=Ga(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=za(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=Ha(t,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),a?.inputs!==void 0&&(i.inputs=Ha(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=Ha(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 iu={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 au(t){return typeof t=="string"?t.trim():t==null?t:Ce(t,t.toString())}o(au,"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}=iu,Va=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(iu.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: "${au(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: "${au(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 qa,Wa=o(()=>(qa===void 0&&(qa=new tt(Me("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),qa),"getDefaultLangChainClientSingleton");var Ja=class{static{o(this,"MockAsyncLocalStorage")}getStore(){}run(e,r){return r()}},Ka=Symbol.for("ls:tracing_async_local_storage"),Jg=new Ja,Za=class{static{o(this,"AsyncLocalStorageProvider")}getInstance(){return globalThis[Ka]??Jg}initializeGlobalInstance(e){globalThis[Ka]===void 0&&(globalThis[Ka]=e)}},Zg=new Za;function su(t=!1){let e=Zg.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(su,"getCurrentRunTree");var lu=new Set(["ls_agent_type"]);function Yg(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(Yg,"_getUsageMetadataFromGenerations");var Xt=class Ya 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??Wa(),this.tracingMetadata=s?{...s}:void 0,this.tracingTags=l??[];let c=Ya.getTraceableRunTree();c&&this.updateFromRunTree(c)}async persistRun(e){}async onRunCreate(e){ou(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){ou(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=Yg(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)||lu.has(s))&&(n[s]=l)}let a=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],i=new Ya({...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 su(!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 ou(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)||lu.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(ou,"_patchMissingTracingDefaults");var ln=xe(Tr(),1);var Qt;function Xg(){return new("default"in ln.default?ln.default.default:ln.default)({autoStart:!0,concurrency:1})}o(Xg,"createQueue");function Qg(){return typeof Qt>"u"&&(Qt=Xg()),Qt}o(Qg,"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=Qg(),Qt.add(async()=>{let r=Qe();r!==void 0?await r.run(void 0,async()=>t()):await t()})}o(Z,"consumeCallback");var cu=o(t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>Me(e)==="true"),"isTracingEnabled");function Xa(t){let e=Qe();if(e!==void 0)return e.getStore()?.[lt]?.[t]}o(Xa,"getContextVariable");var e_=Symbol("lc:configure_hooks"),uu=o(()=>Xa(e_)||[],"_getConfigureHooks");var t_=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)))}},r_=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)))}},du=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)))}},n_=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)))}},a_=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 t_{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 du(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 du(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 n_(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 a_(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 r_(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(Qa)??[],!0)):c=e,c=c.copy(Array.isArray(r)?r.map(Qa):r?.handlers,!1));let u=Me("LANGCHAIN_VERBOSE")==="true"||l?.verbose,p=Xt.getTraceableRunTree(),m=p?.tracingEnabled??cu();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||(Me("LANGCHAIN_TRACING")??!1);if(u||g){if(c||(c=new er),u&&!c.handlers.some(x=>x.name===Va.prototype.name)){let x=new Va;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 uu()){let C=L&&Me(L)==="true"&&N,M,F=x!==void 0?Xa(x):void 0;F&&Ls(F)?M=F:C&&(M=new N({})),M!==void 0&&(c||(c=new er),c.handlers.some(B=>B.name===M.name)||c.addHandler(M,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 Qa(t){return"name"in t?t:vt.fromMethods(t)}o(Qa,"ensureHandler");var fu=class{static{o(this,"MockAsyncLocalStorage")}getStore(){}run(t,e){return e()}enterWith(t){}},i_=new fu,pu=Symbol.for("lc:child_config"),s_=class{static{o(this,"AsyncLocalStorageProvider")}getInstance(){return Qe()??i_}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[pu]}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,[pu]: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&&Ps(t)}},tr=new s_;var o_=Object.prototype.hasOwnProperty;function gu(t,e){return o_.call(t,e)}o(gu,"hasOwnProperty");function _u(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)gu(t,r)&&e.push(r);return e}o(_u,"_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 yu(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}o(yu,"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=_u(t),n=r.length;for(var e=0;e<n;e++)if(un(t[r[e]]))return!0}}return!1}o(un,"hasUndefined");function hu(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(hu,"patchErrorMessageFormatter");var bu=class extends Error{static{o(this,"PatchError")}constructor(t,e,r,n,a){super(hu(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=hu(t,{name:e,index:r,operation:n,tree:a})}};var wu=j({JsonPatchError:o(()=>Y,"JsonPatchError"),_areEquals:o(()=>rr,"_areEquals"),applyOperation:o(()=>ht,"applyOperation"),applyPatch:o(()=>mn,"applyPatch"),applyReducer:o(()=>u_,"applyReducer"),deepClone:o(()=>l_,"deepClone"),getValueByPointer:o(()=>pn,"getValueByPointer"),validate:o(()=>vu,"validate"),validator:o(()=>fn,"validator")}),Y=bu,l_=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")},c_={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=yu(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=c_[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 u_(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(u_,"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=vu([{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 vu(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(vu,"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");({...wu});var uN=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 __=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,y_=[0,31,28,31,30,31,30,31,31,30,31,30,31],b_=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,w_=/^(?=.{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,v_=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,E_=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,T_=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,x_=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,S_=/^(?:\/(?:[^~/]|~0|~1)*)*$/,A_=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,I_=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,C_=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"),O_=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,R_=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,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 M_={date:Eu,time:Tu.bind(void 0,!1),"date-time":$_,duration:k_,uri:F_,"uri-reference":ze(v_),"uri-template":ze(E_),url:ze(T_),email:C_,hostname:ze(w_),ipv4:ze(O_),ipv6:ze(R_),regex:j_,uuid:ze(x_),"json-pointer":ze(S_),"json-pointer-uri-fragment":ze(A_),"relative-json-pointer":ze(I_)};function N_(t){return t%4===0&&(t%100!==0||t%400===0)}o(N_,"isLeapYear");function Eu(t){let e=t.match(__);if(!e)return!1;let r=+e[1],n=+e[2],a=+e[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&N_(r)?29:y_[n])}o(Eu,"date");function Tu(t,e){let r=e.match(b_);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(Tu,"time");var P_=/t|\s/i;function $_(t){let e=t.split(P_);return e.length==2&&Eu(e[0])&&Tu(!0,e[1])}o($_,"date_time");var L_=/\/|:/,D_=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function F_(t){return L_.test(t)&&D_.test(t)}o(F_,"uri");var U_=/[^\\]\\Z/;function j_(t){if(U_.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}o(j_,"regex");var xu;(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(xu||(xu={}));var Lu=xe($u(),1);var ry=Object.defineProperty,ny=o((t,e,r)=>e in t?ry(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,"__defNormalProp"),ay=o((t,e,r)=>(ny(t,typeof e!="symbol"?e+"":e,r),r),"__publicField");function iy(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(iy,"bytePairMerge");function sy(t,e){return t.length===1?[e.get(t.join(","))]:iy(t,e).map(r=>e.get(t.slice(r.start,r.end).join(","))).filter(r=>r!=null)}o(sy,"bytePairEncode");function oy(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}o(oy,"escapeRegex");var ii=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=Lu.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=ii.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=ii.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(...sy(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)}},si=ii;ay(si,"specialTokenRegex",t=>new RegExp(t.map(e=>oy(e)).join("|"),"g"));var ju=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"];var Bu=["image","video","audio","text-plain","file"];var uy=["text","reasoning",...ju,...Bu];var yy=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(){hi(this)},"end"),write:fd,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 M(f){return f==='"'||f==="'"}o(M,"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 hi(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(hi,"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 pd(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(pd,"newTag");function bn(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(bn,"qname");function wn(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=bn(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(wn,"attrib");function nt(f,d){if(f.opt.xmlns){var w=f.tag,y=bn(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(wi){G(f,"onopennamespace",{prefix:wi,uri:w.ns[wi]})});for(var Q=0,we=f.attribList.length;Q<we;Q++){var pe=f.attribList[Q],Re=pe[0],at=pe[1],le=bn(Re,!0),it=le.prefix,md=le.local,bi=it===""?"":w.ns[it]||"",En={name:Re,value:at,prefix:it,local:md,uri:bi};it&&it!=="xmlns"&&!bi&&(z(f,"Unbound namespace prefix: "+JSON.stringify(it)),En.uri=it),f.tag.attributes[Re]=En,G(f,"onattribute",En)}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 vn(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(vn,"closeTag");function gi(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(gi,"parseEntity");function _i(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(_i,"beginWhiteSpace");function yi(f,d){var w="";return d<f.length&&(w=f.charAt(d)),w}o(yi,"charAt");function fd(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 hi(d);typeof f=="object"&&(f=f.toString());for(var w=0,y="";y=yi(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;_i(d,y);continue;case _.BEGIN_WHITESPACE:_i(d,y);continue;case _.TEXT:if(d.sawRoot&&!d.closedRoot){for(var H=w-1;y&&y!=="<"&&y!=="&";)y=yi(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):(M(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:M(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:M(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:(pd(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),vn(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,wn(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;M(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}wn(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}wn(d),y===">"?nt(d):d.state=_.ATTRIB;continue;case _.CLOSE_TAG:if(d.tagName)y===">"?vn(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===">"?vn(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=gi(d);d.entity="",d.state=we,d.write(Re)}else d[pe]+=gi(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(fd,"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"),by=yy();var cU=require("@playwright/test");var Q4={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 Qu=xe(Xu());Qu.default.config({path:[`${__dirname}/.env`,`${__dirname}/../../.env`]});var jy="claude_4",By={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}},Gy=o(()=>({nodeEnv:process.env.NODE_ENV??"production",selectedModel:{name:jy},models:By,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=Gy();var sU={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 ed=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 pi=require("fs");var td="\x1B[31m",Hy="\x1B[33m",zy="\x1B[32m",Vy="\x1B[36m",qy="\x1B[2m",Wy="\x1B[1m",sr="\x1B[0m",Ky=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"),Jy=new Set(["severity","message","kind","timestamp","_startedAtMs"]),Zy=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"),Yy=o(t=>t==="ERROR"||t==="CRITICAL"?td:t==="WARNING"?Hy:zy,"colorForSeverity"),Xy=o(t=>{let e=String(t.severity??"INFO"),r=`${Yy(e)}${e.padEnd(5)}${sr}`,n=t.kind?`${Vy}${t.kind}${sr}`:"",a=String(t.message??""),i=t.error&&typeof t.error=="object"?(()=>{let p=t.error;return` ${td}${p.type??"Error"}: ${p.message??""}${sr}`})():"",s=["outcome","test_suite_run_id","status"],l=Object.entries(t).filter(([p,m])=>!Jy.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])=>`${qy}${p}=${sr}${m}`).join(" ");return[r,Wy+n+sr,a,u,i].filter(p=>p&&p.trim()!=="").join(" ")},"formatPretty"),Qy=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"),rd=o(t=>{let e=Ky()?Xy(t):Zy(Qy(t));(0,pi.writeSync)(1,e+`
|
|
58
|
+
`)},"emitEvent");var nd=o(t=>{(0,pi.writeSync)(2,t.endsWith(`
|
|
59
|
+
`)?t:`${t}
|
|
60
|
+
`)},"writeStderrLine");var eb=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"),tb=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"),rb=o((t={})=>{let e=t.decide??(()=>!0),r=t.deriveMessage??eb,n=t.label??"[wide-event]",a=t.sink??(l=>rd(l)),i=o(l=>{if(!e(l))return;let c={severity:ed(l),message:l.message??r(l),...l};try{a(c)}catch(u){try{nd(`${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={})=>tb(l,c,i),"wideEvent"),configureSink:o(l=>{a=l},"configureSink")}},"createWideEvents"),ad=o(t=>t==="true"||t==="1","truthy"),id=o(()=>ad(process.env.CHECKSUM_WIDE_EVENTS)||ad(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),sd=rb({decide:o(()=>id(),"decide")}),nb=sd.configureSink;var fi=o((t,e={})=>{sd.emitWideEvent(t,e)},"emitWideEvent");var ab="http://127.0.0.1";async function od(t,e){let r=e.fetchImpl??globalThis.fetch;try{return await(await r(`${ab}:${e.port}/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(e.timeoutMs)})).body?.cancel().catch(()=>{}),!0}catch(n){return e.onError?.(n),!1}}o(od,"postToMonitor");async function ld(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(ld,"settleWithin");var cd={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},cliHardCapMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CLI_HARD_CAP_MS",fallback:27e5,min:12e4,max:72e5},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},connectTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CONNECT_TIMEOUT_MS",fallback:1e4,min:1e3,max:6e4},headersTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_HEADERS_TIMEOUT_MS",fallback:6e4,min:5e3,max:6e5},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 ib(t,e,r,n){let a=parseInt(t??"",10);return Number.isFinite(a)?Math.min(n,Math.max(r,a)):e}o(ib,"clampInt");function mi(t){let e={};for(let r of Object.keys(cd)){let n=cd[r];e[r]=ib(t[n.env],n.fallback,n.min,n.max)}return e}o(mi,"resolveUploadTunables");var UU=mi({});var ud=2e3;function ob(t){switch(t){case"passed":return"passed";case"timedOut":return"timedOut";case"skipped":return"skipped";case"interrupted":return"interrupted";default:return"failed"}}o(ob,"toProgressStatus");var yn=class{constructor(){this.monitorPort=process.env.CHECKSUM_UPLOAD_AGENT_PORT;this.tunables=mi(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=ob(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";fi("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 ld(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,dd.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>=ud){this.lastFlushAt=Date.now(),this.send();return}this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.lastFlushAt=Date.now(),this.send()},ud-r))}send(){return this.monitorPort?(this.sendChain=this.sendChain.then(()=>this.postSnapshot()),this.sendChain):Promise.resolve()}async postSnapshot(){this.monitorPort&&await od({type:"runProgress",payload:this.snapshot()},{port:this.monitorPort,timeoutMs:this.tunables.ipcTimeoutMs})}guard(e){try{e()}catch{}}};
|
|
61
|
+
/*! Bundled license information:
|
|
62
|
+
|
|
63
|
+
@langchain/core/dist/utils/js-sha256/hash.js:
|
|
64
|
+
(**
|
|
65
|
+
* [js-sha256]{@link https://github.com/emn178/js-sha256}
|
|
66
|
+
*
|
|
67
|
+
* @version 0.11.1
|
|
68
|
+
* @author Chen, Yi-Cyuan [emn178@gmail.com]
|
|
69
|
+
* @copyright Chen, Yi-Cyuan 2014-2025
|
|
70
|
+
* @license MIT
|
|
71
|
+
*)
|
|
72
|
+
|
|
73
|
+
@langchain/core/dist/utils/fast-json-patch/src/helpers.js:
|
|
74
|
+
(*!
|
|
75
|
+
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
76
|
+
* (c) 2017-2022 Joachim Wester
|
|
77
|
+
* MIT licensed
|
|
78
|
+
*)
|
|
79
|
+
|
|
80
|
+
@langchain/core/dist/utils/fast-json-patch/src/duplex.js:
|
|
81
|
+
(*!
|
|
82
|
+
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
83
|
+
* (c) 2013-2021 Joachim Wester
|
|
84
|
+
* MIT license
|
|
85
|
+
*)
|
|
86
|
+
|
|
87
|
+
@langchain/core/dist/utils/sax-js/sax.js:
|
|
88
|
+
(*! http://mths.be/fromcodepoint v0.1.0 by @mathias *)
|
|
89
|
+
*/
|