@arcgis/ai-components 5.2.0-next.36 → 5.2.0-next.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cdn/{KRE4U7V7.js → 2K3FTW7J.js} +1 -1
- package/dist/cdn/{TSEQVE2H.js → 32B6ZVYG.js} +1 -1
- package/dist/cdn/{L77BTGXY.js → 3RPE2QMJ.js} +1 -1
- package/dist/cdn/{4RZPOYZ7.js → 3X7JLPXS.js} +1 -1
- package/dist/cdn/53TGCGSX.js +18 -0
- package/dist/cdn/{JEIMRNYM.js → 7GE723EX.js} +1 -1
- package/dist/cdn/{S27EJSLC.js → B7W5WD4R.js} +1 -1
- package/dist/cdn/BLKXZEPZ.js +56 -0
- package/dist/cdn/{IGZWQJW7.js → D36UDLAY.js} +1 -1
- package/dist/cdn/{7IFCBXV7.js → DFF2LGQI.js} +1 -1
- package/dist/cdn/{YRBANNQ5.js → E2JBQWHX.js} +1 -1
- package/dist/cdn/{O7TGCM5P.js → EJ2LRQVR.js} +1 -1
- package/dist/cdn/{Q73PK7Q7.js → FDPJ5Y3M.js} +1 -1
- package/dist/cdn/FK7ENS6I.js +2 -0
- package/dist/cdn/{CIW3QMKV.js → FNFJYOHX.js} +1 -1
- package/dist/cdn/{2NMR43NW.js → GJHBXGNP.js} +1 -1
- package/dist/cdn/HW2FV2RU.js +48 -0
- package/dist/cdn/{XVQJBUMY.js → I4A2LAZS.js} +1 -1
- package/dist/cdn/{O3F47IO5.js → I5QIEV37.js} +1 -1
- package/dist/cdn/{YYY7HKYX.js → IBKTXP76.js} +1 -1
- package/dist/cdn/MU52B4SV.js +181 -0
- package/dist/cdn/{SMADRJ67.js → NV2KTZTO.js} +1 -1
- package/dist/cdn/ON5PWODA.js +208 -0
- package/dist/cdn/{IXAKT6L3.js → P22UEKRX.js} +1 -1
- package/dist/cdn/PA5W5PWE.js +2 -0
- package/dist/cdn/{WAVKMZA6.js → QA7IATZC.js} +1 -1
- package/dist/cdn/{IC5P5NYY.js → QJJ6YSAC.js} +1 -1
- package/dist/cdn/{HOCTVCHH.js → RHM3WKYV.js} +1 -1
- package/dist/cdn/{E7TMP4YV.js → SHFSDORL.js} +1 -1
- package/dist/cdn/{AMVOJNWN.js → TIEV263K.js} +1 -1
- package/dist/cdn/{HXOSLGWU.js → TKSWXCCJ.js} +1 -1
- package/dist/cdn/{AFLQZIKS.js → VAX3IAC3.js} +31 -31
- package/dist/cdn/{WDE3HN7K.js → XHJTT7BG.js} +1 -1
- package/dist/cdn/XNITXZDU.js +2 -0
- package/dist/cdn/{C7E7MJSR.js → XXIKORXX.js} +1 -1
- package/dist/cdn/{HBYZSLEZ.js → Y7KEZCVG.js} +1 -1
- package/dist/cdn/agent-utils/index.js +1 -1
- package/dist/cdn/agent-utils/middlewares/humanInTheLoop.js +1 -1
- package/dist/cdn/agent-utils/middlewares/middleware.js +1 -1
- package/dist/cdn/agent-utils/middlewares/trace.js +1 -1
- package/dist/cdn/index.js +1 -1
- package/dist/docs/api.json +1 -1
- package/dist/docs/docs.json +1 -1
- package/dist/docs/web-types.json +1 -1
- package/package.json +9 -9
- package/dist/cdn/6LZ6GOHF.js +0 -56
- package/dist/cdn/CJIV4KJZ.js +0 -179
- package/dist/cdn/CVHJMR5X.js +0 -2
- package/dist/cdn/EBRNMPPO.js +0 -48
- package/dist/cdn/IKEF7ZHH.js +0 -181
- package/dist/cdn/LODKJRS4.js +0 -2
- package/dist/cdn/PKHQW7QU.js +0 -18
- package/dist/cdn/VKU4WAQV.js +0 -2
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import{$ as Ca,Dd as Oa,d as dt,e as Aa,j as Ln,k as ka,m as Bo,n as Fo,o as Ia,u as $e,w as Ho,x as Go}from"./ZEYIBYSF.js";import{a as Kt,b as vp,c as jn}from"./YIMNOUTF.js";var Al=Kt((BE,As)=>{"use strict";var km=Object.prototype.hasOwnProperty,Ie="~";function fn(){}Object.create&&(fn.prototype=Object.create(null),new fn().__proto__||(Ie=!1));function Im(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function Tl(e,t,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var a=new Im(r,n||e,i),s=Ie?Ie+t:t;return e._events[s]?e._events[s].fn?e._events[s]=[e._events[s],a]:e._events[s].push(a):(e._events[s]=a,e._eventsCount++),e}function pi(e,t){--e._eventsCount===0?e._events=new fn:delete e._events[t]}function xe(){this._events=new fn,this._eventsCount=0}xe.prototype.eventNames=function(){var t=[],r,n;if(this._eventsCount===0)return t;for(n in r=this._events)km.call(r,n)&&t.push(Ie?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(r)):t};xe.prototype.listeners=function(t){var r=Ie?Ie+t:t,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,s=new Array(a);i<a;i++)s[i]=n[i].fn;return s};xe.prototype.listenerCount=function(t){var r=Ie?Ie+t:t,n=this._events[r];return n?n.fn?1:n.length:0};xe.prototype.emit=function(t,r,n,i,a,s){var o=Ie?Ie+t:t;if(!this._events[o])return!1;var c=this._events[o],u=arguments.length,l,d;if(c.fn){switch(c.once&&this.removeListener(t,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,s),!0}for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];c.fn.apply(c.context,l)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(t,c[d].fn,void 0,!0),u){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,r);break;case 3:c[d].fn.call(c[d].context,r,n);break;case 4:c[d].fn.call(c[d].context,r,n,i);break;default:if(!l)for(p=1,l=new Array(u-1);p<u;p++)l[p-1]=arguments[p];c[d].fn.apply(c[d].context,l)}}return!0};xe.prototype.on=function(t,r,n){return Tl(this,t,r,n,!1)};xe.prototype.once=function(t,r,n){return Tl(this,t,r,n,!0)};xe.prototype.removeListener=function(t,r,n,i){var a=Ie?Ie+t:t;if(!this._events[a])return this;if(!r)return pi(this,a),this;var s=this._events[a];if(s.fn)s.fn===r&&(!i||s.once)&&(!n||s.context===n)&&pi(this,a);else{for(var o=0,c=[],u=s.length;o<u;o++)(s[o].fn!==r||i&&!s[o].once||n&&s[o].context!==n)&&c.push(s[o]);c.length?this._events[a]=c.length===1?c[0]:c:pi(this,a)}return this};xe.prototype.removeAllListeners=function(t){var r;return t?(r=Ie?Ie+t:t,this._events[r]&&pi(this,r)):(this._events=new fn,this._eventsCount=0),this};xe.prototype.off=xe.prototype.removeListener;xe.prototype.addListener=xe.prototype.on;xe.prefixed=Ie;xe.EventEmitter=xe;typeof As<"u"&&(As.exports=xe)});var Il=Kt((FE,kl)=>{"use strict";kl.exports=(e,t)=>(t=t||(()=>{}),e.then(r=>new Promise(n=>{n(t())}).then(()=>r),r=>new Promise(n=>{n(t())}).then(()=>{throw r})))});var Ol=Kt((HE,mi)=>{"use strict";var Cm=Il(),hi=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Cl=(e,t,r)=>new Promise((n,i)=>{if(typeof t!="number"||t<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(t===1/0){n(e);return}let a=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(c){i(c)}return}let s=typeof r=="string"?r:`Promise timed out after ${t} milliseconds`,o=r instanceof Error?r:new hi(s);typeof e.cancel=="function"&&e.cancel(),i(o)},t);Cm(e.then(n,i),()=>{clearTimeout(a)})});mi.exports=Cl;mi.exports.default=Cl;mi.exports.TimeoutError=hi});var Rl=Kt(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});function Om(e,t,r){let n=0,i=e.length;for(;i>0;){let a=i/2|0,s=n+a;r(e[s],t)<=0?(n=++s,i-=a+1):i=a}return n}ks.default=Om});var Nl=Kt(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});var Rm=Rl(),Is=class{constructor(){this._queue=[]}enqueue(t,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:t};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let i=Rm.default(this._queue,n,(a,s)=>s.priority-a.priority);this._queue.splice(i,0,n)}dequeue(){let t=this._queue.shift();return t?.run}filter(t){return this._queue.filter(r=>r.priority===t.priority).map(r=>r.run)}get size(){return this._queue.length}};Cs.default=Is});var _i=Kt(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});var Nm=Al(),$l=Ol(),$m=Nl(),gi=()=>{},Pm=new $l.TimeoutError,Os=class extends Nm{constructor(t){var r,n,i,a;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=gi,this._resolveIdle=gi,t=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:$m.default},t),!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=t.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(a=(i=t.interval)===null||i===void 0?void 0:i.toString())!==null&&a!==void 0?a:""}\` (${typeof t.interval})`);this._carryoverConcurrencyCount=t.carryoverConcurrencyCount,this._isIntervalIgnored=t.intervalCap===1/0||t.interval===0,this._intervalCap=t.intervalCap,this._interval=t.interval,this._queue=new t.queueClass,this._queueClass=t.queueClass,this.concurrency=t.concurrency,this._timeout=t.timeout,this._throwOnTimeout=t.throwOnTimeout===!0,this._isPaused=t.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=gi,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=gi,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let t=Date.now();if(this._intervalId===void 0){let r=this._intervalEnd-t;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 t=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let r=this._queue.dequeue();return r?(this.emit("active"),r(),t&&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(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this._concurrency=t,this._processQueue()}async add(t,r={}){return new Promise((n,i)=>{let a=async()=>{this._pendingCount++,this._intervalCount++;try{let s=this._timeout===void 0&&r.timeout===void 0?t():$l.default(Promise.resolve(t()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&i(Pm)});n(await s)}catch(s){i(s)}this._next()};this._queue.enqueue(a,r),this._tryToStartAnother(),this.emit("add")})}async addAll(t,r){return Promise.all(t.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(t=>{let r=this._resolveEmpty;this._resolveEmpty=()=>{r(),t()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(t=>{let r=this._resolveIdle;this._resolveIdle=()=>{r(),t()}})}get size(){return this._queue.size}sizeBy(t){return this._queue.filter(t).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(t){this._timeout=t}};Rs.default=Os});var dp=Kt(pa=>{"use strict";pa.byteLength=hw;pa.toByteArray=gw;pa.fromByteArray=ww;var St=[],Xe=[],pw=typeof Uint8Array<"u"?Uint8Array:Array,ko="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Ir=0,up=ko.length;Ir<up;++Ir)St[Ir]=ko[Ir],Xe[ko.charCodeAt(Ir)]=Ir;var Ir,up;Xe[45]=62;Xe[95]=63;function lp(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function hw(e){var t=lp(e),r=t[0],n=t[1];return(r+n)*3/4-n}function mw(e,t,r){return(t+r)*3/4-r}function gw(e){var t,r=lp(e),n=r[0],i=r[1],a=new pw(mw(e,n,i)),s=0,o=i>0?n-4:n,c;for(c=0;c<o;c+=4)t=Xe[e.charCodeAt(c)]<<18|Xe[e.charCodeAt(c+1)]<<12|Xe[e.charCodeAt(c+2)]<<6|Xe[e.charCodeAt(c+3)],a[s++]=t>>16&255,a[s++]=t>>8&255,a[s++]=t&255;return i===2&&(t=Xe[e.charCodeAt(c)]<<2|Xe[e.charCodeAt(c+1)]>>4,a[s++]=t&255),i===1&&(t=Xe[e.charCodeAt(c)]<<10|Xe[e.charCodeAt(c+1)]<<4|Xe[e.charCodeAt(c+2)]>>2,a[s++]=t>>8&255,a[s++]=t&255),a}function _w(e){return St[e>>18&63]+St[e>>12&63]+St[e>>6&63]+St[e&63]}function yw(e,t,r){for(var n,i=[],a=t;a<r;a+=3)n=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(_w(n));return i.join("")}function ww(e){for(var t,r=e.length,n=r%3,i=[],a=16383,s=0,o=r-n;s<o;s+=a)i.push(yw(e,s,s+a>o?o:s+a));return n===1?(t=e[r-1],i.push(St[t>>2]+St[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],i.push(St[t>>10]+St[t>>4&63]+St[t<<2&63]+"=")),i.join("")}});var Vo=Object.defineProperty,L=(e,t)=>{let r={};for(var n in e)Vo(r,n,{get:e[n],enumerable:!0});return t||Vo(r,Symbol.toStringTag,{value:"Module"}),r};var xp=/([A-Z]+)([A-Z][a-z0-9]+)/g,Ep=/([a-z0-9])([A-Z])/g,Zo=/[-_\s]+/g;function Sp(e){return e.replace(xp,"$1_$2").replace(Ep,"$1_$2").replace(Zo,"_").toLowerCase()}function Tp(e){let t=e.trim();return/[-_\s]/.test(t)?t.replace(Zo,"_").toLowerCase().replace(/_+([a-z0-9])/g,(r,n)=>n.toUpperCase()):t}function qo(e,t){return t?.[e]||Sp(e)}function Dw(e,t){return t?.[e]||Tp(e)}function Wo(e,t,r){let n={};for(let i in e)Object.hasOwn(e,i)&&(n[t(i,r)]=e[i]);return n}var Ko="__lc_escaped__";function Ap(e){return"lc"in e||Object.keys(e).length===1&&"__lc_escaped__"in e}function kp(e){return{[Ko]:e}}function Ip(e){return Object.keys(e).length===1&&"__lc_escaped__"in e}function Cp(e){return e!==null&&typeof e=="object"&&"lc_serializable"in e&&typeof e.toJSON=="function"}function Op(e){let t;return e!==null&&typeof e=="object"?"lc_id"in e&&Array.isArray(e.lc_id)?t=e.lc_id:t=[e.constructor?.name??"Object"]:t=[typeof e],{lc:1,type:"not_implemented",id:t}}function Dn(e,t=new WeakSet){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){if(t.has(e))return Op(e);if(Cp(e))return e;t.add(e);let r=e;if(Ap(r))return t.delete(e),kp(r);let n={};for(let[i,a]of Object.entries(r))n[i]=Dn(a,t);return t.delete(e),n}return Array.isArray(e)?e.map(r=>Dn(r,t)):e}function Jo(e){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(Ip(t))return t[Ko];let r={};for(let[n,i]of Object.entries(t))r[n]=Jo(i);return r}return Array.isArray(e)?e.map(t=>Jo(t)):e}var Gw=L({Serializable:()=>ft,get_lc_unique_name:()=>Un});function Yo(e){return Array.isArray(e)?[...e]:{...e}}function Rp(e,t){let r=Yo(e);for(let[n,i]of Object.entries(t)){let[a,...s]=n.split(".").reverse(),o=r;for(let c of s.reverse()){if(o[c]===void 0)break;o[c]=Yo(o[c]),o=o[c]}o[a]!==void 0&&(o[a]={lc:1,type:"secret",id:[i]})}return r}function Un(e){let t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var ft=class Xo{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Un(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...r){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof Xo||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let t={},r={},n=Object.keys(this.lc_kwargs).reduce((o,c)=>(o[c]=c in this?this[c]:this.lc_kwargs[c],o),{});for(let o=Object.getPrototypeOf(this);o;o=Object.getPrototypeOf(o))Object.assign(t,Reflect.get(o,"lc_aliases",this)),Object.assign(r,Reflect.get(o,"lc_secrets",this)),Object.assign(n,Reflect.get(o,"lc_attributes",this));Object.keys(r).forEach(o=>{let c=this,u=n,[l,...d]=o.split(".").reverse();for(let f of d.reverse()){if(!(f in c)||c[f]===void 0)return;(!(f in u)||u[f]===void 0)&&(typeof c[f]=="object"&&c[f]!=null?u[f]={}:Array.isArray(c[f])&&(u[f]=[])),c=c[f],u=u[f]}l in c&&c[l]!==void 0&&(u[l]=u[l]||c[l])});let i={},a=new WeakSet;a.add(this);for(let[o,c]of Object.entries(n))i[o]=Dn(c,a);let s=Wo(Object.keys(r).length?Rp(i,r):i,qo,t);return{lc:1,type:"constructor",id:this.lc_id,kwargs:s}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function Rt(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&"source_type"in e&&(e.source_type==="url"||e.source_type==="base64"||e.source_type==="text"||e.source_type==="id")}function Qo(e){return Rt(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function ec(e){return Rt(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function Zw(e){return Rt(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function tc(e){return Rt(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function qw(e){if(Rt(e)){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url}};if(e.source_type==="base64"){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Ww(e){let t=e.split(";")[0].split("/");if(t.length!==2)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);let r=t[0].trim(),n=t[1].trim();if(r===""||n==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);let i={};for(let a of e.split(";").slice(1)){let s=a.split("=");if(s.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);let o=s[0].trim(),c=s[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${e}".`);i[o]=c}return{type:r,subtype:n,parameters:i}}function Ra({dataUrl:e,asTypedArray:t=!1}){let r=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(r){n=r[1].toLowerCase();let i=t?Uint8Array.from(atob(r[2]),a=>a.charCodeAt(0)):r[2];return{mime_type:n,data:i}}}function Jw(e,t){if(e.type==="text"){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type==="image"){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type==="audio"){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type==="file"){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function T(e,t){return $(e)&&e.type===t}function $(e){return typeof e=="object"&&e!==null}function de(e){return Array.isArray(e)}function g(e){return typeof e=="string"}function De(e){return typeof e=="number"}function zn(e){return e instanceof Uint8Array}function Na(e){try{return JSON.parse(e)}catch{return}}var Ue=e=>e();function Np(e){if(e.type==="char_location"&&g(e.document_title)&&De(e.start_char_index)&&De(e.end_char_index)&&g(e.cited_text)){let{document_title:t,start_char_index:r,end_char_index:n,cited_text:i,...a}=e;return{...a,type:"citation",source:"char",title:t??void 0,startIndex:r,endIndex:n,citedText:i}}if(e.type==="page_location"&&g(e.document_title)&&De(e.start_page_number)&&De(e.end_page_number)&&g(e.cited_text)){let{document_title:t,start_page_number:r,end_page_number:n,cited_text:i,...a}=e;return{...a,type:"citation",source:"page",title:t??void 0,startIndex:r,endIndex:n,citedText:i}}if(e.type==="content_block_location"&&g(e.document_title)&&De(e.start_block_index)&&De(e.end_block_index)&&g(e.cited_text)){let{document_title:t,start_block_index:r,end_block_index:n,cited_text:i,...a}=e;return{...a,type:"citation",source:"block",title:t??void 0,startIndex:r,endIndex:n,citedText:i}}if(e.type==="web_search_result_location"&&g(e.url)&&g(e.title)&&g(e.encrypted_index)&&g(e.cited_text)){let{url:t,title:r,encrypted_index:n,cited_text:i,...a}=e;return{...a,type:"citation",source:"url",url:t,title:r,startIndex:Number(n),endIndex:Number(n),citedText:i}}if(e.type==="search_result_location"&&g(e.source)&&g(e.title)&&De(e.start_block_index)&&De(e.end_block_index)&&g(e.cited_text)){let{source:t,title:r,start_block_index:n,end_block_index:i,cited_text:a,...s}=e;return{...s,type:"citation",source:"search",url:t,title:r??void 0,startIndex:n,endIndex:i,citedText:a}}}function nc(e){if(T(e,"document")&&$(e.source)&&"type"in e.source){if(e.source.type==="base64"&&g(e.source.media_type)&&g(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&g(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&g(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&g(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(T(e,"image")&&$(e.source)&&"type"in e.source){if(e.source.type==="base64"&&g(e.source.media_type)&&g(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&g(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&g(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function ic(e){function*t(){for(let r of e){let n=nc(r);n?yield n:yield r}}return Array.from(t())}function rc(e){function*t(){let r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(let n of r){if(T(n,"text")&&g(n.text)){let{text:i,citations:a,...s}=n;if(de(a)&&a.length){let o=a.reduce((c,u)=>{let l=Np(u);return l?[...c,l]:c},[]);yield{...s,type:"text",text:i,annotations:o};continue}else{yield{...s,type:"text",text:i};continue}}else if(T(n,"thinking")&&g(n.thinking)){let{thinking:i,signature:a,...s}=n;yield{...s,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")&&g(n.name)&&g(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(T(n,"input_json_delta")){if($p(e)&&e.tool_call_chunks?.length){let i=e.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")&&g(n.name)&&g(n.id)){let{name:i,id:a}=n;if(i==="web_search"){yield{id:a,type:"server_tool_call",name:"web_search",args:{query:Ue(()=>{if(typeof n.input=="string")return n.input;if($(n.input)&&g(n.input.query))return n.input.query;if(g(n.partial_json)){let s=Na(n.partial_json);if(s?.query)return s.query}return""})}};continue}else if(n.name==="code_execution"){yield{id:a,type:"server_tool_call",name:"code_execution",args:{code:Ue(()=>{if(typeof n.input=="string")return n.input;if($(n.input)&&g(n.input.code))return n.input.code;if(g(n.partial_json)){let s=Na(n.partial_json);if(s?.code)return s.code}return""})}};continue}}else if(T(n,"web_search_tool_result")&&g(n.tool_use_id)&&de(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((s,o)=>T(o,"web_search_result")?[...s,o.url]:s,[])}};continue}else if(T(n,"code_execution_tool_result")&&g(n.tool_use_id)&&$(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")&&g(n.tool_use_id)&&$(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=nc(n);if(i){yield i;continue}}yield{type:"non_standard",value:n}}}return Array.from(t())}var ac={translateContent:rc,translateContentChunk:rc};function $p(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function Pp(e){return Qo(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:ec(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:tc(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function sc(e){return e.map(Pp)}function oc(e){return!!(T(e,"image_url")&&$(e.image_url)||T(e,"input_audio")&&$(e.input_audio)||T(e,"file")&&$(e.file))}function cc(e){if(T(e,"image_url")&&$(e.image_url)&&g(e.image_url.url)){let t=Ra({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}else{if(T(e,"input_audio")&&$(e.input_audio)&&g(e.input_audio.data)&&g(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(T(e,"file")&&$(e.file)&&g(e.file.data)){let t=Ra({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(g(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function Mp(e){let t=[];typeof e.content=="string"?e.content.length>0&&t.push({type:"text",text:e.content}):t.push(...Bn(e.content));for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function jp(e){let t=[];typeof e.content=="string"?e.content.length>0&&t.push({type:"text",text:e.content}):t.push(...Bn(e.content));for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function Bn(e){let t=[];for(let r of e)oc(r)?t.push(cc(r)):t.push(r);return t}function Lp(e){if(e.type==="url_citation"){let{url:t,title:r,start_index:n,end_index:i}=e;return{type:"citation",url:t,title:r,startIndex:n,endIndex:i}}if(e.type==="file_citation"){let{file_id:t,filename:r,index:n}=e;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:t}}return e}function uc(e){function*t(){$(e.additional_kwargs?.reasoning)&&de(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((n,i)=>$(i)&&g(i.text)?`${n}${i.text}`:n,"")});let r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(let n of r)if(T(n,"text")){let{text:i,annotations:a,phase:s,extras:o,...c}=n,u=$(o)?{...o}:{};g(s)&&(u.phase=s);let l=Object.keys(u).length>0?{extras:u}:{};Array.isArray(a)?yield{...c,...l,type:"text",text:String(i),annotations:a.map(Lp)}:yield{...c,...l,type:"text",text:String(i)}}for(let n of e.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if($(e.additional_kwargs)&&de(e.additional_kwargs.tool_outputs))for(let n of e.additional_kwargs.tool_outputs){if(T(n,"web_search_call")){let i={};if($(n.action)&&g(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={};$(n.action)&&(a.action=n.action),yield{type:"server_tool_call_result",toolCallId:g(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:de(n.queries)?n.queries:[]}},(n.status==="completed"||n.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:g(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:de(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(g(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),de(n.outputs)){let i=Ue(()=>{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={};$(n.arguments)&&Object.assign(i,n.arguments);let a={};g(n.execution)&&(a.execution=n.execution),g(n.status)&&(a.status=n.status),g(n.call_id)&&(a.call_id=n.call_id),yield{id:g(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"};g(n.execution)&&(i.execution=n.execution),yield{type:"server_tool_call_result",toolCallId:g(n.id)?n.id:"",status:n.status==="completed"?"success":n.status==="failed"?"error":"success",output:{tools:de(n.tools)?n.tools:[]},extras:i};continue}else if(T(n,"image_generation_call")){g(n.result)&&(yield{type:"image",mimeType:"image/png",data:n.result,id:g(n.id)?n.id:void 0,metadata:{status:g(n.status)?n.status:void 0}}),yield{type:"non_standard",value:n};continue}$(n)&&(yield{type:"non_standard",value:n})}}return Array.from(t())}function Dp(e){function*t(){yield*uc(e);for(let r of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return Array.from(t())}var lc={translateContent:e=>typeof e.content=="string"?Mp(e):uc(e),translateContentChunk:e=>typeof e.content=="string"?jp(e):Dp(e)};function dc(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function fc(e,t="pretty"){return t==="pretty"?Up(e):JSON.stringify(e)}function Up(e){let t=[],r=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),i="=".repeat(n),a=r.length%2===0?i:`${i}=`;if(t.push(`${i}${r}${a}`),e.type==="ai"){let s=e;if(s.tool_calls&&s.tool_calls.length>0){t.push("Tool Calls:");for(let o of s.tool_calls){t.push(` ${o.name} (${o.id})`),t.push(` Call ID: ${o.id}`),t.push(" Args:");for(let[c,u]of Object.entries(o.args))t.push(` ${c}: ${typeof u=="object"?JSON.stringify(u):u}`)}}}if(e.type==="tool"){let s=e;s.name&&t.push(`Name: ${s.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
|
|
3
|
+
`)}var $a=Symbol.for("langchain.message");function pc(e){return Array.isArray(e)?e:typeof e=="string"?e===""?[]:[{type:"text",text:e}]:e==null?[]:[e]}function Pe(e,t){if(typeof e=="string")return e===""?t:typeof t=="string"?e+t:Array.isArray(t)&&t.length===0?e:Array.isArray(t)&&t.some(r=>Rt(r))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t];if(Array.isArray(t)){let r=pc(e);return Cr(r,t)??[...r,...t]}else return t===""?e:Array.isArray(e)&&e.some(r=>Rt(r))?[...e,{type:"file",source_type:"text",text:t}]:[...pc(e),{type:"text",text:t}]}function _c(e,t){return e==="error"||t==="error"?"error":"success"}function zp(e,t){function r(n,i){if(typeof n!="object"||n===null||n===void 0)return n;if(i>=t)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(s=>r(s,i+1));let a={};for(let s of Object.keys(n))a[s]=r(n[s],i+1);return a}return JSON.stringify(r(e,0),null,2)}var ke=class extends ft{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[$a]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){let t=typeof e=="string"||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),this.name=t.name,t.content===void 0&&t.contentBlocks!==void 0?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):t.content!==void 0?(this.content=t.content??[],this.response_metadata=t.response_metadata):(this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){let e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[sc,Bn,ic].reduce((t,r)=>r(t),e)}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(e){return typeof e=="object"&&e!==null&&$a in e&&e[$a]===!0&&dc(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;let t=zp(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return fc(this,e)}};function mb(e){return Array.isArray(e)&&e.every(t=>typeof t.index=="number")}var Bp=["index","created","timestamp"];function ce(e,t,r){let n=r?.ignoreKeys??Bp;if(e==null&&t==null)return;if(e==null||t==null)return e??t;let i={...e};for(let[a,s]of Object.entries(t))if(i[a]==null)i[a]=s;else{if(s==null)continue;if(typeof i[a]!=typeof s||Array.isArray(i[a])!==Array.isArray(s))throw new Error(`field[${a}] already exists in the message chunk, but with a different type.`);if(typeof i[a]=="string"){if(a==="type")continue;if(["id","name","output_version","model_provider"].includes(a))s&&(i[a]=s);else{if(n.includes(a))continue;i[a]+=s}}else if(typeof i[a]=="number"){if(n.includes(a))continue;i[a]=i[a]+s}else if(typeof i[a]=="object"&&!Array.isArray(i[a]))i[a]=ce(i[a],s,r);else if(Array.isArray(i[a]))i[a]=Cr(i[a],s,r);else{if(i[a]===s)continue;console.warn(`field[${a}] already exists in this message chunk and value has unsupported type.`)}}return i}function Fp(e){return typeof e=="number"||typeof e=="string"}function hc(e){return typeof e!="object"||e===null||!("index"in e)?!1:Fp(e.index)}function mc(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return t!=null&&t!==""}function gc(e){return e.endsWith("_delta")?e.slice(0,-6):e}function Hp(e,t){return typeof e!="object"||e===null||typeof t!="object"||t===null||!("type"in e)||!("type"in t)?!1:typeof e.type=="string"&&typeof t.type=="string"&&gc(e.type)!==gc(t.type)}function Gp(e,t){let r=hc(t),n=mc(t);return!r&&!n?-1:e.findIndex(i=>{let a=hc(i),s=mc(i);return r&&a?i.index!==t.index||Hp(i,t)?!1:s&&n?i.id===t.id:!0:!r&&!a&&n&&s?i.id===t.id:!1})}function Cr(e,t,r){if(!(e==null&&t==null)){if(e==null||t==null)return e||t;{let n=[...e];for(let i of t){let a=Gp(n,i);if(a!==-1)n[a]=ce(n[a],i,r);else{if(typeof i=="object"&&i!==null&&"text"in i&&i.text==="")continue;n.push(i)}}return n}}}function yc(e,t,r){if(!(e==null&&t==null)){if(e==null||t==null)return e??t;if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.
|
|
4
|
+
Left ${typeof e}
|
|
5
|
+
Right ${typeof t}`);if(typeof e=="string"&&typeof t=="string")return e+t;if(Array.isArray(e)&&Array.isArray(t))return Cr(e,t,r);if(typeof e=="object"&&typeof t=="object")return ce(e,t,r);if(e===t)return e;throw new Error(`Can not merge objects of different types.
|
|
6
|
+
Left ${e}
|
|
7
|
+
Right ${t}`)}}var ze=class wc extends ke{static isInstance(t){if(!super.isInstance(t))return!1;let r=Object.getPrototypeOf(t);for(;r!==null;){if(r===wc.prototype)return!0;r=Object.getPrototypeOf(r)}return!1}};function bc(e){return typeof e.role=="string"}function vc(e){return typeof e?._getType=="function"}function gb(e){return ze.isInstance(e)}var vb=L({ToolMessage:()=>Yt,ToolMessageChunk:()=>Vp,defaultToolCallParser:()=>Ma,isDirectToolOutput:()=>Pa,isToolMessage:()=>Zp,isToolMessageChunk:()=>qp});function Pa(e){return e!=null&&typeof e=="object"&&"lc_direct_tool_output"in e&&e.lc_direct_tool_output===!0}var Yt=class extends ke{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(e,t,r){let n=typeof e=="string"||Array.isArray(e)?{content:e,name:r,tool_call_id:t}:e;super(n),this.tool_call_id=n.tool_call_id,this.artifact=n.artifact,this.status=n.status,this.metadata=n.metadata}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Vp=class extends ze{type="tool";tool_call_id;status;artifact;constructor(e){super(e),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){let t=this.constructor;return new t({content:Pe(this.content,e.content),additional_kwargs:ce(this.additional_kwargs,e.additional_kwargs),response_metadata:ce(this.response_metadata,e.response_metadata),artifact:yc(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:_c(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function Ma(e){let t=[],r=[];for(let n of e)if(n.function){let i=n.function.name;try{let a=JSON.parse(n.function.arguments);t.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[t,r]}function Zp(e){return typeof e=="object"&&e!==null&&"getType"in e&&typeof e.getType=="function"&&e.getType()==="tool"}function qp(e){return e._getType()==="tool"}function ja(e){switch(e){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"}}function Wp(e){if($(e.document)&&$(e.document.source)){let t=ja($(e.document)&&g(e.document.format)?e.document.format:"");if($(e.document.source)){if($(e.document.source.s3Location)&&g(e.document.source.s3Location.uri))return{type:"file",mimeType:t,fileId:e.document.source.s3Location.uri};if(zn(e.document.source.bytes))return{type:"file",mimeType:t,data:e.document.source.bytes};if(g(e.document.source.text))return{type:"file",mimeType:t,data:Buffer.from(e.document.source.text).toString("base64")};if(de(e.document.source.content))return{type:"file",mimeType:t,data:e.document.source.content.reduce((r,n)=>$(n)&&g(n.text)?r+n.text:r,"")}}}return{type:"non_standard",value:e}}function Jp(e){if(T(e,"image")&&$(e.image)){let t=ja($(e.image)&&g(e.image.format)?e.image.format:"");if($(e.image.source)){if($(e.image.source.s3Location)&&g(e.image.source.s3Location.uri))return{type:"image",mimeType:t,fileId:e.image.source.s3Location.uri};if(zn(e.image.source.bytes))return{type:"image",mimeType:t,data:e.image.source.bytes}}}return{type:"non_standard",value:e}}function Kp(e){if(T(e,"video")&&$(e.video)){let t=ja($(e.video)&&g(e.video.format)?e.video.format:"");if($(e.video.source)){if($(e.video.source.s3Location)&&g(e.video.source.s3Location.uri))return{type:"video",mimeType:t,fileId:e.video.source.s3Location.uri};if(zn(e.video.source.bytes))return{type:"video",mimeType:t,data:e.video.source.bytes}}}return{type:"non_standard",value:e}}function xc(e){function*t(){let r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(let n of r){if(T(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(T(n,"citations_content")&&$(n.citationsContent)){yield{type:"text",text:de(n.citationsContent.content)?n.citationsContent.content.reduce((i,a)=>$(a)&&g(a.text)?i+a.text:i,""):"",annotations:de(n.citationsContent.citations)?n.citationsContent.citations.reduce((i,a)=>{if($(a)){let s=de(a.sourceContent)?a.sourceContent.reduce((c,u)=>$(u)&&g(u.text)?c+u.text:c,""):"",o=Ue(()=>{if($(a.location)){let c=a.location.documentChar||a.location.documentPage||a.location.documentChunk;if($(c))return{source:De(c.documentIndex)?c.documentIndex.toString():void 0,startIndex:De(c.start)?c.start:void 0,endIndex:De(c.end)?c.end:void 0}}return{}});i.push({type:"citation",citedText:s,...o})}return i},[]):[]};continue}else if(T(n,"document")&&$(n.document)){yield Wp(n);continue}else if(T(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(T(n,"image")&&$(n.image)){yield Jp(n);continue}else if(T(n,"reasoning_content")&&g(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(T(n,"text")&&g(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")&&$(n.video)){yield Kp(n);continue}}yield{type:"non_standard",value:n}}}return Array.from(t())}var Ec={translateContent:xc,translateContentChunk:xc};function Sc(e){let t=[],r=e.additional_kwargs?.reasoning_content;if(g(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),typeof e.content=="string")e.content.length>0&&t.push({type:"text",text:e.content});else for(let n of e.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&g(n.text)&&t.push({type:"text",text:n.text});for(let n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}var Tc={translateContent:Sc,translateContentChunk:Sc};function Ac(e){function*t(){let r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(let n of r){if(T(n,"text")&&g(n.text)){yield{type:"text",text:n.text};continue}else if(T(n,"thinking")&&g(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(T(n,"inlineData")&&$(n.inlineData)&&g(n.inlineData.mimeType)&&g(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(T(n,"functionCall")&&$(n.functionCall)&&g(n.functionCall.name)&&$(n.functionCall.args)){yield{type:"tool_call",id:e.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")&&$(n.fileData)&&g(n.fileData.mimeType)&&g(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 Array.from(t())}var kc={translateContent:Ac,translateContentChunk:Ac};function Ic(e){function*t(){let r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(let n of r){if(T(n,"reasoning")&&g(n.reasoning)){let i=Ue(()=>{let a=r.indexOf(n);if(de(e.additional_kwargs?.signatures)&&a>=0)return e.additional_kwargs.signatures.at(a)});g(i)?yield{type:"reasoning",reasoning:n.reasoning,signature:i}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(T(n,"thinking")&&g(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(T(n,"text")&&g(n.text)){yield{type:"text",text:n.text};continue}else if(T(n,"image_url")){if(g(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")&&g(n.mimeType)&&g(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return Array.from(t())}var Cc={translateContent:Ic,translateContentChunk:Ic};function Oc(e){let t=[],r=e.additional_kwargs?.reasoning;if(g(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),typeof e.content=="string"){let n=e.content,i=n.match(/<think>([\s\S]*?)<\/think>/);if(i){let a=i[1].trim();a.length>0&&t.push({type:"reasoning",reasoning:a}),n=n.replace(/<think>[\s\S]*?<\/think>/,"").trim()}n.length>0&&t.push({type:"text",text:n})}else for(let n of e.content)if(typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&g(n.text)){let i=n.text,a=i.match(/<think>([\s\S]*?)<\/think>/);if(a){let s=a[1].trim();s.length>0&&t.push({type:"reasoning",reasoning:s}),i=i.replace(/<think>[\s\S]*?<\/think>/,"").trim()}i.length>0&&t.push({type:"text",text:i})}for(let n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}var Rc={translateContent:Oc,translateContentChunk:Oc};function Nc(e){let t=[],r=e.additional_kwargs?.reasoning_content;if(g(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),typeof e.content=="string")e.content.length>0&&t.push({type:"text",text:e.content});else for(let n of e.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&g(n.text)&&t.push({type:"text",text:n.text});for(let n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}var $c={translateContent:Nc,translateContentChunk:Nc};function Pc(e){let t=[],r=e.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 s=i.summary;g(s)&&s.length>0&&(t.push({type:"reasoning",reasoning:s}),n=!0)}else if(a==="reasoning.text"){let s=i.text;g(s)&&s.length>0&&(t.push({type:"reasoning",reasoning:s}),n=!0)}}if(!n){let i=e.additional_kwargs?.reasoning_content;g(i)&&i.length>0&&t.push({type:"reasoning",reasoning:i})}if(typeof e.content=="string")e.content.length>0&&t.push({type:"text",text:e.content});else for(let i of e.content)typeof i=="object"&&"type"in i&&i.type==="text"&&"text"in i&&g(i.text)&&t.push({type:"text",text:i.text});for(let i of e.tool_calls??[])t.push({type:"tool_call",id:i.id,name:i.name,args:i.args});return t}var Mc={translateContent:Pc,translateContentChunk:Pc};function jc(e){let t=[];if($(e.additional_kwargs?.reasoning)){let n=e.additional_kwargs.reasoning;if(de(n.summary)){let i=n.summary.reduce((a,s)=>$(s)&&g(s.text)?`${a}${s.text}`:a,"");i.length>0&&t.push({type:"reasoning",reasoning:i})}}let r=e.additional_kwargs?.reasoning_content;if(g(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),typeof e.content=="string")e.content.length>0&&t.push({type:"text",text:e.content});else for(let n of e.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&g(n.text)&&t.push({type:"text",text:n.text});for(let n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}var Lc={translateContent:jc,translateContentChunk:jc};function Dc(e){function*t(){let r=Ue(()=>{if(typeof e.content=="string")return e.additional_kwargs.originalTextContentBlock?[{...e.additional_kwargs.originalTextContentBlock,type:"text"}]:[{type:"text",text:e.content}];{let n=e.additional_kwargs?.originalTextContentBlock;if(n?.thoughtSignature&&!e.content.some(i=>"thoughtSignature"in i)){let i=[...e.content];for(let a=i.length-1;a>=0;a--){let s=i[a];if(s.type==="text"&&!s.thought)return s.thoughtSignature=n.thoughtSignature,i}}return e.content}});for(let n of r){let i=Ue(()=>T(n,"text")&&g(n.text)?{type:"text",text:n.text}:T(n,"inlineData")&&$(n.inlineData)&&g(n.inlineData.mimeType)&&g(n.inlineData.data)?{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data}:T(n,"functionCall")&&$(n.functionCall)&&g(n.functionCall.name)&&$(n.functionCall.args)?{type:"tool_call",id:e.id,name:n.functionCall.name,args:n.functionCall.args}:T(n,"functionResponse")?{type:"non_standard",value:n}:T(n,"fileData")&&$(n.fileData)&&g(n.fileData.mimeType)&&g(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=Ue(()=>"thought"in n&&n.thought?{type:"reasoning",reasoning:i.type==="text"?i.text:"",reasoningContentBlock:i}:i),s={thought:n.thought,thoughtSignature:n.thoughtSignature,partMetadata:n.partMetadata,...a};for(let o in s)s[o]===void 0&&delete s[o];yield s}}return Array.from(t())}var Uc={translateContent:Dc,translateContentChunk:Dc};globalThis.lc_block_translators_registry??=new Map([["anthropic",ac],["bedrock-converse",Ec],["deepseek",Tc],["google",Uc],["google-genai",kc],["google-vertexai",Cc],["groq",Rc],["ollama",$c],["openai",lc],["openrouter",Mc],["xai",Lc]]);function La(e){return globalThis.lc_block_translators_registry.get(e)}function zc(e,t){return ce(e,t)??{}}function Bc(e,t){let r={};return(e?.audio!==void 0||t?.audio!==void 0)&&(r.audio=(e?.audio??0)+(t?.audio??0)),(e?.image!==void 0||t?.image!==void 0)&&(r.image=(e?.image??0)+(t?.image??0)),(e?.video!==void 0||t?.video!==void 0)&&(r.video=(e?.video??0)+(t?.video??0)),(e?.document!==void 0||t?.document!==void 0)&&(r.document=(e?.document??0)+(t?.document??0)),(e?.text!==void 0||t?.text!==void 0)&&(r.text=(e?.text??0)+(t?.text??0)),r}function Yp(e,t){let r={...Bc(e,t)};return(e?.cache_read!==void 0||t?.cache_read!==void 0)&&(r.cache_read=(e?.cache_read??0)+(t?.cache_read??0)),(e?.cache_creation!==void 0||t?.cache_creation!==void 0)&&(r.cache_creation=(e?.cache_creation??0)+(t?.cache_creation??0)),r}function Xp(e,t){let r={...Bc(e,t)};return(e?.reasoning!==void 0||t?.reasoning!==void 0)&&(r.reasoning=(e?.reasoning??0)+(t?.reasoning??0)),r}function Fn(e,t){return{input_tokens:(e?.input_tokens??0)+(t?.input_tokens??0),output_tokens:(e?.output_tokens??0)+(t?.output_tokens??0),total_tokens:(e?.total_tokens??0)+(t?.total_tokens??0),input_token_details:Yp(e?.input_token_details,t?.input_token_details),output_token_details:Xp(e?.output_token_details,t?.output_token_details)}}function Fc(e){let t=Symbol.for(e);return{brand(r,n){let i=n?Symbol.for(`${e}.${n}`):t;class a extends r{[i]=!0;constructor(...o){super(...o)}static isInstance(o){return typeof o=="object"&&o!==null&&i in o&&o[i]===!0}}return Object.defineProperty(a,"name",{value:r.name}),a},sub(r){return Fc(`${e}.${r}`)},isInstance(r){return typeof r=="object"&&r!==null&&t in r&&r[t]===!0}}}var Hc=Fc("langchain");var s0=L({ContextOverflowError:()=>eh,LangChainError:()=>Ua,ModelAbortError:()=>Qp,addLangChainErrorFields:()=>Da,ns:()=>Hn});function Da(e,t){return e.lc_error_code=t,e.message=`${e.message}
|
|
8
|
+
|
|
9
|
+
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/
|
|
10
|
+
`,e}var Hn=Hc.sub("error"),Ua=class extends Hn.brand(Error){name="LangChainError";constructor(e){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},Qp=class extends Hn.brand(Ua,"model-abort"){name="ModelAbortError";partialOutput;constructor(e,t){super(e),this.partialOutput=t}},eh=class Gc extends Hn.brand(Ua,"context-overflow"){name="ContextOverflowError";cause;constructor(t){super(t??"Input exceeded the model's context window.")}static fromError(t){let r=new Gc(t.message);return r.cause=t,r}};function Nt(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="tool_call")}function Vc(e){return!!(e&&typeof e=="object"&&"toolCall"in e&&e.toolCall!=null&&typeof e.toolCall=="object"&&"id"in e.toolCall&&typeof e.toolCall.id=="string")}var Or=class extends Error{output;constructor(e,t){super(e),this.output=t}};function f0(e,t=za){e=e.trim();let r=e.indexOf("```");if(r===-1)return t(e);let n=e.substring(r+3);n.startsWith(`json
|
|
11
|
+
`)?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith(`
|
|
12
|
+
`)&&(n=n.substring(1));let i=n.indexOf("```"),a=n;return i!==-1&&(a=n.substring(0,i)),t(a.trim())}function th(e){try{return JSON.parse(e)}catch{}let t=e.trim();if(t.length===0)throw new Error("Unexpected end of JSON input");let r=0;function n(){for(;r<t.length&&/\s/.test(t[r]);)r+=1}function i(){if(t[r]!=='"')throw new Error(`Expected '"' at position ${r}, got '${t[r]}'`);r+=1;let l="",d=!1;for(;r<t.length;){let f=t[r];if(d){if(f==="n")l+=`
|
|
13
|
+
`;else if(f==="t")l+=" ";else if(f==="r")l+="\r";else if(f==="\\")l+="\\";else if(f==='"')l+='"';else if(f==="b")l+="\b";else if(f==="f")l+="\f";else if(f==="/")l+="/";else if(f==="u"){let p=t.substring(r+1,r+5);if(/^[0-9A-Fa-f]{0,4}$/.test(p))p.length===4?l+=String.fromCharCode(Number.parseInt(p,16)):l+=`u${p}`,r+=p.length;else throw new Error(`Invalid unicode escape sequence '\\u${p}' at position ${r}`)}else throw new Error(`Invalid escape sequence '\\${f}' at position ${r}`);d=!1}else if(f==="\\")d=!0;else{if(f==='"')return r+=1,l;l+=f}r+=1}return d&&(l+="\\"),l}function a(){let l=r,d="";if(t[r]==="-"&&(d+="-",r+=1),r<t.length&&t[r]==="0"&&(d+="0",r+=1,t[r]>="0"&&t[r]<="9"))throw new Error(`Invalid number at position ${l}`);if(r<t.length&&t[r]>="1"&&t[r]<="9")for(;r<t.length&&t[r]>="0"&&t[r]<="9";)d+=t[r],r+=1;if(r<t.length&&t[r]===".")for(d+=".",r+=1;r<t.length&&t[r]>="0"&&t[r]<="9";)d+=t[r],r+=1;if(r<t.length&&(t[r]==="e"||t[r]==="E"))for(d+=t[r],r+=1,r<t.length&&(t[r]==="+"||t[r]==="-")&&(d+=t[r],r+=1);r<t.length&&t[r]>="0"&&t[r]<="9";)d+=t[r],r+=1;if(d==="-")return-0;let f=Number.parseFloat(d);if(Number.isNaN(f))throw r=l,new Error(`Invalid number '${d}' at position ${l}`);return f}function s(){if(n(),r>=t.length)throw new Error(`Unexpected end of input at position ${r}`);let l=t[r];if(l==="{")return c();if(l==="[")return o();if(l==='"')return i();if("null".startsWith(t.substring(r,r+4)))return r+=Math.min(4,t.length-r),null;if("true".startsWith(t.substring(r,r+4)))return r+=Math.min(4,t.length-r),!0;if("false".startsWith(t.substring(r,r+5)))return r+=Math.min(5,t.length-r),!1;if(l==="-"||l>="0"&&l<="9")return a();throw new Error(`Unexpected character '${l}' at position ${r}`)}function o(){if(t[r]!=="[")throw new Error(`Expected '[' at position ${r}, got '${t[r]}'`);let l=[];if(r+=1,n(),r>=t.length)return l;if(t[r]==="]")return r+=1,l;for(;r<t.length;){if(n(),r>=t.length||(l.push(s()),n(),r>=t.length))return l;if(t[r]==="]")return r+=1,l;if(t[r]===","){r+=1;continue}throw new Error(`Expected ',' or ']' at position ${r}, got '${t[r]}'`)}return l}function c(){if(t[r]!=="{")throw new Error(`Expected '{' at position ${r}, got '${t[r]}'`);let l={};if(r+=1,n(),r>=t.length)return l;if(t[r]==="}")return r+=1,l;for(;r<t.length;){if(n(),r>=t.length)return l;let d=i();if(n(),r>=t.length)return l;if(t[r]!==":")throw new Error(`Expected ':' at position ${r}, got '${t[r]}'`);if(r+=1,n(),r>=t.length||(l[d]=s(),n(),r>=t.length))return l;if(t[r]==="}")return r+=1,l;if(t[r]===","){r+=1;continue}throw new Error(`Expected ',' or '}' at position ${r}, got '${t[r]}'`)}return l}let u=s();if(n(),r<t.length)throw new Error(`Unexpected character '${t[r]}' at position ${r}`);return u}function za(e){try{return typeof e>"u"?null:th(e)}catch{return null}}var Ba=class Zc extends ke{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return Zc}constructor(t,r){(typeof t=="string"||Array.isArray(t))&&(t={content:t,role:r}),super(t),this.role=t.role}static isInstance(t){return super.isInstance(t)&&t.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},qc=class extends ze{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(e,t){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}concat(e){let t=this.constructor;return new t({content:Pe(this.content,e.content),additional_kwargs:ce(this.additional_kwargs,e.additional_kwargs),response_metadata:ce(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function m0(e){return e._getType()==="generic"}function g0(e){return e._getType()==="generic"}var Wc=class extends ke{static lc_name(){return"FunctionMessage"}type="function";name;constructor(e){super(e),this.name=e.name}},Jc=class extends ze{static lc_name(){return"FunctionMessageChunk"}type="function";concat(e){let t=this.constructor;return new t({content:Pe(this.content,e.content),additional_kwargs:ce(this.additional_kwargs,e.additional_kwargs),response_metadata:ce(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}};function b0(e){return e._getType()==="function"}function v0(e){return e._getType()==="function"}var Xt=class extends ke{static lc_name(){return"HumanMessage"}type="human";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&e.type==="human"}},Kc=class extends ze{static lc_name(){return"HumanMessageChunk"}type="human";constructor(e){super(e)}concat(e){let t=this.constructor;return new t({content:Pe(this.content,e.content),additional_kwargs:ce(this.additional_kwargs,e.additional_kwargs),response_metadata:ce(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="human"}};function A0(e){return e.getType()==="human"}function k0(e){return e.getType()==="human"}var Yc=class extends ke{type="remove";id;constructor(e){super({...e,content:[]}),this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&e.type==="remove"}};var Vn=class Gn extends ke{static lc_name(){return"SystemMessage"}type="system";constructor(t){super(t)}concat(t){if(typeof t=="string")return new Gn({content:Pe(this.content,t),additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata,id:this.id,name:this.name});if(Gn.isInstance(t))return new Gn({content:Pe(this.content,t.content),additional_kwargs:{...this.additional_kwargs,...t.additional_kwargs},response_metadata:{...this.response_metadata,...t.response_metadata},id:this.id??t.id,name:this.name??t.name});throw new Error("Unexpected chunk type for system message")}static isInstance(t){return super.isInstance(t)&&t.type==="system"}},Xc=class extends ze{static lc_name(){return"SystemMessageChunk"}type="system";constructor(e){super(e)}concat(e){let t=this.constructor;return new t({content:Pe(this.content,e.content),additional_kwargs:ce(this.additional_kwargs,e.additional_kwargs),response_metadata:ce(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="system"}};function M0(e){return e._getType()==="system"}function j0(e){return e._getType()==="system"}function rh(e){return e.isCustomTool===!0}var K0=e=>e();function nh(e){return Nt(e)?e:typeof e.id=="string"&&e.type==="function"&&typeof e.function=="object"&&e.function!==null&&"arguments"in e.function&&typeof e.function.arguments=="string"&&"name"in e.function&&typeof e.function.name=="string"?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function ih(e){return typeof e=="object"&&e!=null&&e.lc===1&&Array.isArray(e.id)&&e.kwargs!=null&&typeof e.kwargs=="object"}function Fa(e){let t,r;if(ih(e)){let n=e.id.at(-1);n==="HumanMessage"||n==="HumanMessageChunk"?t="user":n==="AIMessage"||n==="AIMessageChunk"?t="assistant":n==="SystemMessage"||n==="SystemMessageChunk"?t="system":n==="FunctionMessage"||n==="FunctionMessageChunk"?t="function":n==="ToolMessage"||n==="ToolMessageChunk"?t="tool":t="unknown",r=e.kwargs}else{let{type:n,...i}=e;t=n,r=i}if(t==="human"||t==="user")return new Xt(r);if(t==="ai"||t==="assistant"){let{tool_calls:n,...i}=r;if(!Array.isArray(n))return new Rr(r);let a=n.map(nh);return new Rr({...i,tool_calls:a})}else{if(t==="system")return new Vn(r);if(t==="developer")return new Vn({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if(t==="tool"&&"tool_call_id"in r)return new Yt({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});if(t==="remove"&&"id"in r&&typeof r.id=="string")return new Yc({...r,id:r.id});throw Da(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
|
|
14
|
+
|
|
15
|
+
Received: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Qc(e){if(typeof e=="string")return new Xt(e);if(vc(e))return e;if(Array.isArray(e)){let[t,r]=e;return Fa({type:t,content:r})}else if(bc(e)){let{role:t,...r}=e;return Fa({...r,type:t})}else return Fa(e)}function ah(e){if(typeof e=="string")return e;switch(e.type){case"text":return e.text??"";case"text-plain":return e.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 e.type?`[${e.type}]`:""}}function Zn(e,t="Human",r="AI"){let n=[];for(let i of e){let a;if(i.type==="human")a=t;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 s=i.name?`${i.name}, `:"",o=typeof i.content=="string"?i.content:Array.isArray(i.content)?i.content.map(ah).filter(Boolean).join(""):"",c=`${a}: ${s}${o}`;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(`
|
|
16
|
+
`)}function sh(e){if(e.data!==void 0)return e;{let t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}function Ha(e){let t=sh(e);switch(t.type){case"human":return new Xt(t.data);case"ai":return new Rr(t.data);case"system":return new Vn(t.data);case"function":if(t.data.name===void 0)throw new Error("Name must be defined for function messages");return new Wc(t.data);case"tool":if(t.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new Yt(t.data);case"generic":if(t.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Ba(t.data);default:throw new Error(`Got unexpected type: ${t.type}`)}}function Y0(e){return e.map(Ha)}function X0(e){return e.map(t=>t.toDict())}function Q0(e){let t=e._getType();if(t==="human")return new Kc({...e});if(t==="ai"){let r={...e};return"tool_calls"in r&&(r={...r,tool_call_chunks:r.tool_calls?.map(n=>({...n,type:"tool_call_chunk",index:void 0,args:JSON.stringify(n.args)}))}),new Nr({...r})}else{if(t==="system")return new Xc({...e});if(t==="function")return new Jc({...e});if(Ba.isInstance(e))return new qc({...e});throw new Error("Unknown message type.")}}function eu(e){let t=e.reduce((i,a)=>{let s=i.findIndex(([o])=>"id"in a&&a.id&&"index"in a&&a.index!==void 0?a.id===o.id&&a.index===o.index:"id"in a&&a.id?a.id===o.id:"index"in a&&a.index!==void 0?a.index===o.index:!1);return s!==-1?i[s].push(a):i.push([a]),i},[]),r=[],n=[];for(let i of t){let a=null,s=i.some(rh),o=i[0]?.name??"",c=i.map(f=>f.args||"").join(""),u=s?c:c.trim(),l=u.length?u:"{}",d=i.find(f=>f.id)?.id??i[0]?.id;if(s&&d){r.push({name:o,args:{input:u},id:d,type:"tool_call"});continue}try{if(a=za(l),!d||a===null||typeof a!="object"||Array.isArray(a))throw new Error("Malformed tool call chunk args.");r.push({name:o,args:a,id:d,type:"tool_call"})}catch{n.push({name:o,args:l,id:d,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:e,tool_calls:r,invalid_tool_calls:n}}var Rr=class extends ke{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(e){let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;let r=t.additional_kwargs?.tool_calls,n=t.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.
|
|
17
|
+
|
|
18
|
+
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]=Ma(r);t.tool_calls=i??[],t.invalid_tool_calls=a??[]}else t.tool_calls=t.tool_calls??[],t.invalid_tool_calls=t.invalid_tool_calls??[]}catch{t.tool_calls=[],t.invalid_tool_calls=[]}if(t.response_metadata!==void 0&&"output_version"in t.response_metadata&&t.response_metadata.output_version==="v1"&&t.content!==void 0&&(t.contentBlocks=t.content,t.content=void 0),t.contentBlocks!==void 0){if(t.tool_calls){let a=t.tool_calls.filter(s=>!t.contentBlocks?.some(o=>o.type==="tool_call"&&o.id===s.id&&o.name===s.name));t.contentBlocks.push(...a.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})))}let i=t.contentBlocks.filter(a=>a.type==="tool_call").filter(a=>!t.tool_calls?.some(s=>s.id===a.id&&s.name===a.name));i.length>0&&(t.tool_calls=[...t.tool_calls??[],...i.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args}))])}}super(t),typeof t!="string"&&(this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=t.usage_metadata}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 t=La(this.response_metadata.model_provider);if(t)return t.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls){let t=this.tool_calls.filter(r=>!e.some(n=>n.id===r.id&&n.name===r.name));e.push(...t.map(r=>({type:"tool_call",id:r.id,name:r.name,args:r.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};function sv(e){return e._getType()==="ai"}function ov(e){return e._getType()==="ai"}var Nr=class extends ze{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(e){let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{let r=eu(e.tool_call_chunks??[]);t={...e,tool_call_chunks:r.tool_call_chunks,tool_calls:r.tool_calls,invalid_tool_calls:r.invalid_tool_calls,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(t),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessageChunk"}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 t=La(this.response_metadata.model_provider);if(t)return t.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){let t=this.content.filter(r=>r.type==="tool_call").map(r=>r.id);for(let r of this.tool_calls)r.id&&!t.includes(r.id)&&e.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){let t={content:Pe(this.content,e.content),additional_kwargs:ce(this.additional_kwargs,e.additional_kwargs),response_metadata:zc(this.response_metadata,e.response_metadata),tool_call_chunks:[],tool_calls:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){let n=Cr(this.tool_call_chunks,e.tool_call_chunks);n!==void 0&&n.length>0&&(t.tool_call_chunks=n)}if(this.tool_calls!==void 0||e.tool_calls!==void 0){let n=Cr(this.tool_calls,e.tool_calls);n!==void 0&&n.length>0&&(t.tool_calls=n)}(this.usage_metadata!==void 0||e.usage_metadata!==void 0)&&(t.usage_metadata=Fn(this.usage_metadata,e.usage_metadata));let r=this.constructor;return new r(t)}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};var tu="ffffffff-ffff-ffff-ffff-ffffffffffff";var ru="00000000-0000-0000-0000-000000000000";var nu=/^(?:[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 $t(e){return typeof e=="string"&&nu.test(e)}function Qt(e){if(!$t(e))throw TypeError("Invalid UUID");let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var ye=[];for(let e=0;e<256;++e)ye.push((e+256).toString(16).slice(1));function Be(e,t=0){return(ye[e[t+0]]+ye[e[t+1]]+ye[e[t+2]]+ye[e[t+3]]+"-"+ye[e[t+4]]+ye[e[t+5]]+"-"+ye[e[t+6]]+ye[e[t+7]]+"-"+ye[e[t+8]]+ye[e[t+9]]+"-"+ye[e[t+10]]+ye[e[t+11]]+ye[e[t+12]]+ye[e[t+13]]+ye[e[t+14]]+ye[e[t+15]]).toLowerCase()}function iu(e,t=0){let r=Be(e,t);if(!$t(r))throw TypeError("Stringified UUID is invalid");return r}var oh=new Uint8Array(16);function Pt(){return crypto.getRandomValues(oh)}var on={};function qn(e,t,r){let n,i=e?._v6??!1;if(e){let a=Object.keys(e);a.length===1&&a[0]==="_v6"&&(e=void 0)}if(e)n=au(e.random??e.rng?.()??Pt(),e.msecs,e.nsecs,e.clockseq,e.node,t,r);else{let a=Date.now(),s=Pt();ch(on,a,s),n=au(s,on.msecs,on.nsecs,i?void 0:on.clockseq,i?void 0:on.node,t,r)}return t??Be(n)}function ch(e,t,r){return e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0),e.node||(e.node=r.slice(10,16),e.node[0]|=1,e.clockseq=(r[8]<<8|r[9])&16383),e.msecs=t,e}function au(e,t,r,n,i,a,s=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(!a)a=new Uint8Array(16),s=0;else if(s<0||s+16>a.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);t??=Date.now(),r??=0,n??=(e[8]<<8|e[9])&16383,i??=e.slice(10,16),t+=122192928e5;let o=((t&268435455)*1e4+r)%4294967296;a[s++]=o>>>24&255,a[s++]=o>>>16&255,a[s++]=o>>>8&255,a[s++]=o&255;let c=t/4294967296*1e4&268435455;a[s++]=c>>>8&255,a[s++]=c&255,a[s++]=c>>>24&15|16,a[s++]=c>>>16&255,a[s++]=n>>>8|128,a[s++]=n&255;for(let u=0;u<6;++u)a[s++]=i[u];return a}function su(e,t,r){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():uh(e,t,r)}function uh(e,t,r){e=e||{};let n=e.random??e.rng?.()??Pt();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,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[r+i]=n[i];return t}return Be(n)}function lh(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:return t^r^n;case 2:return t&r^t&n^r&n;case 3:return t^r^n}}function Ga(e,t){return e<<t|e>>>32-t}function ou(e){let t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(e.length+1);n.set(e),n[e.length]=128,e=n;let i=e.length/4+2,a=Math.ceil(i/16),s=new Array(a);for(let o=0;o<a;++o){let c=new Uint32Array(16);for(let u=0;u<16;++u)c[u]=e[o*64+u*4]<<24|e[o*64+u*4+1]<<16|e[o*64+u*4+2]<<8|e[o*64+u*4+3];s[o]=c}s[a-1][14]=(e.length-1)*8/2**32,s[a-1][14]=Math.floor(s[a-1][14]),s[a-1][15]=(e.length-1)*8&4294967295;for(let o=0;o<a;++o){let c=new Uint32Array(80);for(let h=0;h<16;++h)c[h]=s[o][h];for(let h=16;h<80;++h)c[h]=Ga(c[h-3]^c[h-8]^c[h-14]^c[h-16],1);let u=r[0],l=r[1],d=r[2],f=r[3],p=r[4];for(let h=0;h<80;++h){let m=Math.floor(h/20),b=Ga(u,5)+lh(m,l,d,f)+p+t[m]+c[h]>>>0;p=f,f=d,d=Ga(l,30)>>>0,l=u,u=b}r[0]=r[0]+u>>>0,r[1]=r[1]+l>>>0,r[2]=r[2]+d>>>0,r[3]=r[3]+f>>>0,r[4]=r[4]+p>>>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])}function dh(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}var cu="6ba7b810-9dad-11d1-80b4-00c04fd430c8",uu="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function lu(e,t,r,n,i,a){let s=typeof r=="string"?dh(r):r,o=typeof n=="string"?Qt(n):n;if(typeof n=="string"&&(n=Qt(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+s.length);if(c.set(o),c.set(s,o.length),c=t(c),c[6]=c[6]&15|e,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 Be(c)}function Wn(e,t,r,n){return lu(80,ou,e,t,r,n)}Wn.DNS=cu;Wn.URL=uu;function du(e){let t=fh(typeof e=="string"?Qt(e):e);return typeof e=="string"?Be(t):t}function fh(e){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function fu(e,t,r){e??={},r??=0;let n=qn({...e,_v6:!0},new Uint8Array(16));if(n=du(n),t){if(r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;i++)t[r+i]=n[i];return t}return Be(n)}var Va={};function hu(e,t,r){let n;if(e)n=pu(e.random??e.rng?.()??Pt(),e.msecs,e.seq,t,r);else{let i=Date.now(),a=Pt();ph(Va,i,a),n=pu(a,Va.msecs,Va.seq,t,r)}return t??Be(n)}function ph(e,t,r){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}function pu(e,t,r,n,i=0){if(e.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 t??=Date.now(),r??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],n[i++]=t/1099511627776&255,n[i++]=t/4294967296&255,n[i++]=t/16777216&255,n[i++]=t/65536&255,n[i++]=t/256&255,n[i++]=t&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|e[10]&3,n[i++]=e[11],n[i++]=e[12],n[i++]=e[13],n[i++]=e[14],n[i++]=e[15],n}function mu(e){if(!$t(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)}var ix=L({MAX:()=>hh,NIL:()=>mh,parse:()=>gh,stringify:()=>_h,v1:()=>yh,v4:()=>Za,v5:()=>wh,v6:()=>bh,v7:()=>Ge,validate:()=>$r,version:()=>vh}),hh=tu,mh=ru,gh=Qt,_h=iu,yh=qn,Za=su,wh=Wn,bh=fu,Ge=hu,$r=$t,vh=mu;var ox=L({getEnv:()=>bu,getEnvironmentVariable:()=>Qe,getRuntimeEnvironment:()=>Wa,isBrowser:()=>gu,isDeno:()=>Jn,isJsDom:()=>yu,isNode:()=>wu,isWebWorker:()=>_u}),gu=()=>typeof window<"u"&&typeof window.document<"u",_u=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",yu=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Jn=()=>typeof Deno<"u",wu=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Jn(),bu=()=>{let e;return gu()?e="browser":wu()?e="node":_u()?e="webworker":yu()?e="jsdom":Jn()?e="deno":e="other",e},qa;function Wa(){return qa===void 0&&(qa={library:"langchain-js",runtime:bu()}),qa}function Qe(e){try{return typeof process<"u"?process.env?.[e]:Jn()?Deno?.env.get(e):void 0}catch{return}}var px=L({BaseCallbackHandler:()=>er,callbackHandlerPrefersChatModelStreamEvents:()=>Sh,callbackHandlerPrefersStreaming:()=>Eh,isBaseCallbackHandler:()=>Ja}),xh=class{};function Eh(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}function Sh(e){return"lc_prefer_chat_model_stream_events"in e&&e.lc_prefer_chat_model_stream_events}var er=class extends xh{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,Un(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Qe("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(e){super(),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return ft.prototype.toJSON.call(this)}toJSONNotImplemented(){return ft.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends er{name=Ge();constructor(){super(),Object.assign(this,e)}}return new t}},Ja=e=>{let t=e;return t!==void 0&&typeof t.copy=="function"&&typeof t.name=="string"&&typeof t.awaitHandlers=="boolean"};var vu=/^(?:[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 Th(e){return typeof e=="string"&&vu.test(e)}var cn=Th;function Ah(e){if(!cn(e))throw TypeError("Invalid UUID");let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var Kn=Ah;var we=[];for(let e=0;e<256;++e)we.push((e+256).toString(16).slice(1));function Pr(e,t=0){return(we[e[t+0]]+we[e[t+1]]+we[e[t+2]]+we[e[t+3]]+"-"+we[e[t+4]]+we[e[t+5]]+"-"+we[e[t+6]]+we[e[t+7]]+"-"+we[e[t+8]]+we[e[t+9]]+"-"+we[e[t+10]]+we[e[t+11]]+we[e[t+12]]+we[e[t+13]]+we[e[t+14]]+we[e[t+15]]).toLowerCase()}var kh=new Uint8Array(16);function Mr(){return crypto.getRandomValues(kh)}function Ih(e,t,r){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():Ch(e,t,r)}function Ch(e,t,r){e=e||{};let n=e.random??e.rng?.()??Mr();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,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[r+i]=n[i];return t}return Pr(n)}var tr=Ih;function Oh(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:return t^r^n;case 2:return t&r^t&n^r&n;case 3:return t^r^n}}function Ka(e,t){return e<<t|e>>>32-t}function Rh(e){let t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(e.length+1);n.set(e),n[e.length]=128,e=n;let i=e.length/4+2,a=Math.ceil(i/16),s=new Array(a);for(let o=0;o<a;++o){let c=new Uint32Array(16);for(let u=0;u<16;++u)c[u]=e[o*64+u*4]<<24|e[o*64+u*4+1]<<16|e[o*64+u*4+2]<<8|e[o*64+u*4+3];s[o]=c}s[a-1][14]=(e.length-1)*8/2**32,s[a-1][14]=Math.floor(s[a-1][14]),s[a-1][15]=(e.length-1)*8&4294967295;for(let o=0;o<a;++o){let c=new Uint32Array(80);for(let h=0;h<16;++h)c[h]=s[o][h];for(let h=16;h<80;++h)c[h]=Ka(c[h-3]^c[h-8]^c[h-14]^c[h-16],1);let u=r[0],l=r[1],d=r[2],f=r[3],p=r[4];for(let h=0;h<80;++h){let m=Math.floor(h/20),b=Ka(u,5)+Oh(m,l,d,f)+p+t[m]+c[h]>>>0;p=f,f=d,d=Ka(l,30)>>>0,l=u,u=b}r[0]=r[0]+u>>>0,r[1]=r[1]+l>>>0,r[2]=r[2]+d>>>0,r[3]=r[3]+f>>>0,r[4]=r[4]+p>>>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])}var xu=Rh;function Nh(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}var Ya="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Xa="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Qa(e,t,r,n,i,a){let s=typeof r=="string"?Nh(r):r,o=typeof n=="string"?Kn(n):n;if(typeof n=="string"&&(n=Kn(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+s.length);if(c.set(o),c.set(s,o.length),c=t(c),c[6]=c[6]&15|e,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 Pr(c)}function es(e,t,r,n){return Qa(80,xu,e,t,r,n)}es.DNS=Ya;es.URL=Xa;var ts=es;var rs={};function $h(e,t,r){let n;if(e)n=Eu(e.random??e.rng?.()??Mr(),e.msecs,e.seq,t,r);else{let i=Date.now(),a=Mr();Ph(rs,i,a),n=Eu(a,rs.msecs,rs.seq,t,r)}return t??Pr(n)}function Ph(e,t,r){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}function Eu(e,t,r,n,i=0){if(e.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 t??=Date.now(),r??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],n[i++]=t/1099511627776&255,n[i++]=t/4294967296&255,n[i++]=t/16777216&255,n[i++]=t/65536&255,n[i++]=t/256&255,n[i++]=t&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|e[10]&3,n[i++]=e[11],n[i++]=e[12],n[i++]=e[13],n[i++]=e[14],n[i++]=e[15],n}var jr=$h;var Su="gen_ai.operation.name",Tu="gen_ai.system",ns="gen_ai.request.model",Au="gen_ai.response.model",is="gen_ai.usage.input_tokens",as="gen_ai.usage.output_tokens",ss="gen_ai.usage.total_tokens",ku="gen_ai.request.max_tokens",Iu="gen_ai.request.temperature",Cu="gen_ai.request.top_p",Ou="gen_ai.request.frequency_penalty",Ru="gen_ai.request.presence_penalty",Nu="gen_ai.response.finish_reasons",$u="gen_ai.prompt",Pu="gen_ai.completion",Mu="gen_ai.request.extra_query",ju="gen_ai.request.extra_body",Lu="gen_ai.serialized.name",Du="gen_ai.serialized.signature",Uu="gen_ai.serialized.doc",zu="gen_ai.response.id",Bu="gen_ai.response.service_tier",Fu="gen_ai.response.system_fingerprint",Hu="gen_ai.usage.input_token_details",Gu="gen_ai.usage.output_token_details",Vu="langsmith.trace.session_id",Zu="langsmith.trace.session_name",qu="langsmith.span.kind",Wu="langsmith.trace.name",Ju="langsmith.metadata",os="langsmith.span.tags";var Ku="langsmith.request.streaming",Yu="langsmith.request.headers";var cs="langsmith.usage_metadata";var Lh=(...e)=>fetch(...e),Dh,Xu=Symbol.for("ls:fetch_implementation");var Qu=()=>globalThis[Xu]===void 0?!0:Dh??!1,el=e=>async(...t)=>{if(e||ne("DEBUG")==="true"){let[n,i]=t;console.log(`\u2192 ${i?.method||"GET"} ${n}`)}let r=await(globalThis[Xu]??Lh)(...t);return(e||ne("DEBUG")==="true")&&console.log(`\u2190 ${r.status} ${r.statusText} ${r.url}`),r};var un=()=>ne("PROJECT")??pe("LANGCHAIN_SESSION")??"default";var tl={};function rr(e){tl[e]||(console.warn(e),tl[e]=!0)}var _=e=>BigInt(e),al=_("0x9E3779B1"),sl=_("0x85EBCA77"),Uh=_("0xC2B2AE3D"),Mt=_("0x9E3779B185EBCA87"),nr=_("0xC2B2AE3D27D4EB4F"),ol=_("0x165667B19E3779F9"),fs=_("0x85EBCA77C2B2AE63"),zh=_("0x27D4EB2F165667C5"),Bh=_("0x165667919E3779F9"),Fh=_("0x9FB21C651E98DF25");function Hh(e){let t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.substring(r,r+2),16);return t}var pt=Hh("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Dr=(_(1)<<_(128))-_(1),Z=(_(1)<<_(64))-_(1),ei=(_(1)<<_(32))-_(1),At=64,cl=At/8,Gh=8,Yn=4;function te(e,t=0){return new Uint8Array(e.buffer,e.byteOffset+t,e.length-t)}function ie(e,t=0){return new DataView(e.buffer,e.byteOffset+t).getBigUint64(0,!0)}function Lr(e,t=0){return new DataView(e.buffer,e.byteOffset+t).getUint32(0,!0)}function us(e,t=0){return e[t]}var Vh=e=>(e&_(255))<<_(56)|(e&_(65280))<<_(40)|(e&_(16711680))<<_(24)|(e&_(4278190080))<<_(8)|(e&_(0xff00000000))>>_(8)|(e&_(0xff0000000000))>>_(24)|(e&_(0xff000000000000))>>_(40)|(e&_(0xff00000000000000))>>_(56),Zh=e=>(e=(e&_(65535))<<_(16)|(e&_(4294901760))>>_(16),e=(e&_(16711935))<<_(8)|(e&_(4278255360))>>_(8),e),qh=(e,t)=>(e&ei)*(t&ei)&Z,Ur=e=>{if(!e)throw new Error("Assert failed")};function Wh(e,t){return(e<<t|e>>_(32)-t)&ei}function ul(e,t,r){for(let n=0;n<cl;n++){let i=ie(t,n*8),a=i^ie(r,n*8);e[n^1]+=i,e[n]+=qh(a,a>>_(32))}return e}function rl(e,t,r,n){for(let i=0;i<n;i++)ul(e,te(t,i*At),te(r,i*8));return e}function Jh(e,t){for(let r=0;r<cl;r++){let n=ie(t,r*8),i=e[r];i=ls(i,_(47)),i^=n,i*=al,e[r]=i&Z}return e}function Xn(e,t){return ll(e[0]^ie(t,0),e[1]^ie(t,Gh))}function nl(e,t,r){let n=r;return n+=Xn(e.slice(0),te(t,0*Yn)),n+=Xn(e.slice(2),te(t,4*Yn)),n+=Xn(e.slice(4),te(t,8*Yn)),n+=Xn(e.slice(6),te(t,12*Yn)),ht(n&Z)}function Kh(e,t,r,n,i){let a=Math.floor((r.byteLength-At)/8),s=At*a,o=Math.floor((t.byteLength-1)/s);for(let c=0;c<o;c++)e=rl(e,te(t,c*s),r,a),e=i(e,te(r,r.byteLength-At));{let c=Math.floor((t.byteLength-1-s*o)/At);e=rl(e,te(t,o*s),r,c),e=n(e,te(t,t.byteLength-At),te(r,r.byteLength-At-7))}return e}function Yh(e,t,r){let n=new BigUint64Array([Uh,Mt,nr,ol,fs,sl,zh,al]);Ur(e.length>128),n=Kh(n,e,t,ul,Jh),Ur(n.length*8==64);{let i=nl(n,te(t,11),_(e.byteLength)*Mt&Z);return nl(n,te(t,t.byteLength-At-11),~(_(e.byteLength)*nr)&Z)<<_(64)|i}}function ll(e,t){let r=e*t&Dr;return r&Z^r>>_(64)}function il(e,t,r){return ll((ie(e,0)^ie(t,0)+r)&Z,(ie(e,8)^ie(t,8)-r)&Z)}function Qn(e,t,r,n,i){let a=e&Z,s=e>>_(64)&Z;return a+=il(t,n,i),a^=ie(r,0)+ie(r,8),a&=Z,s+=il(r,te(n,16),i),s^=ie(t,0)+ie(t,8),s&=Z,s<<_(64)|a}function ht(e){return e^=e>>_(37),e*=Bh,e&=Z,e^=e>>_(32),e}function ti(e){return e^=e>>_(33),e*=nr,e&=Z,e^=e>>_(29),e*=ol,e&=Z,e^=e>>_(32),e}function Xh(e,t,r){let n=e.byteLength;Ur(n>0&&n<=3);let i=_(us(e,n-1))|_(n<<8)|_(us(e,0)<<16)|_(us(e,n>>1)<<24),a=(_(Lr(t,0))^_(Lr(t,4)))+r,s=(i^a)&Z,o=(_(Lr(t,8))^_(Lr(t,12)))-r,c=(Wh(Zh(i),_(13))^o)&Z;return(ti(c)&Z)<<_(64)|ti(s)}function ls(e,t){return e^e>>t}function Qh(e,t,r){let n=e.byteLength;Ur(n>=4&&n<=8);{let i=Lr(e,0),a=Lr(e,n-4),s=_(i)|_(a)<<_(32),o=(ie(t,16)^ie(t,24))+r&Z,u=(s^o)*(Mt+(_(n)<<_(2)))&Dr;return u+=(u&Z)<<_(65),u&=Dr,u^=u>>_(67),ls(ls(u&Z,_(35))*Fh&Z,_(28))|ht(u>>_(64))<<_(64)}}function em(e,t,r){let n=e.byteLength;Ur(n>=9&&n<=16);{let i=(ie(t,32)^ie(t,40))+r&Z,a=(ie(t,48)^ie(t,56))-r&Z,s=ie(e),o=ie(e,n-8),c=(s^o^i)*Mt,u=(c&Z)+(_(n-1)<<_(54));c=c&(Dr^Z)|u,o^=a,c+=o+(o&ei)*(sl-_(1))<<_(64),c&=Dr,c^=Vh(c>>_(64));let l=(c&Z)*nr;return l+=(c>>_(64))*nr<<_(64),l&=Dr,ht(l&Z)|ht(l>>_(64))<<_(64)}}function tm(e,t){let r=e.byteLength;return Ur(r<=16),r>8?em(e,pt,t):r>=4?Qh(e,pt,t):r>0?Xh(e,pt,t):ti(t^ie(pt,64)^ie(pt,72))|ti(t^ie(pt,80)^ie(pt,88))<<_(64)}function ds(e){return~e+_(1)&Z}function rm(e,t,r){let n=_(e.byteLength)*Mt&Z,i=_(e.byteLength-1)/_(32);for(;i>=0;){let o=Number(i);n=Qn(n,te(e,16*o),te(e,e.byteLength-16*(o+1)),te(t,32*o),r),i--}let a=n+(n>>_(64))&Z;a=ht(a);let s=(n&Z)*Mt+(n>>_(64))*fs+(_(e.byteLength)-r&Z)*nr;return s&=Z,s=ds(ht(s)),a|s<<_(64)}function nm(e,t,r){let n=_(e.byteLength)*Mt&Z;for(let s=32;s<160;s+=32)n=Qn(n,te(e,s-32),te(e,s-16),te(t,s-32),r);n=ht(n&Z)|ht(n>>_(64))<<_(64);for(let s=160;s<=e.byteLength;s+=32)n=Qn(n,te(e,s-32),te(e,s-16),te(t,3+s-160),r);n=Qn(n,te(e,e.byteLength-16),te(e,e.byteLength-32),te(t,103),ds(r));let i=n+(n>>_(64))&Z;i=ht(i);let a=(n&Z)*Mt+(n>>_(64))*fs+(_(e.byteLength)-r&Z)*nr;return a&=Z,a=ds(ht(a)),i|a<<_(64)}function dl(e,t=_(0)){let r=e.byteLength;return r<=16?tm(e,t):r<=128?rm(e,pt,t):r<=240?nm(e,pt,t):Yh(e,pt,t)}function fl(e){let t=new Uint8Array(16),r=new DataView(t.buffer),n=e&Z,i=e>>_(64);return r.setBigUint64(0,i,!1),r.setBigUint64(8,n,!1),t}var pl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function G(e,t){if(!pl.test(e)){let r=t!==void 0?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`;throw new Error(r)}return e}function ri(e){let t=typeof e=="string"?Date.parse(e):e;return jr({msecs:t,seq:0})}function im(e){if(!pl.test(e))return null;let t=e[14];return parseInt(t,16)}function am(e){let t=e.replace(/-/g,""),r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(t.slice(n*2,n*2+2),16);return r}function sm(e){let t=Array.from(e).map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var om=new TextEncoder;function cm(e){let t=om.encode(e),r=dl(t);return fl(r)}function ln(e,t){let r=`${e}:${t}`,n=cm(r),i=new Uint8Array(16);if(im(e)===7){let s=am(e);i.set(s.slice(0,6),0)}else{let s=Date.now();i[0]=s/1099511627776&255,i[1]=s/4294967296&255,i[2]=s/16777216&255,i[3]=s/65536&255,i[4]=s/256&255,i[5]=s&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),sm(i)}var ir={join:(...e)=>e.join("/"),dirname:e=>e.split("/").slice(0,-1).join("/")};async function hl(e){}async function ni(e,t){}async function ml(e){return[]}async function gl(e){return{size:0}}function zr(e){return!1}function ii(e){return""}function um(e,t){return t===null?!1:Date.now()-e.createdAt>t*1e3}var ai=class{constructor(t={}){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(t)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let t=this.totalRequests;return t>0?this._metrics.hits/t:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(t,r){if(this.maxSize===0)return;let n=this.cache.get(t);if(!n){this._metrics.misses+=1;return}return this.cache.delete(t),this.cache.set(t,{...n,refreshFunc:r}),this._metrics.hits+=1,n.value}set(t,r,n){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(t)&&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(t),this.cache.set(t,i)}invalidate(t){this.cache.delete(t)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(t){let r={};for(let[a,s]of this.cache.entries())r[a]=s.value;let n=ir.dirname(t);zr(n)||void 0;let i=`${t}.tmp`;try{JSON.stringify({entries:r},null,2)}catch(a){throw zr(i)&&void 0,a}}load(t){if(!zr(t))return 0;let r;try{let a=ii(t);r=JSON.parse(a).entries??null}catch{return 0}if(!r)return 0;let n=0,i=Date.now();for(let[a,s]of Object.entries(r)){if(this.cache.size>=this.maxSize)break;let o={value:s,createdAt:i};this.cache.set(a,o),n+=1}return n}startRefreshLoop(){this.stop(),this.ttlSeconds!==null&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(t=>{console.warn("Unexpected error in cache refresh loop:",t)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){let t=[];for(let[r,n]of this.cache.entries())um(n,this.ttlSeconds)&&t.push([r,n]);return t}async refreshStaleEntries(){let t=this.getStaleEntries();if(t.length!==0){for(let[r,n]of t)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(t){this.stop(),this.refreshIntervalSeconds=t.refreshIntervalSeconds??60,this.maxSize=t.maxSize??100,this.ttlSeconds=t.ttlSeconds??300}},si=new ai;var oi="0.6.3";var mt,lm=()=>typeof window<"u"&&typeof window.document<"u",dm=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",fm=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),bl=()=>typeof Deno<"u",pm=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!bl(),dn=()=>mt||(typeof Bun<"u"?mt="bun":lm()?mt="browser":pm()?mt="node":dm()?mt="webworker":fm()?mt="jsdom":bl()?mt="deno":mt="other",mt),ps;function ci(){if(ps===void 0){let e=dn(),t=mm();ps={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:oi,...t}}return ps}function ms(){let e=hm(),t={},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(e))typeof i=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?t.revision_id=i:t[n]=i);return t}function hm(){let e={};try{if(typeof process<"u"&&process.env)for(let[t,r]of Object.entries(process.env))(t.startsWith("LANGCHAIN_")||t.startsWith("LANGSMITH_"))&&r!=null&&((t.toLowerCase().includes("key")||t.toLowerCase().includes("secret")||t.toLowerCase().includes("token"))&&typeof r=="string"?e[t]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):e[t]=r)}catch{}return e}function pe(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function ne(e){return pe(`LANGSMITH_${e}`)||pe(`LANGCHAIN_${e}`)}var hs;function mm(){if(hs!==void 0)return hs;let e=["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"],t={};for(let r of e){let n=pe(r);n!==void 0&&(t[r]=n)}return hs=t,t}function yl(){return pe("OTEL_ENABLED")==="true"||ne("OTEL_ENABLED")==="true"}var wl=new Set(["langsmith","otel"]);function ui(e){if(e!==void 0)return e;let t=ne("TRACING_MODE");if(t!==void 0&&t!==""){let r=t.toLowerCase();if(!wl.has(r))throw new Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(t)}. Must be one of: ${[...wl].sort().join(", ")}`);return yl()&&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 yl()?"otel":"langsmith"}var ys=class{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(t,...r){!this.hasWarned&&ui()==="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()}},ws=class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new ys})}getTracer(t,r){return this.mockTracer}getActiveSpan(){}setSpan(t,r){return t}getSpan(t){}setSpanContext(t,r){return t}getTracerProvider(){}setGlobalTracerProvider(t){return!1}},bs=class{active(){return{}}with(t,r){return r()}},gs=Symbol.for("ls:otel_trace"),_s=Symbol.for("ls:otel_context"),vl=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),gm=new ws,_m=new bs,vs=class{getTraceInstance(){return globalThis[gs]??gm}getContextInstance(){return globalThis[_s]??_m}initializeGlobalInstances(t){globalThis[gs]===void 0&&(globalThis[gs]=t.trace),globalThis[_s]===void 0&&(globalThis[_s]=t.context)}setDefaultOTLPTracerComponents(t){globalThis[vl]=t}getDefaultOTLPTracerComponents(){return globalThis[vl]??void 0}},xs=new vs;function li(){return xs.getTraceInstance()}function xl(){return xs.getContextInstance()}function El(){return xs.getDefaultOTLPTracerComponents()}var ym={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function wm(e){return ym[e]||e}function bm(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}var di=class{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(t,r){for(let n of t)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(t,r,n){let i=n&&li().getSpan(n);if(i)try{return this.finishSpanSetup(i,r,t)}catch(a){console.error(`Failed to create span for run ${t.id}:`,a);return}}finishSpanSetup(t,r,n){return this.setSpanAttributes(t,r,n),r.error?(t.setStatus({code:2}),t.recordException(new Error(r.error))):t.setStatus({code:1}),r.end_time&&t.end(new Date(r.end_time)),t}updateSpanForRun(t,r){try{let n=this.spans.get(t.id);if(!n){console.debug(`No span found for run ${t.id} during update`);return}this.setSpanAttributes(n,r,t),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(t.id))}catch(n){console.error(`Failed to update span for run ${t.id}:`,n)}}extractModelName(t){if(t.extra?.metadata){let r=t.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(t,r,n){if("run_type"in r&&r.run_type){t.setAttribute(qu,r.run_type);let o=wm(r.run_type||"chain");t.setAttribute(Su,o)}"name"in r&&r.name&&t.setAttribute(Wu,r.name),"session_id"in r&&r.session_id&&t.setAttribute(Vu,r.session_id),"session_name"in r&&r.session_name&&t.setAttribute(Zu,r.session_name),this.setGenAiSystem(t,r);let i=this.extractModelName(r);i&&t.setAttribute(ns,i),r.extra?.metadata?.usage_metadata&&typeof r.extra.metadata.usage_metadata=="object"&&t.setAttribute(cs,JSON.stringify(r.extra.metadata.usage_metadata)),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&t.setAttribute(is,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&t.setAttribute(as,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&t.setAttribute(ss,r.total_tokens),this.setInvocationParameters(t,r);let a=r.extra?.metadata||{};for(let[o,c]of Object.entries(a))c!=null&&t.setAttribute(`${Ju}.${o}`,bm(c)?String(c):JSON.stringify(c));let s=r.tags;if(s&&Array.isArray(s)?t.setAttribute(os,s.join(", ")):s&&t.setAttribute(os,String(s)),"serialized"in r&&typeof r.serialized=="object"){let o=r.serialized;o.name&&t.setAttribute(Lu,String(o.name)),o.signature&&t.setAttribute(Du,String(o.signature)),o.doc&&t.setAttribute(Uu,String(o.doc))}this.setIOAttributes(t,n)}setGenAiSystem(t,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")}t.setAttribute(Tu,n)}setInvocationParameters(t,r){if(!r.extra?.metadata?.invocation_params)return;let n=r.extra.metadata.invocation_params;n.max_tokens!==void 0&&t.setAttribute(ku,n.max_tokens),n.temperature!==void 0&&t.setAttribute(Iu,n.temperature),n.top_p!==void 0&&t.setAttribute(Cu,n.top_p),n.frequency_penalty!==void 0&&t.setAttribute(Ou,n.frequency_penalty),n.presence_penalty!==void 0&&t.setAttribute(Ru,n.presence_penalty)}setIOAttributes(t,r){if(r.run.inputs)try{let n=r.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&t.setAttribute(ns,n.model),n.stream!==void 0&&t.setAttribute(Ku,n.stream),n.extra_headers&&t.setAttribute(Yu,JSON.stringify(n.extra_headers)),n.extra_query&&t.setAttribute(Mu,JSON.stringify(n.extra_query)),n.extra_body&&t.setAttribute(ju,JSON.stringify(n.extra_body))),t.setAttribute($u,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&&(t.setAttribute(is,i[0]),t.setAttribute(as,i[1]),t.setAttribute(ss,i[0]+i[1])),n&&typeof n=="object"){if(n.model&&t.setAttribute(Au,String(n.model)),n.id&&t.setAttribute(zu,n.id),n.choices&&Array.isArray(n.choices)){let a=n.choices.map(s=>s.finish_reason).filter(s=>s).map(String);a.length>0&&t.setAttribute(Nu,a.join(", "))}if(n.service_tier&&t.setAttribute(Bu,n.service_tier),n.system_fingerprint&&t.setAttribute(Fu,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let a=n.usage_metadata;t.setAttribute(cs,JSON.stringify(a)),a.input_token_details&&t.setAttribute(Hu,JSON.stringify(a.input_token_details)),a.output_token_details&&t.setAttribute(Gu,JSON.stringify(a.output_token_details))}}t.setAttribute(Pu,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${r.id}`,n)}}getUnifiedRunTokens(t){if(!t)return null;let r=this.extractUnifiedRunTokens(t.usage_metadata);if(r)return r;let n=Object.keys(t);for(let s of n){let o=t[s];if(!(!o||typeof o!="object")&&(r=this.extractUnifiedRunTokens(o.usage_metadata),r||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(r=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),r)))return r}let i=t.generations||[];if(!Array.isArray(i))return null;let a=Array.isArray(i[0])?i.flat():i;for(let s of a)if(typeof s=="object"&&s.message&&typeof s.message=="object"&&s.message.kwargs&&typeof s.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(s.message.kwargs.usage_metadata),r))return r;return null}extractUnifiedRunTokens(t){return!t||typeof t!="object"||typeof t.input_tokens!="number"||typeof t.output_tokens!="number"?null:[t.input_tokens,t.output_tokens]}};var vm=Object.prototype.toString,xm=e=>vm.call(e)==="[object Error]",Em=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 Es(e){if(!(e&&xm(e)&&e.name==="TypeError"&&typeof e.message=="string"))return!1;let{message:r,stack:n}=e;return r==="Load failed"?n===void 0||"__sentry_captured__"in e:r.startsWith("error sending request for url")?!0:Em.has(r)}function Sm(e){if(typeof e=="number"){if(e<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function fi(e,t,{min:r=0,allowInfinity:n=!1}={}){if(t!==void 0){if(typeof t!="number"||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<r)throw new TypeError(`Expected \`${e}\` to be \u2265 ${r}.`)}}var Ss=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}};function Tm(e,t){let r=Math.max(1,e+1),n=t.randomize?Math.random()+1:1,i=Math.round(n*t.minTimeout*t.factor**(r-1));return i=Math.min(i,t.maxTimeout),i}function Sl(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function Am({error:e,attemptNumber:t,retriesConsumed:r,startTime:n,options:i}){let a=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(a instanceof Ss)throw a.originalError;let s=Number.isFinite(i.retries)?Math.max(0,i.retries-r):i.retries,o=i.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:a,attemptNumber:t,retriesLeft:s,retriesConsumed:r});if(await i.onFailedAttempt(c),Sl(n,o)<=0)throw a;let u=await i.shouldConsumeRetry(c),l=Sl(n,o);if(l<=0||s<=0)throw a;if(a instanceof TypeError&&!Es(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 d=Tm(r,i),f=Math.min(d,l);return f>0&&await new Promise((p,h)=>{let m=()=>{clearTimeout(b),i.signal?.removeEventListener("abort",m),h(i.signal.reason)},b=setTimeout(()=>{i.signal?.removeEventListener("abort",m),p()},f);i.unref&&b.unref?.(),i.signal?.addEventListener("abort",m,{once:!0})}),i.signal?.throwIfAborted(),!0}async function Ts(e,t={}){if(t={...t},Sm(t.retries),Object.hasOwn(t,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=Number.POSITIVE_INFINITY,t.maxRetryTime??=Number.POSITIVE_INFINITY,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,fi("factor",t.factor,{min:0,allowInfinity:!1}),fi("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),fi("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),fi("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let r=0,n=0,i=performance.now();for(;!Number.isFinite(t.retries)||n<=t.retries;){r++;try{t.signal?.throwIfAborted();let a=await e(r);return t.signal?.throwIfAborted(),a}catch(a){await Am({error:a,attemptNumber:r,retriesConsumed:n,startTime:i,options:t})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var yi=jn(_i(),1),Pl="default"in yi.default?yi.default.default:yi.default;var Mm=[408,425,429,500,502,503,504],pn=class{constructor(t){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=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.maxQueueSizeBytes=t.maxQueueSizeBytes,this.queue=new Pl({concurrency:this.maxConcurrency}),this.onFailedResponseHook=t?.onFailedResponseHook}call(t,...r){return this.callWithOptions({},t,...r)}callWithOptions(t,r,...n){let i=t.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,s=this.queue.add(()=>Ts(()=>r(...n).catch(o=>{throw o instanceof Error?o:new Error(o)}),{async onFailedAttempt({error:o}){if(typeof o!="object"||o==null)throw o;let c="message"in o&&typeof o.message=="string"?o.message:void 0;if(c?.startsWith("Cancel")||c?.startsWith("TimeoutError")||c?.startsWith("AbortError")||"name"in o&&o.name==="TimeoutError"||"code"in o&&o.code==="ECONNABORTED")throw o;let u="response"in o?o.response:void 0;if(a&&await a(u))return;let l=u?.status??("status"in o?o.status:void 0);if(l!=null&&(typeof l=="number"||typeof l=="string")&&!Mm.includes(+l))throw o},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return i>0&&(s=s.finally(()=>{this.queueSizeBytes-=i})),t.signal?Promise.race([s,new Promise((o,c)=>{t.signal?.addEventListener("abort",()=>{c(new Error("AbortError"))})})]):s}};function Ns(e){return typeof e?._getType=="function"}function $s(e){let t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}function bi(e){return`Invalid prompt identifier format: "${e}". Expected one of:
|
|
19
|
+
- "prompt-name" (for private prompts)
|
|
20
|
+
- "owner/prompt-name" (for prompts with explicit owner)
|
|
21
|
+
- "prompt-name:commit-hash" (with commit reference)
|
|
22
|
+
- "owner/prompt-name:commit-hash" (with owner and commit)`}var Ps=class extends Error{constructor(t){super(t),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}},Ms=class extends Error{constructor(t){super(t),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}};function vi(e){return e!=null&&typeof e=="object"&&"name"in e&&e?.name==="LangSmithNotFoundError"}function Ml(e){return e!=null&&typeof e=="object"&&"name"in e&&e?.name==="LangSmithConflictError"}async function O(e,t,r){let n;if(e.ok){r&&(n=await e.text());return}if(e.status===403)try{(await e.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 o=new Error(`${e.status} ${e.statusText}`);throw o.status=e?.status,o}if(n===void 0)try{n=await e.text()}catch{n=""}let i=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Message: ${n}`;if(e.status===404)throw new Ms(i);if(e.status===409)throw new Ps(i);let a=new Error(i);throw a.status=e.status,a}var jl="ERR_CONFLICTING_ENDPOINTS",wi=class extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:jl}),this.name="ConflictingEndpointsError"}};function Ll(e){return typeof e=="object"&&e!==null&&e.code===jl}function Ee(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw new Error(bi(e));let[t,r]=e.split(":"),n=r||"latest";if(t.includes("/")){let[i,a]=t.split("/",2);if(!i||!a)throw new Error(bi(e));return[i,a,n]}else{if(!t)throw new Error(bi(e));return["-",t,n]}}var xi="https://api.smith.langchain.com",jm="langsmith-cli",Lm=6e4,Dm=1e4;function Um(){let e=dn();return e==="browser"||e==="webworker"}function zm(){let e=pe("LANGSMITH_CONFIG_FILE");if(e)return e;let t=pe("HOME")??pe("USERPROFILE");if(t)return ir.join(t,".langsmith","config.json")}function Bm(e){let t=pe("LANGSMITH_PROFILE");if(t)return t;if(e.current_profile)return e.current_profile;if(e.profiles?.default)return"default"}function Fm(){if(Um())return;let e=zm();if(!(!e||!zr(e)))try{let t=JSON.parse(ii(e)),r=Bm(t),n=r?t.profiles?.[r]:void 0;return!r||!n?void 0:{configPath:e,config:t,profileName:r,profile:n}}catch{return}}function Ve(e){return e!=null&&e.trim()!==""}function Lt(e){return e?.trim().replace(/^["']|["']$/g,"")}function Hm(e){let t=e.oauth;if(!t?.refresh_token)return!1;if(!t.access_token)return!0;if(!t.expires_at)return!1;let r=Date.parse(t.expires_at);return Number.isNaN(r)?!1:r<=Date.now()+Lm}function Gm(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);let r="/api/v1";return t.endsWith(r)?t.slice(0,-r.length):t}function Vm(e,t){e.oauth??={},t.access_token&&(e.oauth.access_token=t.access_token),t.refresh_token&&(e.oauth.refresh_token=t.refresh_token),typeof t.expires_in=="number"&&t.expires_in>0&&(e.oauth.expires_at=new Date(Date.now()+t.expires_in*1e3).toISOString())}function Dl(e){return e.reason??new Error("The operation was aborted.")}async function Zm(e,t){if(!t)return e;if(t.aborted)throw Dl(t);let r,n=new Promise((i,a)=>{let s=()=>{a(Dl(t))};t.addEventListener("abort",s,{once:!0}),r=()=>{t.removeEventListener("abort",s)}});try{return await Promise.race([e,n])}finally{r?.()}}function Ul(){let e=Fm(),t=e?.profile;if(!e||!t)return{};let r=Lt(t.api_key),n=Lt(t.oauth?.access_token),i=Lt(t.oauth?.refresh_token);return{apiUrl:t.api_url,apiKey:r,workspaceId:t.workspace_id,oauthAccessToken:n,oauthRefreshToken:i,profileAuth:r||n||i?new js(e):void 0}}var js=class{constructor(t){Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:t}),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 t=qm(this.state.profile);return this.rememberProfileAuthHeader(t),t}async getAuthHeader(t,r){Hm(this.state.profile)&&(this.refreshPromise||(this.refreshPromise=this.refreshOAuthToken(t).finally(()=>{this.refreshPromise=void 0})),await Zm(this.refreshPromise,r));let n=zl(this.state.profile);return this.rememberProfileAuthHeader(n),n}isProfileAuthorizationHeader(t){return t===this.managedAuthorizationValue}async refreshOAuthToken(t){let r=this.state.profile.oauth?.refresh_token;if(!r)return;let n=Lt(this.state.profile.api_url)??xi;try{let i=new URLSearchParams({grant_type:"refresh_token",client_id:jm,refresh_token:r}),a=await t(`${Gm(n)}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString(),signal:AbortSignal.timeout(Dm)});if(!a.ok)return;let s=await a.json();if(!s.access_token)return;Vm(this.state.profile,s),this.state.config.profiles??={},this.state.config.profiles[this.state.profileName]=this.state.profile,await ni(this.state.configPath,`${JSON.stringify(this.state.config,null,2)}
|
|
23
|
+
`)}catch{return}}rememberProfileAuthHeader(t){this.managedAuthorizationValue=t?.name==="Authorization"?t.value:void 0}};function qm(e){let t=Lt(e.oauth?.access_token);if(t)return{name:"Authorization",value:`Bearer ${t}`};if(!Lt(e.oauth?.refresh_token))return zl(e)}function zl(e){let t=Lt(e.oauth?.access_token);if(t)return{name:"Authorization",value:`Bearer ${t}`};let r=Lt(e.api_key);if(r)return{name:"x-api-key",value:r}}var Bl="[...]",Wm={result:"[Circular]"},Si=[],Br=[],Jm=new TextEncoder;function Km(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Ei(e){return Jm.encode(e)}function Fl(e){if(e&&typeof e=="object"&&e!==null){if(e instanceof Map)return Object.fromEntries(e);if(e instanceof Set)return Array.from(e);if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(e instanceof Error)return{name:e.name,message:e.message}}else if(typeof e=="bigint")return e.toString();return e}function Ym(e){return function(t,r){if(e){let n=e.call(this,t,r);if(n!==void 0)return n}return Fl(r)}}function Hl(e){try{let i=function(l){let d=n(l);return d>r&&(r=d),d+2},a=function(l){return l===0?2:2+l*4},s=function(l){return l===void 0||typeof l=="function"||typeof l=="symbol"},o=function(l){return l===void 0||typeof l=="function"||typeof l=="symbol"?4:c(l)},c=function(l){if(l===null)return 4;if(l===void 0)return 0;let d=typeof l;if(d==="boolean")return 5;if(d==="number")return Number.isFinite(l)?l.toString().length:4;if(d==="bigint")return l.toString().length+2;if(d==="string")return i(l);if(d==="function"||d==="symbol")return 0;let f=l;if(f instanceof Date)return 26;if(f instanceof RegExp)return n(f.toString())+2;if(f instanceof Error){let h=f.name??"",m=f.message??"";return 22+n(h)+n(m)}if(typeof Buffer<"u"&&f instanceof Buffer)return 28+a(f.byteLength);if(ArrayBuffer.isView(f)){if(f instanceof DataView)return 2;let h=f.length??0,b=f instanceof Float32Array||f instanceof Float64Array?30:12;return 2+h*b}if(f instanceof ArrayBuffer)return 2;if(t.has(f))return 24;if(typeof f.toJSON=="function"){let h;try{h=f.toJSON("")}catch{return 16}t.add(f);let m=c(h);return t.delete(f),m}t.add(f);let p;if(Array.isArray(f)){p=2;let h=f.length;for(let m=0;m<h;m++)p+=o(f[m]),m<h-1&&(p+=1)}else if(f instanceof Map){p=2;let h=0;for(let[m,b]of f){if(s(b))continue;h>0&&(p+=1);let x=typeof m=="string"?m:String(m);p+=n(x)+3,p+=c(b),h++}}else if(f instanceof Set){p=2;let h=0;for(let m of f)h>0&&(p+=1),p+=o(m),h++}else{p=2;let h=0,m=Object.keys(f);for(let b=0;b<m.length;b++){let x=m[b],v=f[x];s(v)||(h>0&&(p+=1),p+=n(x)+3,p+=c(v),h++)}}return t.delete(f),p},t=new Set,r=0,n=typeof Buffer<"u"&&typeof Buffer.byteLength=="function"?l=>Buffer.byteLength(l,"utf8"):l=>l.length;return{size:c(e),maxStringLen:r}}catch{return{size:Se(e).length,maxStringLen:0}}}function Se(e,t,r,n,i){try{let a=JSON.stringify(e,Ym(r),n);return Ei(a)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?`
|
|
24
|
+
Context: ${t}`:""}`),Ei("[Unserializable]");ne("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${t?`
|
|
25
|
+
Context: ${t}`:""}`),typeof i>"u"&&(i=Km()),Ds(e,"",0,[],void 0,0,i);let s;try{Br.length===0?s=JSON.stringify(e,r,n):s=JSON.stringify(e,Xm(r),n)}catch{return Ei("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Si.length!==0;){let o=Si.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return Ei(s)}}function Ls(e,t,r,n){var i=Object.getOwnPropertyDescriptor(n,r);i.get!==void 0?i.configurable?(Object.defineProperty(n,r,{value:e}),Si.push([n,r,t,i])):Br.push([t,r,e]):(n[r]=e,Si.push([n,r,t]))}function Ds(e,t,r,n,i,a,s){a+=1;var o;if(typeof e=="object"&&e!==null){for(o=0;o<n.length;o++)if(n[o]===e){Ls(Wm,e,t,i);return}if(typeof s.depthLimit<"u"&&a>s.depthLimit){Ls(Bl,e,t,i);return}if(typeof s.edgesLimit<"u"&&r+1>s.edgesLimit){Ls(Bl,e,t,i);return}if(n.push(e),Array.isArray(e))for(o=0;o<e.length;o++)Ds(e[o],o,o,n,e,a,s);else{e=Fl(e);var c=Object.keys(e);for(o=0;o<c.length;o++){var u=c[o];Ds(e[u],u,o,n,e,a,s)}}n.pop()}}function Xm(e){return e=typeof e<"u"?e:function(t,r){return r},function(t,r){if(Br.length>0)for(var n=0;n<Br.length;n++){var i=Br[n];if(i[1]===t&&i[0]===r){r=i[2],Br.splice(n,1);break}}return e.call(this,t,r)}}var eg=`
|
|
26
|
+
const { parentPort } = require("worker_threads");
|
|
27
|
+
|
|
28
|
+
const CIRCULAR_REPLACE_NODE = { result: "[Circular]" };
|
|
29
|
+
|
|
30
|
+
function serializeWellKnownTypes(val) {
|
|
31
|
+
if (val && typeof val === "object") {
|
|
32
|
+
if (val instanceof Map) return Object.fromEntries(val);
|
|
33
|
+
if (val instanceof Set) return Array.from(val);
|
|
34
|
+
if (val instanceof Date) return val.toISOString();
|
|
35
|
+
if (val instanceof RegExp) return val.toString();
|
|
36
|
+
if (val instanceof Error) return { name: val.name, message: val.message };
|
|
37
|
+
} else if (typeof val === "bigint") {
|
|
38
|
+
return val.toString();
|
|
39
|
+
}
|
|
40
|
+
return val;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function defaultReplacer(_key, val) {
|
|
44
|
+
return serializeWellKnownTypes(val);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Decirculate in-place: replace circular refs with { result: "[Circular]" }
|
|
48
|
+
// then restore after stringify. Mirrors fast-safe-stringify's decirc().
|
|
49
|
+
const restoreStack = [];
|
|
50
|
+
function decirc(val, k, stack, parent) {
|
|
51
|
+
if (typeof val === "object" && val !== null) {
|
|
52
|
+
for (let i = 0; i < stack.length; i++) {
|
|
53
|
+
if (stack[i] === val) {
|
|
54
|
+
const orig = parent[k];
|
|
55
|
+
parent[k] = CIRCULAR_REPLACE_NODE;
|
|
56
|
+
restoreStack.push([parent, k, orig]);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
stack.push(val);
|
|
61
|
+
if (Array.isArray(val)) {
|
|
62
|
+
for (let i = 0; i < val.length; i++) decirc(val[i], i, stack, val);
|
|
63
|
+
} else {
|
|
64
|
+
const normalized = serializeWellKnownTypes(val);
|
|
65
|
+
// Only recurse into normalized if it's still an object (arrays/objects),
|
|
66
|
+
// else it was replaced with a primitive (e.g. Date -> string).
|
|
67
|
+
if (normalized === val) {
|
|
68
|
+
const keys = Object.keys(val);
|
|
69
|
+
for (let i = 0; i < keys.length; i++) decirc(val[keys[i]], keys[i], stack, val);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
stack.pop();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function serialize(obj) {
|
|
77
|
+
try {
|
|
78
|
+
return JSON.stringify(obj, defaultReplacer);
|
|
79
|
+
} catch (e) {
|
|
80
|
+
if (!String(e && e.message).includes("Converting circular structure to JSON")) {
|
|
81
|
+
return "[Unserializable]";
|
|
82
|
+
}
|
|
83
|
+
decirc(obj, "", [], { "": obj });
|
|
84
|
+
try {
|
|
85
|
+
return JSON.stringify(obj, defaultReplacer);
|
|
86
|
+
} catch (_) {
|
|
87
|
+
return "[unable to serialize, circular reference is too complex to analyze]";
|
|
88
|
+
} finally {
|
|
89
|
+
while (restoreStack.length) {
|
|
90
|
+
const [p, k, v] = restoreStack.pop();
|
|
91
|
+
p[k] = v;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
parentPort.on("message", (msg) => {
|
|
98
|
+
const { id, op, payload } = msg;
|
|
99
|
+
try {
|
|
100
|
+
if (op === "serialize") {
|
|
101
|
+
const str = serialize(payload);
|
|
102
|
+
const buf = Buffer.from(str, "utf8");
|
|
103
|
+
// Slice into its own ArrayBuffer so we can transfer without dragging
|
|
104
|
+
// unrelated bytes from any shared pool buffer.
|
|
105
|
+
const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
|
106
|
+
parentPort.postMessage({ id, bytes: ab, length: buf.byteLength }, [ab]);
|
|
107
|
+
} else if (op === "ping") {
|
|
108
|
+
parentPort.postMessage({ id });
|
|
109
|
+
} else {
|
|
110
|
+
parentPort.postMessage({ id, error: "unknown op: " + op });
|
|
111
|
+
}
|
|
112
|
+
} catch (e) {
|
|
113
|
+
parentPort.postMessage({ id, error: String((e && e.message) || e) });
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
`,zs=class{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(!!1||null===null)return this.disabled=!0,!1;try{let t=new null(eg,{eval:!0});return t.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")))}),t.on("error",r=>{for(let[,n]of this.pending)n.reject(r);this.pending.clear(),this.disabled=!0,this.worker=null}),t.on("exit",r=>{for(let[,n]of this.pending)n.reject(new Error(`worker exited with code ${r}`));this.pending.clear(),this.worker=null}),t.unref(),this.worker=t,!0}catch{return this.disabled=!0,!1}}async serialize(t){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:t})}catch(s){this.pending.delete(n),a(s)}})}async terminate(){this.worker&&(await this.worker.terminate(),this.worker=null);for(let[,t]of this.pending)t.reject(new Error("worker terminated"));this.pending.clear()}},Us=null;function Vl(){return Us===null&&(Us=new zs),Us}var tg=64*1024,rg=2048;function Zl(e,t=tg,r=rg){if(e===null||typeof e!="object")return typeof e=="string"&&e.length>=t;let n=[e],i=new Set,a=0;for(;n.length>0;){if(a++>=r)return!1;let s=n.pop();if(s==null)continue;let o=typeof s;if(o==="string"){if(s.length>=t)return!0;continue}if(o!=="object")continue;let c=s;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 l=c.length-1;l>=0;l--)n.push(c[l]);continue}if(c instanceof Map){for(let[,l]of c)n.push(l);continue}if(c instanceof Set){for(let l of c)n.push(l);continue}let u=Object.keys(c);for(let l=u.length-1;l>=0;l--)n.push(c[u[l]])}return!1}function ng(e,t){let[r]=Ee(e);if(r!=="-"&&!t)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.")}function ql(e){return typeof e=="string"&&e.length>0&&!e.includes("Z")&&!e.includes("+")&&!e.includes("-",10)?e+"Z":e}function hn(e){return{...e,start_time:ql(e.start_time),end_time:ql(e.end_time)}}function Wl(e,t,r){if(r)return e;let n=ci(),i=t??ms(),a=e.extra??{},s=a.metadata;return e.extra={...a,runtime:{...n,...a?.runtime},metadata:{...i,...i.revision_id||"revision_id"in e&&e.revision_id?{revision_id:("revision_id"in e?e.revision_id:void 0)??i.revision_id}:{},...s}},e}var ig=e=>{let t=e?.toString()??ne("TRACING_SAMPLING_RATE");if(t===void 0)return;let r=parseFloat(t);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},ag=e=>{let r=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};async function sg(e){let t=[];for await(let r of e)t.push(r);return t}function Ti(e){if(e!==void 0)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}var og=async e=>{if(e?.status===429){let t=parseInt(e.headers.get("retry-after")??"10",10)*1e3;if(t>0)return await new Promise(r=>setTimeout(r,t)),!0}return!1};function Jl(e){return typeof e=="number"?Number(e.toFixed(4)):e}var cg=24*1024*1024,Yl=1024*1024*1024,ug=1e4,lg=100,Bs=class{constructor(t){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=t??Yl}peek(){return this.items[0]}push(t){let r,n=new Promise(a=>{r=a}),i=Hl(t.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: ${t.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${i} bytes.`),r(),n):(this.items.push({action:t.action,payload:t.item,otelContext:t.otelContext,apiKey:t.apiKey,apiUrl:t.apiUrl,itemPromiseResolve:r,itemPromise:n,size:i}),this.sizeBytes+=i,n)}pop({upToSizeBytes:t,upToSize:r}){if(t<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)<t&&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,size:a.size})),()=>n.forEach(a=>a.itemPromiseResolve())]}},jt=class e{get tracingMode(){return this._tracingMode}get _fetch(){let t=this.fetchImplementation||el(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(t,n?.signal)),t(r,this.applyCurrentAuthHeaders(n,i,a))})}getProfileManagedAuthorizationHeader(t){if(!t?.headers||!this.profileAuth)return;let r=new Headers(t.headers).get("Authorization");if(Ve(r))return this.profileAuth.isProfileAuthorizationHeader(r??"")?r??void 0:void 0}isProfileManagedAuthorizationHeader(t,r){return t===r||this.profileAuth?.isProfileAuthorizationHeader(t)===!0}hasExplicitAuthHeader(t,r){if(!t?.headers)return!1;let n=new Headers(t.headers);if(Ve(n.get("x-api-key")))return!0;let i=n.get("Authorization");return Ve(i)?!this.isProfileManagedAuthorizationHeader(i??"",r):!1}applyCurrentAuthHeaders(t,r,n){if(!r)return t;let i=d=>{if(this.apiKey!==void 0&&r.name==="x-api-key")return d.delete("Authorization"),d.has("x-api-key")||d.set("x-api-key",r.value),d;if(r.name==="Authorization"){if(Ve(d.get("x-api-key")))return d;let p=d.get("Authorization");return Ve(p)&&!this.isProfileManagedAuthorizationHeader(p??"",n)||d.set("Authorization",r.value),d}let f=d.get("Authorization");return Ve(f)&&!this.isProfileManagedAuthorizationHeader(f??"",n)||(Ve(f)&&d.delete("Authorization"),d.has("x-api-key")||d.set("x-api-key",r.value)),d};if(!t)return{headers:{[r.name]:r.value}};if(t.headers instanceof Headers)return{...t,headers:i(new Headers(t.headers))};if(Array.isArray(t.headers))return{...t,headers:i(new Headers(t.headers))};let a={...t.headers??{}},s=d=>Object.keys(a).find(f=>f.toLowerCase()===d),o=d=>{let f=s(d);return f?a[f]:void 0},c=Ve(o("x-api-key")),u=o("authorization"),l=Ve(u)&&!this.isProfileManagedAuthorizationHeader(u??"",n);if(this.apiKey!==void 0&&r.name==="x-api-key"){let d=s("authorization");return d&&delete a[d],c||(a["x-api-key"]=r.value),{...t,headers:a}}if(r.name==="Authorization"){if(!c&&!l){let d=s("authorization");d&&d!=="Authorization"&&delete a[d],a.Authorization=r.value}return{...t,headers:a}}if(!l){let d=s("authorization");d&&delete a[d],c||(a["x-api-key"]=r.value)}return{...t,headers:a}}_trackDrain(t){this._pendingDrains.add(t),t.finally(()=>{this._pendingDrains.delete(t)})}async _serializeBody(t,r){if(this.manualFlushMode)return Se(t,r);if(!Zl(t))return Se(t,r);if(this._serializeWorker===void 0&&(this._serializeWorker=Vl()),this._serializeWorker===null)return Se(t,r);try{let n=await this._serializeWorker.serialize(t);return n===null?(this._serializeWorker=null,Se(t,r)):n}catch{return Se(t,r)}}constructor(t={}){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,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:pe("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_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:!1}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:ne("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:pe("LANGSMITH_DEBUG")==="true"});let r=e.getDefaultClientConfig();this.tracingSampleRate=ig(t.tracingSamplingRate),this.apiUrl=Ti(t.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1));let n=Ti(t.apiKey??r.apiKey);if(this.apiKey=Ve(n)?n:void 0,this.profileAuth=this.apiKey!==void 0?void 0:r.profileAuth,this.webUrl=Ti(t.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Ti(t.workspaceId??r.workspaceId),this.timeout_ms=t.timeout_ms??9e4,this.caller=new pn({...t.callerOptions??{},maxRetries:4,debug:t.debug??this.debug}),this.traceBatchConcurrency=t.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=t.debug??this.debug,this.fetchImplementation=t.fetchImplementation,this.failedTracesDir=ne("FAILED_TRACES_DIR")||void 0;let i=ne("FAILED_TRACES_MAX_MB");if(i){let s=parseInt(i,10);Number.isFinite(s)&&s>0&&(this.failedTracesMaxBytes=s*1024*1024)}let a=t.maxIngestMemoryBytes??Yl;this.batchIngestCaller=new pn({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:a,...t.callerOptions??{},onFailedResponseHook:og,debug:t.debug??this.debug}),this.hideInputs=t.hideInputs??t.anonymizer??r.hideInputs,this.hideOutputs=t.hideOutputs??t.anonymizer??r.hideOutputs,this.hideMetadata=t.hideMetadata??r.hideMetadata,this.omitTracedRuntimeInfo=t.omitTracedRuntimeInfo??!1,this.autoBatchTracing=t.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new Bs(a),this.blockOnRootRunFinalization=t.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=t.batchSizeBytesLimit,this.batchSizeLimit=t.batchSizeLimit,this.fetchOptions=t.fetchOptions||{},this.manualFlushMode=t.manualFlushMode??this.manualFlushMode,this._tracingMode=ui(t.tracingMode),this._tracingMode==="otel"&&(this.langSmithToOTELTranslator=new di),this.cachedLSEnvVarsForMetadata=ms(),t.cache!==void 0&&t.disablePromptCache&&rr("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),t.cache!==void 0?(rr("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."),t.cache===!1?this._promptCache=void 0:t.cache===!0?this._promptCache=si:this._promptCache=t.cache):t.disablePromptCache||(this._promptCache=si),this._customHeaders=t.headers??{}}static getDefaultClientConfig(){let t=Ul(),r=ne("API_KEY"),n=ne("ENDPOINT"),i=ne("WORKSPACE_ID"),a=Ve(r),s=n??t.apiUrl??xi,o=i??t.workspaceId,c=ne("HIDE_INPUTS")==="true",u=ne("HIDE_OUTPUTS")==="true",l=ne("HIDE_METADATA")==="true";return{apiUrl:s,apiKey:r,webUrl:void 0,hideInputs:c,hideOutputs:u,hideMetadata:l,workspaceId:o,oauthAccessToken:a?void 0:t.oauthAccessToken,oauthRefreshToken:a?void 0:t.oauthRefreshToken,profileAuth:a?void 0:t.profileAuth}}getHostUrl(){return this.webUrl?this.webUrl:ag(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 _mergedHeaders(){let t={"User-Agent":`langsmith-js/${oi}`,...this._customHeaders};if(this.apiKey!==void 0)t["x-api-key"]=`${this.apiKey}`;else{let r=this.profileAuth?.currentAuthHeader();r&&(t[r.name]=r.value)}return this.workspaceId&&(t["x-tenant-id"]=this.workspaceId),t}get headers(){return this._customHeaders}set headers(t){this._customHeaders=t??{}}_getPlatformEndpointPath(t){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${t}`:`/platform/${t}`}async processInputs(t){return this.hideInputs===!1?t:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(t):t}async processOutputs(t){return this.hideOutputs===!1?t:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(t):t}async processMetadata(t){return this.hideMetadata===!1?t:this.hideMetadata===!0?{}:typeof this.hideMetadata=="function"?this.hideMetadata(t):t}_filterNewTokenEvents(t){return!t||t.length===0?t:t.map(r=>{if(r.name==="new_token"){let{kwargs:n,...i}=r;return i}return r})}async prepareRunCreateOrUpdateInputs(t){let r={...t};return r.inputs!==void 0&&(r.inputs=await this.processInputs(r.inputs)),r.outputs!==void 0&&(r.outputs=await this.processOutputs(r.outputs)),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(t,r){let n=r?.toString()??"",i=`${this.apiUrl}${t}?${n}`;return await this.caller.call(async()=>{let s=await this._fetch(i,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(s,`fetch ${t}`),s})}async _get(t,r){return(await this._getResponse(t,r)).json()}async*_getPaginated(t,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 s=`${this.apiUrl}${t}?${r}`,o=await this.caller.call(async()=>{let u=await this._fetch(s,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(u,`fetch ${t}`),u}),c=n?n(await o.json()):await o.json();if(c.length===0||(yield c,c.length<a))break;i+=c.length}}async*_getCursorPaginatedList(t,r=null,n="POST",i="runs"){let a=r?{...r}:{};for(;;){let s=JSON.stringify(a),c=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}${t}`,{method:n,headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await O(l,`fetch ${t}`),l})).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(t,r=!1){if(this.tracingSampleRate===void 0)return t;if(r){let n=[];for(let i of t)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 t){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 t=await this._ensureServerInfo();return this.batchSizeBytesLimit??t?.batch_ingest_config?.size_limit_bytes??cg}async _getBatchSizeLimit(){let t=await this._ensureServerInfo();return this.batchSizeLimit??t?.batch_ingest_config?.size_limit??lg}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:t,batchSizeLimit:r}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[i,a]=this.autoBatchQueue.pop({upToSizeBytes:t,upToSize:r});if(!i.length){a();break}let s=i.reduce((u,l)=>{let d=l.apiUrl??this.apiUrl,f=l.apiKey??this.apiKey,h=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${d}|${f}`;return u[h]||(u[h]=[]),u[h].push(l),u},{}),o=[];for(let[u,l]of Object.entries(s)){let d=this._processBatch(l,{apiUrl:u==="default"?void 0:u.split("|")[0],apiKey:u==="default"?void 0:u.split("|")[1]});o.push(d)}let c=Promise.all(o).finally(a);n.push(c)}return Promise.all(n)}static async _writeTraceToFallbackDir(t,r,n,i,a){try{let s=typeof r=="string"?Buffer.from(r,"utf8"):Buffer.from(r),o=JSON.stringify({version:1,endpoint:i,headers:n,body_base64:s.toString("base64")}),c=`trace_${Date.now()}_${tr().slice(0,8)}.json`,u=ir.join(t,c);if(e._fallbackDirsCreated.has(t)||(await hl(t),e._fallbackDirsCreated.add(t)),a!==void 0&&a>0)try{let d=(await ml(t)).filter(p=>p.startsWith("trace_")&&p.endsWith(".json")),f=0;for(let p of d){let{size:h}=await gl(ir.join(t,p));f+=h}if(f>=a){console.warn(`Could not write trace to fallback dir ${t} as it's already over size limit (${f} bytes >= ${a} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await ni(u,o),console.warn(`LangSmith trace upload failed; data saved to ${u} for later replay.`)}catch(s){console.error(`LangSmith tracing error: could not write trace to fallback dir ${t}:`,s)}}async _processBatch(t,r){if(!t.length)return;let n=t.reduce((i,a)=>i+(a.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(t);else{let i={runCreates:t.filter(o=>o.action==="create").map(o=>o.item),runUpdates:t.filter(o=>o.action==="update").map(o=>o.item)},a=await this._ensureServerInfo();if(!this._multipartDisabled&&(a?.batch_ingest_config?.use_multipart_endpoint??!0)){let o=!this._runCompressionDisabled&&a?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(i,{...r,useGzip:o,sizeBytes:n})}catch(c){if(vi(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(t){if(this.langSmithToOTELTranslator!==void 0){let r=new Map,n=[];for(let i of t)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(t){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,t.item=Wl(t.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let r=this.autoBatchQueue.push(t);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(ug),...this.fetchOptions});return await O(n,"get server info"),n})).json();return this.debug&&console.log(`
|
|
117
|
+
=== LangSmith Server Configuration ===
|
|
118
|
+
`+JSON.stringify(r,null,2)+`
|
|
119
|
+
`),r}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(t){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${t.status??"Unspecified status code"} ${t.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(t=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),t))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let t=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:t,batchSizeLimit:r})}_cloneCurrentOTELContext(){let t=li(),r=xl();if(this.langSmithToOTELTranslator!==void 0){let n=t.getActiveSpan();if(n)return t.setSpan(r.active(),n)}}async createRun(t,r){if(!this._filterForSampling([t]).length)return;let n={...this._mergedHeaders,"Content-Type":"application/json"},i=t.project_name;delete t.project_name;let a=await this.prepareRunCreateOrUpdateInputs({session_name:i,...t,start_time:t.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}).catch(console.error);return}let s=Wl(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 o=Se(s,`Creating run with id: ${s.id}`);await this.caller.call(async()=>{let c=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await O(c,"create run",!0),c})}async batchIngestRuns({runCreates:t,runUpdates:r},n){if(t===void 0&&r===void 0)return;let i=await Promise.all(t?.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((l,d)=>(d.id&&(l[d.id]=d),l),{}),u=[];for(let l of a)l.id!==void 0&&c[l.id]?c[l.id]={...c[l.id],...l}:u.push(l);i=Object.values(c),a=u}let s={post:i,patch:a};if(!s.post.length&&!s.patch.length)return;let o={post:[],patch:[]};for(let c of["post","patch"]){let u=c,l=s[u].reverse(),d=l.pop();for(;d!==void 0;)o[u].push(d),d=l.pop()}if(o.post.length>0||o.patch.length>0){let c=o.post.map(u=>u.id).concat(o.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(await this._serializeBody(o,`Ingesting runs with ids: ${c}`),n)}}async _postBatchIngestRuns(t,r){let n={...this._mergedHeaders,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let i=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await O(i,"batch create run",!0),i})}async multipartIngestRuns({runCreates:t,runUpdates:r},n){if(t===void 0&&r===void 0)return;let i={},a=[];for(let d of t??[]){let f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(i[f.id]=f.attachments),delete f.attachments,a.push(f)}let s=[];for(let d of r??[])s.push(await this.prepareRunCreateOrUpdateInputs(d));if(a.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(s.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(a.length>0&&s.length>0){let d=a.reduce((p,h)=>(h.id&&(p[h.id]=h),p),{}),f=[];for(let p of s)p.id!==void 0&&d[p.id]?d[p.id]={...d[p.id],...p}:f.push(p);a=Object.values(d),s=f}if(a.length===0&&s.length===0)return;let u=[],l=[];for(let[d,f]of[["post",a],["patch",s]])for(let p of f){let{inputs:h,outputs:m,events:b,extra:x,error:v,serialized:I,attachments:k,...j}=p,X={inputs:h,outputs:m,events:b,extra:x,error:v,serialized:I},K=await this._serializeBody(j,`Serializing for multipart ingestion of run with id: ${j.id}`);l.push({name:`${d}.${j.id}`,payload:new Blob([K],{type:`application/json; length=${K.length}`})});for(let[Q,ee]of Object.entries(X)){if(ee===void 0)continue;let fe=await this._serializeBody(ee,`Serializing ${Q} for multipart ingestion of run with id: ${j.id}`);l.push({name:`${d}.${j.id}.${Q}`,payload:new Blob([fe],{type:`application/json; length=${fe.length}`})})}if(j.id!==void 0){let Q=i[j.id];if(Q){delete i[j.id];for(let[ee,fe]of Object.entries(Q)){let Ae,lt;if(Array.isArray(fe)?[Ae,lt]=fe:(Ae=fe.mimeType,lt=fe.data),ee.includes(".")){console.warn(`Skipping attachment '${ee}' for run ${j.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${j.id}.${ee}`,payload:new Blob([lt],{type:`${Ae}; length=${lt.byteLength}`})})}}}u.push(`trace=${j.trace_id},id=${j.id}`)}await this._sendMultipartRequest(l,u.join("; "),n)}async _createNodeFetchBody(t,r){let n=[];for(let s of t)n.push(new Blob([`--${r}\r
|
|
120
|
+
`])),n.push(new Blob([`Content-Disposition: form-data; name="${s.name}"\r
|
|
121
|
+
`,`Content-Type: ${s.payload.type}\r
|
|
122
|
+
\r
|
|
123
|
+
`])),n.push(s.payload),n.push(new Blob([`\r
|
|
124
|
+
`]));return n.push(new Blob([`--${r}--\r
|
|
125
|
+
`])),await new Blob(n).arrayBuffer()}async _createMultipartStream(t,r){let n=new TextEncoder;return new ReadableStream({async start(a){let s=async o=>{typeof o=="string"?a.enqueue(n.encode(o)):a.enqueue(o)};for(let o of t){await s(`--${r}\r
|
|
126
|
+
`),await s(`Content-Disposition: form-data; name="${o.name}"\r
|
|
127
|
+
`),await s(`Content-Type: ${o.payload.type}\r
|
|
128
|
+
\r
|
|
129
|
+
`);let u=o.payload.stream().getReader();try{let l;for(;!(l=await u.read()).done;)a.enqueue(l.value)}finally{u.releaseLock()}await s(`\r
|
|
130
|
+
`)}await s(`--${r}--\r
|
|
131
|
+
`),a.close()}})}async _sendMultipartRequest(t,r,n){let i="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=()=>this._createNodeFetchBody(t,i),s=()=>this._createMultipartStream(t,i),o=async c=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let u=await c(),l={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${i}`};n?.apiKey!==void 0&&(l["x-api-key"]=n.apiKey);let d=u;n?.useGzip&&typeof u=="object"&&"pipeThrough"in u&&(d=u.pipeThrough(new CompressionStream("gzip")),l["Content-Encoding"]="gzip");let f=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:l,body:d,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(f,"Failed to send multipart request",!0),f});try{let c,u=!1;Qu()&&!this.multipartStreamingDisabled&&dn()!=="bun"?(u=!0,c=await o(s)):c=await o(a),(!this.multipartStreamingDisabled||u)&&c.status===422&&(n?.apiUrl??this.apiUrl)!==xi&&(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 o(a))}catch(c){if(vi(c))throw c;if(console.warn(`${c.message.trim()}
|
|
132
|
+
|
|
133
|
+
Context: ${r}`),this.failedTracesDir){let u=await this._createNodeFetchBody(t,i).catch(()=>null);u&&await e._writeTraceToFallbackDir(this.failedTracesDir,u,{"Content-Type":`multipart/form-data; boundary=${i}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(t,r,n){G(t),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs)),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:t};if(!this._filterForSampling([i],!0).length)return;if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let o=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:o,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:i,otelContext:o,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).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 s=Se(r,`Serializing payload to update run with id: ${t}`);await this.caller.call(async()=>{let o=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${t}`,{method:"PATCH",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await O(o,"update run",!0),o})}async readRun(t,{loadChildRuns:r}={loadChildRuns:!1}){G(t);let n=hn(await this._get(`/runs/${t}`));return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:t,run:r,projectOpts:n}){if(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:ne("PROJECT")||"default"})).id;let a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${i}/r/${r.id}?poll=true`}else if(t!==void 0){let i=await this.readRun(t);if(!i.app_path)throw new Error(`Run ${t} has no app_path`);return`${this.getHostUrl()}${i.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(t){let r=await sg(this.listRuns({isRoot:!1,projectId:t.session_id,traceId:t.trace_id})),n={},i={};r.sort((a,s)=>(a?.dotted_order??"").localeCompare(s?.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(t.dotted_order??"")&&a.id!==t.id&&(a.parent_run_id in n||(n[a.parent_run_id]=[]),n[a.parent_run_id].push(a),i[a.id]=a)}t.child_runs=n[t.id]||[];for(let a in n)a!==t.id&&(i[a].child_runs=n[a]);return t}async*listRuns(t){let{projectId:r,projectName:n,parentRunId:i,traceId:a,referenceExampleId:s,startTime:o,executionOrder:c,isRoot:u,runType:l,error:d,id:f,query:p,filter:h,traceFilter:m,treeFilter:b,limit:x,select:v,order:I}=t,k=[];if(r&&(k=Array.isArray(r)?r:[r]),n){let Q=Array.isArray(n)?n:[n],ee=await Promise.all(Q.map(fe=>this.readProject({projectName:fe}).then(Ae=>Ae.id)));k.push(...ee)}let j=["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"],X={session:k.length?k:null,run_type:l,reference_example:s,query:p,filter:h,trace_filter:m,tree_filter:b,execution_order:c,parent_run:i,start_time:o?o.toISOString():null,error:d,id:f,limit:x,trace:a,select:v||j,is_root:u,order:I};X.select.includes("child_run_ids")&&rr("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let K=0;for await(let Q of this._getCursorPaginatedList("/runs/query",X)){let ee=Q.map(hn);if(x){if(K>=x)break;if(ee.length+K>x){yield*ee.slice(0,x-K);break}K+=ee.length,yield*ee}else yield*ee}}async*listGroupRuns(t){let{projectId:r,projectName:n,groupBy:i,filter:a,startTime:s,endTime:o,limit:c,offset:u}=t,d={session_id:r||(await this.readProject({projectName:n})).id,group_by:i,filter:a,start_time:s?s.toISOString():null,end_time:o?o.toISOString():null,limit:Number(c)||100},f=Number(u)||0,p="/runs/group",h=`${this.apiUrl}${p}`;for(;;){let m={...d,offset:f},b=Object.fromEntries(Object.entries(m).filter(([X,K])=>K!==void 0)),x=JSON.stringify(b),I=await(await this.caller.call(async()=>{let X=await this._fetch(h,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:x});return await O(X,`Failed to fetch ${p}`),X})).json(),{groups:k,total:j}=I;if(k.length===0)break;for(let X of k)yield X;if(f+=k.length,f>=j)break}}async*readThread(t){let{threadId:r,projectId:n,projectName:i,isRoot:a=!0,limit:s,filter:o,order:c="asc"}=t;if(!n&&!i)throw new Error("threadId requires projectId or projectName");let u=`eq(thread_id, ${JSON.stringify(r)})`,l=o?`and(${u}, ${o})`:u;yield*this.listRuns({projectId:n??void 0,projectName:i??void 0,isRoot:a,limit:s,filter:l,order:c})}async listThreads(t){let{projectId:r,projectName:n,limit:i,offset:a=0,filter:s,startTime:o,isRoot:c=!0}=t;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,l=o??new Date(Date.now()-1440*60*1e3),f={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:l.toISOString()};s!=null&&(f.filter=s);let p=new Map;for await(let x of this._getCursorPaginatedList("/runs/query",f))for(let v of x){let I=hn(v),k=I.thread_id;if(k){let j=p.get(k)??[];j.push(I),p.set(k,j)}}let h=[];for(let[x,v]of p.entries()){v.sort((K,Q)=>{let ee=K,fe=Q,Ae=ee.start_time??"",lt=fe.start_time??"";if(Ae!==lt)return Ae.localeCompare(lt);let Cn=ee.dotted_order??"",rn=fe.dotted_order??"";return Cn.localeCompare(rn)});let k=[...v.map(K=>K.start_time).filter(Boolean)].sort(),j=k.length?k[0]:"",X=k.length?k[k.length-1]:"";h.push({thread_id:x,runs:v,count:v.length,filter:"",total_tokens:0,total_cost:null,min_start_time:j,max_start_time:X,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}h.sort((x,v)=>{let I=x.max_start_time??"";return(v.max_start_time??"").localeCompare(I)});let m=a>0?h.slice(a):h;return i!==void 0?m.slice(0,i):m}async getRunStats({id:t,trace:r,parentRun:n,runType:i,projectNames:a,projectIds:s,referenceExampleIds:o,startTime:c,endTime:u,error:l,query:d,filter:f,traceFilter:p,treeFilter:h,isRoot:m,dataSourceType:b}){let x=s||[];a&&(x=[...s||[],...await Promise.all(a.map(K=>this.readProject({projectName:K}).then(Q=>Q.id)))]);let I=Object.fromEntries(Object.entries({id:t,trace:r,parent_run:n,run_type:i,session:x,reference_example:o,start_time:c,end_time:u,error:l,query:d,filter:f,trace_filter:p,tree_filter:h,is_root:m,data_source_type:b}).filter(([K,Q])=>Q!==void 0)),k=JSON.stringify(I);return await(await this.caller.call(async()=>{let K=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:k});return await O(K,"get run stats"),K})).json()}async shareRun(t,{shareId:r}={}){let n={run_id:t,share_token:r||tr()};G(t);let i=JSON.stringify(n),s=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await O(o,"share run"),o})).json();if(s===null||!("share_token"in s))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${s.share_token}/r`}async unshareRun(t){G(t),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(r,"unshare run",!0),r})}async readRunSharedLink(t){G(t);let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(i,"read run shared link"),i})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(t,{runIds:r}={}){let n=new URLSearchParams({share_token:t});if(r!==void 0)for(let s of r)n.append("id",s);return G(t),(await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/public/${t}/runs${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(s,"list shared runs"),s})).json()).map(hn)}async readDatasetSharedSchema(t,r){if(!t&&!r)throw new Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:r})).id),G(t);let i=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(a,"read dataset shared schema"),a})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async shareDataset(t,r){if(!t&&!r)throw new Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:r})).id);let n={dataset_id:t};G(t);let i=JSON.stringify(n),s=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await O(o,"share dataset"),o})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async unshareDataset(t){G(t),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(r,"unshare dataset",!0),r})}async readSharedDataset(t){return G(t),await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/public/${t}/datasets`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(i,"read shared dataset"),i})).json()}async listSharedExamples(t,r){let n={};r?.exampleIds&&(n.id=r.exampleIds);let i=new URLSearchParams;Object.entries(n).forEach(([o,c])=>{Array.isArray(c)?c.forEach(u=>i.append(o,u)):i.append(o,c)});let a=await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/public/${t}/examples?${i.toString()}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(o,"list shared examples"),o}),s=await a.json();if(!a.ok)throw"detail"in s?new Error(`Failed to list shared examples.
|
|
134
|
+
Status: ${a.status}
|
|
135
|
+
Message: ${Array.isArray(s.detail)?s.detail.join(`
|
|
136
|
+
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${a.status} ${a.statusText}`);return s.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:t,description:r=null,metadata:n=null,upsert:i=!1,projectExtra:a=null,referenceDatasetId:s=null}){let o=i?"?upsert=true":"",c=`${this.apiUrl}/sessions${o}`,u=a||{};n&&(u.metadata=n);let l={name:t,extra:u,description:r};s!==null&&(l.reference_dataset_id=s);let d=JSON.stringify(l);return await(await this.caller.call(async()=>{let h=await this._fetch(c,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await O(h,"create project"),h})).json()}async updateProject(t,{name:r=null,description:n=null,metadata:i=null,projectExtra:a=null,endTime:s=null}){let o=`${this.apiUrl}/sessions/${t}`,c=a;i&&(c={...c||{},metadata:i});let u=JSON.stringify({name:r,extra:c,description:n,end_time:s?new Date(s).toISOString():null});return await(await this.caller.call(async()=>{let f=await this._fetch(o,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await O(f,"update project"),f})).json()}async hasProject({projectId:t,projectName:r}){let n="/sessions",i=new URLSearchParams;if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)G(t),n+=`/${t}`;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 s=await this._fetch(`${this.apiUrl}${n}?${i}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(s,"has project"),s});try{let s=await a.json();return a.ok?Array.isArray(s)?s.length>0:!0:!1}catch{return!1}}async readProject({projectId:t,projectName:r,includeStats:n}){let i="/sessions",a=new URLSearchParams;if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)G(t),i+=`/${t}`;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 s=await this._get(i,a),o;if(Array.isArray(s)){if(s.length===0)throw new Error(`Project[id=${t}, name=${r}] not found`);o=s[0]}else o=s;return o}async getProjectUrl({projectId:t,projectName:r}){if(t===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:t,projectName:r}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${n.id}`}async getDatasetUrl({datasetId:t,datasetName:r}){if(t===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:t,datasetName:r}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let t=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",t))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:t,name:r,nameContains:n,referenceDatasetId:i,referenceDatasetName:a,includeStats:s,datasetVersion:o,referenceFree:c,metadata:u}={}){let l=new URLSearchParams;if(t!==void 0)for(let d of t)l.append("id",d);if(r!==void 0&&l.append("name",r),n!==void 0&&l.append("name_contains",n),i!==void 0)l.append("reference_dataset",i);else if(a!==void 0){let d=await this.readDataset({datasetName:a});l.append("reference_dataset",d.id)}s!==void 0&&l.append("include_stats",s.toString()),o!==void 0&&l.append("dataset_version",o),c!==void 0&&l.append("reference_free",c.toString()),u!==void 0&&l.append("metadata",JSON.stringify(u));for await(let d of this._getPaginated("/sessions",l))yield*d}async deleteProject({projectId:t,projectName:r}){let n;if(t===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");t===void 0?n=(await this.readProject({projectName:r})).id:n=t,G(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 O(i,`delete session ${n} (${r})`,!0),i})}async uploadCsv({csvFile:t,fileName:r,inputKeys:n,outputKeys:i,description:a,dataType:s,name:o}){let c=`${this.apiUrl}/datasets/upload`,u=new FormData,l=new Blob([t],{type:"text/csv"});return u.append("file",l,r),n.forEach(p=>{u.append("input_keys",p)}),i.forEach(p=>{u.append("output_keys",p)}),a&&u.append("description",a),s&&u.append("data_type",s),o&&u.append("name",o),await(await this.caller.call(async()=>{let p=await this._fetch(c,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await O(p,"upload CSV"),p})).json()}async createDataset(t,{description:r,dataType:n,inputsSchema:i,outputsSchema:a,metadata:s}={}){let o={name:t,description:r,extra:{source:"sdk",...s?{metadata:s}:{}}};n&&(o.data_type=n),i&&(o.inputs_schema_definition=i),a&&(o.outputs_schema_definition=a);let c=JSON.stringify(o);return await(await this.caller.call(async()=>{let d=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 O(d,"create dataset"),d})).json()}async readDataset({datasetId:t,datasetName:r}){let n="/datasets",i=new URLSearchParams({limit:"1"});if(t&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(t)G(t),n+=`/${t}`;else if(r)i.append("name",r);else throw new Error("Must provide datasetName or datasetId");let a=await this._get(n,i),s;if(Array.isArray(a)){if(a.length===0)throw new Error(`Dataset[id=${t}, name=${r}] not found`);s=a[0]}else s=a;return s}async hasDataset({datasetId:t,datasetName:r}){try{return await this.readDataset({datasetId:t,datasetName:r}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:t,datasetName:r,fromVersion:n,toVersion:i}){let a=t;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 s=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`,s)}async readDatasetOpenaiFinetuning({datasetId:t,datasetName:r}){let n="/datasets";if(t===void 0)if(r!==void 0)t=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${t}/openai_ft`)).text()).trim().split(`
|
|
137
|
+
`).map(o=>JSON.parse(o))}async*listDatasets({limit:t=100,offset:r=0,datasetIds:n,datasetName:i,datasetNameContains:a,metadata:s}={}){let o="/datasets",c=new URLSearchParams({limit:t.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),s!==void 0&&c.append("metadata",JSON.stringify(s));for await(let u of this._getPaginated(o,c))yield*u}async updateDataset(t){let{datasetId:r,datasetName:n,...i}=t;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let a=r??(await this.readDataset({datasetName:n})).id;G(a);let s=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:s});return await O(c,"update dataset"),c})).json()}async updateDatasetTag(t){let{datasetId:r,datasetName:n,asOf:i,tag:a}=t;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let s=r??(await this.readDataset({datasetName:n})).id;G(s);let o=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/${s}/tags`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await O(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:t,datasetName:r}){let n="/datasets",i=t;if(t!==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)G(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 O(a,`delete ${n}`,!0),a})}async createExample(t,r,n){if(Kl(t)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let i=r?n?.datasetId:t.dataset_id,a=r?n?.datasetName:t.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 s=(r?n?.createdAt:t.created_at)||new Date,o;Kl(t)?o=t:o={inputs:t,outputs:r,created_at:s?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let c=await this._uploadExamplesMultipart(i,[o]);return await this.readExample(c.example_ids?.[0]??tr())}async createExamples(t){if(Array.isArray(t)){if(t.length===0)return[];let v=t,I=v[0].dataset_id,k=v[0].dataset_name;if(I===void 0&&k===void 0)throw new Error("Must provide either datasetName or datasetId");if(I!==void 0&&k!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");I===void 0&&(I=(await this.readDataset({datasetName:k})).id);let j=await this._uploadExamplesMultipart(I,v);return await Promise.all(j.example_ids.map(K=>this.readExample(K)))}let{inputs:r,outputs:n,metadata:i,splits:a,sourceRunIds:s,useSourceRunIOs:o,useSourceRunAttachments:c,attachments:u,exampleIds:l,datasetId:d,datasetName:f}=t;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let p=d,h=f;if(p===void 0&&h===void 0)throw new Error("Must provide either datasetName or datasetId");if(p!==void 0&&h!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");p===void 0&&(p=(await this.readDataset({datasetName:h})).id);let m=r.map((v,I)=>({dataset_id:p,inputs:v,outputs:n?.[I],metadata:i?.[I],split:a?.[I],id:l?.[I],attachments:u?.[I],source_run_id:s?.[I],use_source_run_io:o?.[I],use_source_run_attachments:c?.[I]})),b=await this._uploadExamplesMultipart(p,m);return await Promise.all(b.example_ids.map(v=>this.readExample(v)))}async createLLMExample(t,r,n){return this.createExample({input:t},{output:r},n)}async createChatExample(t,r,n){let i=t.map(s=>Ns(s)?$s(s):s),a=Ns(r)?$s(r):r;return this.createExample({input:i},{output:a},n)}async readExample(t){G(t);let r=`/examples/${t}`,n=await this._get(r),{attachment_urls:i,...a}=n,s=a;return i&&(s.attachments=Object.entries(i).reduce((o,[c,u])=>(o[c.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},o),{})),s}async*listExamples({datasetId:t,datasetName:r,exampleIds:n,asOf:i,splits:a,inlineS3Urls:s,metadata:o,limit:c,offset:u,filter:l,includeAttachments:d}={}){let f;if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0)f=t;else if(r!==void 0)f=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");let p=new URLSearchParams({dataset:f}),h=i?typeof i=="string"?i:i?.toISOString():void 0;h&&p.append("as_of",h);let m=s??!0;if(p.append("inline_s3_urls",m.toString()),n!==void 0)for(let x of n)p.append("id",x);if(a!==void 0)for(let x of a)p.append("splits",x);if(o!==void 0){let x=JSON.stringify(o);p.append("metadata",x)}c!==void 0&&p.append("limit",c.toString()),u!==void 0&&p.append("offset",u.toString()),l!==void 0&&p.append("filter",l),d===!0&&["attachment_urls","outputs","metadata"].forEach(x=>p.append("select",x));let b=0;for await(let x of this._getPaginated("/examples",p)){for(let v of x){let{attachment_urls:I,...k}=v,j=k;I&&(j.attachments=Object.entries(I).reduce((X,[K,Q])=>(X[K.slice(11)]={presigned_url:Q.presigned_url,mime_type:Q.mime_type||void 0},X),{})),yield j,b++}if(c!==void 0&&b>=c)break}}async deleteExample(t){G(t);let r=`/examples/${t}`;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 O(n,`delete ${r}`,!0),n})}async deleteExamples(t,r){if(t.forEach(n=>G(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:t,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(i,"hard delete examples",!0),i})}else{let n=new URLSearchParams;t.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 O(i,"delete examples",!0),i})}}async updateExample(t,r){let n;r?n=t:n=t.id,G(n);let i;r?i={id:n,...r}:i=t;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(t){let r;return t[0].dataset_id===void 0?r=(await this.readExample(t[0].id)).dataset_id:r=t[0].dataset_id,this._updateExamplesMultipart(r,t)}async readDatasetVersion({datasetId:t,datasetName:r,asOf:n,tag:i}){let a;if(t?a=t:a=(await this.readDataset({datasetName:r})).id,G(a),n&&i||!n&&!i)throw new Error("Exactly one of asOf and tag must be specified.");let s=new URLSearchParams;return n!==void 0&&s.append("as_of",typeof n=="string"?n:n.toISOString()),i!==void 0&&s.append("tag",i),await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${a}/version?${s.toString()}`,{method:"GET",headers:{...this._mergedHeaders},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:t,datasetName:r,asOf:n}){let i;if(t===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");t===void 0?i=(await this.readDataset({datasetName:r})).id:i=t,G(i);let a=new URLSearchParams,s=n?typeof n=="string"?n:n?.toISOString():void 0;return s&&a.append("as_of",s),await this._get(`/datasets/${i}/splits`,a)}async updateDatasetSplits({datasetId:t,datasetName:r,splitName:n,exampleIds:i,remove:a=!1}){let s;if(t===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");t===void 0?s=(await this.readDataset({datasetName:r})).id:s=t,G(s);let o={split_name:n,examples:i.map(u=>(G(u),u)),remove:a},c=JSON.stringify(o);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${s}/splits`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await O(u,"update dataset splits",!0),u})}async createFeedback(t,r,{score:n,value:i,correction:a,comment:s,sourceInfo:o,feedbackSourceType:c="api",sourceRunId:u,feedbackId:l,feedbackConfig:d,projectId:f,comparativeExperimentId:p,sessionId:h,startTime:m}){if(!t&&!f)throw new Error("One of runId or projectId must be provided");if(t&&f)throw new Error("Only one of runId or projectId can be provided");let b={type:c??"api",metadata:o??{}};u!==void 0&&b?.metadata!==void 0&&!b.metadata.__run&&(b.metadata.__run={run_id:u}),b?.metadata!==void 0&&b.metadata.__run?.run_id!==void 0&&G(b.metadata.__run.run_id);let x={id:l??jr(),run_id:t,key:r,score:Jl(n),value:i,correction:a,comment:s,feedback_source:b,comparative_experiment_id:p,feedbackConfig:d,session_id:h??f,start_time:m},v=JSON.stringify(x),I=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let k=await this._fetch(I,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:v});return await O(k,"create feedback",!0),k}),x}async updateFeedback(t,{score:r,value:n,correction:i,comment:a}){let s={};r!=null&&(s.score=Jl(r)),n!=null&&(s.value=n),i!=null&&(s.correction=i),a!=null&&(s.comment=a),G(t);let o=JSON.stringify(s);await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback/${t}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await O(c,"update feedback",!0),c})}async readFeedback(t){G(t);let r=`/feedback/${t}`;return await this._get(r)}async deleteFeedback(t){G(t);let r=`/feedback/${t}`;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 O(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:t,feedbackKeys:r,feedbackSourceTypes:n}={}){let i=new URLSearchParams;if(t)for(let a of t)G(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(t,r,{expiration:n,feedbackConfig:i}={}){let a={run_id:t,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 s=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:s});return await O(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:t,experimentIds:r,referenceDatasetId:n,createdAt:i,description:a,metadata:s,id:o}){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:o,name:t,experiment_ids:r,reference_dataset_id:n,description:a,created_at:(i??new Date)?.toISOString(),extra:{}};s&&(c.extra.metadata=s);let u=JSON.stringify(c);return(await this.caller.call(async()=>{let d=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 O(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(t){G(t);let r=new URLSearchParams({run_id:t});for await(let n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(t){let r;return"results"in t?r=t.results:Array.isArray(t)?r=t:r=[t],r}async _logEvaluationFeedback(t,r,n){let i=this._selectEvalResults(t),a=[];for(let s of i){let o=n||{};s.evaluatorInfo&&(o={...s.evaluatorInfo,...o});let c=null;s.targetRunId?c=s.targetRunId:r&&(c=r.id),a.push(await this.createFeedback(c,s.key,{score:s.score,value:s.value,comment:s.comment,correction:s.correction,sourceInfo:o,sourceRunId:s.sourceRunId,feedbackConfig:s.feedbackConfig,feedbackSourceType:"model",sessionId:r?.session_id,startTime:r?.start_time}))}return[i,a]}async logEvaluationFeedback(t,r,n){let[i]=await this._logEvaluationFeedback(t,r,n);return i}async createFeedbackConfig(t){let{feedbackKey:r,feedbackConfig:n,isLowerScoreBetter:i=!1}=t,a={feedback_key:r,feedback_config:n,is_lower_score_better:i};return(await this.caller.call(async()=>{let o=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 O(o,"create feedback config"),o})).json()}async*listFeedbackConfigs(t={}){let{feedbackKeys:r,nameContains:n,limit:i}=t,a=new URLSearchParams;r&&r.forEach(o=>{a.append("key",o)}),n&&a.append("name_contains",n),a.append("limit",(i!==void 0?Math.min(i,100):100).toString());let s=0;for await(let o of this._getPaginated("/feedback-configs",a))if(yield*o,s+=o.length,i!==void 0&&s>=i)break}async updateFeedbackConfig(t,r={}){let{feedbackConfig:n,isLowerScoreBetter:i}=r,a={feedback_key:t};return n!==void 0&&(a.feedback_config=n),i!==void 0&&(a.is_lower_score_better=i),(await this.caller.call(async()=>{let o=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 O(o,"update feedback config"),o})).json()}async deleteFeedbackConfig(t){let r=new URLSearchParams({feedback_key:t});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 O(n,"delete feedback config",!0),n})}async*listAnnotationQueues(t={}){let{queueIds:r,name:n,nameContains:i,limit:a}=t,s=new URLSearchParams;r&&r.forEach((c,u)=>{G(c,`queueIds[${u}]`),s.append("ids",c)}),n&&s.append("name",n),i&&s.append("name_contains",i),s.append("limit",(a!==void 0?Math.min(a,100):100).toString());let o=0;for await(let c of this._getPaginated("/annotation-queues",s))if(yield*c,o++,a!==void 0&&o>=a)break}async createAnnotationQueue(t){let{name:r,description:n,queueId:i,rubricInstructions:a,rubricItems:s}=t,o={name:r,description:n,id:i||tr(),rubric_instructions:a,rubric_items:s},c=JSON.stringify(Object.fromEntries(Object.entries(o).filter(([l,d])=>d!==void 0)));return(await this.caller.call(async()=>{let l=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 O(l,"create annotation queue"),l})).json()}async readAnnotationQueue(t){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${G(t,"queueId")}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(t,r){let{name:n,description:i,rubricInstructions:a,rubricItems:s}=r,o={};n!==void 0&&(o.name=n),i!==void 0&&(o.description=i),a!==void 0&&(o.rubric_instructions=a),s!==void 0&&(o.rubric_items=s);let c=JSON.stringify(o);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/annotation-queues/${G(t,"queueId")}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await O(u,"update annotation queue",!0),u})}async deleteAnnotationQueue(t){await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${G(t,"queueId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(t,r){let n=JSON.stringify(r.map((i,a)=>G(i,`runIds[${a}]`).toString()));await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/annotation-queues/${G(t,"queueId")}/runs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await O(i,"add runs to annotation queue",!0),i})}async getRunFromAnnotationQueue(t,r){let n=`/annotation-queues/${G(t,"queueId")}/run`,a=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(s,"get run from annotation queue"),s})).json();return hn(a)}async deleteRunFromAnnotationQueue(t,r){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${G(t,"queueId")}/runs/${G(r,"queueRunId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(t){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${G(t,"queueId")}/size`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(t){let r=await this._getSettings();return t=="-"||r.tenant_handle===t}async _ownerConflictError(t,r){let n=await this._getSettings();return new Error(`Cannot ${t} for another tenant.
|
|
138
|
+
|
|
139
|
+
Current tenant: ${n.tenant_handle}
|
|
140
|
+
|
|
141
|
+
Requested tenant: ${r}`)}async _getLatestCommitHash(t){let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/commits/${t}/?limit=1&offset=0`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(i,"get latest commit hash"),i})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(t,r){let[n,i,a]=Ee(t),s=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:s});return await O(c,`${r?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(t){let[r,n,i]=Ee(t);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(t){return!!await this.getPrompt(t)}async likePrompt(t){return this._likeOrUnlikePrompt(t,!0)}async unlikePrompt(t){return this._likeOrUnlikePrompt(t,!1)}async*listCommits(t){let[r,n,i]=Ee(t);for await(let a of this._getPaginated(`/commits/${r}/${n}/`,new URLSearchParams,s=>s.commits))yield*a}async*listPrompts(t){let r=new URLSearchParams;r.append("sort_field",t?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!t?.isArchived).toString()),t?.isPublic!==void 0&&r.append("is_public",t.isPublic.toString()),t?.query&&r.append("query",t.query);for await(let n of this._getPaginated("/repos",r,i=>i.repos))yield*n}async getPrompt(t){let[r,n,i]=Ee(t),s=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await O(o,"get prompt"),o)}))?.json();return s?.repo?s.repo:null}async createPrompt(t,r){let n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
|
|
142
|
+
|
|
143
|
+
creating a LangChain Hub handle.
|
|
144
|
+
You can add a handle by creating a public prompt at:
|
|
145
|
+
|
|
146
|
+
https://smith.langchain.com/prompts`);let[i,a,s]=Ee(t);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError("create a prompt",i);let o={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(o),u=await this.caller.call(async()=>{let d=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 O(d,"create prompt"),d}),{repo:l}=await u.json();return l}async createCommit(t,r,n){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");let[i,a,s]=Ee(t),o=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${i}/${a}`):n?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(r)),parent_commit:o,...n?.description!==void 0&&{description:n.description}},u=JSON.stringify(c),d=await(await this.caller.call(async()=>{let f=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 O(f,"create commit"),f})).json();return this._getPromptUrl(`${i}/${a}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(t,r=[]){return this._updateExamplesMultipart(t,r)}async _updateExamplesMultipart(t,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let s of r){let o=s.id,c={...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split}},u=Se(c,`Serializing body for example with id: ${o}`),l=new Blob([u],{type:"application/json"});if(n.append(o,l),s.inputs){let d=Se(s.inputs,`Serializing inputs for example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.inputs`,f)}if(s.outputs){let d=Se(s.outputs,`Serializing outputs whle updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.outputs`,f)}if(s.attachments)for(let[d,f]of Object.entries(s.attachments)){let p,h;Array.isArray(f)?[p,h]=f:(p=f.mimeType,h=f.data);let m=new Blob([h],{type:`${p}; length=${h.byteLength}`});n.append(`${o}.attachment.${d}`,m)}if(s.attachments_operations){let d=Se(s.attachments_operations,`Serializing attachments while updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.attachments_operations`,f)}}let i=t??r[0]?.dataset_id;return(await this.caller.call(async()=>{let s=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 O(s,"update examples"),s})).json()}async uploadExamplesMultipart(t,r=[]){return this._uploadExamplesMultipart(t,r)}async _uploadExamplesMultipart(t,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 s=(a.id??tr()).toString(),o={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split},...a.source_run_id&&{source_run_id:a.source_run_id},...a.use_source_run_io&&{use_source_run_io:a.use_source_run_io},...a.use_source_run_attachments&&{use_source_run_attachments:a.use_source_run_attachments}},c=Se(o,`Serializing body for uploaded example with id: ${s}`),u=new Blob([c],{type:"application/json"});if(n.append(s,u),a.inputs){let l=Se(a.inputs,`Serializing inputs for uploaded example with id: ${s}`),d=new Blob([l],{type:"application/json"});n.append(`${s}.inputs`,d)}if(a.outputs){let l=Se(a.outputs,`Serializing outputs for uploaded example with id: ${s}`),d=new Blob([l],{type:"application/json"});n.append(`${s}.outputs`,d)}if(a.attachments)for(let[l,d]of Object.entries(a.attachments)){let f,p;Array.isArray(d)?[f,p]=d:(f=d.mimeType,p=d.data);let h=new Blob([p],{type:`${f}; length=${p.byteLength}`});n.append(`${s}.attachment.${l}`,h)}}return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${t}/examples`)}`,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await O(a,"upload examples"),a})).json()}async updatePrompt(t,r){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");let[n,i]=Ee(t);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 s=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:s});return await O(c,"update prompt"),c})).json()}async deletePrompt(t){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");let[r,n,i]=Ee(t);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(s,"delete prompt"),s})).json()}_getPromptCacheKey(t,r){return`${t}${r?":with_model":""}`}async _fetchPromptFromApi(t,r){let[n,i,a]=Ee(t),o=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 O(c,"pull prompt commit"),c})).json();return{owner:n,repo:i,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples,hub_model_config:o.model_config,hub_model_provider:o.model_provider}}async pullPromptCommit(t,r){ng(t,r?.dangerouslyPullPublicPrompt);let n=this._fetchPromptFromApi.bind(this,t,r);if(!r?.skipCache&&this._promptCache){let i=this._getPromptCacheKey(t,r?.includeModel),a=this._promptCache.get(i,n);if(a)return a;let s=await n();return this._promptCache.set(i,s,n),s}return this._fetchPromptFromApi(t,r)}async _pullPrompt(t,r){let n=await this.pullPromptCommit(t,{includeModel:r?.includeModel,skipCache:r?.skipCache,dangerouslyPullPublicPrompt:r?.dangerouslyPullPublicPrompt});return JSON.stringify(n.manifest)}async pushPrompt(t,r){return await this.promptExists(t)?r&&Object.keys(r).some(i=>i!=="object")&&await this.updatePrompt(t,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(t,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(t,r?.object,{parentCommitHash:r?.parentCommitHash,description:r?.commitDescription}):await this._getPromptUrl(t)}async agentExists(t){let[r,n]=Ee(t);return this._repoExists(r,n)}async skillExists(t){let[r,n]=Ee(t);return this._repoExists(r,n)}async pullAgent(t,r){return await this._pullDirectory(t,"agent",r?.version)}async pullSkill(t,r){return await this._pullDirectory(t,"skill",r?.version)}async pushAgent(t,r){return this._pushDirectory(t,"agent",r)}async pushSkill(t,r){return this._pushDirectory(t,"skill",r)}async deleteAgent(t){return this._deleteDirectory(t)}async deleteSkill(t){return this._deleteDirectory(t)}async*listAgents(t){yield*this._listReposByType("agent",t)}async*listSkills(t){yield*this._listReposByType("skill",t)}async*_listReposByType(t,r){let n=new URLSearchParams;n.append("repo_type",t),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(t,r,n){let[i,a,s]=Ee(t),o=n??(s!=="latest"?s:void 0),c=new URL(`${this.apiUrl}/v1/platform/hub/repos/${i}/${a}/directories`);return c.searchParams.set("repo_type",r),o&&c.searchParams.set("commit",o),await(await this.caller.call(async()=>{let l=await this._fetch(c.toString(),{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(l,"pull directory"),l})).json()}async _pushDirectory(t,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]=Ee(t);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 d=/^[a-z][a-z0-9-_]*$/;if(!d.test(a))throw new Error(`Invalid repo_handle ${JSON.stringify(a)}: must match ${d}`);await this._createRepo(a,r,n)}let s={files:n.files};n.parentCommit&&(s.parent_commit=n.parentCommit);let u=(await(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/v1/platform/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(s)});return await O(d,`push ${r}`),d})).json()).commit.commit_hash,l=i;return i==="-"&&(l=(await this._getSettings()).tenant_handle||i),`${this.getHostUrl()}/hub/${l}/${a}:${u.slice(0,8)}`}async _deleteDirectory(t){let[r,n]=Ee(t);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete",r);await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/v1/platform/hub/repos/${r}/${n}/directories`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(i,"delete directory"),i})}async _repoExists(t,r){try{return await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(n,"check repo exists"),n}),!0}catch(n){if(vi(n))return!1;throw n}}async _createRepo(t,r,n){let i={repo_handle:t,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 O(a,`create ${r}`),a})}catch(a){if(Ml(a))return;throw a}}async _updateRepoMetadata(t,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/${t}/${r}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await O(a,"update repo metadata"),a})}async clonePublicDataset(t,r={}){let{sourceApiUrl:n=this.apiUrl,datasetName:i}=r,[a,s]=this.parseTokenOrUrl(t,n),o=new e({apiUrl:a,apiKey:"placeholder"}),c=await o.readSharedDataset(s),u=i||c.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}let l=await o.listSharedExamples(s),d=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:l.map(f=>f.inputs),outputs:l.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:d.id})}catch(f){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),f}}parseTokenOrUrl(t,r,n=2,i="dataset"){try{return G(t),[r,t]}catch{}try{let s=new URL(t).pathname.split("/").filter(o=>o!=="");if(s.length>=n){let o=s[s.length-n];return[r,o]}else throw new Error(`Invalid public ${i} URL: ${t}`)}catch{throw new Error(`Invalid public ${i} URL or token: ${t}`)}}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(t=>setTimeout(t,1));this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:t})=>t),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await El()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}toString(){let t=[`apiUrl=${JSON.stringify(this.apiUrl)}`];return this.webUrl!==void 0&&t.push(`webUrl=${JSON.stringify(this.webUrl)}`),this.workspaceId!==void 0&&t.push(`workspaceId=${JSON.stringify(this.workspaceId)}`),`[LangSmithClient ${t.join(" ")}]`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}};Object.defineProperty(jt,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function Kl(e){return"dataset_id"in e||"dataset_name"in e}var Xl=e=>e!==void 0?e:!!["TRACING_V2","TRACING"].find(r=>ne(r)==="true");var gt=Symbol.for("lc:context_variables");var Ai=Symbol.for("langsmith:replica_trace_roots");function Fs(e,t){if(gt in e)return e[gt][t]}function Ql(e,t,r){let n=gt in e?e[gt]:{};n[t]=r,e[gt]=n}var mn=36,dg="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function ed(e){let r=Object.keys(e).sort().map(n=>`${n}:${e[n]??""}`).join("|");return ts(r,dg)}function fg(e){return e.replace(/[-:.]/g,"")}function rd(e,t=1){let r=t.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(e).toISOString().slice(0,-1)}${r}Z`}function Hs(e,t,r=1){let n=rd(e,r);return{dottedOrder:fg(n)+t,microsecondPrecisionDatestring:n}}var pg=new Set(["projectName","updates","reroot"]);function hg(e){let t={};for(let r of Object.keys(e))pg.has(r)&&(t[r]=e[r]);return t}var ki=class e{constructor(t,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=t,this.tags=r,this.project_name=n,this.replicas=i}static fromHeader(t){let r=t.split(","),n={},i=[],a,s;for(let o of r){let[c,u]=o.split("="),l=decodeURIComponent(u);c==="langsmith-metadata"?n=JSON.parse(l):c==="langsmith-tags"?i=l.split(","):c==="langsmith-project"?a=l:c==="langsmith-replicas"&&(s=JSON.parse(l).map(f=>Array.isArray(f)?f:hg(f)))}return new e(n,i,a,s)}toHeader(){let t=[];return this.metadata&&Object.keys(this.metadata).length>0&&t.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&t.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&t.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),t.join(",")}},et=class e{constructor(t){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}),nd(t)){Object.assign(this,{...t});return}let r=e.getDefaultConfig(),{metadata:n,...i}=t,a=i.client??e.getSharedClient(),s={...n,...i?.extra?.metadata};if(i.extra={...i.extra,metadata:s},"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=rd(this.start_time,this.execution_order)),this.id||(this.id=ri(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=yg(this.replicas),!this.dotted_order){let{dottedOrder:o}=Hs(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+o:this.dotted_order=o}}set metadata(t){this.extra={...this.extra,metadata:{...this.extra?.metadata,...t}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let t=Date.now();return{run_type:"chain",project_name:un(),child_runs:[],api_url:pe("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:pe("LANGCHAIN_API_KEY"),caller_options:{},start_time:t,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return e.sharedClient||(e.sharedClient=new jt),e.sharedClient}createChild(t){let r=this.child_execution_order+1,n=this.replicas?.map(f=>{let{reroot:p,...h}=f;return h}),i=t.replicas??n,a=new e({...t,parent_run:this,project_name:this.project_name,replicas:i,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r}),s=this.extra?.metadata??{},o=a.extra?.metadata??{};Object.keys(s).length>0&&(a.extra={...a.extra,metadata:{...s,...o}}),gt in this&&(a[gt]=this[gt]);let c=Symbol.for("lc:child_config"),u=t.extra?.[c]??this.extra[c];if(gg(u)){let f={...u},p=mg(f.callbacks)?f.callbacks.copy?.():void 0;p&&(Object.assign(p,{_parentRunId:a.id}),p.handlers?.find(id)?.updateFromRunTree?.(a),f.callbacks=p),a.extra[c]=f}let l=new Set,d=this;for(;d!=null&&!l.has(d.id);)l.add(d.id),d.child_execution_order=Math.max(d.child_execution_order,r),d=d.parent_run;return this.child_runs.push(a),a}async end(t,r,n=Date.now(),i){this.outputs=this.outputs??t,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(t,r,n=!0){let i=t.extra??{};if(i?.runtime?.library===void 0&&(i.runtime||(i.runtime={}),r))for(let[o,c]of Object.entries(r))i.runtime[o]||(i.runtime[o]=c);let a=t.parent_run?.id??t.parent_run_id,s;return n?s=[]:s=t.child_runs.map(o=>this._convertToCreate(o,r,n)),{id:t.id,name:t.name,start_time:t._serialized_start_time??t.start_time,end_time:t.end_time,run_type:t.run_type,reference_example_id:t.reference_example_id,extra:i,serialized:t.serialized,error:t.error,inputs:t.inputs,outputs:t.outputs,session_name:t.project_name,child_runs:s,parent_run_id:a,trace_id:t.trace_id,dotted_order:t.dotted_order,tags:t.tags,attachments:t.attachments,events:t.events}}_sliceParentId(t,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(-mn)===t){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(-mn):r.trace_id=r.id}}r.parent_run_id===t&&(r.parent_run_id=void 0)}_setReplicaTraceRoot(t,r){let n=Fs(this,Ai)??{};n[t]=r,Ql(this,Ai,n);for(let i of this.child_runs)i._setReplicaTraceRoot(t,r)}_remapForProject(t){let{projectName:r,runtimeEnv:n,excludeChildRuns:i=!0,reroot:a=!1,distributedParentId:s,apiUrl:o,apiKey:c,workspaceId:u}=t,l=this._convertToCreate(this,n,i);if(r===this.project_name)return{...l,session_name:r};if(a){if(s)this._sliceParentId(s,l);else if(l.parent_run_id=void 0,l.dotted_order){let v=l.dotted_order.split(".");v.length>0&&(l.dotted_order=v[v.length-1],l.trace_id=l.id)}let x=ed({projectName:r,apiUrl:o,apiKey:c,workspaceId:u});this._setReplicaTraceRoot(x,l.id)}let d;if(!a){let x=Fs(this,Ai)??{},v=ed({projectName:r,apiUrl:o,apiKey:c,workspaceId:u});if(d=x[v],d&&(l.trace_id=d,l.dotted_order)){let I=l.dotted_order.split("."),k=null;for(let j=0;j<I.length;j++)if(I[j].slice(-mn)===d){k=j;break}if(k!==null){let j=I.slice(k);l.dotted_order=j.join(".")}}}let f=l.id,p=ln(f,r),h;l.trace_id?h=ln(l.trace_id,r):h=p;let m;l.parent_run_id&&(m=ln(l.parent_run_id,r));let b;return l.dotted_order&&(b=l.dotted_order.split(".").map(I=>{let k=I.slice(-mn),j=ln(k,r);return I.slice(0,-mn)+j}).join(".")),{...l,id:p,trace_id:h,parent_run_id:m,dotted_order:b,session_name:r}}async postRun(t=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let r=ci();if(this.replicas&&this.replicas.length>0)for(let{projectName:n,apiKey:i,apiUrl:a,workspaceId:s,reroot:o,client:c}of this.replicas){let u=this._remapForProject({projectName:n??this.project_name,runtimeEnv:r,excludeChildRuns:!0,reroot:o,distributedParentId:this.distributedParentId,apiUrl:a,apiKey:i,workspaceId:s});await(c??this.client).createRun(u,{apiKey:i,apiUrl:a,workspaceId:s})}else{let n=this._convertToCreate(this,r,t);await this.client.createRun(n)}if(!t){rr("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(t){if(this.replicas&&this.replicas.length>0)for(let{projectName:r,apiKey:n,apiUrl:i,workspaceId:a,updates:s,reroot:o,client:c}of this.replicas){let u=this._remapForProject({projectName:r??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:o,distributedParentId:this.distributedParentId,apiUrl:i,apiKey:n,workspaceId:a}),l={id:u.id,name:u.name,run_type:u.run_type,start_time:u.start_time,outputs:u.outputs,error:u.error,parent_run_id:u.parent_run_id,session_name:u.session_name,reference_example_id:u.reference_example_id,end_time:u.end_time,dotted_order:u.dotted_order,trace_id:u.trace_id,events:u.events,tags:u.tags,extra:u.extra,attachments:this.attachments,...s};t?.excludeInputs||(l.inputs=u.inputs),await(c??this.client).updateRun(u.id,l,{apiKey:n,apiUrl:i,workspaceId:a})}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};t?.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(t){this.events||(this.events=[]),typeof t=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:t}):this.events.push({...t,time:t.time??new Date().toISOString()})}static fromRunnableConfig(t,r){let n=t?.callbacks,i,a,s,o=Xl();if(n){let u=n?.getParentRunId?.()??"",l=n?.handlers?.find(d=>d?.name=="langchain_tracer");i=l?.getRun?.(u),a=l?.projectName,s=l?.client,o=o||!!l}return i?new e({name:i.name,id:i.id,trace_id:i.trace_id,dotted_order:i.dotted_order,client:s,tracingEnabled:o,project_name:a,tags:[...new Set((i?.tags??[]).concat(t?.tags??[]))],extra:{metadata:{...i?.extra?.metadata,...t?.metadata}}}).createChild(r):new e({...r,client:s,tracingEnabled:o,project_name:a})}static fromDottedOrder(t){return this.fromHeaders({"langsmith-trace":t})}static fromHeaders(t,r){let n="get"in t&&typeof t.get=="function"?{"langsmith-trace":t.get("langsmith-trace"),baggage:t.get("baggage")}:t,i=n["langsmith-trace"];if(!i||typeof i!="string")return;let a=i.trim(),s=a.split(".").map(l=>{let[d,f]=l.split("Z");return{strTime:d,time:Date.parse(d+"Z"),uuid:f}}),o=s[0].uuid,c={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:s.at(-1)?.uuid,trace_id:o,dotted_order:a};if(n.baggage&&typeof n.baggage=="string"){let l=ki.fromHeader(n.baggage);c.metadata=l.metadata,c.tags=l.tags,c.project_name=l.project_name,c.replicas=l.replicas}let u=new e(c);return u.distributedParentId=u.id,u}toHeaders(t){let r={"langsmith-trace":this.dotted_order,baggage:new ki(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(t)for(let[n,i]of Object.entries(r))t.set(n,i);return r}};Object.defineProperty(et,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function nd(e){return e!=null&&typeof e.createChild=="function"&&typeof e.postRun=="function"}function id(e){return typeof e=="object"&&e!=null&&typeof e.name=="string"&&e.name==="langchain_tracer"}function td(e){return Array.isArray(e)&&e.some(t=>id(t))}function mg(e){return typeof e=="object"&&e!=null&&Array.isArray(e.handlers)}function gg(e){let t=e?.callbacks;return e!=null&&typeof t=="object"&&(td(t?.handlers)||td(t))}function _g(){let e=pe("LANGSMITH_RUNS_ENDPOINTS");if(!e)return[];try{let t=JSON.parse(e);if(Array.isArray(t)){let r=[];for(let n of t){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key})}return r}else if(typeof t=="object"&&t!==null){wg(t);let r=[];for(let[n,i]of Object.entries(t)){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 t}`),[]}catch(t){if(Ll(t))throw t;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"),[]}}function yg(e){return e?e.map(t=>Array.isArray(t)?{projectName:t[0],updates:t[1]}:t):_g()}function wg(e){if(Object.keys(e).length>0&&ne("ENDPOINT"))throw new wi}var qS=L({BaseTracer:()=>tt,isBaseTracer:()=>ar}),bg=e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e};function Vs(e,t){if(e)return new et({...e,start_time:e._serialized_start_time??e.start_time,parent_run:Vs(t),child_runs:e.child_runs.map(r=>Vs(r)).filter(r=>r!==void 0),extra:{...e.extra,runtime:Wa()},tracingEnabled:!1})}function Gs(e,t){return e&&!Array.isArray(e)&&typeof e=="object"?e:{[t]:e}}function ar(e){return typeof e._addRunToRunMap=="function"}var tt=class extends er{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?bg(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
|
|
147
|
+
|
|
148
|
+
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){let{dottedOrder:t,microsecondPrecisionDatestring:r}=Hs(new Date(e.start_time).getTime(),e.id,e.execution_order),n={...e},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,t].join("."),n._serialized_start_time=r)):n.parent_run_id=void 0:(n.trace_id=n.id,n.dotted_order=t,n._serialized_start_time=r),this.usesRunTreeMap){let a=Vs(n,i);a!==void 0&&this.runTreeMap.set(n.id,a)}else this.runMap.set(n.id,n);return n}async _endTrace(e){let t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){let t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,n,i,a,s,o){let c=this._getExecutionOrder(n),u=Date.now(),l=s?{...i,metadata:s}:i,d={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:a||[]};return this._addRunToRunMap(d)}async handleLLMStart(e,t,r,n,i,a,s,o){let c=this.getRunById(r)??this._createRunForLLMStart(e,t,r,n,i,a,s,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,r,n,i,a,s,o){let c=this._getExecutionOrder(n),u=Date.now(),l=s?{...i,metadata:s}:i,d={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:a||[]};return this._addRunToRunMap(d)}async handleChatModelStart(e,t,r,n,i,a,s,o){let c=this.getRunById(r)??this._createRunForChatModelStart(e,t,r,n,i,a,s,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,r,n,i){let a=this.getRunById(t);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=e,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(e,t,r,n,i){let a=this.getRunById(t);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),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(e,t,r,n,i,a,s,o,c){let u=this._getExecutionOrder(n),l=Date.now(),d={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:t,execution_order:u,child_execution_order:u,run_type:s??"chain",child_runs:[],extra:a?{...c,metadata:a}:{...c},tags:i||[]};return this._addRunToRunMap(d)}async handleChainStart(e,t,r,n,i,a,s,o){let c=this.getRunById(r)??this._createRunForChainStart(e,t,r,n,i,a,s,o);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,r,n,i){let a=this.getRunById(t);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=Gs(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=Gs(i.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(e,t,r,n,i){let a=this.getRunById(t);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=Gs(i.inputs,"input")),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(e,t,r,n,i,a,s){let o=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:s??e.id[e.id.length-1],parent_run_id:n,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleToolStart(e,t,r,n,i,a,s){let o=this.getRunById(r)??this._createRunForToolStart(e,t,r,n,i,a,s);return await this.onRunCreate?.(o),await this.onToolStart?.(o),o}async handleToolEnd(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="chain")return;let n=r;n.actions=n.actions||[],n.actions.push(e),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(r)}async handleAgentEnd(e,t){let r=this.getRunById(t);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(e,t,r,n,i,a,s){let o=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:s??e.id[e.id.length-1],parent_run_id:n,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(e,t,r,n,i,a,s){let o=this.getRunById(r)??this._createRunForRetrieverStart(e,t,r,n,i,a,s);return await this.onRunCreate?.(o),await this.onRetrieverStart?.(o),o}async handleRetrieverEnd(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(e,t){let r=this.getRunById(t);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(r))}async handleLLMNewToken(e,t,r,n,i,a){let s=this.getRunById(r);if(!s||s?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return s.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:a?.chunk}}),await this.onLLMNewToken?.(s,e,{chunk:a?.chunk}),s}};var XS=L({ConsoleCallbackHandler:()=>Ii}),sd={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 Ce(e,t){return`${e.open}${t}${e.close}`}function Ze(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function ad(e){return typeof e=="string"?e.trim():e==null?e:Ze(e,e.toString())}function Dt(e){if(!e.end_time)return"";let t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}var{color:Me}=sd,Ii=class extends tt{name="console_callback_handler";persistRun(e){return Promise.resolve()}getParents(e){let t=[],r=e;for(;r.parent_run_id;){let n=this.runMap.get(r.parent_run_id);if(n)t.push(n),r=n;else break}return t}getBreadcrumbs(e){let t=[...this.getParents(e).reverse(),e].map((r,n,i)=>{let a=`${r.execution_order}:${r.run_type}:${r.name}`;return n===i.length-1?Ce(sd.bold,a):a}).join(" > ");return Ce(Me.grey,t)}onChainStart(e){let t=this.getBreadcrumbs(e);console.log(`${Ce(Me.green,"[chain/start]")} [${t}] Entering Chain run with input: ${Ze(e.inputs,"[inputs]")}`)}onChainEnd(e){let t=this.getBreadcrumbs(e);console.log(`${Ce(Me.cyan,"[chain/end]")} [${t}] [${Dt(e)}] Exiting Chain run with output: ${Ze(e.outputs,"[outputs]")}`)}onChainError(e){let t=this.getBreadcrumbs(e);console.log(`${Ce(Me.red,"[chain/error]")} [${t}] [${Dt(e)}] Chain run errored with error: ${Ze(e.error,"[error]")}`)}onLLMStart(e){let t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(n=>n.trim())}:e.inputs;console.log(`${Ce(Me.green,"[llm/start]")} [${t}] Entering LLM run with input: ${Ze(r,"[inputs]")}`)}onLLMEnd(e){let t=this.getBreadcrumbs(e);console.log(`${Ce(Me.cyan,"[llm/end]")} [${t}] [${Dt(e)}] Exiting LLM run with output: ${Ze(e.outputs,"[response]")}`)}onLLMError(e){let t=this.getBreadcrumbs(e);console.log(`${Ce(Me.red,"[llm/error]")} [${t}] [${Dt(e)}] LLM run errored with error: ${Ze(e.error,"[error]")}`)}onToolStart(e){let t=this.getBreadcrumbs(e);console.log(`${Ce(Me.green,"[tool/start]")} [${t}] Entering Tool run with input: "${ad(e.inputs.input)}"`)}onToolEnd(e){let t=this.getBreadcrumbs(e);console.log(`${Ce(Me.cyan,"[tool/end]")} [${t}] [${Dt(e)}] Exiting Tool run with output: "${ad(e.outputs?.output)}"`)}onToolError(e){let t=this.getBreadcrumbs(e);console.log(`${Ce(Me.red,"[tool/error]")} [${t}] [${Dt(e)}] Tool run errored with error: ${Ze(e.error,"[error]")}`)}onRetrieverStart(e){let t=this.getBreadcrumbs(e);console.log(`${Ce(Me.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${Ze(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){let t=this.getBreadcrumbs(e);console.log(`${Ce(Me.cyan,"[retriever/end]")} [${t}] [${Dt(e)}] Exiting Retriever run with output: ${Ze(e.outputs,"[outputs]")}`)}onRetrieverError(e){let t=this.getBreadcrumbs(e);console.log(`${Ce(Me.red,"[retriever/error]")} [${t}] [${Dt(e)}] Retriever run errored with error: ${Ze(e.error,"[error]")}`)}onAgentAction(e){let t=e,r=this.getBreadcrumbs(e);console.log(`${Ce(Me.blue,"[agent/action]")} [${r}] Agent selected action: ${Ze(t.actions[t.actions.length-1],"[action]")}`)}};var Zs,Ci=()=>(Zs===void 0&&(Zs=new jt(Qe("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),Zs);var Ws=class{getStore(){}run(t,r){return r()}},qs=Symbol.for("ls:tracing_async_local_storage"),vg=new Ws,Js=class{getInstance(){return globalThis[qs]??vg}initializeGlobalInstance(t){globalThis[qs]===void 0&&(globalThis[qs]=t)}},xg=new Js;function od(e=!1){let t=xg.getInstance().getStore();if(!e&&t===void 0)throw new Error(`Could not get the current run tree.
|
|
149
|
+
|
|
150
|
+
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return t}function Oi(e){return typeof e=="function"&&"langsmith:traceable"in e}var _T=L({LangChainTracer:()=>Fr,OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS:()=>Ys}),Ys=new Set(["ls_agent_type"]);function Eg(e){let t;for(let r of e)for(let n of r)Rr.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(t=Fn(t,n.message.usage_metadata));return t}var Fr=class Ks extends tt{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;tracingMetadata;tracingTags=[];constructor(t={}){super(t),this.fields=t;let{exampleId:r,projectName:n,client:i,replicas:a,metadata:s,tags:o}=t;this.projectName=n??un(),this.replicas=a,this.exampleId=r,this.client=i??Ci(),this.tracingMetadata=s?{...s}:void 0,this.tracingTags=o??[];let c=Ks.getTraceableRunTree();c&&this.updateFromRunTree(c)}async persistRun(t){}async onRunCreate(t){cd(this,t),t.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(t.id)?.postRun()}async onRunUpdate(t){cd(this,t);let r=this.getRunTreeWithTracingConfig(t.id);t.extra?.lc_defers_inputs?await r?.postRun():await r?.patchRun()}onLLMEnd(t){let r=t.outputs;if(r?.generations){let n=Eg(r.generations);if(n!==void 0){t.extra=t.extra??{};let i=t.extra.metadata??{};i.usage_metadata=n,t.extra.metadata=i}}}copyWithTracingConfig({metadata:t,tags:r}){let n;if(t===void 0)n=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)n={...t};else{n={...this.tracingMetadata};for(let[s,o]of Object.entries(t))(!Object.prototype.hasOwnProperty.call(n,s)||Ys.has(s))&&(n[s]=o)}let i=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],a=new Ks({...this.fields,metadata:n,tags:i});return a.runMap=this.runMap,a.runTreeMap=this.runTreeMap,a}getRun(t){return this.runTreeMap.get(t)}updateFromRunTree(t){this.runTreeMap.set(t.id,t);let r=t,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=t.client??this.client,this.replicas=t.replicas??this.replicas,this.projectName=t.project_name??this.projectName,this.exampleId=t.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(t){let r=this.runTreeMap.get(t);if(r)return new et({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return od(!0)}catch{return}}static[Symbol.hasInstance](t){if(typeof t!="object"||t===null)return!1;let r=t;return"name"in r&&r.name==="langchain_tracer"&&"copyWithTracingConfig"in r&&typeof r.copyWithTracingConfig=="function"&&"getRunTreeWithTracingConfig"in r&&typeof r.getRunTreeWithTracingConfig=="function"}};function cd(e,t){if(e.tracingMetadata){t.extra??={};let r=t.extra.metadata??{},n=!1;for(let[i,a]of Object.entries(e.tracingMetadata))(!Object.prototype.hasOwnProperty.call(r,i)||Ys.has(i))&&r[i]!==a&&(r[i]=a,n=!0);n&&(t.extra.metadata=r)}e.tracingTags.length>0&&(t.tags=Array.from(new Set([...t.tags??[],...e.tracingTags])))}var ud=Symbol.for("ls:tracing_async_local_storage"),Ut=Symbol.for("lc:context_variables"),ld=e=>{globalThis[ud]=e},zt=()=>globalThis[ud];var Ri=jn(_i(),1),sr;function Sg(){return new("default"in Ri.default?Ri.default.default:Ri.default)({autoStart:!0,concurrency:1})}function Tg(){return typeof sr>"u"&&(sr=Sg()),sr}async function ae(e,t){if(t===!0){let r=zt();r!==void 0?await r.run(void 0,async()=>e()):await e()}else sr=Tg(),sr.add(async()=>{let r=zt();r!==void 0?await r.run(void 0,async()=>e()):await e()})}async function dd(){let e=Ci();await Promise.allSettled([typeof sr<"u"?sr.onIdle():Promise.resolve(),e.awaitPendingTraceBatches()])}var TT=L({awaitAllCallbacks:()=>dd,consumeCallback:()=>ae});var fd=e=>e!==void 0?e:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(t=>Qe(t)==="true");function Xs(e){let t=zt();if(t!==void 0)return t.getStore()?.[Ut]?.[e]}var Ag=Symbol("lc:configure_hooks"),pd=()=>Xs(Ag)||[];var GT=L({BaseCallbackManager:()=>hd,BaseRunManager:()=>yn,CallbackManager:()=>rt,CallbackManagerForChainRun:()=>gd,CallbackManagerForLLMRun:()=>Qs,CallbackManagerForRetrieverRun:()=>md,CallbackManagerForToolRun:()=>_d,ensureHandler:()=>Hr,parseCallbackConfigArg:()=>_n});function _n(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}var hd=class{setHandler(e){return this.setHandlers([e])}},yn=class{constructor(e,t,r,n,i,a,s,o){this.runId=e,this.handlers=t,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=i,this.metadata=a,this.inheritableMetadata=s,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>ae(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleCustomEvent(e,t,r,n,i){await Promise.all(this.handlers.map(a=>ae(async()=>{try{await a.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(s){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${s}`),a.raiseError)throw s}},a.awaitHandlers)))}},md=class extends yn{getChild(e){let t=new rt(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>ae(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw r}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>ae(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${r}`),t.raiseError)throw e}},t.awaitHandlers)))}},Qs=class extends yn{async handleLLMNewToken(e,t,r,n,i,a){await Promise.all(this.handlers.map(s=>ae(async()=>{if(!s.ignoreLLM)try{await s.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMNewToken: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleChatModelStreamEvent(e){await Promise.all(this.handlers.map(t=>ae(async()=>{if(!t.ignoreLLM)try{await t.handleChatModelStreamEvent?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChatModelStreamEvent: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleLLMError(e,t,r,n,i){await Promise.all(this.handlers.map(a=>ae(async()=>{if(!a.ignoreLLM)try{await a.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(s){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMError: ${s}`),a.raiseError)throw s}},a.awaitHandlers)))}async handleLLMEnd(e,t,r,n,i){await Promise.all(this.handlers.map(a=>ae(async()=>{if(!a.ignoreLLM)try{await a.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(s){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMEnd: ${s}`),a.raiseError)throw s}},a.awaitHandlers)))}},gd=class extends yn{getChild(e){let t=new rt(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,r,n,i){await Promise.all(this.handlers.map(a=>ae(async()=>{if(!a.ignoreChain)try{await a.handleChainError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(s){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainError: ${s}`),a.raiseError)throw s}},a.awaitHandlers)))}async handleChainEnd(e,t,r,n,i){await Promise.all(this.handlers.map(a=>ae(async()=>{if(!a.ignoreChain)try{await a.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(s){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainEnd: ${s}`),a.raiseError)throw s}},a.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>ae(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>ae(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}},_d=class extends yn{getChild(e){let t=new rt(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>ae(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleToolEvent(e){await Promise.all(this.handlers.map(t=>ae(async()=>{if(!t.ignoreAgent)try{await t.handleToolEvent?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if(t.raiseError)throw r}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>ae(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}},rt=class gn extends hd{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(t,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=t}getParentRunId(){return this._parentRunId}async handleLLMStart(t,r,n=void 0,i=void 0,a=void 0,s=void 0,o=void 0,c=void 0){return Promise.all(r.map(async(u,l)=>{let d=l===0&&n?n:Ge();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return ar(f)&&f._createRunForLLMStart(t,[u],d,this._parentRunId,a,this.tags,this.metadata,c),ae(async()=>{try{await f.handleLLMStart?.(t,[u],d,this._parentRunId,a,this.tags,this.metadata,c)}catch(p){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${p}`),f.raiseError)throw p}},f.awaitHandlers)})),new Qs(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(t,r,n=void 0,i=void 0,a=void 0,s=void 0,o=void 0,c=void 0){return Promise.all(r.map(async(u,l)=>{let d=l===0&&n?n:Ge();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return ar(f)&&f._createRunForChatModelStart(t,[u],d,this._parentRunId,a,this.tags,this.metadata,c),ae(async()=>{try{if(f.handleChatModelStart)await f.handleChatModelStart?.(t,[u],d,this._parentRunId,a,this.tags,this.metadata,c);else if(f.handleLLMStart){let p=Zn(u);await f.handleLLMStart?.(t,[p],d,this._parentRunId,a,this.tags,this.metadata,c)}}catch(p){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${p}`),f.raiseError)throw p}},f.awaitHandlers)})),new Qs(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(t,r,n=Ge(),i=void 0,a=void 0,s=void 0,o=void 0,c=void 0,u=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreChain)return ar(l)&&l._createRunForChainStart(t,r,n,this._parentRunId,this.tags,this.metadata,i,o,u),ae(async()=>{try{await l.handleChainStart?.(t,r,n,this._parentRunId,this.tags,this.metadata,i,o,u)}catch(d){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleChainStart: ${d}`),l.raiseError)throw d}},l.awaitHandlers)})),new gd(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(t,r,n=Ge(),i=void 0,a=void 0,s=void 0,o=void 0,c=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return ar(u)&&u._createRunForToolStart(t,r,n,this._parentRunId,this.tags,this.metadata,o),ae(async()=>{try{await u.handleToolStart?.(t,r,n,this._parentRunId,this.tags,this.metadata,o,c)}catch(l){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${l}`),u.raiseError)throw l}},u.awaitHandlers)})),new _d(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(t,r,n=Ge(),i=void 0,a=void 0,s=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return ar(c)&&c._createRunForRetrieverStart(t,r,n,this._parentRunId,this.tags,this.metadata,o),ae(async()=>{try{await c.handleRetrieverStart?.(t,r,n,this._parentRunId,this.tags,this.metadata,o)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new md(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(t,r,n,i,a){await Promise.all(this.handlers.map(s=>ae(async()=>{if(!s.ignoreCustomEvent)try{await s.handleCustomEvent?.(t,r,n,this.tags,this.metadata)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleCustomEvent: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}addHandler(t,r=!0){this.handlers.push(t),r&&this.inheritableHandlers.push(t)}removeHandler(t){this.handlers=this.handlers.filter(r=>r!==t),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==t)}setHandlers(t,r=!0){this.handlers=[],this.inheritableHandlers=[];for(let n of t)this.addHandler(n,r)}addTags(t,r=!0){this.removeTags(t),this.tags.push(...t),r&&this.inheritableTags.push(...t)}removeTags(t){this.tags=this.tags.filter(r=>!t.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!t.includes(r))}addMetadata(t,r=!0){this.metadata={...this.metadata,...t},r&&(this.inheritableMetadata={...this.inheritableMetadata,...t})}removeMetadata(t){for(let r of Object.keys(t))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(t=[],r=!0){let n=new gn(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 t)n.handlers.filter(a=>a.name==="console_callback_handler").some(a=>a.name===i.name)||n.addHandler(i,r);return n}static fromHandlers(t){class r extends er{name=Ge();constructor(){super(),Object.assign(this,t)}}let n=new this;return n.addHandler(new r),n}static configure(t,r,n,i,a,s,o){return this._configureSync(t,r,n,i,a,s,o)}static _configureSync(t,r,n,i,a,s,o){let c;(t||r)&&(Array.isArray(t)||!t?(c=new gn,c.setHandlers(t?.map(Hr)??[],!0)):c=t,c=c.copy(Array.isArray(r)?r.map(Hr):r?.handlers,!1));let u=Qe("LANGCHAIN_VERBOSE")==="true"||o?.verbose,l=Fr.getTraceableRunTree(),d=l?.tracingEnabled??fd();if(l?.tracingEnabled===!1&&c){let m=c.handlers.filter(b=>b.name==="langchain_tracer");for(let b of m)c.removeHandler(b)}let f=d||(Qe("LANGCHAIN_TRACING")??!1);if(u||f){if(c||(c=new gn),u&&!c.handlers.some(m=>m.name===Ii.prototype.name)){let m=new Ii;c.addHandler(m,!0)}if(f&&!c.handlers.some(m=>m.name==="langchain_tracer")&&d){let m=new Fr;c.addHandler(m,!0)}d&&l&&c._parentRunId===void 0&&(c._parentRunId=l.id,c.handlers.find(m=>m.name==="langchain_tracer")?.updateFromRunTree(l))}for(let{contextVar:m,inheritable:b=!0,handlerClass:x,envVar:v}of pd()){let I=v&&Qe(v)==="true"&&x,k,j=m!==void 0?Xs(m):void 0;j&&Ja(j)?k=j:I&&(k=new x({})),k!==void 0&&(c||(c=new gn),c.handlers.some(X=>X.name===k.name)||c.addHandler(k,b))}(n||i)&&c&&(c.addTags(n??[]),c.addTags(i??[],!1)),(a||s)&&c&&(c.addMetadata(a??{}),c.addMetadata(s??{},!1));let p=o?.tracerInheritableMetadata,h=o?.tracerInheritableTags;return c&&(p||h)&&(c.handlers=c.handlers.map(m=>m instanceof Fr?m.copyWithTracingConfig({metadata:p,tags:h}):m),c.inheritableHandlers=c.inheritableHandlers.map(m=>m instanceof Fr?m.copyWithTracingConfig({metadata:p,tags:h}):m)),c}};function Hr(e){return"name"in e?e:er.fromMethods(e)}var eo=class{getStore(){}run(e,t){return t()}enterWith(e){}},kg=new eo,yd=Symbol.for("lc:child_config"),Ig=class{getInstance(){return zt()??kg}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[yd]}runWithConfig(e,t,r){let n=rt._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),i=this.getInstance(),a=i.getStore(),s=n?.getParentRunId(),o=n?.handlers?.find(u=>u?.name==="langchain_tracer"),c;return o&&s?c=o.getRunTreeWithTracingConfig(s):r||(c=new et({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[yd]:e}),a!==void 0&&a[Ut]!==void 0&&(c===void 0&&(c={}),c[Ut]=a[Ut]),i.run(c,t)}initializeGlobalInstance(e){zt()===void 0&&ld(e)}},be=new Ig;var oA=L({AsyncLocalStorageProviderSingleton:()=>be,MockAsyncLocalStorage:()=>eo,_CONTEXT_VARIABLES_KEY:()=>Ut});var Cg=new Set(["api_key"]),Og=new Set(["string","number","boolean"]);function Rg(e){let t=e.configurable??{},r=e.metadata??{},n={};for(let[i,a]of Object.entries(t))!i.startsWith("__")&&!Object.prototype.hasOwnProperty.call(r,i)&&!Cg.has(i)&&Og.has(typeof a)&&(n[i]=a);return Object.keys(n).length>0?n:void 0}async function qe(e){return rt._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata,void 0,{tracerInheritableMetadata:e?Rg(e):void 0})}function wn(...e){let t={};for(let r of e.filter(n=>!!n))for(let n of Object.keys(r))if(n==="metadata")t[n]={...t[n],...r[n]};else if(n==="tags"){let i=t[n]??[];t[n]=[...new Set(i.concat(r[n]??[]))]}else if(n==="configurable")t[n]={...t[n],...r[n]};else if(n==="timeout")t.timeout===void 0?t.timeout=r.timeout:r.timeout!==void 0&&(t.timeout=Math.min(t.timeout,r.timeout));else if(n==="signal")t.signal===void 0?t.signal=r.signal:r.signal!==void 0&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if(n==="callbacks"){let i=t.callbacks,a=r.callbacks;if(Array.isArray(a))if(!i)t.callbacks=a;else if(Array.isArray(i))t.callbacks=i.concat(a);else{let s=i.copy();for(let o of a)s.addHandler(Hr(o),!0);t.callbacks=s}else if(a)if(!i)t.callbacks=a;else if(Array.isArray(i)){let s=a.copy();for(let o of i)s.addHandler(Hr(o),!0);t.callbacks=s}else t.callbacks=new rt(a._parentRunId,{handlers:i.handlers.concat(a.handlers),inheritableHandlers:i.inheritableHandlers.concat(a.inheritableHandlers),tags:Array.from(new Set(i.tags.concat(a.tags))),inheritableTags:Array.from(new Set(i.inheritableTags.concat(a.inheritableTags))),metadata:{...i.metadata,...a.metadata}})}else{let i=n;t[i]=r[i]??t[i]}return t}function Y(e){let t=be.getRunnableConfig(),r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){let{runId:n,runName:i,...a}=t;r=Object.entries(a).reduce((s,[o,c])=>(c!==void 0&&(s[o]=c),s),r)}if(e&&(r=Object.entries(e).reduce((n,[i,a])=>(a!==void 0&&(n[i]=a),n),r)),r?.configurable&&typeof r.configurable.model=="string"&&r.metadata?.model===void 0&&(r.metadata||(r.metadata={}),r.metadata.model=r.configurable.model),r.timeout!==void 0){if(r.timeout<=0)throw new Error("Timeout must be a positive number");let n=r.timeout,i=AbortSignal.timeout(n);r.metadata||(r.metadata={}),r.metadata.timeoutMs===void 0&&(r.metadata.timeoutMs=n),r.signal!==void 0?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,i])):r.signal=i,delete r.timeout}return r}function le(e={},{callbacks:t,maxConcurrency:r,recursionLimit:n,runName:i,configurable:a,runId:s}={}){let o=Y(e);return t!==void 0&&(delete o.runName,o.callbacks=t),n!==void 0&&(o.recursionLimit=n),r!==void 0&&(o.maxConcurrency=r),i!==void 0&&(o.runName=i),a!==void 0&&(o.configurable={...o.configurable,...a}),s!==void 0&&delete o.runId,o}function We(e){if(e)return{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal,store:e.store}}async function nt(e,t){if(t===void 0)return e;let r;return Promise.race([e.catch(n=>{if(!t?.aborted)throw n}),new Promise((n,i)=>{r=()=>{i(Bt(t))},t.addEventListener("abort",r,{once:!0}),t.aborted&&i(Bt(t))})]).finally(()=>t.removeEventListener("abort",r))}function Bt(e){return e?.reason instanceof Error?e.reason:typeof e?.reason=="string"?new Error(e.reason):new Error("Aborted")}function se(e){if(typeof e!="object"||e===null)return!1;let t=e;if(!("_zod"in t))return!1;let r=t._zod;return typeof r=="object"&&r!==null&&"def"in r}function he(e){if(typeof e!="object"||e===null)return!1;let t=e;if(!("_def"in t)||"_zod"in t)return!1;let r=t._def;return typeof r=="object"&&r!=null&&"typeName"in r}function mA(e){return se(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),he(e)}function Gr(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(se(e)||he(e))}function Ng(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodLiteral"}function $g(e){return se(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="literal":!1}function gA(e){return!!(Ng(e)||$g(e))}async function _A(e,t){if(se(e))try{return{success:!0,data:await ka(e,t)}}catch(r){return{success:!1,error:r}}if(he(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function $i(e,t){if(se(e))return await ka(e,t);if(he(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function yA(e,t){if(se(e))try{return{success:!0,data:Ln(e,t)}}catch(r){return{success:!1,error:r}}if(he(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function wA(e,t){if(se(e))return Ln(e,t);if(he(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function vd(e){if(se(e))return $e.get(e)?.description;if(he(e)||"description"in e&&typeof e.description=="string")return e.description}function bA(e){if(!Gr(e))return!1;if(he(e)){let t=e._def;if(t.typeName==="ZodObject"){let r=e;return!r.shape||Object.keys(r.shape).length===0}if(t.typeName==="ZodRecord")return!0}if(se(e)){let t=e._zod.def;if(t.type==="object"){let r=e;return!r.shape||Object.keys(r.shape).length===0}if(t.type==="record")return!0}return typeof e=="object"&&e!==null&&!("shape"in e)}function Pi(e){return Gr(e)?he(e)?e._def.typeName==="ZodString":se(e)?e._zod.def.type==="string":!1:!1}function to(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodObject"}function _t(e){return se(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="object":!1}function ro(e){return se(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="array":!1}function Pg(e){return se(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="optional":!1}function Mg(e){return se(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="nullable":!1}function vA(e){return!!(to(e)||_t(e))}function wd(e){if(he(e))return e.shape;if(se(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function xA(e,t){if(he(e))return e.extend(t);if(se(e))return Aa.extend(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function EA(e){if(he(e))return e.partial();if(se(e))return Aa.partial(Ia,e,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ni(e,t=!1){if(to(e))return e.strict();if(_t(e)){let r=e._zod.def.shape;if(t)for(let[a,s]of Object.entries(e._zod.def.shape)){if(_t(s))r[a]=Ni(s,t);else if(ro(s)){let c=s._zod.def.element;_t(c)&&(c=Ni(c,t)),r[a]=dt(s,{...s._zod.def,element:c})}else r[a]=s;let o=$e.get(s);o&&$e.add(r[a],o)}let n=dt(e,{...e._zod.def,shape:r,catchall:Go(Fo)}),i=$e.get(e);return i&&$e.add(n,i),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function bd(e,t=!1){if(to(e))return e.passthrough();if(_t(e)){let r=e._zod.def.shape;if(t)for(let[a,s]of Object.entries(e._zod.def.shape)){if(_t(s))r[a]=bd(s,t);else if(ro(s)){let c=s._zod.def.element;_t(c)&&(c=bd(c,t)),r[a]=dt(s,{...s._zod.def,element:c})}else r[a]=s;let o=$e.get(s);o&&$e.add(r[a],o)}let n=dt(e,{...e._zod.def,shape:r,catchall:Ho(Bo)}),i=$e.get(e);return i&&$e.add(n,i),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function SA(e){if(he(e))try{let t=e.parse(void 0);return()=>t}catch{return}if(se(e))try{let t=Ln(e,void 0);return()=>t}catch{return}}function jg(e){return he(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function Lg(e){return se(e)&&e._zod.def.type==="pipe"}function or(e,t,r){let n=r.get(e);if(n!==void 0)return n;if(he(e))return jg(e)?or(e._def.schema,t,r):e;if(se(e)){let i=e;if(Lg(e)&&(i=or(e._zod.def.in,t,r)),t){if(_t(i)){let s={};for(let[o,c]of Object.entries(i._zod.def.shape))s[o]=or(c,t,r);i=dt(i,{...i._zod.def,shape:s})}else if(ro(i)){let s=or(i._zod.def.element,t,r);i=dt(i,{...i._zod.def,element:s})}else if(Pg(i)){let s=or(i._zod.def.innerType,t,r);i=dt(i,{...i._zod.def,innerType:s})}else if(Mg(i)){let s=or(i._zod.def.innerType,t,r);i=dt(i,{...i._zod.def,innerType:s})}}let a=$e.get(e);return a&&$e.add(i,a),r.set(e,i),i}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function xd(e,t=!1){return or(e,t,new WeakMap)}function TA(e,t){if(he(e)){let r=wd(e),n={};for(let[i,a]of Object.entries(r))t(i,a)?n[i]=a.optional():n[i]=a;return e.extend(n)}if(se(e)){let r=wd(e),n={...e._zod.def.shape};for(let[s,o]of Object.entries(r))t(s,o)&&(n[s]=new Ia({type:"optional",innerType:o}));let i=dt(e,{...e._zod.def,shape:n}),a=$e.get(e);return a&&$e.add(i,a),i}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ed(e){return e instanceof Error&&(e.constructor.name==="ZodError"||e.constructor.name==="$ZodError")}var Td=Symbol("Let zodToJsonSchema decide on which parser to use"),Sd={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Ad=e=>typeof e=="string"?{...Sd,name:e}:{...Sd,...e};var kd=e=>{let t=Ad(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};var Mi=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function oe(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Mi(t,e.currentPath):t.join("/")}}function no(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function J(e,t,r,n,i){e[t]=r,no(e,t,n,i)}var vt={};vp(vt,{BRAND:()=>u_,DIRTY:()=>cr,EMPTY_PATH:()=>Bg,INVALID:()=>D,NEVER:()=>q_,OK:()=>Te,ParseStatus:()=>ve,Schema:()=>q,ZodAny:()=>Gt,ZodArray:()=>Ot,ZodBigInt:()=>lr,ZodBoolean:()=>dr,ZodBranded:()=>vn,ZodCatch:()=>xr,ZodDate:()=>fr,ZodDefault:()=>vr,ZodDiscriminatedUnion:()=>Di,ZodEffects:()=>Ye,ZodEnum:()=>wr,ZodError:()=>je,ZodFirstPartyTypeKind:()=>w,ZodFunction:()=>zi,ZodIntersection:()=>gr,ZodIssueCode:()=>y,ZodLazy:()=>_r,ZodLiteral:()=>yr,ZodMap:()=>Kr,ZodNaN:()=>Xr,ZodNativeEnum:()=>br,ZodNever:()=>it,ZodNull:()=>hr,ZodNullable:()=>bt,ZodNumber:()=>ur,ZodObject:()=>Le,ZodOptional:()=>Je,ZodParsedType:()=>A,ZodPipeline:()=>xn,ZodPromise:()=>Vt,ZodReadonly:()=>Er,ZodRecord:()=>Ui,ZodSchema:()=>q,ZodSet:()=>Yr,ZodString:()=>Ht,ZodSymbol:()=>Wr,ZodTransformer:()=>Ye,ZodTuple:()=>wt,ZodType:()=>q,ZodUndefined:()=>pr,ZodUnion:()=>mr,ZodUnknown:()=>Ct,ZodVoid:()=>Jr,addIssueToContext:()=>E,any:()=>y_,array:()=>x_,bigint:()=>p_,boolean:()=>Dd,coerce:()=>Z_,custom:()=>Md,date:()=>h_,datetimeRegex:()=>$d,defaultErrorMap:()=>kt,discriminatedUnion:()=>A_,effect:()=>D_,enum:()=>M_,function:()=>N_,getErrorMap:()=>Vr,getParsedType:()=>yt,instanceof:()=>d_,intersection:()=>k_,isAborted:()=>ji,isAsync:()=>Zr,isDirty:()=>Li,isValid:()=>Ft,late:()=>l_,lazy:()=>$_,literal:()=>P_,makeIssue:()=>bn,map:()=>O_,nan:()=>f_,nativeEnum:()=>j_,never:()=>b_,null:()=>__,nullable:()=>z_,number:()=>Ld,object:()=>E_,objectUtil:()=>io,oboolean:()=>V_,onumber:()=>G_,optional:()=>U_,ostring:()=>H_,pipeline:()=>F_,preprocess:()=>B_,promise:()=>L_,quotelessJson:()=>Dg,record:()=>C_,set:()=>R_,setErrorMap:()=>zg,strictObject:()=>S_,string:()=>jd,symbol:()=>m_,transformer:()=>D_,tuple:()=>I_,undefined:()=>g_,union:()=>T_,unknown:()=>w_,util:()=>W,void:()=>v_});var W;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let a={};for(let s of i)a[s]=s;return a},e.getValidEnumValues=i=>{let a=e.objectKeys(i).filter(o=>typeof i[i[o]]!="number"),s={};for(let o of a)s[o]=i[o];return e.objectValues(s)},e.objectValues=i=>e.objectKeys(i).map(function(a){return i[a]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let a=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&a.push(s);return a},e.find=(i,a)=>{for(let s of i)if(a(s))return s},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,a=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(a)}e.joinValues=n,e.jsonStringifyReplacer=(i,a)=>typeof a=="bigint"?a.toString():a})(W||(W={}));var io;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(io||(io={}));var A=W.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),yt=e=>{switch(typeof e){case"undefined":return A.undefined;case"string":return A.string;case"number":return Number.isNaN(e)?A.nan:A.number;case"boolean":return A.boolean;case"function":return A.function;case"bigint":return A.bigint;case"symbol":return A.symbol;case"object":return Array.isArray(e)?A.array:e===null?A.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?A.promise:typeof Map<"u"&&e instanceof Map?A.map:typeof Set<"u"&&e instanceof Set?A.set:typeof Date<"u"&&e instanceof Date?A.date:A.object;default:return A.unknown}};var y=W.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Dg=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),je=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(a){return a.message},n={_errors:[]},i=a=>{for(let s of a.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let o=n,c=0;for(;c<s.path.length;){let u=s.path[c];c===s.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(r(s))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return i(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,W.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r=Object.create(null),n=[];for(let i of this.issues)if(i.path.length>0){let a=i.path[0];r[a]=r[a]||[],r[a].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};je.create=e=>new je(e);var Ug=(e,t)=>{let r;switch(e.code){case y.invalid_type:e.received===A.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case y.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,W.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:r=`Unrecognized key(s) in object: ${W.joinValues(e.keys,", ")}`;break;case y.invalid_union:r="Invalid input";break;case y.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${W.joinValues(e.options)}`;break;case y.invalid_enum_value:r=`Invalid enum value. Expected ${W.joinValues(e.options)}, received '${e.received}'`;break;case y.invalid_arguments:r="Invalid function arguments";break;case y.invalid_return_type:r="Invalid function return type";break;case y.invalid_date:r="Invalid date";break;case y.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:W.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case y.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case y.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case y.custom:r="Invalid input";break;case y.invalid_intersection_types:r="Intersection results could not be merged";break;case y.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case y.not_finite:r="Number must be finite";break;default:r=t.defaultError,W.assertNever(e)}return{message:r}},kt=Ug;var Id=kt;function zg(e){Id=e}function Vr(){return Id}var bn=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,a=[...r,...i.path||[]],s={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let o="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)o=u(s,{data:t,defaultError:o}).message;return{...i,path:a,message:o}},Bg=[];function E(e,t){let r=Vr(),n=bn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===kt?void 0:kt].filter(i=>!!i)});e.common.issues.push(n)}var ve=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return D;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let a=await i.key,s=await i.value;n.push({key:a,value:s})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:a,value:s}=i;if(a.status==="aborted"||s.status==="aborted")return D;a.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),a.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[a.value]=s.value)}return{status:t.value,value:n}}},D=Object.freeze({status:"aborted"}),cr=e=>({status:"dirty",value:e}),Te=e=>({status:"valid",value:e}),ji=e=>e.status==="aborted",Li=e=>e.status==="dirty",Ft=e=>e.status==="valid",Zr=e=>typeof Promise<"u"&&e instanceof Promise;var P;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(P||(P={}));var Ke=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Cd=(e,t)=>{if(Ft(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new je(e.common.issues);return this._error=r,this._error}}};function V(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(s,o)=>{let{message:c}=e;return s.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:s.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:i}}var q=class{get description(){return this._def.description}_getType(t){return yt(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:yt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ve,ctx:{common:t.parent.common,data:t.data,parsedType:yt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(Zr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:yt(t)},i=this._parseSync({data:t,path:n.path,parent:n});return Cd(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:yt(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return Ft(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Ft(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:yt(t)},i=this._parse({data:t,path:n.path,parent:n}),a=await(Zr(i)?i:Promise.resolve(i));return Cd(n,a)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,a)=>{let s=t(i),o=()=>a.addIssue({code:y.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(o(),!1)):s?!0:(o(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new Ye({schema:this,typeName:w.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Je.create(this,this._def)}nullable(){return bt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ot.create(this)}promise(){return Vt.create(this,this._def)}or(t){return mr.create([this,t],this._def)}and(t){return gr.create(this,t,this._def)}transform(t){return new Ye({...V(this._def),schema:this,typeName:w.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new vr({...V(this._def),innerType:this,defaultValue:r,typeName:w.ZodDefault})}brand(){return new vn({typeName:w.ZodBranded,type:this,...V(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new xr({...V(this._def),innerType:this,catchValue:r,typeName:w.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return xn.create(this,t)}readonly(){return Er.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Fg=/^c[^\s-]{8,}$/i,Hg=/^[0-9a-z]+$/,Gg=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Vg=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Zg=/^[a-z0-9_-]{21}$/i,qg=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Wg=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Jg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Kg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ao,Yg=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Xg=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Qg=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,e_=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,t_=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,r_=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Rd="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",n_=new RegExp(`^${Rd}$`);function Nd(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function i_(e){return new RegExp(`^${Nd(e)}$`)}function $d(e){let t=`${Rd}T${Nd(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function a_(e,t){return!!((t==="v4"||!t)&&Yg.test(e)||(t==="v6"||!t)&&Qg.test(e))}function s_(e,t){if(!qg.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function o_(e,t){return!!((t==="v4"||!t)&&Xg.test(e)||(t==="v6"||!t)&&e_.test(e))}var Ht=class e extends q{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==A.string){let a=this._getOrReturnCtx(t);return E(a,{code:y.invalid_type,expected:A.string,received:a.parsedType}),D}let n=new ve,i;for(let a of this._def.checks)if(a.kind==="min")t.data.length<a.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:y.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")t.data.length>a.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:y.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let s=t.data.length>a.value,o=t.data.length<a.value;(s||o)&&(i=this._getOrReturnCtx(t,i),s?E(i,{code:y.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&E(i,{code:y.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")Jg.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"email",code:y.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")ao||(ao=new RegExp(Kg,"u")),ao.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"emoji",code:y.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")Vg.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"uuid",code:y.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")Zg.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"nanoid",code:y.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")Fg.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"cuid",code:y.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")Hg.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"cuid2",code:y.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")Gg.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"ulid",code:y.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),E(i,{validation:"url",code:y.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"regex",code:y.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?t.data=t.data.trim():a.kind==="includes"?t.data.includes(a.value,a.position)||(i=this._getOrReturnCtx(t,i),E(i,{code:y.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?t.data=t.data.toLowerCase():a.kind==="toUpperCase"?t.data=t.data.toUpperCase():a.kind==="startsWith"?t.data.startsWith(a.value)||(i=this._getOrReturnCtx(t,i),E(i,{code:y.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?t.data.endsWith(a.value)||(i=this._getOrReturnCtx(t,i),E(i,{code:y.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?$d(a).test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{code:y.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?n_.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{code:y.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?i_(a).test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{code:y.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?Wg.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"duration",code:y.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?a_(t.data,a.version)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"ip",code:y.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?s_(t.data,a.alg)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"jwt",code:y.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?o_(t.data,a.version)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"cidr",code:y.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?t_.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"base64",code:y.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?r_.test(t.data)||(i=this._getOrReturnCtx(t,i),E(i,{validation:"base64url",code:y.invalid_string,message:a.message}),n.dirty()):W.assertNever(a);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:y.invalid_string,...P.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...P.errToObj(t)})}url(t){return this._addCheck({kind:"url",...P.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...P.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...P.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...P.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...P.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...P.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...P.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...P.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...P.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...P.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...P.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...P.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...P.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...P.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...P.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...P.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...P.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...P.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...P.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...P.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...P.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...P.errToObj(r)})}nonempty(t){return this.min(1,P.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Ht.create=e=>new Ht({checks:[],typeName:w.ZodString,coerce:e?.coerce??!1,...V(e)});function c_(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,a=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return a%s/10**i}var ur=class e extends q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==A.number){let a=this._getOrReturnCtx(t);return E(a,{code:y.invalid_type,expected:A.number,received:a.parsedType}),D}let n,i=new ve;for(let a of this._def.checks)a.kind==="int"?W.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),E(n,{code:y.invalid_type,expected:"integer",received:"float",message:a.message}),i.dirty()):a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(n=this._getOrReturnCtx(t,n),E(n,{code:y.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(n=this._getOrReturnCtx(t,n),E(n,{code:y.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="multipleOf"?c_(t.data,a.value)!==0&&(n=this._getOrReturnCtx(t,n),E(n,{code:y.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):a.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),E(n,{code:y.not_finite,message:a.message}),i.dirty()):W.assertNever(a);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,P.toString(r))}gt(t,r){return this.setLimit("min",t,!1,P.toString(r))}lte(t,r){return this.setLimit("max",t,!0,P.toString(r))}lt(t,r){return this.setLimit("max",t,!1,P.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:P.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:P.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:P.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:P.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&W.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};ur.create=e=>new ur({checks:[],typeName:w.ZodNumber,coerce:e?.coerce||!1,...V(e)});var lr=class e extends q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==A.bigint)return this._getInvalidInput(t);let n,i=new ve;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(n=this._getOrReturnCtx(t,n),E(n,{code:y.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(n=this._getOrReturnCtx(t,n),E(n,{code:y.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="multipleOf"?t.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),E(n,{code:y.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):W.assertNever(a);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return E(r,{code:y.invalid_type,expected:A.bigint,received:r.parsedType}),D}gte(t,r){return this.setLimit("min",t,!0,P.toString(r))}gt(t,r){return this.setLimit("min",t,!1,P.toString(r))}lte(t,r){return this.setLimit("max",t,!0,P.toString(r))}lt(t,r){return this.setLimit("max",t,!1,P.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:P.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:P.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};lr.create=e=>new lr({checks:[],typeName:w.ZodBigInt,coerce:e?.coerce??!1,...V(e)});var dr=class extends q{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==A.boolean){let n=this._getOrReturnCtx(t);return E(n,{code:y.invalid_type,expected:A.boolean,received:n.parsedType}),D}return Te(t.data)}};dr.create=e=>new dr({typeName:w.ZodBoolean,coerce:e?.coerce||!1,...V(e)});var fr=class e extends q{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==A.date){let a=this._getOrReturnCtx(t);return E(a,{code:y.invalid_type,expected:A.date,received:a.parsedType}),D}if(Number.isNaN(t.data.getTime())){let a=this._getOrReturnCtx(t);return E(a,{code:y.invalid_date}),D}let n=new ve,i;for(let a of this._def.checks)a.kind==="min"?t.data.getTime()<a.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:y.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?t.data.getTime()>a.value&&(i=this._getOrReturnCtx(t,i),E(i,{code:y.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):W.assertNever(a);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:P.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:P.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};fr.create=e=>new fr({checks:[],coerce:e?.coerce||!1,typeName:w.ZodDate,...V(e)});var Wr=class extends q{_parse(t){if(this._getType(t)!==A.symbol){let n=this._getOrReturnCtx(t);return E(n,{code:y.invalid_type,expected:A.symbol,received:n.parsedType}),D}return Te(t.data)}};Wr.create=e=>new Wr({typeName:w.ZodSymbol,...V(e)});var pr=class extends q{_parse(t){if(this._getType(t)!==A.undefined){let n=this._getOrReturnCtx(t);return E(n,{code:y.invalid_type,expected:A.undefined,received:n.parsedType}),D}return Te(t.data)}};pr.create=e=>new pr({typeName:w.ZodUndefined,...V(e)});var hr=class extends q{_parse(t){if(this._getType(t)!==A.null){let n=this._getOrReturnCtx(t);return E(n,{code:y.invalid_type,expected:A.null,received:n.parsedType}),D}return Te(t.data)}};hr.create=e=>new hr({typeName:w.ZodNull,...V(e)});var Gt=class extends q{constructor(){super(...arguments),this._any=!0}_parse(t){return Te(t.data)}};Gt.create=e=>new Gt({typeName:w.ZodAny,...V(e)});var Ct=class extends q{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Te(t.data)}};Ct.create=e=>new Ct({typeName:w.ZodUnknown,...V(e)});var it=class extends q{_parse(t){let r=this._getOrReturnCtx(t);return E(r,{code:y.invalid_type,expected:A.never,received:r.parsedType}),D}};it.create=e=>new it({typeName:w.ZodNever,...V(e)});var Jr=class extends q{_parse(t){if(this._getType(t)!==A.undefined){let n=this._getOrReturnCtx(t);return E(n,{code:y.invalid_type,expected:A.void,received:n.parsedType}),D}return Te(t.data)}};Jr.create=e=>new Jr({typeName:w.ZodVoid,...V(e)});var Ot=class e extends q{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==A.array)return E(r,{code:y.invalid_type,expected:A.array,received:r.parsedType}),D;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,o=r.data.length<i.exactLength.value;(s||o)&&(E(r,{code:s?y.too_big:y.too_small,minimum:o?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(E(r,{code:y.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(E(r,{code:y.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,o)=>i.type._parseAsync(new Ke(r,s,r.path,o)))).then(s=>ve.mergeArray(n,s));let a=[...r.data].map((s,o)=>i.type._parseSync(new Ke(r,s,r.path,o)));return ve.mergeArray(n,a)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:P.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:P.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:P.toString(r)}})}nonempty(t){return this.min(1,t)}};Ot.create=(e,t)=>new Ot({type:e,minLength:null,maxLength:null,exactLength:null,typeName:w.ZodArray,...V(t)});function qr(e){if(e instanceof Le){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Je.create(qr(n))}return new Le({...e._def,shape:()=>t})}else return e instanceof Ot?new Ot({...e._def,type:qr(e.element)}):e instanceof Je?Je.create(qr(e.unwrap())):e instanceof bt?bt.create(qr(e.unwrap())):e instanceof wt?wt.create(e.items.map(t=>qr(t))):e}var Le=class e extends q{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=W.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==A.object){let u=this._getOrReturnCtx(t);return E(u,{code:y.invalid_type,expected:A.object,received:u.parsedType}),D}let{status:n,ctx:i}=this._processInputParams(t),{shape:a,keys:s}=this._getCached(),o=[];if(!(this._def.catchall instanceof it&&this._def.unknownKeys==="strip"))for(let u in i.data)s.includes(u)||o.push(u);let c=[];for(let u of s){let l=a[u],d=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Ke(i,d,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof it){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of o)c.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(u==="strict")o.length>0&&(E(i,{code:y.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of o){let d=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Ke(i,d,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>ve.mergeObjectSync(n,u)):ve.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return P.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:P.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:w.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of W.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of W.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return qr(this)}partial(t){let r={};for(let n of W.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of W.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof Je;)a=a._def.innerType;r[n]=a}return new e({...this._def,shape:()=>r})}keyof(){return Pd(W.objectKeys(this.shape))}};Le.create=(e,t)=>new Le({shape:()=>e,unknownKeys:"strip",catchall:it.create(),typeName:w.ZodObject,...V(t)});Le.strictCreate=(e,t)=>new Le({shape:()=>e,unknownKeys:"strict",catchall:it.create(),typeName:w.ZodObject,...V(t)});Le.lazycreate=(e,t)=>new Le({shape:e,unknownKeys:"strip",catchall:it.create(),typeName:w.ZodObject,...V(t)});var mr=class extends q{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;let s=a.map(o=>new je(o.ctx.common.issues));return E(r,{code:y.invalid_union,unionErrors:s}),D}if(r.common.async)return Promise.all(n.map(async a=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let a,s=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!a&&(a={result:l,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let o=s.map(c=>new je(c));return E(r,{code:y.invalid_union,unionErrors:o}),D}}get options(){return this._def.options}};mr.create=(e,t)=>new mr({options:e,typeName:w.ZodUnion,...V(t)});var It=e=>e instanceof _r?It(e.schema):e instanceof Ye?It(e.innerType()):e instanceof yr?[e.value]:e instanceof wr?e.options:e instanceof br?W.objectValues(e.enum):e instanceof vr?It(e._def.innerType):e instanceof pr?[void 0]:e instanceof hr?[null]:e instanceof Je?[void 0,...It(e.unwrap())]:e instanceof bt?[null,...It(e.unwrap())]:e instanceof vn||e instanceof Er?It(e.unwrap()):e instanceof xr?It(e._def.innerType):[],Di=class e extends q{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==A.object)return E(r,{code:y.invalid_type,expected:A.object,received:r.parsedType}),D;let n=this.discriminator,i=r.data[n],a=this.optionsMap.get(i);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(E(r,{code:y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),D)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let a of r){let s=It(a.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let o of s){if(i.has(o))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);i.set(o,a)}}return new e({typeName:w.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...V(n)})}};function so(e,t){let r=yt(e),n=yt(t);if(e===t)return{valid:!0,data:e};if(r===A.object&&n===A.object){let i=W.objectKeys(t),a=W.objectKeys(e).filter(o=>i.indexOf(o)!==-1),s={...e,...t};for(let o of a){let c=so(e[o],t[o]);if(!c.valid)return{valid:!1};s[o]=c.data}return{valid:!0,data:s}}else if(r===A.array&&n===A.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let a=0;a<e.length;a++){let s=e[a],o=t[a],c=so(s,o);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===A.date&&n===A.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var gr=class extends q{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(a,s)=>{if(ji(a)||ji(s))return D;let o=so(a.value,s.value);return o.valid?((Li(a)||Li(s))&&r.dirty(),{status:r.value,value:o.data}):(E(n,{code:y.invalid_intersection_types}),D)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,s])=>i(a,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};gr.create=(e,t,r)=>new gr({left:e,right:t,typeName:w.ZodIntersection,...V(r)});var wt=class e extends q{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==A.array)return E(n,{code:y.invalid_type,expected:A.array,received:n.parsedType}),D;if(n.data.length<this._def.items.length)return E(n,{code:y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),D;!this._def.rest&&n.data.length>this._def.items.length&&(E(n,{code:y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...n.data].map((s,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new Ke(n,s,n.path,o)):null}).filter(s=>!!s);return n.common.async?Promise.all(a).then(s=>ve.mergeArray(r,s)):ve.mergeArray(r,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};wt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new wt({items:e,typeName:w.ZodTuple,rest:null,...V(t)})};var Ui=class e extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==A.object)return E(n,{code:y.invalid_type,expected:A.object,received:n.parsedType}),D;let i=[],a=this._def.keyType,s=this._def.valueType;for(let o in n.data)i.push({key:a._parse(new Ke(n,o,n.path,o)),value:s._parse(new Ke(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?ve.mergeObjectAsync(r,i):ve.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof q?new e({keyType:t,valueType:r,typeName:w.ZodRecord,...V(n)}):new e({keyType:Ht.create(),valueType:t,typeName:w.ZodRecord,...V(r)})}},Kr=class extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==A.map)return E(n,{code:y.invalid_type,expected:A.map,received:n.parsedType}),D;let i=this._def.keyType,a=this._def.valueType,s=[...n.data.entries()].map(([o,c],u)=>({key:i._parse(new Ke(n,o,n.path,[u,"key"])),value:a._parse(new Ke(n,c,n.path,[u,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return D;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}})}else{let o=new Map;for(let c of s){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return D;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}}}};Kr.create=(e,t,r)=>new Kr({valueType:t,keyType:e,typeName:w.ZodMap,...V(r)});var Yr=class e extends q{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==A.set)return E(n,{code:y.invalid_type,expected:A.set,received:n.parsedType}),D;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(E(n,{code:y.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(E(n,{code:y.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let a=this._def.valueType;function s(c){let u=new Set;for(let l of c){if(l.status==="aborted")return D;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let o=[...n.data.values()].map((c,u)=>a._parse(new Ke(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>s(c)):s(o)}min(t,r){return new e({...this._def,minSize:{value:t,message:P.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:P.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};Yr.create=(e,t)=>new Yr({valueType:e,minSize:null,maxSize:null,typeName:w.ZodSet,...V(t)});var zi=class e extends q{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==A.function)return E(r,{code:y.invalid_type,expected:A.function,received:r.parsedType}),D;function n(o,c){return bn({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Vr(),kt].filter(u=>!!u),issueData:{code:y.invalid_arguments,argumentsError:c}})}function i(o,c){return bn({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Vr(),kt].filter(u=>!!u),issueData:{code:y.invalid_return_type,returnTypeError:c}})}let a={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof Vt){let o=this;return Te(async function(...c){let u=new je([]),l=await o._def.args.parseAsync(c,a).catch(p=>{throw u.addIssue(n(c,p)),u}),d=await Reflect.apply(s,this,l);return await o._def.returns._def.type.parseAsync(d,a).catch(p=>{throw u.addIssue(i(d,p)),u})})}else{let o=this;return Te(function(...c){let u=o._def.args.safeParse(c,a);if(!u.success)throw new je([n(c,u.error)]);let l=Reflect.apply(s,this,u.data),d=o._def.returns.safeParse(l,a);if(!d.success)throw new je([i(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:wt.create(t).rest(Ct.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||wt.create([]).rest(Ct.create()),returns:r||Ct.create(),typeName:w.ZodFunction,...V(n)})}},_r=class extends q{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};_r.create=(e,t)=>new _r({getter:e,typeName:w.ZodLazy,...V(t)});var yr=class extends q{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return E(r,{received:r.data,code:y.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:t.data}}get value(){return this._def.value}};yr.create=(e,t)=>new yr({value:e,typeName:w.ZodLiteral,...V(t)});function Pd(e,t){return new wr({values:e,typeName:w.ZodEnum,...V(t)})}var wr=class e extends q{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return E(r,{expected:W.joinValues(n),received:r.parsedType,code:y.invalid_type}),D}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return E(r,{received:r.data,code:y.invalid_enum_value,options:n}),D}return Te(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};wr.create=Pd;var br=class extends q{_parse(t){let r=W.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==A.string&&n.parsedType!==A.number){let i=W.objectValues(r);return E(n,{expected:W.joinValues(i),received:n.parsedType,code:y.invalid_type}),D}if(this._cache||(this._cache=new Set(W.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=W.objectValues(r);return E(n,{received:n.data,code:y.invalid_enum_value,options:i}),D}return Te(t.data)}get enum(){return this._def.values}};br.create=(e,t)=>new br({values:e,typeName:w.ZodNativeEnum,...V(t)});var Vt=class extends q{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==A.promise&&r.common.async===!1)return E(r,{code:y.invalid_type,expected:A.promise,received:r.parsedType}),D;let n=r.parsedType===A.promise?r.data:Promise.resolve(r.data);return Te(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Vt.create=(e,t)=>new Vt({type:e,typeName:w.ZodPromise,...V(t)});var Ye=class extends q{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===w.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,a={addIssue:s=>{E(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),i.type==="preprocess"){let s=i.transform(n.data,a);if(n.common.async)return Promise.resolve(s).then(async o=>{if(r.value==="aborted")return D;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?D:c.status==="dirty"?cr(c.value):r.value==="dirty"?cr(c.value):c});{if(r.value==="aborted")return D;let o=this._def.schema._parseSync({data:s,path:n.path,parent:n});return o.status==="aborted"?D:o.status==="dirty"?cr(o.value):r.value==="dirty"?cr(o.value):o}}if(i.type==="refinement"){let s=o=>{let c=i.refinement(o,a);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?D:(o.status==="dirty"&&r.dirty(),s(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?D:(o.status==="dirty"&&r.dirty(),s(o.value).then(()=>({status:r.value,value:o.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ft(s))return D;let o=i.transform(s.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>Ft(s)?Promise.resolve(i.transform(s.value,a)).then(o=>({status:r.value,value:o})):D);W.assertNever(i)}};Ye.create=(e,t,r)=>new Ye({schema:e,typeName:w.ZodEffects,effect:t,...V(r)});Ye.createWithPreprocess=(e,t,r)=>new Ye({schema:t,effect:{type:"preprocess",transform:e},typeName:w.ZodEffects,...V(r)});var Je=class extends q{_parse(t){return this._getType(t)===A.undefined?Te(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Je.create=(e,t)=>new Je({innerType:e,typeName:w.ZodOptional,...V(t)});var bt=class extends q{_parse(t){return this._getType(t)===A.null?Te(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};bt.create=(e,t)=>new bt({innerType:e,typeName:w.ZodNullable,...V(t)});var vr=class extends q{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===A.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};vr.create=(e,t)=>new vr({innerType:e,typeName:w.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...V(t)});var xr=class extends q{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Zr(i)?i.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new je(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new je(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};xr.create=(e,t)=>new xr({innerType:e,typeName:w.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...V(t)});var Xr=class extends q{_parse(t){if(this._getType(t)!==A.nan){let n=this._getOrReturnCtx(t);return E(n,{code:y.invalid_type,expected:A.nan,received:n.parsedType}),D}return{status:"valid",value:t.data}}};Xr.create=e=>new Xr({typeName:w.ZodNaN,...V(e)});var u_=Symbol("zod_brand"),vn=class extends q{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},xn=class e extends q{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?D:a.status==="dirty"?(r.dirty(),cr(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?D:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:w.ZodPipeline})}},Er=class extends q{_parse(t){let r=this._def.innerType._parse(t),n=i=>(Ft(i)&&(i.value=Object.freeze(i.value)),i);return Zr(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Er.create=(e,t)=>new Er({innerType:e,typeName:w.ZodReadonly,...V(t)});function Od(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function Md(e,t={},r){return e?Gt.create().superRefine((n,i)=>{let a=e(n);if(a instanceof Promise)return a.then(s=>{if(!s){let o=Od(t,n),c=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:c})}});if(!a){let s=Od(t,n),o=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:o})}}):Gt.create()}var l_={object:Le.lazycreate},w;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(w||(w={}));var d_=(e,t={message:`Input not instance of ${e.name}`})=>Md(r=>r instanceof e,t),jd=Ht.create,Ld=ur.create,f_=Xr.create,p_=lr.create,Dd=dr.create,h_=fr.create,m_=Wr.create,g_=pr.create,__=hr.create,y_=Gt.create,w_=Ct.create,b_=it.create,v_=Jr.create,x_=Ot.create,E_=Le.create,S_=Le.strictCreate,T_=mr.create,A_=Di.create,k_=gr.create,I_=wt.create,C_=Ui.create,O_=Kr.create,R_=Yr.create,N_=zi.create,$_=_r.create,P_=yr.create,M_=wr.create,j_=br.create,L_=Vt.create,D_=Ye.create,U_=Je.create,z_=bt.create,B_=Ye.createWithPreprocess,F_=xn.create,H_=()=>jd().optional(),G_=()=>Ld().optional(),V_=()=>Dd().optional(),Z_={string:(e=>Ht.create({...e,coerce:!0})),number:(e=>ur.create({...e,coerce:!0})),boolean:(e=>dr.create({...e,coerce:!0})),bigint:(e=>lr.create({...e,coerce:!0})),date:(e=>fr.create({...e,coerce:!0}))};var q_=D;function Ud(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==w.ZodAny&&(r.items=U(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&J(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&J(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(J(r,"minItems",e.exactLength.value,e.exactLength.message,t),J(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function zd(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?J(r,"minimum",n.value,n.message,t):J(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),J(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?J(r,"maximum",n.value,n.message,t):J(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),J(r,"maximum",n.value,n.message,t));break;case"multipleOf":J(r,"multipleOf",n.value,n.message,t);break}return r}function Bd(){return{type:"boolean"}}function Bi(e,t){return U(e.type._def,t)}var Fd=(e,t)=>U(e.innerType._def,t);function oo(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(i=>oo(e,t,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return W_(e,t)}}var W_=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":J(r,"minimum",n.value,n.message,t);break;case"max":J(r,"maximum",n.value,n.message,t);break}return r};function Hd(e,t){return{...U(e.innerType._def,t),default:e.defaultValue()}}function Gd(e,t){return t.effectStrategy==="input"?U(e.schema._def,t):oe(t)}function Vd(e){return{type:"string",enum:Array.from(e.values)}}var J_=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function Zd(e,t){let r=[U(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),U(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(a=>!!a),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(a=>{if(J_(a))i.push(...a.allOf),a.unevaluatedProperties===void 0&&(n=void 0);else{let s=a;if("additionalProperties"in a&&a.additionalProperties===!1){let{additionalProperties:o,...c}=a;s=c}else n=void 0;i.push(s)}}),i.length?{allOf:i,...n}:void 0}function qd(e,t){let r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}var co,at={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(co===void 0&&(co=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),co),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Fi(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":J(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":J(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":st(r,"email",n.message,t);break;case"format:idn-email":st(r,"idn-email",n.message,t);break;case"pattern:zod":Oe(r,at.email,n.message,t);break}break;case"url":st(r,"uri",n.message,t);break;case"uuid":st(r,"uuid",n.message,t);break;case"regex":Oe(r,n.regex,n.message,t);break;case"cuid":Oe(r,at.cuid,n.message,t);break;case"cuid2":Oe(r,at.cuid2,n.message,t);break;case"startsWith":Oe(r,RegExp(`^${uo(n.value,t)}`),n.message,t);break;case"endsWith":Oe(r,RegExp(`${uo(n.value,t)}$`),n.message,t);break;case"datetime":st(r,"date-time",n.message,t);break;case"date":st(r,"date",n.message,t);break;case"time":st(r,"time",n.message,t);break;case"duration":st(r,"duration",n.message,t);break;case"length":J(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),J(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":Oe(r,RegExp(uo(n.value,t)),n.message,t);break;case"ip":n.version!=="v6"&&st(r,"ipv4",n.message,t),n.version!=="v4"&&st(r,"ipv6",n.message,t);break;case"base64url":Oe(r,at.base64url,n.message,t);break;case"jwt":Oe(r,at.jwt,n.message,t);break;case"cidr":n.version!=="v6"&&Oe(r,at.ipv4Cidr,n.message,t),n.version!=="v4"&&Oe(r,at.ipv6Cidr,n.message,t);break;case"emoji":Oe(r,at.emoji(),n.message,t);break;case"ulid":Oe(r,at.ulid,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":st(r,"binary",n.message,t);break;case"contentEncoding:base64":J(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":Oe(r,at.base64,n.message,t);break}break;case"nanoid":Oe(r,at.nanoid,n.message,t);break;case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function uo(e,t){return t.patternStrategy==="escape"?Y_(e):e}var K_=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Y_(e){let t="";for(let r=0;r<e.length;r++)K_.has(e[r])||(t+="\\"),t+=e[r];return t}function st(e,t,r,n){e.format||e.anyOf?.some(i=>i.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):J(e,"format",t,r,n)}function Oe(e,t,r,n){e.pattern||e.allOf?.some(i=>i.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Wd(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):J(e,"pattern",Wd(t,n),r,n)}function Wd(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source,i="",a=!1,s=!1,o=!1;for(let c=0;c<n.length;c++){if(a){i+=n[c],a=!1;continue}if(r.i){if(s){if(n[c].match(/[a-z]/)){o?(i+=n[c],i+=`${n[c-2]}-${n[c]}`.toUpperCase(),o=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(i+=n[c],o=!0):i+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){i+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){i+=`(^|(?<=[\r
|
|
151
|
+
]))`;continue}else if(n[c]==="$"){i+=`($|(?=[\r
|
|
152
|
+
]))`;continue}}if(r.s&&n[c]==="."){i+=s?`${n[c]}\r
|
|
153
|
+
`:`[${n[c]}\r
|
|
154
|
+
]`;continue}i+=n[c],n[c]==="\\"?a=!0:s&&n[c]==="]"?s=!1:!s&&n[c]==="["&&(s=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Hi(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===w.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,i)=>({...n,[i]:U(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",i]})??oe(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:U(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===w.ZodString&&e.keyType._def.checks?.length){let{type:n,...i}=Fi(e.keyType._def,t);return{...r,propertyNames:i}}else{if(e.keyType?._def.typeName===w.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===w.ZodBranded&&e.keyType._def.type._def.typeName===w.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...i}=Bi(e.keyType._def,t);return{...r,propertyNames:i}}}return r}function Jd(e,t){return t.mapStrategy==="record"?Hi(e,t):{type:"array",maxItems:125,items:{type:"array",items:[U(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||oe(t),U(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||oe(t)],minItems:2,maxItems:2}}}function Kd(e){let t=e.values,r=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),n=Array.from(new Set(r.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:r}}function Yd(e){return e.target==="openAi"?void 0:{not:oe({...e,currentPath:[...e.currentPath,"not"]})}}function Xd(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var En={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ef(e,t){if(t.target==="openApi3")return Qd(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in En&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((i,a)=>{let s=En[a._def.typeName];return s&&!i.includes(s)?[...i,s]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((i,a)=>{let s=typeof a._def.value;switch(s){case"string":case"number":case"boolean":return[...i,s];case"bigint":return[...i,"integer"];case"object":return a._def.value===null?[...i,"null"]:i;default:return i}},[]);if(n.length===r.length){let i=n.filter((a,s,o)=>o.indexOf(a)===s);return{type:i.length>1?i:i[0],enum:r.reduce((a,s)=>a.includes(s._def.value)?a:[...a,s._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(a=>!n.includes(a))],[])};return Qd(e,t)}var Qd=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,i)=>U(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function tf(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:En[e.innerType._def.typeName],nullable:!0}:{type:[En[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=U(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=U(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function rf(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",no(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?J(r,"minimum",n.value,n.message,t):J(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),J(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?J(r,"maximum",n.value,n.message,t):J(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),J(r,"maximum",n.value,n.message,t));break;case"multipleOf":J(r,"multipleOf",n.value,n.message,t);break}return r}function nf(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},i=[],a=e.shape();for(let o in a){let c=a[o];if(c===void 0||c._def===void 0)continue;let u=Q_(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=U(c._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});l!==void 0&&(n.properties[o]=l,u||i.push(o))}i.length&&(n.required=i);let s=X_(e,t);return s!==void 0&&(n.additionalProperties=s),n}function X_(e,t){if(e.catchall._def.typeName!=="ZodNever")return U(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Q_(e){try{return e.isOptional()}catch{return!0}}var af=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return U(e.innerType._def,t);let r=U(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:oe(t)},r]}:oe(t)};var sf=(e,t)=>{if(t.pipeStrategy==="input")return U(e.in._def,t);if(t.pipeStrategy==="output")return U(e.out._def,t);let r=U(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,U(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter(n=>n!==void 0)}};function of(e,t){return U(e.type._def,t)}function cf(e,t){let r={type:"array",uniqueItems:!0,items:U(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&J(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&J(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function uf(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>U(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:U(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>U(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function lf(e){return{not:oe(e)}}function df(e){return oe(e)}var ff=(e,t)=>U(e.innerType._def,t);var pf=(e,t,r)=>{switch(t){case w.ZodString:return Fi(e,r);case w.ZodNumber:return rf(e,r);case w.ZodObject:return nf(e,r);case w.ZodBigInt:return zd(e,r);case w.ZodBoolean:return Bd();case w.ZodDate:return oo(e,r);case w.ZodUndefined:return lf(r);case w.ZodNull:return Xd(r);case w.ZodArray:return Ud(e,r);case w.ZodUnion:case w.ZodDiscriminatedUnion:return ef(e,r);case w.ZodIntersection:return Zd(e,r);case w.ZodTuple:return uf(e,r);case w.ZodRecord:return Hi(e,r);case w.ZodLiteral:return qd(e,r);case w.ZodEnum:return Vd(e);case w.ZodNativeEnum:return Kd(e);case w.ZodNullable:return tf(e,r);case w.ZodOptional:return af(e,r);case w.ZodMap:return Jd(e,r);case w.ZodSet:return cf(e,r);case w.ZodLazy:return()=>e.getter()._def;case w.ZodPromise:return of(e,r);case w.ZodNaN:case w.ZodNever:return Yd(r);case w.ZodEffects:return Gd(e,r);case w.ZodAny:return oe(r);case w.ZodUnknown:return df(r);case w.ZodDefault:return Hd(e,r);case w.ZodBranded:return Bi(e,r);case w.ZodReadonly:return ff(e,r);case w.ZodCatch:return Fd(e,r);case w.ZodPipeline:return sf(e,r);case w.ZodFunction:case w.ZodVoid:case w.ZodSymbol:return;default:return(n=>{})(t)}};function U(e,t,r=!1){let n=t.seen.get(e);if(t.override){let o=t.override?.(e,t,n,r);if(o!==Td)return o}if(n&&!r){let o=ey(n,t);if(o!==void 0)return o}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=pf(e,e.typeName,t),s=typeof a=="function"?U(a(),t):a;if(s&&ty(e,t,s),t.postProcess){let o=t.postProcess(s,e,t);return i.jsonSchema=s,o}return i.jsonSchema=s,s}var ey=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Mi(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),oe(t)):t.$refStrategy==="seen"?oe(t):void 0}},ty=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var hf=(e,t)=>{let r=kd(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:U(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??oe(r)}),{}):void 0,i=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=U(e._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??oe(r),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(a.title=s),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let o=i===void 0?n?{...a,[r.definitionPath]:n}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:a}};return r.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o};var FI=L({isSerializableSchema:()=>ry,isStandardJsonSchema:()=>Gi,isStandardSchema:()=>mf});function mf(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"validate"in e["~standard"]}function Gi(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"jsonSchema"in e["~standard"]}function ry(e){return mf(e)&&Gi(e)}function Zt(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let i=0;i<n;i++)if(!Zt(e[i],t[i]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(let s of n)if(!Zt(e[s],t[s]))return!1;return!0}return e===t}function Fe(e){return encodeURI(ny(e))}function ny(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var iy={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},ay={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},sy={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},oy=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");function ot(e,t=Object.create(null),r=oy,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let a=e.$id||e.id;if(a){let s=new URL(a,r.href);s.hash.length>1?t[s.href]=e:(s.hash="",n===""?r=s:ot(e,t,r))}}else if(e!==!0&&e!==!1)return t;let i=r.href+(n?"#"+n:"");if(t[i]!==void 0)throw new Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let a=new URL(e.$ref,r.href);a.hash=a.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:a.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let a=new URL(e.$recursiveRef,r.href);a.hash=a.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:a.href})}if(e.$anchor){let a=new URL("#"+e.$anchor,r.href);t[a.href]=e}for(let a in e){if(sy[a])continue;let s=`${n}/${Fe(a)}`,o=e[a];if(Array.isArray(o)){if(iy[a]){let c=o.length;for(let u=0;u<c;u++)ot(o[u],t,r,`${s}/${u}`)}}else if(ay[a])for(let c in o)ot(o[c],t,r,`${s}/${Fe(c)}`);else ot(o,t,r,s)}return t}var cy=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,uy=[0,31,28,31,30,31,30,31,31,30,31,30,31],ly=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,dy=/^(?=.{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,fy=/^(?:[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,py=/^(?:(?:[^\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,hy=/^(?:(?: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,my=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,gy=/^(?:\/(?:[^~/]|~0|~1)*)*$/,_y=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,yy=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,wy=e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},by=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,vy=/^((([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,xy=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function xt(e){return e.test.bind(e)}var lo={date:gf,time:_f.bind(void 0,!1),"date-time":Ty,duration:xy,uri:Iy,"uri-reference":xt(fy),"uri-template":xt(py),url:xt(hy),email:wy,hostname:xt(dy),ipv4:xt(by),ipv6:xt(vy),regex:Oy,uuid:xt(my),"json-pointer":xt(gy),"json-pointer-uri-fragment":xt(_y),"relative-json-pointer":xt(yy)};function Ey(e){return e%4===0&&(e%100!==0||e%400===0)}function gf(e){let t=e.match(cy);if(!t)return!1;let r=+t[1],n=+t[2],i=+t[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&Ey(r)?29:uy[n])}function _f(e,t){let r=t.match(ly);if(!r)return!1;let n=+r[1],i=+r[2],a=+r[3],s=!!r[5];return(n<=23&&i<=59&&a<=59||n==23&&i==59&&a==60)&&(!e||s)}var Sy=/t|\s/i;function Ty(e){let t=e.split(Sy);return t.length==2&&gf(t[0])&&_f(!0,t[1])}var Ay=/\/|:/,ky=/^(?:[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 Iy(e){return Ay.test(e)&&ky.test(e)}var Cy=/[^\\]\\Z/;function Oy(e){if(Cy.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var yf;(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(yf||(yf={}));function wf(e){let t=0,r=e.length,n=0,i;for(;n<r;)t++,i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<r&&(i=e.charCodeAt(n),(i&64512)==56320&&n++);return t}function re(e,t,r="2019-09",n=ot(t),i=!0,a=null,s="#",o="#",c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};let u=typeof e,l;switch(u){case"boolean":case"number":case"string":l=u;break;case"object":e===null?l="null":Array.isArray(e)?l="array":l="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:h,const:m,enum:b,required:x,not:v,anyOf:I,allOf:k,oneOf:j,if:X,then:K,else:Q,format:ee,properties:fe,patternProperties:Ae,additionalProperties:lt,unevaluatedProperties:Cn,minProperties:rn,maxProperties:wa,propertyNames:Po,dependentRequired:ba,dependentSchemas:va,dependencies:xa,prefixItems:Ea,items:nn,additionalItems:Mo,unevaluatedItems:jo,contains:Lo,minContains:Tt,maxContains:On,minItems:Sa,maxItems:Ta,uniqueItems:wp,minimum:Wt,maximum:Jt,exclusiveMinimum:an,exclusiveMaximum:sn,multipleOf:Rn,minLength:Nn,maxLength:$n,pattern:Do,__absolute_ref__:Pn,__absolute_recursive_ref__:bp}=t,C=[];if(p===!0&&a===null&&(a=t),f==="#"){let z=a===null?n[bp]:a,M=`${o}/$recursiveRef`,H=re(e,a===null?t:a,r,n,i,z,s,M,c);H.valid||C.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:M,error:"A subschema had errors."},...H.errors)}if(d!==void 0){let M=n[Pn||d];if(M===void 0){let S=`Unresolved $ref "${d}".`;throw Pn&&Pn!==d&&(S+=` Absolute URI "${Pn}".`),S+=`
|
|
155
|
+
Known schemas:
|
|
156
|
+
- ${Object.keys(n).join(`
|
|
157
|
+
- `)}`,new Error(S)}let H=`${o}/$ref`,R=re(e,M,r,n,i,a,s,H,c);if(R.valid||C.push({instanceLocation:s,keyword:"$ref",keywordLocation:H,error:"A subschema had errors."},...R.errors),r==="4"||r==="7")return{valid:C.length===0,errors:C}}if(Array.isArray(h)){let z=h.length,M=!1;for(let H=0;H<z;H++)if(l===h[H]||h[H]==="integer"&&l==="number"&&e%1===0&&e===e){M=!0;break}M||C.push({instanceLocation:s,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${h.join('", "')}".`})}else h==="integer"?(l!=="number"||e%1||e!==e)&&C.push({instanceLocation:s,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${h}".`}):h!==void 0&&l!==h&&C.push({instanceLocation:s,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${h}".`});if(m!==void 0&&(l==="object"||l==="array"?Zt(e,m)||C.push({instanceLocation:s,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(m)}.`}):e!==m&&C.push({instanceLocation:s,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(m)}.`})),b!==void 0&&(l==="object"||l==="array"?b.some(z=>Zt(e,z))||C.push({instanceLocation:s,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`}):b.some(z=>e===z)||C.push({instanceLocation:s,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`})),v!==void 0){let z=`${o}/not`;re(e,v,r,n,i,a,s,z).valid&&C.push({instanceLocation:s,keyword:"not",keywordLocation:z,error:'Instance matched "not" schema.'})}let Mn=[];if(I!==void 0){let z=`${o}/anyOf`,M=C.length,H=!1;for(let R=0;R<I.length;R++){let S=I[R],F=Object.create(c),B=re(e,S,r,n,i,p===!0?a:null,s,`${z}/${R}`,F);C.push(...B.errors),H=H||B.valid,B.valid&&Mn.push(F)}H?C.length=M:C.splice(M,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:z,error:"Instance does not match any subschemas."})}if(k!==void 0){let z=`${o}/allOf`,M=C.length,H=!0;for(let R=0;R<k.length;R++){let S=k[R],F=Object.create(c),B=re(e,S,r,n,i,p===!0?a:null,s,`${z}/${R}`,F);C.push(...B.errors),H=H&&B.valid,B.valid&&Mn.push(F)}H?C.length=M:C.splice(M,0,{instanceLocation:s,keyword:"allOf",keywordLocation:z,error:"Instance does not match every subschema."})}if(j!==void 0){let z=`${o}/oneOf`,M=C.length,H=j.filter((R,S)=>{let F=Object.create(c),B=re(e,R,r,n,i,p===!0?a:null,s,`${z}/${S}`,F);return C.push(...B.errors),B.valid&&Mn.push(F),B.valid}).length;H===1?C.length=M:C.splice(M,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:z,error:`Instance does not match exactly one subschema (${H} matches).`})}if((l==="object"||l==="array")&&Object.assign(c,...Mn),X!==void 0){let z=`${o}/if`;if(re(e,X,r,n,i,a,s,z,c).valid){if(K!==void 0){let H=re(e,K,r,n,i,a,s,`${o}/then`,c);H.valid||C.push({instanceLocation:s,keyword:"if",keywordLocation:z,error:'Instance does not match "then" schema.'},...H.errors)}}else if(Q!==void 0){let H=re(e,Q,r,n,i,a,s,`${o}/else`,c);H.valid||C.push({instanceLocation:s,keyword:"if",keywordLocation:z,error:'Instance does not match "else" schema.'},...H.errors)}}if(l==="object"){if(x!==void 0)for(let R of x)R in e||C.push({instanceLocation:s,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${R}".`});let z=Object.keys(e);if(rn!==void 0&&z.length<rn&&C.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${rn} properties.`}),wa!==void 0&&z.length>wa&&C.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${wa} properties.`}),Po!==void 0){let R=`${o}/propertyNames`;for(let S in e){let F=`${s}/${Fe(S)}`,B=re(S,Po,r,n,i,a,F,R);B.valid||C.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:R,error:`Property name "${S}" does not match schema.`},...B.errors)}}if(ba!==void 0){let R=`${o}/dependantRequired`;for(let S in ba)if(S in e){let F=ba[S];for(let B of F)B in e||C.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:R,error:`Instance has "${S}" but does not have "${B}".`})}}if(va!==void 0)for(let R in va){let S=`${o}/dependentSchemas`;if(R in e){let F=re(e,va[R],r,n,i,a,s,`${S}/${Fe(R)}`,c);F.valid||C.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:S,error:`Instance has "${R}" but does not match dependant schema.`},...F.errors)}}if(xa!==void 0){let R=`${o}/dependencies`;for(let S in xa)if(S in e){let F=xa[S];if(Array.isArray(F))for(let B of F)B in e||C.push({instanceLocation:s,keyword:"dependencies",keywordLocation:R,error:`Instance has "${S}" but does not have "${B}".`});else{let B=re(e,F,r,n,i,a,s,`${R}/${Fe(S)}`);B.valid||C.push({instanceLocation:s,keyword:"dependencies",keywordLocation:R,error:`Instance has "${S}" but does not match dependant schema.`},...B.errors)}}}let M=Object.create(null),H=!1;if(fe!==void 0){let R=`${o}/properties`;for(let S in fe){if(!(S in e))continue;let F=`${s}/${Fe(S)}`,B=re(e[S],fe[S],r,n,i,a,F,`${R}/${Fe(S)}`);if(B.valid)c[S]=M[S]=!0;else if(H=i,C.push({instanceLocation:s,keyword:"properties",keywordLocation:R,error:`Property "${S}" does not match schema.`},...B.errors),H)break}}if(!H&&Ae!==void 0){let R=`${o}/patternProperties`;for(let S in Ae){let F=new RegExp(S,"u"),B=Ae[S];for(let Ne in e){if(!F.test(Ne))continue;let Uo=`${s}/${Fe(Ne)}`,zo=re(e[Ne],B,r,n,i,a,Uo,`${R}/${Fe(S)}`);zo.valid?c[Ne]=M[Ne]=!0:(H=i,C.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:R,error:`Property "${Ne}" matches pattern "${S}" but does not match associated schema.`},...zo.errors))}}}if(!H&<!==void 0){let R=`${o}/additionalProperties`;for(let S in e){if(M[S])continue;let F=`${s}/${Fe(S)}`,B=re(e[S],lt,r,n,i,a,F,R);B.valid?c[S]=!0:(H=i,C.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:R,error:`Property "${S}" does not match additional properties schema.`},...B.errors))}}else if(!H&&Cn!==void 0){let R=`${o}/unevaluatedProperties`;for(let S in e)if(!c[S]){let F=`${s}/${Fe(S)}`,B=re(e[S],Cn,r,n,i,a,F,R);B.valid?c[S]=!0:C.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:R,error:`Property "${S}" does not match unevaluated properties schema.`},...B.errors)}}}else if(l==="array"){Ta!==void 0&&e.length>Ta&&C.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${e.length} > ${Ta}).`}),Sa!==void 0&&e.length<Sa&&C.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${e.length} < ${Sa}).`});let z=e.length,M=0,H=!1;if(Ea!==void 0){let R=`${o}/prefixItems`,S=Math.min(Ea.length,z);for(;M<S;M++){let F=re(e[M],Ea[M],r,n,i,a,`${s}/${M}`,`${R}/${M}`);if(c[M]=!0,!F.valid&&(H=i,C.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:R,error:"Items did not match schema."},...F.errors),H))break}}if(nn!==void 0){let R=`${o}/items`;if(Array.isArray(nn)){let S=Math.min(nn.length,z);for(;M<S;M++){let F=re(e[M],nn[M],r,n,i,a,`${s}/${M}`,`${R}/${M}`);if(c[M]=!0,!F.valid&&(H=i,C.push({instanceLocation:s,keyword:"items",keywordLocation:R,error:"Items did not match schema."},...F.errors),H))break}}else for(;M<z;M++){let S=re(e[M],nn,r,n,i,a,`${s}/${M}`,R);if(c[M]=!0,!S.valid&&(H=i,C.push({instanceLocation:s,keyword:"items",keywordLocation:R,error:"Items did not match schema."},...S.errors),H))break}if(!H&&Mo!==void 0){let S=`${o}/additionalItems`;for(;M<z;M++){let F=re(e[M],Mo,r,n,i,a,`${s}/${M}`,S);c[M]=!0,F.valid||(H=i,C.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:S,error:"Items did not match additional items schema."},...F.errors))}}}if(Lo!==void 0)if(z===0&&Tt===void 0)C.push({instanceLocation:s,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Tt!==void 0&&z<Tt)C.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${z}) than minContains (${Tt}).`});else{let R=`${o}/contains`,S=C.length,F=0;for(let B=0;B<z;B++){let Ne=re(e[B],Lo,r,n,i,a,`${s}/${B}`,R);Ne.valid?(c[B]=!0,F++):C.push(...Ne.errors)}F>=(Tt||0)&&(C.length=S),Tt===void 0&&On===void 0&&F===0?C.splice(S,0,{instanceLocation:s,keyword:"contains",keywordLocation:R,error:"Array does not contain item matching schema."}):Tt!==void 0&&F<Tt?C.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${Tt} items matching schema. Only ${F} items were found.`}):On!==void 0&&F>On&&C.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${On} items matching schema. ${F} items were found.`})}if(!H&&jo!==void 0){let R=`${o}/unevaluatedItems`;for(M;M<z;M++){if(c[M])continue;let S=re(e[M],jo,r,n,i,a,`${s}/${M}`,R);c[M]=!0,S.valid||C.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:R,error:"Items did not match unevaluated items schema."},...S.errors)}}if(wp)for(let R=0;R<z;R++){let S=e[R],F=typeof S=="object"&&S!==null;for(let B=0;B<z;B++){if(R===B)continue;let Ne=e[B];(S===Ne||F&&(typeof Ne=="object"&&Ne!==null)&&Zt(S,Ne))&&(C.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${R} and ${B}.`}),R=Number.MAX_SAFE_INTEGER,B=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(r==="4"?(Wt!==void 0&&(an===!0&&e<=Wt||e<Wt)&&C.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${e} is less than ${an?"or equal to ":""} ${Wt}.`}),Jt!==void 0&&(sn===!0&&e>=Jt||e>Jt)&&C.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${sn?"or equal to ":""} ${Jt}.`})):(Wt!==void 0&&e<Wt&&C.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${e} is less than ${Wt}.`}),Jt!==void 0&&e>Jt&&C.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${Jt}.`}),an!==void 0&&e<=an&&C.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${e} is less than ${an}.`}),sn!==void 0&&e>=sn&&C.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${e} is greater than or equal to ${sn}.`})),Rn!==void 0){let z=e%Rn;Math.abs(0-z)>=11920929e-14&&Math.abs(Rn-z)>=11920929e-14&&C.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${e} is not a multiple of ${Rn}.`})}}else if(l==="string"){let z=Nn===void 0&&$n===void 0?0:wf(e);Nn!==void 0&&z<Nn&&C.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${z} < ${Nn}).`}),$n!==void 0&&z>$n&&C.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${z} > ${$n}).`}),Do!==void 0&&!new RegExp(Do,"u").test(e)&&C.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),ee!==void 0&&lo[ee]&&!lo[ee](e)&&C.push({instanceLocation:s,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${ee}".`})}return{valid:C.length===0,errors:C}}var Vi=class{schema;draft;shortCircuit;lookup;constructor(t,r="2019-09",n=!0){this.schema=t,this.draft=r,this.shortCircuit=n,this.lookup=ot(t)}validate(t){return re(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),ot(t,this.lookup)}};var xC=L({Validator:()=>Vi,deepCompareStrict:()=>Zt,toJsonSchema:()=>fo,validatesOnlyStrings:()=>Qr}),bf=new WeakMap;function fo(e,t){let r=!t&&e!=null&&typeof e=="object";if(r){let i=bf.get(e);if(i)return i}let n;if(Gi(e)&&!se(e))n=e["~standard"].jsonSchema.input({target:"draft-07"});else if(se(e)){let i=xd(e,!0);_t(i)?n=Ca(Ni(i,!0),t):n=Ca(e,t)}else he(e)?n=hf(e):n=e;return r&&n!=null&&typeof n=="object"&&bf.set(e,n),n}function Qr(e){if(!e||typeof e!="object"||Object.keys(e).length===0||Array.isArray(e))return!1;if("type"in e)return typeof e.type=="string"?e.type==="string":Array.isArray(e.type)?e.type.every(t=>t==="string"):!1;if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(t=>typeof t=="string");if("const"in e)return typeof e.const=="string";if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some(t=>Qr(t));if("anyOf"in e&&Array.isArray(e.anyOf)||"oneOf"in e&&Array.isArray(e.oneOf)){let t="anyOf"in e?e.anyOf:e.oneOf;return t.length>0&&t.every(r=>Qr(r))}if("not"in e)return!1;if("$ref"in e&&typeof e.$ref=="string"){let t=e.$ref,r=ot(e);return r[t]?Qr(r[t]):!1}return!1}function po(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.iterator]=="function"&&typeof e.next=="function"}var vf=e=>e!=null&&typeof e=="object"&&"next"in e&&typeof e.next=="function";function Zi(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.asyncIterator]=="function"}function ho(e){return e!=null&&typeof e=="object"&&typeof e.next=="function"}async function xf(e,t){try{let r=await e.next();for(;!r.done;)await t?.(r.value),r=await e.next();return r.value}finally{await e.return?.(void 0)}}function*mo(e,t){for(;;){let{value:r,done:n}=be.runWithConfig(We(e),t.next.bind(t),!0);if(n)break;yield r}}async function*qi(e,t){let r=t[Symbol.asyncIterator]();for(;;){let{value:n,done:i}=await be.runWithConfig(We(e),r.next.bind(t),!0);if(i)break;yield n}}var N="0123456789abcdef".split(""),Ry=[-2147483648,8388608,32768,128],ct=[24,16,8,0],Wi=[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],me=[];function ut(e,t){t?(me[0]=me[16]=me[1]=me[2]=me[3]=me[4]=me[5]=me[6]=me[7]=me[8]=me[9]=me[10]=me[11]=me[12]=me[13]=me[14]=me[15]=0,this.blocks=me):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(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=e}ut.prototype.update=function(e){if(!this.finalized){var t,r=typeof e;if(r!=="string"){if(r==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);t=!0}for(var n,i=0,a,s=e.length,o=this.blocks;i<s;){if(this.hashed&&(this.hashed=!1,o[0]=this.block,this.block=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0),t)for(a=this.start;i<s&&a<64;++i)o[a>>>2]|=e[i]<<ct[a++&3];else for(a=this.start;i<s&&a<64;++i)n=e.charCodeAt(i),n<128?o[a>>>2]|=n<<ct[a++&3]:n<2048?(o[a>>>2]|=(192|n>>>6)<<ct[a++&3],o[a>>>2]|=(128|n&63)<<ct[a++&3]):n<55296||n>=57344?(o[a>>>2]|=(224|n>>>12)<<ct[a++&3],o[a>>>2]|=(128|n>>>6&63)<<ct[a++&3],o[a>>>2]|=(128|n&63)<<ct[a++&3]):(n=65536+((n&1023)<<10|e.charCodeAt(++i)&1023),o[a>>>2]|=(240|n>>>18)<<ct[a++&3],o[a>>>2]|=(128|n>>>12&63)<<ct[a++&3],o[a>>>2]|=(128|n>>>6&63)<<ct[a++&3],o[a>>>2]|=(128|n&63)<<ct[a++&3]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=o[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}};ut.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=Ry[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};ut.prototype.hash=function(){var e=this.h0,t=this.h1,r=this.h2,n=this.h3,i=this.h4,a=this.h5,s=this.h6,o=this.h7,c=this.blocks,u,l,d,f,p,h,m,b,x,v,I;for(u=16;u<64;++u)p=c[u-15],l=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[u-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[u]=c[u-16]+l+c[u-7]+d<<0;for(I=t&r,u=0;u<64;u+=4)this.first?(this.is224?(b=300032,p=c[0]-1413257819,o=p-150054599<<0,n=p+24177077<<0):(b=704751109,p=c[0]-210244248,o=p-1521486534<<0,n=p+143694565<<0),this.first=!1):(l=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),b=e&t,f=b^e&r^I,m=i&a^~i&s,p=o+d+m+Wi[u]+c[u],h=l+f,o=n+p<<0,n=p+h<<0),l=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),x=n&e,f=x^n&t^b,m=s&o^~s&i,p=a+d+m+Wi[u+1]+c[u+1],h=l+f,s=r+p<<0,r=p+h<<0,l=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),v=r&n,f=v^r&e^x,m=a&s^~a&o,p=i+d+m+Wi[u+2]+c[u+2],h=l+f,a=t+p<<0,t=p+h<<0,l=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),I=t&r,f=I^t&n^v,m=a&s^~a&o,p=i+d+m+Wi[u+3]+c[u+3],h=l+f,i=e+p<<0,e=p+h<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<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+s<<0,this.h7=this.h7+o<<0};ut.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,i=this.h4,a=this.h5,s=this.h6,o=this.h7,c=N[e>>>28&15]+N[e>>>24&15]+N[e>>>20&15]+N[e>>>16&15]+N[e>>>12&15]+N[e>>>8&15]+N[e>>>4&15]+N[e&15]+N[t>>>28&15]+N[t>>>24&15]+N[t>>>20&15]+N[t>>>16&15]+N[t>>>12&15]+N[t>>>8&15]+N[t>>>4&15]+N[t&15]+N[r>>>28&15]+N[r>>>24&15]+N[r>>>20&15]+N[r>>>16&15]+N[r>>>12&15]+N[r>>>8&15]+N[r>>>4&15]+N[r&15]+N[n>>>28&15]+N[n>>>24&15]+N[n>>>20&15]+N[n>>>16&15]+N[n>>>12&15]+N[n>>>8&15]+N[n>>>4&15]+N[n&15]+N[i>>>28&15]+N[i>>>24&15]+N[i>>>20&15]+N[i>>>16&15]+N[i>>>12&15]+N[i>>>8&15]+N[i>>>4&15]+N[i&15]+N[a>>>28&15]+N[a>>>24&15]+N[a>>>20&15]+N[a>>>16&15]+N[a>>>12&15]+N[a>>>8&15]+N[a>>>4&15]+N[a&15]+N[s>>>28&15]+N[s>>>24&15]+N[s>>>20&15]+N[s>>>16&15]+N[s>>>12&15]+N[s>>>8&15]+N[s>>>4&15]+N[s&15];return this.is224||(c+=N[o>>>28&15]+N[o>>>24&15]+N[o>>>20&15]+N[o>>>16&15]+N[o>>>12&15]+N[o>>>8&15]+N[o>>>4&15]+N[o&15]),c};ut.prototype.toString=ut.prototype.hex;ut.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,i=this.h4,a=this.h5,s=this.h6,o=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,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,s>>>24&255,s>>>16&255,s>>>8&255,s&255];return this.is224||c.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),c};ut.prototype.array=ut.prototype.digest;ut.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};var Ji=(...e)=>new ut(!1,!0).update(e.join("")).hex();var RC=L({sha256:()=>Ji});var LC=L({BaseCache:()=>Sf,InMemoryCache:()=>go,defaultHashKeyEncoder:()=>Ef,deserializeStoredGeneration:()=>Ny,serializeGeneration:()=>$y}),Ef=(...e)=>Ji(e.join("_"));function Ny(e){return e.message!==void 0?{text:e.text,message:Ha(e.message)}:{text:e.text}}function $y(e){let t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var Sf=class{keyEncoder=Ef;makeDefaultKeyEncoder(e){this.keyEncoder=e}},Py=new Map,go=class Tf extends Sf{cache;constructor(t){super(),this.cache=t??new Map}lookup(t,r){return Promise.resolve(this.cache.get(this.keyEncoder(t,r))??null)}async update(t,r,n){this.cache.set(this.keyEncoder(t,r),n)}static global(){return new Tf(Py)}};var My=Object.prototype.toString,jy=e=>My.call(e)==="[object Error]",Ly=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 Af(e){if(!(e&&jy(e)&&e.name==="TypeError"&&typeof e.message=="string"))return!1;let{message:t,stack:r}=e;return t==="Load failed"?r===void 0||"__sentry_captured__"in e:t.startsWith("error sending request for url")?!0:Ly.has(t)}function Dy(e){if(typeof e=="number"){if(e<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Ki(e,t,{min:r=0,allowInfinity:n=!1}={}){if(t!==void 0){if(typeof t!="number"||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<r)throw new TypeError(`Expected \`${e}\` to be \u2265 ${r}.`)}}var Uy=class extends Error{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 zy(e,t){let r=Math.max(1,e+1),n=t.randomize?Math.random()+1:1,i=Math.round(n*t.minTimeout*t.factor**(r-1));return i=Math.min(i,t.maxTimeout),i}function kf(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function By({error:e,attemptNumber:t,retriesConsumed:r,startTime:n,options:i}){let a=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(a instanceof Uy)throw a.originalError;let s=Number.isFinite(i.retries)?Math.max(0,i.retries-r):i.retries,o=i.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:a,attemptNumber:t,retriesLeft:s,retriesConsumed:r});if(await i.onFailedAttempt(c),kf(n,o)<=0)throw a;let u=await i.shouldConsumeRetry(c),l=kf(n,o);if(l<=0||s<=0)throw a;if(a instanceof TypeError&&!Af(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 d=zy(r,i),f=typeof a.retryAfterMs=="number"&&a.retryAfterMs>=0?a.retryAfterMs:void 0;f!==void 0&&(d=Math.max(d,f));let p=Math.min(d,l);return p>0&&await new Promise((h,m)=>{let b=()=>{clearTimeout(x),i.signal?.removeEventListener("abort",b),m(i.signal.reason)},x=setTimeout(()=>{i.signal?.removeEventListener("abort",b),h()},p);i.unref&&x.unref?.(),i.signal?.addEventListener("abort",b,{once:!0})}),i.signal?.throwIfAborted(),!0}async function Sn(e,t={}){if(t={...t},Dy(t.retries),Object.hasOwn(t,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=Number.POSITIVE_INFINITY,t.maxRetryTime??=Number.POSITIVE_INFINITY,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,Ki("factor",t.factor,{min:0,allowInfinity:!1}),Ki("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),Ki("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),Ki("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let r=0,n=0,i=performance.now();for(;!Number.isFinite(t.retries)||n<=t.retries;){r++;try{t.signal?.throwIfAborted();let a=await e(r);return t.signal?.throwIfAborted(),a}catch(a){await By({error:a,attemptNumber:r,retriesConsumed:n,startTime:i,options:t})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Yi=jn(_i(),1),qC=L({AsyncCaller:()=>Sr,classifyRateLimitError:()=>$f,parseRetryAfterMs:()=>Nf}),Fy=[400,401,402,403,404,405,406,407,409],Hy=6e4,Gy=[/insufficient[_ -]?quota/i,/exceeded (?:your|the current|the available).+quota/i,/usage quota/i,/quota (?:has been )?exhausted/i,/billing/i,/credit balance/i,/out of credits/i,/will reset at/i],Vy=/(?:try again in|retry after)\s+(\d+(?:\.\d+)?)\s*(milliseconds?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h)\b/i;function Cf(e){return typeof e=="object"&&e!==null&&"response"in e&&typeof e.response=="object"&&e.response!==null&&"status"in e.response&&typeof e.response.status=="number"?e.response.status:void 0}function Of(e){if(!(typeof e!="object"||e===null)){if("status"in e&&typeof e.status=="number")return e.status;if("statusCode"in e&&typeof e.statusCode=="number")return e.statusCode}}function yo(e){return typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"?e.message:void 0}function Rf(e){if(!(typeof e!="object"||e===null))return"code"in e&&typeof e.code=="string"?e.code:"error"in e&&typeof e.error=="object"&&e.error!==null&&"code"in e.error&&typeof e.error.code=="string"?e.error.code:void 0}function Zy(e){if(e?.headers)return typeof e.headers.get=="function"?e.headers.get("retry-after"):e.headers["retry-after"]??e.headers["Retry-After"];if(e?.response?.headers)return typeof e.response.headers.get=="function"?e.response.headers.get("retry-after"):e.response.headers["retry-after"]??e.response.headers["Retry-After"]}function qy(e){if(e==null)return;let t=Vy.exec(e);if(!t)return;let r=Number(t[1]),n=t[2]?.toLowerCase();if(!(Number.isNaN(r)||!n))return n==="ms"||n.startsWith("millisecond")?r:n==="m"||n.startsWith("min")?r*6e4:n==="h"||n.startsWith("hr")||n.startsWith("hour")?r*36e5:r*1e3}function If(e,t){if(e instanceof Error)return e;let r=new Error(t);return typeof e=="object"&&e!==null&&Object.assign(r,e),r}function _o(e,t){if(typeof e!="object"||e===null)return;let r=e;r.rateLimitType=t.action,r.rateLimitReason=t.reason,t.retryAfterMs!==void 0&&(r.retryAfterMs=t.retryAfterMs)}function Nf(e){if(e==null)return;let t=e.trim();if(!t)return;let r=Number(t);if(!Number.isNaN(r)&&r>=0)return r*1e3;let n=Date.parse(t);if(!Number.isNaN(n)){let i=n-Date.now();return i>0?i:0}}function $f(e){if((Cf(e)??Of(e))!==429)return;if(Rf(e)==="insufficient_quota")return{action:"stop",reason:"insufficient_quota"};let t=yo(e);if(t&&Gy.some(n=>n.test(t)))return{action:"stop",reason:"quota_message"};let r=Nf(Zy(e))??qy(t);return r!==void 0?r<=Hy?{action:"wait",retryAfterMs:r,reason:"retry_after_hint"}:{action:"capacity",retryAfterMs:r,reason:"retry_after_too_large"}:{action:"capacity",reason:"headerless_429"}}var Wy=e=>{if(typeof e!="object"||e===null)return;if("message"in e&&typeof e.message=="string"&&(e.message.startsWith("Cancel")||e.message.startsWith("AbortError"))||"name"in e&&typeof e.name=="string"&&e.name==="AbortError"||"code"in e&&typeof e.code=="string"&&e.code==="ECONNABORTED")throw e;let t=Cf(e)??Of(e);if(t&&Fy.includes(+t))throw e;if(Rf(e)==="insufficient_quota"){let n=If(e,yo(e)??"Insufficient quota");throw n.name="InsufficientQuotaError",_o(n,{action:"stop",reason:"insufficient_quota"}),n}let r=$f(e);if(r){if(r.action==="wait"){_o(e,r);return}let n=If(e,yo(e)??"Rate limit exceeded");throw n.name==="Error"&&(n.name=r.action==="stop"?"RateLimitQuotaExhaustedError":"RateLimitCapacityError"),_o(n,r),n}},Sr=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??Wy;let t="default"in Yi.default?Yi.default.default:Yi.default;this.queue=new t({concurrency:this.maxConcurrency})}async call(e,...t){return this.queue.add(()=>Sn(()=>e(...t).catch(r=>{throw r instanceof Error?r:new Error(r)}),{onFailedAttempt:({error:r})=>this.onFailedAttempt?.(r),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){if(e.signal){let n;return Promise.race([this.call(t,...r),new Promise((i,a)=>{n=()=>{a(Bt(e.signal))},e.signal?.addEventListener("abort",n,{once:!0})})]).finally(()=>{e.signal&&n&&e.signal.removeEventListener("abort",n)})}return this.call(t,...r)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}};var tO=L({AsyncGeneratorWithSetup:()=>qt,IterableReadableStream:()=>Re,atee:()=>Xi,concat:()=>Qi,pipeGeneratorWithSetup:()=>bo}),Re=class wo extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let t=await this.reader.read();return t.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:t.value}}catch(t){throw this.reader.releaseLock(),t}}async return(){if(this.ensureReader(),this.locked){let t=this.reader.cancel();this.reader.releaseLock(),await t}return{done:!0,value:void 0}}async throw(t){if(this.ensureReader(),this.locked){let r=this.reader.cancel();this.reader.releaseLock(),await r}throw t}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){let r=t.getReader();return new wo({start(n){return i();function i(){return r.read().then(({done:a,value:s})=>{if(a){n.close();return}return n.enqueue(s),i()})}},cancel(){r.releaseLock()}})}static fromAsyncGenerator(t){return new wo({async pull(r){let{value:n,done:i}=await t.next();i&&r.close(),r.enqueue(n)},async cancel(r){await t.return(r)}})}};function Xi(e,t=2){let r=Array.from({length:t},()=>[]);return r.map(async function*(i){for(;;)if(i.length===0){let a=await e.next();for(let s of r)s.push(a)}else{if(i[0].done)return;yield i.shift().value}})}function Qi(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if(typeof e=="string"&&typeof t=="string")return e+t;if(typeof e=="number"&&typeof t=="number")return e+t;if("concat"in e&&typeof e.concat=="function")return e.concat(t);if(typeof e=="object"&&typeof t=="object"){let r={...e};for(let[n,i]of Object.entries(t))n in r&&!Array.isArray(r[n])?r[n]=Qi(r[n],i):r[n]=i;return r}else throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}var qt=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,r)=>{be.runWithConfig(We(e.config),async()=>{this.firstResult=this.signal?nt(e.generator.next(),this.signal):e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then(n=>t(void 0),r)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?be.runWithConfig(We(this.config),this.signal?async()=>nt(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function bo(e,t,r,n,...i){let a=new qt({generator:t,startSetup:r,signal:n}),s=await a.setup;return{output:e(a,s,...i),setup:s}}var Jy=Object.prototype.hasOwnProperty;function ta(e,t){return Jy.call(e,t)}function ra(e){if(Array.isArray(e)){let r=new Array(e.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(e);let t=[];for(let r in e)ta(e,r)&&t.push(r);return t}function He(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function na(e){let t=0,r=e.length,n;for(;t<r;){if(n=e.charCodeAt(t),n>=48&&n<=57){t++;continue}return!1}return!0}function Tr(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function Mf(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function ea(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let r=0,n=e.length;r<n;r++)if(ea(e[r]))return!0}else if(typeof e=="object"){let r=ra(e),n=r.length;for(var t=0;t<n;t++)if(ea(e[r[t]]))return!0}}return!1}function Pf(e,t){let r=[e];for(let n in t){let i=typeof t[n]=="object"?JSON.stringify(t[n],null,2):t[n];typeof i<"u"&&r.push(`${n}: ${i}`)}return r.join(`
|
|
158
|
+
`)}var jf=class extends Error{constructor(e,t,r,n,i){super(Pf(e,{name:t,index:r,operation:n,tree:i})),this.name=t,this.index=r,this.operation=n,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=Pf(e,{name:t,index:r,operation:n,tree:i})}};var Lf=L({JsonPatchError:()=>ue,_areEquals:()=>Tn,applyOperation:()=>Ar,applyPatch:()=>tn,applyReducer:()=>Xy,deepClone:()=>Ky,getValueByPointer:()=>ia,validate:()=>Df,validator:()=>aa}),ue=jf,Ky=He,en={add:function(e,t,r){if(t==="__proto__"||t==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return e[t]=this.value,{newDocument:r}},remove:function(e,t,r){if(t==="__proto__"||t==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=e[t];return delete e[t],{newDocument:r,removed:n}},replace:function(e,t,r){if(t==="__proto__"||t==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:function(e,t,r){let n=ia(r,this.path);n&&(n=He(n));let i=Ar(r,{op:"remove",path:this.from}).removed;return Ar(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},copy:function(e,t,r){let n=ia(r,this.from);return Ar(r,{op:"add",path:this.path,value:He(n)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:Tn(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}},Yy={add:function(e,t,r){return na(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:r,index:t}},remove:function(e,t,r){return{newDocument:r,removed:e.splice(t,1)[0]}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:en.move,copy:en.copy,test:en.test,_get:en._get};function ia(e,t){if(t=="")return e;var r={op:"_get",path:t};return Ar(e,r),r.value}function Ar(e,t,r=!1,n=!0,i=!0,a=0){if(r&&(typeof r=="function"?r(t,0,e,t.path):aa(t,0)),t.path===""){let s={newDocument:e};if(t.op==="add")return s.newDocument=t.value,s;if(t.op==="replace")return s.newDocument=t.value,s.removed=e,s;if(t.op==="move"||t.op==="copy")return s.newDocument=ia(e,t.from),t.op==="move"&&(s.removed=e),s;if(t.op==="test"){if(s.test=Tn(e,t.value),s.test===!1)throw new ue("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return s.newDocument=e,s}else{if(t.op==="remove")return s.removed=e,s.newDocument=null,s;if(t.op==="_get")return t.value=e,s;if(r)throw new ue("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",a,t,e);return s}}else{n||(e=He(e));let s=(t.path||"").split("/"),o=e,c=1,u=s.length,l,d,f;for(typeof r=="function"?f=r:f=aa;;){if(d=s[c],d&&d.indexOf("~")!=-1&&(d=Mf(d)),i&&(d=="__proto__"||d=="prototype"&&c>0&&s[c-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&l===void 0&&(o[d]===void 0?l=s.slice(0,c).join("/"):c==u-1&&(l=t.path),l!==void 0&&f(t,0,e,l)),c++,Array.isArray(o)){if(d==="-")d=o.length;else{if(r&&!na(d))throw new ue("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,t,e);na(d)&&(d=~~d)}if(c>=u){if(r&&t.op==="add"&&d>o.length)throw new ue("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,t,e);let p=Yy[t.op].call(t,o,d,e);if(p.test===!1)throw new ue("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return p}}else if(c>=u){let p=en[t.op].call(t,o,d,e);if(p.test===!1)throw new ue("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return p}if(o=o[d],r&&c<u&&(!o||typeof o!="object"))throw new ue("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",a,t,e)}}}function tn(e,t,r,n=!0,i=!0){if(r&&!Array.isArray(t))throw new ue("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(e=He(e));let a=new Array(t.length);for(let s=0,o=t.length;s<o;s++)a[s]=Ar(e,t[s],r,!0,i,s),e=a[s].newDocument;return a.newDocument=e,a}function Xy(e,t,r){let n=Ar(e,t);if(n.test===!1)throw new ue("Test operation failed","TEST_OPERATION_FAILED",r,t,e);return n.newDocument}function aa(e,t,r,n){if(typeof e!="object"||e===null||Array.isArray(e))throw new ue("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(en[e.op]){if(typeof e.path!="string")throw new ue("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new ue('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new ue("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new ue("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);if((e.op==="add"||e.op==="replace"||e.op==="test")&&ea(e.value))throw new ue("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);if(r){if(e.op=="add"){var i=e.path.split("/").length,a=n.split("/").length;if(i!==a+1&&i!==a)throw new ue("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==n)throw new ue("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if(e.op==="move"||e.op==="copy"){var s=Df([{op:"_get",path:e.from,value:void 0}],r);if(s&&s.name==="OPERATION_PATH_UNRESOLVABLE")throw new ue("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}}else throw new ue("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r)}function Df(e,t,r){try{if(!Array.isArray(e))throw new ue("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)tn(He(t),He(e),r||!0);else{r=r||aa;for(var n=0;n<e.length;n++)r(e[n],n,t,void 0)}}catch(i){if(i instanceof ue)return i;throw i}}function Tn(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var r=Array.isArray(e),n=Array.isArray(t),i,a,s;if(r&&n){if(a=e.length,a!=t.length)return!1;for(i=a;i--!==0;)if(!Tn(e[i],t[i]))return!1;return!0}if(r!=n)return!1;var o=Object.keys(e);if(a=o.length,a!==Object.keys(t).length)return!1;for(i=a;i--!==0;)if(!t.hasOwnProperty(o[i]))return!1;for(i=a;i--!==0;)if(s=o[i],!Tn(e[s],t[s]))return!1;return!0}return e!==e&&t!==t}function Uf(e,t,r,n,i){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var a=ra(t),s=ra(e),o=!1,c=s.length-1;c>=0;c--){var u=s[c],l=e[u];if(ta(t,u)&&!(t[u]===void 0&&l!==void 0&&Array.isArray(t)===!1)){var d=t[u];typeof l=="object"&&l!=null&&typeof d=="object"&&d!=null&&Array.isArray(l)===Array.isArray(d)?Uf(l,d,r,n+"/"+Tr(u),i):l!==d&&(i&&r.push({op:"test",path:n+"/"+Tr(u),value:He(l)}),r.push({op:"replace",path:n+"/"+Tr(u),value:He(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&r.push({op:"test",path:n+"/"+Tr(u),value:He(l)}),r.push({op:"remove",path:n+"/"+Tr(u)}),o=!0):(i&&r.push({op:"test",path:n,value:e}),r.push({op:"replace",path:n,value:t}))}if(!(!o&&a.length==s.length))for(var c=0;c<a.length;c++){var u=a[c];!ta(e,u)&&t[u]!==void 0&&r.push({op:"add",path:n+"/"+Tr(u),value:He(t[u])})}}}function dO(e,t,r=!1){var n=[];return Uf(e,t,n,"",r),n}({...Lf});var xO=L({LogStreamCallbackHandler:()=>oa,RunLog:()=>sa,RunLogPatch:()=>Et,isLogStreamHandler:()=>xo}),Et=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),r=tn({},t);return new sa({ops:t,state:r[r.length-1].newDocument})}},sa=class vo extends Et{state;constructor(t){super(t),this.state=t.state}concat(t){let r=this.ops.concat(t.ops),n=tn(this.state,t.ops);return new vo({ops:r,state:n[n.length-1].newDocument})}static fromRunLogPatch(t){let r=tn({},t.ops);return new vo({ops:t.ops,state:r[r.length-1].newDocument})}},xo=e=>e.name==="log_stream_tracer";async function zf(e,t){if(t==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");let{inputs:r}=e;if(["retriever","llm","prompt"].includes(e.run_type))return r;if(!(Object.keys(r).length===1&&r?.input===""))return r.input}async function Bf(e,t){let{outputs:r}=e;return t==="original"||["retriever","llm","prompt"].includes(e.run_type)?r:r!==void 0&&Object.keys(r).length===1&&r?.output!==void 0?r.output:r}function Qy(e){return e!==void 0&&e.message!==void 0}var oa=class extends tt{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Re.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let t=e.tags??[],r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(r=r||t.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(r=r&&t.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(e,t){for await(let r of t){if(e!==this.rootId){let n=this.keyMapByRunId[e];n&&await this.writer.write(new Et({ops:[{op:"add",path:`/logs/${n}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new Et({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;let r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await zf(e,this._schemaFormat)),await this.writer.write(new Et({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(t===void 0)return;let r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await zf(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await Bf(e,this._schemaFormat)}),e.end_time!==void 0&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let n=new Et({ops:r});await this.writer.write(n)}finally{if(e.id===this.rootId){let t=new Et({ops:[{op:"replace",path:"/final_output",value:await Bf(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){let n=this.keyMapByRunId[e.id];if(n===void 0)return;let i=e.inputs.messages!==void 0,a;i?Qy(r?.chunk)?a=r?.chunk:a=new Nr({id:`run-${e.id}`,content:t}):a=t;let s=new Et({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${n}/streamed_output/-`,value:a}]});await this.writer.write(s)}};var kO=L({ChatGenerationChunk:()=>tw,GenerationChunk:()=>An,RUN_KEY:()=>ew}),ew="__run",An=class Ff{text;generationInfo;constructor(t){this.text=t.text,this.generationInfo=t.generationInfo}concat(t){return new Ff({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},tw=class Hf extends An{message;constructor(t){super(t),this.message=t.message}concat(t){return new Hf({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function ca({name:e,serialized:t}){return e!==void 0?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}var Gf=e=>e.name==="event_stream_tracer",Vf=class extends tt{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;readableStreamClosed=!1;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Re.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(r=r||t.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(r=r&&t.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(e,t){let r=await t.next();if(r.done)return;let n=this.runInfoMap.get(e);if(n===void 0){yield r.value;return}function i(s,o){return s==="llm"&&typeof o=="string"?new An({text:o}):o}let a=this.tappedPromises.get(e);if(a===void 0){let s;a=new Promise(o=>{s=o}),this.tappedPromises.set(e,a);try{let o={event:`on_${n.runType}_stream`,run_id:e,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};await this.send({...o,data:{chunk:i(n.runType,r.value)}},n),yield r.value;for await(let c of t)n.runType!=="tool"&&n.runType!=="retriever"&&await this.send({...o,data:{chunk:i(n.runType,c)}},n),yield c}finally{s?.()}}else{yield r.value;for await(let s of t)yield s}}async send(e,t){this.readableStreamClosed||this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let r=this.tappedPromises.get(e.run_id);r!==void 0?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){let t=ca(e),r=e.inputs.messages!==void 0?"chat_model":"llm",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,n);let i=`on_${r}_start`;await this.send({event:i,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onLLMNewToken(e,t,r){let n=this.runInfoMap.get(e.id),i,a;if(n===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(n.runType==="chat_model")a="on_chat_model_stream",r?.chunk===void 0?i=new Nr({content:t,id:`run-${e.id}`}):i=r.chunk.message;else if(n.runType==="llm")a="on_llm_stream",r?.chunk===void 0?i=new An({text:t}):i=r.chunk;else throw new Error(`Unexpected run type ${n.runType}`);await this.send({event:a,data:{chunk:i},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(e){let t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let r;if(t===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let n=e.outputs?.generations,i;if(t.runType==="chat_model"){for(let a of n??[]){if(i!==void 0)break;i=a[0]?.message}r="on_chat_model_end"}else if(t.runType==="llm")i={generations:n?.map(a=>a.map(s=>({text:s.text,generationInfo:s.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:r,data:{output:i,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){let t=ca(e),r=e.run_type??"chain",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},i={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(i={},n.inputs={}):e.inputs.input!==void 0?(i.input=e.inputs.input,n.inputs=e.inputs.input):(i.input=e.inputs,n.inputs=e.inputs),this.runInfoMap.set(e.id,n),await this.send({event:`on_${r}_start`,data:i,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onChainEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let r=`on_${e.run_type}_end`,n=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:n};n.input&&Object.keys(n).length===1&&(i.input=n.input,t.inputs=n.input),await this.sendEndEvent({event:r,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=ca(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let r=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onToolError(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:t.inputs,error:e.error},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){let t=ca(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,r){let n=this.runInfoMap.get(r);if(n===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:n.tags,metadata:n.metadata,data:t},n)}async finish(){let e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}};var Eo=class extends tt{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:r,onError:n}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=r,this.argOnError=n}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function kn(e){return e?e.lc_runnable:!1}var Zf=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let r=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,n=e.tags??[];return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t)),this.includeTags!==void 0&&(r=r||n.some(i=>this.includeTags?.includes(i))),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(r=r&&n.every(i=>!this.excludeTags?.includes(i))),r}},qf=e=>btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");function So(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}var rw=["*","_","`"];function nw(e){let t="";for(let[r,n]of Object.entries(e))t+=` classDef ${r} ${n};
|
|
159
|
+
`;return t}function Wf(e,t,r){let{firstNode:n,lastNode:i,nodeColors:a,withStyles:s=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=r??{},u=s?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
|
|
160
|
+
graph TD;
|
|
161
|
+
`:`graph TD;
|
|
162
|
+
`;if(s){let h="default",m={[h]:"{0}({1})"};n!==void 0&&(m[n]="{0}([{1}]):::first"),i!==void 0&&(m[i]="{0}([{1}]):::last");for(let[b,x]of Object.entries(e)){let v=x.name.split(":").pop()??"",I=rw.some(j=>v.startsWith(j)&&v.endsWith(j))?`<p>${v}</p>`:v;Object.keys(x.metadata??{}).length&&(I+=`<hr/><small><em>${Object.entries(x.metadata??{}).map(([j,X])=>`${j} = ${X}`).join(`
|
|
163
|
+
`)}</em></small>`);let k=(m[b]??m[h]).replace("{0}",So(b)).replace("{1}",I);u+=` ${k}
|
|
164
|
+
`}}let l={};for(let h of t){let m=h.source.split(":"),b=h.target.split(":"),x=m.filter((v,I)=>v===b[I]).join(":");l[x]||(l[x]=[]),l[x].push(h)}let d=new Set;function f(h){return[...h].sort((m,b)=>m.split(":").length-b.split(":").length)}function p(h,m){let b=h.length===1&&h[0].source===h[0].target;if(m&&!b){let v=m.split(":").pop();if(d.has(m))throw new Error(`Found duplicate subgraph '${v}' at '${m} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(m),u+=` subgraph ${v}
|
|
165
|
+
`}let x=f(Object.keys(l).filter(v=>v.startsWith(`${m}:`)&&v!==m&&v.split(":").length===m.split(":").length+1));for(let v of x)p(l[v],v);for(let v of h){let{source:I,target:k,data:j,conditional:X}=v,K="";if(j!==void 0){let Q=j,ee=Q.split(" ");ee.length>c&&(Q=Array.from({length:Math.ceil(ee.length/c)},(fe,Ae)=>ee.slice(Ae*c,(Ae+1)*c).join(" ")).join(" <br> ")),K=X?` -. ${Q} .-> `:` -- ${Q} --> `}else K=X?" -.-> ":" --> ";u+=` ${So(I)}${K}${So(k)};
|
|
166
|
+
`}m&&!b&&(u+=` end
|
|
167
|
+
`)}p(l[""]??[],"");for(let h in l)!h.includes(":")&&h!==""&&p(l[h],h);return s&&(u+=nw(a??{})),u}async function Jf(e,t){let r=t?.backgroundColor??"white",n=t?.imageType??"png",i=qf(e);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));let a=`https://mermaid.ink/img/${i}?bgColor=${r}&type=${n}`,s=await fetch(a);if(!s.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${s.status}`,`Status text: ${s.statusText}`].join(`
|
|
168
|
+
`));return await s.blob()}var qO=L({Graph:()=>ua});function iw(e,t){if(e!==void 0&&!$r(e))return e;if(kn(t))try{let r=t.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return t.getName()}else return t.name??"UnknownSchema"}function aw(e){return kn(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...fo(e.data.schema),title:e.data.name}}}var ua=class Xf{nodes={};edges=[];constructor(t){this.nodes=t?.nodes??this.nodes,this.edges=t?.edges??this.edges}toJSON(){let t={};return Object.values(this.nodes).forEach((r,n)=>{t[r.id]=$r(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:t[r.id],...aw(r)})),edges:this.edges.map(r=>{let n={source:t[r.source],target:t[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(t,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);let i=r??Za(),a={id:i,data:t,name:iw(r,t),metadata:n};return this.nodes[i]=a,a}removeNode(t){delete this.nodes[t.id],this.edges=this.edges.filter(r=>r.source!==t.id&&r.target!==t.id)}addEdge(t,r,n,i){if(this.nodes[t.id]===void 0)throw new Error(`Source node ${t.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);let a={source:t.id,target:r.id,data:n,conditional:i};return this.edges.push(a),a}firstNode(){return Kf(this)}lastNode(){return Yf(this)}extend(t,r=""){let n=r;Object.values(t.nodes).map(c=>c.id).every($r)&&(n="");let i=c=>n?`${n}:${c}`:c;Object.entries(t.nodes).forEach(([c,u])=>{this.nodes[i(c)]={...u,id:i(c)}});let a=t.edges.map(c=>({...c,source:i(c.source),target:i(c.target)}));this.edges=[...this.edges,...a];let s=t.firstNode(),o=t.lastNode();return[s?{id:i(s.id),data:s.data}:void 0,o?{id:i(o.id),data:o.data}:void 0]}trimFirstNode(){let t=this.firstNode();t&&Kf(this,[t.id])&&this.removeNode(t)}trimLastNode(){let t=this.lastNode();t&&Yf(this,[t.id])&&this.removeNode(t)}reid(){let t=Object.fromEntries(Object.values(this.nodes).map(i=>[i.id,i.name])),r=new Map;Object.values(t).forEach(i=>{r.set(i,(r.get(i)||0)+1)});let n=i=>{let a=t[i];return $r(i)&&r.get(a)===1?a:i};return new Xf({nodes:Object.fromEntries(Object.entries(this.nodes).map(([i,a])=>[n(i),{...a,id:n(i)}])),edges:this.edges.map(i=>({...i,source:n(i.source),target:n(i.target)}))})}drawMermaid(t){let{withStyles:r,curveStyle:n,nodeColors:i={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:a}=t??{},s=this.reid(),o=s.firstNode(),c=s.lastNode();return Wf(s.nodes,s.edges,{firstNode:o?.id,lastNode:c?.id,withStyles:r,curveStyle:n,nodeColors:i,wrapLabelNWords:a})}async drawMermaidPng(t){return Jf(this.drawMermaid(t),{backgroundColor:t?.backgroundColor})}};function Kf(e,t=[]){let r=new Set(e.edges.filter(i=>!t.includes(i.source)).map(i=>i.target)),n=[];for(let i of Object.values(e.nodes))!t.includes(i.id)&&!r.has(i.id)&&n.push(i);return n.length===1?n[0]:void 0}function Yf(e,t=[]){let r=new Set(e.edges.filter(i=>!t.includes(i.target)).map(i=>i.source)),n=[];for(let i of Object.values(e.nodes))!t.includes(i.id)&&!r.has(i.id)&&n.push(i);return n.length===1?n[0]:void 0}function Qf(e){let t=new TextEncoder,r=new ReadableStream({async start(n){for await(let i of e)n.enqueue(t.encode(`event: data
|
|
169
|
+
data: ${JSON.stringify(i)}
|
|
170
|
+
|
|
171
|
+
`));n.enqueue(t.encode(`event: end
|
|
172
|
+
|
|
173
|
+
`)),n.close()}});return Re.fromReadableStream(r)}function ge(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}var _e=class extends ft{lc_runnable=!0;name;getName(e){let t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new np({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new la({bound:this,config:e,kwargs:{}})}withFallbacks(e){let t=Array.isArray(e)?e:e.fallbacks;return new cw({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(Y);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let r=Object.fromEntries(Object.entries(e).filter(([n])=>n!=="runId"));return Array.from({length:t},(n,i)=>Y(i===0?e:r))}return Array.from({length:t},()=>Y(e))}async batch(e,t,r){let n=this._getOptionsList(t??{},e.length),i=new Sr({maxConcurrency:n[0]?.maxConcurrency??r?.maxConcurrency,onFailedAttempt:s=>{throw s}}),a=e.map((s,o)=>i.call(async()=>{try{return await this.invoke(s,n[o])}catch(c){if(r?.returnExceptions)return c;throw c}}));return Promise.all(a)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let r=Y(t),n=new qt({generator:this._streamIterator(e,r),config:r});return await n.setup,Re.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=Y(e):t=Y({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});let r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[t,r]}async _callWithConfig(e,t,r){let n=Y(r),i=await(await qe(n))?.handleChainStart(this.toJSON(),ge(t,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName());delete n.runId;let a;try{a=await nt(e.call(this,t,n,i),n.signal)}catch(s){throw await i?.handleChainError(s),s}return await i?.handleChainEnd(ge(a,"output")),a}async _batchWithConfig(e,t,r,n){let i=this._getOptionsList(r??{},t.length),a=await Promise.all(i.map(qe)),s=await Promise.all(a.map(async(c,u)=>{let l=await c?.handleChainStart(this.toJSON(),ge(t[u],"input"),i[u].runId,i[u].runType,void 0,void 0,i[u].runName??this.getName());return delete i[u].runId,l})),o;try{o=await nt(e.call(this,t,i,s,n),i?.[0]?.signal)}catch(c){throw await Promise.all(s.map(u=>u?.handleChainError(c))),c}return await Promise.all(s.map(c=>c?.handleChainEnd(ge(o,"output")))),o}_concatOutputChunks(e,t){return Qi(e,t)}async*_transformStreamWithConfig(e,t,r){let n,i=!0,a,s=!0,o=Y(r),c=await qe(o),u=this;async function*l(){for await(let f of e){if(i)if(n===void 0)n=f;else try{n=u._concatOutputChunks(n,f)}catch{n=void 0,i=!1}yield f}}let d;try{let f=await bo(t.bind(this),l(),async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName(),void 0,{lc_defers_inputs:!0}),o.signal,o);delete o.runId,d=f.setup;let p=d?.handlers.find(Gf),h=f.output;p!==void 0&&d!==void 0&&(h=p.tapOutputIterable(d.runId,h));let m=d?.handlers.find(xo);m!==void 0&&d!==void 0&&(h=m.tapOutputIterable(d.runId,h));for await(let b of h)if(yield b,s)if(a===void 0)a=b;else try{a=this._concatOutputChunks(a,b)}catch{a=void 0,s=!1}}catch(f){throw await d?.handleChainError(f,void 0,void 0,void 0,{inputs:ge(n,"input")}),f}await d?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:ge(n,"input")})}getGraph(e){let t=new ua,r=t.addNode({name:`${this.getName()}Input`,schema:vt.any()}),n=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:vt.any()});return t.addEdge(r,n),t.addEdge(n,i),t}pipe(e){return new ip({first:this,last:kr(e)})}pick(e){return this.pipe(new lw(e))}assign(e){return this.pipe(new uw(new da({steps:e})))}async*transform(e,t){let r;for await(let n of e)r===void 0?r=n:r=this._concatOutputChunks(r,n);yield*this._streamIterator(r,Y(t))}async*streamLog(e,t,r){let n=new oa({...r,autoClose:!1,_schemaFormat:"original"}),i=Y(t);yield*this._streamLog(e,n,i)}async*_streamLog(e,t,r){let{callbacks:n}=r;if(n===void 0)r.callbacks=[t];else if(Array.isArray(n))r.callbacks=n.concat([t]);else{let o=n.copy();o.addHandler(t,!0),r.callbacks=o}let i=this.stream(e,r);async function a(){try{let o=await i;for await(let c of o){let u=new Et({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(u)}}finally{await t.writer.close()}}let s=a();try{for await(let o of t)yield o}finally{await s}}streamEvents(e,t,r){let n;if(t.version==="v1")n=this._streamEventsV1(e,t,r);else if(t.version==="v2")n=this._streamEventsV2(e,t,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?Qf(n):Re.fromAsyncGenerator(n)}async*_streamEventsV2(e,t,r){let n=new Vf({...r,autoClose:!1}),i=Y(t),a=i.runId??Ge();i.runId=a;let s=i.callbacks;if(s===void 0)i.callbacks=[n];else if(Array.isArray(s))i.callbacks=s.concat(n);else{let p=s.copy();p.addHandler(n,!0),i.callbacks=p}let o=new AbortController,c=this;async function u(){let p;try{if(i.signal)if("any"in AbortSignal)p=AbortSignal.any([o.signal,i.signal]);else{let b=new AbortController;i.signal.addEventListener("abort",()=>b.abort(),{once:!0}),o.signal.addEventListener("abort",()=>b.abort(),{once:!0}),p=b.signal}else p=o.signal;let h=await c.stream(e,{...i,signal:p}),m=n.tapOutputIterable(a,h);for await(let b of m)if(o.signal.aborted)break}finally{await n.finish()}}let l=u(),d=!1,f;try{for await(let p of n){if(!d){p.data.input=e,d=!0,f=p.run_id,yield p;continue}p.run_id===f&&p.event.endsWith("_end")&&p.data?.input&&delete p.data.input,yield p}}finally{o.abort(),await l}}async*_streamEventsV1(e,t,r){let n,i=!1,a=Y(t),s=a.tags??[],o=a.metadata??{},c=a.runName??this.getName(),u=new oa({...r,autoClose:!1,_schemaFormat:"streaming_events"}),l=new Zf({...r}),d=this._streamLog(e,u,a);for await(let p of d){if(n?n=n.concat(p):n=sa.fromRunLogPatch(p),n.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;let x={...n.state},v={run_id:x.id,event:`on_${x.type}_start`,name:c,tags:s,metadata:o,data:{input:e}};l.includeEvent(v,x.type)&&(yield v)}let h=p.ops.filter(x=>x.path.startsWith("/logs/")).map(x=>x.path.split("/")[2]),m=[...new Set(h)];for(let x of m){let v,I={},k=n.state.logs[x];if(k.end_time===void 0?k.streamed_output.length>0?v="stream":v="start":v="end",v==="start")k.inputs!==void 0&&(I.input=k.inputs);else if(v==="end")k.inputs!==void 0&&(I.input=k.inputs),I.output=k.final_output;else if(v==="stream"){let j=k.streamed_output.length;if(j!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${j} instead. Encountered in: "${k.name}"`);I={chunk:k.streamed_output[0]},k.streamed_output=[]}yield{event:`on_${k.type}_${v}`,name:k.name,run_id:k.id,tags:k.tags,metadata:k.metadata,data:I}}let{state:b}=n;if(b.streamed_output.length>0){let x=b.streamed_output.length;if(x!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${x} instead. Encountered in: "${b.name}"`);let v={chunk:b.streamed_output[0]};b.streamed_output=[];let I={event:`on_${b.type}_stream`,run_id:b.id,tags:s,metadata:o,name:c,data:v};l.includeEvent(I,b.type)&&(yield I)}}let f=n?.state;if(f!==void 0){let p={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:s,metadata:o,data:{output:f.final_output}};l.includeEvent(p,f.type)&&(yield p)}}static isRunnable(e){return kn(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new la({bound:this,config:{},configFactories:[n=>({callbacks:[new Eo({config:n,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return dw(this,e)}},la=class tp extends _e{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(t){super(t),this.bound=t.bound,this.kwargs=t.kwargs,this.config=t.config,this.configFactories=t.configFactories}getName(t){return this.bound.getName(t)}async _mergeConfig(...t){let r=wn(this.config,...t);return wn(r,...this.configFactories?await Promise.all(this.configFactories.map(async n=>await n(r))):[])}withConfig(t){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...t}})}withRetry(t){return new np({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:t?.stopAfterAttempt,...t})}async invoke(t,r){return this.bound.invoke(t,await this._mergeConfig(r,this.kwargs))}async batch(t,r,n){let i=Array.isArray(r)?await Promise.all(r.map(async a=>this._mergeConfig(Y(a),this.kwargs))):await this._mergeConfig(Y(r),this.kwargs);return this.bound.batch(t,i,n)}_concatOutputChunks(t,r){return this.bound._concatOutputChunks(t,r)}async*_streamIterator(t,r){yield*this.bound._streamIterator(t,await this._mergeConfig(Y(r),this.kwargs))}async stream(t,r){return this.bound.stream(t,await this._mergeConfig(Y(r),this.kwargs))}async*transform(t,r){yield*this.bound.transform(t,await this._mergeConfig(Y(r),this.kwargs))}streamEvents(t,r,n){let i=this,a=async function*(){yield*i.bound.streamEvents(t,{...await i._mergeConfig(Y(r),i.kwargs),version:r.version},n)};return Re.fromAsyncGenerator(a())}static isRunnableBinding(t){return t.bound&&_e.isRunnable(t.bound)}withListeners({onStart:t,onEnd:r,onError:n}){return new tp({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[i=>({callbacks:[new Eo({config:i,onStart:t,onEnd:r,onError:n})]})]})}},_R=class rp extends _e{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(t){super(t),this.bound=t.bound}async invoke(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async _invoke(t,r,n){return this.bound.batch(t,le(r,{callbacks:n?.getChild()}))}withListeners({onStart:t,onEnd:r,onError:n}){return new rp({bound:this.bound.withListeners({onStart:t,onEnd:r,onError:n})})}},np=class extends la{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,r){let n=e>1?`retry:attempt:${e}`:void 0;return le(t,{callbacks:r?.getChild(n)})}async _invoke(e,t,r){return Sn(n=>super.invoke(e,this._patchConfigForRetry(n,t,r)),{onFailedAttempt:({error:n})=>this.onFailedAttempt(n,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,r,n){let i={};try{await Sn(async a=>{let s=e.map((d,f)=>f).filter(d=>i[d.toString()]===void 0||i[d.toString()]instanceof Error),o=s.map(d=>e[d]),c=s.map(d=>this._patchConfigForRetry(a,t?.[d],r?.[d])),u=await super.batch(o,c,{...n,returnExceptions:!0}),l;for(let d=0;d<u.length;d+=1){let f=u[d],p=s[d];f instanceof Error&&l===void 0&&(l=f,l.input=o[d]),i[p.toString()]=f}if(l)throw l;return u},{onFailedAttempt:({error:a})=>this.onFailedAttempt(a,a.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(a){if(n?.returnExceptions!==!0)throw a}return Object.keys(i).sort((a,s)=>parseInt(a,10)-parseInt(s,10)).map(a=>i[parseInt(a,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}},ip=class In extends _e{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(t){super(t),this.first=t.first,this.middle=t.middle??this.middle,this.last=t.last,this.name=t.name,this.omitSequenceTags=t.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(t,r){let n=Y(r),i=await(await qe(n))?.handleChainStart(this.toJSON(),ge(t,"input"),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let a=t,s;try{let o=[this.first,...this.middle];for(let c=0;c<o.length;c+=1)a=await nt(o[c].invoke(a,le(n,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`)})),n.signal);if(n.signal?.aborted)throw Bt(n.signal);s=await this.last.invoke(a,le(n,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(o){throw await i?.handleChainError(o),o}return await i?.handleChainEnd(ge(s,"output")),s}async batch(t,r,n){let i=this._getOptionsList(r??{},t.length),a=await Promise.all(i.map(qe)),s=await Promise.all(a.map(async(c,u)=>{let l=await c?.handleChainStart(this.toJSON(),ge(t[u],"input"),i[u].runId,void 0,void 0,void 0,i[u].runName);return delete i[u].runId,l})),o=t;try{for(let c=0;c<this.steps.length;c+=1)o=await nt(this.steps[c].batch(o,s.map((u,l)=>{let d=u?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return le(i[l],{callbacks:d})}),n),i[0]?.signal)}catch(c){throw await Promise.all(s.map(u=>u?.handleChainError(c))),c}return await Promise.all(s.map(c=>c?.handleChainEnd(ge(o,"output")))),o}_concatOutputChunks(t,r){return this.last._concatOutputChunks(t,r)}async*_streamIterator(t,r){let n=await qe(r),{runId:i,...a}=r??{},s=await n?.handleChainStart(this.toJSON(),ge(t,"input"),i,void 0,void 0,void 0,a?.runName),o=[this.first,...this.middle,this.last],c=!0,u;async function*l(){yield t}try{let d=o[0].transform(l(),le(a,{callbacks:s?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let f=1;f<o.length;f+=1)d=await o[f].transform(d,le(a,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${f+1}`)}));for await(let f of d)if(r?.signal?.throwIfAborted(),yield f,c)if(u===void 0)u=f;else try{u=this._concatOutputChunks(u,f)}catch{u=void 0,c=!1}}catch(d){throw await s?.handleChainError(d),d}await s?.handleChainEnd(ge(u,"output"))}getGraph(t){let r=new ua,n=null;return this.steps.forEach((i,a)=>{let s=i.getGraph(t);a!==0&&s.trimFirstNode(),a!==this.steps.length-1&&s.trimLastNode(),r.extend(s);let o=s.firstNode();if(!o)throw new Error(`Runnable ${i} has no first node`);n&&r.addEdge(n,o),n=s.lastNode()}),r}pipe(t){return In.isRunnableSequence(t)?new In({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new In({first:this.first,middle:[...this.middle,this.last],last:kr(t),name:this.name})}static isRunnableSequence(t){return Array.isArray(t.middle)&&_e.isRunnable(t)}static from([t,...r],n){let i={};return typeof n=="string"?i.name=n:n!==void 0&&(i=n),new In({...i,first:kr(t),middle:r.slice(0,-1).map(kr),last:kr(r[r.length-1])})}},da=class ap extends _e{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(t){super(t),this.steps={};for(let[r,n]of Object.entries(t.steps))this.steps[r]=kr(n)}static from(t){return new ap({steps:t})}async invoke(t,r){let n=Y(r),i=await(await qe(n))?.handleChainStart(this.toJSON(),{input:t},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let a={};try{let s=Object.entries(this.steps).map(async([o,c])=>{a[o]=await c.invoke(t,le(n,{callbacks:i?.getChild(`map:key:${o}`)}))});await nt(Promise.all(s),n.signal)}catch(s){throw await i?.handleChainError(s),s}return await i?.handleChainEnd(a),a}async*_transform(t,r,n){let i={...this.steps},a=Xi(t,Object.keys(i).length),s=new Map(Object.entries(i).map(([o,c],u)=>{let l=c.transform(a[u],le(n,{callbacks:r?.getChild(`map:key:${o}`)}));return[o,l.next().then(d=>({key:o,gen:l,result:d}))]}));for(;s.size;){let{key:o,result:c,gen:u}=await nt(Promise.race(s.values()),n?.signal);s.delete(o),c.done||(yield{[o]:c.value},s.set(o,u.next().then(l=>({key:o,gen:u,result:l}))))}}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*n(){yield t}let i=Y(r),a=new qt({generator:this.transform(n(),i),config:i});return await a.setup,Re.fromAsyncGenerator(a)}},sw=class sp extends _e{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(t){if(super(t),!Oi(t.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=t.func}async invoke(t,r){let[n]=this._getOptionsList(r??{},1),i=await qe(n);return nt(this.func(le(n,{callbacks:i}),t),n?.signal)}async*_streamIterator(t,r){let[n]=this._getOptionsList(r??{},1),i=await this.invoke(t,r);if(Zi(i)){for await(let a of i)n?.signal?.throwIfAborted(),yield a;return}if(vf(i)){for(;;){n?.signal?.throwIfAborted();let a=i.next();if(a.done)break;yield a.value}return}yield i}static from(t){return new sp({func:t})}};function ow(e){if(Oi(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var op=class cp extends _e{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(t){if(Oi(t.func))return sw.from(t.func);super(t),ow(t.func),this.func=t.func}static from(t){return new cp({func:t})}async _invoke(t,r,n){return new Promise((i,a)=>{let s=le(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??25)-1});be.runWithConfig(We(s),async()=>{try{let o=await this.func(t,{...s});if(o&&_e.isRunnable(o)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(t,{...s,recursionLimit:(s.recursionLimit??25)-1})}else if(Zi(o)){let c;for await(let u of qi(s,o))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}o=c}else if(po(o)){let c;for(let u of mo(s,o))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}o=c}i(o)}catch(o){a(o)}})})}async invoke(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async*_transform(t,r,n){let i;for await(let o of t)if(i===void 0)i=o;else try{i=this._concatOutputChunks(i,o)}catch{i=o}let a=le(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??25)-1}),s=await new Promise((o,c)=>{be.runWithConfig(We(a),async()=>{try{o(await this.func(i,{...a,config:a}))}catch(u){c(u)}})});if(s&&_e.isRunnable(s)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");let o=await s.stream(i,a);for await(let c of o)yield c}else if(Zi(s))for await(let o of qi(a,s))n?.signal?.throwIfAborted(),yield o;else if(po(s))for(let o of mo(a,s))n?.signal?.throwIfAborted(),yield o;else yield s}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*n(){yield t}let i=Y(r),a=new qt({generator:this.transform(n(),i),config:i});return await a.setup,Re.fromAsyncGenerator(a)}},yR=class extends da{},cw=class extends _e{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(let e of this.fallbacks)yield e}async invoke(e,t){let r=Y(t),n=await qe(r),{runId:i,...a}=r,s=await n?.handleChainStart(this.toJSON(),ge(e,"input"),i,void 0,void 0,void 0,a?.runName),o=le(a,{callbacks:s?.getChild()});return await be.runWithConfig(o,async()=>{let c;for(let u of this.runnables()){r?.signal?.throwIfAborted();try{let l=await u.invoke(e,o);return await s?.handleChainEnd(ge(l,"output")),l}catch(l){c===void 0&&(c=l)}}throw c===void 0?new Error("No error stored at end of fallback."):(await s?.handleChainError(c),c)})}async*_streamIterator(e,t){let r=Y(t),n=await qe(r),{runId:i,...a}=r,s=await n?.handleChainStart(this.toJSON(),ge(e,"input"),i,void 0,void 0,void 0,a?.runName),o,c;for(let l of this.runnables()){r?.signal?.throwIfAborted();let d=le(a,{callbacks:s?.getChild()});try{c=qi(d,await l.stream(e,d));break}catch(f){o===void 0&&(o=f)}}if(c===void 0){let l=o??new Error("No error stored at end of fallback.");throw await s?.handleChainError(l),l}let u;try{for await(let l of c){yield l;try{u=u===void 0?u:this._concatOutputChunks(u,l)}catch{u=void 0}}}catch(l){throw await s?.handleChainError(l),l}await s?.handleChainEnd(ge(u,"output"))}async batch(e,t,r){if(r?.returnExceptions)throw new Error("Not implemented.");let n=this._getOptionsList(t??{},e.length),i=await Promise.all(n.map(o=>qe(o))),a=await Promise.all(i.map(async(o,c)=>{let u=await o?.handleChainStart(this.toJSON(),ge(e[c],"input"),n[c].runId,void 0,void 0,void 0,n[c].runName);return delete n[c].runId,u})),s;for(let o of this.runnables()){n[0].signal?.throwIfAborted();try{let c=await o.batch(e,a.map((u,l)=>le(n[l],{callbacks:u?.getChild()})),r);return await Promise.all(a.map((u,l)=>u?.handleChainEnd(ge(c[l],"output")))),c}catch(c){s===void 0&&(s=c)}}throw s?(await Promise.all(a.map(o=>o?.handleChainError(s))),s):new Error("No error stored at end of fallbacks.")}};function kr(e){if(typeof e=="function")return new op({func:e});if(_e.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=kr(n);return new da({steps:t})}else throw new Error(`Expected a Runnable, function or object.
|
|
174
|
+
Instead got an unsupported type.`)}var uw=class extends _e{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof da&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){let r=await this.mapper.invoke(e,t);return{...e,...r}}async*_transform(e,t,r){let n=this.mapper.getStepsKeys(),[i,a]=Xi(e),s=this.mapper.transform(a,le(r,{callbacks:t?.getChild()})),o=s.next();for await(let c of i){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);let u=Object.fromEntries(Object.entries(c).filter(([l])=>!n.includes(l)));Object.keys(u).length>0&&(yield u)}yield(await o).value;for await(let c of s)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=Y(t),i=new qt({generator:this.transform(r(),n),config:n});return await i.setup,Re.fromAsyncGenerator(i)}},lw=class extends _e{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{let t=this.keys.map(r=>[r,e[r]]).filter(r=>r[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(let t of e){let r=await this._pick(t);r!==void 0&&(yield r)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=Y(t),i=new qt({generator:this.transform(r(),n),config:n});return await i.setup,Re.fromAsyncGenerator(i)}},ep=class extends la{name;description;schema;constructor(e){let t=ip.from([op.from(async r=>{let n;if(Nt(r))try{n=await $i(this.schema,r.args)}catch{throw new Or("Received tool input did not match expected schema",JSON.stringify(r.args))}else n=r;return n}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function dw(e,t){let r=t.name??e.getName(),n=t.description??vd(t.schema);return Pi(t.schema)?new ep({name:r,description:n,schema:vt.object({input:vt.string()}).transform(i=>i.input),bound:e}):new ep({name:r,description:n,schema:t.schema,bound:e})}var RR=L({BasePromptValue:()=>fa,ChatPromptValue:()=>Ao,ImagePromptValue:()=>fw,StringPromptValue:()=>To}),fa=class extends ft{},To=class extends fa{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new Xt(this.value)]}},Ao=class extends fa{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return Zn(this.messages)}toChatMessages(){return this.messages}},fw=class extends fa{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Xt({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}};var fp=jn(dp(),1),bw=Object.defineProperty,vw=(e,t,r)=>t in e?bw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,xw=(e,t,r)=>(vw(e,typeof t!="symbol"?t+"":t,r),r);function Ew(e,t){let r=Array.from({length:e.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=e.slice(r[i].start,r[i+1].end),s=t.get(a.join(","));s!=null&&(n==null||s<n[0])&&(n=[s,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}function Sw(e,t){return e.length===1?[t.get(e.join(","))]:Ew(e,t).map(r=>t.get(e.slice(r.start,r.end).join(","))).filter(r=>r!=null)}function Tw(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var Io=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,t){this.patStr=e.pat_str;let r=e.bpe_ranks.split(`
|
|
175
|
+
`).filter(Boolean).reduce((n,i)=>{let[a,s,...o]=i.split(" "),c=Number.parseInt(s,10);return o.forEach((u,l)=>n[u]=c+l),n},{});for(let[n,i]of Object.entries(r)){let a=fp.default.toByteArray(n);this.rankMap.set(a.join(","),i),this.textMap.set(i,a)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[i,a])=>(n[a]=this.textEncoder.encode(i),n),{})}encode(e,t=[],r="all"){let n=new RegExp(this.patStr,"ug"),i=Io.specialTokenRegex(Object.keys(this.specialTokens)),a=[],s=new Set(t==="all"?Object.keys(this.specialTokens):t),o=new Set(r==="all"?Object.keys(this.specialTokens).filter(u=>!s.has(u)):r);if(o.size>0){let u=Io.specialTokenRegex([...o]),l=e.match(u);if(l!=null)throw new Error(`The text contains a special token that is not allowed: ${l[0]}`)}let c=0;for(;;){let u=null,l=c;for(;i.lastIndex=l,u=i.exec(e),!(u==null||s.has(u[0]));)l=u.index+1;let d=u?.index??e.length;for(let p of e.substring(c,d).matchAll(n)){let h=this.textEncoder.encode(p[0]),m=this.rankMap.get(h.join(","));if(m!=null){a.push(m);continue}a.push(...Sw(h,this.rankMap))}if(u==null)break;let f=this.specialTokens[u[0]];a.push(f),c=u.index+u[0].length}return a}decode(e){let t=[],r=0;for(let a=0;a<e.length;++a){let s=e[a],o=this.textMap.get(s)??this.inverseSpecialTokens[s];o!=null&&(t.push(o),r+=o.length)}let n=new Uint8Array(r),i=0;for(let a of t)n.set(a,i),i+=a.length;return this.textDecoder.decode(n)}},ha=Io;xw(ha,"specialTokenRegex",e=>new RegExp(e.map(t=>Tw(t)).join("|"),"g"));function Co(e){switch(e){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}var VR=L({encodingForModel:()=>ga,getEncoding:()=>pp}),ma={},Aw=new Sr({});async function pp(e){return e in ma||(ma[e]=Aw.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(t=>t.json()).then(t=>new ha(t)).catch(t=>{throw delete ma[e],t})),await ma[e]}async function ga(e){return pp(Co(e))}var eN=L({BaseLangChain:()=>ya,BaseLanguageModel:()=>Rw,calculateMaxTokens:()=>Cw,getEmbeddingContextSize:()=>kw,getModelContextSize:()=>hp,getModelNameForTiktoken:()=>_a,isOpenAITool:()=>Iw}),_a=e=>e.startsWith("gpt-5")?"gpt-5":e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,kw=e=>e==="text-embedding-ada-002"?8191:2046,hp=e=>{switch(_a(e)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function Iw(e){return typeof e!="object"||!e?!1:!!("type"in e&&e.type==="function"&&"function"in e&&typeof e.function=="object"&&e.function&&"name"in e.function&&"parameters"in e.function)}var Cw=async({prompt:e,modelName:t})=>{let r;try{r=(await ga(_a(t))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),r=Math.ceil(e.length/4)}return hp(t)-r},Ow=()=>!1,ya=class extends _e{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??Ow(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{},this._addVersion("@langchain/core","1.2.1")}_addVersion(e,t){let r=this.metadata?.versions;this.metadata={...this.metadata,versions:{...typeof r=="object"&&r!==null?r:{},[e]:t}}}},Rw=class extends ya{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:t,...r}){let{cache:n,...i}=r;super({callbacks:e??t,...i}),typeof n=="object"?this.cache=n:n?this.cache=go.global():this.cache=void 0,this.caller=new Sr(r??{})}_encoding;async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(n=>typeof n=="string"?n:n.type==="text"&&"text"in n?n.text:"").join("");let r=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await ga("modelName"in this?_a(this.modelName):"gpt2")}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}if(this._encoding)try{r=this._encoding.encode(t).length}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new To(e):Array.isArray(e)?new Ao(e.map(Qc)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){let r={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([n,i])=>i!==void 0).map(([n,i])=>`${n}:${JSON.stringify(i)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}get profile(){return{}}_filterInvocationParamsForTracing(e){let{tools:t,functions:r,messages:n,response_format:i,...a}=e;return a}};function Oo(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function Ro(e){return e!==void 0&&_e.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function No(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(Gr(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function mp(e){return No(e)||Ro(e)||Oo(e)}var TN=L({BaseToolkit:()=>Nw,DynamicStructuredTool:()=>yp,DynamicTool:()=>_p,StructuredTool:()=>$o,Tool:()=>gp,ToolInputParsingException:()=>Or,isLangChainTool:()=>mp,isRunnableToolLike:()=>Ro,isStructuredTool:()=>Oo,isStructuredToolParams:()=>No,tool:()=>$w}),$o=class extends ya{extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(e){super(e??{}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata,this.extras=e?.extras??this.extras}async invoke(e,t){let r,n=Y(wn(this.defaultConfig,t));return Nt(e)?(r=e.args,n={...n,toolCall:e}):r=e,this.call(r,n)}async call(e,t,r){let n=Nt(e)?e.args:e,i;if(Gr(this.schema))try{i=await $i(this.schema,n)}catch(p){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
|
|
176
|
+
Details: ${p.message}`),Ed(p)&&(h=`${h}
|
|
177
|
+
|
|
178
|
+
${Oa.prettifyError(p)}`),new Or(h,JSON.stringify(e))}else{let p=re(n,this.schema);if(!p.valid){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
|
|
179
|
+
Details: ${p.errors.map(m=>`${m.keywordLocation}: ${m.error}`).join(`
|
|
180
|
+
`)}`),new Or(h,JSON.stringify(e))}i=n}let a=_n(t),s=rt.configure(a.callbacks,this.callbacks,a.tags||r,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),o;Nt(e)&&(o=e.id),!o&&Vc(a)&&(o=a.toolCall.id);let c=await s?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),a.runId,void 0,void 0,void 0,a.runName,o);delete a.runId;let u;try{let p=await this._call(i,c,a);u=ho(p)?await xf(p,async h=>{try{await c?.handleToolEvent(h)}catch(m){await c?.handleToolError(m)}}):p}catch(p){throw await c?.handleToolError(p),p}let l,d;if(this.responseFormat==="content_and_artifact")if(Array.isArray(u)&&u.length===2)[l,d]=u;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
|
|
181
|
+
Result: ${JSON.stringify(u)}`);else l=u;let f=Mw({content:l,artifact:d,toolCallId:o,name:this.name,metadata:this.metadata});return await c?.handleToolEnd(f),f}},gp=class extends $o{schema=vt.object({input:vt.string().optional()}).transform(e=>e.input);constructor(e){super(e)}call(e,t){let r=typeof e=="string"||e==null?{input:e}:e;return super.call(r,t)}},_p=class extends gp{static lc_name(){return"DynamicTool"}name;description;func;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,t){let r=_n(t);return r.runName===void 0&&(r.runName=this.name),super.call(e,r)}_call(e,t,r){return this.func(e,t,r)}},yp=class extends $o{static lc_name(){return"DynamicStructuredTool"}description;func;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,t,r){let n=_n(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n,r)}_call(e,t,r){return this.func(e,t,r)}},Nw=class{getTools(){return this.tools}};function $w(e,t){let r=Pi(t.schema),n=Qr(t.schema);if(!t.schema||r||n)return new _p({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(s,o,c)=>new Promise((u,l)=>{let d=le(c,{callbacks:o?.getChild()});be.runWithConfig(We(d),async()=>{try{u(e(s,d))}catch(f){l(f)}})})});let i=t.schema,a=t.description??t.schema.description??`${t.name} tool`;return new yp({...t,description:a,schema:i,func:async(s,o,c)=>new Promise((u,l)=>{let d,f=()=>{c?.signal&&d&&c.signal.removeEventListener("abort",d)};c?.signal&&(d=()=>{f(),l(Bt(c.signal))},c.signal.addEventListener("abort",d,{once:!0}));let p=le(c,{callbacks:o?.getChild()});be.runWithConfig(We(p),async()=>{try{let h=await e(s,p);if(ho(h)){u(h);return}if(c?.signal?.aborted){f();return}f(),u(h)}catch(h){f(),l(h)}})})})}function Pw(e){return typeof e=="object"&&e!==null&&"type"in e}function Mw(e){let{content:t,artifact:r,toolCallId:n,metadata:i}=e;return n&&!Pa(t)?typeof t=="string"||Array.isArray(t)&&t.every(Pw)?new Yt({status:"success",content:t,artifact:r,tool_call_id:n,name:e.name,metadata:i}):new Yt({status:"success",content:jw(t),artifact:r,tool_call_id:n,name:e.name,metadata:i}):t}function jw(e){try{return JSON.stringify(e)??""}catch{return`${e}`}}export{L as a,ix as b,Za as c,wh as d,bh as e,$r as f,Dw as g,Wo as h,Ip as i,Jo as j,Gw as k,Un as l,ft as m,ox as n,bu as o,Qe as p,Ji as q,RC as r,s0 as s,Da as t,Qp as u,eh as v,Rt as w,Qo as x,ec as y,Zw as z,tc as A,qw as B,Ww as C,Ra as D,Jw as E,dc as F,Pe as G,_c as H,ke as I,mb as J,Bp as K,ce as L,Cr as M,yc as N,ze as O,bc as P,vc as Q,gb as R,vb as S,Pa as T,Yt as U,Vp as V,Ma as W,Zp as X,qp as Y,Or as Z,f0 as _,za as $,zc as aa,Fn as ba,Rr as ca,sv as da,ov as ea,Nr as fa,Ba as ga,qc as ha,m0 as ia,g0 as ja,Wc as ka,Jc as la,b0 as ma,v0 as na,Xt as oa,Kc as pa,A0 as qa,k0 as ra,Yc as sa,Vn as ta,Xc as ua,M0 as va,j0 as wa,K0 as xa,Qc as ya,Zn as za,Ha as Aa,Y0 as Ba,X0 as Ca,Q0 as Da,eu as Ea,LC as Fa,px as Ga,Eh as Ha,Sh as Ia,er as Ja,jt as Ka,qS as La,tt as Ma,XS as Na,_T as Oa,TT as Pa,GT as Qa,_n as Ra,rt as Sa,Hr as Ta,be as Ua,oA as Va,qe as Wa,wn as Xa,Y as Ya,le as Za,We as _a,nt as $a,tO as ab,Re as bb,Qi as cb,qt as db,tn as eb,dO as fb,xO as gb,kO as hb,ew as ib,An as jb,tw as kb,qC as lb,Sr as mb,FI as nb,ry as ob,se as pb,he as qb,mA as rb,Gr as sb,Ng as tb,$g as ub,gA as vb,_A as wb,$i as xb,yA as yb,wA as zb,vd as Ab,bA as Bb,Pi as Cb,to as Db,_t as Eb,ro as Fb,Pg as Gb,Mg as Hb,vA as Ib,wd as Jb,xA as Kb,EA as Lb,Ni as Mb,bd as Nb,SA as Ob,xd as Pb,TA as Qb,Ed as Rb,w as Sb,vt as Tb,Zt as Ub,Vi as Vb,xC as Wb,fo as Xb,qO as Yb,ua as Zb,ge as _b,_e as $b,la as ac,_R as bc,np as cc,ip as dc,da as ec,op as fc,yR as gc,cw as hc,kr as ic,uw as jc,lw as kc,ep as lc,RR as mc,To as nc,Ao as oc,fw as pc,VR as qc,eN as rc,hp as sc,Iw as tc,Rw as uc,Oo as vc,Ro as wc,No as xc,mp as yc,TN as zc,$o as Ac,$w as Bc};
|