@checksum-ai/runtime 4.14.0 → 4.16.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,189 @@
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
- `)},"emitEvent");var x=o(e=>{(0,y.writeSync)(2,e.endsWith(`
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 id=Object.create;var xr=Object.defineProperty;var ad=Object.getOwnPropertyDescriptor;var sd=Object.getOwnPropertyNames;var od=Object.getPrototypeOf,ld=Object.prototype.hasOwnProperty;var s=(t,e)=>xr(t,"name",{value:e,configurable:!0});var nt=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},cd=(t,e)=>{for(var r in e)xr(t,r,{get:e[r],enumerable:!0})},fs=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of sd(e))!ld.call(t,i)&&i!==r&&xr(t,i,{get:()=>e[i],enumerable:!(n=ad(e,i))||n.enumerable});return t};var it=(t,e,r)=>(r=t!=null?id(od(t)):{},fs(e||!t||!t.__esModule?xr(r,"default",{value:t,enumerable:!0}):r,t)),ud=t=>fs(xr({},"__esModule",{value:!0}),t);var uo=nt((Uw,_i)=>{"use strict";var Kd=Object.prototype.hasOwnProperty,_e="~";function Sr(){}s(Sr,"Events");Object.create&&(Sr.prototype=Object.create(null),new Sr().__proto__||(_e=!1));function Jd(t,e,r){this.fn=t,this.context=e,this.once=r||!1}s(Jd,"EE");function co(t,e,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var a=new Jd(r,n||t,i),o=_e?_e+e:e;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],a]:t._events[o].push(a):(t._events[o]=a,t._eventsCount++),t}s(co,"addListener");function an(t,e){--t._eventsCount===0?t._events=new Sr:delete t._events[e]}s(an,"clearEvent");function fe(){this._events=new Sr,this._eventsCount=0}s(fe,"EventEmitter");fe.prototype.eventNames=s(function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)Kd.call(r,n)&&e.push(_e?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e},"eventNames");fe.prototype.listeners=s(function(e){var r=_e?_e+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=new Array(a);i<a;i++)o[i]=n[i].fn;return o},"listeners");fe.prototype.listenerCount=s(function(e){var r=_e?_e+e:e,n=this._events[r];return n?n.fn?1:n.length:0},"listenerCount");fe.prototype.emit=s(function(e,r,n,i,a,o){var l=_e?_e+e:e;if(!this._events[l])return!1;var c=this._events[l],u=arguments.length,d,p;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,i),!0;case 5:return c.fn.call(c.context,r,n,i,a),!0;case 6:return c.fn.call(c.context,r,n,i,a,o),!0}for(p=1,d=new Array(u-1);p<u;p++)d[p-1]=arguments[p];c.fn.apply(c.context,d)}else{var h=c.length,g;for(p=0;p<h;p++)switch(c[p].once&&this.removeListener(e,c[p].fn,void 0,!0),u){case 1:c[p].fn.call(c[p].context);break;case 2:c[p].fn.call(c[p].context,r);break;case 3:c[p].fn.call(c[p].context,r,n);break;case 4:c[p].fn.call(c[p].context,r,n,i);break;default:if(!d)for(g=1,d=new Array(u-1);g<u;g++)d[g-1]=arguments[g];c[p].fn.apply(c[p].context,d)}}return!0},"emit");fe.prototype.on=s(function(e,r,n){return co(this,e,r,n,!1)},"on");fe.prototype.once=s(function(e,r,n){return co(this,e,r,n,!0)},"once");fe.prototype.removeListener=s(function(e,r,n,i){var a=_e?_e+e:e;if(!this._events[a])return this;if(!r)return an(this,a),this;var o=this._events[a];if(o.fn)o.fn===r&&(!i||o.once)&&(!n||o.context===n)&&an(this,a);else{for(var l=0,c=[],u=o.length;l<u;l++)(o[l].fn!==r||i&&!o[l].once||n&&o[l].context!==n)&&c.push(o[l]);c.length?this._events[a]=c.length===1?c[0]:c:an(this,a)}return this},"removeListener");fe.prototype.removeAllListeners=s(function(e){var r;return e?(r=_e?_e+e:e,this._events[r]&&an(this,r)):(this._events=new Sr,this._eventsCount=0),this},"removeAllListeners");fe.prototype.off=fe.prototype.removeListener;fe.prototype.addListener=fe.prototype.on;fe.prefixed=_e;fe.EventEmitter=fe;typeof _i<"u"&&(_i.exports=fe)});var fo=nt((jw,po)=>{"use strict";po.exports=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))});var ho=nt((Bw,on)=>{"use strict";var Zd=fo(),sn=class extends Error{static{s(this,"TimeoutError")}constructor(e){super(e),this.name="TimeoutError"}},mo=s((t,e,r)=>new Promise((n,i)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(t);return}let a=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(c){i(c)}return}let o=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,l=r instanceof Error?r:new sn(o);typeof t.cancel=="function"&&t.cancel(),i(l)},e);Zd(t.then(n,i),()=>{clearTimeout(a)})}),"pTimeout");on.exports=mo;on.exports.default=mo;on.exports.TimeoutError=sn});var go=nt(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});function Yd(t,e,r){let n=0,i=t.length;for(;i>0;){let a=i/2|0,o=n+a;r(t[o],e)<=0?(n=++o,i-=a+1):i=a}return n}s(Yd,"lowerBound");bi.default=Yd});var yo=nt(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});var Xd=go(),wi=class{static{s(this,"PriorityQueue")}constructor(){this._queue=[]}enqueue(e,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let i=Xd.default(this._queue,n,(a,o)=>o.priority-a.priority);this._queue.splice(i,0,n)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this._queue.length}};vi.default=wi});var cn=nt(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});var Qd=uo(),_o=ho(),ep=yo(),ln=s(()=>{},"empty"),tp=new _o.TimeoutError,xi=class extends Qd{static{s(this,"PQueue")}constructor(e){var r,n,i,a;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=ln,this._resolveIdle=ln,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:ep.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(a=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&a!==void 0?a:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=ln,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=ln,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let r=this._intervalEnd-e;if(r<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},r)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let r=this._queue.dequeue();return r?(this.emit("active"),r(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,r={}){return new Promise((n,i)=>{let a=s(async()=>{this._pendingCount++,this._intervalCount++;try{let o=this._timeout===void 0&&r.timeout===void 0?e():_o.default(Promise.resolve(e()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&i(tp)});n(await o)}catch(o){i(o)}this._next()},"run");this._queue.enqueue(a,r),this._tryToStartAnother(),this.emit("add")})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let r=this._resolveEmpty;this._resolveEmpty=()=>{r(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let r=this._resolveIdle;this._resolveIdle=()=>{r(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};Ei.default=xi});var Su=nt(ti=>{"use strict";ti.byteLength=Wh;ti.toByteArray=Jh;ti.fromByteArray=Xh;var qe=[],Oe=[],qh=typeof Uint8Array<"u"?Uint8Array:Array,Ya="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Vt=0,xu=Ya.length;Vt<xu;++Vt)qe[Vt]=Ya[Vt],Oe[Ya.charCodeAt(Vt)]=Vt;var Vt,xu;Oe[45]=62;Oe[95]=63;function Eu(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}s(Eu,"getLens");function Wh(t){var e=Eu(t),r=e[0],n=e[1];return(r+n)*3/4-n}s(Wh,"byteLength");function Kh(t,e,r){return(e+r)*3/4-r}s(Kh,"_byteLength");function Jh(t){var e,r=Eu(t),n=r[0],i=r[1],a=new qh(Kh(t,n,i)),o=0,l=i>0?n-4:n,c;for(c=0;c<l;c+=4)e=Oe[t.charCodeAt(c)]<<18|Oe[t.charCodeAt(c+1)]<<12|Oe[t.charCodeAt(c+2)]<<6|Oe[t.charCodeAt(c+3)],a[o++]=e>>16&255,a[o++]=e>>8&255,a[o++]=e&255;return i===2&&(e=Oe[t.charCodeAt(c)]<<2|Oe[t.charCodeAt(c+1)]>>4,a[o++]=e&255),i===1&&(e=Oe[t.charCodeAt(c)]<<10|Oe[t.charCodeAt(c+1)]<<4|Oe[t.charCodeAt(c+2)]>>2,a[o++]=e>>8&255,a[o++]=e&255),a}s(Jh,"toByteArray");function Zh(t){return qe[t>>18&63]+qe[t>>12&63]+qe[t>>6&63]+qe[t&63]}s(Zh,"tripletToBase64");function Yh(t,e,r){for(var n,i=[],a=e;a<r;a+=3)n=(t[a]<<16&16711680)+(t[a+1]<<8&65280)+(t[a+2]&255),i.push(Zh(n));return i.join("")}s(Yh,"encodeChunk");function Xh(t){for(var e,r=t.length,n=r%3,i=[],a=16383,o=0,l=r-n;o<l;o+=a)i.push(Yh(t,o,o+a>l?l:o+a));return n===1?(e=t[r-1],i.push(qe[e>>2]+qe[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(qe[e>>10]+qe[e>>4&63]+qe[e<<2&63]+"=")),i.join("")}s(Xh,"fromByteArray")});var Bu=nt(($j,et)=>{var is=require("fs"),ni=require("path"),xg=require("os"),Eg=require("crypto"),$u=["\u25C8 encrypted .env [www.dotenvx.com]","\u25C8 secrets for agents [www.dotenvx.com]","\u2301 auth for agents [www.vestauth.com]","\u2318 custom filepath { path: '/custom/path/.env' }","\u2318 enable debugging { debug: true }","\u2318 override existing { override: true }","\u2318 suppress logs { quiet: true }","\u2318 multiple files { path: ['.env.local', '.env'] }"];function Sg(){return $u[Math.floor(Math.random()*$u.length)]}s(Sg,"_getRandomTip");function wr(t){return typeof t=="string"?!["false","0","no","off",""].includes(t.toLowerCase()):!!t}s(wr,"parseBoolean");function Tg(){return process.stdout.isTTY}s(Tg,"supportsAnsi");function Ag(t){return Tg()?`\x1B[2m${t}\x1B[0m`:t}s(Ag,"dim");var Ig=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Cg(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
2
+ `);let n;for(;(n=Ig.exec(r))!=null;){let i=n[1],a=n[2]||"";a=a.trim();let o=a[0];a=a.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),o==='"'&&(a=a.replace(/\\n/g,`
3
+ `),a=a.replace(/\\r/g,"\r")),e[i]=a}return e}s(Cg,"parse");function kg(t){t=t||{};let e=ju(t);t.path=e;let r=ne.configDotenv(t);if(!r.parsed){let o=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw o.code="MISSING_DATA",o}let n=Fu(t).split(","),i=n.length,a;for(let o=0;o<i;o++)try{let l=n[o].trim(),c=Pg(r,l);a=ne.decrypt(c.ciphertext,c.key);break}catch(l){if(o+1>=i)throw l}return ne.parse(a)}s(kg,"_parseVault");function Og(t){console.error(`\u26A0 ${t}`)}s(Og,"_warn");function Vr(t){console.log(`\u2506 ${t}`)}s(Vr,"_debug");function Uu(t){console.log(`\u25C7 ${t}`)}s(Uu,"_log");function Fu(t){return t&&t.DOTENV_KEY&&t.DOTENV_KEY.length>0?t.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}s(Fu,"_dotenvKey");function Pg(t,e){let r;try{r=new URL(e)}catch(l){if(l.code==="ERR_INVALID_URL"){let c=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw c.code="INVALID_DOTENV_KEY",c}throw l}let n=r.password;if(!n){let l=new Error("INVALID_DOTENV_KEY: Missing key part");throw l.code="INVALID_DOTENV_KEY",l}let i=r.searchParams.get("environment");if(!i){let l=new Error("INVALID_DOTENV_KEY: Missing environment part");throw l.code="INVALID_DOTENV_KEY",l}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=t.parsed[a];if(!o){let l=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw l.code="NOT_FOUND_DOTENV_ENVIRONMENT",l}return{ciphertext:o,key:n}}s(Pg,"_instructions");function ju(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)is.existsSync(r)&&(e=r.endsWith(".vault")?r:`${r}.vault`);else e=t.path.endsWith(".vault")?t.path:`${t.path}.vault`;else e=ni.resolve(process.cwd(),".env.vault");return is.existsSync(e)?e:null}s(ju,"_vaultPath");function Du(t){return t[0]==="~"?ni.join(xg.homedir(),t.slice(1)):t}s(Du,"_resolveHome");function Rg(t){let e=wr(process.env.DOTENV_CONFIG_DEBUG||t&&t.debug),r=wr(process.env.DOTENV_CONFIG_QUIET||t&&t.quiet);(e||!r)&&Uu("loading env from encrypted .env.vault");let n=ne._parseVault(t),i=process.env;return t&&t.processEnv!=null&&(i=t.processEnv),ne.populate(i,n,t),{parsed:n}}s(Rg,"_configVault");function Mg(t){let e=ni.resolve(process.cwd(),".env"),r="utf8",n=process.env;t&&t.processEnv!=null&&(n=t.processEnv);let i=wr(n.DOTENV_CONFIG_DEBUG||t&&t.debug),a=wr(n.DOTENV_CONFIG_QUIET||t&&t.quiet);t&&t.encoding?r=t.encoding:i&&Vr("no encoding is specified (UTF-8 is used by default)");let o=[e];if(t&&t.path)if(!Array.isArray(t.path))o=[Du(t.path)];else{o=[];for(let d of t.path)o.push(Du(d))}let l,c={};for(let d of o)try{let p=ne.parse(is.readFileSync(d,{encoding:r}));ne.populate(c,p,t)}catch(p){i&&Vr(`failed to load ${d} ${p.message}`),l=p}let u=ne.populate(n,c,t);if(i=wr(n.DOTENV_CONFIG_DEBUG||i),a=wr(n.DOTENV_CONFIG_QUIET||a),i||!a){let d=Object.keys(u).length,p=[];for(let h of o)try{let g=ni.relative(process.cwd(),h);p.push(g)}catch(g){i&&Vr(`failed to load ${h} ${g.message}`),l=g}Uu(`injected env (${d}) from ${p.join(",")} ${Ag(`// tip: ${Sg()}`)}`)}return l?{parsed:c,error:l}:{parsed:c}}s(Mg,"configDotenv");function Ng(t){if(Fu(t).length===0)return ne.configDotenv(t);let e=ju(t);return e?ne._configVault(t):(Og(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),ne.configDotenv(t))}s(Ng,"config");function Lg(t,e){let r=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(t,"base64"),i=n.subarray(0,12),a=n.subarray(-16);n=n.subarray(12,-16);try{let o=Eg.createDecipheriv("aes-256-gcm",r,i);return o.setAuthTag(a),`${o.update(n)}${o.final()}`}catch(o){let l=o instanceof RangeError,c=o.message==="Invalid key length",u=o.message==="Unsupported state or unable to authenticate data";if(l||c){let d=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw d.code="INVALID_DOTENV_KEY",d}else if(u){let d=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw d.code="DECRYPTION_FAILED",d}else throw o}}s(Lg,"decrypt");function $g(t,e,r={}){let n=!!(r&&r.debug),i=!!(r&&r.override),a={};if(typeof e!="object"){let o=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw o.code="OBJECT_REQUIRED",o}for(let o of Object.keys(e))Object.prototype.hasOwnProperty.call(t,o)?(i===!0&&(t[o]=e[o],a[o]=e[o]),n&&Vr(i===!0?`"${o}" is already defined and WAS overwritten`:`"${o}" is already defined and was NOT overwritten`)):(t[o]=e[o],a[o]=e[o]);return a}s($g,"populate");var ne={configDotenv:Mg,_configVault:Rg,_parseVault:kg,config:Ng,decrypt:Lg,parse:Cg,populate:$g};et.exports.configDotenv=ne.configDotenv;et.exports._configVault=ne._configVault;et.exports._parseVault=ne._parseVault;et.exports.config=ne.config;et.exports.decrypt=ne.decrypt;et.exports.parse=ne.parse;et.exports.populate=ne.populate;et.exports=ne});var ly={};cd(ly,{default:()=>ai});module.exports=ud(ly);var ed=require("path");var Yj=require("@playwright/test");var gj=require("@playwright/test");var jy=require("@playwright/test");var $y=require("@playwright/test");var ms=Object.defineProperty,H=s((t,e)=>{let r={};for(var n in t)ms(r,n,{get:t[n],enumerable:!0});return e||ms(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll");function hs(t){let e=Symbol.for(t);return{brand(r,n){let i=n?Symbol.for(`${t}.${n}`):e;class a extends r{static{s(this,"_Branded")}[i]=!0;constructor(...l){super(...l)}static isInstance(l){return typeof l=="object"&&l!==null&&i in l&&l[i]===!0}}return Object.defineProperty(a,"name",{value:r.name}),a},sub(r){return hs(`${t}.${r}`)},isInstance(r){return typeof r=="object"&&r!==null&&e in r&&r[e]===!0}}}s(hs,"createNamespace");var gs=hs("langchain");var ui=gs.sub("error"),ys=class extends ui.brand(Error){static{s(this,"LangChainError")}name="LangChainError";constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},dd=class extends ui.brand(ys,"model-abort"){static{s(this,"ModelAbortError")}name="ModelAbortError";partialOutput;constructor(t,e){super(t),this.partialOutput=e}},Zy=class _s extends ui.brand(ys,"context-overflow"){static{s(this,"ContextOverflowError")}name="ContextOverflowError";cause;constructor(e){super(e??"Input exceeded the model's context window.")}static fromError(e){let r=new _s(e.message);return r.cause=e,r}};var pd=/([A-Z]+)([A-Z][a-z0-9]+)/g,fd=/([a-z0-9])([A-Z])/g,md=/[-_\s]+/g;function hd(t){return t.replace(pd,"$1_$2").replace(fd,"$1_$2").replace(md,"_").toLowerCase()}s(hd,"snakeCase");function bs(t,e){return e?.[t]||hd(t)}s(bs,"keyToJson");function ws(t,e,r){let n={};for(let i in t)Object.hasOwn(t,i)&&(n[e(i,r)]=t[i]);return n}s(ws,"mapKeys");var gd="__lc_escaped__";function yd(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}s(yd,"needsEscaping");function _d(t){return{[gd]:t}}s(_d,"escapeObject");function bd(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}s(bd,"isSerializableLike");function wd(t){let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[t.constructor?.name??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}s(wd,"createNotImplemented");function Wr(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return wd(t);if(bd(t))return t;e.add(t);let r=t;if(yd(r))return e.delete(t),_d(r);let n={};for(let[i,a]of Object.entries(r))n[i]=Wr(a,e);return e.delete(t),n}return Array.isArray(t)?t.map(r=>Wr(r,e)):t}s(Wr,"escapeIfNeeded");function vs(t){return Array.isArray(t)?[...t]:{...t}}s(vs,"shallowCopy");function vd(t,e){let r=vs(t);for(let[n,i]of Object.entries(e)){let[a,...o]=n.split(".").reverse(),l=r;for(let c of o.reverse()){if(l[c]===void 0)break;l[c]=vs(l[c]),l=l[c]}l[a]!==void 0&&(l[a]={lc:1,type:"secret",id:[i]})}return r}s(vd,"replaceSecrets");function di(t){let e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}s(di,"get_lc_unique_name");var wt=class xs{static{s(this,"Serializable")}lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,di(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...r){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof xs||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},r={},n=Object.keys(this.lc_kwargs).reduce((l,c)=>(l[c]=c in this?this[c]:this.lc_kwargs[c],l),{});for(let l=Object.getPrototypeOf(this);l;l=Object.getPrototypeOf(l))Object.assign(e,Reflect.get(l,"lc_aliases",this)),Object.assign(r,Reflect.get(l,"lc_secrets",this)),Object.assign(n,Reflect.get(l,"lc_attributes",this));Object.keys(r).forEach(l=>{let c=this,u=n,[d,...p]=l.split(".").reverse();for(let h of p.reverse()){if(!(h in c)||c[h]===void 0)return;(!(h in u)||u[h]===void 0)&&(typeof c[h]=="object"&&c[h]!=null?u[h]={}:Array.isArray(c[h])&&(u[h]=[])),c=c[h],u=u[h]}d in c&&c[d]!==void 0&&(u[d]=u[d]||c[d])});let i={},a=new WeakSet;a.add(this);for(let[l,c]of Object.entries(n))i[l]=Wr(c,a);let o=ws(Object.keys(r).length?vd(i,r):i,bs,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:o}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function Er(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}s(Er,"isDataContentBlock");function Kr(t){return Er(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}s(Kr,"isURLContentBlock");function Jr(t){return Er(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}s(Jr,"isBase64ContentBlock");function pi(t){return Er(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}s(pi,"isIDContentBlock");function Zr({dataUrl:t,asTypedArray:e=!1}){let r=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(r){n=r[1].toLowerCase();let i=e?Uint8Array.from(atob(r[2]),a=>a.charCodeAt(0)):r[2];return{mime_type:n,data:i}}}s(Zr,"parseBase64DataUrl");function T(t,e){return M(t)&&t.type===e}s(T,"_isContentBlock");function M(t){return typeof t=="object"&&t!==null}s(M,"_isObject");function te(t){return Array.isArray(t)}s(te,"_isArray");function w(t){return typeof t=="string"}s(w,"_isString");function Ae(t){return typeof t=="number"}s(Ae,"_isNumber");function Yr(t){return t instanceof Uint8Array}s(Yr,"_isBytesArray");function fi(t){try{return JSON.parse(t)}catch{return}}s(fi,"safeParseJson");var Ie=s(t=>t(),"iife");function xd(t){if(t.type==="char_location"&&w(t.document_title)&&Ae(t.start_char_index)&&Ae(t.end_char_index)&&w(t.cited_text)){let{document_title:e,start_char_index:r,end_char_index:n,cited_text:i,...a}=t;return{...a,type:"citation",source:"char",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="page_location"&&w(t.document_title)&&Ae(t.start_page_number)&&Ae(t.end_page_number)&&w(t.cited_text)){let{document_title:e,start_page_number:r,end_page_number:n,cited_text:i,...a}=t;return{...a,type:"citation",source:"page",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="content_block_location"&&w(t.document_title)&&Ae(t.start_block_index)&&Ae(t.end_block_index)&&w(t.cited_text)){let{document_title:e,start_block_index:r,end_block_index:n,cited_text:i,...a}=t;return{...a,type:"citation",source:"block",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="web_search_result_location"&&w(t.url)&&w(t.title)&&w(t.encrypted_index)&&w(t.cited_text)){let{url:e,title:r,encrypted_index:n,cited_text:i,...a}=t;return{...a,type:"citation",source:"url",url:e,title:r,startIndex:Number(n),endIndex:Number(n),citedText:i}}if(t.type==="search_result_location"&&w(t.source)&&w(t.title)&&Ae(t.start_block_index)&&Ae(t.end_block_index)&&w(t.cited_text)){let{source:e,title:r,start_block_index:n,end_block_index:i,cited_text:a,...o}=t;return{...o,type:"citation",source:"search",url:e,title:r??void 0,startIndex:n,endIndex:i,citedText:a}}}s(xd,"convertAnthropicAnnotation");function Ss(t){if(T(t,"document")&&M(t.source)&&"type"in t.source){if(t.source.type==="base64"&&w(t.source.media_type)&&w(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&w(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&w(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&w(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(T(t,"image")&&M(t.source)&&"type"in t.source){if(t.source.type==="base64"&&w(t.source.media_type)&&w(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&w(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&w(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}s(Ss,"convertToV1FromAnthropicContentBlock");function Ts(t){function*e(){for(let r of t){let n=Ss(r);n?yield n:yield r}}return s(e,"iterateContent"),Array.from(e())}s(Ts,"convertToV1FromAnthropicInput");function Es(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(T(n,"text")&&w(n.text)){let{text:i,citations:a,...o}=n;if(te(a)&&a.length){let l=a.reduce((c,u)=>{let d=xd(u);return d?[...c,d]:c},[]);yield{...o,type:"text",text:i,annotations:l};continue}else{yield{...o,type:"text",text:i};continue}}else if(T(n,"thinking")&&w(n.thinking)){let{thinking:i,signature:a,...o}=n;yield{...o,type:"reasoning",reasoning:i,signature:a};continue}else if(T(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(T(n,"tool_use")&&w(n.name)&&w(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(T(n,"input_json_delta")){if(Ed(t)&&t.tool_call_chunks?.length){let i=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:i.id,name:i.name,args:i.args,index:i.index};continue}}else if(T(n,"server_tool_use")&&w(n.name)&&w(n.id)){let{name:i,id:a}=n;if(i==="web_search"){yield{id:a,type:"server_tool_call",name:"web_search",args:{query:Ie(()=>{if(typeof n.input=="string")return n.input;if(M(n.input)&&w(n.input.query))return n.input.query;if(w(n.partial_json)){let o=fi(n.partial_json);if(o?.query)return o.query}return""})}};continue}else if(n.name==="code_execution"){yield{id:a,type:"server_tool_call",name:"code_execution",args:{code:Ie(()=>{if(typeof n.input=="string")return n.input;if(M(n.input)&&w(n.input.code))return n.input.code;if(w(n.partial_json)){let o=fi(n.partial_json);if(o?.code)return o.code}return""})}};continue}}else if(T(n,"web_search_tool_result")&&w(n.tool_use_id)&&te(n.content)){let{content:i,tool_use_id:a}=n;yield{type:"server_tool_call_result",name:"web_search",toolCallId:a,status:"success",output:{urls:i.reduce((o,l)=>T(l,"web_search_result")?[...o,l.url]:o,[])}};continue}else if(T(n,"code_execution_tool_result")&&w(n.tool_use_id)&&M(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(T(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(T(n,"mcp_tool_result")&&w(n.tool_use_id)&&M(n.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(T(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(T(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(T(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}else{let i=Ss(n);if(i){yield i;continue}}yield{type:"non_standard",value:n}}}return s(e,"iterateContent"),Array.from(e())}s(Es,"convertToV1FromAnthropicMessage");var As={translateContent:Es,translateContentChunk:Es};function Ed(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}s(Ed,"_isAIMessageChunk");function Sd(t){return Kr(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:Jr(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:pi(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}s(Sd,"convertToV1FromDataContentBlock");function Is(t){return t.map(Sd)}s(Is,"convertToV1FromDataContent");function Cs(t){return!!(T(t,"image_url")&&M(t.image_url)||T(t,"input_audio")&&M(t.input_audio)||T(t,"file")&&M(t.file))}s(Cs,"isOpenAIDataBlock");function ks(t){if(T(t,"image_url")&&M(t.image_url)&&w(t.image_url.url)){let e=Zr({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(T(t,"input_audio")&&M(t.input_audio)&&w(t.input_audio.data)&&w(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(T(t,"file")&&M(t.file)&&w(t.file.data)){let e=Zr({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(w(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}s(ks,"convertToV1FromOpenAIDataBlock");function Td(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Xr(t.content));for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}s(Td,"convertToV1FromChatCompletions");function Ad(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Xr(t.content));for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}s(Ad,"convertToV1FromChatCompletionsChunk");function Xr(t){let e=[];for(let r of t)Cs(r)?e.push(ks(r)):e.push(r);return e}s(Xr,"convertToV1FromChatCompletionsInput");function Id(t){if(t.type==="url_citation"){let{url:e,title:r,start_index:n,end_index:i}=t;return{type:"citation",url:e,title:r,startIndex:n,endIndex:i}}if(t.type==="file_citation"){let{file_id:e,filename:r,index:n}=t;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:e}}return t}s(Id,"convertResponsesAnnotation");function Os(t){function*e(){M(t.additional_kwargs?.reasoning)&&te(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((n,i)=>M(i)&&w(i.text)?`${n}${i.text}`:n,"")});let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r)if(T(n,"text")){let{text:i,annotations:a,phase:o,extras:l,...c}=n,u=M(l)?{...l}:{};w(o)&&(u.phase=o);let d=Object.keys(u).length>0?{extras:u}:{};Array.isArray(a)?yield{...c,...d,type:"text",text:String(i),annotations:a.map(Id)}:yield{...c,...d,type:"text",text:String(i)}}for(let n of t.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if(M(t.additional_kwargs)&&te(t.additional_kwargs.tool_outputs))for(let n of t.additional_kwargs.tool_outputs){if(T(n,"web_search_call")){let i={};if(M(n.action)&&w(n.action.query)&&(i.query=n.action.query),yield{id:n.id,type:"server_tool_call",name:"web_search",args:i},n.status==="completed"||n.status==="failed"){let a={};M(n.action)&&(a.action=n.action),yield{type:"server_tool_call_result",toolCallId:w(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:a}}continue}else if(T(n,"file_search_call")){yield{id:n.id,type:"server_tool_call",name:"file_search",args:{queries:te(n.queries)?n.queries:[]}},(n.status==="completed"||n.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:w(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:te(n.results)?{results:n.results}:{}});continue}else if(T(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(T(n,"code_interpreter_call")){if(w(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),te(n.outputs)){let i=Ie(()=>{if(n.status!=="in_progress"){if(n.status==="completed")return 0;if(n.status==="incomplete")return 127;if(n.status!=="interpreting"&&n.status==="failed")return 1}});for(let a of n.outputs)if(T(a,"logs")){yield{type:"server_tool_call_result",toolCallId:n.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:i??0,stderr:[0,void 0].includes(i)?void 0:String(a.logs),stdout:[0,void 0].includes(i)?String(a.logs):void 0}};continue}}continue}else if(T(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(T(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(T(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(T(n,"tool_search_call")){let i={};M(n.arguments)&&Object.assign(i,n.arguments);let a={};w(n.execution)&&(a.execution=n.execution),w(n.status)&&(a.status=n.status),w(n.call_id)&&(a.call_id=n.call_id),yield{id:w(n.id)?n.id:"",type:"server_tool_call",name:"tool_search",args:i,...Object.keys(a).length>0?{extras:a}:{}};continue}else if(T(n,"tool_search_output")){let i={name:"tool_search"};w(n.execution)&&(i.execution=n.execution),yield{type:"server_tool_call_result",toolCallId:w(n.id)?n.id:"",status:n.status==="completed"?"success":n.status==="failed"?"error":"success",output:{tools:te(n.tools)?n.tools:[]},extras:i};continue}else if(T(n,"image_generation_call")){w(n.result)&&(yield{type:"image",mimeType:"image/png",data:n.result,id:w(n.id)?n.id:void 0,metadata:{status:w(n.status)?n.status:void 0}}),yield{type:"non_standard",value:n};continue}M(n)&&(yield{type:"non_standard",value:n})}}return s(e,"iterateContent"),Array.from(e())}s(Os,"convertToV1FromResponses");function Cd(t){function*e(){yield*Os(t);for(let r of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return s(e,"iterateContent"),Array.from(e())}s(Cd,"convertToV1FromResponsesChunk");var Ps={translateContent:s(t=>typeof t.content=="string"?Td(t):Os(t),"translateContent"),translateContentChunk:s(t=>typeof t.content=="string"?Ad(t):Cd(t),"translateContentChunk")};function mi(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}s(mi,"isMessage");function Rs(t,e="pretty"){return e==="pretty"?kd(t):JSON.stringify(t)}s(Rs,"convertToFormattedString");function kd(t){let e=[],r=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),i="=".repeat(n),a=r.length%2===0?i:`${i}=`;if(e.push(`${i}${r}${a}`),t.type==="ai"){let o=t;if(o.tool_calls&&o.tool_calls.length>0){e.push("Tool Calls:");for(let l of o.tool_calls){e.push(` ${l.name} (${l.id})`),e.push(` Call ID: ${l.id}`),e.push(" Args:");for(let[c,u]of Object.entries(l.args))e.push(` ${c}: ${typeof u=="object"?JSON.stringify(u):u}`)}}}if(t.type==="tool"){let o=t;o.name&&e.push(`Name: ${o.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
4
+ `)}s(kd,"convertToPrettyString");var hi=Symbol.for("langchain.message");function Od(t,e){function r(n,i){if(typeof n!="object"||n===null||n===void 0)return n;if(i>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(o=>r(o,i+1));let a={};for(let o of Object.keys(n))a[o]=r(n[o],i+1);return a}return s(r,"helper"),JSON.stringify(r(t,0),null,2)}s(Od,"stringifyWithDepthLimit");var We=class extends wt{static{s(this,"BaseMessage")}lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[hi]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(t){let e=typeof t=="string"||Array.isArray(t)?{content:t}:t;e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),this.name=e.name,e.content===void 0&&e.contentBlocks!==void 0?(this.content=e.contentBlocks,this.response_metadata={output_version:"v1",...e.response_metadata}):e.content!==void 0?(this.content=e.content??[],this.response_metadata=e.response_metadata):(this.content=[],this.response_metadata=e.response_metadata),this.additional_kwargs=e.additional_kwargs,this.id=e.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(t=>typeof t=="string"?t:t.type==="text"?t.text:"").join(""):""}get contentBlocks(){let t=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[Is,Xr,Ts].reduce((e,r)=>r(e),t)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(t){return typeof t=="object"&&t!==null&&hi in t&&t[hi]===!0&&mi(t)}_updateId(t){this.id=t,this.lc_kwargs.id=t}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](t){if(t===null)return this;let e=Od(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return Rs(this,t)}};function gi(t){let e=[],r=[];for(let n of t)if(n.function){let i=n.function.name;try{let a=JSON.parse(n.function.arguments);e.push({name:i||"",args:a||{},id:n.id})}catch{r.push({name:i,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}s(gi,"defaultToolCallParser");function yi(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}s(yi,"convertFileFormatToMimeType");function Md(t){if(M(t.document)&&M(t.document.source)){let e=yi(M(t.document)&&w(t.document.format)?t.document.format:"");if(M(t.document.source)){if(M(t.document.source.s3Location)&&w(t.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:t.document.source.s3Location.uri};if(Yr(t.document.source.bytes))return{type:"file",mimeType:e,data:t.document.source.bytes};if(w(t.document.source.text))return{type:"file",mimeType:e,data:Buffer.from(t.document.source.text).toString("base64")};if(te(t.document.source.content))return{type:"file",mimeType:e,data:t.document.source.content.reduce((r,n)=>M(n)&&w(n.text)?r+n.text:r,"")}}}return{type:"non_standard",value:t}}s(Md,"convertConverseDocumentBlock");function Nd(t){if(T(t,"image")&&M(t.image)){let e=yi(M(t.image)&&w(t.image.format)?t.image.format:"");if(M(t.image.source)){if(M(t.image.source.s3Location)&&w(t.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:t.image.source.s3Location.uri};if(Yr(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}s(Nd,"convertConverseImageBlock");function Ld(t){if(T(t,"video")&&M(t.video)){let e=yi(M(t.video)&&w(t.video.format)?t.video.format:"");if(M(t.video.source)){if(M(t.video.source.s3Location)&&w(t.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:t.video.source.s3Location.uri};if(Yr(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}s(Ld,"convertConverseVideoBlock");function Ms(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(T(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(T(n,"citations_content")&&M(n.citationsContent)){yield{type:"text",text:te(n.citationsContent.content)?n.citationsContent.content.reduce((i,a)=>M(a)&&w(a.text)?i+a.text:i,""):"",annotations:te(n.citationsContent.citations)?n.citationsContent.citations.reduce((i,a)=>{if(M(a)){let o=te(a.sourceContent)?a.sourceContent.reduce((c,u)=>M(u)&&w(u.text)?c+u.text:c,""):"",l=Ie(()=>{if(M(a.location)){let c=a.location.documentChar||a.location.documentPage||a.location.documentChunk;if(M(c))return{source:Ae(c.documentIndex)?c.documentIndex.toString():void 0,startIndex:Ae(c.start)?c.start:void 0,endIndex:Ae(c.end)?c.end:void 0}}return{}});i.push({type:"citation",citedText:o,...l})}return i},[]):[]};continue}else if(T(n,"document")&&M(n.document)){yield Md(n);continue}else if(T(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(T(n,"image")&&M(n.image)){yield Nd(n);continue}else if(T(n,"reasoning_content")&&w(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(T(n,"text")&&w(n.text)){yield{type:"text",text:n.text};continue}else if(T(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(T(n,"tool_call"))continue;if(T(n,"video")&&M(n.video)){yield Ld(n);continue}}yield{type:"non_standard",value:n}}}return s(e,"iterateContent"),Array.from(e())}s(Ms,"convertToV1FromChatBedrockConverseMessage");var Ns={translateContent:Ms,translateContentChunk:Ms};function Ls(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(w(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&w(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}s(Ls,"convertToV1FromDeepSeekMessage");var $s={translateContent:Ls,translateContentChunk:Ls};function Ds(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(T(n,"text")&&w(n.text)){yield{type:"text",text:n.text};continue}else if(T(n,"thinking")&&w(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(T(n,"inlineData")&&M(n.inlineData)&&w(n.inlineData.mimeType)&&w(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(T(n,"functionCall")&&M(n.functionCall)&&w(n.functionCall.name)&&M(n.functionCall.args)){yield{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(T(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(T(n,"fileData")&&M(n.fileData)&&w(n.fileData.mimeType)&&w(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(T(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(T(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return s(e,"iterateContent"),Array.from(e())}s(Ds,"convertToV1FromChatGoogleMessage");var Us={translateContent:Ds,translateContentChunk:Ds};function Fs(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(T(n,"reasoning")&&w(n.reasoning)){let i=Ie(()=>{let a=r.indexOf(n);if(te(t.additional_kwargs?.signatures)&&a>=0)return t.additional_kwargs.signatures.at(a)});w(i)?yield{type:"reasoning",reasoning:n.reasoning,signature:i}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(T(n,"thinking")&&w(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(T(n,"text")&&w(n.text)){yield{type:"text",text:n.text};continue}else if(T(n,"image_url")){if(w(n.image_url))if(n.image_url.startsWith("data:")){let i=n.image_url.match(/^data:([^;]+);base64,(.+)$/);i?yield{type:"image",data:i[2],mimeType:i[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(T(n,"media")&&w(n.mimeType)&&w(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return s(e,"iterateContent"),Array.from(e())}s(Fs,"convertToV1FromChatVertexMessage");var js={translateContent:Fs,translateContentChunk:Fs};function Bs(t){let e=[],r=t.additional_kwargs?.reasoning;if(w(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string"){let n=t.content,i=n.match(/<think>([\s\S]*?)<\/think>/);if(i){let a=i[1].trim();a.length>0&&e.push({type:"reasoning",reasoning:a}),n=n.replace(/<think>[\s\S]*?<\/think>/,"").trim()}n.length>0&&e.push({type:"text",text:n})}else for(let n of t.content)if(typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&w(n.text)){let i=n.text,a=i.match(/<think>([\s\S]*?)<\/think>/);if(a){let o=a[1].trim();o.length>0&&e.push({type:"reasoning",reasoning:o}),i=i.replace(/<think>[\s\S]*?<\/think>/,"").trim()}i.length>0&&e.push({type:"text",text:i})}for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}s(Bs,"convertToV1FromGroqMessage");var Hs={translateContent:Bs,translateContentChunk:Bs};function zs(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(w(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&w(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}s(zs,"convertToV1FromOllamaMessage");var Gs={translateContent:zs,translateContentChunk:zs};function Vs(t){let e=[],r=t.additional_kwargs?.reasoning_details,n=!1;if(Array.isArray(r)&&r.length>0)for(let i of r){if(i==null||typeof i!="object")continue;let a=i.type;if(a==="reasoning.summary"){let o=i.summary;w(o)&&o.length>0&&(e.push({type:"reasoning",reasoning:o}),n=!0)}else if(a==="reasoning.text"){let o=i.text;w(o)&&o.length>0&&(e.push({type:"reasoning",reasoning:o}),n=!0)}}if(!n){let i=t.additional_kwargs?.reasoning_content;w(i)&&i.length>0&&e.push({type:"reasoning",reasoning:i})}if(typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let i of t.content)typeof i=="object"&&"type"in i&&i.type==="text"&&"text"in i&&w(i.text)&&e.push({type:"text",text:i.text});for(let i of t.tool_calls??[])e.push({type:"tool_call",id:i.id,name:i.name,args:i.args});return e}s(Vs,"convertToV1FromOpenRouterMessage");var qs={translateContent:Vs,translateContentChunk:Vs};function Ws(t){let e=[];if(M(t.additional_kwargs?.reasoning)){let n=t.additional_kwargs.reasoning;if(te(n.summary)){let i=n.summary.reduce((a,o)=>M(o)&&w(o.text)?`${a}${o.text}`:a,"");i.length>0&&e.push({type:"reasoning",reasoning:i})}}let r=t.additional_kwargs?.reasoning_content;if(w(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&w(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}s(Ws,"convertToV1FromXAIMessage");var Ks={translateContent:Ws,translateContentChunk:Ws};function Js(t){function*e(){let r=Ie(()=>{if(typeof t.content=="string")return t.additional_kwargs.originalTextContentBlock?[{...t.additional_kwargs.originalTextContentBlock,type:"text"}]:[{type:"text",text:t.content}];{let n=t.additional_kwargs?.originalTextContentBlock;if(n?.thoughtSignature&&!t.content.some(i=>"thoughtSignature"in i)){let i=[...t.content];for(let a=i.length-1;a>=0;a--){let o=i[a];if(o.type==="text"&&!o.thought)return o.thoughtSignature=n.thoughtSignature,i}}return t.content}});for(let n of r){let i=Ie(()=>T(n,"text")&&w(n.text)?{type:"text",text:n.text}:T(n,"inlineData")&&M(n.inlineData)&&w(n.inlineData.mimeType)&&w(n.inlineData.data)?{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data}:T(n,"functionCall")&&M(n.functionCall)&&w(n.functionCall.name)&&M(n.functionCall.args)?{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args}:T(n,"functionResponse")?{type:"non_standard",value:n}:T(n,"fileData")&&M(n.fileData)&&w(n.fileData.mimeType)&&w(n.fileData.fileUri)?{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri}:T(n,"executableCode")?{type:"non_standard",value:n}:T(n,"codeExecutionResult")?{type:"non_standard",value:n}:{type:"non_standard",value:n}),a=Ie(()=>"thought"in n&&n.thought?{type:"reasoning",reasoning:i.type==="text"?i.text:"",reasoningContentBlock:i}:i),o={thought:n.thought,thoughtSignature:n.thoughtSignature,partMetadata:n.partMetadata,...a};for(let l in o)o[l]===void 0&&delete o[l];yield o}}return s(e,"iterateContent"),Array.from(e())}s(Js,"convertToV1FromChatGoogleMessage");var Zs={translateContent:Js,translateContentChunk:Js};globalThis.lc_block_translators_registry??=new Map([["anthropic",As],["bedrock-converse",Ns],["deepseek",$s],["google",Zs],["google-genai",Us],["google-vertexai",js],["groq",Hs],["ollama",Gs],["openai",Ps],["openrouter",qs],["xai",Ks]]);function Ys(t){return globalThis.lc_block_translators_registry.get(t)}s(Ys,"getTranslator");function Xs(t,e){let r={};return(t?.audio!==void 0||e?.audio!==void 0)&&(r.audio=(t?.audio??0)+(e?.audio??0)),(t?.image!==void 0||e?.image!==void 0)&&(r.image=(t?.image??0)+(e?.image??0)),(t?.video!==void 0||e?.video!==void 0)&&(r.video=(t?.video??0)+(e?.video??0)),(t?.document!==void 0||e?.document!==void 0)&&(r.document=(t?.document??0)+(e?.document??0)),(t?.text!==void 0||e?.text!==void 0)&&(r.text=(t?.text??0)+(e?.text??0)),r}s(Xs,"mergeModalitiesTokenDetails");function $d(t,e){let r={...Xs(t,e)};return(t?.cache_read!==void 0||e?.cache_read!==void 0)&&(r.cache_read=(t?.cache_read??0)+(e?.cache_read??0)),(t?.cache_creation!==void 0||e?.cache_creation!==void 0)&&(r.cache_creation=(t?.cache_creation??0)+(e?.cache_creation??0)),r}s($d,"mergeInputTokenDetails");function Dd(t,e){let r={...Xs(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}s(Dd,"mergeOutputTokenDetails");function Qr(t,e){return{input_tokens:(t?.input_tokens??0)+(e?.input_tokens??0),output_tokens:(t?.output_tokens??0)+(e?.output_tokens??0),total_tokens:(t?.total_tokens??0)+(e?.total_tokens??0),input_token_details:$d(t?.input_token_details,e?.input_token_details),output_token_details:Dd(t?.output_token_details,e?.output_token_details)}}s(Qr,"mergeUsageMetadata");var at=class extends We{static{s(this,"AIMessage")}type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",usage_metadata:"usage_metadata"}}constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{e=t;let r=e.additional_kwargs?.tool_calls,n=e.tool_calls;r!=null&&r.length>0&&(n===void 0||n.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
5
+
6
+ Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&n===void 0){let[i,a]=gi(r);e.tool_calls=i??[],e.invalid_tool_calls=a??[]}else e.tool_calls=e.tool_calls??[],e.invalid_tool_calls=e.invalid_tool_calls??[]}catch{e.tool_calls=[],e.invalid_tool_calls=[]}if(e.response_metadata!==void 0&&"output_version"in e.response_metadata&&e.response_metadata.output_version==="v1"&&(e.contentBlocks=e.content,e.content=void 0),e.contentBlocks!==void 0){if(e.tool_calls){let a=e.tool_calls.filter(o=>!e.contentBlocks?.some(l=>l.type==="tool_call"&&l.id===o.id&&l.name===o.name));e.contentBlocks.push(...a.map(o=>({type:"tool_call",id:o.id,name:o.name,args:o.args})))}let i=e.contentBlocks.filter(a=>a.type==="tool_call").filter(a=>!e.tool_calls?.some(o=>o.id===a.id&&o.name===a.name));i.length>0&&(e.tool_calls=[...e.tool_calls??[],...i.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args}))])}}super(e),typeof e!="string"&&(this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=e.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let e=Ys(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let t=super.contentBlocks;if(this.tool_calls){let e=this.tool_calls.filter(r=>!t.some(n=>n.id===r.id&&n.name===r.name));t.push(...e.map(r=>({type:"tool_call",id:r.id,name:r.name,args:r.args})))}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}};function Gd(t){if(typeof t=="string")return t;switch(t.type){case"text":return t.text??"";case"text-plain":return t.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return t.type?`[${t.type}]`:""}}s(Gd,"_contentBlockToString");function rn(t,e="Human",r="AI"){let n=[];for(let i of t){let a;if(i.type==="human")a=e;else if(i.type==="ai")a=r;else if(i.type==="system")a="System";else if(i.type==="tool")a="Tool";else if(i.type==="generic")a=i.role;else throw new Error(`Got unsupported message type: ${i.type}`);let o=i.name?`${i.name}, `:"",l=typeof i.content=="string"?i.content:Array.isArray(i.content)?i.content.map(Gd).filter(Boolean).join(""):"",c=`${a}: ${o}${l}`;if(i.type==="ai"){let u=i;u.tool_calls&&u.tool_calls.length>0?c+=JSON.stringify(u.tool_calls):u.additional_kwargs&&"function_call"in u.additional_kwargs&&(c+=JSON.stringify(u.additional_kwargs.function_call))}n.push(c)}return n.join(`
7
+ `)}s(rn,"getBufferString");var k="0123456789abcdef".split(""),Vd=[-2147483648,8388608,32768,128],Re=[24,16,8,0],nn=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],ie=[];function $e(t,e){e?(ie[0]=ie[16]=ie[1]=ie[2]=ie[3]=ie[4]=ie[5]=ie[6]=ie[7]=ie[8]=ie[9]=ie[10]=ie[11]=ie[12]=ie[13]=ie[14]=ie[15]=0,this.blocks=ie):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}s($e,"Sha256");$e.prototype.update=function(t){if(!this.finalized){var e,r=typeof t;if(r!=="string"){if(r==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var n,i=0,a,o=t.length,l=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,l[0]=this.block,this.block=l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0),e)for(a=this.start;i<o&&a<64;++i)l[a>>>2]|=t[i]<<Re[a++&3];else for(a=this.start;i<o&&a<64;++i)n=t.charCodeAt(i),n<128?l[a>>>2]|=n<<Re[a++&3]:n<2048?(l[a>>>2]|=(192|n>>>6)<<Re[a++&3],l[a>>>2]|=(128|n&63)<<Re[a++&3]):n<55296||n>=57344?(l[a>>>2]|=(224|n>>>12)<<Re[a++&3],l[a>>>2]|=(128|n>>>6&63)<<Re[a++&3],l[a>>>2]|=(128|n&63)<<Re[a++&3]):(n=65536+((n&1023)<<10|t.charCodeAt(++i)&1023),l[a>>>2]|=(240|n>>>18)<<Re[a++&3],l[a>>>2]|=(128|n>>>12&63)<<Re[a++&3],l[a>>>2]|=(128|n>>>6&63)<<Re[a++&3],l[a>>>2]|=(128|n&63)<<Re[a++&3]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=l[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};$e.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=Vd[e&3],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}};$e.prototype.hash=function(){var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,a=this.h5,o=this.h6,l=this.h7,c=this.blocks,u,d,p,h,g,b,v,P,I,S,A;for(u=16;u<64;++u)g=c[u-15],d=(g>>>7|g<<25)^(g>>>18|g<<14)^g>>>3,g=c[u-2],p=(g>>>17|g<<15)^(g>>>19|g<<13)^g>>>10,c[u]=c[u-16]+d+c[u-7]+p<<0;for(A=e&r,u=0;u<64;u+=4)this.first?(this.is224?(P=300032,g=c[0]-1413257819,l=g-150054599<<0,n=g+24177077<<0):(P=704751109,g=c[0]-210244248,l=g-1521486534<<0,n=g+143694565<<0),this.first=!1):(d=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),p=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),P=t&e,h=P^t&r^A,v=i&a^~i&o,g=l+p+v+nn[u]+c[u],b=d+h,l=n+g<<0,n=g+b<<0),d=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),p=(l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7),I=n&t,h=I^n&e^P,v=o&l^~o&i,g=a+p+v+nn[u+1]+c[u+1],b=d+h,o=r+g<<0,r=g+b<<0,d=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),p=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),S=r&n,h=S^r&t^I,v=a&o^~a&l,g=i+p+v+nn[u+2]+c[u+2],b=d+h,a=e+g<<0,e=g+b<<0,d=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),p=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),A=e&r,h=A^e&n^S,v=a&o^~a&l,g=i+p+v+nn[u+3]+c[u+3],b=d+h,i=t+g<<0,t=g+b<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+e<<0,this.h2=this.h2+r<<0,this.h3=this.h3+n<<0,this.h4=this.h4+i<<0,this.h5=this.h5+a<<0,this.h6=this.h6+o<<0,this.h7=this.h7+l<<0};$e.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,a=this.h5,o=this.h6,l=this.h7,c=k[t>>>28&15]+k[t>>>24&15]+k[t>>>20&15]+k[t>>>16&15]+k[t>>>12&15]+k[t>>>8&15]+k[t>>>4&15]+k[t&15]+k[e>>>28&15]+k[e>>>24&15]+k[e>>>20&15]+k[e>>>16&15]+k[e>>>12&15]+k[e>>>8&15]+k[e>>>4&15]+k[e&15]+k[r>>>28&15]+k[r>>>24&15]+k[r>>>20&15]+k[r>>>16&15]+k[r>>>12&15]+k[r>>>8&15]+k[r>>>4&15]+k[r&15]+k[n>>>28&15]+k[n>>>24&15]+k[n>>>20&15]+k[n>>>16&15]+k[n>>>12&15]+k[n>>>8&15]+k[n>>>4&15]+k[n&15]+k[i>>>28&15]+k[i>>>24&15]+k[i>>>20&15]+k[i>>>16&15]+k[i>>>12&15]+k[i>>>8&15]+k[i>>>4&15]+k[i&15]+k[a>>>28&15]+k[a>>>24&15]+k[a>>>20&15]+k[a>>>16&15]+k[a>>>12&15]+k[a>>>8&15]+k[a>>>4&15]+k[a&15]+k[o>>>28&15]+k[o>>>24&15]+k[o>>>20&15]+k[o>>>16&15]+k[o>>>12&15]+k[o>>>8&15]+k[o>>>4&15]+k[o&15];return this.is224||(c+=k[l>>>28&15]+k[l>>>24&15]+k[l>>>20&15]+k[l>>>16&15]+k[l>>>12&15]+k[l>>>8&15]+k[l>>>4&15]+k[l&15]),c};$e.prototype.toString=$e.prototype.hex;$e.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,a=this.h5,o=this.h6,l=this.h7,c=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||c.push(l>>>24&255,l>>>16&255,l>>>8&255,l&255),c};$e.prototype.array=$e.prototype.digest;$e.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),e.setUint32(20,this.h5),e.setUint32(24,this.h6),this.is224||e.setUint32(28,this.h7),t};var ip=it(cn(),1);var bo=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Tr(t){return typeof t=="string"&&bo.test(t)}s(Tr,"validate");function Ar(t){if(!Tr(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}s(Ar,"parse");var oe=[];for(let t=0;t<256;++t)oe.push((t+256).toString(16).slice(1));function st(t,e=0){return(oe[t[e+0]]+oe[t[e+1]]+oe[t[e+2]]+oe[t[e+3]]+"-"+oe[t[e+4]]+oe[t[e+5]]+"-"+oe[t[e+6]]+oe[t[e+7]]+"-"+oe[t[e+8]]+oe[t[e+9]]+"-"+oe[t[e+10]]+oe[t[e+11]]+oe[t[e+12]]+oe[t[e+13]]+oe[t[e+14]]+oe[t[e+15]]).toLowerCase()}s(st,"unsafeStringify");var ap=new Uint8Array(16);function Ir(){return crypto.getRandomValues(ap)}s(Ir,"rng");function sp(t,e,r,n){switch(t){case 0:return e&r^~e&n;case 1:return e^r^n;case 2:return e&r^e&n^r&n;case 3:return e^r^n}}s(sp,"f");function Si(t,e){return t<<e|t>>>32-e}s(Si,"ROTL");function wo(t){let e=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(t.length+1);n.set(t),n[t.length]=128,t=n;let i=t.length/4+2,a=Math.ceil(i/16),o=new Array(a);for(let l=0;l<a;++l){let c=new Uint32Array(16);for(let u=0;u<16;++u)c[u]=t[l*64+u*4]<<24|t[l*64+u*4+1]<<16|t[l*64+u*4+2]<<8|t[l*64+u*4+3];o[l]=c}o[a-1][14]=(t.length-1)*8/2**32,o[a-1][14]=Math.floor(o[a-1][14]),o[a-1][15]=(t.length-1)*8&4294967295;for(let l=0;l<a;++l){let c=new Uint32Array(80);for(let b=0;b<16;++b)c[b]=o[l][b];for(let b=16;b<80;++b)c[b]=Si(c[b-3]^c[b-8]^c[b-14]^c[b-16],1);let u=r[0],d=r[1],p=r[2],h=r[3],g=r[4];for(let b=0;b<80;++b){let v=Math.floor(b/20),P=Si(u,5)+sp(v,d,p,h)+g+e[v]+c[b]>>>0;g=h,h=p,p=Si(d,30)>>>0,d=u,u=P}r[0]=r[0]+u>>>0,r[1]=r[1]+d>>>0,r[2]=r[2]+p>>>0,r[3]=r[3]+h>>>0,r[4]=r[4]+g>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])}s(wo,"sha1");function op(t){t=unescape(encodeURIComponent(t));let e=new Uint8Array(t.length);for(let r=0;r<t.length;++r)e[r]=t.charCodeAt(r);return e}s(op,"stringToBytes");var vo="6ba7b810-9dad-11d1-80b4-00c04fd430c8",xo="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Eo(t,e,r,n,i,a){let o=typeof r=="string"?op(r):r,l=typeof n=="string"?Ar(n):n;if(typeof n=="string"&&(n=Ar(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+o.length);if(c.set(l),c.set(o,l.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,i){if(a??=0,a<0||a+16>i.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let u=0;u<16;++u)i[a+u]=c[u];return i}return st(c)}s(Eo,"v35");function Ti(t,e,r,n){return Eo(80,wo,t,e,r,n)}s(Ti,"v5");Ti.DNS=vo;Ti.URL=xo;var Ai={};function To(t,e,r){let n;if(t)n=So(t.random??t.rng?.()??Ir(),t.msecs,t.seq,e,r);else{let i=Date.now(),a=Ir();cp(Ai,i,a),n=So(a,Ai.msecs,Ai.seq,e,r)}return e??st(n)}s(To,"v7");function cp(t,e,r){return t.msecs??=-1/0,t.seq??=0,e>t.msecs?(t.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}s(cp,"updateV7State");function So(t,e,r,n,i=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),i=0;else if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return e??=Date.now(),r??=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9],n[i++]=e/1099511627776&255,n[i++]=e/4294967296&255,n[i++]=e/16777216&255,n[i++]=e/65536&255,n[i++]=e/256&255,n[i++]=e&255,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|t[10]&3,n[i++]=t[11],n[i++]=t[12],n[i++]=t[13],n[i++]=t[14],n[i++]=t[15],n}s(So,"v7Bytes");var De=To;var Ao=Symbol.for("ls:tracing_async_local_storage"),xt=Symbol.for("lc:context_variables"),Io=s(t=>{globalThis[Ao]=t},"setGlobalAsyncLocalStorageInstance"),ot=s(()=>globalThis[Ao],"getGlobalAsyncLocalStorageInstance");var up=s(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),dp=s(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),pp=s(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),Ci=s(()=>typeof Deno<"u","isDeno"),fp=s(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Ci(),"isNode"),mp=s(()=>{let t;return up()?t="browser":fp()?t="node":dp()?t="webworker":pp()?t="jsdom":Ci()?t="deno":t="other",t},"getEnv"),Ii;function Co(){return Ii===void 0&&(Ii={library:"langchain-js",runtime:mp()}),Ii}s(Co,"getRuntimeEnvironment");function Me(t){try{return typeof process<"u"?process.env?.[t]:Ci()?Deno?.env.get(t):void 0}catch{return}}s(Me,"getEnvironmentVariable");var hp=class{static{s(this,"BaseCallbackHandlerMethodsClass")}};var Jt=class extends hp{static{s(this,"BaseCallbackHandler")}lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,di(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Me("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(t){super(),this.lc_kwargs=t||{},t&&(this.ignoreLLM=t.ignoreLLM??this.ignoreLLM,this.ignoreChain=t.ignoreChain??this.ignoreChain,this.ignoreAgent=t.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=t.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=t.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=t.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(t._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return wt.prototype.toJSON.call(this)}toJSONNotImplemented(){return wt.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends Jt{static{s(this,"Handler")}name=De();constructor(){super(),Object.assign(this,t)}}return new e}},ko=s(t=>{let e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},"isBaseCallbackHandler");var Oo=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function gp(t){return typeof t=="string"&&Oo.test(t)}s(gp,"validate");var Cr=gp;function yp(t){if(!Cr(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}s(yp,"parse");var un=yp;var le=[];for(let t=0;t<256;++t)le.push((t+256).toString(16).slice(1));function Zt(t,e=0){return(le[t[e+0]]+le[t[e+1]]+le[t[e+2]]+le[t[e+3]]+"-"+le[t[e+4]]+le[t[e+5]]+"-"+le[t[e+6]]+le[t[e+7]]+"-"+le[t[e+8]]+le[t[e+9]]+"-"+le[t[e+10]]+le[t[e+11]]+le[t[e+12]]+le[t[e+13]]+le[t[e+14]]+le[t[e+15]]).toLowerCase()}s(Zt,"unsafeStringify");var _p=new Uint8Array(16);function Yt(){return crypto.getRandomValues(_p)}s(Yt,"rng");function bp(t,e,r){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():wp(t,e,r)}s(bp,"v4");function wp(t,e,r){t=t||{};let n=t.random??t.rng?.()??Yt();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[r+i]=n[i];return e}return Zt(n)}s(wp,"_v4");var Et=bp;function vp(t,e,r,n){switch(t){case 0:return e&r^~e&n;case 1:return e^r^n;case 2:return e&r^e&n^r&n;case 3:return e^r^n}}s(vp,"f");function ki(t,e){return t<<e|t>>>32-e}s(ki,"ROTL");function xp(t){let e=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(t.length+1);n.set(t),n[t.length]=128,t=n;let i=t.length/4+2,a=Math.ceil(i/16),o=new Array(a);for(let l=0;l<a;++l){let c=new Uint32Array(16);for(let u=0;u<16;++u)c[u]=t[l*64+u*4]<<24|t[l*64+u*4+1]<<16|t[l*64+u*4+2]<<8|t[l*64+u*4+3];o[l]=c}o[a-1][14]=(t.length-1)*8/2**32,o[a-1][14]=Math.floor(o[a-1][14]),o[a-1][15]=(t.length-1)*8&4294967295;for(let l=0;l<a;++l){let c=new Uint32Array(80);for(let b=0;b<16;++b)c[b]=o[l][b];for(let b=16;b<80;++b)c[b]=ki(c[b-3]^c[b-8]^c[b-14]^c[b-16],1);let u=r[0],d=r[1],p=r[2],h=r[3],g=r[4];for(let b=0;b<80;++b){let v=Math.floor(b/20),P=ki(u,5)+vp(v,d,p,h)+g+e[v]+c[b]>>>0;g=h,h=p,p=ki(d,30)>>>0,d=u,u=P}r[0]=r[0]+u>>>0,r[1]=r[1]+d>>>0,r[2]=r[2]+p>>>0,r[3]=r[3]+h>>>0,r[4]=r[4]+g>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])}s(xp,"sha1");var Po=xp;function Ep(t){t=unescape(encodeURIComponent(t));let e=new Uint8Array(t.length);for(let r=0;r<t.length;++r)e[r]=t.charCodeAt(r);return e}s(Ep,"stringToBytes");var Oi="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Pi="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Ri(t,e,r,n,i,a){let o=typeof r=="string"?Ep(r):r,l=typeof n=="string"?un(n):n;if(typeof n=="string"&&(n=un(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+o.length);if(c.set(l),c.set(o,l.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,i){if(a??=0,a<0||a+16>i.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let u=0;u<16;++u)i[a+u]=c[u];return i}return Zt(c)}s(Ri,"v35");function Mi(t,e,r,n){return Ri(80,Po,t,e,r,n)}s(Mi,"v5");Mi.DNS=Oi;Mi.URL=Pi;var Ni=Mi;var Li={};function Sp(t,e,r){let n;if(t)n=Ro(t.random??t.rng?.()??Yt(),t.msecs,t.seq,e,r);else{let i=Date.now(),a=Yt();Tp(Li,i,a),n=Ro(a,Li.msecs,Li.seq,e,r)}return e??Zt(n)}s(Sp,"v7");function Tp(t,e,r){return t.msecs??=-1/0,t.seq??=0,e>t.msecs?(t.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}s(Tp,"updateV7State");function Ro(t,e,r,n,i=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),i=0;else if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return e??=Date.now(),r??=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9],n[i++]=e/1099511627776&255,n[i++]=e/4294967296&255,n[i++]=e/16777216&255,n[i++]=e/65536&255,n[i++]=e/256&255,n[i++]=e&255,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|t[10]&3,n[i++]=t[11],n[i++]=t[12],n[i++]=t[13],n[i++]=t[14],n[i++]=t[15],n}s(Ro,"v7Bytes");var Xt=Sp;var Mo="gen_ai.operation.name",No="gen_ai.system",$i="gen_ai.request.model",Lo="gen_ai.response.model",Di="gen_ai.usage.input_tokens",Ui="gen_ai.usage.output_tokens",Fi="gen_ai.usage.total_tokens",$o="gen_ai.request.max_tokens",Do="gen_ai.request.temperature",Uo="gen_ai.request.top_p",Fo="gen_ai.request.frequency_penalty",jo="gen_ai.request.presence_penalty",Bo="gen_ai.response.finish_reasons",Ho="gen_ai.prompt",zo="gen_ai.completion",Go="gen_ai.request.extra_query",Vo="gen_ai.request.extra_body",qo="gen_ai.serialized.name",Wo="gen_ai.serialized.signature",Ko="gen_ai.serialized.doc",Jo="gen_ai.response.id",Zo="gen_ai.response.service_tier",Yo="gen_ai.response.system_fingerprint",Xo="gen_ai.usage.input_token_details",Qo="gen_ai.usage.output_token_details",el="langsmith.trace.session_id",tl="langsmith.trace.session_name",rl="langsmith.span.kind",nl="langsmith.trace.name",il="langsmith.metadata",ji="langsmith.span.tags";var al="langsmith.request.streaming",sl="langsmith.request.headers";var Bi="langsmith.usage_metadata";var Cp=s((...t)=>fetch(...t),"DEFAULT_FETCH_IMPLEMENTATION"),kp,ol=Symbol.for("ls:fetch_implementation");var ll=s(()=>globalThis[ol]===void 0?!0:kp??!1,"_shouldStreamForGlobalFetchImplementation"),cl=s(t=>async(...e)=>{if(t||q("DEBUG")==="true"){let[n,i]=e;console.log(`\u2192 ${i?.method||"GET"} ${n}`)}let r=await(globalThis[ol]??Cp)(...e);return(t||q("DEBUG")==="true")&&console.log(`\u2190 ${r.status} ${r.statusText} ${r.url}`),r},"_getFetchImplementation");var kr=s(()=>q("PROJECT")??ae("LANGCHAIN_SESSION")??"default","getDefaultProjectName");var ul={};function se(t,e){let r=e?.code??t;ul[r]||(ul[r]=!0,e?.type&&typeof process<"u"&&typeof process.emitWarning=="function"?process.emitWarning(t,{type:e.type,code:e.code}):e?.type&&e?.code?console.warn(`${e.type} [${e.code}]: ${t}`):console.warn(t))}s(se,"warnOnce");var E=s(t=>BigInt(t),"n"),ml=E("0x9E3779B1"),hl=E("0x85EBCA77"),Op=E("0xC2B2AE3D"),lt=E("0x9E3779B185EBCA87"),St=E("0xC2B2AE3D27D4EB4F"),gl=E("0x165667B19E3779F9"),Vi=E("0x85EBCA77C2B2AE63"),Pp=E("0x27D4EB2F165667C5"),Rp=E("0x165667919E3779F9"),Mp=E("0x9FB21C651E98DF25");function Np(t){let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)e[r/2]=parseInt(t.substring(r,r+2),16);return e}s(Np,"hexToBytes");var Ue=Np("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),er=(E(1)<<E(128))-E(1),D=(E(1)<<E(64))-E(1),mn=(E(1)<<E(32))-E(1),Ke=64,yl=Ke/8,Lp=8,dn=4;function W(t,e=0){return new Uint8Array(t.buffer,t.byteOffset+e,t.length-e)}s(W,"getView");function J(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getBigUint64(0,!0)}s(J,"readBigUInt64LE");function Qt(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getUint32(0,!0)}s(Qt,"readUInt32LE");function Hi(t,e=0){return t[e]}s(Hi,"readUInt8");var $p=s(t=>(t&E(255))<<E(56)|(t&E(65280))<<E(40)|(t&E(16711680))<<E(24)|(t&E(4278190080))<<E(8)|(t&E(0xff00000000))>>E(8)|(t&E(0xff0000000000))>>E(24)|(t&E(0xff000000000000))>>E(40)|(t&E(0xff00000000000000))>>E(56),"bswap64"),Dp=s(t=>(t=(t&E(65535))<<E(16)|(t&E(4294901760))>>E(16),t=(t&E(16711935))<<E(8)|(t&E(4278255360))>>E(8),t),"bswap32"),Up=s((t,e)=>(t&mn)*(e&mn)&D,"XXH_mult32to64"),tr=s(t=>{if(!t)throw new Error("Assert failed")},"assert");function Fp(t,e){return(t<<e|t>>E(32)-e)&mn}s(Fp,"rotl32");function _l(t,e,r){for(let n=0;n<yl;n++){let i=J(e,n*8),a=i^J(r,n*8);t[n^1]+=i,t[n]+=Up(a,a>>E(32))}return t}s(_l,"XXH3_accumulate_512");function dl(t,e,r,n){for(let i=0;i<n;i++)_l(t,W(e,i*Ke),W(r,i*8));return t}s(dl,"XXH3_accumulate");function jp(t,e){for(let r=0;r<yl;r++){let n=J(e,r*8),i=t[r];i=zi(i,E(47)),i^=n,i*=ml,t[r]=i&D}return t}s(jp,"XXH3_scrambleAcc");function pn(t,e){return bl(t[0]^J(e,0),t[1]^J(e,Lp))}s(pn,"XXH3_mix2Accs");function pl(t,e,r){let n=r;return n+=pn(t.slice(0),W(e,0*dn)),n+=pn(t.slice(2),W(e,4*dn)),n+=pn(t.slice(4),W(e,8*dn)),n+=pn(t.slice(6),W(e,12*dn)),Fe(n&D)}s(pl,"XXH3_mergeAccs");function Bp(t,e,r,n,i){let a=Math.floor((r.byteLength-Ke)/8),o=Ke*a,l=Math.floor((e.byteLength-1)/o);for(let c=0;c<l;c++)t=dl(t,W(e,c*o),r,a),t=i(t,W(r,r.byteLength-Ke));{let c=Math.floor((e.byteLength-1-o*l)/Ke);t=dl(t,W(e,l*o),r,c),t=n(t,W(e,e.byteLength-Ke),W(r,r.byteLength-Ke-7))}return t}s(Bp,"XXH3_hashLong");function Hp(t,e,r){let n=new BigUint64Array([Op,lt,St,gl,Vi,hl,Pp,ml]);tr(t.length>128),n=Bp(n,t,e,_l,jp),tr(n.length*8==64);{let i=pl(n,W(e,11),E(t.byteLength)*lt&D);return pl(n,W(e,e.byteLength-Ke-11),~(E(t.byteLength)*St)&D)<<E(64)|i}}s(Hp,"XXH3_hashLong_128b");function bl(t,e){let r=t*e&er;return r&D^r>>E(64)}s(bl,"XXH3_mul128_fold64");function fl(t,e,r){return bl((J(t,0)^J(e,0)+r)&D,(J(t,8)^J(e,8)-r)&D)}s(fl,"XXH3_mix16B");function fn(t,e,r,n,i){let a=t&D,o=t>>E(64)&D;return a+=fl(e,n,i),a^=J(r,0)+J(r,8),a&=D,o+=fl(r,W(n,16),i),o^=J(e,0)+J(e,8),o&=D,o<<E(64)|a}s(fn,"XXH3_mix32B");function Fe(t){return t^=t>>E(37),t*=Rp,t&=D,t^=t>>E(32),t}s(Fe,"XXH3_avalanche");function hn(t){return t^=t>>E(33),t*=St,t&=D,t^=t>>E(29),t*=gl,t&=D,t^=t>>E(32),t}s(hn,"XXH3_avalanche64");function zp(t,e,r){let n=t.byteLength;tr(n>0&&n<=3);let i=E(Hi(t,n-1))|E(n<<8)|E(Hi(t,0)<<16)|E(Hi(t,n>>1)<<24),a=(E(Qt(e,0))^E(Qt(e,4)))+r,o=(i^a)&D,l=(E(Qt(e,8))^E(Qt(e,12)))-r,c=(Fp(Dp(i),E(13))^l)&D;return(hn(c)&D)<<E(64)|hn(o)}s(zp,"XXH3_len_1to3_128b");function zi(t,e){return t^t>>e}s(zi,"xorshift64");function Gp(t,e,r){let n=t.byteLength;tr(n>=4&&n<=8);{let i=Qt(t,0),a=Qt(t,n-4),o=E(i)|E(a)<<E(32),l=(J(e,16)^J(e,24))+r&D,u=(o^l)*(lt+(E(n)<<E(2)))&er;return u+=(u&D)<<E(65),u&=er,u^=u>>E(67),zi(zi(u&D,E(35))*Mp&D,E(28))|Fe(u>>E(64))<<E(64)}}s(Gp,"XXH3_len_4to8_128b");function Vp(t,e,r){let n=t.byteLength;tr(n>=9&&n<=16);{let i=(J(e,32)^J(e,40))+r&D,a=(J(e,48)^J(e,56))-r&D,o=J(t),l=J(t,n-8),c=(o^l^i)*lt,u=(c&D)+(E(n-1)<<E(54));c=c&(er^D)|u,l^=a,c+=l+(l&mn)*(hl-E(1))<<E(64),c&=er,c^=$p(c>>E(64));let d=(c&D)*St;return d+=(c>>E(64))*St<<E(64),d&=er,Fe(d&D)|Fe(d>>E(64))<<E(64)}}s(Vp,"XXH3_len_9to16_128b");function qp(t,e){let r=t.byteLength;return tr(r<=16),r>8?Vp(t,Ue,e):r>=4?Gp(t,Ue,e):r>0?zp(t,Ue,e):hn(e^J(Ue,64)^J(Ue,72))|hn(e^J(Ue,80)^J(Ue,88))<<E(64)}s(qp,"XXH3_len_0to16_128b");function Gi(t){return~t+E(1)&D}s(Gi,"inv64");function Wp(t,e,r){let n=E(t.byteLength)*lt&D,i=E(t.byteLength-1)/E(32);for(;i>=0;){let l=Number(i);n=fn(n,W(t,16*l),W(t,t.byteLength-16*(l+1)),W(e,32*l),r),i--}let a=n+(n>>E(64))&D;a=Fe(a);let o=(n&D)*lt+(n>>E(64))*Vi+(E(t.byteLength)-r&D)*St;return o&=D,o=Gi(Fe(o)),a|o<<E(64)}s(Wp,"XXH3_len_17to128_128b");function Kp(t,e,r){let n=E(t.byteLength)*lt&D;for(let o=32;o<160;o+=32)n=fn(n,W(t,o-32),W(t,o-16),W(e,o-32),r);n=Fe(n&D)|Fe(n>>E(64))<<E(64);for(let o=160;o<=t.byteLength;o+=32)n=fn(n,W(t,o-32),W(t,o-16),W(e,3+o-160),r);n=fn(n,W(t,t.byteLength-16),W(t,t.byteLength-32),W(e,103),Gi(r));let i=n+(n>>E(64))&D;i=Fe(i);let a=(n&D)*lt+(n>>E(64))*Vi+(E(t.byteLength)-r&D)*St;return a&=D,a=Gi(Fe(a)),i|a<<E(64)}s(Kp,"XXH3_len_129to240_128b");function wl(t,e=E(0)){let r=t.byteLength;return r<=16?qp(t,e):r<=128?Wp(t,Ue,e):r<=240?Kp(t,Ue,e):Hp(t,Ue,e)}s(wl,"XXH3_128");function vl(t){let e=new Uint8Array(16),r=new DataView(e.buffer),n=t&D,i=t>>E(64);return r.setBigUint64(0,i,!1),r.setBigUint64(8,n,!1),e}s(vl,"xxh128ToBytes");var xl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function L(t,e){if(!xl.test(t)){let r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}s(L,"assertUuid");function gn(t){let e=typeof t=="string"?Date.parse(t):t;return Xt({msecs:e,seq:0})}s(gn,"uuid7FromTime");function El(t){if(!xl.test(t))return null;let e=t[14];return parseInt(e,16)}s(El,"getUuidVersion");function Jp(t){let e=t.replace(/-/g,""),r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(e.slice(n*2,n*2+2),16);return r}s(Jp,"uuidToBytes");function Zp(t){let e=Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}s(Zp,"bytesToUuid");var Yp=new TextEncoder;function Xp(t){let e=Yp.encode(t),r=wl(e);return vl(r)}s(Xp,"_fastHash128");function rr(t,e){let r=`${t}:${e}`,n=Xp(r),i=new Uint8Array(16);if(El(t)===7){let o=Jp(t);i.set(o.slice(0,6),0)}else{let o=Date.now();i[0]=o/1099511627776&255,i[1]=o/4294967296&255,i[2]=o/16777216&255,i[3]=o/65536&255,i[4]=o/256&255,i[5]=o&255}return i[6]=112|n[0]&15,i[7]=n[1],i[8]=128|n[2]&63,i.set(n.slice(3,10),9),Zp(i)}s(rr,"nonCryptographicUuid7Deterministic");var qi=s(t=>t!==void 0?t:!!["TRACING_V2","TRACING"].find(r=>q(r)==="true"),"isEnvTracingEnabled");var Ki=class{static{s(this,"MockAsyncLocalStorage")}getStore(){}run(e,r){return r()}},Wi=Symbol.for("ls:tracing_async_local_storage"),Qp=new Ki,Ji=class{static{s(this,"AsyncLocalStorageProvider")}getInstance(){return globalThis[Wi]??Qp}initializeGlobalInstance(e){globalThis[Wi]===void 0&&(globalThis[Wi]=e)}},ef=new Ji;function Zi(t=!1){let e=ef.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
8
+
9
+ Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}s(Zi,"getCurrentRunTree");var ve=it(require("node:fs"),1),xe=it(require("node:fs/promises"),1),tf=it(require("node:path"),1);var Ne=tf;async function yn(t){await xe.mkdir(t,{recursive:!0})}s(yn,"mkdir");async function nr(t,e){let r=`${t}.tmp`;await xe.writeFile(r,e,{encoding:"utf8",mode:384}),await xe.rename(r,t)}s(nr,"writeFileAtomic");async function Sl(t){return xe.readdir(t)}s(Sl,"readdir");async function Tl(t){return xe.stat(t)}s(Tl,"stat");function ir(t){return ve.existsSync(t)}s(ir,"existsSync");function Al(t){ve.mkdirSync(t,{recursive:!0})}s(Al,"mkdirSync");function Il(t,e){ve.writeFileSync(t,e)}s(Il,"writeFileSync");function Cl(t,e){ve.renameSync(t,e)}s(Cl,"renameSync");function kl(t){ve.unlinkSync(t)}s(kl,"unlinkSync");function Tt(t){return ve.readFileSync(t,"utf-8")}s(Tt,"readFileSync");async function Ol(t){await xe.mkdir(t,{mode:448})}s(Ol,"mkdirExclusive");function Pl(t){try{return ve.statSync(t).mtimeMs}catch{return}}s(Pl,"statMtimeMs");async function _n(t){await xe.rm(t,{recursive:!0,force:!0})}s(_n,"rmRecursive");function rf(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}s(rf,"isStale");var bn=class{static{s(this,"PromptCache")}constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,r){if(this.maxSize===0)return;let n=this.cache.get(e);if(!n){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...n,refreshFunc:r}),this._metrics.hits+=1,n.value}set(e,r,n){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){let a=this.cache.keys().next().value;a!==void 0&&this.cache.delete(a)}let i={value:r,createdAt:Date.now(),refreshFunc:n};this.cache.delete(e),this.cache.set(e,i)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){let r={};for(let[a,o]of this.cache.entries())r[a]=o.value;let n=Ne.dirname(e);ir(n)||Al(n);let i=`${e}.tmp`;try{Il(i,JSON.stringify({entries:r},null,2)),Cl(i,e)}catch(a){throw ir(i)&&kl(i),a}}load(e){if(!ir(e))return 0;let r;try{let a=Tt(e);r=JSON.parse(a).entries??null}catch{return 0}if(!r)return 0;let n=0,i=Date.now();for(let[a,o]of Object.entries(r)){if(this.cache.size>=this.maxSize)break;let l={value:o,createdAt:i};this.cache.set(a,l),n+=1}return n}startRefreshLoop(){this.stop(),this.ttlSeconds!==null&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){let e=[];for(let[r,n]of this.cache.entries())rf(n,this.ttlSeconds)&&e.push([r,n]);return e}async refreshStaleEntries(){let e=this.getStaleEntries();if(e.length!==0){for(let[r,n]of e)if(n.refreshFunc!==void 0)try{let i=await n.refreshFunc();this.set(r,i,n.refreshFunc),this._metrics.refreshes+=1}catch(i){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${r}:`,i)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}},wn=new bn;function Rl(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}s(Rl,"isAbortError");var Or=s(t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)},"castToError");var Ee=class extends Error{static{s(this,"LangsmithError")}},ce=class t extends Ee{static{s(this,"APIError")}constructor(e,r,n,i){super(`${t.makeMessage(e,r,n)}`),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.status=e,this.headers=i,this.error=r}static makeMessage(e,r,n){let i=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,r,n,i){if(!e||!i)return new Je({message:n,cause:Or(r)});let a=r;return e===400?new It(e,a,n,i):e===401?new Ct(e,a,n,i):e===403?new kt(e,a,n,i):e===404?new Ot(e,a,n,i):e===409?new Pt(e,a,n,i):e===422?new Rt(e,a,n,i):e===429?new Mt(e,a,n,i):e>=500?new Nt(e,a,n,i):new t(e,a,n,i)}},ct=class extends ce{static{s(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Je=class extends ce{static{s(this,"APIConnectionError")}constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},At=class extends Je{static{s(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}},It=class extends ce{static{s(this,"BadRequestError")}},Ct=class extends ce{static{s(this,"AuthenticationError")}},kt=class extends ce{static{s(this,"PermissionDeniedError")}},Ot=class extends ce{static{s(this,"NotFoundError")}},Pt=class extends ce{static{s(this,"ConflictError")}},Rt=class extends ce{static{s(this,"UnprocessableEntityError")}},Mt=class extends ce{static{s(this,"RateLimitError")}},Nt=class extends ce{static{s(this,"InternalServerError")}};var vn="0.8.9";var je,af=s(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),sf=s(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),of=s(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),Ll=s(()=>typeof globalThis.Deno<"u","isDeno"),lf=s(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Ll(),"isNode"),Pr=s(()=>je||(typeof Bun<"u"?je="bun":af()?je="browser":lf()?je="node":sf()?je="webworker":of()?je="jsdom":Ll()?je="deno":je="other",je),"getEnv"),Xi;function xn(){if(Xi===void 0){let t=Pr(),e=uf();Xi={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:vn,...e}}return Xi}s(xn,"getRuntimeEnvironment");function ea(){let t=cf(),e={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_CONFIG_FILE","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[n,i]of Object.entries(t))typeof i=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=i:e[n]=i);return e}s(ea,"getLangSmithEnvVarsMetadata");function cf(){let t={};try{if(typeof process<"u"&&process.env)for(let[e,r]of Object.entries(process.env))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&r!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof r=="string"?t[e]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):t[e]=r)}catch{}return t}s(cf,"getLangSmithEnvironmentVariables");function ae(t){try{return typeof process<"u"?process.env?.[t]:void 0}catch{return}}s(ae,"getEnvironmentVariable");function q(t){return ae(`LANGSMITH_${t}`)||ae(`LANGCHAIN_${t}`)}s(q,"getLangSmithEnvironmentVariable");var Qi;function uf(){if(Qi!==void 0)return Qi;let t=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(let r of t){let n=ae(r);n!==void 0&&(e[r]=n)}return Qi=e,e}s(uf,"getShas");function Ml(){return ae("OTEL_ENABLED")==="true"||q("OTEL_ENABLED")==="true"}s(Ml,"getOtelEnabled");var Nl=new Set(["langsmith","otel"]);function En(t){if(t!==void 0)return t;let e=q("TRACING_MODE");if(e!==void 0&&e!==""){let r=e.toLowerCase();if(!Nl.has(r))throw new Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(e)}. Must be one of: ${[...Nl].sort().join(", ")}`);return Ml()&&console.warn("Both LANGSMITH_TRACING_MODE and the legacy OTEL_ENABLED / LANGSMITH_OTEL_ENABLED env vars are set. LANGSMITH_TRACING_MODE takes precedence."),r}return Ml()?"otel":"langsmith"}s(En,"resolveTracingMode");var na=class{static{s(this,"MockTracer")}constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&En()==="otel"&&(console.warn('OTel tracing mode is active (via LANGSMITH_TRACING_MODE, OTEL_ENABLED, or LANGSMITH_OTEL_ENABLED), but the required OTEL instances have not been initialized. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let n;if(r.length===1&&typeof r[0]=="function"?n=r[0]:r.length===2&&typeof r[1]=="function"?n=r[1]:r.length===3&&typeof r[2]=="function"&&(n=r[2]),typeof n=="function")return n()}},ia=class{static{s(this,"MockOTELTrace")}constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new na})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},aa=class{static{s(this,"MockOTELContext")}active(){return{}}with(e,r){return r()}},ta=Symbol.for("ls:otel_trace"),ra=Symbol.for("ls:otel_context"),$l=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),df=new ia,pf=new aa,sa=class{static{s(this,"OTELProvider")}getTraceInstance(){return globalThis[ta]??df}getContextInstance(){return globalThis[ra]??pf}initializeGlobalInstances(e){globalThis[ta]===void 0&&(globalThis[ta]=e.trace),globalThis[ra]===void 0&&(globalThis[ra]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[$l]=e}getDefaultOTLPTracerComponents(){return globalThis[$l]??void 0}},oa=new sa;function Sn(){return oa.getTraceInstance()}s(Sn,"getOTELTrace");function Dl(){return oa.getContextInstance()}s(Dl,"getOTELContext");function Ul(){return oa.getDefaultOTLPTracerComponents()}s(Ul,"getDefaultOTLPTracerComponents");var ff={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function mf(t){return ff[t]||t}s(mf,"getOperationName");function hf(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}s(hf,"isPrimitive");var Tn=class{static{s(this,"LangSmithToOTELTranslator")}constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,r){for(let n of e)try{if(!n.run)continue;if(n.operation==="post"){let i=this.createSpanForRun(n,n.run,r.get(n.id));i&&!n.run.end_time&&this.spans.set(n.id,i)}else this.updateSpanForRun(n,n.run)}catch(i){console.error(`Error processing operation ${n.id}:`,i)}}createSpanForRun(e,r,n){let i=n&&Sn().getSpan(n);if(i)try{return this.finishSpanSetup(i,r,e)}catch(a){console.error(`Failed to create span for run ${e.id}:`,a);return}}finishSpanSetup(e,r,n){return this.setSpanAttributes(e,r,n),r.error?(e.setStatus({code:2}),e.recordException(new Error(r.error))):e.setStatus({code:1}),r.end_time&&e.end(new Date(r.end_time)),e}updateSpanForRun(e,r){try{let n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,r,e),r.error?(n.setStatus({code:2}),n.recordException(new Error(r.error))):n.setStatus({code:1});let i=r.end_time;i&&(n.end(new Date(i)),this.spans.delete(e.id))}catch(n){console.error(`Failed to update span for run ${e.id}:`,n)}}extractModelName(e){if(e.extra?.metadata){let r=e.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){let n=r.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(e,r,n){if("run_type"in r&&r.run_type){e.setAttribute(rl,r.run_type);let l=mf(r.run_type||"chain");e.setAttribute(Mo,l)}"name"in r&&r.name&&e.setAttribute(nl,r.name),"session_id"in r&&r.session_id&&e.setAttribute(el,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(tl,r.session_name),this.setGenAiSystem(e,r);let i=this.extractModelName(r);i&&e.setAttribute($i,i),r.extra?.metadata?.usage_metadata&&typeof r.extra.metadata.usage_metadata=="object"&&e.setAttribute(Bi,JSON.stringify(r.extra.metadata.usage_metadata)),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(Di,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(Ui,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(Fi,r.total_tokens),this.setInvocationParameters(e,r);let a=r.extra?.metadata||{};for(let[l,c]of Object.entries(a))c!=null&&e.setAttribute(`${il}.${l}`,hf(c)?String(c):JSON.stringify(c));let o=r.tags;if(o&&Array.isArray(o)?e.setAttribute(ji,o.join(", ")):o&&e.setAttribute(ji,String(o)),"serialized"in r&&typeof r.serialized=="object"){let l=r.serialized;l.name&&e.setAttribute(qo,String(l.name)),l.signature&&e.setAttribute(Wo,String(l.signature)),l.doc&&e.setAttribute(Ko,String(l.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,r){let n="langchain",i=this.extractModelName(r);if(i){let a=i.toLowerCase();a.includes("anthropic")||a.startsWith("claude")?n="anthropic":a.includes("bedrock")?n="aws.bedrock":a.includes("azure")&&a.includes("openai")?n="az.ai.openai":a.includes("azure")&&a.includes("inference")?n="az.ai.inference":a.includes("cohere")?n="cohere":a.includes("deepseek")?n="deepseek":a.includes("gemini")?n="gemini":a.includes("groq")?n="groq":a.includes("watson")||a.includes("ibm")?n="ibm.watsonx.ai":a.includes("mistral")?n="mistral_ai":a.includes("gpt")||a.includes("openai")?n="openai":a.includes("perplexity")||a.includes("sonar")?n="perplexity":a.includes("vertex")?n="vertex_ai":(a.includes("xai")||a.includes("grok"))&&(n="xai")}e.setAttribute(No,n)}setInvocationParameters(e,r){if(!r.extra?.metadata?.invocation_params)return;let n=r.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute($o,n.max_tokens),n.temperature!==void 0&&e.setAttribute(Do,n.temperature),n.top_p!==void 0&&e.setAttribute(Uo,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(Fo,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(jo,n.presence_penalty)}setIOAttributes(e,r){if(r.run.inputs)try{let n=r.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&e.setAttribute($i,n.model),n.stream!==void 0&&e.setAttribute(al,n.stream),n.extra_headers&&e.setAttribute(sl,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(Go,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(Vo,JSON.stringify(n.extra_body))),e.setAttribute(Ho,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${r.id}`,n)}if(r.run.outputs)try{let n=r.run.outputs,i=this.getUnifiedRunTokens(n);if(i&&(e.setAttribute(Di,i[0]),e.setAttribute(Ui,i[1]),e.setAttribute(Fi,i[0]+i[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(Lo,String(n.model)),n.id&&e.setAttribute(Jo,n.id),n.choices&&Array.isArray(n.choices)){let a=n.choices.map(o=>o.finish_reason).filter(o=>o).map(String);a.length>0&&e.setAttribute(Bo,a.join(", "))}if(n.service_tier&&e.setAttribute(Zo,n.service_tier),n.system_fingerprint&&e.setAttribute(Yo,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let a=n.usage_metadata;e.setAttribute(Bi,JSON.stringify(a)),a.input_token_details&&e.setAttribute(Xo,JSON.stringify(a.input_token_details)),a.output_token_details&&e.setAttribute(Qo,JSON.stringify(a.output_token_details))}}e.setAttribute(zo,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${r.id}`,n)}}getUnifiedRunTokens(e){if(!e)return null;let r=this.extractUnifiedRunTokens(e.usage_metadata);if(r)return r;let n=Object.keys(e);for(let o of n){let l=e[o];if(!(!l||typeof l!="object")&&(r=this.extractUnifiedRunTokens(l.usage_metadata),r||l.lc===1&&l.kwargs&&typeof l.kwargs=="object"&&(r=this.extractUnifiedRunTokens(l.kwargs.usage_metadata),r)))return r}let i=e.generations||[];if(!Array.isArray(i))return null;let a=Array.isArray(i[0])?i.flat():i;for(let o of a)if(typeof o=="object"&&o.message&&typeof o.message=="object"&&o.message.kwargs&&typeof o.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(o.message.kwargs.usage_metadata),r))return r;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}};var gf=Object.prototype.toString,yf=s(t=>gf.call(t)==="[object Error]","isError"),_f=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function la(t){if(!(t&&yf(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;let{message:r,stack:n}=t;return r==="Load failed"?n===void 0||"__sentry_captured__"in t:r.startsWith("error sending request for url")?!0:_f.has(r)}s(la,"isNetworkError");function bf(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}s(bf,"validateRetries");function An(t,e,{min:r=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<r)throw new TypeError(`Expected \`${t}\` to be \u2265 ${r}.`)}}s(An,"validateNumberOption");var ca=class extends Error{static{s(this,"AbortError")}constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function wf(t,e){let r=Math.max(1,t+1),n=e.randomize?Math.random()+1:1,i=Math.round(n*e.minTimeout*e.factor**(r-1));return i=Math.min(i,e.maxTimeout),i}s(wf,"calculateDelay");function Fl(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}s(Fl,"calculateRemainingTime");async function vf({error:t,attemptNumber:e,retriesConsumed:r,startTime:n,options:i}){let a=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(a instanceof ca)throw a.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-r):i.retries,l=i.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:a,attemptNumber:e,retriesLeft:o,retriesConsumed:r});if(await i.onFailedAttempt(c),Fl(n,l)<=0)throw a;let u=await i.shouldConsumeRetry(c),d=Fl(n,l);if(d<=0||o<=0)throw a;if(a instanceof TypeError&&!la(a)){if(u)throw a;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw a;if(!u)return i.signal?.throwIfAborted(),!1;let p=wf(r,i),h=Math.min(p,d);return h>0&&await new Promise((g,b)=>{let v=s(()=>{clearTimeout(P),i.signal?.removeEventListener("abort",v),b(i.signal.reason)},"onAbort"),P=setTimeout(()=>{i.signal?.removeEventListener("abort",v),g()},h);i.unref&&P.unref?.(),i.signal?.addEventListener("abort",v,{once:!0})}),i.signal?.throwIfAborted(),!0}s(vf,"onAttemptFailure");async function ua(t,e={}){if(e={...e},bf(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,An("factor",e.factor,{min:0,allowInfinity:!1}),An("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),An("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),An("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let r=0,n=0,i=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){r++;try{e.signal?.throwIfAborted();let a=await t(r);return e.signal?.throwIfAborted(),a}catch(a){await vf({error:a,attemptNumber:r,retriesConsumed:n,startTime:i,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}s(ua,"pRetry");var In=it(cn(),1),jl="default"in In.default?In.default.default:In.default;var xf=[408,425,429,500,502,503,504],Rr=class{static{s(this,"AsyncCaller")}constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new jl({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...r){return this.callWithOptions({},e,...r)}callWithOptions(e,r,...n){let i=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&i>0&&this.queueSizeBytes+i>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${i} bytes.`));i>0&&(this.queueSizeBytes+=i);let a=this.onFailedResponseHook,o=this.queue.add(()=>ua(()=>r(...n).catch(l=>{throw l instanceof Error?l:new Error(l)}),{async onFailedAttempt({error:l}){if(typeof l!="object"||l==null)throw l;let c="message"in l&&typeof l.message=="string"?l.message:void 0;if(c?.startsWith("Cancel")||c?.startsWith("TimeoutError")||c?.startsWith("AbortError")||"name"in l&&l.name==="TimeoutError"||"code"in l&&l.code==="ECONNABORTED")throw l;let u="response"in l?l.response:void 0;if(a&&await a(u))return;let d=u?.status??("status"in l?l.status:void 0);if(d!=null&&(typeof d=="number"||typeof d=="string")&&!xf.includes(+d))throw l},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return i>0&&(o=o.finally(()=>{this.queueSizeBytes-=i})),e.signal?Promise.race([o,new Promise((l,c)=>{e.signal?.addEventListener("abort",()=>{c(new Error("AbortError"))})})]):o}};function da(t){return typeof t?._getType=="function"}s(da,"isLangChainMessage");function pa(t){let e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}s(pa,"convertLangChainMessageToExample");var fa=s(function(){let{crypto:t}=globalThis;if(t?.randomUUID)return fa=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))},"uuid4");var Ef=/^[a-z][a-z0-9+.-]*:/i,Bl=s(t=>Ef.test(t),"isAbsoluteURL"),me=s(t=>(me=Array.isArray,me(t)),"isArray"),ma=me;function ar(t){return typeof t!="object"?{}:t??{}}s(ar,"maybeObj");function ha(t){if(!t)return!0;for(let e in t)return!1;return!0}s(ha,"isEmptyObj");function Hl(t,e){return Object.prototype.hasOwnProperty.call(t,e)}s(Hl,"hasOwn");var zl=s((t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Ee(`${t} must be an integer`);if(e<0)throw new Ee(`${t} must be a positive integer`);return e},"validatePositiveInteger");var Gl=s(t=>{try{return JSON.parse(t)}catch{return}},"safeJSON");var Vl=s(t=>new Promise(e=>setTimeout(e,t)),"sleep");var dt="0.0.1";function Sf(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}s(Sf,"getDetectedPlatform");var Tf=s(()=>{let t=Sf();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":Wl(Deno.build.os),"X-Stainless-Arch":ql(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":Wl(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ql(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Af();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function Af(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let i=n[1]||0,a=n[2]||0,o=n[3]||0;return{browser:e,version:`${i}.${a}.${o}`}}}return null}s(Af,"getBrowserInfo");var ql=s(t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown","normalizeArch"),Wl=s(t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),"normalizePlatform"),If,Kl=s(()=>If??=Tf(),"getPlatformHeaders");function Jl(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Langsmith({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}s(Jl,"getDefaultFetch");function Cf(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}s(Cf,"makeReadableStream");function ga(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Cf({start(){},async pull(r){let{done:n,value:i}=await e.next();n?r.close():r.enqueue(i)},async cancel(){await e.return?.()}})}s(ga,"ReadableStreamFrom");async function Zl(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}s(Zl,"CancelReadableStream");var Yl=s(({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");var ya="RFC3986",_a=s(t=>String(t),"default_formatter"),ba={RFC1738:s(t=>String(t).replace(/%20/g,"+"),"RFC1738"),RFC3986:_a},Xl="RFC1738";var Cn=s((t,e)=>(Cn=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Cn(t,e)),"has"),Be=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var wa=1024,Ql=s((t,e,r,n,i)=>{if(t.length===0)return t;let a=t;if(typeof t=="symbol"?a=Symbol.prototype.toString.call(t):typeof t!="string"&&(a=String(t)),r==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let o="";for(let l=0;l<a.length;l+=wa){let c=a.length>=wa?a.slice(l,l+wa):a,u=[];for(let d=0;d<c.length;++d){let p=c.charCodeAt(d);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||i===Xl&&(p===40||p===41)){u[u.length]=c.charAt(d);continue}if(p<128){u[u.length]=Be[p];continue}if(p<2048){u[u.length]=Be[192|p>>6]+Be[128|p&63];continue}if(p<55296||p>=57344){u[u.length]=Be[224|p>>12]+Be[128|p>>6&63]+Be[128|p&63];continue}d+=1,p=65536+((p&1023)<<10|c.charCodeAt(d)&1023),u[u.length]=Be[240|p>>18]+Be[128|p>>12&63]+Be[128|p>>6&63]+Be[128|p&63]}o+=u.join("")}return o},"encode");function ec(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}s(ec,"is_buffer");function va(t,e){if(me(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}s(va,"maybe_map");var tc={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},rc=s(function(t,e){Array.prototype.push.apply(t,me(e)?e:[e])},"push_to_array"),Pf,re={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ql,encodeValuesOnly:!1,format:ya,formatter:_a,indices:!1,serializeDate(t){return(Pf??=Function.prototype.call.bind(Date.prototype.toISOString))(t)},skipNulls:!1,strictNullHandling:!1};function Rf(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}s(Rf,"is_non_nullish_primitive");var xa={};function nc(t,e,r,n,i,a,o,l,c,u,d,p,h,g,b,v,P,I){let S=t,A=I,R=0,$=!1;for(;(A=A.get(xa))!==void 0&&!$;){let B=A.get(t);if(R+=1,typeof B<"u"){if(B===R)throw new RangeError("Cyclic object value");$=!0}typeof A.get(xa)>"u"&&(R=0)}if(typeof u=="function"?S=u(e,S):S instanceof Date?S=h?.(S):r==="comma"&&me(S)&&(S=va(S,function(B){return B instanceof Date?h?.(B):B})),S===null){if(a)return c&&!v?c(e,re.encoder,P,"key",g):e;S=""}if(Rf(S)||ec(S)){if(c){let B=v?e:c(e,re.encoder,P,"key",g);return[b?.(B)+"="+b?.(c(S,re.encoder,P,"value",g))]}return[b?.(e)+"="+b?.(String(S))]}let N=[];if(typeof S>"u")return N;let j;if(r==="comma"&&me(S))v&&c&&(S=va(S,c)),j=[{value:S.length>0?S.join(",")||null:void 0}];else if(me(u))j=u;else{let B=Object.keys(S);j=d?B.sort(d):B}let y=l?String(e).replace(/\./g,"%2E"):String(e),K=n&&me(S)&&S.length===1?y+"[]":y;if(i&&me(S)&&S.length===0)return K+"[]";for(let B=0;B<j.length;++B){let F=j[B],de=typeof F=="object"&&typeof F.value<"u"?F.value:S[F];if(o&&de===null)continue;let tt=p&&l?F.replace(/\./g,"%2E"):F,rt=me(S)?typeof r=="function"?r(K,tt):K:K+(p?"."+tt:"["+tt+"]");I.set(t,R);let vr=new WeakMap;vr.set(xa,I),rc(N,nc(de,rt,r,n,i,a,o,l,r==="comma"&&v&&me(S)?null:c,u,d,p,h,g,b,v,P,vr))}return N}s(nc,"inner_stringify");function Mf(t=re){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||re.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=ya;if(typeof t.format<"u"){if(!Cn(ba,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=ba[r],i=re.filter;(typeof t.filter=="function"||me(t.filter))&&(i=t.filter);let a;if(t.arrayFormat&&t.arrayFormat in tc?a=t.arrayFormat:"indices"in t?a=t.indices?"indices":"repeat":a=re.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let o=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:re.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:re.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:re.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:re.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?re.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:re.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:re.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:re.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:re.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:re.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:re.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:re.strictNullHandling}}s(Mf,"normalize_stringify_options");function ic(t,e={}){let r=t,n=Mf(e),i,a;typeof n.filter=="function"?(a=n.filter,r=a("",r)):me(n.filter)&&(a=n.filter,i=a);let o=[];if(typeof r!="object"||r===null)return"";let l=tc[n.arrayFormat],c=l==="comma"&&n.commaRoundTrip;i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);let u=new WeakMap;for(let h=0;h<i.length;++h){let g=i[h];n.skipNulls&&r[g]===null||rc(o,nc(r[g],g,l,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,u))}let d=o.join(n.delimiter),p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),d.length>0?p+d:""}s(ic,"stringify");function ac(t){return ic(t,{arrayFormat:"repeat"})}s(ac,"stringifyQuery");var On={off:0,error:200,warn:300,info:400,debug:500},Ea=s((t,e,r)=>{if(t){if(Hl(On,t))return t;be(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(On))}`)}},"parseLogLevel");function Mr(){}s(Mr,"noop");function kn(t,e,r){return!e||On[t]>On[r]?Mr:e[t].bind(e)}s(kn,"makeLogFn");var Lf={error:Mr,warn:Mr,info:Mr,debug:Mr},sc=new WeakMap;function be(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Lf;let n=sc.get(e);if(n&&n[0]===r)return n[1];let i={error:kn("error",e,r),warn:kn("warn",e,r),info:kn("info",e,r),debug:kn("debug",e,r)};return sc.set(e,[r,i]),i}s(be,"loggerFor");var Ze=s(t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"||e.toLowerCase()==="x-tenant-id"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t),"formatRequestDetails");async function Pn(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:a}=e,o=await(async()=>{if(r.status===204)return null;if(e.options.__binaryResponse)return r;let c=r.headers.get("content-type")?.split(";")[0]?.trim();return c?.includes("application/json")||c?.endsWith("+json")?r.headers.get("content-length")==="0"?void 0:await r.json():await r.text()})();return be(t).debug(`[${n}] response parsed`,Ze({retryOfRequestLogID:i,url:r.url,status:r.status,body:o,durationMs:Date.now()-a})),o}s(Pn,"defaultParseResponse");var $f=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},oc=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Nr,Lt=class t extends Promise{static{s(this,"APIPromise")}constructor(e,r,n=Pn){super(i=>{i(null)}),Object.defineProperty(this,"responsePromise",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"parseResponse",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"parsedPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Nr.set(this,void 0),$f(this,Nr,e,"f")}_thenUnwrap(e){return new t(oc(this,Nr,"f"),this.responsePromise,async(r,n)=>e(await this.parseResponse(r,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(oc(this,Nr,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Nr=new WeakMap;var Df=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},Uf=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Rn,$t=class{static{s(this,"AbstractPage")}constructor(e,r,n,i){Rn.set(this,void 0),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Df(this,Rn,e,"f"),this.options=i,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new Ee("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Uf(this,Rn,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Rn=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Lr=class extends Lt{static{s(this,"PagePromise")}constructor(e,r,n){super(e,r,async(i,a)=>new n(i,a.response,await Pn(i,a),a.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},Mn=class extends $t{static{s(this,"OffsetPaginationTopLevelArray")}constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=n||[]}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.options.query.offset??0,r=this.getPaginatedItems().length,n=e+r;return{...this.options,query:{...ar(this.options.query),offset:n}}}},Nn=class extends $t{static{s(this,"OffsetPaginationIssues")}constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=n||[]}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.options.query.offset??0,r=this.getPaginatedItems().length,n=e+r;return{...this.options,query:{...ar(this.options.query),offset:n}}}};var Ln=class extends $t{static{s(this,"OffsetPaginationOnlineEvaluators")}constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"evaluators",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"total",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.evaluators=n.evaluators||[],this.total=n.total||0}getPaginatedItems(){return this.evaluators??[]}nextPageRequestOptions(){let e=this.options.query.offset??0,r=this.getPaginatedItems().length,n=e+r;return{...this.options,query:{...ar(this.options.query),offset:n}}}};var He=class extends $t{static{s(this,"ItemsCursorPostPagination")}constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"next_cursor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=n.items||[],this.next_cursor=n.next_cursor||""}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.next_cursor;return e?{...this.options,body:{...ar(this.options.body),cursor:e}}:null}},sr=class extends $t{static{s(this,"ItemsCursorGetPagination")}constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"next_cursor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=n.items||[],this.next_cursor=n.next_cursor||""}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.next_cursor;return e?{...this.options,query:{...ar(this.options.query),cursor:e}}:null}};var Sa=s(()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}},"checkFileSupport");function $n(t,e,r){return Sa(),new File(t,e??"unknown_file",r)}s($n,"makeFile");function lc(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}s(lc,"getName");var cc=s(t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function","isAsyncIterable");var uc=s(t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function","isBlobLike"),jf=s(t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&uc(t),"isFileLike"),Bf=s(t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function","isResponseLike");async function Dn(t,e,r){if(Sa(),t=await t,jf(t))return t instanceof File?t:$n([await t.arrayBuffer()],t.name);if(Bf(t)){let i=await t.blob();return e||=new URL(t.url).pathname.split(/[\\/]/).pop(),$n(await Ta(i),e,r)}let n=await Ta(t);if(e||=lc(t),!r?.type){let i=n.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof i=="string"&&(r={...r,type:i})}return $n(n,e,r)}s(Dn,"toFile");async function Ta(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(uc(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(cc(t))for await(let r of t)e.push(...await Ta(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${Hf(t)}`)}return e}s(Ta,"getBytes");function Hf(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}s(Hf,"propsForError");var U=class{static{s(this,"APIResource")}constructor(e){Object.defineProperty(this,"_client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._client=e}};function pc(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}s(pc,"encodeURIPath");var dc=Object.freeze(Object.create(null)),Gf=s((t=pc)=>s(function(r,...n){if(r.length===1)return r[0];let i=!1,a=[],o=r.reduce((d,p,h)=>{/[?#]/.test(p)&&(i=!0);let g=n[h],b=(i?encodeURIComponent:t)(""+g);return h!==n.length&&(g==null||typeof g=="object"&&g.toString===Object.getPrototypeOf(Object.getPrototypeOf(g.hasOwnProperty??dc)??dc)?.toString)&&(b=g+"",a.push({start:d.length+p.length,length:b.length,error:`Value of type ${Object.prototype.toString.call(g).slice(8,-1)} is not a valid path parameter`})),d+p+(h===n.length?"":b)},""),l=o.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=c.exec(l))!==null;)a.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(a.sort((d,p)=>d.start-p.start),a.length>0){let d=0,p=a.reduce((h,g)=>{let b=" ".repeat(g.start-d),v="^".repeat(g.length);return d=g.start+g.length,h+b+v},"");throw new Ee(`Path parameters result in path with invalid segments:
10
+ ${a.map(h=>h.error).join(`
11
+ `)}
12
+ ${o}
13
+ ${p}`)}return o},"path"),"createPathTagFunction"),O=Gf(pc);var or=class extends U{static{s(this,"Items")}create(e,r,n){let{extend_trace_retention:i,...a}=r;return this._client.post(O`/api/v1/platform/annotation-queues/${e}/items`,{query:{extend_trace_retention:i},body:a,...n})}update(e,r,n){let{queue_id:i,...a}=r;return this._client.patch(O`/api/v1/platform/annotation-queues/${i}/items/${e}`,{body:a,...n})}list(e,r,n){return this._client.getAPIList(O`/api/v1/platform/annotation-queues/${e}/items`,sr,{query:r,...n})}createStatus(e,r,n){return this._client.post(O`/api/v1/platform/annotation-queues/items/${e}/status`,{body:r,...n})}deleteAll(e,r,n){return this._client.post(O`/api/v1/platform/annotation-queues/${e}/items/delete`,{body:r,...n})}retrieveCount(e,r,n){return this._client.get(O`/api/v1/platform/annotation-queues/${e}/items/count`,{query:r,...n})}retrievePlacement(e,r,n){let{queue_id:i}=r;return this._client.get(O`/api/v1/platform/annotation-queues/${i}/items/${e}/placement`,n)}};var lr=class extends U{static{s(this,"Runs")}create(e,r,n){let{body:i,extend_trace_retention:a}=r;return this._client.post(O`/api/v1/annotation-queues/${e}/runs`,{query:{extend_trace_retention:a},body:i,...n})}update(e,r,n){let{queue_id:i,...a}=r;return this._client.patch(O`/api/v1/annotation-queues/${i}/runs/${e}`,{body:a,...n})}list(e,r={},n){return this._client.get(O`/api/v1/annotation-queues/${e}/runs`,{query:r,...n})}createByKey(e,r,n){let{body:i,extend_trace_retention:a}=r;return this._client.post(O`/api/v1/annotation-queues/${e}/runs/by-key`,{query:{extend_trace_retention:a},body:i,...n})}deleteAll(e,r,n){return this._client.post(O`/api/v1/annotation-queues/${e}/runs/delete`,{body:r,...n})}deleteQueue(e,r,n){let{queue_id:i}=r;return this._client.delete(O`/api/v1/annotation-queues/${i}/runs/${e}`,n)}};var Ye=class extends U{static{s(this,"AnnotationQueues")}constructor(){super(...arguments),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new lr(this._client)}),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:new or(this._client)})}retrieve(e,r){return this._client.get(O`/api/v1/annotation-queues/${e}`,r)}update(e,r,n){return this._client.patch(O`/api/v1/annotation-queues/${e}`,{body:r,...n})}delete(e,r){return this._client.delete(O`/api/v1/annotation-queues/${e}`,r)}annotationQueues(e,r){return this._client.post("/api/v1/annotation-queues",{body:e,...r})}createRunStatus(e,r,n){return this._client.post(O`/api/v1/annotation-queues/status/${e}`,{body:r,...n})}export(e,r,n){return this._client.post(O`/api/v1/annotation-queues/${e}/export`,{body:r,...n})}populate(e,r){return this._client.post("/api/v1/annotation-queues/populate",{body:e,...r})}retrieveAnnotationQueues(e={},r){return this._client.getAPIList("/api/v1/annotation-queues",Mn,{query:e,...r})}retrieveQueues(e,r){return this._client.get(O`/api/v1/annotation-queues/${e}/queues`,r)}retrieveRun(e,r,n){let{queue_id:i,...a}=r;return this._client.get(O`/api/v1/annotation-queues/${i}/run/${e}`,{query:a,...n})}retrieveSize(e,r={},n){return this._client.get(O`/api/v1/annotation-queues/${e}/size`,{query:r,...n})}retrieveTotalArchived(e,r={},n){return this._client.get(O`/api/v1/annotation-queues/${e}/total_archived`,{query:r,...n})}retrieveTotalSize(e,r){return this._client.get(O`/api/v1/annotation-queues/${e}/total_size`,r)}};Ye.Runs=lr;Ye.Items=or;var cr=class extends U{static{s(this,"ExperimentRuns")}query(e,r,n){return this._client.getAPIList(O`/api/v2/datasets/${e}/experiment-runs`,He,{body:r,method:"post",...n})}};var pt=class extends U{static{s(this,"Datasets")}constructor(){super(...arguments),Object.defineProperty(this,"experimentRuns",{enumerable:!0,configurable:!0,writable:!0,value:new cr(this._client)})}};pt.ExperimentRuns=cr;var Dt=class extends U{static{s(this,"Info")}list(e){return this._client.get("/api/v1/info",e)}};var Ut=class extends U{static{s(this,"Issues")}retrieve(e,r){return this._client.get(O`/api/v1/platform/issues/${e}`,r)}list(e={},r){return this._client.getAPIList("/api/v1/platform/issues",Nn,{query:e,...r})}};var fc=Symbol("brand.privateNullableHeaders");function*Kf(t){if(!t)return;if(fc in t){let{values:n,nulls:i}=t;yield*n.entries();for(let a of i)yield[a,null];return}let e=!1,r;t instanceof Headers?r=t.entries():ma(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let i=n[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let a=ma(n[1])?n[1]:[n[1]],o=!1;for(let l of a)l!==void 0&&(e&&!o&&(o=!0,yield[i,null]),yield[i,l])}}s(Kf,"iterateHeaders");var Z=s(t=>{let e=new Headers,r=new Set;for(let n of t){let i=new Set;for(let[a,o]of Kf(n)){let l=a.toLowerCase();i.has(l)||(e.delete(a),i.add(l)),o===null?(e.delete(a),r.add(l)):(e.append(a,o),r.delete(l))}}return{[fc]:!0,values:e,nulls:r}},"buildHeaders");var Ft=class extends U{static{s(this,"OnlineEvaluators")}create(e,r){return this._client.post("/api/v1/platform/evaluators",{body:e,...r})}retrieve(e,r){return this._client.get(O`/api/v1/platform/evaluators/${e}`,r)}update(e,r,n){return this._client.patch(O`/api/v1/platform/evaluators/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/api/v1/platform/evaluators",Ln,{query:e,...r})}delete(e,r={},n){let{delete_run_rules:i}=r??{};return this._client.delete(O`/api/v1/platform/evaluators/${e}`,{query:{delete_run_rules:i},...n,headers:Z([{Accept:"*/*"},n?.headers])})}bulkDelete(e,r){let{evaluator_ids:n,delete_run_rules:i}=e;return this._client.delete("/api/v1/platform/evaluators",{query:{evaluator_ids:n,delete_run_rules:i},...r})}spend(e,r){return this._client.get("/api/v1/platform/evaluators/spend",{query:e,...r})}};var ur=class extends U{static{s(this,"Runs")}retrieve(e,r,n){let{share_token:i,Accept:a,...o}=r;return this._client.get(O`/api/v2/public/${i}/run/${e}`,{query:o,...n,headers:Z([{...a!=null?{Accept:a}:void 0},n?.headers])})}query(e,r,n){let{Accept:i,...a}=r;return this._client.post(O`/api/v2/public/${e}/runs/query`,{body:a,...n,headers:Z([{...i!=null?{Accept:i}:void 0},n?.headers])})}};var ft=class extends U{static{s(this,"Public")}constructor(){super(...arguments),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new ur(this._client)})}};ft.Runs=ur;var dr=class extends U{static{s(this,"Share")}create(e,r,n){return this._client.post(O`/api/v2/runs/${e}/share`,{body:r,...n})}delete(e,r,n){return this._client.delete(O`/api/v2/runs/${e}/share`,{body:r,...n,headers:Z([{Accept:"*/*"},n?.headers])})}};var mt=class extends U{static{s(this,"Runs")}constructor(){super(...arguments),Object.defineProperty(this,"share",{enumerable:!0,configurable:!0,writable:!0,value:new dr(this._client)}),Object.defineProperty(this,"retrieve",{enumerable:!0,configurable:!0,writable:!0,value:this.retrieveV2}),Object.defineProperty(this,"query",{enumerable:!0,configurable:!0,writable:!0,value:this.queryV2})}getURL(e,r,n){return this._client.get(O`/api/v2/runs/${e}/url`,{query:r,...n})}queryV2(e,r){let{Accept:n,...i}=e;return this._client.getAPIList("/api/v2/runs/query",He,{body:i,method:"post",...r,headers:Z([{...n!=null?{Accept:n}:void 0},r?.headers])})}retrieveV2(e,r,n){let{Accept:i,...a}=r;return this._client.get(O`/api/v2/runs/${e}`,{query:a,...n,headers:Z([{...i!=null?{Accept:i}:void 0},n?.headers])})}};mt.Share=dr;var pr=class extends U{static{s(this,"Boxes")}create(e,r){return this._client.post("/api/v2/sandboxes/boxes",{body:e,...r})}retrieve(e,r){return this._client.get(O`/api/v2/sandboxes/boxes/${e}`,r)}update(e,r,n){return this._client.patch(O`/api/v2/sandboxes/boxes/${e}`,{body:r,...n})}list(e={},r){return this._client.get("/api/v2/sandboxes/boxes",{query:e,...r})}delete(e,r){return this._client.delete(O`/api/v2/sandboxes/boxes/${e}`,{...r,headers:Z([{Accept:"*/*"},r?.headers])})}createSnapshot(e,r,n){return this._client.post(O`/api/v2/sandboxes/boxes/${e}/snapshot`,{body:r,...n})}generateServiceURL(e,r,n){return this._client.post(O`/api/v2/sandboxes/boxes/${e}/service-url`,{body:r,...n})}getStatus(e,r){return this._client.get(O`/api/v2/sandboxes/boxes/${e}/status`,r)}start(e,r){return this._client.post(O`/api/v2/sandboxes/boxes/${e}/start`,r)}stop(e,r){return this._client.post(O`/api/v2/sandboxes/boxes/${e}/stop`,{...r,headers:Z([{Accept:"*/*"},r?.headers])})}};var fr=class extends U{static{s(this,"Registries")}create(e,r){return this._client.post("/api/v2/sandboxes/registries",{body:e,...r})}retrieve(e,r){return this._client.get(O`/api/v2/sandboxes/registries/${e}`,r)}update(e,r,n){return this._client.patch(O`/api/v2/sandboxes/registries/${e}`,{body:r,...n})}list(e={},r){return this._client.get("/api/v2/sandboxes/registries",{query:e,...r})}delete(e,r){return this._client.delete(O`/api/v2/sandboxes/registries/${e}`,{...r,headers:Z([{Accept:"*/*"},r?.headers])})}};var mr=class extends U{static{s(this,"Snapshots")}create(e,r){return this._client.post("/api/v2/sandboxes/snapshots",{body:e,...r})}retrieve(e,r){return this._client.get(O`/api/v2/sandboxes/snapshots/${e}`,r)}list(e={},r){return this._client.get("/api/v2/sandboxes/snapshots",{query:e,...r})}delete(e,r){return this._client.delete(O`/api/v2/sandboxes/snapshots/${e}`,{...r,headers:Z([{Accept:"*/*"},r?.headers])})}};var ze=class extends U{static{s(this,"Sandboxes")}constructor(){super(...arguments),Object.defineProperty(this,"boxes",{enumerable:!0,configurable:!0,writable:!0,value:new pr(this._client)}),Object.defineProperty(this,"registries",{enumerable:!0,configurable:!0,writable:!0,value:new fr(this._client)}),Object.defineProperty(this,"snapshots",{enumerable:!0,configurable:!0,writable:!0,value:new mr(this._client)})}};ze.Boxes=pr;ze.Registries=fr;ze.Snapshots=mr;var jt=class extends U{static{s(this,"Threads")}listTraces(e,r,n){return this._client.getAPIList(O`/api/v2/threads/${e}/traces`,sr,{query:r,...n})}query(e,r){return this._client.getAPIList("/api/v2/threads/query",He,{body:e,method:"post",...r})}stats(e,r,n){return this._client.get(O`/api/v2/threads/${e}/stats`,{query:r,...n})}};var Bt=class extends U{static{s(this,"Traces")}listRuns(e,r,n){let{Accept:i,...a}=r;return this._client.get(O`/api/v2/traces/${e}/runs`,{query:a,...n,headers:Z([{...i!=null?{Accept:i}:void 0},n?.headers])})}query(e,r){return this._client.getAPIList("/api/v2/traces/query",He,{body:e,method:"post",...r})}};var hr=s(t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0},"readEnv");var tm=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},mc=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Aa,Ia,Un,hc,z=class{static{s(this,"Langsmith")}constructor({baseURL:e=hr("LANGCHAIN_BASE_URL"),apiKey:r=hr("LANGSMITH_API_KEY")??null,tenantID:n=hr("LANGSMITH_TENANT_ID")??null,...i}={}){Aa.add(this),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tenantID",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"baseURL",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logLevel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Un.set(this,void 0),Object.defineProperty(this,"idempotencyHeader",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"datasets",{enumerable:!0,configurable:!0,writable:!0,value:new pt(this)}),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new mt(this)}),Object.defineProperty(this,"threads",{enumerable:!0,configurable:!0,writable:!0,value:new jt(this)}),Object.defineProperty(this,"traces",{enumerable:!0,configurable:!0,writable:!0,value:new Bt(this)}),Object.defineProperty(this,"onlineEvaluators",{enumerable:!0,configurable:!0,writable:!0,value:new Ft(this)}),Object.defineProperty(this,"public",{enumerable:!0,configurable:!0,writable:!0,value:new ft(this)}),Object.defineProperty(this,"annotationQueues",{enumerable:!0,configurable:!0,writable:!0,value:new Ye(this)}),Object.defineProperty(this,"info",{enumerable:!0,configurable:!0,writable:!0,value:new Dt(this)}),Object.defineProperty(this,"issues",{enumerable:!0,configurable:!0,writable:!0,value:new Ut(this)}),Object.defineProperty(this,"sandboxes",{enumerable:!0,configurable:!0,writable:!0,value:new ze(this)});let a={apiKey:r,tenantID:n,...i,baseURL:e||"https://api.smith.langchain.com/"};this.baseURL=a.baseURL,this.timeout=a.timeout??Ia.DEFAULT_TIMEOUT,this.logger=a.logger??console;let o="warn";this.logLevel=o,this.logLevel=Ea(a.logLevel,"ClientOptions.logLevel",this)??Ea(hr("LANGCHAIN_LOG"),"process.env['LANGCHAIN_LOG']",this)??o,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Jl(),tm(this,Un,Yl,"f");let l=hr("LANGCHAIN_CUSTOM_HEADERS");if(l){let c={};for(let u of l.split(`
14
+ `)){let d=u.indexOf(":");d>=0&&(c[u.substring(0,d).trim()]=u.substring(d+1).trim())}a.defaultHeaders={...c,...a.defaultHeaders}}this._options=a,this.apiKey=r,this.tenantID=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,tenantID:this.tenantID,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(this.apiKey&&e.get("x-api-key"))&&!r.has("x-api-key")&&!(this.tenantID&&e.get("x-tenant-id"))&&!r.has("x-tenant-id"))throw new Error('Could not resolve authentication method. Expected either apiKey or tenantID to be set. Or for one of the "X-API-Key" or "X-Tenant-Id" headers to be explicitly omitted')}async authHeaders(e){return Z([await this.apiKeyAuth(e),await this.tenantIDAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return Z([{"X-API-Key":this.apiKey}])}async tenantIDAuth(e){if(this.tenantID!=null)return Z([{"X-Tenant-Id":this.tenantID}])}stringifyQuery(e){return ac(e)}getUserAgent(){return`${this.constructor.name}/JS ${dt}`}defaultIdempotencyKey(){return`stainless-node-retry-${fa()}`}makeStatusError(e,r,n,i){return ce.generate(e,r,n,i)}buildURL(e,r,n){let i=!mc(this,Aa,"m",hc).call(this)&&n||this.baseURL,a=Bl(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),l=Object.fromEntries(a.searchParams);return(!ha(o)||!ha(l))&&(r={...l,...o,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(a.search=this.stringifyQuery(r)),a.toString()}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:r,...i})))}request(e,r=null){return new Lt(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let i=await e,a=i.maxRetries??this.maxRetries;r==null&&(r=a),await this.prepareOptions(i);let{req:o,url:l,timeout:c}=await this.buildRequest(i,{retryCount:a-r});await this.prepareRequest(o,{url:l,options:i});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=n===void 0?"":`, retryOf: ${n}`,p=Date.now();if(be(this).debug(`[${u}] sending request`,Ze({retryOfRequestLogID:n,method:i.method,url:l,options:i,headers:o.headers})),i.signal?.aborted)throw new ct;let h=new AbortController,g=await this.fetchWithTimeout(l,o,c,h).catch(Or),b=Date.now();if(g instanceof globalThis.Error){let P=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new ct;let I=Rl(g)||/timed? ?out/i.test(String(g)+("cause"in g?String(g.cause):""));if(r)return be(this).info(`[${u}] connection ${I?"timed out":"failed"} - ${P}`),be(this).debug(`[${u}] connection ${I?"timed out":"failed"} (${P})`,Ze({retryOfRequestLogID:n,url:l,durationMs:b-p,message:g.message})),this.retryRequest(i,r,n??u);throw be(this).info(`[${u}] connection ${I?"timed out":"failed"} - error; no more retries left`),be(this).debug(`[${u}] connection ${I?"timed out":"failed"} (error; no more retries left)`,Ze({retryOfRequestLogID:n,url:l,durationMs:b-p,message:g.message})),I?new At:new Je({cause:g})}let v=`[${u}${d}] ${o.method} ${l} ${g.ok?"succeeded":"failed"} with status ${g.status} in ${b-p}ms`;if(!g.ok){let P=await this.shouldRetry(g);if(r&&P){let N=`retrying, ${r} attempts remaining`;return await Zl(g.body),be(this).info(`${v} - ${N}`),be(this).debug(`[${u}] response error (${N})`,Ze({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:b-p})),this.retryRequest(i,r,n??u,g.headers)}let I=P?"error; no more retries left":"error; not retryable";be(this).info(`${v} - ${I}`);let S=await g.text().catch(N=>Or(N).message),A=Gl(S),R=A?void 0:S;throw be(this).debug(`[${u}] response error (${I})`,Ze({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,message:R,durationMs:Date.now()-p})),this.makeStatusError(g.status,A,R,g.headers)}return be(this).info(v),be(this).debug(`[${u}] response start`,Ze({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:b-p})),{response:g,options:i,controller:h,requestLogID:u,retryOfRequestLogID:n,startTime:p}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(i=>({method:"get",path:e,...i})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new Lr(this,n,e)}async fetchWithTimeout(e,r,n,i){let{signal:a,method:o,...l}=r||{},c=this._makeAbort(i);a&&a.addEventListener("abort",c,{once:!0});let u=setTimeout(c,n),d=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,p={signal:i.signal,...d?{duplex:"half"}:{},method:"GET",...l};o&&(p.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,p)}finally{clearTimeout(u)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,i){let a,o=i?.get("retry-after-ms");if(o){let c=parseFloat(o);Number.isNaN(c)||(a=c)}let l=i?.get("retry-after");if(l&&!a){let c=parseFloat(l);Number.isNaN(c)?a=Date.parse(l)-Date.now():a=c*1e3}if(a===void 0){let c=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(r,c)}return await Vl(a),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let a=r-e,o=Math.min(.5*Math.pow(2,a),16),l=1-Math.random()*.25;return o*l*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:i,path:a,query:o,defaultBaseURL:l}=n,c=this.buildURL(a,o,l);"timeout"in n&&zl("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:u,body:d}=this.buildBody({options:n}),p=await this.buildHeaders({options:e,method:i,bodyHeaders:u,retryCount:r});return{req:{method:i,headers:p,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let a={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);let o=Z([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Kl()},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=Z([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:ga(e)}:typeof e=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:mc(this,Un,"f").call(this,{body:e,headers:n})}};Ia=z,Un=new WeakMap,Aa=new WeakSet,hc=s(function(){return this.baseURL!=="https://api.smith.langchain.com/"},"_Langsmith_baseURLOverridden");Object.defineProperty(z,"Langsmith",{enumerable:!0,configurable:!0,writable:!0,value:Ia});Object.defineProperty(z,"DEFAULT_TIMEOUT",{enumerable:!0,configurable:!0,writable:!0,value:9e4});Object.defineProperty(z,"LangsmithError",{enumerable:!0,configurable:!0,writable:!0,value:Ee});Object.defineProperty(z,"APIError",{enumerable:!0,configurable:!0,writable:!0,value:ce});Object.defineProperty(z,"APIConnectionError",{enumerable:!0,configurable:!0,writable:!0,value:Je});Object.defineProperty(z,"APIConnectionTimeoutError",{enumerable:!0,configurable:!0,writable:!0,value:At});Object.defineProperty(z,"APIUserAbortError",{enumerable:!0,configurable:!0,writable:!0,value:ct});Object.defineProperty(z,"NotFoundError",{enumerable:!0,configurable:!0,writable:!0,value:Ot});Object.defineProperty(z,"ConflictError",{enumerable:!0,configurable:!0,writable:!0,value:Pt});Object.defineProperty(z,"RateLimitError",{enumerable:!0,configurable:!0,writable:!0,value:Mt});Object.defineProperty(z,"BadRequestError",{enumerable:!0,configurable:!0,writable:!0,value:It});Object.defineProperty(z,"AuthenticationError",{enumerable:!0,configurable:!0,writable:!0,value:Ct});Object.defineProperty(z,"InternalServerError",{enumerable:!0,configurable:!0,writable:!0,value:Nt});Object.defineProperty(z,"PermissionDeniedError",{enumerable:!0,configurable:!0,writable:!0,value:kt});Object.defineProperty(z,"UnprocessableEntityError",{enumerable:!0,configurable:!0,writable:!0,value:Rt});Object.defineProperty(z,"toFile",{enumerable:!0,configurable:!0,writable:!0,value:Dn});z.Datasets=pt;z.Runs=mt;z.Threads=jt;z.Traces=Bt;z.OnlineEvaluators=Ft;z.Public=ft;z.AnnotationQueues=Ye;z.Info=Dt;z.Issues=Ut;z.Sandboxes=ze;var $r={CLICKHOUSE_ONLY:"clickhouse_only",SMITHDB_ONLY:"smithdb_only",DUAL:"dual"};function gc(t){let e=t??{},r=!!(e.ch_query_enabled??!0),n=!!(e.sdb_query_enabled??!1);return!r&&n?$r.SMITHDB_ONLY:r&&n?$r.DUAL:$r.CLICKHOUSE_ONLY}s(gc,"getQueryBackend");function jn(t){return`Invalid prompt identifier format: "${t}". Expected one of:
15
+ - "prompt-name" (for private prompts)
16
+ - "owner/prompt-name" (for prompts with explicit owner)
17
+ - "prompt-name:commit-hash" (with commit reference)
18
+ - "owner/prompt-name:commit-hash" (with owner and commit)`}s(jn,"getInvalidPromptIdentifierMsg");var Ca=class extends Error{static{s(this,"LangSmithConflictError")}constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}},ka=class extends Error{static{s(this,"LangSmithNotFoundError")}constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}};function Bn(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}s(Bn,"isLangSmithNotFoundError");function yc(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithConflictError"}s(yc,"isLangSmithConflictError");async function C(t,e,r){let n;if(t.ok){r&&(n=await t.text());return}if(t.status===403)try{(await t.json())?.error==="org_scoped_key_requires_workspace"&&(n="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{let l=new Error(`${t.status} ${t.statusText}`);throw l.status=t?.status,l}if(n===void 0)try{n=await t.text()}catch{n=""}let i=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${n}`;if(t.status===404)throw new ka(i);if(t.status===409)throw new Ca(i);let a=new Error(i);throw a.status=t.status,a}s(C,"raiseForStatus");var _c="ERR_CONFLICTING_ENDPOINTS",Fn=class extends Error{static{s(this,"ConflictingEndpointsError")}constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:_c}),this.name="ConflictingEndpointsError"}};function bc(t){return typeof t=="object"&&t!==null&&t.code===_c}s(bc,"isConflictingEndpointsError");function he(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(jn(t));let[e,r]=t.split(":"),n=r||"latest";if(e.includes("/")){let[i,a]=e.split("/",2);if(!i||!a)throw new Error(jn(t));return[i,a,n]}else{if(!e)throw new Error(jn(t));return["-",e,n]}}s(he,"parseHubIdentifier");var rm=10,nm=1e4,wc="created_at";function im(t){return new Promise(e=>setTimeout(e,t))}s(im,"sleep");function am(t){return typeof t=="object"&&t!==null&&t.code==="EEXIST"}s(am,"isEEXIST");function vc(t){try{return Tt(Ne.join(t,wc)).split(`
19
+ `)}catch{return}}s(vc,"lockMetadataLines");function sm(t){let e=vc(t);if(e&&e[0]&&e[0].trim()){let r=Date.parse(e[0].trim());if(!Number.isNaN(r))return r}return Pl(t)}s(sm,"lockCreatedAtMs");function om(t){let e=vc(t);if(e&&e.length>=2&&e[1].trim())return e[1].trim()}s(om,"lockOwner");async function lm(t){let e=sm(t);return e===void 0||Date.now()-e<=nm?!1:(await _n(t),!0)}s(lm,"removeStaleLock");async function xc(t,e){let r=`${t}.oauth.lock.lock`,n=Ne.dirname(r);n&&await yn(n);let i=globalThis.crypto.randomUUID();for(;;){try{await Ol(r)}catch(a){if(!am(a))throw a;if(!await lm(r)){if(Date.now()>=e)throw new Error("timed out acquiring OAuth refresh lock");await im(Math.min(rm,Math.max(0,e-Date.now())))}continue}try{await nr(Ne.join(r,wc),`${new Date().toISOString()}
20
+ ${i}
21
+ `)}catch(a){throw await _n(r),a}break}return{async release(){om(r)===i&&await _n(r)}}}s(xc,"acquireOAuthRefreshLock");var Hn="https://api.smith.langchain.com",cm="langsmith-cli",um=6e4,dm=1e4;function pm(){let t=Pr();return t==="browser"||t==="webworker"}s(pm,"isBrowserLikeRuntime");function fm(){let t=ae("LANGSMITH_CONFIG_FILE");if(t)return t;let e=ae("HOME")??ae("USERPROFILE");if(e)return Ne.join(e,".langsmith","config.json")}s(fm,"getProfileConfigPath");function mm(t){let e=ae("LANGSMITH_PROFILE");if(e)return e;if(t.current_profile)return t.current_profile;if(t.profiles?.default)return"default"}s(mm,"resolveProfileName");function hm(){if(pm())return;let t=fm();if(!(!t||!ir(t)))try{let e=JSON.parse(Tt(t)),r=mm(e),n=r?e.profiles?.[r]:void 0;return!r||!n?void 0:{configPath:t,config:e,profileName:r,profile:n}}catch{return}}s(hm,"loadProfileState");function Ce(t){return t!=null&&t.trim()!==""}s(Ce,"hasValue");function ht(t){return t?.trim().replace(/^["']|["']$/g,"")}s(ht,"trimConfigValue");function Ec(t){let e=t.oauth;if(!e?.refresh_token)return!1;if(!e.access_token)return!0;if(!e.expires_at)return!1;let r=Date.parse(e.expires_at);return Number.isNaN(r)?!1:r<=Date.now()+um}s(Ec,"shouldRefreshProfileToken");function gm(t){let e=t;for(;e.endsWith("/");)e=e.slice(0,-1);let r="/api/v1";return e.endsWith(r)?e.slice(0,-r.length):e}s(gm,"normalizeConfigUrl");function ym(t,e){t.oauth??={},e.access_token&&(t.oauth.access_token=e.access_token),e.refresh_token&&(t.oauth.refresh_token=e.refresh_token),typeof e.expires_in=="number"&&e.expires_in>0&&(t.oauth.expires_at=new Date(Date.now()+e.expires_in*1e3).toISOString())}s(ym,"applyTokenResponse");function Sc(t){return t.reason??new Error("The operation was aborted.")}s(Sc,"getAbortReason");async function _m(t,e){if(!e)return t;if(e.aborted)throw Sc(e);let r,n=new Promise((i,a)=>{let o=s(()=>{a(Sc(e))},"onAbort");e.addEventListener("abort",o,{once:!0}),r=s(()=>{e.removeEventListener("abort",o)},"cleanup")});try{return await Promise.race([t,n])}finally{r?.()}}s(_m,"waitForAbortSignal");function Tc(){let t=hm(),e=t?.profile;if(!t||!e)return{};let r=ht(e.api_key),n=ht(e.oauth?.access_token),i=ht(e.oauth?.refresh_token);return{apiUrl:e.api_url,apiKey:r,workspaceId:e.workspace_id,oauthAccessToken:n,oauthRefreshToken:i,profileAuth:r||n||i?new Oa(t):void 0}}s(Tc,"loadProfileClientConfig");var Oa=class{static{s(this,"ProfileAuth")}constructor(e){Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"refreshPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"managedAuthorizationValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.rememberProfileAuthHeader(this.currentAuthHeader())}currentAuthHeader(){let e=bm(this.state.profile);return this.rememberProfileAuthHeader(e),e}async getAuthHeader(e,r){Ec(this.state.profile)&&(this.refreshPromise||(this.refreshPromise=this.refreshOAuthToken(e).finally(()=>{this.refreshPromise=void 0})),await _m(this.refreshPromise,r));let n=Ac(this.state.profile);return this.rememberProfileAuthHeader(n),n}isProfileAuthorizationHeader(e){return e===this.managedAuthorizationValue}reloadProfile(){try{let e=JSON.parse(Tt(this.state.configPath)),r=e.profiles?.[this.state.profileName];return r?(this.state.config=e,this.state.profile=r,r):void 0}catch{return}}async refreshOAuthToken(e){let r=this.state.profile.oauth?.refresh_token;if(!r)return;let n=ht(this.state.profile.api_url)??Hn,i=Date.now()+dm,a;try{if(a=await xc(this.state.configPath,i),this.reloadProfile()&&!Ec(this.state.profile))return;let l=new URLSearchParams({grant_type:"refresh_token",client_id:cm,refresh_token:this.state.profile.oauth?.refresh_token??r}),c=await e(`${gm(n)}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString(),signal:AbortSignal.timeout(Math.max(0,i-Date.now()))});if(!c.ok)return;let u=await c.json();if(!u.access_token)return;ym(this.state.profile,u),this.state.config.profiles??={},this.state.config.profiles[this.state.profileName]=this.state.profile,await nr(this.state.configPath,`${JSON.stringify(this.state.config,null,2)}
22
+ `)}catch{return}finally{await a?.release()}}rememberProfileAuthHeader(e){this.managedAuthorizationValue=e?.name==="Authorization"?e.value:void 0}};function bm(t){let e=ht(t.oauth?.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};if(!ht(t.oauth?.refresh_token))return Ac(t)}s(bm,"currentAuthHeaderFromProfile");function Ac(t){let e=ht(t.oauth?.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};let r=ht(t.api_key);if(r)return{name:"x-api-key",value:r}}s(Ac,"authHeaderFromProfile");var Ic="[...]",wm={result:"[Circular]"},Gn=[],gr=[],vm=new TextEncoder;function xm(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}s(xm,"defaultOptions");function zn(t){return vm.encode(t)}s(zn,"encodeString");function Cc(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}s(Cc,"serializeWellKnownTypes");function Em(t){return function(e,r){if(t){let n=t.call(this,e,r);if(n!==void 0)return n}return Cc(r)}}s(Em,"createDefaultReplacer");function kc(t){try{let i=function(d){let p=n(d);return p>r&&(r=p),p+2},a=function(d){return d===0?2:2+d*4},o=function(d){return d===void 0||typeof d=="function"||typeof d=="symbol"},l=function(d){return d===void 0||typeof d=="function"||typeof d=="symbol"?4:c(d)},c=function(d){if(d===null)return 4;if(d===void 0)return 0;let p=typeof d;if(p==="boolean")return 5;if(p==="number")return Number.isFinite(d)?d.toString().length:4;if(p==="bigint")return d.toString().length+2;if(p==="string")return i(d);if(p==="function"||p==="symbol")return 0;let h=d;if(h instanceof Date)return 26;if(h instanceof RegExp)return n(h.toString())+2;if(h instanceof Error){let b=h.name??"",v=h.message??"";return 22+n(b)+n(v)}if(typeof Buffer<"u"&&h instanceof Buffer)return 28+a(h.byteLength);if(ArrayBuffer.isView(h)){if(h instanceof DataView)return 2;let b=h.length??0,P=h instanceof Float32Array||h instanceof Float64Array?30:12;return 2+b*P}if(h instanceof ArrayBuffer)return 2;if(e.has(h))return 24;if(typeof h.toJSON=="function"){let b;try{b=h.toJSON("")}catch{return 16}e.add(h);let v=c(b);return e.delete(h),v}e.add(h);let g;if(Array.isArray(h)){g=2;let b=h.length;for(let v=0;v<b;v++)g+=l(h[v]),v<b-1&&(g+=1)}else if(h instanceof Map){g=2;let b=0;for(let[v,P]of h){if(o(P))continue;b>0&&(g+=1);let I=typeof v=="string"?v:String(v);g+=n(I)+3,g+=c(P),b++}}else if(h instanceof Set){g=2;let b=0;for(let v of h)b>0&&(g+=1),g+=l(v),b++}else{g=2;let b=0,v=Object.keys(h);for(let P=0;P<v.length;P++){let I=v[P],S=h[I];o(S)||(b>0&&(g+=1),g+=n(I)+3,g+=c(S),b++)}}return e.delete(h),g};s(i,"estimateString"),s(a,"estimateByteArrayJson"),s(o,"isDropped"),s(l,"estimateInArray"),s(c,"estimate");let e=new Set,r=0,n=typeof Buffer<"u"&&typeof Buffer.byteLength=="function"?d=>Buffer.byteLength(d,"utf8"):d=>d.length;return{size:c(t),maxStringLen:r}}catch{return{size:ge(t).length,maxStringLen:0}}}s(kc,"estimateSerializedSize");function ge(t,e,r,n,i){try{let a=JSON.stringify(t,Em(r),n);return zn(a)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
23
+ Context: ${e}`:""}`),zn("[Unserializable]");q("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
24
+ Context: ${e}`:""}`),typeof i>"u"&&(i=xm()),Ra(t,"",0,[],void 0,0,i);let o;try{gr.length===0?o=JSON.stringify(t,r,n):o=JSON.stringify(t,Sm(r),n)}catch{return zn("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Gn.length!==0;){let l=Gn.pop();l.length===4?Object.defineProperty(l[0],l[1],l[3]):l[0][l[1]]=l[2]}}return zn(o)}}s(ge,"serialize");function Pa(t,e,r,n){var i=Object.getOwnPropertyDescriptor(n,r);i.get!==void 0?i.configurable?(Object.defineProperty(n,r,{value:t}),Gn.push([n,r,e,i])):gr.push([e,r,t]):(n[r]=t,Gn.push([n,r,e]))}s(Pa,"setReplace");function Ra(t,e,r,n,i,a,o){a+=1;var l;if(typeof t=="object"&&t!==null){for(l=0;l<n.length;l++)if(n[l]===t){Pa(wm,t,e,i);return}if(typeof o.depthLimit<"u"&&a>o.depthLimit){Pa(Ic,t,e,i);return}if(typeof o.edgesLimit<"u"&&r+1>o.edgesLimit){Pa(Ic,t,e,i);return}if(n.push(t),Array.isArray(t))for(l=0;l<t.length;l++)Ra(t[l],l,l,n,t,a,o);else{t=Cc(t);var c=Object.keys(t);for(l=0;l<c.length;l++){var u=c[l];Ra(t[u],u,l,n,t,a,o)}}n.pop()}}s(Ra,"decirc");function Sm(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(gr.length>0)for(var n=0;n<gr.length;n++){var i=gr[n];if(i[1]===e&&i[0]===r){r=i[2],gr.splice(n,1);break}}return t.call(this,e,r)}}s(Sm,"replaceGetterValues");var Oc=require("node:worker_threads"),Ma=Oc.Worker,Pc=!0;var Tm=`
25
+ const { parentPort } = require("worker_threads");
26
+
27
+ const CIRCULAR_REPLACE_NODE = { result: "[Circular]" };
28
+
29
+ function serializeWellKnownTypes(val) {
30
+ if (val && typeof val === "object") {
31
+ if (val instanceof Map) return Object.fromEntries(val);
32
+ if (val instanceof Set) return Array.from(val);
33
+ if (val instanceof Date) return val.toISOString();
34
+ if (val instanceof RegExp) return val.toString();
35
+ if (val instanceof Error) return { name: val.name, message: val.message };
36
+ } else if (typeof val === "bigint") {
37
+ return val.toString();
38
+ }
39
+ return val;
40
+ }
41
+
42
+ function defaultReplacer(_key, val) {
43
+ return serializeWellKnownTypes(val);
44
+ }
45
+
46
+ // Decirculate in-place: replace circular refs with { result: "[Circular]" }
47
+ // then restore after stringify. Mirrors fast-safe-stringify's decirc().
48
+ const restoreStack = [];
49
+ function decirc(val, k, stack, parent) {
50
+ if (typeof val === "object" && val !== null) {
51
+ for (let i = 0; i < stack.length; i++) {
52
+ if (stack[i] === val) {
53
+ const orig = parent[k];
54
+ parent[k] = CIRCULAR_REPLACE_NODE;
55
+ restoreStack.push([parent, k, orig]);
56
+ return;
57
+ }
58
+ }
59
+ stack.push(val);
60
+ if (Array.isArray(val)) {
61
+ for (let i = 0; i < val.length; i++) decirc(val[i], i, stack, val);
62
+ } else {
63
+ const normalized = serializeWellKnownTypes(val);
64
+ // Only recurse into normalized if it's still an object (arrays/objects),
65
+ // else it was replaced with a primitive (e.g. Date -> string).
66
+ if (normalized === val) {
67
+ const keys = Object.keys(val);
68
+ for (let i = 0; i < keys.length; i++) decirc(val[keys[i]], keys[i], stack, val);
69
+ }
70
+ }
71
+ stack.pop();
72
+ }
73
+ }
74
+
75
+ function serialize(obj) {
76
+ try {
77
+ return JSON.stringify(obj, defaultReplacer);
78
+ } catch (e) {
79
+ if (!String(e && e.message).includes("Converting circular structure to JSON")) {
80
+ return "[Unserializable]";
81
+ }
82
+ decirc(obj, "", [], { "": obj });
83
+ try {
84
+ return JSON.stringify(obj, defaultReplacer);
85
+ } catch (_) {
86
+ return "[unable to serialize, circular reference is too complex to analyze]";
87
+ } finally {
88
+ while (restoreStack.length) {
89
+ const [p, k, v] = restoreStack.pop();
90
+ p[k] = v;
91
+ }
92
+ }
93
+ }
94
+ }
95
+
96
+ parentPort.on("message", (msg) => {
97
+ const { id, op, payload } = msg;
98
+ try {
99
+ if (op === "serialize") {
100
+ const str = serialize(payload);
101
+ const buf = Buffer.from(str, "utf8");
102
+ // Slice into its own ArrayBuffer so we can transfer without dragging
103
+ // unrelated bytes from any shared pool buffer.
104
+ const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
105
+ parentPort.postMessage({ id, bytes: ab, length: buf.byteLength }, [ab]);
106
+ } else if (op === "ping") {
107
+ parentPort.postMessage({ id });
108
+ } else {
109
+ parentPort.postMessage({ id, error: "unknown op: " + op });
110
+ }
111
+ } catch (e) {
112
+ parentPort.postMessage({ id, error: String((e && e.message) || e) });
113
+ }
114
+ });
115
+ `,La=class{static{s(this,"SerializeWorker")}constructor(){Object.defineProperty(this,"worker",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"nextId",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"pending",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"disabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"startPromise",{enumerable:!0,configurable:!0,writable:!0,value:null})}async ensureStarted(){if(this.disabled)return!1;if(this.worker!==null)return!0;if(this.startPromise!==null)return this.startPromise;this.startPromise=this._start();try{return await this.startPromise}finally{this.startPromise=null}}async _start(){if(!Pc||Ma===null)return this.disabled=!0,!1;try{let e=new Ma(Tm,{eval:!0});return e.on("message",r=>{let n=this.pending.get(r.id);n&&(this.pending.delete(r.id),r.error?n.reject(new Error(r.error)):r.bytes&&typeof r.length=="number"?n.resolve(new Uint8Array(r.bytes,0,r.length)):n.reject(new Error("worker returned malformed message")))}),e.on("error",r=>{for(let[,n]of this.pending)n.reject(r);this.pending.clear(),this.disabled=!0,this.worker=null}),e.on("exit",r=>{for(let[,n]of this.pending)n.reject(new Error(`worker exited with code ${r}`));this.pending.clear(),this.worker=null}),e.unref(),this.worker=e,!0}catch{return this.disabled=!0,!1}}async serialize(e){if(!await this.ensureStarted())return null;let n=this.nextId++;return new Promise((i,a)=>{this.pending.set(n,{resolve:i,reject:a});try{this.worker.postMessage({id:n,op:"serialize",payload:e})}catch(o){this.pending.delete(n),a(o)}})}async terminate(){this.worker&&(await this.worker.terminate(),this.worker=null);for(let[,e]of this.pending)e.reject(new Error("worker terminated"));this.pending.clear()}},Na=null;function Rc(){return Na===null&&(Na=new La),Na}s(Rc,"getSharedSerializeWorker");var Am=64*1024,Im=2048;function Mc(t,e=Am,r=Im){if(t===null||typeof t!="object")return typeof t=="string"&&t.length>=e;let n=[t],i=new Set,a=0;for(;n.length>0;){if(a++>=r)return!1;let o=n.pop();if(o==null)continue;let l=typeof o;if(l==="string"){if(o.length>=e)return!0;continue}if(l!=="object")continue;let c=o;if(i.has(c)||(i.add(c),c instanceof Date||c instanceof RegExp||c instanceof Error||c instanceof ArrayBuffer||ArrayBuffer.isView(c)))continue;if(Array.isArray(c)){for(let d=c.length-1;d>=0;d--)n.push(c[d]);continue}if(c instanceof Map){for(let[,d]of c)n.push(d);continue}if(c instanceof Set){for(let d of c)n.push(d);continue}let u=Object.keys(c);for(let d=u.length-1;d>=0;d--)n.push(c[u[d]])}return!1}s(Mc,"hasLargeString");function Cm(t,e){let[r]=he(t);if(r!=="-"&&!e)throw new Error("Pulling a public prompt by owner/name is disabled by default because prompts may contain untrusted serialized LangChain objects. If you trust this prompt, set `dangerouslyPullPublicPrompt: true` to acknowledge the risk.")}s(Cm,"assertPullPublicPromptAllowed");function Nc(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}s(Nc,"_ensureUTCTimestamp");function yr(t){return{...t,start_time:Nc(t.start_time),end_time:Nc(t.end_time)}}s(yr,"_normalizeRunTimestamps");function Lc(t,e,r){if(r)return t;let n=xn(),i=e??ea(),a=t.extra??{},o=a.metadata;return t.extra={...a,runtime:{...n,...a?.runtime},metadata:{...i,...i.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??i.revision_id}:{},...o}},t}s(Lc,"mergeRuntimeEnvIntoRun");var km=s(t=>{let e=t?.toString()??q("TRACING_SAMPLING_RATE");if(e===void 0)return;let r=parseFloat(e);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},"getTracingSamplingRate"),Om=s(t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"},"isLocalhost");async function Pm(t){let e=[];for await(let r of t)e.push(r);return e}s(Pm,"toArray");function Vn(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}s(Vn,"trimQuotes");var Rm=s(async t=>{if(t?.status===429){let e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1},"handle429");function $c(t){return typeof t=="number"?Number(t.toFixed(4)):t}s($c,"_formatFeedbackScore");function Mm(t,e){if(!t)return;let r=s(u=>u.split(".").map(d=>parseInt(d,10)),"parse"),[n,i,a]=r(t),[o,l,c]=r(e);if(isNaN(n)||isNaN(i)||isNaN(a)||isNaN(o)||isNaN(l)||isNaN(c)){console.warn(`[LANGSMITH]: Could not parse backend version ${JSON.stringify(t)} for compatibility check.`);return}(n<o||n===o&&i<l||n===o&&i===l&&a<c)&&console.warn(`[LANGSMITH]: Backend version ${JSON.stringify(t)} is older than the minimum version required by this SDK (${JSON.stringify(e)}). Some features may not work as expected. See https://docs.langchain.com/langsmith/smithdb-sdk-migration`)}s(Mm,"_checkBackendVersion");var Nm=24*1024*1024,jc=1024*1024*1024,Lm=1e4,$m=100;function Bc(t,e){new Headers({[t]:e})}s(Bc,"assertValidHeader");function Dc(t){for(let[e,r]of Object.entries(t??{}))Bc(e,r)}s(Dc,"assertValidHeaders");function Uc(t){if(!t)return{};let e=t instanceof Headers?[...t.entries()]:Array.isArray(t)?t.map(([i,a])=>[i,a]):Object.entries(t),r={},n=new Map;for(let[i,a]of e){Bc(i,a);let o=i.toLowerCase(),l=n.get(o);l===void 0?(n.set(o,i),r[i]=a):r[l]=a}return r}s(Uc,"normalizeHeaders");function Dm(t,e,r){let n={...t},i=new Map(Object.keys(n).map(a=>[a.toLowerCase(),a]));for(let[a,o]of Object.entries(e)){let l=a.toLowerCase();n[i.get(l)??a]=o}for(let a of Object.keys(n))r.has(a.toLowerCase())&&delete n[a];return n}s(Dm,"mergeCallerHeaders");var $a=class{static{s(this,"AutoBatchQueue")}constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??jc}peek(){return this.items[0]}push(e){let r,n=new Promise(a=>{r=a}),i=kc(e.item).size;return this.sizeBytes+i>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${i} bytes.`),r(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,workspaceId:e.workspaceId,itemPromiseResolve:r,itemPromise:n,size:i}),this.sizeBytes+=i,n)}pop({upToSizeBytes:e,upToSize:r}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let n=[],i=0;for(;i+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){let a=this.items.shift();a&&(n.push(a),i+=a.size,this.sizeBytes-=a.size)}if(n.length===0&&this.items.length>0){let a=this.items.shift();n.push(a),i+=a.size,this.sizeBytes-=a.size}return[n.map(a=>({action:a.action,item:a.payload,otelContext:a.otelContext,apiKey:a.apiKey,apiUrl:a.apiUrl,workspaceId:a.workspaceId,size:a.size})),()=>n.forEach(a=>a.itemPromiseResolve())]}},ut=class t{static{s(this,"Client")}get tracingMode(){return this._tracingMode}get _fetch(){let e=this.fetchImplementation||cl(this.debug);return(async(r,n)=>{let i,a=this.getProfileManagedAuthorizationHeader(n);return this.apiKey!==void 0?i={name:"x-api-key",value:`${this.apiKey}`}:this.hasExplicitAuthHeader(n,a)||(i=await this.profileAuth?.getAuthHeader(e,n?.signal)),e(r,this.applyCurrentAuthHeaders(n,i,a))})}getProfileManagedAuthorizationHeader(e){if(!e?.headers||!this.profileAuth)return;let r=new Headers(e.headers).get("Authorization");if(Ce(r))return this.profileAuth.isProfileAuthorizationHeader(r??"")?r??void 0:void 0}isProfileManagedAuthorizationHeader(e,r){return e===r||this.profileAuth?.isProfileAuthorizationHeader(e)===!0}hasExplicitAuthHeader(e,r){if(!e?.headers)return!1;let n=new Headers(e.headers);if(Ce(n.get("x-api-key")))return!0;let i=n.get("Authorization");return Ce(i)?!this.isProfileManagedAuthorizationHeader(i??"",r):!1}applyCurrentAuthHeaders(e,r,n){if(!r)return e;let i=s(p=>{if(this.apiKey!==void 0&&r.name==="x-api-key")return p.delete("Authorization"),p.has("x-api-key")||p.set("x-api-key",r.value),p;if(r.name==="Authorization"){if(Ce(p.get("x-api-key")))return p;let g=p.get("Authorization");return Ce(g)&&!this.isProfileManagedAuthorizationHeader(g??"",n)||p.set("Authorization",r.value),p}let h=p.get("Authorization");return Ce(h)&&!this.isProfileManagedAuthorizationHeader(h??"",n)||(Ce(h)&&p.delete("Authorization"),p.has("x-api-key")||p.set("x-api-key",r.value)),p},"applyAuth");if(!e)return{headers:{[r.name]:r.value}};if(e.headers instanceof Headers)return{...e,headers:i(new Headers(e.headers))};if(Array.isArray(e.headers))return{...e,headers:i(new Headers(e.headers))};let a={...e.headers??{}},o=s(p=>Object.keys(a).find(h=>h.toLowerCase()===p),"getHeaderKey"),l=s(p=>{let h=o(p);return h?a[h]:void 0},"getHeader"),c=Ce(l("x-api-key")),u=l("authorization"),d=Ce(u)&&!this.isProfileManagedAuthorizationHeader(u??"",n);if(this.apiKey!==void 0&&r.name==="x-api-key"){let p=o("authorization");return p&&delete a[p],c||(a["x-api-key"]=r.value),{...e,headers:a}}if(r.name==="Authorization"){if(!c&&!d){let p=o("authorization");p&&p!=="Authorization"&&delete a[p],a.Authorization=r.value}return{...e,headers:a}}if(!d){let p=o("authorization");p&&delete a[p],c||(a["x-api-key"]=r.value)}return{...e,headers:a}}_trackDrain(e){this._pendingDrains.add(e),e.finally(()=>{this._pendingDrains.delete(e)})}async _serializeBody(e,r){if(this.manualFlushMode)return ge(e,r);if(!Mc(e))return ge(e,r);if(this._serializeWorker===void 0&&(this._serializeWorker=Rc()),this._serializeWorker===null)return ge(e,r);try{let n=await this._serializeWorker.serialize(e);return n===null?(this._serializeWorker=null,ge(e,r)):n}catch{return ge(e,r)}}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"anonymizer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_fetchOptionsHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_openAPIClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_openAPIClientSignature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:ae("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_stainlessVersionsChecked",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_serializeWorker",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pendingDrains",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tracingMode",{enumerable:!0,configurable:!0,writable:!0,value:"langsmith"}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_promptCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"profileAuth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:q("DISABLE_MULTIPART_STREAMING")==="true"}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:q("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"failedTracesDir",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"failedTracesMaxBytes",{enumerable:!0,configurable:!0,writable:!0,value:100*1024*1024}),Object.defineProperty(this,"_customHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:ae("LANGSMITH_DEBUG")==="true"});let r=t.getDefaultClientConfig();this.tracingSampleRate=km(e.tracingSamplingRate),this.apiUrl=Vn(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1));let n=Vn(e.apiKey??r.apiKey);if(this.apiKey=Ce(n)?n:void 0,this.profileAuth=this.apiKey!==void 0?void 0:r.profileAuth,this.webUrl=Vn(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Vn(e.workspaceId??r.workspaceId),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Rr({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.failedTracesDir=q("FAILED_TRACES_DIR")||void 0;let i=q("FAILED_TRACES_MAX_MB");if(i){let c=parseInt(i,10);Number.isFinite(c)&&c>0&&(this.failedTracesMaxBytes=c*1024*1024)}let a=e.maxIngestMemoryBytes??jc;this.batchIngestCaller=new Rr({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:a,...e.callerOptions??{},onFailedResponseHook:Rm,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??r.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??r.hideOutputs,this.hideMetadata=e.hideMetadata??r.hideMetadata,this.anonymizer=e.anonymizer,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new $a(a),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit;let{headers:o,...l}=e.fetchOptions||{};this.fetchOptions=l,this._fetchOptionsHeaders=Uc(o),Dc(e.headers),this._customHeaders=e.headers??{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,this._tracingMode=En(e.tracingMode),this._tracingMode==="otel"&&(this.langSmithToOTELTranslator=new Tn),this.cachedLSEnvVarsForMetadata=ea(),e.cache!==void 0&&e.disablePromptCache&&se("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),e.cache!==void 0?(se("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."),e.cache===!1?this._promptCache=void 0:e.cache===!0?this._promptCache=wn:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=wn)}static getDefaultClientConfig(){let e=Tc(),r=q("API_KEY"),n=q("ENDPOINT"),i=q("WORKSPACE_ID"),a=Ce(r),o=n??e.apiUrl??Hn,l=i??e.workspaceId,c=q("HIDE_INPUTS")==="true",u=q("HIDE_OUTPUTS")==="true",d=q("HIDE_METADATA")==="true";return{apiUrl:o,apiKey:r,webUrl:void 0,hideInputs:c,hideOutputs:u,hideMetadata:d,workspaceId:l,oauthAccessToken:a?void 0:e.oauthAccessToken,oauthRefreshToken:a?void 0:e.oauthRefreshToken,profileAuth:a?void 0:e.profileAuth}}getHostUrl(){return this.webUrl?this.webUrl:Om(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("aws")?(this.webUrl="https://aws.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("apac")?(this.webUrl="https://apac.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get _sdkControlledHeaders(){let e=new Set;if(this.apiKey!==void 0)e.add("x-api-key");else{let r=this.profileAuth?.currentAuthHeader();r&&e.add(r.name.toLowerCase())}return this.workspaceId&&e.add("x-tenant-id"),e}get _callerHeaders(){return Dm(Uc(this._customHeaders),this._fetchOptionsHeaders,this._sdkControlledHeaders)}get _mergedHeaders(){let e={"User-Agent":`langsmith-js/${vn}`,...this._callerHeaders};if(this.apiKey!==void 0)e["x-api-key"]=`${this.apiKey}`;else{let r=this.profileAuth?.currentAuthHeader();r&&(e[r.name]=r.value)}return this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}get _openAPIAuth(){let e={...this._callerHeaders},r=Object.keys(e).find(i=>i.toLowerCase()==="x-api-key"),n=this.apiKey;return n===void 0&&r!==void 0&&(n=e[r]??void 0,delete e[r]),n===void 0&&this.workspaceId===void 0&&(e["X-API-Key"]=null),{apiKey:n,defaultHeaders:Object.keys(e).length>0?e:void 0}}get headers(){return this._customHeaders}set headers(e){Dc(e),this._customHeaders=e??{}}_getOpenAPIBaseUrl(){let e=this.apiUrl.replace(/\/$/,"");for(let r of["/api/v1","/api"])if(e.endsWith(r))return e.slice(0,-r.length);return e}get openAPIClient(){let e=this._openAPIAuth,r=JSON.stringify([e.apiKey,e.defaultHeaders]);return(this._openAPIClient===void 0||this._openAPIClientSignature!==r)&&(this._openAPIClientSignature=r,this._openAPIClient=this._newOpenAPIClient(e)),this._openAPIClient}_newOpenAPIClient(e=this._openAPIAuth){let{method:r,body:n,signal:i,...a}=this.fetchOptions;return new z({apiKey:e.apiKey,tenantID:this.workspaceId,baseURL:this._getOpenAPIBaseUrl(),timeout:this.timeout_ms,fetch:this._fetch,fetchOptions:a,defaultHeaders:e.defaultHeaders})}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}get evaluators(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.onlineEvaluators}get runs(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.runs}get sandboxes(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.sandboxes}get datasets(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.datasets}get annotationQueues(){return this._checkStainlessVersion("0.16.14"),this.openAPIClient.annotationQueues}get threads(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.threads}get traces(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.traces}get public(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.public}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async processMetadata(e){return this.hideMetadata===!1?e:this.hideMetadata===!0?{}:typeof this.hideMetadata=="function"?this.hideMetadata(e):e}async processError(e){if(this.anonymizer==null)return e;let r=await this.anonymizer({error:e});return typeof r?.error=="string"?r.error:e}_filterNewTokenEvents(e){return!e||e.length===0?e:e.map(r=>{if(r.name==="new_token"){let{kwargs:n,...i}=r;return i}return r})}async prepareRunCreateOrUpdateInputs(e){let r={...e};return r.inputs!==void 0&&(r.inputs=await this.processInputs(r.inputs)),r.outputs!==void 0&&(r.outputs=await this.processOutputs(r.outputs)),r.error!==void 0&&(r.error=await this.processError(r.error)),r.extra!=null&&"metadata"in r.extra&&(r.extra={...r.extra,metadata:await this.processMetadata(r.extra.metadata)}),r.events!==void 0&&(r.events=this._filterNewTokenEvents(r.events)),r}async _getResponse(e,r){let n=r?.toString()??"",i=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{let o=await this._fetch(i,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(o,`fetch ${e}`),o})}async _get(e,r){return(await this._getResponse(e,r)).json()}async*_getPaginated(e,r=new URLSearchParams,n){let i=Number(r.get("offset"))||0,a=Number(r.get("limit"))||100;for(;;){r.set("offset",String(i)),r.set("limit",String(a));let o=`${this.apiUrl}${e}?${r}`,l=await this.caller.call(async()=>{let u=await this._fetch(o,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(u,`fetch ${e}`),u}),c=n?n(await l.json()):await l.json();if(c.length===0||(yield c,c.length<a))break;i+=c.length}}async*_getCursorPaginatedList(e,r=null,n="POST",i="runs"){let a=r?{...r}:{};for(;;){let o=JSON.stringify(a),c=await(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await C(d,`fetch ${e}`),d})).json();if(!c||!c[i])break;yield c[i];let u=c.cursors;if(!u||!u.next)break;a.cursor=u.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,r=!1){if(this.tracingSampleRate===void 0)return e;if(r){let n=[];for(let i of e)this.filteredPostUuids.has(i.trace_id)?i.id===i.trace_id&&this.filteredPostUuids.delete(i.trace_id):n.push(i);return n}else{let n=[];for(let i of e){let a=i.trace_id??i.id;this.filteredPostUuids.has(a)||(i.id===a?this._shouldSample()?n.push(i):this.filteredPostUuids.add(a):n.push(i))}return n}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??Nm}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??$m}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[i,a]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:r});if(!i.length){a();break}let o=i.reduce((u,d)=>{let p=d.apiUrl??this.apiUrl,h=d.apiKey??this.apiKey,g=d.workspaceId??this.workspaceId,v=d.apiKey===this.apiKey&&d.apiUrl===this.apiUrl&&d.workspaceId===this.workspaceId?"default":`${p}|${h}|${g??""}`;return u[v]||(u[v]=[]),u[v].push(d),u},{}),l=[];for(let[u,d]of Object.entries(o)){let p=u==="default",h=p?[]:u.split("|"),g=h[2],b=this._processBatch(d,{apiUrl:p?void 0:h[0],apiKey:p?void 0:h[1],workspaceId:p||!g?void 0:g});l.push(b)}let c=Promise.all(l).finally(a);n.push(c)}return Promise.all(n)}static async _writeTraceToFallbackDir(e,r,n,i,a){try{let o=typeof r=="string"?Buffer.from(r,"utf8"):Buffer.from(r),l=JSON.stringify({version:1,endpoint:i,headers:n,body_base64:o.toString("base64")}),c=`trace_${Date.now()}_${Et().slice(0,8)}.json`,u=Ne.join(e,c);if(t._fallbackDirsCreated.has(e)||(await yn(e),t._fallbackDirsCreated.add(e)),a!==void 0&&a>0)try{let p=(await Sl(e)).filter(g=>g.startsWith("trace_")&&g.endsWith(".json")),h=0;for(let g of p){let{size:b}=await Tl(Ne.join(e,g));h+=b}if(h>=a){console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${h} bytes >= ${a} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await nr(u,l),console.warn(`LangSmith trace upload failed; data saved to ${u} for later replay.`)}catch(o){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,o)}}async _processBatch(e,r){if(!e.length)return;let n=e.reduce((i,a)=>i+(a.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let i={runCreates:e.filter(l=>l.action==="create").map(l=>l.item),runUpdates:e.filter(l=>l.action==="update").map(l=>l.item)},a=await this._ensureServerInfo();if(!this._multipartDisabled&&(a?.batch_ingest_config?.use_multipart_endpoint??!0)){let l=!this._runCompressionDisabled&&a?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(i,{...r,useGzip:l,sizeBytes:n})}catch(c){if(Bn(c))this._multipartDisabled=!0,await this.batchIngestRuns(i,{...r,sizeBytes:n});else throw c}}else await this.batchIngestRuns(i,{...r,sizeBytes:n})}}catch(i){console.error("Error exporting batch:",i)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let r=new Map,n=[];for(let i of e)i.item.id&&i.otelContext&&(r.set(i.item.id,i.otelContext),i.action==="create"?n.push({operation:"post",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}):n.push({operation:"patch",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=Lc(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let r=this.autoBatchQueue.push(e);if(this.manualFlushMode)return r;let n=await this._getBatchSizeLimitBytes(),i=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>i)&&this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:i})),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:i}))},this.autoBatchAggregationDelayMs)),r}async _getServerInfo(){let r=await(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(Lm),...this.fetchOptions});return await C(n,"get server info"),n})).json();return this.debug&&console.log(`
116
+ === LangSmith Server Configuration ===
117
+ `+JSON.stringify(r,null,2)+`
118
+ `),r}_checkStainlessVersion(e){this._stainlessVersionsChecked.has(e)||(this._stainlessVersionsChecked.add(e),this._ensureServerInfo().then(r=>{Mm(r?.version,e)}).catch(()=>{}))}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _supportsSDBQuery(){return(await this._ensureServerInfo()).instance_flags?.sdb_query_enabled===!0}async _checkFeedbackSessionId(){let e="https://docs.langchain.com/langsmith/smithdb-sdk-migration#feedback-create",r=await this._ensureServerInfo();if(gc(r.instance_flags)===$r.SMITHDB_ONLY)throw new Error(`sessionId must be provided when creating feedback for a run: this deployment cannot locate the run without it. See ${e}`);se(`Creating feedback for a run without sessionId is deprecated and will stop working in a future release. See ${e}`)}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r})}_cloneCurrentOTELContext(){let e=Sn(),r=Dl();if(this.langSmithToOTELTranslator!==void 0){let n=e.getActiveSpan();if(n)return e.setSpan(r.active(),n)}}async createRun(e,r){if(!this._filterForSampling([e]).length)return;let n={...this._mergedHeaders,"Content-Type":"application/json"},i=e.project_name;delete e.project_name;let a=await this.prepareRunCreateOrUpdateInputs({session_name:i,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){let c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:a,otelContext:c,apiKey:r?.apiKey,apiUrl:r?.apiUrl,workspaceId:r?.workspaceId}).catch(console.error);return}let o=Lc(a,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);let l=ge(o,`Creating run with id: ${o.id}`);await this.caller.call(async()=>{let c=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await C(c,"create run",!0),c})}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let i=await Promise.all(e?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]),a=await Promise.all(r?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]);if(i.length>0&&a.length>0){let c=i.reduce((d,p)=>(p.id&&(d[p.id]=p),d),{}),u=[];for(let d of a)d.id!==void 0&&c[d.id]?c[d.id]={...c[d.id],...d}:u.push(d);i=Object.values(c),a=u}let o={post:i,patch:a};if(!o.post.length&&!o.patch.length)return;let l={post:[],patch:[]};for(let c of["post","patch"]){let u=c,d=o[u].reverse(),p=d.pop();for(;p!==void 0;)l[u].push(p),p=d.pop()}if(l.post.length>0||l.patch.length>0){let c=l.post.map(u=>u.id).concat(l.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(await this._serializeBody(l,`Ingesting runs with ids: ${c}`),n)}}async _postBatchIngestRuns(e,r){let n={...this._mergedHeaders,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId),await this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let i=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await C(i,"batch create run",!0),i})}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let i={},a=[];for(let p of e??[]){let h=await this.prepareRunCreateOrUpdateInputs(p);h.id!==void 0&&h.attachments!==void 0&&(i[h.id]=h.attachments),delete h.attachments,a.push(h)}let o=[];for(let p of r??[])o.push(await this.prepareRunCreateOrUpdateInputs(p));if(a.find(p=>p.trace_id===void 0||p.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(o.find(p=>p.trace_id===void 0||p.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(a.length>0&&o.length>0){let p=a.reduce((g,b)=>(b.id&&(g[b.id]=b),g),{}),h=[];for(let g of o)g.id!==void 0&&p[g.id]?p[g.id]={...p[g.id],...g}:h.push(g);a=Object.values(p),o=h}if(a.length===0&&o.length===0)return;let u=[],d=[];for(let[p,h]of[["post",a],["patch",o]])for(let g of h){let{inputs:b,outputs:v,events:P,extra:I,error:S,serialized:A,attachments:R,...$}=g,N={inputs:b,outputs:v,events:P,extra:I,error:S,serialized:A},j=await this._serializeBody($,`Serializing for multipart ingestion of run with id: ${$.id}`);d.push({name:`${p}.${$.id}`,payload:new Blob([j],{type:`application/json; length=${j.length}`})});for(let[y,K]of Object.entries(N)){if(K===void 0)continue;let B=await this._serializeBody(K,`Serializing ${y} for multipart ingestion of run with id: ${$.id}`);d.push({name:`${p}.${$.id}.${y}`,payload:new Blob([B],{type:`application/json; length=${B.length}`})})}if($.id!==void 0){let y=i[$.id];if(y){delete i[$.id];for(let[K,B]of Object.entries(y)){let F,de;if(Array.isArray(B)?[F,de]=B:(F=B.mimeType,de=B.data),K.includes(".")){console.warn(`Skipping attachment '${K}' for run ${$.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}d.push({name:`attachment.${$.id}.${K}`,payload:new Blob([de],{type:`${F}; length=${de.byteLength}`})})}}}u.push(`trace=${$.trace_id},id=${$.id}`)}await this._sendMultipartRequest(d,u.join("; "),n)}async _createNodeFetchBody(e,r){let n=[];for(let o of e)n.push(new Blob([`--${r}\r
119
+ `])),n.push(new Blob([`Content-Disposition: form-data; name="${o.name}"\r
120
+ `,`Content-Type: ${o.payload.type}\r
121
+ \r
122
+ `])),n.push(o.payload),n.push(new Blob([`\r
123
+ `]));return n.push(new Blob([`--${r}--\r
124
+ `])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,r){let n=new TextEncoder;return new ReadableStream({async start(a){let o=s(async l=>{typeof l=="string"?a.enqueue(n.encode(l)):a.enqueue(l)},"writeChunk");for(let l of e){await o(`--${r}\r
125
+ `),await o(`Content-Disposition: form-data; name="${l.name}"\r
126
+ `),await o(`Content-Type: ${l.payload.type}\r
127
+ \r
128
+ `);let u=l.payload.stream().getReader();try{let d;for(;!(d=await u.read()).done;)a.enqueue(d.value)}finally{u.releaseLock()}await o(`\r
129
+ `)}await o(`--${r}--\r
130
+ `),a.close()}})}async _sendMultipartRequest(e,r,n){let i="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=s(()=>this._createNodeFetchBody(e,i),"buildBuffered"),o=s(()=>this._createMultipartStream(e,i),"buildStream"),l=s(async c=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let u=await c(),d={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${i}`};n?.apiKey!==void 0&&(d["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(d["x-tenant-id"]=n.workspaceId);let p=u;n?.useGzip&&typeof u=="object"&&"pipeThrough"in u&&(p=u.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");let h=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:p,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(h,"Failed to send multipart request",!0),h}),"sendWithRetry");try{let c,u=!1;ll()&&!this.multipartStreamingDisabled&&Pr()!=="bun"?(u=!0,c=await l(o)):c=await l(a),(!this.multipartStreamingDisabled||u)&&c.status===422&&(n?.apiUrl??this.apiUrl)!==Hn&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,c=await l(a))}catch(c){if(Bn(c))throw c;if(console.warn(`${c.message.trim()}
131
+
132
+ Context: ${r}`),this.failedTracesDir){let u=await this._createNodeFetchBody(e,i).catch(()=>null);u&&await t._writeTraceToFallbackDir(this.failedTracesDir,u,{"Content-Type":`multipart/form-data; boundary=${i}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,r,n){L(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs)),r.error&&(r.error=await this.processError(r.error)),r.extra!=null&&"metadata"in r.extra&&(r.extra={...r.extra,metadata:await this.processMetadata(r.extra.metadata)}),r.events&&(r.events=this._filterNewTokenEvents(r.events));let i={...r,id:e};if(!this._filterForSampling([i],!0).length)return;if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let l=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&i.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:i,otelContext:l,apiKey:n?.apiKey,apiUrl:n?.apiUrl,workspaceId:n?.workspaceId}).catch(console.error);return}else this.processRunOperation({action:"update",item:i,otelContext:l,apiKey:n?.apiKey,apiUrl:n?.apiUrl,workspaceId:n?.workspaceId}).catch(console.error);return}let a={...this._mergedHeaders,"Content-Type":"application/json"};n?.apiKey!==void 0&&(a["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(a["x-tenant-id"]=n.workspaceId);let o=ge(r,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let l=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await C(l,"update run",!0),l})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){return se("readRun() is deprecated and will be removed after Jan 31, 2027. Use client.runs.retrieve() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#runs-retrieve for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_READ_RUN"}),this._readRun(e,{loadChildRuns:r})}async _readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){L(e);let n=yr(await this._get(`/runs/${e}`));return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(se("getRunUrl() is deprecated and will be removed after Jan 31, 2027. Use client.runs.getURL() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#runs-get-url for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_GET_RUN_URL"}),r!==void 0){let i;r.session_id?i=r.session_id:n?.projectName?i=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?i=n?.projectId:i=(await this.readProject({projectName:q("PROJECT")||"default"})).id;let a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${i}/r/${r.id}?poll=true`}else if(e!==void 0){let i=await this._readRun(e);if(!i.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${i.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){let r=await Pm(this._listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},i={};r.sort((a,o)=>(a?.dotted_order??"").localeCompare(o?.dotted_order??""));for(let a of r){if(a.parent_run_id===null||a.parent_run_id===void 0)throw new Error(`Child run ${a.id} has no parent`);a.dotted_order?.startsWith(e.dotted_order??"")&&a.id!==e.id&&(a.parent_run_id in n||(n[a.parent_run_id]=[]),n[a.parent_run_id].push(a),i[a.id]=a)}e.child_runs=n[e.id]||[];for(let a in n)a!==e.id&&(i[a].child_runs=n[a]);return e}async*listRuns(e){se("listRuns() is deprecated and will be removed after Jan 31, 2027. Use client.runs.query() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#runs-query for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_LIST_RUNS"}),yield*this._listRuns(e)}async*_listRuns(e){let{projectId:r,projectName:n,parentRunId:i,traceId:a,referenceExampleId:o,startTime:l,executionOrder:c,isRoot:u,runType:d,error:p,id:h,query:g,filter:b,traceFilter:v,treeFilter:P,limit:I,select:S,order:A}=e,R=[];if(r&&(R=Array.isArray(r)?r:[r]),n){let y=Array.isArray(n)?n:[n],K=await Promise.all(y.map(B=>this.readProject({projectName:B}).then(F=>F.id)));R.push(...K)}let $=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],N={session:R.length?R:null,run_type:d,reference_example:o,query:g,filter:b,trace_filter:v,tree_filter:P,execution_order:c,parent_run:i,start_time:l?l.toISOString():null,error:p,id:h,limit:I,trace:a,select:S||$,is_root:u,order:A};N.select.includes("child_run_ids")&&se("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let j=0;for await(let y of this._getCursorPaginatedList("/runs/query",N)){let K=y.map(yr);if(I){if(j>=I)break;if(K.length+j>I){yield*K.slice(0,I-j);break}j+=K.length,yield*K}else yield*K}}async*listGroupRuns(e){let{projectId:r,projectName:n,groupBy:i,filter:a,startTime:o,endTime:l,limit:c,offset:u}=e,p={session_id:r||(await this.readProject({projectName:n})).id,group_by:i,filter:a,start_time:o?o.toISOString():null,end_time:l?l.toISOString():null,limit:Number(c)||100},h=Number(u)||0,g="/runs/group",b=`${this.apiUrl}${g}`;for(;;){let v={...p,offset:h},P=Object.fromEntries(Object.entries(v).filter(([N,j])=>j!==void 0)),I=JSON.stringify(P),A=await(await this.caller.call(async()=>{let N=await this._fetch(b,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:I});return await C(N,`Failed to fetch ${g}`),N})).json(),{groups:R,total:$}=A;if(R.length===0)break;for(let N of R)yield N;if(h+=R.length,h>=$)break}}async*readThread(e){se("readThread() is deprecated and will be removed after Jan 31, 2027. Use client.threads.listTraces() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#threads-list-traces for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_READ_THREAD"});let{threadId:r,projectId:n,projectName:i,isRoot:a=!0,limit:o,filter:l,order:c="asc"}=e;if(!n&&!i)throw new Error("threadId requires projectId or projectName");let u=`eq(thread_id, ${JSON.stringify(r)})`,d=l?`and(${u}, ${l})`:u;yield*this._listRuns({projectId:n??void 0,projectName:i??void 0,isRoot:a,limit:o,filter:d,order:c})}async listThreads(e){se("listThreads() is deprecated and will be removed after Jan 31, 2027. Use client.threads.query() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#threads-query for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_LIST_THREADS"});let{projectId:r,projectName:n,limit:i,offset:a=0,filter:o,startTime:l,isRoot:c=!0}=e;if(!r&&!n)throw new Error("Either projectId or projectName must be provided");if(r&&n)throw new Error("Provide exactly one of projectId or projectName");let u=r??(await this.readProject({projectName:n})).id,d=l??new Date(Date.now()-1440*60*1e3),h={session:[u],is_root:c,limit:100,order:"desc",select:["id","name","status","start_time","end_time","thread_id","trace_id","run_type","error","tags","session_id","parent_run_id","total_tokens","total_cost","dotted_order","reference_example_id","feedback_stats","app_path","completion_cost","completion_tokens","prompt_cost","prompt_tokens","first_token_time"],start_time:d.toISOString()};o!=null&&(h.filter=o);let g=new Map;for await(let I of this._getCursorPaginatedList("/runs/query",h))for(let S of I){let A=yr(S),R=A.thread_id;if(R){let $=g.get(R)??[];$.push(A),g.set(R,$)}}let b=[];for(let[I,S]of g.entries()){S.sort((j,y)=>{let K=j,B=y,F=K.start_time??"",de=B.start_time??"";if(F!==de)return F.localeCompare(de);let tt=K.dotted_order??"",rt=B.dotted_order??"";return tt.localeCompare(rt)});let R=[...S.map(j=>j.start_time).filter(Boolean)].sort(),$=R.length?R[0]:"",N=R.length?R[R.length-1]:"";b.push({thread_id:I,runs:S,count:S.length,filter:"",total_tokens:0,total_cost:null,min_start_time:$,max_start_time:N,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}b.sort((I,S)=>{let A=I.max_start_time??"";return(S.max_start_time??"").localeCompare(A)});let v=a>0?b.slice(a):b;return i!==void 0?v.slice(0,i):v}async getRunStats({id:e,trace:r,parentRun:n,runType:i,projectNames:a,projectIds:o,referenceExampleIds:l,startTime:c,endTime:u,error:d,query:p,filter:h,traceFilter:g,treeFilter:b,isRoot:v,dataSourceType:P}){let I=o||[];if(a&&(I=[...o||[],...await Promise.all(a.map(j=>this.readProject({projectName:j}).then(y=>y.id)))]),I.length===0)throw new Error("At least one of projectNames or projectIds must be provided.");let A=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:i,session:I,reference_example:l,start_time:c,end_time:u,error:d,query:p,filter:h,trace_filter:g,tree_filter:b,is_root:v,data_source_type:P}).filter(([j,y])=>y!==void 0)),R=JSON.stringify(A);return await(await this.caller.call(async()=>{let j=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:R});return await C(j,"get run stats"),j})).json()}async shareRun(e,{shareId:r}={}){se("shareRun() is deprecated and will be removed after Jan 31, 2027. Use client.runs.share.create() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#share-and-read-public-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_SHARE_RUN"});let n={run_id:e,share_token:r||Et()};L(e);let i=JSON.stringify(n),o=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await C(l,"share run"),l})).json();if(o===null||!("share_token"in o))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${o.share_token}/r`}async unshareRun(e){se("unshareRun() is deprecated and will be removed after Jan 31, 2027. Use client.runs.share.delete() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#share-and-read-public-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_UNSHARE_RUN"}),L(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(r,"unshare run",!0),r})}async readRunSharedLink(e){se('readRunSharedLink() is deprecated and will be removed after Jan 31, 2027. Use client.runs.retrieve({ selects: ["SHARE_URL"] }) instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#share-and-read-public-runs for the migration guide.',{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_READ_RUN_SHARED_LINK"}),L(e);let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(i,"read run shared link"),i})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:r}={}){se("listSharedRuns() is deprecated and will be removed after Jan 31, 2027. Use client.public.runs.query() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#share-and-read-public-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_LIST_SHARED_RUNS"});let n=new URLSearchParams({share_token:e});if(r!==void 0)for(let o of r)n.append("id",o);return L(e),(await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(o,"list shared runs"),o})).json()).map(yr)}async readDatasetSharedSchema(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id),L(e);let i=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(a,"read dataset shared schema"),a})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async shareDataset(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id);let n={dataset_id:e};L(e);let i=JSON.stringify(n),o=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await C(l,"share dataset"),l})).json();return o.url=`${this.getHostUrl()}/public/${o.share_token}/d`,o}async unshareDataset(e){L(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(r,"unshare dataset",!0),r})}async readSharedDataset(e){return L(e),await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(i,"read shared dataset"),i})).json()}async listSharedExamples(e,r){let n={};r?.exampleIds&&(n.id=r.exampleIds);let i=new URLSearchParams;Object.entries(n).forEach(([l,c])=>{Array.isArray(c)?c.forEach(u=>i.append(l,u)):i.append(l,c)});let a=await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/public/${e}/examples?${i.toString()}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(l,"list shared examples"),l}),o=await a.json();if(!a.ok)throw"detail"in o?new Error(`Failed to list shared examples.
133
+ Status: ${a.status}
134
+ Message: ${Array.isArray(o.detail)?o.detail.join(`
135
+ `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${a.status} ${a.statusText}`);return o.map(l=>({...l,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:i=!1,projectExtra:a=null,referenceDatasetId:o=null,numExamples:l=null,numRepetitions:c=null,evaluatorKeys:u=null}){let d=i?"?upsert=true":"",p=`${this.apiUrl}/sessions${d}`,h=a||{};n&&(h.metadata=n);let g={name:e,extra:h,description:r};o!==null&&(g.reference_dataset_id=o),l!=null&&(g.num_examples=l),c!=null&&(g.num_repetitions=c),u!=null&&u.length>0&&(g.evaluator_keys=u);let b=JSON.stringify(g);return await(await this.caller.call(async()=>{let I=await this._fetch(p,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:b});return await C(I,"create project"),I})).json()}async updateProject(e,{name:r=null,description:n=null,metadata:i=null,projectExtra:a=null,endTime:o=null}){let l=`${this.apiUrl}/sessions/${e}`,c=a;i&&(c={...c||{},metadata:i});let u=JSON.stringify({name:r,extra:c,description:n,end_time:o?new Date(o).toISOString():null});return await(await this.caller.call(async()=>{let h=await this._fetch(l,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await C(h,"update project"),h})).json()}async hasProject({projectId:e,projectName:r}){let n="/sessions",i=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)L(e),n+=`/${e}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");let a=await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}${n}?${i}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(o,"has project"),o});try{let o=await a.json();return a.ok?Array.isArray(o)?o.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let i="/sessions",a=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)L(e),i+=`/${e}`;else if(r!==void 0)a.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&a.append("include_stats",n.toString());let o=await this._get(i,a),l;if(Array.isArray(o)){if(o.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);l=o[0]}else l=o;return l}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:e,projectName:r}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:e,datasetName:r}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:i,referenceDatasetName:a,includeStats:o,datasetVersion:l,referenceFree:c,metadata:u}={}){let d=new URLSearchParams;if(e!==void 0)for(let p of e)d.append("id",p);if(r!==void 0&&d.append("name",r),n!==void 0&&d.append("name_contains",n),i!==void 0)d.append("reference_dataset",i);else if(a!==void 0){let p=await this.readDataset({datasetName:a});d.append("reference_dataset",p.id)}o!==void 0&&d.append("include_stats",o.toString()),l!==void 0&&d.append("dataset_version",l),c!==void 0&&d.append("reference_free",c.toString()),u!==void 0&&d.append("metadata",JSON.stringify(u));for await(let p of this._getPaginated("/sessions",d))yield*p}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:r})).id:n=e,L(n),await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(i,`delete session ${n} (${r})`,!0),i})}async uploadCsv({csvFile:e,fileName:r,inputKeys:n,outputKeys:i,description:a,dataType:o,name:l}){let c=`${this.apiUrl}/datasets/upload`,u=new FormData,d=new Blob([e],{type:"text/csv"});return u.append("file",d,r),n.forEach(g=>{u.append("input_keys",g)}),i.forEach(g=>{u.append("output_keys",g)}),a&&u.append("description",a),o&&u.append("data_type",o),l&&u.append("name",l),await(await this.caller.call(async()=>{let g=await this._fetch(c,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await C(g,"upload CSV"),g})).json()}async createDataset(e,{description:r,dataType:n,inputsSchema:i,outputsSchema:a,metadata:o}={}){let l={name:e,description:r,extra:{source:"sdk",...o?{metadata:o}:{}}};n&&(l.data_type=n),i&&(l.inputs_schema_definition=i),a&&(l.outputs_schema_definition=a);let c=JSON.stringify(l);return await(await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await C(p,"create dataset"),p})).json()}async readDataset({datasetId:e,datasetName:r}){let n="/datasets",i=new URLSearchParams({limit:"1"});if(e&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(e)L(e),n+=`/${e}`;else if(r)i.append("name",r);else throw new Error("Must provide datasetName or datasetId");let a=await this._get(n,i),o;if(Array.isArray(a)){if(a.length===0)throw new Error(`Dataset[id=${e}, name=${r}] not found`);o=a[0]}else o=a;return o}async hasDataset({datasetId:e,datasetName:r}){try{return await this.readDataset({datasetId:e,datasetName:r}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:e,datasetName:r,fromVersion:n,toVersion:i}){let a=e;if(a===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(await this.readDataset({datasetName:r})).id);let o=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof i=="string"?i:i.toISOString()});return await this._get(`/datasets/${a}/versions/diff`,o)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:r}){let n="/datasets";if(e===void 0)if(r!==void 0)e=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${e}/openai_ft`)).text()).trim().split(`
136
+ `).map(l=>JSON.parse(l))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:i,datasetNameContains:a,metadata:o}={}){let l="/datasets",c=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(let u of n)c.append("id",u);i!==void 0&&c.append("name",i),a!==void 0&&c.append("name_contains",a),o!==void 0&&c.append("metadata",JSON.stringify(o));for await(let u of this._getPaginated(l,c))yield*u}async updateDataset(e){let{datasetId:r,datasetName:n,...i}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let a=r??(await this.readDataset({datasetName:n})).id;L(a);let o=JSON.stringify(i);return await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${a}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await C(c,"update dataset"),c})).json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:i,tag:a}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let o=r??(await this.readDataset({datasetName:n})).id;L(o);let l=JSON.stringify({as_of:typeof i=="string"?i:i.toISOString(),tag:a});await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${o}/tags`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await C(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",i=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(i=(await this.readDataset({datasetName:r})).id),i!==void 0)L(i),n+=`/${i}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let a=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(a,`delete ${n}`,!0),a})}async createExample(e,r,n){if(Fc(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let i=r?n?.datasetId:e.dataset_id,a=r?n?.datasetName:e.dataset_name;if(i===void 0&&a===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&a!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:a})).id);let o=(r?n?.createdAt:e.created_at)||new Date,l;Fc(e)?l=e:l={inputs:e,outputs:r,created_at:o?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let c=await this._uploadExamplesMultipart(i,[l]);return await this.readExample(c.example_ids?.[0]??Et())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let S=e,A=S[0].dataset_id,R=S[0].dataset_name;if(A===void 0&&R===void 0)throw new Error("Must provide either datasetName or datasetId");if(A!==void 0&&R!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");A===void 0&&(A=(await this.readDataset({datasetName:R})).id);let $=await this._uploadExamplesMultipart(A,S);return await Promise.all($.example_ids.map(j=>this.readExample(j)))}let{inputs:r,outputs:n,metadata:i,splits:a,sourceRunIds:o,useSourceRunIOs:l,useSourceRunAttachments:c,attachments:u,exampleIds:d,datasetId:p,datasetName:h}=e;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let g=p,b=h;if(g===void 0&&b===void 0)throw new Error("Must provide either datasetName or datasetId");if(g!==void 0&&b!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");g===void 0&&(g=(await this.readDataset({datasetName:b})).id);let v=r.map((S,A)=>({dataset_id:g,inputs:S,outputs:n?.[A],metadata:i?.[A],split:a?.[A],id:d?.[A],attachments:u?.[A],source_run_id:o?.[A],use_source_run_io:l?.[A],use_source_run_attachments:c?.[A]})),P=await this._uploadExamplesMultipart(g,v);return await Promise.all(P.example_ids.map(S=>this.readExample(S)))}async createLLMExample(e,r,n){return this.createExample({input:e},{output:r},n)}async createChatExample(e,r,n){let i=e.map(o=>da(o)?pa(o):o),a=da(r)?pa(r):r;return this.createExample({input:i},{output:a},n)}async readExample(e){L(e);let r=`/examples/${e}`,n=await this._get(r),{attachment_urls:i,...a}=n,o=a;return i&&(o.attachments=Object.entries(i).reduce((l,[c,u])=>(l[c.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},l),{})),o}async*listExamples({datasetId:e,datasetName:r,exampleIds:n,asOf:i,splits:a,inlineS3Urls:o,metadata:l,limit:c,offset:u,filter:d,includeAttachments:p}={}){let h;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)h=e;else if(r!==void 0)h=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");let g=new URLSearchParams({dataset:h}),b=i?typeof i=="string"?i:i?.toISOString():void 0;b&&g.append("as_of",b);let v=o??!0;if(g.append("inline_s3_urls",v.toString()),n!==void 0)for(let I of n)g.append("id",I);if(a!==void 0)for(let I of a)g.append("splits",I);if(l!==void 0){let I=JSON.stringify(l);g.append("metadata",I)}c!==void 0&&g.append("limit",c.toString()),u!==void 0&&g.append("offset",u.toString()),d!==void 0&&g.append("filter",d),p===!0&&["attachment_urls","outputs","metadata"].forEach(I=>g.append("select",I));let P=0;for await(let I of this._getPaginated("/examples",g)){for(let S of I){let{attachment_urls:A,...R}=S,$=R;A&&($.attachments=Object.entries(A).reduce((N,[j,y])=>(N[j.slice(11)]={presigned_url:y.presigned_url,mime_type:y.mime_type||void 0},N),{})),yield $,P++}if(c!==void 0&&P>=c)break}}async deleteExample(e){L(e);let r=`/examples/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(n,`delete ${r}`,!0),n})}async deleteExamples(e,r){if(e.forEach(n=>L(n)),r?.hardDelete){let n=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${n}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(i,"hard delete examples",!0),i})}else{let n=new URLSearchParams;e.forEach(i=>n.append("example_ids",i)),await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/examples?${n.toString()}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(i,"delete examples",!0),i})}}async updateExample(e,r){let n;r?n=e:n=e.id,L(n);let i;r?i={id:n,...r}:i=e;let a;return i.dataset_id!==void 0?a=i.dataset_id:a=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(a,[i])}async updateExamples(e){let r;return e[0].dataset_id===void 0?r=(await this.readExample(e[0].id)).dataset_id:r=e[0].dataset_id,this._updateExamplesMultipart(r,e)}async readDatasetVersion({datasetId:e,datasetName:r,asOf:n,tag:i}){let a;if(e?a=e:a=(await this.readDataset({datasetName:r})).id,L(a),n&&i||!n&&!i)throw new Error("Exactly one of asOf and tag must be specified.");let o=new URLSearchParams;return n!==void 0&&o.append("as_of",typeof n=="string"?n:n.toISOString()),i!==void 0&&o.append("tag",i),await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${a}/version?${o.toString()}`,{method:"GET",headers:{...this._mergedHeaders},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:e,datasetName:r,asOf:n}){let i;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:r})).id:i=e,L(i);let a=new URLSearchParams,o=n?typeof n=="string"?n:n?.toISOString():void 0;return o&&a.append("as_of",o),await this._get(`/datasets/${i}/splits`,a)}async updateDatasetSplits({datasetId:e,datasetName:r,splitName:n,exampleIds:i,remove:a=!1}){let o;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?o=(await this.readDataset({datasetName:r})).id:o=e,L(o);let l={split_name:n,examples:i.map(u=>(L(u),u)),remove:a},c=JSON.stringify(l);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${o}/splits`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await C(u,"update dataset splits",!0),u})}async createFeedback(e,r,n){let{runId:i=null,key:a,score:o,value:l,correction:c,comment:u,sourceInfo:d,feedbackSourceType:p="api",sourceRunId:h,feedbackId:g,feedbackConfig:b,projectId:v,comparativeExperimentId:P,sessionId:I,startTime:S,extendTraceRetention:A}=typeof e=="object"&&e!==null?e:{runId:e,key:r,...n};if(!i&&!v)throw new Error("One of runId or projectId must be provided");if(i&&v)throw new Error("Only one of runId or projectId can be provided");i&&I===void 0&&await this._checkFeedbackSessionId();let R={type:p??"api",metadata:d??{}};h!==void 0&&R?.metadata!==void 0&&!R.metadata.__run&&(R.metadata.__run={run_id:h}),R?.metadata!==void 0&&R.metadata.__run?.run_id!==void 0&&L(R.metadata.__run.run_id);let $={id:g??Xt(),run_id:i,key:a,score:$c(o),value:l,correction:c,comment:u,feedback_source:R,comparative_experiment_id:P,feedbackConfig:b,session_id:I??v,start_time:S,extend_trace_retention:A},N=JSON.stringify($),j=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let y=await this._fetch(j,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:N});return await C(y,"create feedback",!0),y}),$}async updateFeedback(e,{score:r,value:n,correction:i,comment:a}){let o={};r!=null&&(o.score=$c(r)),n!=null&&(o.value=n),i!=null&&(o.correction=i),a!=null&&(o.comment=a),L(e);let l=JSON.stringify(o);await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await C(c,"update feedback",!0),c})}async readFeedback(e){L(e);let r=`/feedback/${e}`;return await this._get(r)}async deleteFeedback(e){L(e);let r=`/feedback/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:r,feedbackSourceTypes:n}={}){let i=new URLSearchParams;if(e)for(let a of e)L(a),i.append("run",a);if(r)for(let a of r)i.append("key",a);if(n)for(let a of n)i.append("source",a);for await(let a of this._getPaginated("/feedback",i))yield*a}async createPresignedFeedbackToken(e,r,{expiration:n,feedbackConfig:i}={}){let a={run_id:e,feedback_key:r,feedback_config:i};n?typeof n=="string"?a.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(a.expires_in=n):a.expires_in={hours:3};let o=JSON.stringify(a);return await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await C(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:e,experimentIds:r,referenceDatasetId:n,createdAt:i,description:a,metadata:o,id:l}){if(r.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:r[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");let c={id:l,name:e,experiment_ids:r,reference_dataset_id:n,description:a,created_at:(i??new Date)?.toISOString(),extra:{}};o&&(c.extra.metadata=o);let u=JSON.stringify(c);return(await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await C(p,"create comparative experiment"),p})).json()}async*listPresignedFeedbackTokens(e){L(e);let r=new URLSearchParams({run_id:e});for await(let n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(e){let r;return"results"in e?r=e.results:Array.isArray(e)?r=e:r=[e],r}async _logEvaluationFeedback(e,r,n,i){let a=this._selectEvalResults(e),o=[];for(let l of a){let c=n||{};l.evaluatorInfo&&(c={...l.evaluatorInfo,...c});let u=null;l.targetRunId?u=l.targetRunId:r&&(u=r.id),o.push(await this.createFeedback(u,l.key,{score:l.score,value:l.value,comment:l.comment,correction:l.correction,sourceInfo:c,sourceRunId:l.sourceRunId,feedbackConfig:l.feedbackConfig,feedbackSourceType:"model",sessionId:r?.session_id??i,startTime:r?.start_time}))}return[a,o]}async logEvaluationFeedback(e,r,n,i){if(e!=null&&typeof e=="object"&&"evaluatorResponse"in e){let[o]=await this._logEvaluationFeedback(e.evaluatorResponse,e.run,e.sourceInfo,e.projectId);return o}let[a]=await this._logEvaluationFeedback(e,r,n,i);return a}async createFeedbackConfig(e){let{feedbackKey:r,feedbackConfig:n,isLowerScoreBetter:i=!1}=e,a={feedback_key:r,feedback_config:n,is_lower_score_better:i};return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await C(l,"create feedback config"),l})).json()}async*listFeedbackConfigs(e={}){let{feedbackKeys:r,nameContains:n,limit:i}=e,a=new URLSearchParams;r&&r.forEach(l=>{a.append("key",l)}),n&&a.append("name_contains",n),a.append("limit",(i!==void 0?Math.min(i,100):100).toString());let o=0;for await(let l of this._getPaginated("/feedback-configs",a))if(yield*l,o+=l.length,i!==void 0&&o>=i)break}async updateFeedbackConfig(e,r={}){let{feedbackConfig:n,isLowerScoreBetter:i}=r,a={feedback_key:e};return n!==void 0&&(a.feedback_config=n),i!==void 0&&(a.is_lower_score_better=i),(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await C(l,"update feedback config"),l})).json()}async deleteFeedbackConfig(e){let r=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/feedback-configs?${r}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(n,"delete feedback config",!0),n})}async*listAnnotationQueues(e={}){let{queueIds:r,name:n,nameContains:i,limit:a}=e,o=new URLSearchParams;r&&r.forEach((c,u)=>{L(c,`queueIds[${u}]`),o.append("ids",c)}),n&&o.append("name",n),i&&o.append("name_contains",i),o.append("limit",(a!==void 0?Math.min(a,100):100).toString());let l=0;for await(let c of this._getPaginated("/annotation-queues",o))if(yield*c,l++,a!==void 0&&l>=a)break}async createAnnotationQueue(e){let{name:r,description:n,queueId:i,rubricInstructions:a,rubricItems:o}=e,l={name:r,description:n,id:i||Et(),rubric_instructions:a,rubric_items:o},c=JSON.stringify(Object.fromEntries(Object.entries(l).filter(([d,p])=>p!==void 0)));return(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await C(d,"create annotation queue"),d})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${L(e,"queueId")}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,r){let{name:n,description:i,rubricInstructions:a,rubricItems:o}=r,l={};n!==void 0&&(l.name=n),i!==void 0&&(l.description=i),a!==void 0&&(l.rubric_instructions=a),o!==void 0&&(l.rubric_items=o);let c=JSON.stringify(l);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/annotation-queues/${L(e,"queueId")}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await C(u,"update annotation queue",!0),u})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${L(e,"queueId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(e,r){let n=`${this.apiUrl}/annotation-queues/${L(e,"queueId")}/runs`,i=r.every(l=>typeof l=="string"),a,o;i?(se("Passing run IDs as strings to addRunsToAnnotationQueue() is deprecated and will be removed after Jan 31, 2027. Use RunKey[] instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#annotation-queues-add-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_ADD_RUNS_STRING_IDS"}),a=n,o=JSON.stringify(r.map((l,c)=>L(l,`runs[${c}]`).toString()))):(a=`${n}/by-key`,o=JSON.stringify(r.map((l,c)=>{let u={run_id:L(l.runId,`runs[${c}].runId`).toString(),session_id:L(l.sessionId,`runs[${c}].sessionId`).toString(),start_time:typeof l.startTime=="string"?l.startTime:new Date(l.startTime).toISOString()};return l.sourceProposedExampleId!=null&&(u.source_proposed_example_id=L(l.sourceProposedExampleId,`runs[${c}].sourceProposedExampleId`).toString()),u}))),await this.caller.call(async()=>{let l=await this._fetch(a,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await C(l,"add runs to annotation queue",!0),l})}async getRunFromAnnotationQueue(e,r){let n=`/annotation-queues/${L(e,"queueId")}/run`,a=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(o,"get run from annotation queue"),o})).json();return yr(a)}async*listRunsFromAnnotationQueue(e,r={}){let{status:n,limit:i}=r,a=new URLSearchParams,o=i!==void 0&&Number.isFinite(i)?Math.min(i,100):100;n&&a.append("status",n),a.append("limit",o.toString());let l=0,c=`/annotation-queues/${L(e,"queueId")}/runs`;for await(let u of this._getPaginated(c,a))for(let d of u)if(yield yr(d),l++,l>=o)return}async deleteRunFromAnnotationQueue(e,r){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${L(e,"queueId")}/runs/${L(r,"queueRunId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${L(e,"queueId")}/size`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(e){let r=await this._getSettings();return e=="-"||r.tenant_handle===e}async _ownerConflictError(e,r){let n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
137
+
138
+ Current tenant: ${n.tenant_handle}
139
+
140
+ Requested tenant: ${r}`)}async _getLatestCommitHash(e){let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(i,"get latest commit hash"),i})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _createCommitTags(e,r,n){let i=typeof n=="string"?[n]:n;await Promise.all(i.map(async a=>this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/repos/${e}/tags`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify({tag_name:a,commit_id:r})});return await C(o,"create commit tag"),o})))}async _likeOrUnlikePrompt(e,r){let[n,i,a]=he(e),o=JSON.stringify({like:r});return(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/likes/${n}/${i}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await C(c,`${r?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(e){let[r,n,i]=he(e);if(await this._currentTenantIsOwner(r)){let a=await this._getSettings();return i!=="latest"?`${this.getHostUrl()}/prompts/${n}/${i.substring(0,8)}?organizationId=${a.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${a.id}`}else return i!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${i.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){let[r,n,i]=he(e);for await(let a of this._getPaginated(`/commits/${r}/${n}/`,new URLSearchParams,o=>o.commits))yield*a}async*listPrompts(e){let r=new URLSearchParams;r.append("sort_field",e?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&r.append("is_public",e.isPublic.toString()),e?.query&&r.append("query",e.query);for await(let n of this._getPaginated("/repos",r,i=>i.repos))yield*n}async getPrompt(e){let[r,n,i]=he(e),o=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return l?.status===404?null:(await C(l,"get prompt"),l)}))?.json();return o?.repo?o.repo:null}async createPrompt(e,r){let n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
141
+
142
+ creating a LangChain Hub handle.
143
+ You can add a handle by creating a public prompt at:
144
+
145
+ https://smith.langchain.com/prompts`);let[i,a,o]=he(e);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError("create a prompt",i);let l={repo_handle:a,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},c=JSON.stringify(l),u=await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await C(p,"create prompt"),p}),{repo:d}=await u.json();return d}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[i,a,o]=he(e),l=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${i}/${a}`):n?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(r)),parent_commit:l,...n?.description!==void 0&&{description:n.description}},u=JSON.stringify(c),p=await(await this.caller.call(async()=>{let g=await this._fetch(`${this.apiUrl}/commits/${i}/${a}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await C(g,"create commit"),g})).json(),h=p.commit??p;return n?.tags&&await this._createCommitTags(`${i}/${a}`,h.id,n.tags),this._getPromptUrl(`${i}/${a}${h.commit_hash?`:${h.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let o of r){let l=o.id,c={...o.metadata&&{metadata:o.metadata},...o.split&&{split:o.split}},u=ge(c,`Serializing body for example with id: ${l}`),d=new Blob([u],{type:"application/json"});if(n.append(l,d),o.inputs){let p=ge(o.inputs,`Serializing inputs for example with id: ${l}`),h=new Blob([p],{type:"application/json"});n.append(`${l}.inputs`,h)}if(o.outputs){let p=ge(o.outputs,`Serializing outputs whle updating example with id: ${l}`),h=new Blob([p],{type:"application/json"});n.append(`${l}.outputs`,h)}if(o.attachments)for(let[p,h]of Object.entries(o.attachments)){let g,b;Array.isArray(h)?[g,b]=h:(g=h.mimeType,b=h.data);let v=new Blob([b],{type:`${g}; length=${b.byteLength}`});n.append(`${l}.attachment.${p}`,v)}if(o.attachments_operations){let p=ge(o.attachments_operations,`Serializing attachments while updating example with id: ${l}`),h=new Blob([p],{type:"application/json"});n.append(`${l}.attachments_operations`,h)}}let i=e??r[0]?.dataset_id;return(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${i}/examples`)}`,{method:"PATCH",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await C(o,"update examples"),o})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let a of r){let o=(a.id??Et()).toString(),l={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split},...a.source_run_id&&{source_run_id:a.source_run_id},...a.use_source_run_io&&{use_source_run_io:a.use_source_run_io},...a.use_source_run_attachments&&{use_source_run_attachments:a.use_source_run_attachments}},c=ge(l,`Serializing body for uploaded example with id: ${o}`),u=new Blob([c],{type:"application/json"});if(n.append(o,u),a.inputs){let d=ge(a.inputs,`Serializing inputs for uploaded example with id: ${o}`),p=new Blob([d],{type:"application/json"});n.append(`${o}.inputs`,p)}if(a.outputs){let d=ge(a.outputs,`Serializing outputs for uploaded example with id: ${o}`),p=new Blob([d],{type:"application/json"});n.append(`${o}.outputs`,p)}if(a.attachments)for(let[d,p]of Object.entries(a.attachments)){let h,g;Array.isArray(p)?[h,g]=p:(h=p.mimeType,g=p.data);let b=new Blob([g],{type:`${h}; length=${g.byteLength}`});n.append(`${o}.attachment.${d}`,b)}}return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await C(a,"upload examples"),a})).json()}async updatePrompt(e,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[n,i]=he(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let a={};if(r?.description!==void 0&&(a.description=r.description),r?.readme!==void 0&&(a.readme=r.readme),r?.tags!==void 0&&(a.tags=r.tags),r?.isPublic!==void 0&&(a.is_public=r.isPublic),r?.isArchived!==void 0&&(a.is_archived=r.isArchived),Object.keys(a).length===0)throw new Error("No valid update options provided");let o=JSON.stringify(a);return(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/repos/${n}/${i}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await C(c,"update prompt"),c})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[r,n,i]=he(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(o,"delete prompt"),o})).json()}_getPromptCacheKey(e,r){return`${e}${r?":with_model":""}`}async _fetchPromptFromApi(e,r){let[n,i,a]=he(e),l=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/commits/${n}/${i}/${a}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(c,"pull prompt commit"),c})).json();return{owner:n,repo:i,commit_hash:l.commit_hash,manifest:l.manifest,examples:l.examples,hub_model_config:l.model_config,hub_model_provider:l.model_provider}}async pullPromptCommit(e,r){Cm(e,r?.dangerouslyPullPublicPrompt);let n=this._fetchPromptFromApi.bind(this,e,r);if(!r?.skipCache&&this._promptCache){let i=this._getPromptCacheKey(e,r?.includeModel),a=this._promptCache.get(i,n);if(a)return a;let o=await n();return this._promptCache.set(i,o,n),o}return this._fetchPromptFromApi(e,r)}async _pullPrompt(e,r){let n=await this.pullPromptCommit(e,{includeModel:r?.includeModel,skipCache:r?.skipCache,dangerouslyPullPublicPrompt:r?.dangerouslyPullPublicPrompt});return JSON.stringify(n.manifest)}async pushPrompt(e,r){return await this.promptExists(e)?r&&["description","readme","tags","isPublic"].some(i=>r[i]!==void 0)&&await this.updatePrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(e,r?.object,{parentCommitHash:r?.parentCommitHash,tags:r?.commitTags,description:r?.commitDescription}):await this._getPromptUrl(e)}async agentExists(e){let[r,n]=he(e);return this._repoExists(r,n)}async skillExists(e){let[r,n]=he(e);return this._repoExists(r,n)}async pullAgent(e,r){return await this._pullDirectory(e,"agent",r?.version)}async pullSkill(e,r){return await this._pullDirectory(e,"skill",r?.version)}async pushAgent(e,r){return this._pushDirectory(e,"agent",r)}async pushSkill(e,r){return this._pushDirectory(e,"skill",r)}async deleteAgent(e){return this._deleteDirectory(e)}async deleteSkill(e){return this._deleteDirectory(e)}async*listAgents(e){yield*this._listReposByType("agent",e)}async*listSkills(e){yield*this._listReposByType("skill",e)}async*_listReposByType(e,r){let n=new URLSearchParams;n.append("repo_type",e),n.append("is_archived",(!!r?.isArchived).toString()),r?.isPublic!==void 0&&n.append("is_public",r.isPublic.toString()),r?.query&&n.append("query",r.query);for await(let i of this._getPaginated("/repos",n,a=>a.repos))yield*i}async _pullDirectory(e,r,n){let[i,a,o]=he(e),l=n??(o!=="latest"?o:void 0),c=new URL(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${i}/${a}/directories`)}`);return c.searchParams.set("repo_type",r),l&&c.searchParams.set("commit",l),await(await this.caller.call(async()=>{let d=await this._fetch(c.toString(),{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(d,"pull directory"),d})).json()}async _pushDirectory(e,r,n){if(n.parentCommit!==void 0&&(n.parentCommit.length<8||n.parentCommit.length>64))throw new Error("parent_commit must be 8-64 characters");let[i,a]=he(e);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError(`push ${r}`,i);if(await this._repoExists(i,a))(n.description!==void 0||n.readme!==void 0||n.tags!==void 0||n.isPublic!==void 0)&&await this._updateRepoMetadata(i,a,n);else{let h=/^[a-z][a-z0-9-_]*$/;if(!h.test(a))throw new Error(`Invalid repo_handle ${JSON.stringify(a)}: must match ${h}`);await this._createRepo(a,r,n)}let o={files:n.files};n.parentCommit&&(o.parent_commit=n.parentCommit);let u=(await(await this.caller.call(async()=>{let h=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${i}/${a}/directories/commits`)}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(o)});return await C(h,`push ${r}`),h})).json()).commit.commit_hash,d=await this._getSettings(),p=new URLSearchParams({organizationId:d.id});return`${this.getHostUrl()}/context/${a}/${u.slice(0,8)}?${p.toString()}`}async _deleteDirectory(e){let[r,n]=he(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete",r);await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${r}/${n}/directories`)}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(i,"delete directory"),i})}async _repoExists(e,r){try{return await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/repos/${e}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(n,"check repo exists"),n}),!0}catch(n){if(Bn(n))return!1;throw n}}async _createRepo(e,r,n){let i={repo_handle:e,repo_type:r,is_public:!!n.isPublic};n.description!==void 0&&(i.description=n.description),n.readme!==void 0&&(i.readme=n.readme),n.tags!==void 0&&(i.tags=n.tags);try{await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await C(a,`create ${r}`),a})}catch(a){if(yc(a))return;throw a}}async _updateRepoMetadata(e,r,n){let i={};n.description!==void 0&&(i.description=n.description),n.readme!==void 0&&(i.readme=n.readme),n.tags!==void 0&&(i.tags=n.tags),n.isPublic!==void 0&&(i.is_public=n.isPublic),Object.keys(i).length!==0&&await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/${e}/${r}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await C(a,"update repo metadata"),a})}async clonePublicDataset(e,r={}){let{sourceApiUrl:n=this.apiUrl,datasetName:i}=r,[a,o]=this.parseTokenOrUrl(e,n),l=new t({apiUrl:a,apiKey:"placeholder"}),c=await l.readSharedDataset(o),u=i||c.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}let d=await l.listSharedExamples(o),p=await this.createDataset(u,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:d.map(h=>h.inputs),outputs:d.flatMap(h=>h.outputs?[h.outputs]:[]),datasetId:p.id})}catch(h){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),h}}parseTokenOrUrl(e,r,n=2,i="dataset"){try{return L(e),[r,e]}catch{}try{let o=new URL(e).pathname.split("/").filter(l=>l!=="");if(o.length>=n){let l=o[o.length-n];return[r,l]}else throw new Error(`Invalid public ${i} URL: ${e}`)}catch{throw new Error(`Invalid public ${i} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();for(await new Promise(e=>setTimeout(e,1));this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await Ul()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}toString(){let e=[`apiUrl=${JSON.stringify(this.apiUrl)}`];return this.webUrl!==void 0&&e.push(`webUrl=${JSON.stringify(this.webUrl)}`),this.workspaceId!==void 0&&e.push(`workspaceId=${JSON.stringify(this.workspaceId)}`),`[LangSmithClient ${e.join(" ")}]`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}};Object.defineProperty(ut,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function Fc(t){return"dataset_id"in t||"dataset_name"in t}s(Fc,"isExampleCreate");var Ge=Symbol.for("lc:context_variables");var qn=Symbol.for("langsmith:replica_trace_roots");function Da(t,e){if(Ge in t)return t[Ge][e]}s(Da,"getContextVar");function Hc(t,e,r){let n=Ge in t?t[Ge]:{};n[e]=r,t[Ge]=n}s(Hc,"setContextVar");var Dr=36,Um="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function zc(t){let r=Object.keys(t).sort().map(n=>`${n}:${t[n]??""}`).join("|");return Ni(r,Um)}s(zc,"getReplicaKey");function Fm(t){return t.replace(/[-:.]/g,"")}s(Fm,"stripNonAlphanumeric");function Vc(t,e=1){let r=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${r}Z`}s(Vc,"getMicrosecondPrecisionDatestring");function Ua(t,e,r=1){let n=Vc(t,r);return{dottedOrder:Fm(n)+e,microsecondPrecisionDatestring:n}}s(Ua,"convertToDottedOrderFormat");var jm=new Set(["projectName","primary","updates","reroot"]);function Bm(t){let e={};for(let r of Object.keys(t))r==="primary"&&typeof t[r]!="boolean"||jm.has(r)&&(e[r]=t[r]);return e}s(Bm,"filterReplicaForHeaders");var Wn=class t{static{s(this,"Baggage")}constructor(e,r,n,i){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=r,this.project_name=n,this.replicas=i}static fromHeader(e){let r=e.split(","),n={},i=[],a,o;for(let l of r){let[c,u]=l.split("="),d=decodeURIComponent(u);c==="langsmith-metadata"?n=JSON.parse(d):c==="langsmith-tags"?i=d.split(","):c==="langsmith-project"?a=d:c==="langsmith-replicas"&&(o=JSON.parse(d).map(h=>Array.isArray(h)?h:Bm(h)))}return new t(n,i,a,o)}toHeader(){let e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}},Le=class t{static{s(this,"RunTree")}constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),qc(e)){Object.assign(this,{...e});return}let r=t.getDefaultConfig(),{metadata:n,...i}=e,a=i.client??t.getSharedClient(),o={...n,...i?.extra?.metadata};if(i.extra={...i.extra,metadata:o},"id"in i&&i.id==null&&delete i.id,Object.assign(this,{...r,...i,client:a}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=Vc(this.start_time,this.execution_order)),this.id||(this.id=gn(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=Vm(this.replicas),!this.dotted_order){let{dottedOrder:l}=Ua(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+l:this.dotted_order=l}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let e=Date.now();return{run_type:"chain",project_name:kr(),child_runs:[],api_url:ae("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:ae("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return t.sharedClient||(t.sharedClient=new ut),t.sharedClient}createChild(e){let r=this.child_execution_order+1,n=this.replicas?.map(h=>{let{reroot:g,...b}=h;return b}),i=e.replicas??n,a=new t({...e,parent_run:this,project_name:this.project_name,replicas:i,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r}),o=this.extra?.metadata??{},l=a.extra?.metadata??{};Object.keys(o).length>0&&(a.extra={...a.extra,metadata:{...o,...l}}),Ge in this&&(a[Ge]=this[Ge]);let c=Symbol.for("lc:child_config"),u=e.extra?.[c]??this.extra[c];if(zm(u)){let h={...u},g=Hm(h.callbacks)?h.callbacks.copy?.():void 0;g&&(Object.assign(g,{_parentRunId:a.id}),g.handlers?.find(Wc)?.updateFromRunTree?.(a),h.callbacks=g),a.extra[c]=h}let d=new Set,p=this;for(;p!=null&&!d.has(p.id);)d.add(p.id),p.child_execution_order=Math.max(p.child_execution_order,r),p=p.parent_run;return this.child_runs.push(a),a}async end(e,r,n=Date.now(),i){this.outputs=this.outputs??e,this.error=this.error??r,this.end_time=this.end_time??n,i&&Object.keys(i).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...i}}:{metadata:i})}_convertToCreate(e,r,n=!0){let i=e.extra??{};if(i?.runtime?.library===void 0&&(i.runtime||(i.runtime={}),r))for(let[l,c]of Object.entries(r))i.runtime[l]||(i.runtime[l]=c);let a=e.parent_run?.id??e.parent_run_id,o;return n?o=[]:o=e.child_runs.map(l=>this._convertToCreate(l,r,n)),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:i,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:o,parent_run_id:a,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,r){if(r.dotted_order){let n=r.dotted_order.split("."),i=null;for(let a=0;a<n.length;a++)if(n[a].slice(-Dr)===e){i=a;break}if(i!==null){let a=n.slice(i+1);r.dotted_order=a.join("."),a.length>0?r.trace_id=a[0].slice(-Dr):r.trace_id=r.id}}r.parent_run_id===e&&(r.parent_run_id=void 0)}_setReplicaTraceRoot(e,r){let n=Da(this,qn)??{};n[e]=r,Hc(this,qn,n);for(let i of this.child_runs)i._setReplicaTraceRoot(e,r)}_remapForProject(e){let{projectName:r,primary:n,runtimeEnv:i,excludeChildRuns:a=!0,reroot:o=!1,distributedParentId:l,apiUrl:c,apiKey:u,workspaceId:d}=e,p=this._convertToCreate(this,i,a);if(n===void 0&&r===this.project_name)return{...p,session_name:r};if(o){if(l)this._sliceParentId(l,p);else if(p.parent_run_id=void 0,p.dotted_order){let A=p.dotted_order.split(".");A.length>0&&(p.dotted_order=A[A.length-1],p.trace_id=p.id)}let S=zc({projectName:r,apiUrl:c,apiKey:u,workspaceId:d});this._setReplicaTraceRoot(S,p.id)}let h;if(!o){let S=Da(this,qn)??{},A=zc({projectName:r,apiUrl:c,apiKey:u,workspaceId:d});if(h=S[A],h&&(p.trace_id=h,p.dotted_order)){let R=p.dotted_order.split("."),$=null;for(let N=0;N<R.length;N++)if(R[N].slice(-Dr)===h){$=N;break}if($!==null){let N=R.slice($);p.dotted_order=N.join(".")}}}if(n)return{...p,session_name:r};let g=p.id,b=rr(g,r),v;p.trace_id?v=rr(p.trace_id,r):v=b;let P;p.parent_run_id&&(P=rr(p.parent_run_id,r));let I;return p.dotted_order&&(I=p.dotted_order.split(".").map(R=>{let $=R.slice(-Dr),N=rr($,r);return R.slice(0,-Dr)+N}).join(".")),{...p,id:b,trace_id:v,parent_run_id:P,dotted_order:I,session_name:r}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let r=xn();if(this.replicas&&this.replicas.length>0)for(let{projectName:n,primary:i,apiKey:a,apiUrl:o,workspaceId:l,reroot:c,client:u}of this.replicas){let d=this._remapForProject({projectName:n??this.project_name,primary:i,runtimeEnv:r,excludeChildRuns:!0,reroot:c,distributedParentId:this.distributedParentId,apiUrl:o,apiKey:a,workspaceId:l});await(u??this.client).createRun(d,{apiKey:a,apiUrl:o,workspaceId:l})}else{let n=this._convertToCreate(this,r,e);await this.client.createRun(n)}if(!e){se("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let n of this.child_runs)await n.postRun(!1)}this.child_runs=[]}catch(r){console.error(`Error in postRun for run ${this.id}:`,r)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:r,primary:n,apiKey:i,apiUrl:a,workspaceId:o,updates:l,reroot:c,client:u}of this.replicas){let d=this._remapForProject({projectName:r??this.project_name,primary:n,runtimeEnv:void 0,excludeChildRuns:!0,reroot:c,distributedParentId:this.distributedParentId,apiUrl:a,apiKey:i,workspaceId:o}),p={id:d.id,name:d.name,run_type:d.run_type,start_time:d.start_time,outputs:d.outputs,error:d.error,parent_run_id:d.parent_run_id,session_name:d.session_name,reference_example_id:d.reference_example_id,end_time:d.end_time,dotted_order:d.dotted_order,trace_id:d.trace_id,events:d.events,tags:d.tags,extra:d.extra,attachments:this.attachments,...l};e?.excludeInputs||(p.inputs=d.inputs),await(u??this.client).updateRun(d.id,p,{apiKey:i,apiUrl:a,workspaceId:o})}else try{let r={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,r){let n=e?.callbacks,i,a,o,l=qi();if(n){let u=n?.getParentRunId?.()??"",d=n?.handlers?.find(p=>p?.name=="langchain_tracer");i=d?.getRun?.(u),a=d?.projectName,o=d?.client,l=l||!!d}return i?new t({name:i.name,id:i.id,trace_id:i.trace_id,dotted_order:i.dotted_order,client:o,tracingEnabled:l,project_name:a,tags:[...new Set((i?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...i?.extra?.metadata,...e?.metadata}}}).createChild(r):new t({...r,client:o,tracingEnabled:l,project_name:a})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,r){let n="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,i=n["langsmith-trace"];if(!i||typeof i!="string")return;let a=i.trim(),o=a.split(".").map(d=>{let[p,h]=d.split("Z");return{strTime:p,time:Date.parse(p+"Z"),uuid:h}}),l=o[0].uuid,c={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:o.at(-1)?.uuid,trace_id:l,dotted_order:a};if(n.baggage&&typeof n.baggage=="string"){let d=Wn.fromHeader(n.baggage);c.metadata=d.metadata,c.tags=d.tags,c.project_name=d.project_name,c.replicas=d.replicas}let u=new t(c);return u.distributedParentId=u.id,u}toHeaders(e){let r={"langsmith-trace":this.dotted_order,baggage:new Wn(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[n,i]of Object.entries(r))e.set(n,i);return r}};Object.defineProperty(Le,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function qc(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}s(qc,"isRunTree");function Wc(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}s(Wc,"isLangChainTracerLike");function Gc(t){return Array.isArray(t)&&t.some(e=>Wc(e))}s(Gc,"containsLangChainTracerLike");function Hm(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}s(Hm,"isCallbackManagerLike");function zm(t){let e=t?.callbacks;return t!=null&&typeof e=="object"&&(Gc(e?.handlers)||Gc(e))}s(zm,"isRunnableConfigLike");function Gm(){let t=ae("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{let e=JSON.parse(t);if(Array.isArray(e)){let r=[];for(let n of e){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}if(n.project_name!==void 0&&n.project_name!==null&&typeof n.project_name!="string"){console.warn(`Invalid project_name type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.project_name}`);continue}if(n.primary!==void 0&&typeof n.primary!="boolean"){console.warn(`Invalid primary type in LANGSMITH_RUNS_ENDPOINTS: expected boolean, got ${typeof n.primary}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key,projectName:n.project_name??void 0,primary:n.primary??void 0})}return r}else if(typeof e=="object"&&e!==null){qm(e);let r=[];for(let[n,i]of Object.entries(e)){let a=n.replace(/\/$/,"");if(typeof i=="string")r.push({apiUrl:a,apiKey:i});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof i}`);continue}}return r}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(bc(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}s(Gm,"_getWriteReplicasFromEnv");function Vm(t){let e=t?t.map(r=>Array.isArray(r)?{projectName:r[0],updates:r[1]}:r):Gm();if(e.filter(r=>r.primary===!0).length>1)throw new Error("Only one replica can be marked as primary.");return e}s(Vm,"_ensureWriteReplicas");function qm(t){if(Object.keys(t).length>0&&q("ENDPOINT"))throw new Fn}s(qm,"_checkEndpointEnvUnset");var Wm=s(t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t},"convertRunTreeToRun");function ja(t,e){if(t)return new Le({...t,start_time:t._serialized_start_time??t.start_time,parent_run:ja(e),child_runs:t.child_runs.map(r=>ja(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:Co()},tracingEnabled:!1})}s(ja,"convertRunToRunTree");function Fa(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}s(Fa,"_coerceToDict");function _r(t){return typeof t._addRunToRunMap=="function"}s(_r,"isBaseTracer");var Ht=class extends Jt{static{s(this,"BaseTracer")}runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(t){super(...arguments)}copy(){return this}getRunById(t){if(t!==void 0)return this.usesRunTreeMap?Wm(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`
146
+
147
+ ${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,e){t.child_runs.push(e)}_addRunToRunMap(t){let{dottedOrder:e,microsecondPrecisionDatestring:r}=Ua(new Date(t.start_time).getTime(),t.id,t.execution_order),n={...t},i=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?i?(this._addChildRun(i,n),i.child_execution_order=Math.max(i.child_execution_order,n.child_execution_order),n.trace_id=i.trace_id,i.dotted_order!==void 0&&(n.dotted_order=[i.dotted_order,e].join("."),n._serialized_start_time=r)):n.parent_run_id=void 0:(n.trace_id=n.id,n.dotted_order=e,n._serialized_start_time=r),this.usesRunTreeMap){let a=ja(n,i);a!==void 0&&this.runTreeMap.set(n.id,a)}else this.runMap.set(n.id,n);return n}async _endTrace(t){let e=t.parent_run_id!==void 0&&this.getRunById(t.parent_run_id);e?e.child_execution_order=Math.max(e.child_execution_order,t.child_execution_order):await this.persistRun(t),await this.onRunUpdate?.(t),this.usesRunTreeMap?this.runTreeMap.delete(t.id):this.runMap.delete(t.id)}_getExecutionOrder(t){let e=t!==void 0&&this.getRunById(t);return e?e.child_execution_order+1:1}_createRunForLLMStart(t,e,r,n,i,a,o,l){let c=this._getExecutionOrder(n),u=Date.now(),d=o?{...i,metadata:o}:i,p={id:r,name:l??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:e},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(p)}async handleLLMStart(t,e,r,n,i,a,o,l){let c=this.getRunById(r)??this._createRunForLLMStart(t,e,r,n,i,a,o,l);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(t,e,r,n,i,a,o,l){let c=this._getExecutionOrder(n),u=Date.now(),d=o?{...i,metadata:o}:i,p={id:r,name:l??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:e},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(p)}async handleChatModelStart(t,e,r,n,i,a,o,l){let c=this.getRunById(r)??this._createRunForChatModelStart(t,e,r,n,i,a,o,l);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(t,e,r,n,i){let a=this.getRunById(e);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=t,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMEnd?.(a),await this._endTrace(a),a}async handleLLMError(t,e,r,n,i){let a=this.getRunById(e);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(t),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMError?.(a),await this._endTrace(a),a}_createRunForChainStart(t,e,r,n,i,a,o,l,c){let u=this._getExecutionOrder(n),d=Date.now(),p={id:r,name:l??t.id[t.id.length-1],parent_run_id:n,start_time:d,serialized:t,events:[{name:"start",time:new Date(d).toISOString()}],inputs:e,execution_order:u,child_execution_order:u,run_type:o??"chain",child_runs:[],extra:a?{...c,metadata:a}:{...c},tags:i||[]};return this._addRunToRunMap(p)}async handleChainStart(t,e,r,n,i,a,o,l){let c=this.getRunById(r)??this._createRunForChainStart(t,e,r,n,i,a,o,l);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(t,e,r,n,i){let a=this.getRunById(e);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=Fa(t,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=Fa(i.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(t,e,r,n,i){let a=this.getRunById(e);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(t),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=Fa(i.inputs,"input")),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(t,e,r,n,i,a,o){let l=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:e},execution_order:l,child_execution_order:l,run_type:"tool",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleToolStart(t,e,r,n,i,a,o){let l=this.getRunById(r)??this._createRunForToolStart(t,e,r,n,i,a,o);return await this.onRunCreate?.(l),await this.onToolStart?.(l),l}async handleToolEnd(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="chain")return;let n=r;n.actions=n.actions||[],n.actions.push(t),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentAction?.(r)}async handleAgentEnd(t,e){let r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(t,e,r,n,i,a,o){let l=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:e},execution_order:l,child_execution_order:l,run_type:"retriever",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(t,e,r,n,i,a,o){let l=this.getRunById(r)??this._createRunForRetrieverStart(t,e,r,n,i,a,o);return await this.onRunCreate?.(l),await this.onRetrieverStart?.(l),l}async handleRetrieverEnd(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(t,e){let r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:t}}),await this.onText?.(r))}async handleLLMNewToken(t,e,r,n,i,a){let o=this.getRunById(r);if(!o||o?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return o.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:t,idx:e,chunk:a?.chunk}}),await this.onLLMNewToken?.(o,t,{chunk:a?.chunk}),o}};var Jc={bold:{open:"\x1B[1m",close:"\x1B[22m"},color:{grey:{open:"\x1B[90m",close:"\x1B[39m"},green:{open:"\x1B[32m",close:"\x1B[39m"},cyan:{open:"\x1B[36m",close:"\x1B[39m"},red:{open:"\x1B[31m",close:"\x1B[39m"},blue:{open:"\x1B[34m",close:"\x1B[39m"}}};function we(t,e){return`${t.open}${e}${t.close}`}s(we,"wrap");function ke(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}s(ke,"tryJsonStringify");function Kc(t){return typeof t=="string"?t.trim():t==null?t:ke(t,t.toString())}s(Kc,"formatKVMapItem");function gt(t){if(!t.end_time)return"";let e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}s(gt,"elapsed");var{color:Se}=Jc,Ba=class extends Ht{static{s(this,"ConsoleCallbackHandler")}name="console_callback_handler";persistRun(t){return Promise.resolve()}getParents(t){let e=[],r=t;for(;r.parent_run_id;){let n=this.runMap.get(r.parent_run_id);if(n)e.push(n),r=n;else break}return e}getBreadcrumbs(t){let e=[...this.getParents(t).reverse(),t].map((r,n,i)=>{let a=`${r.execution_order}:${r.run_type}:${r.name}`;return n===i.length-1?we(Jc.bold,a):a}).join(" > ");return we(Se.grey,e)}onChainStart(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.green,"[chain/start]")} [${e}] Entering Chain run with input: ${ke(t.inputs,"[inputs]")}`)}onChainEnd(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.cyan,"[chain/end]")} [${e}] [${gt(t)}] Exiting Chain run with output: ${ke(t.outputs,"[outputs]")}`)}onChainError(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.red,"[chain/error]")} [${e}] [${gt(t)}] Chain run errored with error: ${ke(t.error,"[error]")}`)}onLLMStart(t){let e=this.getBreadcrumbs(t),r="prompts"in t.inputs?{prompts:t.inputs.prompts.map(n=>n.trim())}:t.inputs;console.log(`${we(Se.green,"[llm/start]")} [${e}] Entering LLM run with input: ${ke(r,"[inputs]")}`)}onLLMEnd(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.cyan,"[llm/end]")} [${e}] [${gt(t)}] Exiting LLM run with output: ${ke(t.outputs,"[response]")}`)}onLLMError(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.red,"[llm/error]")} [${e}] [${gt(t)}] LLM run errored with error: ${ke(t.error,"[error]")}`)}onToolStart(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.green,"[tool/start]")} [${e}] Entering Tool run with input: "${Kc(t.inputs.input)}"`)}onToolEnd(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.cyan,"[tool/end]")} [${e}] [${gt(t)}] Exiting Tool run with output: "${Kc(t.outputs?.output)}"`)}onToolError(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.red,"[tool/error]")} [${e}] [${gt(t)}] Tool run errored with error: ${ke(t.error,"[error]")}`)}onRetrieverStart(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${ke(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.cyan,"[retriever/end]")} [${e}] [${gt(t)}] Exiting Retriever run with output: ${ke(t.outputs,"[outputs]")}`)}onRetrieverError(t){let e=this.getBreadcrumbs(t);console.log(`${we(Se.red,"[retriever/error]")} [${e}] [${gt(t)}] Retriever run errored with error: ${ke(t.error,"[error]")}`)}onAgentAction(t){let e=t,r=this.getBreadcrumbs(t);console.log(`${we(Se.blue,"[agent/action]")} [${r}] Agent selected action: ${ke(e.actions[e.actions.length-1],"[action]")}`)}};var Ha,za=s(()=>(Ha===void 0&&(Ha=new ut(Me("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),Ha),"getDefaultLangChainClientSingleton");var Yc=new Set(["ls_agent_type"]);function Km(t){let e;for(let r of t)for(let n of r)at.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=Qr(e,n.message.usage_metadata));return e}s(Km,"_getUsageMetadataFromGenerations");var Ur=class Ga extends Ht{static{s(this,"LangChainTracer")}name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;tracingMetadata;tracingTags=[];constructor(e={}){super(e),this.fields=e;let{exampleId:r,projectName:n,client:i,replicas:a,metadata:o,tags:l}=e;this.projectName=n??kr(),this.replicas=a,this.exampleId=r,this.client=i??za(),this.tracingMetadata=o?{...o}:void 0,this.tracingTags=l??[];let c=Ga.getTraceableRunTree();c&&this.updateFromRunTree(c)}async persistRun(e){}async onRunCreate(e){Zc(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){Zc(this,e);let r=this.getRunTreeWithTracingConfig(e.id);e.extra?.lc_defers_inputs?await r?.postRun():await r?.patchRun()}onLLMEnd(e){let r=e.outputs;if(r?.generations){let n=Km(r.generations);if(n!==void 0){e.extra=e.extra??{};let i=e.extra.metadata??{};i.usage_metadata=n,e.extra.metadata=i}}}copyWithTracingConfig({metadata:e,tags:r}){let n;if(e===void 0)n=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)n={...e};else{n={...this.tracingMetadata};for(let[o,l]of Object.entries(e))(!Object.prototype.hasOwnProperty.call(n,o)||Yc.has(o))&&(n[o]=l)}let i=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],a=new Ga({...this.fields,metadata:n,tags:i});return a.runMap=this.runMap,a.runTreeMap=this.runTreeMap,a}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let r=e,n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();let i=[r];for(;i.length>0;){let a=i.shift();!a||n.has(a.id)||(n.add(a.id),this.runTreeMap.set(a.id,a),a.child_runs&&i.push(...a.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(e){let r=this.runTreeMap.get(e);if(r)return new Le({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Zi(!0)}catch{return}}static[Symbol.hasInstance](e){if(typeof e!="object"||e===null)return!1;let r=e;return"name"in r&&r.name==="langchain_tracer"&&"copyWithTracingConfig"in r&&typeof r.copyWithTracingConfig=="function"&&"getRunTreeWithTracingConfig"in r&&typeof r.getRunTreeWithTracingConfig=="function"}};function Zc(t,e){if(t.tracingMetadata){e.extra??={};let r=e.extra.metadata??{},n=!1;for(let[i,a]of Object.entries(t.tracingMetadata))(!Object.prototype.hasOwnProperty.call(r,i)||Yc.has(i))&&r[i]!==a&&(r[i]=a,n=!0);n&&(e.extra.metadata=r)}t.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...t.tracingTags])))}s(Zc,"_patchMissingTracingDefaults");var Kn=it(cn(),1);var Fr;function Jm(){return new("default"in Kn.default?Kn.default.default:Kn.default)({autoStart:!0,concurrency:1})}s(Jm,"createQueue");function Zm(){return typeof Fr>"u"&&(Fr=Jm()),Fr}s(Zm,"getQueue");async function Y(t,e){if(e===!0){let r=ot();r!==void 0?await r.run(void 0,async()=>t()):await t()}else Fr=Zm(),Fr.add(async()=>{let r=ot();r!==void 0?await r.run(void 0,async()=>t()):await t()})}s(Y,"consumeCallback");var Xc=s(t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>Me(e)==="true"),"isTracingEnabled");function Va(t){let e=ot();if(e!==void 0)return e.getStore()?.[xt]?.[t]}s(Va,"getContextVariable");var Ym=Symbol("lc:configure_hooks"),Qc=s(()=>Va(Ym)||[],"_getConfigureHooks");var Xm=class{static{s(this,"BaseCallbackManager")}setHandler(t){return this.setHandlers([t])}},Jn=class{static{s(this,"BaseRunManager")}constructor(t,e,r,n,i,a,o,l){this.runId=t,this.handlers=e,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=i,this.metadata=a,this.inheritableMetadata=o,this._parentRunId=l}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>Y(async()=>{try{await e.handleText?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleCustomEvent(t,e,r,n,i){await Promise.all(this.handlers.map(a=>Y(async()=>{try{await a.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}},Qm=class extends Jn{static{s(this,"CallbackManagerForRetrieverRun")}getChild(t){let e=new zt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>Y(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw r}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>Y(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${r}`),e.raiseError)throw t}},e.awaitHandlers)))}},eu=class extends Jn{static{s(this,"CallbackManagerForLLMRun")}async handleLLMNewToken(t,e,r,n,i,a){await Promise.all(this.handlers.map(o=>Y(async()=>{if(!o.ignoreLLM)try{await o.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a)}catch(l){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleLLMNewToken: ${l}`),o.raiseError)throw l}},o.awaitHandlers)))}async handleChatModelStreamEvent(t){await Promise.all(this.handlers.map(e=>Y(async()=>{if(!e.ignoreLLM)try{await e.handleChatModelStreamEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleChatModelStreamEvent: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleLLMError(t,e,r,n,i){await Promise.all(this.handlers.map(a=>Y(async()=>{if(!a.ignoreLLM)try{await a.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,i)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMError: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleLLMEnd(t,e,r,n,i){await Promise.all(this.handlers.map(a=>Y(async()=>{if(!a.ignoreLLM)try{await a.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,i)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMEnd: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}},eh=class extends Jn{static{s(this,"CallbackManagerForChainRun")}getChild(t){let e=new zt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,r,n,i){await Promise.all(this.handlers.map(a=>Y(async()=>{if(!a.ignoreChain)try{await a.handleChainError?.(t,this.runId,this._parentRunId,this.tags,i)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainError: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleChainEnd(t,e,r,n,i){await Promise.all(this.handlers.map(a=>Y(async()=>{if(!a.ignoreChain)try{await a.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,i)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainEnd: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>Y(async()=>{if(!e.ignoreAgent)try{await e.handleAgentAction?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>Y(async()=>{if(!e.ignoreAgent)try{await e.handleAgentEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},th=class extends Jn{static{s(this,"CallbackManagerForToolRun")}getChild(t){let e=new zt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>Y(async()=>{if(!e.ignoreAgent)try{await e.handleToolError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEvent(t){await Promise.all(this.handlers.map(e=>Y(async()=>{if(!e.ignoreAgent)try{await e.handleToolEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if(e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>Y(async()=>{if(!e.ignoreAgent)try{await e.handleToolEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},zt=class jr extends Xm{static{s(this,"CallbackManager")}handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,r){super(),this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,r,n=void 0,i=void 0,a=void 0,o=void 0,l=void 0,c=void 0){return Promise.all(r.map(async(u,d)=>{let p=d===0&&n?n:De();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return _r(h)&&h._createRunForLLMStart(e,[u],p,this._parentRunId,a,this.tags,this.metadata,c),Y(async()=>{try{await h.handleLLMStart?.(e,[u],p,this._parentRunId,a,this.tags,this.metadata,c)}catch(g){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${g}`),h.raiseError)throw g}},h.awaitHandlers)})),new eu(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,r,n=void 0,i=void 0,a=void 0,o=void 0,l=void 0,c=void 0){return Promise.all(r.map(async(u,d)=>{let p=d===0&&n?n:De();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return _r(h)&&h._createRunForChatModelStart(e,[u],p,this._parentRunId,a,this.tags,this.metadata,c),Y(async()=>{try{if(h.handleChatModelStart)await h.handleChatModelStart?.(e,[u],p,this._parentRunId,a,this.tags,this.metadata,c);else if(h.handleLLMStart){let g=rn(u);await h.handleLLMStart?.(e,[g],p,this._parentRunId,a,this.tags,this.metadata,c)}}catch(g){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${g}`),h.raiseError)throw g}},h.awaitHandlers)})),new eu(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,r,n=De(),i=void 0,a=void 0,o=void 0,l=void 0,c=void 0,u=void 0){return await Promise.all(this.handlers.map(d=>{if(!d.ignoreChain)return _r(d)&&d._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,i,l,u),Y(async()=>{try{await d.handleChainStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,i,l,u)}catch(p){if((d.raiseError?console.error:console.warn)(`Error in handler ${d.constructor.name}, handleChainStart: ${p}`),d.raiseError)throw p}},d.awaitHandlers)})),new eh(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,r,n=De(),i=void 0,a=void 0,o=void 0,l=void 0,c=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return _r(u)&&u._createRunForToolStart(e,r,n,this._parentRunId,this.tags,this.metadata,l),Y(async()=>{try{await u.handleToolStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,l,c)}catch(d){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${d}`),u.raiseError)throw d}},u.awaitHandlers)})),new th(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,r,n=De(),i=void 0,a=void 0,o=void 0,l=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return _r(c)&&c._createRunForRetrieverStart(e,r,n,this._parentRunId,this.tags,this.metadata,l),Y(async()=>{try{await c.handleRetrieverStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,l)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new Qm(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,r,n,i,a){await Promise.all(this.handlers.map(o=>Y(async()=>{if(!o.ignoreCustomEvent)try{await o.handleCustomEvent?.(e,r,n,this.tags,this.metadata)}catch(l){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleCustomEvent: ${l}`),o.raiseError)throw l}},o.awaitHandlers)))}addHandler(e,r=!0){this.handlers.push(e),r&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(r=>r!==e),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==e)}setHandlers(e,r=!0){this.handlers=[],this.inheritableHandlers=[];for(let n of e)this.addHandler(n,r)}addTags(e,r=!0){this.removeTags(e),this.tags.push(...e),r&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(r=>!e.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!e.includes(r))}addMetadata(e,r=!0){this.metadata={...this.metadata,...e},r&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let r of Object.keys(e))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(e=[],r=!0){let n=new jr(this._parentRunId);for(let i of this.handlers){let a=this.inheritableHandlers.includes(i);n.addHandler(i,a)}for(let i of this.tags){let a=this.inheritableTags.includes(i);n.addTags([i],a)}for(let i of Object.keys(this.metadata)){let a=Object.keys(this.inheritableMetadata).includes(i);n.addMetadata({[i]:this.metadata[i]},a)}for(let i of e)n.handlers.filter(a=>a.name==="console_callback_handler").some(a=>a.name===i.name)||n.addHandler(i,r);return n}static fromHandlers(e){class r extends Jt{static{s(this,"Handler")}name=De();constructor(){super(),Object.assign(this,e)}}let n=new this;return n.addHandler(new r),n}static configure(e,r,n,i,a,o,l){return this._configureSync(e,r,n,i,a,o,l)}static _configureSync(e,r,n,i,a,o,l){let c;(e||r)&&(Array.isArray(e)||!e?(c=new jr,c.setHandlers(e?.map(qa)??[],!0)):c=e,c=c.copy(Array.isArray(r)?r.map(qa):r?.handlers,!1));let u=Me("LANGCHAIN_VERBOSE")==="true"||l?.verbose,d=Ur.getTraceableRunTree(),p=d?.tracingEnabled??Xc();if(d?.tracingEnabled===!1&&c){let v=c.handlers.filter(P=>P.name==="langchain_tracer");for(let P of v)c.removeHandler(P)}let h=p||(Me("LANGCHAIN_TRACING")??!1);if(u||h){if(c||(c=new jr),u&&!c.handlers.some(v=>v.name===Ba.prototype.name)){let v=new Ba;c.addHandler(v,!0)}if(h&&!c.handlers.some(v=>v.name==="langchain_tracer")&&p){let v=new Ur;c.addHandler(v,!0)}p&&d&&c._parentRunId===void 0&&(c._parentRunId=d.id,c.handlers.find(v=>v.name==="langchain_tracer")?.updateFromRunTree(d))}for(let{contextVar:v,inheritable:P=!0,handlerClass:I,envVar:S}of Qc()){let A=S&&Me(S)==="true"&&I,R,$=v!==void 0?Va(v):void 0;$&&ko($)?R=$:A&&(R=new I({})),R!==void 0&&(c||(c=new jr),c.handlers.some(N=>N.name===R.name)||c.addHandler(R,P))}(n||i)&&c&&(c.addTags(n??[]),c.addTags(i??[],!1)),(a||o)&&c&&(c.addMetadata(a??{}),c.addMetadata(o??{},!1));let g=l?.tracerInheritableMetadata,b=l?.tracerInheritableTags;return c&&(g||b)&&(c.handlers=c.handlers.map(v=>v instanceof Ur?v.copyWithTracingConfig({metadata:g,tags:b}):v),c.inheritableHandlers=c.inheritableHandlers.map(v=>v instanceof Ur?v.copyWithTracingConfig({metadata:g,tags:b}):v)),c}};function qa(t){return"name"in t?t:Jt.fromMethods(t)}s(qa,"ensureHandler");var ru=class{static{s(this,"MockAsyncLocalStorage")}getStore(){}run(t,e){return e()}enterWith(t){}},rh=new ru,tu=Symbol.for("lc:child_config"),nh=class{static{s(this,"AsyncLocalStorageProvider")}getInstance(){return ot()??rh}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[tu]}runWithConfig(t,e,r){let n=zt._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),i=this.getInstance(),a=i.getStore(),o=n?.getParentRunId(),l=n?.handlers?.find(u=>u?.name==="langchain_tracer"),c;return l&&o?c=l.getRunTreeWithTracingConfig(o):r||(c=new Le({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[tu]:t}),a!==void 0&&a[xt]!==void 0&&(c===void 0&&(c={}),c[xt]=a[xt]),i.run(c,e)}initializeGlobalInstance(t){ot()===void 0&&Io(t)}},Br=new nh;var ih=Object.prototype.hasOwnProperty;function au(t,e){return ih.call(t,e)}s(au,"hasOwnProperty");function su(t){if(Array.isArray(t)){let r=new Array(t.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(t);let e=[];for(let r in t)au(t,r)&&e.push(r);return e}s(su,"_objectKeys");function Xe(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}s(Xe,"_deepClone");function Yn(t){let e=0,r=t.length,n;for(;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}s(Yn,"isInteger");function ou(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}s(ou,"unescapePathComponent");function Zn(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(Zn(t[r]))return!0}else if(typeof t=="object"){let r=su(t),n=r.length;for(var e=0;e<n;e++)if(Zn(t[r[e]]))return!0}}return!1}s(Zn,"hasUndefined");function iu(t,e){let r=[t];for(let n in e){let i=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof i<"u"&&r.push(`${n}: ${i}`)}return r.join(`
148
+ `)}s(iu,"patchErrorMessageFormatter");var lu=class extends Error{static{s(this,"PatchError")}constructor(t,e,r,n,i){super(iu(t,{name:e,index:r,operation:n,tree:i})),this.name=e,this.index=r,this.operation=n,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=iu(t,{name:e,index:r,operation:n,tree:i})}};var cu=H({JsonPatchError:s(()=>X,"JsonPatchError"),_areEquals:s(()=>Hr,"_areEquals"),applyOperation:s(()=>Gt,"applyOperation"),applyPatch:s(()=>ei,"applyPatch"),applyReducer:s(()=>oh,"applyReducer"),deepClone:s(()=>ah,"deepClone"),getValueByPointer:s(()=>Xn,"getValueByPointer"),validate:s(()=>uu,"validate"),validator:s(()=>Qn,"validator")}),X=lu,ah=Xe,br={add:s(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return t[e]=this.value,{newDocument:r}},"add"),remove:s(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=t[e];return delete t[e],{newDocument:r,removed:n}},"remove"),replace:s(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},"replace"),move:s(function(t,e,r){let n=Xn(r,this.path);n&&(n=Xe(n));let i=Gt(r,{op:"remove",path:this.from}).removed;return Gt(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},"move"),copy:s(function(t,e,r){let n=Xn(r,this.from);return Gt(r,{op:"add",path:this.path,value:Xe(n)}),{newDocument:r}},"copy"),test:s(function(t,e,r){return{newDocument:r,test:Hr(t[e],this.value)}},"test"),_get:s(function(t,e,r){return this.value=t[e],{newDocument:r}},"_get")},sh={add:s(function(t,e,r){return Yn(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},"add"),remove:s(function(t,e,r){return{newDocument:r,removed:t.splice(e,1)[0]}},"remove"),replace:s(function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},"replace"),move:br.move,copy:br.copy,test:br.test,_get:br._get};function Xn(t,e){if(e=="")return t;var r={op:"_get",path:e};return Gt(t,r),r.value}s(Xn,"getValueByPointer");function Gt(t,e,r=!1,n=!0,i=!0,a=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):Qn(e,0)),e.path===""){let o={newDocument:t};if(e.op==="add")return o.newDocument=e.value,o;if(e.op==="replace")return o.newDocument=e.value,o.removed=t,o;if(e.op==="move"||e.op==="copy")return o.newDocument=Xn(t,e.from),e.op==="move"&&(o.removed=t),o;if(e.op==="test"){if(o.test=Hr(t,e.value),o.test===!1)throw new X("Test operation failed","TEST_OPERATION_FAILED",a,e,t);return o.newDocument=t,o}else{if(e.op==="remove")return o.removed=t,o.newDocument=null,o;if(e.op==="_get")return e.value=t,o;if(r)throw new X("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",a,e,t);return o}}else{n||(t=Xe(t));let o=(e.path||"").split("/"),l=t,c=1,u=o.length,d,p,h;for(typeof r=="function"?h=r:h=Qn;;){if(p=o[c],p&&p.indexOf("~")!=-1&&(p=ou(p)),i&&(p=="__proto__"||p=="prototype"&&c>0&&o[c-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&d===void 0&&(l[p]===void 0?d=o.slice(0,c).join("/"):c==u-1&&(d=e.path),d!==void 0&&h(e,0,t,d)),c++,Array.isArray(l)){if(p==="-")p=l.length;else{if(r&&!Yn(p))throw new X("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",a,e,t);Yn(p)&&(p=~~p)}if(c>=u){if(r&&e.op==="add"&&p>l.length)throw new X("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,e,t);let g=sh[e.op].call(e,l,p,t);if(g.test===!1)throw new X("Test operation failed","TEST_OPERATION_FAILED",a,e,t);return g}}else if(c>=u){let g=br[e.op].call(e,l,p,t);if(g.test===!1)throw new X("Test operation failed","TEST_OPERATION_FAILED",a,e,t);return g}if(l=l[p],r&&c<u&&(!l||typeof l!="object"))throw new X("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",a,e,t)}}}s(Gt,"applyOperation");function ei(t,e,r,n=!0,i=!0){if(r&&!Array.isArray(e))throw new X("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=Xe(t));let a=new Array(e.length);for(let o=0,l=e.length;o<l;o++)a[o]=Gt(t,e[o],r,!0,i,o),t=a[o].newDocument;return a.newDocument=t,a}s(ei,"applyPatch");function oh(t,e,r){let n=Gt(t,e);if(n.test===!1)throw new X("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}s(oh,"applyReducer");function Qn(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new X("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(br[t.op]){if(typeof t.path!="string")throw new X("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new X('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new X("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new X("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Zn(t.value))throw new X("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var i=t.path.split("/").length,a=n.split("/").length;if(i!==a+1&&i!==a)throw new X("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new X("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var o=uu([{op:"_get",path:t.from,value:void 0}],r);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new X("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new X("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}s(Qn,"validator");function uu(t,e,r){try{if(!Array.isArray(t))throw new X("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)ei(Xe(e),Xe(t),r||!0);else{r=r||Qn;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(i){if(i instanceof X)return i;throw i}}s(uu,"validate");function Hr(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),i,a,o;if(r&&n){if(a=t.length,a!=e.length)return!1;for(i=a;i--!==0;)if(!Hr(t[i],e[i]))return!1;return!0}if(r!=n)return!1;var l=Object.keys(t);if(a=l.length,a!==Object.keys(e).length)return!1;for(i=a;i--!==0;)if(!e.hasOwnProperty(l[i]))return!1;for(i=a;i--!==0;)if(o=l[i],!Hr(t[o],e[o]))return!1;return!0}return t!==t&&e!==e}s(Hr,"_areEquals");({...cu});var V1=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");var mh=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,hh=[0,31,28,31,30,31,30,31,31,30,31,30,31],gh=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,yh=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,_h=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,bh=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,wh=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,vh=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,xh=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Eh=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Sh=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Th=s(t=>{if(t[0]==='"')return!1;let[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},"EMAIL"),Ah=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Ih=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Ch=s(t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t)),"DURATION");function Ve(t){return t.test.bind(t)}s(Ve,"bind");var kh={date:du,time:pu.bind(void 0,!1),"date-time":Rh,duration:Ch,uri:Lh,"uri-reference":Ve(_h),"uri-template":Ve(bh),url:Ve(wh),email:Th,hostname:Ve(yh),ipv4:Ve(Ah),ipv6:Ve(Ih),regex:Dh,uuid:Ve(vh),"json-pointer":Ve(xh),"json-pointer-uri-fragment":Ve(Eh),"relative-json-pointer":Ve(Sh)};function Oh(t){return t%4===0&&(t%100!==0||t%400===0)}s(Oh,"isLeapYear");function du(t){let e=t.match(mh);if(!e)return!1;let r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&Oh(r)?29:hh[n])}s(du,"date");function pu(t,e){let r=e.match(gh);if(!r)return!1;let n=+r[1],i=+r[2],a=+r[3],o=!!r[5];return(n<=23&&i<=59&&a<=59||n==23&&i==59&&a==60)&&(!t||o)}s(pu,"time");var Ph=/t|\s/i;function Rh(t){let e=t.split(Ph);return e.length==2&&du(e[0])&&pu(!0,e[1])}s(Rh,"date_time");var Mh=/\/|:/,Nh=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Lh(t){return Mh.test(t)&&Nh.test(t)}s(Lh,"uri");var $h=/[^\\]\\Z/;function Dh(t){if($h.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}s(Dh,"regex");var fu;(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(fu||(fu={}));var Tu=it(Su(),1);var Qh=Object.defineProperty,eg=s((t,e,r)=>e in t?Qh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,"__defNormalProp"),tg=s((t,e,r)=>(eg(t,typeof e!="symbol"?e+"":e,r),r),"__publicField");function rg(t,e){let r=Array.from({length:t.length},(n,i)=>({start:i,end:i+1}));for(;r.length>1;){let n=null;for(let i=0;i<r.length-1;i++){let a=t.slice(r[i].start,r[i+1].end),o=e.get(a.join(","));o!=null&&(n==null||o<n[0])&&(n=[o,i])}if(n!=null){let i=n[1];r[i]={start:r[i].start,end:r[i+1].end},r.splice(i+1,1)}else break}return r}s(rg,"bytePairMerge");function ng(t,e){return t.length===1?[e.get(t.join(","))]:rg(t,e).map(r=>e.get(t.slice(r.start,r.end).join(","))).filter(r=>r!=null)}s(ng,"bytePairEncode");function ig(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}s(ig,"escapeRegex");var Xa=class{static{s(this,"_Tiktoken")}specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(t,e){this.patStr=t.pat_str;let r=t.bpe_ranks.split(`
149
+ `).filter(Boolean).reduce((n,i)=>{let[a,o,...l]=i.split(" "),c=Number.parseInt(o,10);return l.forEach((u,d)=>n[u]=c+d),n},{});for(let[n,i]of Object.entries(r)){let a=Tu.default.toByteArray(n);this.rankMap.set(a.join(","),i),this.textMap.set(i,a)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[i,a])=>(n[a]=this.textEncoder.encode(i),n),{})}encode(t,e=[],r="all"){let n=new RegExp(this.patStr,"ug"),i=Xa.specialTokenRegex(Object.keys(this.specialTokens)),a=[],o=new Set(e==="all"?Object.keys(this.specialTokens):e),l=new Set(r==="all"?Object.keys(this.specialTokens).filter(u=>!o.has(u)):r);if(l.size>0){let u=Xa.specialTokenRegex([...l]),d=t.match(u);if(d!=null)throw new Error(`The text contains a special token that is not allowed: ${d[0]}`)}let c=0;for(;;){let u=null,d=c;for(;i.lastIndex=d,u=i.exec(t),!(u==null||o.has(u[0]));)d=u.index+1;let p=u?.index??t.length;for(let g of t.substring(c,p).matchAll(n)){let b=this.textEncoder.encode(g[0]),v=this.rankMap.get(b.join(","));if(v!=null){a.push(v);continue}a.push(...ng(b,this.rankMap))}if(u==null)break;let h=this.specialTokens[u[0]];a.push(h),c=u.index+u[0].length}return a}decode(t){let e=[],r=0;for(let a=0;a<t.length;++a){let o=t[a],l=this.textMap.get(o)??this.inverseSpecialTokens[o];l!=null&&(e.push(l),r+=l.length)}let n=new Uint8Array(r),i=0;for(let a of e)n.set(a,i),i+=a.length;return this.textDecoder.decode(n)}},Qa=Xa;tg(Qa,"specialTokenRegex",t=>new RegExp(t.map(e=>ig(e)).join("|"),"g"));var ku=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"];var Ou=["image","video","audio","text-plain","file"];var og=["text","reasoning",...ku,...Ou];var hg=s(function(){let t={};t.parser=function(m,f){return new r(m,f)},t.SAXParser=r,t.SAXStream=u,t.createStream=c,t.MAX_BUFFER_LENGTH=65536;let e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function r(m,f){if(!(this instanceof r))return new r(m,f);var x=this;i(x),x.q=x.c="",x.bufferCheckPosition=t.MAX_BUFFER_LENGTH,x.opt=f||{},x.opt.lowercase=x.opt.lowercase||x.opt.lowercasetags,x.looseCase=x.opt.lowercase?"toLowerCase":"toUpperCase",x.tags=[],x.closed=x.closedRoot=x.sawRoot=!1,x.tag=x.error=null,x.strict=!!m,x.noscript=!!(m||x.opt.noscript),x.state=y.BEGIN,x.strictEntities=x.opt.strictEntities,x.ENTITIES=x.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),x.attribList=[],x.opt.xmlns&&(x.ns=Object.create(b)),x.trackPosition=x.opt.position!==!1,x.trackPosition&&(x.position=x.line=x.column=0),B(x,"onready")}s(r,"SAXParser"),Object.create||(Object.create=function(m){function f(){}return s(f,"F"),f.prototype=m,new f}),Object.keys||(Object.keys=function(m){var f=[];for(var x in m)m.hasOwnProperty(x)&&f.push(x);return f});function n(m){for(var f=Math.max(t.MAX_BUFFER_LENGTH,10),x=0,_=0,G=e.length;_<G;_++){var Q=m[e[_]].length;if(Q>f)switch(e[_]){case"textNode":de(m);break;case"cdata":F(m,"oncdata",m.cdata),m.cdata="";break;case"script":F(m,"onscript",m.script),m.script="";break;default:rt(m,"Max buffer length exceeded: "+e[_])}x=Math.max(x,Q)}m.bufferCheckPosition=t.MAX_BUFFER_LENGTH-x+m.position}s(n,"checkBufferLength");function i(m){for(var f=0,x=e.length;f<x;f++)m[e[f]]=""}s(i,"clearBuffers");function a(m){de(m),m.cdata!==""&&(F(m,"oncdata",m.cdata),m.cdata=""),m.script!==""&&(F(m,"onscript",m.script),m.script="")}s(a,"flushBuffers"),r.prototype={end:s(function(){vr(this)},"end"),write:rd,resume:s(function(){return this.error=null,this},"resume"),close:s(function(){return this.write(null)},"close"),flush:s(function(){a(this)},"flush")};var o=ReadableStream;o||(o=s(function(){},"Stream"));var l=t.EVENTS.filter(function(m){return m!=="error"&&m!=="end"});function c(m,f){return new u(m,f)}s(c,"createStream");function u(m,f){if(!(this instanceof u))return new u(m,f);o.apply(this),this._parser=new r(m,f),this.writable=!0,this.readable=!0;var x=this;this._parser.onend=function(){x.emit("end")},this._parser.onerror=function(_){x.emit("error",_),x._parser.error=null},this._decoder=null,l.forEach(function(_){Object.defineProperty(x,"on"+_,{get:s(function(){return x._parser["on"+_]},"get"),set:s(function(G){if(!G)return x.removeAllListeners(_),x._parser["on"+_]=G,G;x.on(_,G)},"set"),enumerable:!0,configurable:!1})})}s(u,"SAXStream"),u.prototype=Object.create(o.prototype,{constructor:{value:u}}),u.prototype.write=function(m){return this._parser.write(m.toString()),this.emit("data",m),!0},u.prototype.end=function(m){return m&&m.length&&this.write(m),this._parser.end(),!0},u.prototype.on=function(m,f){var x=this;return!x._parser["on"+m]&&l.indexOf(m)!==-1&&(x._parser["on"+m]=function(){var _=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);_.splice(0,0,m),x.emit.apply(x,_)}),o.prototype.on.call(x,m,f)};var d="[CDATA[",p="DOCTYPE",h="http://www.w3.org/XML/1998/namespace",g="http://www.w3.org/2000/xmlns/",b={xml:h,xmlns:g},v=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,P=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,I=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,S=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function A(m){return m===" "||m===`
150
+ `||m==="\r"||m===" "}s(A,"isWhitespace");function R(m){return m==='"'||m==="'"}s(R,"isQuote");function $(m){return m===">"||A(m)}s($,"isAttribEnd");function N(m,f){return m.test(f)}s(N,"isMatch");function j(m,f){return!N(m,f)}s(j,"notMatch");var y=0;t.STATE={BEGIN:y++,BEGIN_WHITESPACE:y++,TEXT:y++,TEXT_ENTITY:y++,OPEN_WAKA:y++,SGML_DECL:y++,SGML_DECL_QUOTED:y++,DOCTYPE:y++,DOCTYPE_QUOTED:y++,DOCTYPE_DTD:y++,DOCTYPE_DTD_QUOTED:y++,COMMENT_STARTING:y++,COMMENT:y++,COMMENT_ENDING:y++,COMMENT_ENDED:y++,CDATA:y++,CDATA_ENDING:y++,CDATA_ENDING_2:y++,PROC_INST:y++,PROC_INST_BODY:y++,PROC_INST_ENDING:y++,OPEN_TAG:y++,OPEN_TAG_SLASH:y++,ATTRIB:y++,ATTRIB_NAME:y++,ATTRIB_NAME_SAW_WHITE:y++,ATTRIB_VALUE:y++,ATTRIB_VALUE_QUOTED:y++,ATTRIB_VALUE_CLOSED:y++,ATTRIB_VALUE_UNQUOTED:y++,ATTRIB_VALUE_ENTITY_Q:y++,ATTRIB_VALUE_ENTITY_U:y++,CLOSE_TAG:y++,CLOSE_TAG_SAW_WHITE:y++,SCRIPT:y++,SCRIPT_ENDING:y++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(m){var f=t.ENTITIES[m],x=typeof f=="number"?String.fromCharCode(f):f;t.ENTITIES[m]=x});for(var K in t.STATE)t.STATE[t.STATE[K]]=K;y=t.STATE;function B(m,f,x){m[f]&&m[f](x)}s(B,"emit");function F(m,f,x){m.textNode&&de(m),B(m,f,x)}s(F,"emitNode");function de(m){m.textNode=tt(m.opt,m.textNode),m.textNode&&B(m,"ontext",m.textNode),m.textNode=""}s(de,"closeText");function tt(m,f){return m.trim&&(f=f.trim()),m.normalize&&(f=f.replace(/\s+/g," ")),f}s(tt,"textopts");function rt(m,f){return de(m),m.trackPosition&&(f+=`
151
+ Line: `+m.line+`
152
+ Column: `+m.column+`
153
+ Char: `+m.c),f=new Error(f),m.error=f,B(m,"onerror",f),m}s(rt,"error");function vr(m){return m.sawRoot&&!m.closedRoot&&V(m,"Unclosed root tag"),m.state!==y.BEGIN&&m.state!==y.BEGIN_WHITESPACE&&m.state!==y.TEXT&&rt(m,"Unexpected end"),de(m),m.c="",m.closed=!0,B(m,"onend"),r.call(m,m.strict,m.opt),m}s(vr,"end");function V(m,f){if(typeof m!="object"||!(m instanceof r))throw new Error("bad call to strictFail");m.strict&&rt(m,f)}s(V,"strictFail");function td(m){m.strict||(m.tagName=m.tagName[m.looseCase]());var f=m.tags[m.tags.length-1]||m,x=m.tag={name:m.tagName,attributes:{}};m.opt.xmlns&&(x.ns=f.ns),m.attribList.length=0,F(m,"onopentagstart",x)}s(td,"newTag");function si(m,f){var x=m.indexOf(":")<0?["",m]:m.split(":"),_=x[0],G=x[1];return f&&m==="xmlns"&&(_="xmlns",G=""),{prefix:_,local:G}}s(si,"qname");function oi(m){if(m.strict||(m.attribName=m.attribName[m.looseCase]()),m.attribList.indexOf(m.attribName)!==-1||m.tag.attributes.hasOwnProperty(m.attribName)){m.attribName=m.attribValue="";return}if(m.opt.xmlns){var f=si(m.attribName,!0),x=f.prefix,_=f.local;if(x==="xmlns")if(_==="xml"&&m.attribValue!==h)V(m,"xml: prefix must be bound to "+h+`
154
+ Actual: `+m.attribValue);else if(_==="xmlns"&&m.attribValue!==g)V(m,"xmlns: prefix must be bound to "+g+`
155
+ Actual: `+m.attribValue);else{var G=m.tag,Q=m.tags[m.tags.length-1]||m;G.ns===Q.ns&&(G.ns=Object.create(Q.ns)),G.ns[_]=m.attribValue}m.attribList.push([m.attribName,m.attribValue])}else m.tag.attributes[m.attribName]=m.attribValue,F(m,"onattribute",{name:m.attribName,value:m.attribValue});m.attribName=m.attribValue=""}s(oi,"attrib");function yt(m,f){if(m.opt.xmlns){var x=m.tag,_=si(m.tagName);x.prefix=_.prefix,x.local=_.local,x.uri=x.ns[_.prefix]||"",x.prefix&&!x.uri&&(V(m,"Unbound namespace prefix: "+JSON.stringify(m.tagName)),x.uri=_.prefix);var G=m.tags[m.tags.length-1]||m;x.ns&&G.ns!==x.ns&&Object.keys(x.ns).forEach(function(ps){F(m,"onopennamespace",{prefix:ps,uri:x.ns[ps]})});for(var Q=0,Te=m.attribList.length;Q<Te;Q++){var ye=m.attribList[Q],Pe=ye[0],_t=ye[1],pe=si(Pe,!0),bt=pe.prefix,nd=pe.local,ds=bt===""?"":x.ns[bt]||"",ci={name:Pe,value:_t,prefix:bt,local:nd,uri:ds};bt&&bt!=="xmlns"&&!ds&&(V(m,"Unbound namespace prefix: "+JSON.stringify(bt)),ci.uri=bt),m.tag.attributes[Pe]=ci,F(m,"onattribute",ci)}m.attribList.length=0}m.tag.isSelfClosing=!!f,m.sawRoot=!0,m.tags.push(m.tag),F(m,"onopentag",m.tag),f||(!m.noscript&&m.tagName.toLowerCase()==="script"?m.state=y.SCRIPT:m.state=y.TEXT,m.tag=null,m.tagName=""),m.attribName=m.attribValue="",m.attribList.length=0}s(yt,"openTag");function li(m){if(!m.tagName){V(m,"Weird empty close tag."),m.textNode+="</>",m.state=y.TEXT;return}if(m.script){if(m.tagName!=="script"){m.script+="</"+m.tagName+">",m.tagName="",m.state=y.SCRIPT;return}F(m,"onscript",m.script),m.script=""}var f=m.tags.length,x=m.tagName;m.strict||(x=x[m.looseCase]());for(var _=x;f--&&m.tags[f].name!==_;)V(m,"Unexpected close tag");if(f<0){V(m,"Unmatched closing tag: "+m.tagName),m.textNode+="</"+m.tagName+">",m.state=y.TEXT;return}m.tagName=x;for(var G=m.tags.length;G-- >f;){var Q=m.tag=m.tags.pop();m.tagName=m.tag.name,F(m,"onclosetag",m.tagName);var Te={};for(var ye in Q.ns)Te[ye]=Q.ns[ye];var Pe=m.tags[m.tags.length-1]||m;m.opt.xmlns&&Q.ns!==Pe.ns&&Object.keys(Q.ns).forEach(function(_t){var pe=Q.ns[_t];F(m,"onclosenamespace",{prefix:_t,uri:pe})})}f===0&&(m.closedRoot=!0),m.tagName=m.attribValue=m.attribName="",m.attribList.length=0,m.state=y.TEXT}s(li,"closeTag");function ls(m){var f=m.entity,x=f.toLowerCase(),_,G="";return m.ENTITIES[f]?m.ENTITIES[f]:m.ENTITIES[x]?m.ENTITIES[x]:(f=x,f.charAt(0)==="#"&&(f.charAt(1)==="x"?(f=f.slice(2),_=parseInt(f,16),G=_.toString(16)):(f=f.slice(1),_=parseInt(f,10),G=_.toString(10))),f=f.replace(/^0+/,""),isNaN(_)||G.toLowerCase()!==f?(V(m,"Invalid character entity"),"&"+m.entity+";"):String.fromCodePoint(_))}s(ls,"parseEntity");function cs(m,f){f==="<"?(m.state=y.OPEN_WAKA,m.startTagPosition=m.position):A(f)||(V(m,"Non-whitespace before first tag."),m.textNode=f,m.state=y.TEXT)}s(cs,"beginWhiteSpace");function us(m,f){var x="";return f<m.length&&(x=m.charAt(f)),x}s(us,"charAt");function rd(m){var f=this;if(this.error)throw this.error;if(f.closed)return rt(f,"Cannot write after close. Assign an onready handler.");if(m===null)return vr(f);typeof m=="object"&&(m=m.toString());for(var x=0,_="";_=us(m,x++),f.c=_,!!_;)switch(f.trackPosition&&(f.position++,_===`
156
+ `?(f.line++,f.column=0):f.column++),f.state){case y.BEGIN:if(f.state=y.BEGIN_WHITESPACE,_==="\uFEFF")continue;cs(f,_);continue;case y.BEGIN_WHITESPACE:cs(f,_);continue;case y.TEXT:if(f.sawRoot&&!f.closedRoot){for(var G=x-1;_&&_!=="<"&&_!=="&";)_=us(m,x++),_&&f.trackPosition&&(f.position++,_===`
157
+ `?(f.line++,f.column=0):f.column++);f.textNode+=m.substring(G,x-1)}_==="<"&&!(f.sawRoot&&f.closedRoot&&!f.strict)?(f.state=y.OPEN_WAKA,f.startTagPosition=f.position):(!A(_)&&(!f.sawRoot||f.closedRoot)&&V(f,"Text data outside of root node."),_==="&"?f.state=y.TEXT_ENTITY:f.textNode+=_);continue;case y.SCRIPT:_==="<"?f.state=y.SCRIPT_ENDING:f.script+=_;continue;case y.SCRIPT_ENDING:_==="/"?f.state=y.CLOSE_TAG:(f.script+="<"+_,f.state=y.SCRIPT);continue;case y.OPEN_WAKA:if(_==="!")f.state=y.SGML_DECL,f.sgmlDecl="";else if(!A(_))if(N(v,_))f.state=y.OPEN_TAG,f.tagName=_;else if(_==="/")f.state=y.CLOSE_TAG,f.tagName="";else if(_==="?")f.state=y.PROC_INST,f.procInstName=f.procInstBody="";else{if(V(f,"Unencoded <"),f.startTagPosition+1<f.position){var Q=f.position-f.startTagPosition;_=new Array(Q).join(" ")+_}f.textNode+="<"+_,f.state=y.TEXT}continue;case y.SGML_DECL:(f.sgmlDecl+_).toUpperCase()===d?(F(f,"onopencdata"),f.state=y.CDATA,f.sgmlDecl="",f.cdata=""):f.sgmlDecl+_==="--"?(f.state=y.COMMENT,f.comment="",f.sgmlDecl=""):(f.sgmlDecl+_).toUpperCase()===p?(f.state=y.DOCTYPE,(f.doctype||f.sawRoot)&&V(f,"Inappropriately located doctype declaration"),f.doctype="",f.sgmlDecl=""):_===">"?(F(f,"onsgmldeclaration",f.sgmlDecl),f.sgmlDecl="",f.state=y.TEXT):(R(_)&&(f.state=y.SGML_DECL_QUOTED),f.sgmlDecl+=_);continue;case y.SGML_DECL_QUOTED:_===f.q&&(f.state=y.SGML_DECL,f.q=""),f.sgmlDecl+=_;continue;case y.DOCTYPE:_===">"?(f.state=y.TEXT,F(f,"ondoctype",f.doctype),f.doctype=!0):(f.doctype+=_,_==="["?f.state=y.DOCTYPE_DTD:R(_)&&(f.state=y.DOCTYPE_QUOTED,f.q=_));continue;case y.DOCTYPE_QUOTED:f.doctype+=_,_===f.q&&(f.q="",f.state=y.DOCTYPE);continue;case y.DOCTYPE_DTD:f.doctype+=_,_==="]"?f.state=y.DOCTYPE:R(_)&&(f.state=y.DOCTYPE_DTD_QUOTED,f.q=_);continue;case y.DOCTYPE_DTD_QUOTED:f.doctype+=_,_===f.q&&(f.state=y.DOCTYPE_DTD,f.q="");continue;case y.COMMENT:_==="-"?f.state=y.COMMENT_ENDING:f.comment+=_;continue;case y.COMMENT_ENDING:_==="-"?(f.state=y.COMMENT_ENDED,f.comment=tt(f.opt,f.comment),f.comment&&F(f,"oncomment",f.comment),f.comment=""):(f.comment+="-"+_,f.state=y.COMMENT);continue;case y.COMMENT_ENDED:_!==">"?(V(f,"Malformed comment"),f.comment+="--"+_,f.state=y.COMMENT):f.state=y.TEXT;continue;case y.CDATA:_==="]"?f.state=y.CDATA_ENDING:f.cdata+=_;continue;case y.CDATA_ENDING:_==="]"?f.state=y.CDATA_ENDING_2:(f.cdata+="]"+_,f.state=y.CDATA);continue;case y.CDATA_ENDING_2:_===">"?(f.cdata&&F(f,"oncdata",f.cdata),F(f,"onclosecdata"),f.cdata="",f.state=y.TEXT):_==="]"?f.cdata+="]":(f.cdata+="]]"+_,f.state=y.CDATA);continue;case y.PROC_INST:_==="?"?f.state=y.PROC_INST_ENDING:A(_)?f.state=y.PROC_INST_BODY:f.procInstName+=_;continue;case y.PROC_INST_BODY:if(!f.procInstBody&&A(_))continue;_==="?"?f.state=y.PROC_INST_ENDING:f.procInstBody+=_;continue;case y.PROC_INST_ENDING:_===">"?(F(f,"onprocessinginstruction",{name:f.procInstName,body:f.procInstBody}),f.procInstName=f.procInstBody="",f.state=y.TEXT):(f.procInstBody+="?"+_,f.state=y.PROC_INST_BODY);continue;case y.OPEN_TAG:N(P,_)?f.tagName+=_:(td(f),_===">"?yt(f):_==="/"?f.state=y.OPEN_TAG_SLASH:(A(_)||V(f,"Invalid character in tag name"),f.state=y.ATTRIB));continue;case y.OPEN_TAG_SLASH:_===">"?(yt(f,!0),li(f)):(V(f,"Forward-slash in opening tag not followed by >"),f.state=y.ATTRIB);continue;case y.ATTRIB:if(A(_))continue;_===">"?yt(f):_==="/"?f.state=y.OPEN_TAG_SLASH:N(v,_)?(f.attribName=_,f.attribValue="",f.state=y.ATTRIB_NAME):V(f,"Invalid attribute name");continue;case y.ATTRIB_NAME:_==="="?f.state=y.ATTRIB_VALUE:_===">"?(V(f,"Attribute without value"),f.attribValue=f.attribName,oi(f),yt(f)):A(_)?f.state=y.ATTRIB_NAME_SAW_WHITE:N(P,_)?f.attribName+=_:V(f,"Invalid attribute name");continue;case y.ATTRIB_NAME_SAW_WHITE:if(_==="=")f.state=y.ATTRIB_VALUE;else{if(A(_))continue;V(f,"Attribute without value"),f.tag.attributes[f.attribName]="",f.attribValue="",F(f,"onattribute",{name:f.attribName,value:""}),f.attribName="",_===">"?yt(f):N(v,_)?(f.attribName=_,f.state=y.ATTRIB_NAME):(V(f,"Invalid attribute name"),f.state=y.ATTRIB)}continue;case y.ATTRIB_VALUE:if(A(_))continue;R(_)?(f.q=_,f.state=y.ATTRIB_VALUE_QUOTED):(V(f,"Unquoted attribute value"),f.state=y.ATTRIB_VALUE_UNQUOTED,f.attribValue=_);continue;case y.ATTRIB_VALUE_QUOTED:if(_!==f.q){_==="&"?f.state=y.ATTRIB_VALUE_ENTITY_Q:f.attribValue+=_;continue}oi(f),f.q="",f.state=y.ATTRIB_VALUE_CLOSED;continue;case y.ATTRIB_VALUE_CLOSED:A(_)?f.state=y.ATTRIB:_===">"?yt(f):_==="/"?f.state=y.OPEN_TAG_SLASH:N(v,_)?(V(f,"No whitespace between attributes"),f.attribName=_,f.attribValue="",f.state=y.ATTRIB_NAME):V(f,"Invalid attribute name");continue;case y.ATTRIB_VALUE_UNQUOTED:if(!$(_)){_==="&"?f.state=y.ATTRIB_VALUE_ENTITY_U:f.attribValue+=_;continue}oi(f),_===">"?yt(f):f.state=y.ATTRIB;continue;case y.CLOSE_TAG:if(f.tagName)_===">"?li(f):N(P,_)?f.tagName+=_:f.script?(f.script+="</"+f.tagName,f.tagName="",f.state=y.SCRIPT):(A(_)||V(f,"Invalid tagname in closing tag"),f.state=y.CLOSE_TAG_SAW_WHITE);else{if(A(_))continue;j(v,_)?f.script?(f.script+="</"+_,f.state=y.SCRIPT):V(f,"Invalid tagname in closing tag."):f.tagName=_}continue;case y.CLOSE_TAG_SAW_WHITE:if(A(_))continue;_===">"?li(f):V(f,"Invalid characters in closing tag");continue;case y.TEXT_ENTITY:case y.ATTRIB_VALUE_ENTITY_Q:case y.ATTRIB_VALUE_ENTITY_U:var Te,ye;switch(f.state){case y.TEXT_ENTITY:Te=y.TEXT,ye="textNode";break;case y.ATTRIB_VALUE_ENTITY_Q:Te=y.ATTRIB_VALUE_QUOTED,ye="attribValue";break;case y.ATTRIB_VALUE_ENTITY_U:Te=y.ATTRIB_VALUE_UNQUOTED,ye="attribValue";break}if(_===";")if(f.opt.unparsedEntities){var Pe=ls(f);f.entity="",f.state=Te,f.write(Pe)}else f[ye]+=ls(f),f.entity="",f.state=Te;else N(f.entity.length?S:I,_)?f.entity+=_:(V(f,"Invalid character in entity name"),f[ye]+="&"+f.entity+_,f.entity="",f.state=Te);continue;default:throw new Error(f,"Unknown state: "+f.state)}return f.position>=f.bufferCheckPosition&&n(f),f}s(rd,"write");return String.fromCodePoint||(function(){var m=String.fromCharCode,f=Math.floor,x=s(function(){var _=16384,G=[],Q,Te,ye=-1,Pe=arguments.length;if(!Pe)return"";for(var _t="";++ye<Pe;){var pe=Number(arguments[ye]);if(!isFinite(pe)||pe<0||pe>1114111||f(pe)!==pe)throw RangeError("Invalid code point: "+pe);pe<=65535?G.push(pe):(pe-=65536,Q=(pe>>10)+55296,Te=pe%1024+56320,G.push(Q,Te)),(ye+1===Pe||G.length>_)&&(_t+=m.apply(null,G),G.length=0)}return _t},"fromCodePoint");Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:x,configurable:!0,writable:!0}):String.fromCodePoint=x})(),t},"initializeSax"),gg=hg();var Gj=require("@playwright/test");var Nj={openai_gpt_4_1:{model:"gpt-4.1-2025-04-14",type:"openai"},openai_gpt_4_1_mini:{model:"gpt-4.1-mini-2025-04-14",type:"openai"},openai_gpt_4_1_nano:{model:"gpt-4.1-nano-2025-04-14",type:"openai"},gemini_2_0_flash:{model:"gemini-2.0-flash",type:"gemini"},gemini_2_5_pro_exp:{model:"gemini-2.5-pro-exp-03-25",type:"gemini"},gemini_2_5_flash:{model:"gemini-2.5-flash",type:"gemini"},gemini_2_5_pro_preview_05_06:{model:"gemini-2.5-pro-preview-05-06",type:"gemini"},claude_sonnet_4:{model:"claude-sonnet-4@20250514",type:"anthropic-vertexai"},claude_sonnet_4_6:{model:"claude-sonnet-4-6",type:"anthropic-vertexai"},claude_sonnet_5:{model:"claude-sonnet-5",type:"anthropic-vertexai"},claude_opus_4_8:{model:"claude-opus-4-8",type:"anthropic-vertexai"},gemini_2_5_flash_lite:{model:"gemini-2.5-flash-lite",type:"gemini"},gemini_3_5_flash:{model:"gemini-3.5-flash",type:"gemini"},gemini_3_1_flash_lite:{model:"gemini-3.1-flash-lite",type:"gemini"}};var Hu=it(Bu());Hu.default.config({path:[`${__dirname}/.env`,`${__dirname}/../../.env`]});var Dg="claude_4",Ug={gemini20flash:{name:"google-vertexai/gemini-2.0-flash",inputTokenLimit:8e5,provider:"gemini",temperature:0},gpt41:{name:"openai/gpt-4.1",inputTokenLimit:8e5,provider:"openai",temperature:0},gemini25flash:{name:"google-vertexai/gemini-2.5-flash",inputTokenLimit:8e5,provider:"gemini",temperature:.7},gemini25flash_lite:{name:"google-vertexai/gemini-2.5-flash-lite",inputTokenLimit:8e5,provider:"gemini",temperature:0},gpt4onano:{name:"openai/gpt-4o-nano",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt41nano:{name:"openai/gpt-4.1-nano",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt41mini:{name:"openai/gpt-4.1-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},o3mini:{name:"openai/o3-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},o4mini:{name:"openai/o4-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gemini25pro:{name:"google-vertexai/gemini-2.5-pro-preview-05-06",inputTokenLimit:8e5,provider:"gemini",temperature:0},claude37sonnet:{name:"google-vertexai/claude-3-7-sonnet@20250219",inputTokenLimit:15e4,provider:"anthropic",temperature:0},claude4sonnet:{name:"google-vertexai/claude-sonnet-4@20250514",inputTokenLimit:15e4,provider:"anthropic",temperature:1},claudeSonnet46:{name:"google-vertexai/claude-sonnet-4-6",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},claudeSonnet5:{name:"google-vertexai/claude-sonnet-5",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},claudeOpus48:{name:"google-vertexai/claude-opus-4-8",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},gemini35flash:{name:"google-vertexai/gemini-3.5-flash",inputTokenLimit:8e5,provider:"gemini",temperature:0,location:"global"},gemini31flashLite:{name:"google-vertexai/gemini-3.1-flash-lite",inputTokenLimit:8e5,provider:"gemini",temperature:0,location:"global"},gpt4omini:{name:"openai/gpt-4o-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt5mini:{name:"openai/gpt-5-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt5nano:{name:"openai/gpt-5-nano",inputTokenLimit:8e5,provider:"openai",temperature:0}},Fg=s(()=>({nodeEnv:process.env.NODE_ENV??"production",selectedModel:{name:Dg},models:Ug,langsmith:{enabled:process.env.LANGSMITH_TRACING==="true",endpoint:process.env.LANGSMITH_ENDPOINT??"",apiKey:process.env.LANGSMITH_API_KEY??"",project:process.env.LANGSMITH_PROJECT??""}}),"make"),ee=Fg();var Bj={claude_4:ee.models.claude4sonnet,"claude_3.7":ee.models.claude37sonnet,claude_sonnet_4_6:ee.models.claudeSonnet46,claude_sonnet_5:ee.models.claudeSonnet5,claude_opus_4_8:ee.models.claudeOpus48,"gemini_2.5_pro":ee.models.gemini25pro,"gemini_2.0_flash":ee.models.gemini20flash,"gemini_2.5_flash_lite":ee.models.gemini25flash_lite,"gemini_2.5_flash":ee.models.gemini25flash,"gemini_3.5_flash":ee.models.gemini35flash,"gemini_3.1_flash_lite":ee.models.gemini31flashLite,gpt_4o_mini:ee.models.gpt4omini,gpt_4o_nano:ee.models.gpt4onano,gpt_41_nano:ee.models.gpt41nano,gpt_5_mini:ee.models.gpt5mini,gpt_5_nano:ee.models.gpt5nano,gpt_41_mini:ee.models.gpt41mini,gpt_41:ee.models.gpt41,o4_mini:ee.models.o4mini,o3_mini:ee.models.o3mini};var zu=s(t=>{if(t.error!=null)return"ERROR";let e=t.status_code;if(typeof e=="number"&&e>=500)return"ERROR";let r=t.exit_code;return typeof r=="number"&&r!==0?"ERROR":"INFO"},"severityFor");var as=require("fs");var Gu="\x1B[31m",jg="\x1B[33m",Bg="\x1B[32m",Hg="\x1B[36m",zg="\x1B[2m",Gg="\x1B[1m",qr="\x1B[0m",Vg=s(()=>{let t=process.env.WIDE_EVENT_PRETTY;return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:process.stdout.isTTY?!0:process.env.APP_ENV==="local"},"shouldPretty"),qg=new Set(["severity","message","kind","timestamp","_startedAtMs"]),Wg=s(t=>{let e=new WeakSet;return JSON.stringify(t,(r,n)=>{if(typeof n=="bigint")return n.toString();if(typeof n=="object"&&n!==null){if(e.has(n))return"[Circular]";e.add(n)}return n})},"safeStringify"),Kg=s(t=>t==="ERROR"||t==="CRITICAL"?Gu:t==="WARNING"?jg:Bg,"colorForSeverity"),Jg=s(t=>{let e=String(t.severity??"INFO"),r=`${Kg(e)}${e.padEnd(5)}${qr}`,n=t.kind?`${Hg}${t.kind}${qr}`:"",i=String(t.message??""),a=t.error&&typeof t.error=="object"?(()=>{let d=t.error;return` ${Gu}${d.type??"Error"}: ${d.message??""}${qr}`})():"",o=["outcome","test_suite_run_id","status"],l=Object.entries(t).filter(([d,p])=>!qg.has(d)&&p!=null&&d!=="error"&&typeof p!="object"),c=s(d=>{let p=o.indexOf(d);return p===-1?o.length:p},"rank"),u=l.sort(([d],[p])=>c(d)-c(p)).slice(0,8).map(([d,p])=>`${zg}${d}=${qr}${p}`).join(" ");return[r,Gg+n+qr,i,u,a].filter(d=>d&&d.trim()!=="").join(" ")},"formatPretty"),Zg=s(t=>{let e=t.trace_id;if(typeof e!="string"||e==="")return t;let r=process.env.GCP_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT;return r?{...t,"logging.googleapis.com/trace":`projects/${r}/traces/${e}`}:t},"withGcpTraceField"),Vu=s(t=>{let e=Vg()?Jg(t):Wg(Zg(t));(0,as.writeSync)(1,e+`
158
+ `)},"emitEvent");var qu=s(t=>{(0,as.writeSync)(2,t.endsWith(`
159
+ `)?t:`${t}
160
+ `)},"writeStderrLine");var Yg=s(t=>{let e=t.kind??"event",r=t.outcome?` ${t.outcome}`:"",n=typeof t.duration_ms=="number"?` ${t.duration_ms}ms`:"";return`${e}${r}${n}`.trim()},"defaultMessage"),Xg=s((t,e,r)=>{let n=Date.now(),i={timestamp:new Date().toISOString(),kind:t,...e},a=!1,o={set(l){return Object.assign(i,l),o},emit(l){a||(a=!0,l&&Object.assign(i,l),i.duration_ms===void 0&&(i.duration_ms=Date.now()-n),r(i))}};return o},"startHandle"),Qg=s((t={})=>{let e=t.decide??(()=>!0),r=t.deriveMessage??Yg,n=t.label??"[wide-event]",i=t.sink??(l=>Vu(l)),a=s(l=>{if(!e(l))return;let c={severity:zu(l),message:l.message??r(l),...l};try{i(c)}catch(u){try{qu(`${n} emit failed: ${String(u)}`)}catch{}}},"emit");return{emit:a,emitWideEvent:s((l,c={})=>{a({timestamp:new Date().toISOString(),kind:l,...c})},"emitWideEvent"),wideEvent:s((l,c={})=>Xg(l,c,a),"wideEvent"),configureSink:s(l=>{i=l},"configureSink")}},"createWideEvents"),Wu=s(t=>t==="true"||t==="1","truthy"),Ku=s(()=>Wu(process.env.CHECKSUM_WIDE_EVENTS)||Wu(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),Ju=Qg({decide:s(()=>Ku(),"decide")}),ey=Ju.configureSink;var ss=s((t,e={})=>{Ju.emitWideEvent(t,e)},"emitWideEvent");async function Zu(t){await t.body?.cancel().catch(()=>{})}s(Zu,"drainBody");var ty="http://127.0.0.1";async function Yu(t,e){let r=e.fetchImpl??globalThis.fetch;try{let n=await r(`${ty}:${e.port}/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(e.timeoutMs)});return await Zu(n),n.ok?!0:(e.onError?.(new Error(`monitor rejected message with status ${n.status}`)),!1)}catch(n){return e.onError?.(n),!1}}s(Yu,"postToMonitor");async function Xu(t,e){let r,n=new Promise(i=>{r=setTimeout(()=>i(!1),e),r.unref()});try{return await Promise.race([t.then(()=>!0).catch(()=>!0),n])}finally{r&&clearTimeout(r)}}s(Xu,"settleWithin");var ii={uploadTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_TIMEOUT_MS",fallback:6e5,min:5e3,max:36e5},noProgressAbortMs:{env:"CHECKSUM_RUNTIME_UPLOAD_NO_PROGRESS_MS",fallback:6e4,min:5e3,max:6e5},assetDeadlineMs:{env:"CHECKSUM_RUNTIME_UPLOAD_ASSET_DEADLINE_MS",fallback:12e5,min:3e4,max:54e5},maxAttempts:{env:"CHECKSUM_RUNTIME_UPLOAD_MAX_ATTEMPTS",fallback:6,min:1,max:20},stallTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_STALL_TIMEOUT_MS",fallback:6e5,min:3e4,max:36e5},minProgressBytes:{env:"CHECKSUM_RUNTIME_UPLOAD_MIN_PROGRESS_BYTES",fallback:65536,min:1,max:67108864},finalizeBudgetMs:{env:"CHECKSUM_RUNTIME_UPLOAD_FINALIZE_BUDGET_MS",fallback:18e5,min:6e4,max:54e5},finalizeCeilingMs:{env:"CHECKSUM_RUNTIME_UPLOAD_FINALIZE_CEILING_MS",fallback:24e5,min:12e4,max:72e5},cliHardCapMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CLI_HARD_CAP_MS",fallback:27e5,min:12e4,max:72e5},watchTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_WATCH_TIMEOUT_MS",fallback:12e4,min:5e3,max:18e5},ipcTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_IPC_TIMEOUT_MS",fallback:5e3,min:500,max:6e4},onEndFlushTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_ONEND_FLUSH_TIMEOUT_MS",fallback:5e3,min:500,max:6e4},resumableChunkBytes:{env:"CHECKSUM_RUNTIME_UPLOAD_RESUMABLE_CHUNK_BYTES",fallback:8388608,min:262144,max:268435456},connectTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CONNECT_TIMEOUT_MS",fallback:1e4,min:1e3,max:6e4},headersTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_HEADERS_TIMEOUT_MS",fallback:3e5,min:5e3,max:18e5},bodyTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_BODY_TIMEOUT_MS",fallback:3e5,min:5e3,max:18e5},maxConcurrentUploads:{env:"CHECKSUM_RUNTIME_UPLOAD_MAX_CONCURRENT",fallback:15,min:1,max:64}};function ry(t,e,r,n){if(t===void 0||t.trim()==="")return e;let i=Number(t);return Number.isInteger(i)?Math.min(n,Math.max(r,i)):e}s(ry,"clampEnvInt");var ny=[["cliHardCapMs",["finalizeCeilingMs"],.9],["finalizeCeilingMs",["finalizeBudgetMs"],1],["finalizeBudgetMs",["stallTimeoutMs","assetDeadlineMs","watchTimeoutMs"],1],["assetDeadlineMs",["uploadTimeoutMs"],1],["uploadTimeoutMs",["noProgressAbortMs"],.5]];function iy(t){let e={...t},r=[];for(let[n,i,a]of ny)for(let o of i){let l=Math.floor(e[n]*a);e[o]>l&&(r.push(`${ii[o].env} (${e[o]}ms) exceeds its bound under ${ii[n].env} (${e[n]}ms); using ${l}ms`),e[o]=l)}return{tunables:e,warnings:r}}s(iy,"coerceScopeHierarchy");function ay(t){let e={};for(let r of Object.keys(ii)){let n=ii[r];e[r]=ry(t[n.env],n.fallback,n.min,n.max)}return e.resumableChunkBytes=Math.max(1,Math.floor(e.resumableChunkBytes/262144))*262144,iy(e)}s(ay,"resolveUploadTunablesDetailed");function os(t){return ay(t).tunables}s(os,"resolveUploadTunables");var E4=os({});var Qu=2e3;function oy(t){switch(t){case"passed":return"passed";case"timedOut":return"timedOut";case"skipped":return"skipped";case"interrupted":return"interrupted";default:return"failed"}}s(oy,"toProgressStatus");var ai=class{constructor(){this.monitorPort=process.env.CHECKSUM_UPLOAD_AGENT_PORT;this.tunables=os(process.env);this.startedAt=Date.now();this.rootDir=process.cwd();this.testsById=new Map;this.lastFlushAt=0;this.sendChain=Promise.resolve()}static{s(this,"ChecksumProgressReporter")}printsToStdio(){return!1}onBegin(e,r){this.guard(()=>{e.rootDir&&(this.rootDir=e.rootDir);for(let n of r.allTests?.()??[])this.register(n);this.flush(!0)})}onTestBegin(e,r){this.guard(()=>{let n=this.itemFor(e);n.status="running",n.startedAt=r.startTime?.getTime()??Date.now(),n.endedAt=null,n.durationMs=null,n.retry=r.retry??0,this.flush()})}onTestEnd(e,r){this.guard(()=>{let n=this.itemFor(e);n.status=oy(r.status),n.endedAt=Date.now(),n.durationMs=r.duration??null,n.retry=r.retry??n.retry,n.startedAt??=r.startTime?.getTime()??null,this.flush();let i=n.status==="passed"||n.status==="skipped";ss("test_result",{test_suite_run_id:process.env.CHECKSUM_TEST_SUITE_ID,outcome:i?"success":"error",test_id:n.id,status:n.status,retry:n.retry,duration_ms:n.durationMs??void 0,title:n.title,file:n.file,project:n.project||void 0})})}async onEnd(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),await Xu(this.send(),this.tunables.onEndFlushTimeoutMs)}itemFor(e){return this.testsById.get(e.id)??this.register(e)}register(e){let r="";try{r=e.parent?.project?.()?.name??""}catch{}let n=e.location?.file??"";try{n&&(n=(0,ed.relative)(this.rootDir,n))}catch{}let i={id:e.id,title:e.title??"",titlePath:this.titlePathOf(e),file:n,line:e.location?.line??0,project:r,status:"pending",startedAt:null,endedAt:null,durationMs:null,retry:0};return this.testsById.set(i.id,i),i}titlePathOf(e){try{return(e.titlePath?.()??[]).filter(r=>!!r)}catch{return e.title?[e.title]:[]}}snapshot(){return{schemaVersion:1,source:"playwright",startedAt:this.startedAt,updatedAt:Date.now(),tests:[...this.testsById.values()]}}flush(e=!1){if(!this.monitorPort)return;let r=Date.now()-this.lastFlushAt;if(e||r>=Qu){this.lastFlushAt=Date.now(),this.send();return}this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.lastFlushAt=Date.now(),this.send()},Qu-r))}send(){return this.monitorPort?(this.sendChain=this.sendChain.then(()=>this.postSnapshot()),this.sendChain):Promise.resolve()}async postSnapshot(){this.monitorPort&&await Yu({type:"runProgress",payload:this.snapshot()},{port:this.monitorPort,timeoutMs:this.tunables.ipcTimeoutMs})}guard(e){try{e()}catch{}}};
161
+ /*! Bundled license information:
162
+
163
+ @langchain/core/dist/utils/js-sha256/hash.js:
164
+ (**
165
+ * [js-sha256]{@link https://github.com/emn178/js-sha256}
166
+ *
167
+ * @version 0.11.1
168
+ * @author Chen, Yi-Cyuan [emn178@gmail.com]
169
+ * @copyright Chen, Yi-Cyuan 2014-2025
170
+ * @license MIT
171
+ *)
172
+
173
+ @langchain/core/dist/utils/fast-json-patch/src/helpers.js:
174
+ (*!
175
+ * https://github.com/Starcounter-Jack/JSON-Patch
176
+ * (c) 2017-2022 Joachim Wester
177
+ * MIT licensed
178
+ *)
179
+
180
+ @langchain/core/dist/utils/fast-json-patch/src/duplex.js:
181
+ (*!
182
+ * https://github.com/Starcounter-Jack/JSON-Patch
183
+ * (c) 2013-2021 Joachim Wester
184
+ * MIT license
185
+ *)
186
+
187
+ @langchain/core/dist/utils/sax-js/sax.js:
188
+ (*! http://mths.be/fromcodepoint v0.1.0 by @mathias *)
189
+ */