@arcgis/ai-components 5.2.0-next.10 → 5.2.0-next.12
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/agent-utils/FunctionAgent.d.ts +2 -2
- package/dist/agent-utils/LLMAgent.d.ts +2 -2
- package/dist/agent-utils/WorkflowAgent.d.ts +2 -2
- package/dist/agent-utils/index.d.ts +99 -0
- package/dist/agent-utils/index.js +148 -0
- package/dist/agent-utils/middlewares/trace.js +25 -33
- package/dist/agent-utils/tools/FunctionTool.d.ts +2 -2
- package/dist/agent-utils/types.d.ts +30 -1
- package/dist/agent-utils/workflows/ConditionalWorkflow.d.ts +2 -2
- package/dist/agent-utils/workflows/LoopWorkflow.d.ts +2 -2
- package/dist/agent-utils/workflows/ParallelWorkflow.d.ts +2 -2
- package/dist/agent-utils/workflows/RouterWorkflow.d.ts +2 -2
- package/dist/agent-utils/workflows/SequentialWorkflow.d.ts +2 -2
- package/dist/agent-utils/workflows/SwitchWorkflow.d.ts +2 -2
- package/dist/cdn/{VMXLYWUK.js → 24QNMEFG.js} +1 -1
- package/dist/cdn/{D2N2NSRQ.js → 34SG44C3.js} +1 -1
- package/dist/cdn/3JGWGKT6.js +2 -0
- package/dist/cdn/{CCY4TSBO.js → 3NBDVZ2I.js} +1 -1
- package/dist/cdn/3VOQD2MR.js +2 -0
- package/dist/cdn/{BIV2IPHH.js → 53NTYC4I.js} +1 -1
- package/dist/cdn/{MODWHY3R.js → 5CV7R5IS.js} +6 -4
- package/dist/cdn/{FL4W4VYN.js → 6ZW7Z36F.js} +16 -0
- package/dist/cdn/7CYGX4F4.js +2 -0
- package/dist/cdn/{2SJAOYZT.js → AZGGTNA3.js} +1 -1
- package/dist/cdn/{EGHBXLNG.js → B7WJFBOZ.js} +1 -1
- package/dist/cdn/BX7FSMUU.js +56 -0
- package/dist/cdn/CHPQM77M.js +181 -0
- package/dist/cdn/DHKUXLU3.js +179 -0
- package/dist/cdn/DQSEBKOX.js +2 -0
- package/dist/cdn/DXVU45KM.js +2 -0
- package/dist/cdn/{XER22VYQ.js → DZ2QWNUA.js} +1 -1
- package/dist/cdn/EBISDZ5H.js +2 -0
- package/dist/cdn/{VNQN5ZQO.js → ERL2CB2Y.js} +5 -5
- package/dist/cdn/{SWOXSJ62.js → F6QHMKF5.js} +1 -1
- package/dist/cdn/FUIGPHBH.js +2 -0
- package/dist/cdn/{CTSALWEP.js → H2CHHGGH.js} +1 -1
- package/dist/cdn/{6AWNQHCO.js → HWKDNS4K.js} +1 -1
- package/dist/cdn/IMQ4TVHF.js +16 -0
- package/dist/cdn/IOD3GDA7.js +2 -0
- package/dist/cdn/IR7PTESF.js +2 -0
- package/dist/cdn/{EEUCKMU7.js → IRZDTYO2.js} +1 -1
- package/dist/cdn/JIWK6QK6.js +2 -0
- package/dist/cdn/{EWI4V3GQ.js → JLKGS6Y5.js} +11 -11
- package/dist/cdn/K3JCH4XW.js +2 -0
- package/dist/cdn/{WIDTPVSU.js → KHXUWZHB.js} +1 -1
- package/dist/cdn/LIFK3QSD.js +2 -0
- package/dist/cdn/{JOFUPKIB.js → O3EN27N5.js} +1 -1
- package/dist/cdn/O3RFFPU3.js +6 -0
- package/dist/cdn/P7DG5T3Z.js +9 -0
- package/dist/cdn/{OIVRK7HT.js → PBO6FZN6.js} +1 -1
- package/dist/cdn/Q3ZW4FYA.js +3 -0
- package/dist/cdn/Q6LRANX6.js +2 -0
- package/dist/cdn/Q7TL5Q5N.js +2 -0
- package/dist/cdn/{KUEOKIQR.js → QCSN44H4.js} +1 -1
- package/dist/cdn/R56X6ZKR.js +161 -0
- package/dist/cdn/T43LEBBE.js +47 -0
- package/dist/cdn/TR4GFL7X.js +2 -0
- package/dist/cdn/{D3TNNRP4.js → UPEEHMSY.js} +1 -1
- package/dist/cdn/{GTLS44GI.js → WAIFKDR3.js} +1 -1
- package/dist/cdn/WNS5ZUF5.js +2 -0
- package/dist/cdn/X4XY5HIE.js +2 -0
- package/dist/cdn/XOH56EQ2.js +2 -0
- package/dist/cdn/{64PJB5NU.js → XON27U6U.js} +1 -1
- package/dist/cdn/{DOV5ZJ7M.js → YLN2BZ5J.js} +1 -1
- package/dist/cdn/{OBUZ7HBN.js → YUKR4AZW.js} +1 -1
- package/dist/cdn/{TSZPHE7L.js → Z2G7MP5L.js} +3 -3
- package/dist/cdn/ZEYIBYSF.js +66 -0
- package/dist/cdn/agent-utils/index.js +2 -0
- package/dist/cdn/agent-utils/middlewares/humanInTheLoop.js +3 -0
- package/dist/cdn/agent-utils/middlewares/middleware.js +2 -0
- package/dist/cdn/agent-utils/middlewares/trace.js +2 -0
- package/dist/cdn/index.js +1 -1
- package/dist/chunks/adapter.js +1379 -1307
- package/dist/chunks/arcgisKnowledgeGraph.js +109 -72
- package/dist/chunks/dataExplorationGraph.js +8 -3
- package/dist/chunks/generateLayerDescriptions.js +228 -217
- package/dist/chunks/helpGraph.js +14 -11
- package/dist/chunks/index.js +11 -0
- package/dist/chunks/intent_prompt.js +16 -0
- package/dist/chunks/layerStylingGraph.js +25 -22
- package/dist/chunks/navigationGraph.js +7 -3
- package/dist/chunks/orchestrator.js +9 -8
- package/dist/chunks/toolCallResponse.js +5 -3
- package/dist/components/arcgis-assistant/customElement.js +1 -0
- package/dist/components/arcgis-assistant-data-exploration-agent/customElement.js +1 -0
- package/dist/components/arcgis-assistant-help-agent/customElement.js +1 -0
- package/dist/components/arcgis-assistant-knowledge-agent/customElement.d.ts +7 -7
- package/dist/components/arcgis-assistant-knowledge-agent/customElement.js +1 -0
- package/dist/components/arcgis-assistant-layer-styling-agent/customElement.js +1 -0
- package/dist/components/arcgis-assistant-navigation-agent/customElement.js +1 -0
- package/dist/docs/api.json +1 -1
- package/dist/docs/docs.json +1 -1
- package/dist/docs/web-types.json +1 -1
- package/dist/orchestrator/registry/agentRegistry.d.ts +33 -0
- package/dist/utils/index.d.ts +5 -4
- package/dist/utils/index.js +48 -47
- package/package.json +5 -4
- package/dist/cdn/462JBSEV.js +0 -422
- package/dist/cdn/ETRWZ3MS.js +0 -108
- package/dist/cdn/I6HNBTWY.js +0 -2
- package/dist/cdn/JBHNHHWO.js +0 -3
- package/dist/cdn/LKRAPK4A.js +0 -165
- package/dist/cdn/RVOAPUBN.js +0 -2
- package/dist/cdn/VAZNJSKA.js +0 -16
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import{$ as Sa,Dd as Ta,d as dt,e as va,j as $n,k as xa,m as Uo,n as Bo,o as Ea,u as $e,w as zo,x as Fo}from"./ZEYIBYSF.js";import{a as ut,b as pp,c as Wt}from"./YIMNOUTF.js";var Vo=ut((ww,Go)=>{"use strict";Go.exports=function(t,e){if(typeof t!="string")throw new TypeError("Expected a string");return e=typeof e>"u"?"_":e,t.replace(/([a-z\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+e+"$2").toLowerCase()}});var Xo=ut((bw,Aa)=>{"use strict";var hp=/[\p{Lu}]/u,mp=/[\p{Ll}]/u,Zo=/^[\p{Lu}](?![\p{Lu}])/gu,Wo=/([\p{Alpha}\p{N}_]|$)/u,Ko=/[_.\- ]+/,gp=new RegExp("^"+Ko.source),qo=new RegExp(Ko.source+Wo.source,"gu"),Jo=new RegExp("\\d+"+Wo.source,"gu"),_p=(t,e,r)=>{let n=!1,i=!1,a=!1;for(let s=0;s<t.length;s++){let o=t[s];n&&hp.test(o)?(t=t.slice(0,s)+"-"+t.slice(s),n=!1,a=i,i=!0,s++):i&&a&&mp.test(o)?(t=t.slice(0,s-1)+"-"+t.slice(s-1),a=i,i=!1,n=!0):(n=e(o)===o&&r(o)!==o,a=i,i=r(o)===o&&e(o)!==o)}return t},yp=(t,e)=>(Zo.lastIndex=0,t.replace(Zo,r=>e(r))),wp=(t,e)=>(qo.lastIndex=0,Jo.lastIndex=0,t.replace(qo,(r,n)=>e(n)).replace(Jo,r=>e(r))),Yo=(t,e)=>{if(!(typeof t=="string"||Array.isArray(t)))throw new TypeError("Expected the input to be `string | string[]`");if(e={pascalCase:!1,preserveConsecutiveUppercase:!1,...e},Array.isArray(t)?t=t.map(a=>a.trim()).filter(a=>a.length).join("-"):t=t.trim(),t.length===0)return"";let r=e.locale===!1?a=>a.toLowerCase():a=>a.toLocaleLowerCase(e.locale),n=e.locale===!1?a=>a.toUpperCase():a=>a.toLocaleUpperCase(e.locale);return t.length===1?e.pascalCase?n(t):r(t):(t!==r(t)&&(t=_p(t,r,n)),t=t.replace(gp,""),e.preserveConsecutiveUppercase?t=yp(t,r):t=r(t),e.pascalCase&&(t=n(t.charAt(0))+t.slice(1)),wp(t,n))};Aa.exports=Yo;Aa.exports.default=Yo});var vu=ut((Yx,ks)=>{"use strict";var mm=Object.prototype.hasOwnProperty,Ie="~";function ln(){}Object.create&&(ln.prototype=Object.create(null),new ln().__proto__||(Ie=!1));function gm(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function bu(t,e,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var a=new gm(r,n||t,i),s=Ie?Ie+e:e;return t._events[s]?t._events[s].fn?t._events[s]=[t._events[s],a]:t._events[s].push(a):(t._events[s]=a,t._eventsCount++),t}function oi(t,e){--t._eventsCount===0?t._events=new ln:delete t._events[e]}function xe(){this._events=new ln,this._eventsCount=0}xe.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)mm.call(r,n)&&e.push(Ie?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};xe.prototype.listeners=function(e){var r=Ie?Ie+e:e,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(e){var r=Ie?Ie+e:e,n=this._events[r];return n?n.fn?1:n.length:0};xe.prototype.emit=function(e,r,n,i,a,s){var o=Ie?Ie+e:e;if(!this._events[o])return!1;var c=this._events[o],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){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,u=new Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){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(!u)for(p=1,u=new Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0};xe.prototype.on=function(e,r,n){return bu(this,e,r,n,!1)};xe.prototype.once=function(e,r,n){return bu(this,e,r,n,!0)};xe.prototype.removeListener=function(e,r,n,i){var a=Ie?Ie+e:e;if(!this._events[a])return this;if(!r)return oi(this,a),this;var s=this._events[a];if(s.fn)s.fn===r&&(!i||s.once)&&(!n||s.context===n)&&oi(this,a);else{for(var o=0,c=[],l=s.length;o<l;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:oi(this,a)}return this};xe.prototype.removeAllListeners=function(e){var r;return e?(r=Ie?Ie+e:e,this._events[r]&&oi(this,r)):(this._events=new ln,this._eventsCount=0),this};xe.prototype.off=xe.prototype.removeListener;xe.prototype.addListener=xe.prototype.on;xe.prefixed=Ie;xe.EventEmitter=xe;typeof ks<"u"&&(ks.exports=xe)});var Eu=ut((Xx,xu)=>{"use strict";xu.exports=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))});var Tu=ut((Qx,li)=>{"use strict";var _m=Eu(),ci=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Su=(t,e,r)=>new Promise((n,i)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(t);return}let a=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(c){i(c)}return}let s=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,o=r instanceof Error?r:new ci(s);typeof t.cancel=="function"&&t.cancel(),i(o)},e);_m(t.then(n,i),()=>{clearTimeout(a)})});li.exports=Su;li.exports.default=Su;li.exports.TimeoutError=ci});var Au=ut(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});function ym(t,e,r){let n=0,i=t.length;for(;i>0;){let a=i/2|0,s=n+a;r(t[s],e)<=0?(n=++s,i-=a+1):i=a}return n}Is.default=ym});var ku=ut(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});var wm=Au(),Cs=class{constructor(){this._queue=[]}enqueue(e,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let i=wm.default(this._queue,n,(a,s)=>s.priority-a.priority);this._queue.splice(i,0,n)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this._queue.length}};Os.default=Cs});var di=ut(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});var bm=vu(),Iu=Tu(),vm=ku(),ui=()=>{},xm=new Iu.TimeoutError,Rs=class extends bm{constructor(e){var r,n,i,a;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=ui,this._resolveIdle=ui,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:vm.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(a=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&a!==void 0?a:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=ui,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=ui,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let r=this._intervalEnd-e;if(r<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},r)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let r=this._queue.dequeue();return r?(this.emit("active"),r(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,r={}){return new Promise((n,i)=>{let a=async()=>{this._pendingCount++,this._intervalCount++;try{let s=this._timeout===void 0&&r.timeout===void 0?e():Iu.default(Promise.resolve(e()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&i(xm)});n(await s)}catch(s){i(s)}this._next()};this._queue.enqueue(a,r),this._tryToStartAnother(),this.emit("add")})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let r=this._resolveEmpty;this._resolveEmpty=()=>{r(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let r=this._resolveIdle;this._resolveIdle=()=>{r(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};Ns.default=Rs});var nd=ut((sS,rd)=>{"use strict";var ed=(t=0)=>e=>`\x1B[${38+t};5;${e}m`,td=(t=0)=>(e,r,n)=>`\x1B[${38+t};2;${e};${r};${n}m`;function lg(){let t=new Map,e={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};e.color.gray=e.color.blackBright,e.bgColor.bgGray=e.bgColor.bgBlackBright,e.color.grey=e.color.blackBright,e.bgColor.bgGrey=e.bgColor.bgBlackBright;for(let[r,n]of Object.entries(e)){for(let[i,a]of Object.entries(n))e[i]={open:`\x1B[${a[0]}m`,close:`\x1B[${a[1]}m`},n[i]=e[i],t.set(a[0],a[1]);Object.defineProperty(e,r,{value:n,enumerable:!1})}return Object.defineProperty(e,"codes",{value:t,enumerable:!1}),e.color.close="\x1B[39m",e.bgColor.close="\x1B[49m",e.color.ansi256=ed(),e.color.ansi16m=td(),e.bgColor.ansi256=ed(10),e.bgColor.ansi16m=td(10),Object.defineProperties(e,{rgbToAnsi256:{value:(r,n,i)=>r===n&&n===i?r<8?16:r>248?231:Math.round((r-8)/247*24)+232:16+36*Math.round(r/255*5)+6*Math.round(n/255*5)+Math.round(i/255*5),enumerable:!1},hexToRgb:{value:r=>{let n=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(r.toString(16));if(!n)return[0,0,0];let{colorString:i}=n.groups;i.length===3&&(i=i.split("").map(s=>s+s).join(""));let a=Number.parseInt(i,16);return[a>>16&255,a>>8&255,a&255]},enumerable:!1},hexToAnsi256:{value:r=>e.rgbToAnsi256(...e.hexToRgb(r)),enumerable:!1}}),e}Object.defineProperty(rd,"exports",{enumerable:!0,get:lg})});var np=ut(ca=>{"use strict";ca.byteLength=Ky;ca.toByteArray=Xy;ca.fromByteArray=tw;var St=[],Ye=[],Wy=typeof Uint8Array<"u"?Uint8Array:Array,To="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Ar=0,tp=To.length;Ar<tp;++Ar)St[Ar]=To[Ar],Ye[To.charCodeAt(Ar)]=Ar;var Ar,tp;Ye[45]=62;Ye[95]=63;function rp(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function Ky(t){var e=rp(t),r=e[0],n=e[1];return(r+n)*3/4-n}function Yy(t,e,r){return(e+r)*3/4-r}function Xy(t){var e,r=rp(t),n=r[0],i=r[1],a=new Wy(Yy(t,n,i)),s=0,o=i>0?n-4:n,c;for(c=0;c<o;c+=4)e=Ye[t.charCodeAt(c)]<<18|Ye[t.charCodeAt(c+1)]<<12|Ye[t.charCodeAt(c+2)]<<6|Ye[t.charCodeAt(c+3)],a[s++]=e>>16&255,a[s++]=e>>8&255,a[s++]=e&255;return i===2&&(e=Ye[t.charCodeAt(c)]<<2|Ye[t.charCodeAt(c+1)]>>4,a[s++]=e&255),i===1&&(e=Ye[t.charCodeAt(c)]<<10|Ye[t.charCodeAt(c+1)]<<4|Ye[t.charCodeAt(c+2)]>>2,a[s++]=e>>8&255,a[s++]=e&255),a}function Qy(t){return St[t>>18&63]+St[t>>12&63]+St[t>>6&63]+St[t&63]}function ew(t,e,r){for(var n,i=[],a=e;a<r;a+=3)n=(t[a]<<16&16711680)+(t[a+1]<<8&65280)+(t[a+2]&255),i.push(Qy(n));return i.join("")}function tw(t){for(var e,r=t.length,n=r%3,i=[],a=16383,s=0,o=r-n;s<o;s+=a)i.push(ew(t,s,s+a>o?o:s+a));return n===1?(e=t[r-1],i.push(St[e>>2]+St[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(St[e>>10]+St[e>>4&63]+St[e<<2&63]+"=")),i.join("")}});var Ho=Object.defineProperty,D=(t,e)=>{let r={};for(var n in t)Ho(r,n,{get:t[n],enumerable:!0});return e||Ho(r,Symbol.toStringTag,{value:"Module"}),r};var Qo=Wt(Vo(),1),ec=Wt(Xo(),1);function tc(t,e){return e?.[t]||(0,Qo.default)(t)}function vw(t,e){return e?.[t]||(0,ec.default)(t)}function rc(t,e,r){let n={};for(let i in t)Object.hasOwn(t,i)&&(n[e(i,r)]=t[i]);return n}var ic="__lc_escaped__";function bp(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}function vp(t){return{[ic]:t}}function xp(t){return Object.keys(t).length===1&&"__lc_escaped__"in t}function Ep(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}function Sp(t){let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[t.constructor?.name??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}function Pn(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return Sp(t);if(Ep(t))return t;e.add(t);let r=t;if(bp(r))return e.delete(t),vp(r);let n={};for(let[i,a]of Object.entries(r))n[i]=Pn(a,e);return e.delete(t),n}return Array.isArray(t)?t.map(r=>Pn(r,e)):t}function nc(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;if(xp(e))return e[ic];let r={};for(let[n,i]of Object.entries(e))r[n]=nc(i);return r}return Array.isArray(t)?t.map(e=>nc(e)):t}var kw=D({Serializable:()=>ft,get_lc_unique_name:()=>Mn});function ac(t){return Array.isArray(t)?[...t]:{...t}}function Tp(t,e){let r=ac(t);for(let[n,i]of Object.entries(e)){let[a,...s]=n.split(".").reverse(),o=r;for(let c of s.reverse()){if(o[c]===void 0)break;o[c]=ac(o[c]),o=o[c]}o[a]!==void 0&&(o[a]={lc:1,type:"secret",id:[i]})}return r}function Mn(t){let e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}var ft=class sc{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Mn(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...r){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof sc||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},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(e,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,l=n,[u,...d]=o.split(".").reverse();for(let f of d.reverse()){if(!(f in c)||c[f]===void 0)return;(!(f in l)||l[f]===void 0)&&(typeof c[f]=="object"&&c[f]!=null?l[f]={}:Array.isArray(c[f])&&(l[f]=[])),c=c[f],l=l[f]}u in c&&c[u]!==void 0&&(l[u]=l[u]||c[u])});let i={},a=new WeakSet;a.add(this);for(let[o,c]of Object.entries(n))i[o]=Pn(c,a);let s=rc(Object.keys(r).length?Tp(i,r):i,tc,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:s}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function Rt(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}function oc(t){return Rt(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function cc(t){return Rt(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function Cw(t){return Rt(t)&&t.source_type==="text"&&"text"in t&&typeof t.text=="string"}function lc(t){return Rt(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}function Ow(t){if(Rt(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Rw(t){let e=t.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${t}" - does not match type/subtype format.`);let r=e[0].trim(),n=e[1].trim();if(r===""||n==="")throw new Error(`Invalid mime type: "${t}" - type or subtype is empty.`);let i={};for(let a of t.split(";").slice(1)){let s=a.split("=");if(s.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${t}".`);let o=s[0].trim(),c=s[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${t}".`);i[o]=c}return{type:r,subtype:n,parameters:i}}function ka({dataUrl:t,asTypedArray:e=!1}){let r=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(r){n=r[1].toLowerCase();let i=e?Uint8Array.from(atob(r[2]),a=>a.charCodeAt(0)):r[2];return{mime_type:n,data:i}}}function Nw(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(t)}throw new Error(`Unable to convert content block type '${t.type}' to provider-specific format: not recognized.`)}function T(t,e){return $(t)&&t.type===e}function $(t){return typeof t=="object"&&t!==null}function de(t){return Array.isArray(t)}function m(t){return typeof t=="string"}function De(t){return typeof t=="number"}function Ln(t){return t instanceof Uint8Array}function Ia(t){try{return JSON.parse(t)}catch{return}}var Ue=t=>t();function Ap(t){if(t.type==="char_location"&&m(t.document_title)&&De(t.start_char_index)&&De(t.end_char_index)&&m(t.cited_text)){let{document_title:e,start_char_index:r,end_char_index:n,cited_text:i,...a}=t;return{...a,type:"citation",source:"char",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="page_location"&&m(t.document_title)&&De(t.start_page_number)&&De(t.end_page_number)&&m(t.cited_text)){let{document_title:e,start_page_number:r,end_page_number:n,cited_text:i,...a}=t;return{...a,type:"citation",source:"page",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="content_block_location"&&m(t.document_title)&&De(t.start_block_index)&&De(t.end_block_index)&&m(t.cited_text)){let{document_title:e,start_block_index:r,end_block_index:n,cited_text:i,...a}=t;return{...a,type:"citation",source:"block",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="web_search_result_location"&&m(t.url)&&m(t.title)&&m(t.encrypted_index)&&m(t.cited_text)){let{url:e,title:r,encrypted_index:n,cited_text:i,...a}=t;return{...a,type:"citation",source:"url",url:e,title:r,startIndex:Number(n),endIndex:Number(n),citedText:i}}if(t.type==="search_result_location"&&m(t.source)&&m(t.title)&&De(t.start_block_index)&&De(t.end_block_index)&&m(t.cited_text)){let{source:e,title:r,start_block_index:n,end_block_index:i,cited_text:a,...s}=t;return{...s,type:"citation",source:"search",url:e,title:r??void 0,startIndex:n,endIndex:i,citedText:a}}}function dc(t){if(T(t,"document")&&$(t.source)&&"type"in t.source){if(t.source.type==="base64"&&m(t.source.media_type)&&m(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&m(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&m(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&m(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(T(t,"image")&&$(t.source)&&"type"in t.source){if(t.source.type==="base64"&&m(t.source.media_type)&&m(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&m(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&m(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}function fc(t){function*e(){for(let r of t){let n=dc(r);n?yield n:yield r}}return Array.from(e())}function uc(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(T(n,"text")&&m(n.text)){let{text:i,citations:a,...s}=n;if(de(a)&&a.length){let o=a.reduce((c,l)=>{let u=Ap(l);return u?[...c,u]:c},[]);yield{...s,type:"text",text:i,annotations:o};continue}else{yield{...s,type:"text",text:i};continue}}else if(T(n,"thinking")&&m(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")&&m(n.name)&&m(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(T(n,"input_json_delta")){if(kp(t)&&t.tool_call_chunks?.length){let i=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:i.id,name:i.name,args:i.args,index:i.index};continue}}else if(T(n,"server_tool_use")&&m(n.name)&&m(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)&&m(n.input.query))return n.input.query;if(m(n.partial_json)){let s=Ia(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)&&m(n.input.code))return n.input.code;if(m(n.partial_json)){let s=Ia(n.partial_json);if(s?.code)return s.code}return""})}};continue}}else if(T(n,"web_search_tool_result")&&m(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")&&m(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")&&m(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=dc(n);if(i){yield i;continue}}yield{type:"non_standard",value:n}}}return Array.from(e())}var pc={translateContent:uc,translateContentChunk:uc};function kp(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}function Ip(t){return oc(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:cc(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:lc(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}function hc(t){return t.map(Ip)}function mc(t){return!!(T(t,"image_url")&&$(t.image_url)||T(t,"input_audio")&&$(t.input_audio)||T(t,"file")&&$(t.file))}function gc(t){if(T(t,"image_url")&&$(t.image_url)&&m(t.image_url.url)){let e=ka({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(T(t,"input_audio")&&$(t.input_audio)&&m(t.input_audio.data)&&m(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(T(t,"file")&&$(t.file)&&m(t.file.data)){let e=ka({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(m(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}function Cp(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...jn(t.content));for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}function Op(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...jn(t.content));for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}function jn(t){let e=[];for(let r of t)mc(r)?e.push(gc(r)):e.push(r);return e}function Rp(t){if(t.type==="url_citation"){let{url:e,title:r,start_index:n,end_index:i}=t;return{type:"citation",url:e,title:r,startIndex:n,endIndex:i}}if(t.type==="file_citation"){let{file_id:e,filename:r,index:n}=t;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:e}}return t}function _c(t){function*e(){$(t.additional_kwargs?.reasoning)&&de(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((n,i)=>$(i)&&m(i.text)?`${n}${i.text}`:n,"")});let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r)if(T(n,"text")){let{text:i,annotations:a,phase:s,extras:o,...c}=n,l=$(o)?{...o}:{};m(s)&&(l.phase=s);let u=Object.keys(l).length>0?{extras:l}:{};Array.isArray(a)?yield{...c,...u,type:"text",text:String(i),annotations:a.map(Rp)}:yield{...c,...u,type:"text",text:String(i)}}for(let n of t.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if($(t.additional_kwargs)&&de(t.additional_kwargs.tool_outputs))for(let n of t.additional_kwargs.tool_outputs){if(T(n,"web_search_call")){let i={};if($(n.action)&&m(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:m(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:m(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(m(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={};m(n.execution)&&(a.execution=n.execution),m(n.status)&&(a.status=n.status),m(n.call_id)&&(a.call_id=n.call_id),yield{id:m(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"};m(n.execution)&&(i.execution=n.execution),yield{type:"server_tool_call_result",toolCallId:m(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")){m(n.result)&&(yield{type:"image",mimeType:"image/png",data:n.result,id:m(n.id)?n.id:void 0,metadata:{status:m(n.status)?n.status:void 0}}),yield{type:"non_standard",value:n};continue}$(n)&&(yield{type:"non_standard",value:n})}}return Array.from(e())}function Np(t){function*e(){yield*_c(t);for(let r of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return Array.from(e())}var yc={translateContent:t=>typeof t.content=="string"?Cp(t):_c(t),translateContentChunk:t=>typeof t.content=="string"?Op(t):Np(t)};function wc(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}function bc(t,e="pretty"){return e==="pretty"?$p(t):JSON.stringify(t)}function $p(t){let e=[],r=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),i="=".repeat(n),a=r.length%2===0?i:`${i}=`;if(e.push(`${i}${r}${a}`),t.type==="ai"){let s=t;if(s.tool_calls&&s.tool_calls.length>0){e.push("Tool Calls:");for(let o of s.tool_calls){e.push(` ${o.name} (${o.id})`),e.push(` Call ID: ${o.id}`),e.push(" Args:");for(let[c,l]of Object.entries(o.args))e.push(` ${c}: ${typeof l=="object"?JSON.stringify(l):l}`)}}}if(t.type==="tool"){let s=t;s.name&&e.push(`Name: ${s.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
|
|
3
|
+
`)}var Ca=Symbol.for("langchain.message");function vc(t){return Array.isArray(t)?t:typeof t=="string"?t===""?[]:[{type:"text",text:t}]:t==null?[]:[t]}function Pe(t,e){if(typeof t=="string")return t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.length===0?t:Array.isArray(e)&&e.some(r=>Rt(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e];if(Array.isArray(e)){let r=vc(t);return kr(r,e)??[...r,...e]}else return e===""?t:Array.isArray(t)&&t.some(r=>Rt(r))?[...t,{type:"file",source_type:"text",text:e}]:[...vc(t),{type:"text",text:e}]}function Sc(t,e){return t==="error"||e==="error"?"error":"success"}function Pp(t,e){function r(n,i){if(typeof n!="object"||n===null||n===void 0)return n;if(i>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(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(t,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"}}[Ca]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(t){let e=typeof t=="string"||Array.isArray(t)?{content:t}:t;e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),this.name=e.name,e.content===void 0&&e.contentBlocks!==void 0?(this.content=e.contentBlocks,this.response_metadata={output_version:"v1",...e.response_metadata}):e.content!==void 0?(this.content=e.content??[],this.response_metadata=e.response_metadata):(this.content=[],this.response_metadata=e.response_metadata),this.additional_kwargs=e.additional_kwargs,this.id=e.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(t=>typeof t=="string"?t:t.type==="text"?t.text:"").join(""):""}get contentBlocks(){let t=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[hc,jn,fc].reduce((e,r)=>r(e),t)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(t){return typeof t=="object"&&t!==null&&Ca in t&&t[Ca]===!0&&wc(t)}_updateId(t){this.id=t,this.lc_kwargs.id=t}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](t){if(t===null)return this;let e=Pp(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return bc(this,t)}};function Xw(t){return Array.isArray(t)&&t.every(e=>typeof e.index=="number")}var Mp=["index","created","timestamp"];function ce(t,e,r){let n=r?.ignoreKeys??Mp;if(t==null&&e==null)return;if(t==null||e==null)return t??e;let i={...t};for(let[a,s]of Object.entries(e))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]=kr(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 Lp(t){return typeof t=="number"||typeof t=="string"}function xc(t){return typeof t!="object"||t===null||!("index"in t)?!1:Lp(t.index)}function Ec(t){if(typeof t!="object"||t===null||!("id"in t))return!1;let e=t.id;return e!=null&&e!==""}function jp(t,e){let r=xc(e),n=Ec(e);return!r&&!n?-1:t.findIndex(i=>{let a=xc(i),s=Ec(i);return r&&a?i.index!==e.index?!1:s&&n?i.id===e.id:!0:!r&&!a&&n&&s?i.id===e.id:!1})}function kr(t,e,r){if(!(t==null&&e==null)){if(t==null||e==null)return t||e;{let n=[...t];for(let i of e){let a=jp(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 Tc(t,e,r){if(!(t==null&&e==null)){if(t==null||e==null)return t??e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
|
|
4
|
+
Left ${typeof t}
|
|
5
|
+
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return kr(t,e,r);if(typeof t=="object"&&typeof e=="object")return ce(t,e,r);if(t===e)return t;throw new Error(`Can not merge objects of different types.
|
|
6
|
+
Left ${t}
|
|
7
|
+
Right ${e}`)}}var Be=class Ac extends ke{static isInstance(e){if(!super.isInstance(e))return!1;let r=Object.getPrototypeOf(e);for(;r!==null;){if(r===Ac.prototype)return!0;r=Object.getPrototypeOf(r)}return!1}};function kc(t){return typeof t.role=="string"}function Ic(t){return typeof t?._getType=="function"}function Qw(t){return Be.isInstance(t)}var ib=D({ToolMessage:()=>Kt,ToolMessageChunk:()=>Dp,defaultToolCallParser:()=>Ra,isDirectToolOutput:()=>Oa,isToolMessage:()=>Up,isToolMessageChunk:()=>Bp});function Oa(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}var Kt=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(t,e,r){let n=typeof t=="string"||Array.isArray(t)?{content:t,name:r,tool_call_id:e}:t;super(n),this.tool_call_id=n.tool_call_id,this.artifact=n.artifact,this.status=n.status,this.metadata=n.metadata}static isInstance(t){return super.isInstance(t)&&t.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Dp=class extends Be{type="tool";tool_call_id;status;artifact;constructor(t){super(t),this.tool_call_id=t.tool_call_id,this.artifact=t.artifact,this.status=t.status}static lc_name(){return"ToolMessageChunk"}concat(t){let e=this.constructor;return new e({content:Pe(this.content,t.content),additional_kwargs:ce(this.additional_kwargs,t.additional_kwargs),response_metadata:ce(this.response_metadata,t.response_metadata),artifact:Tc(this.artifact,t.artifact),tool_call_id:this.tool_call_id,id:this.id??t.id,status:Sc(this.status,t.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function Ra(t){let e=[],r=[];for(let n of t)if(n.function){let i=n.function.name;try{let a=JSON.parse(n.function.arguments);e.push({name:i||"",args:a||{},id:n.id})}catch{r.push({name:i,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}function Up(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}function Bp(t){return t._getType()==="tool"}function Na(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function zp(t){if($(t.document)&&$(t.document.source)){let e=Na($(t.document)&&m(t.document.format)?t.document.format:"");if($(t.document.source)){if($(t.document.source.s3Location)&&m(t.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:t.document.source.s3Location.uri};if(Ln(t.document.source.bytes))return{type:"file",mimeType:e,data:t.document.source.bytes};if(m(t.document.source.text))return{type:"file",mimeType:e,data:Buffer.from(t.document.source.text).toString("base64")};if(de(t.document.source.content))return{type:"file",mimeType:e,data:t.document.source.content.reduce((r,n)=>$(n)&&m(n.text)?r+n.text:r,"")}}}return{type:"non_standard",value:t}}function Fp(t){if(T(t,"image")&&$(t.image)){let e=Na($(t.image)&&m(t.image.format)?t.image.format:"");if($(t.image.source)){if($(t.image.source.s3Location)&&m(t.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:t.image.source.s3Location.uri};if(Ln(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}function Hp(t){if(T(t,"video")&&$(t.video)){let e=Na($(t.video)&&m(t.video.format)?t.video.format:"");if($(t.video.source)){if($(t.video.source.s3Location)&&m(t.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:t.video.source.s3Location.uri};if(Ln(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}function Cc(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(T(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(T(n,"citations_content")&&$(n.citationsContent)){yield{type:"text",text:de(n.citationsContent.content)?n.citationsContent.content.reduce((i,a)=>$(a)&&m(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,l)=>$(l)&&m(l.text)?c+l.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 zp(n);continue}else if(T(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(T(n,"image")&&$(n.image)){yield Fp(n);continue}else if(T(n,"reasoning_content")&&m(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(T(n,"text")&&m(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 Hp(n);continue}}yield{type:"non_standard",value:n}}}return Array.from(e())}var Oc={translateContent:Cc,translateContentChunk:Cc};function Rc(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(m(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&m(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}var Nc={translateContent:Rc,translateContentChunk:Rc};function $c(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(T(n,"text")&&m(n.text)){yield{type:"text",text:n.text};continue}else if(T(n,"thinking")&&m(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(T(n,"inlineData")&&$(n.inlineData)&&m(n.inlineData.mimeType)&&m(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(T(n,"functionCall")&&$(n.functionCall)&&m(n.functionCall.name)&&$(n.functionCall.args)){yield{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(T(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(T(n,"fileData")&&$(n.fileData)&&m(n.fileData.mimeType)&&m(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(e())}var Pc={translateContent:$c,translateContentChunk:$c};function Mc(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(T(n,"reasoning")&&m(n.reasoning)){let i=Ue(()=>{let a=r.indexOf(n);if(de(t.additional_kwargs?.signatures)&&a>=0)return t.additional_kwargs.signatures.at(a)});m(i)?yield{type:"reasoning",reasoning:n.reasoning,signature:i}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(T(n,"thinking")&&m(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(T(n,"text")&&m(n.text)){yield{type:"text",text:n.text};continue}else if(T(n,"image_url")){if(m(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")&&m(n.mimeType)&&m(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return Array.from(e())}var Lc={translateContent:Mc,translateContentChunk:Mc};function jc(t){let e=[],r=t.additional_kwargs?.reasoning;if(m(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string"){let n=t.content,i=n.match(/<think>([\s\S]*?)<\/think>/);if(i){let a=i[1].trim();a.length>0&&e.push({type:"reasoning",reasoning:a}),n=n.replace(/<think>[\s\S]*?<\/think>/,"").trim()}n.length>0&&e.push({type:"text",text:n})}else for(let n of t.content)if(typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&m(n.text)){let i=n.text,a=i.match(/<think>([\s\S]*?)<\/think>/);if(a){let s=a[1].trim();s.length>0&&e.push({type:"reasoning",reasoning:s}),i=i.replace(/<think>[\s\S]*?<\/think>/,"").trim()}i.length>0&&e.push({type:"text",text:i})}for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}var Dc={translateContent:jc,translateContentChunk:jc};function Uc(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(m(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&m(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}var Bc={translateContent:Uc,translateContentChunk:Uc};function zc(t){let e=[];if($(t.additional_kwargs?.reasoning)){let n=t.additional_kwargs.reasoning;if(de(n.summary)){let i=n.summary.reduce((a,s)=>$(s)&&m(s.text)?`${a}${s.text}`:a,"");i.length>0&&e.push({type:"reasoning",reasoning:i})}}let r=t.additional_kwargs?.reasoning_content;if(m(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&m(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}var Fc={translateContent:zc,translateContentChunk:zc};function Hc(t){function*e(){let r=Ue(()=>{if(typeof t.content=="string")return t.additional_kwargs.originalTextContentBlock?[{...t.additional_kwargs.originalTextContentBlock,type:"text"}]:[{type:"text",text:t.content}];{let n=t.additional_kwargs?.originalTextContentBlock;if(n?.thoughtSignature&&!t.content.some(i=>"thoughtSignature"in i)){let i=[...t.content];for(let a=i.length-1;a>=0;a--){let s=i[a];if(s.type==="text"&&!s.thought)return s.thoughtSignature=n.thoughtSignature,i}}return t.content}});for(let n of r){let i=Ue(()=>T(n,"text")&&m(n.text)?{type:"text",text:n.text}:T(n,"inlineData")&&$(n.inlineData)&&m(n.inlineData.mimeType)&&m(n.inlineData.data)?{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data}:T(n,"functionCall")&&$(n.functionCall)&&m(n.functionCall.name)&&$(n.functionCall.args)?{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args}:T(n,"functionResponse")?{type:"non_standard",value:n}:T(n,"fileData")&&$(n.fileData)&&m(n.fileData.mimeType)&&m(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(e())}var Gc={translateContent:Hc,translateContentChunk:Hc};globalThis.lc_block_translators_registry??=new Map([["anthropic",pc],["bedrock-converse",Oc],["deepseek",Nc],["google",Gc],["google-genai",Pc],["google-vertexai",Lc],["groq",Dc],["ollama",Bc],["openai",yc],["xai",Fc]]);function $a(t){return globalThis.lc_block_translators_registry.get(t)}function Vc(t,e){return ce(t,e)??{}}function Zc(t,e){let r={};return(t?.audio!==void 0||e?.audio!==void 0)&&(r.audio=(t?.audio??0)+(e?.audio??0)),(t?.image!==void 0||e?.image!==void 0)&&(r.image=(t?.image??0)+(e?.image??0)),(t?.video!==void 0||e?.video!==void 0)&&(r.video=(t?.video??0)+(e?.video??0)),(t?.document!==void 0||e?.document!==void 0)&&(r.document=(t?.document??0)+(e?.document??0)),(t?.text!==void 0||e?.text!==void 0)&&(r.text=(t?.text??0)+(e?.text??0)),r}function Gp(t,e){let r={...Zc(t,e)};return(t?.cache_read!==void 0||e?.cache_read!==void 0)&&(r.cache_read=(t?.cache_read??0)+(e?.cache_read??0)),(t?.cache_creation!==void 0||e?.cache_creation!==void 0)&&(r.cache_creation=(t?.cache_creation??0)+(e?.cache_creation??0)),r}function Vp(t,e){let r={...Zc(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}function Dn(t,e){return{input_tokens:(t?.input_tokens??0)+(e?.input_tokens??0),output_tokens:(t?.output_tokens??0)+(e?.output_tokens??0),total_tokens:(t?.total_tokens??0)+(e?.total_tokens??0),input_token_details:Gp(t?.input_token_details,e?.input_token_details),output_token_details:Vp(t?.output_token_details,e?.output_token_details)}}function qc(t){let e=Symbol.for(t);return{brand(r,n){let i=n?Symbol.for(`${t}.${n}`):e;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 qc(`${t}.${r}`)},isInstance(r){return typeof r=="object"&&r!==null&&e in r&&r[e]===!0}}}var Jc=qc("langchain");var Bb=D({ContextOverflowError:()=>qp,LangChainError:()=>Ma,ModelAbortError:()=>Zp,addLangChainErrorFields:()=>Pa,ns:()=>Un});function Pa(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
8
|
+
|
|
9
|
+
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
10
|
+
`,t}var Un=Jc.sub("error"),Ma=class extends Un.brand(Error){name="LangChainError";constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},Zp=class extends Un.brand(Ma,"model-abort"){name="ModelAbortError";partialOutput;constructor(t,e){super(t),this.partialOutput=e}},qp=class Wc extends Un.brand(Ma,"context-overflow"){name="ContextOverflowError";cause;constructor(e){super(e??"Input exceeded the model's context window.")}static fromError(e){let r=new Wc(e.message);return r.cause=e,r}};function Nt(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function Kc(t){return!!(t&&typeof t=="object"&&"toolCall"in t&&t.toolCall!=null&&typeof t.toolCall=="object"&&"id"in t.toolCall&&typeof t.toolCall.id=="string")}var Ir=class extends Error{output;constructor(t,e){super(t),this.output=e}};function Zb(t,e=La){t=t.trim();let r=t.indexOf("```");if(r===-1)return e(t);let n=t.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)),e(a.trim())}function Jp(t){try{return JSON.parse(t)}catch{}let e=t.trim();if(e.length===0)throw new Error("Unexpected end of JSON input");let r=0;function n(){for(;r<e.length&&/\s/.test(e[r]);)r+=1}function i(){if(e[r]!=='"')throw new Error(`Expected '"' at position ${r}, got '${e[r]}'`);r+=1;let u="",d=!1;for(;r<e.length;){let f=e[r];if(d){if(f==="n")u+=`
|
|
13
|
+
`;else if(f==="t")u+=" ";else if(f==="r")u+="\r";else if(f==="\\")u+="\\";else if(f==='"')u+='"';else if(f==="b")u+="\b";else if(f==="f")u+="\f";else if(f==="/")u+="/";else if(f==="u"){let p=e.substring(r+1,r+5);if(/^[0-9A-Fa-f]{0,4}$/.test(p))p.length===4?u+=String.fromCharCode(Number.parseInt(p,16)):u+=`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,u;u+=f}r+=1}return d&&(u+="\\"),u}function a(){let u=r,d="";if(e[r]==="-"&&(d+="-",r+=1),r<e.length&&e[r]==="0"&&(d+="0",r+=1,e[r]>="0"&&e[r]<="9"))throw new Error(`Invalid number at position ${u}`);if(r<e.length&&e[r]>="1"&&e[r]<="9")for(;r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(r<e.length&&e[r]===".")for(d+=".",r+=1;r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(r<e.length&&(e[r]==="e"||e[r]==="E"))for(d+=e[r],r+=1,r<e.length&&(e[r]==="+"||e[r]==="-")&&(d+=e[r],r+=1);r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(d==="-")return-0;let f=Number.parseFloat(d);if(Number.isNaN(f))throw r=u,new Error(`Invalid number '${d}' at position ${u}`);return f}function s(){if(n(),r>=e.length)throw new Error(`Unexpected end of input at position ${r}`);let u=e[r];if(u==="{")return c();if(u==="[")return o();if(u==='"')return i();if("null".startsWith(e.substring(r,r+4)))return r+=Math.min(4,e.length-r),null;if("true".startsWith(e.substring(r,r+4)))return r+=Math.min(4,e.length-r),!0;if("false".startsWith(e.substring(r,r+5)))return r+=Math.min(5,e.length-r),!1;if(u==="-"||u>="0"&&u<="9")return a();throw new Error(`Unexpected character '${u}' at position ${r}`)}function o(){if(e[r]!=="[")throw new Error(`Expected '[' at position ${r}, got '${e[r]}'`);let u=[];if(r+=1,n(),r>=e.length)return u;if(e[r]==="]")return r+=1,u;for(;r<e.length;){if(n(),r>=e.length||(u.push(s()),n(),r>=e.length))return u;if(e[r]==="]")return r+=1,u;if(e[r]===","){r+=1;continue}throw new Error(`Expected ',' or ']' at position ${r}, got '${e[r]}'`)}return u}function c(){if(e[r]!=="{")throw new Error(`Expected '{' at position ${r}, got '${e[r]}'`);let u={};if(r+=1,n(),r>=e.length)return u;if(e[r]==="}")return r+=1,u;for(;r<e.length;){if(n(),r>=e.length)return u;let d=i();if(n(),r>=e.length)return u;if(e[r]!==":")throw new Error(`Expected ':' at position ${r}, got '${e[r]}'`);if(r+=1,n(),r>=e.length||(u[d]=s(),n(),r>=e.length))return u;if(e[r]==="}")return r+=1,u;if(e[r]===","){r+=1;continue}throw new Error(`Expected ',' or '}' at position ${r}, got '${e[r]}'`)}return u}let l=s();if(n(),r<e.length)throw new Error(`Unexpected character '${e[r]}' at position ${r}`);return l}function La(t){try{return typeof t>"u"?null:Jp(t)}catch{return null}}var ja=class Yc extends ke{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return Yc}constructor(e,r){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:r}),super(e),this.role=e.role}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},Xc=class extends Be{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(t,e){(typeof t=="string"||Array.isArray(t))&&(t={content:t,role:e}),super(t),this.role=t.role}concat(t){let e=this.constructor;return new e({content:Pe(this.content,t.content),additional_kwargs:ce(this.additional_kwargs,t.additional_kwargs),response_metadata:ce(this.response_metadata,t.response_metadata),role:this.role,id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function Wb(t){return t._getType()==="generic"}function Kb(t){return t._getType()==="generic"}var Qc=class extends ke{static lc_name(){return"FunctionMessage"}type="function";name;constructor(t){super(t),this.name=t.name}},el=class extends Be{static lc_name(){return"FunctionMessageChunk"}type="function";concat(t){let e=this.constructor;return new e({content:Pe(this.content,t.content),additional_kwargs:ce(this.additional_kwargs,t.additional_kwargs),response_metadata:ce(this.response_metadata,t.response_metadata),name:this.name??"",id:this.id??t.id})}};function e0(t){return t._getType()==="function"}function t0(t){return t._getType()==="function"}var Yt=class extends ke{static lc_name(){return"HumanMessage"}type="human";constructor(t){super(t)}static isInstance(t){return super.isInstance(t)&&t.type==="human"}},tl=class extends Be{static lc_name(){return"HumanMessageChunk"}type="human";constructor(t){super(t)}concat(t){let e=this.constructor;return new e({content:Pe(this.content,t.content),additional_kwargs:ce(this.additional_kwargs,t.additional_kwargs),response_metadata:ce(this.response_metadata,t.response_metadata),id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="human"}};function s0(t){return t.getType()==="human"}function o0(t){return t.getType()==="human"}var rl=class extends ke{type="remove";id;constructor(t){super({...t,content:[]}),this.id=t.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(t){return super.isInstance(t)&&t.type==="remove"}};var zn=class Bn extends ke{static lc_name(){return"SystemMessage"}type="system";constructor(e){super(e)}concat(e){if(typeof e=="string")return new Bn({content:Pe(this.content,e),additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata,id:this.id,name:this.name});if(Bn.isInstance(e))return new Bn({content:Pe(this.content,e.content),additional_kwargs:{...this.additional_kwargs,...e.additional_kwargs},response_metadata:{...this.response_metadata,...e.response_metadata},id:this.id??e.id,name:this.name??e.name});throw new Error("Unexpected chunk type for system message")}static isInstance(e){return super.isInstance(e)&&e.type==="system"}},nl=class extends Be{static lc_name(){return"SystemMessageChunk"}type="system";constructor(t){super(t)}concat(t){let e=this.constructor;return new e({content:Pe(this.content,t.content),additional_kwargs:ce(this.additional_kwargs,t.additional_kwargs),response_metadata:ce(this.response_metadata,t.response_metadata),id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="system"}};function m0(t){return t._getType()==="system"}function g0(t){return t._getType()==="system"}var O0=t=>t();function Wp(t){return Nt(t)?t:typeof t.id=="string"&&t.type==="function"&&typeof t.function=="object"&&t.function!==null&&"arguments"in t.function&&typeof t.function.arguments=="string"&&"name"in t.function&&typeof t.function.name=="string"?{id:t.id,args:JSON.parse(t.function.arguments),name:t.function.name,type:"tool_call"}:t}function Kp(t){return typeof t=="object"&&t!=null&&t.lc===1&&Array.isArray(t.id)&&t.kwargs!=null&&typeof t.kwargs=="object"}function Da(t){let e,r;if(Kp(t)){let n=t.id.at(-1);n==="HumanMessage"||n==="HumanMessageChunk"?e="user":n==="AIMessage"||n==="AIMessageChunk"?e="assistant":n==="SystemMessage"||n==="SystemMessageChunk"?e="system":n==="FunctionMessage"||n==="FunctionMessageChunk"?e="function":n==="ToolMessage"||n==="ToolMessageChunk"?e="tool":e="unknown",r=t.kwargs}else{let{type:n,...i}=t;e=n,r=i}if(e==="human"||e==="user")return new Yt(r);if(e==="ai"||e==="assistant"){let{tool_calls:n,...i}=r;if(!Array.isArray(n))return new Cr(r);let a=n.map(Wp);return new Cr({...i,tool_calls:a})}else{if(e==="system")return new zn(r);if(e==="developer")return new zn({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in r)return new Kt({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});if(e==="remove"&&"id"in r&&typeof r.id=="string")return new rl({...r,id:r.id});throw Pa(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(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function il(t){if(typeof t=="string")return new Yt(t);if(Ic(t))return t;if(Array.isArray(t)){let[e,r]=t;return Da({type:e,content:r})}else if(kc(t)){let{role:e,...r}=t;return Da({...r,type:e})}else return Da(t)}function Yp(t){if(typeof t=="string")return t;switch(t.type){case"text":return t.text??"";case"text-plain":return t.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return t.type?`[${t.type}]`:""}}function Fn(t,e="Human",r="AI"){let n=[];for(let i of t){let a;if(i.type==="human")a=e;else if(i.type==="ai")a=r;else if(i.type==="system")a="System";else if(i.type==="tool")a="Tool";else if(i.type==="generic")a=i.role;else throw new Error(`Got unsupported message type: ${i.type}`);let s=i.name?`${i.name}, `:"",o=typeof i.content=="string"?i.content:Array.isArray(i.content)?i.content.map(Yp).filter(Boolean).join(""):"",c=`${a}: ${s}${o}`;if(i.type==="ai"){let l=i;l.tool_calls&&l.tool_calls.length>0?c+=JSON.stringify(l.tool_calls):l.additional_kwargs&&"function_call"in l.additional_kwargs&&(c+=JSON.stringify(l.additional_kwargs.function_call))}n.push(c)}return n.join(`
|
|
16
|
+
`)}function Xp(t){if(t.data!==void 0)return t;{let e=t;return{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}}}}function Ua(t){let e=Xp(t);switch(e.type){case"human":return new Yt(e.data);case"ai":return new Cr(e.data);case"system":return new zn(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new Qc(e.data);case"tool":if(e.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new Kt(e.data);case"generic":if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new ja(e.data);default:throw new Error(`Got unexpected type: ${e.type}`)}}function R0(t){return t.map(Ua)}function N0(t){return t.map(e=>e.toDict())}function $0(t){let e=t._getType();if(e==="human")return new tl({...t});if(e==="ai"){let r={...t};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 Or({...r})}else{if(e==="system")return new nl({...t});if(e==="function")return new el({...t});if(ja.isInstance(t))return new Xc({...t});throw new Error("Unknown message type.")}}function al(t){let e=t.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 e){let a=null,s=i[0]?.name??"",o=i.map(u=>u.args||"").join("").trim(),c=o.length?o:"{}",l=i[0]?.id;try{if(a=La(c),!l||a===null||typeof a!="object"||Array.isArray(a))throw new Error("Malformed tool call chunk args.");r.push({name:s,args:a,id:l,type:"tool_call"})}catch{n.push({name:s,args:c,id:l,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:t,tool_calls:r,invalid_tool_calls:n}}var Cr=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(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{e=t;let r=e.additional_kwargs?.tool_calls,n=e.tool_calls;r!=null&&r.length>0&&(n===void 0||n.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
|
|
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]=Ra(r);e.tool_calls=i??[],e.invalid_tool_calls=a??[]}else e.tool_calls=e.tool_calls??[],e.invalid_tool_calls=e.invalid_tool_calls??[]}catch{e.tool_calls=[],e.invalid_tool_calls=[]}if(e.response_metadata!==void 0&&"output_version"in e.response_metadata&&e.response_metadata.output_version==="v1"&&(e.contentBlocks=e.content,e.content=void 0),e.contentBlocks!==void 0){e.tool_calls&&e.contentBlocks.push(...e.tool_calls.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})));let i=e.contentBlocks.filter(a=>a.type==="tool_call").filter(a=>!e.tool_calls?.some(s=>s.id===a.id&&s.name===a.name));i.length>0&&(e.tool_calls=i.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})))}}super(e),typeof e!="string"&&(this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=e.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let e=$a(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let t=super.contentBlocks;if(this.tool_calls){let e=this.tool_calls.filter(r=>!t.some(n=>n.id===r.id&&n.name===r.name));t.push(...e.map(r=>({type:"tool_call",id:r.id,name:r.name,args:r.args})))}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}};function B0(t){return t._getType()==="ai"}function z0(t){return t._getType()==="ai"}var Or=class extends Be{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(t.tool_call_chunks===void 0||t.tool_call_chunks.length===0)e={...t,tool_calls:t.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0};else{let r=al(t.tool_call_chunks??[]);e={...t,tool_call_chunks:r.tool_call_chunks,tool_calls:r.tool_calls,invalid_tool_calls:r.invalid_tool_calls,usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0}}super(e),this.tool_call_chunks=e.tool_call_chunks??this.tool_call_chunks,this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=e.usage_metadata}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 e=$a(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let t=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){let e=this.content.filter(r=>r.type==="tool_call").map(r=>r.id);for(let r of this.tool_calls)r.id&&!e.includes(r.id)&&t.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(t){let e={content:Pe(this.content,t.content),additional_kwargs:ce(this.additional_kwargs,t.additional_kwargs),response_metadata:Vc(this.response_metadata,t.response_metadata),tool_call_chunks:[],tool_calls:[],id:this.id??t.id};if(this.tool_call_chunks!==void 0||t.tool_call_chunks!==void 0){let n=kr(this.tool_call_chunks,t.tool_call_chunks);n!==void 0&&n.length>0&&(e.tool_call_chunks=n)}if(this.tool_calls!==void 0||t.tool_calls!==void 0){let n=kr(this.tool_calls,t.tool_calls);n!==void 0&&n.length>0&&(e.tool_calls=n)}(this.usage_metadata!==void 0||t.usage_metadata!==void 0)&&(e.usage_metadata=Dn(this.usage_metadata,t.usage_metadata));let r=this.constructor;return new r(e)}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}};var Z0=D({getEnv:()=>ul,getEnvironmentVariable:()=>Xe,getRuntimeEnvironment:()=>za,isBrowser:()=>sl,isDeno:()=>Hn,isJsDom:()=>cl,isNode:()=>ll,isWebWorker:()=>ol}),sl=()=>typeof window<"u"&&typeof window.document<"u",ol=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",cl=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Hn=()=>typeof Deno<"u",ll=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Hn(),ul=()=>{let t;return sl()?t="browser":ll()?t="node":ol()?t="webworker":cl()?t="jsdom":Hn()?t="deno":t="other",t},Ba;function za(){return Ba===void 0&&(Ba={library:"langchain-js",runtime:ul()}),Ba}function Xe(t){try{return typeof process<"u"?process.env?.[t]:Hn()?Deno?.env.get(t):void 0}catch{return}}var dl=/^(?:[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 Qp(t){return typeof t=="string"&&dl.test(t)}var $t=Qp;function eh(t){if(!$t(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}var Fa=eh;var ye=[];for(let t=0;t<256;++t)ye.push((t+256).toString(16).slice(1));function Rr(t,e=0){return(ye[t[e+0]]+ye[t[e+1]]+ye[t[e+2]]+ye[t[e+3]]+"-"+ye[t[e+4]]+ye[t[e+5]]+"-"+ye[t[e+6]]+ye[t[e+7]]+"-"+ye[t[e+8]]+ye[t[e+9]]+"-"+ye[t[e+10]]+ye[t[e+11]]+ye[t[e+12]]+ye[t[e+13]]+ye[t[e+14]]+ye[t[e+15]]).toLowerCase()}var Ha,th=new Uint8Array(16);function Nr(){if(!Ha){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ha=crypto.getRandomValues.bind(crypto)}return Ha(th)}function rh(t){t=unescape(encodeURIComponent(t));let e=new Uint8Array(t.length);for(let r=0;r<t.length;++r)e[r]=t.charCodeAt(r);return e}var fl="6ba7b810-9dad-11d1-80b4-00c04fd430c8",pl="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Ga(t,e,r,n,i,a){let s=typeof r=="string"?rh(r):r,o=typeof n=="string"?Fa(n):n;if(typeof n=="string"&&(n=Fa(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=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,i){if(a=a||0,a<0||a+16>i.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let l=0;l<16;++l)i[a+l]=c[l];return i}return Rr(c)}var nh=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Va={randomUUID:nh};function ih(t,e,r){if(Va.randomUUID&&!e&&!t)return Va.randomUUID();t=t||{};let n=t.random??t.rng?.()??Nr();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[r+i]=n[i];return e}return Rr(n)}var Za=ih;function ah(t,e,r,n){switch(t){case 0:return e&r^~e&n;case 1:return e^r^n;case 2:return e&r^e&n^r&n;case 3:return e^r^n}}function qa(t,e){return t<<e|t>>>32-e}function sh(t){let e=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(t.length+1);n.set(t),n[t.length]=128,t=n;let i=t.length/4+2,a=Math.ceil(i/16),s=new Array(a);for(let o=0;o<a;++o){let c=new Uint32Array(16);for(let l=0;l<16;++l)c[l]=t[o*64+l*4]<<24|t[o*64+l*4+1]<<16|t[o*64+l*4+2]<<8|t[o*64+l*4+3];s[o]=c}s[a-1][14]=(t.length-1)*8/Math.pow(2,32),s[a-1][14]=Math.floor(s[a-1][14]),s[a-1][15]=(t.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]=qa(c[h-3]^c[h-8]^c[h-14]^c[h-16],1);let l=r[0],u=r[1],d=r[2],f=r[3],p=r[4];for(let h=0;h<80;++h){let g=Math.floor(h/20),b=qa(l,5)+ah(g,u,d,f)+p+e[g]+c[h]>>>0;p=f,f=d,d=qa(u,30)>>>0,u=l,l=b}r[0]=r[0]+l>>>0,r[1]=r[1]+u>>>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 hl=sh;function Ja(t,e,r,n){return Ga(80,hl,t,e,r,n)}Ja.DNS=fl;Ja.URL=pl;var oh=Ja;var Wa={};function ch(t,e,r){let n;if(t)n=ml(t.random??t.rng?.()??Nr(),t.msecs,t.seq,e,r);else{let i=Date.now(),a=Nr();lh(Wa,i,a),n=ml(a,Wa.msecs,Wa.seq,e,r)}return e??Rr(n)}function lh(t,e,r){return t.msecs??=-1/0,t.seq??=0,e>t.msecs?(t.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}function ml(t,e,r,n,i=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),i=0;else if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return e??=Date.now(),r??=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9],n[i++]=e/1099511627776&255,n[i++]=e/4294967296&255,n[i++]=e/16777216&255,n[i++]=e/65536&255,n[i++]=e/256&255,n[i++]=e&255,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|t[10]&3,n[i++]=t[11],n[i++]=t[12],n[i++]=t[13],n[i++]=t[14],n[i++]=t[15],n}var He=ch;var Ev=D({BaseCallbackHandler:()=>Xt,callbackHandlerPrefersStreaming:()=>fh,isBaseCallbackHandler:()=>Ka}),dh=class{};function fh(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}var Xt=class extends dh{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,Mn(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Xe("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(t){super(),this.lc_kwargs=t||{},t&&(this.ignoreLLM=t.ignoreLLM??this.ignoreLLM,this.ignoreChain=t.ignoreChain??this.ignoreChain,this.ignoreAgent=t.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=t.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=t.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=t.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(t._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return ft.prototype.toJSON.call(this)}toJSONNotImplemented(){return ft.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends Xt{name=He();constructor(){super(),Object.assign(this,t)}}return new e}},Ka=t=>{let e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"};var gl=/^(?:[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 ph(t){return typeof t=="string"&&gl.test(t)}var an=ph;function hh(t){if(!an(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}var Gn=hh;var we=[];for(let t=0;t<256;++t)we.push((t+256).toString(16).slice(1));function $r(t,e=0){return(we[t[e+0]]+we[t[e+1]]+we[t[e+2]]+we[t[e+3]]+"-"+we[t[e+4]]+we[t[e+5]]+"-"+we[t[e+6]]+we[t[e+7]]+"-"+we[t[e+8]]+we[t[e+9]]+"-"+we[t[e+10]]+we[t[e+11]]+we[t[e+12]]+we[t[e+13]]+we[t[e+14]]+we[t[e+15]]).toLowerCase()}var mh=new Uint8Array(16);function Pr(){return crypto.getRandomValues(mh)}function gh(t,e,r){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():_h(t,e,r)}function _h(t,e,r){t=t||{};let n=t.random??t.rng?.()??Pr();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[r+i]=n[i];return e}return $r(n)}var Qt=gh;function yh(t,e,r,n){switch(t){case 0:return e&r^~e&n;case 1:return e^r^n;case 2:return e&r^e&n^r&n;case 3:return e^r^n}}function Ya(t,e){return t<<e|t>>>32-e}function wh(t){let e=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(t.length+1);n.set(t),n[t.length]=128,t=n;let i=t.length/4+2,a=Math.ceil(i/16),s=new Array(a);for(let o=0;o<a;++o){let c=new Uint32Array(16);for(let l=0;l<16;++l)c[l]=t[o*64+l*4]<<24|t[o*64+l*4+1]<<16|t[o*64+l*4+2]<<8|t[o*64+l*4+3];s[o]=c}s[a-1][14]=(t.length-1)*8/2**32,s[a-1][14]=Math.floor(s[a-1][14]),s[a-1][15]=(t.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]=Ya(c[h-3]^c[h-8]^c[h-14]^c[h-16],1);let l=r[0],u=r[1],d=r[2],f=r[3],p=r[4];for(let h=0;h<80;++h){let g=Math.floor(h/20),b=Ya(l,5)+yh(g,u,d,f)+p+e[g]+c[h]>>>0;p=f,f=d,d=Ya(u,30)>>>0,u=l,l=b}r[0]=r[0]+l>>>0,r[1]=r[1]+u>>>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 _l=wh;function bh(t){t=unescape(encodeURIComponent(t));let e=new Uint8Array(t.length);for(let r=0;r<t.length;++r)e[r]=t.charCodeAt(r);return e}var Xa="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Qa="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function es(t,e,r,n,i,a){let s=typeof r=="string"?bh(r):r,o=typeof n=="string"?Gn(n):n;if(typeof n=="string"&&(n=Gn(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=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,i){if(a??=0,a<0||a+16>i.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let l=0;l<16;++l)i[a+l]=c[l];return i}return $r(c)}function ts(t,e,r,n){return es(80,_l,t,e,r,n)}ts.DNS=Xa;ts.URL=Qa;var rs=ts;var ns={};function vh(t,e,r){let n;if(t)n=yl(t.random??t.rng?.()??Pr(),t.msecs,t.seq,e,r);else{let i=Date.now(),a=Pr();xh(ns,i,a),n=yl(a,ns.msecs,ns.seq,e,r)}return e??$r(n)}function xh(t,e,r){return t.msecs??=-1/0,t.seq??=0,e>t.msecs?(t.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}function yl(t,e,r,n,i=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),i=0;else if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return e??=Date.now(),r??=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9],n[i++]=e/1099511627776&255,n[i++]=e/4294967296&255,n[i++]=e/16777216&255,n[i++]=e/65536&255,n[i++]=e/256&255,n[i++]=e&255,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|t[10]&3,n[i++]=t[11],n[i++]=t[12],n[i++]=t[13],n[i++]=t[14],n[i++]=t[15],n}var Mr=vh;var wl="gen_ai.operation.name",bl="gen_ai.system",is="gen_ai.request.model",vl="gen_ai.response.model",as="gen_ai.usage.input_tokens",ss="gen_ai.usage.output_tokens",os="gen_ai.usage.total_tokens",xl="gen_ai.request.max_tokens",El="gen_ai.request.temperature",Sl="gen_ai.request.top_p",Tl="gen_ai.request.frequency_penalty",Al="gen_ai.request.presence_penalty",kl="gen_ai.response.finish_reasons",Il="gen_ai.prompt",Cl="gen_ai.completion",Ol="gen_ai.request.extra_query",Rl="gen_ai.request.extra_body",Nl="gen_ai.serialized.name",$l="gen_ai.serialized.signature",Pl="gen_ai.serialized.doc",Ml="gen_ai.response.id",Ll="gen_ai.response.service_tier",jl="gen_ai.response.system_fingerprint",Dl="gen_ai.usage.input_token_details",Ul="gen_ai.usage.output_token_details",Bl="langsmith.trace.session_id",zl="langsmith.trace.session_name",Fl="langsmith.span.kind",Hl="langsmith.trace.name",Gl="langsmith.metadata",cs="langsmith.span.tags";var Vl="langsmith.request.streaming",Zl="langsmith.request.headers";var ls="langsmith.usage_metadata";var Th=(...t)=>fetch(...t),Ah,ql=Symbol.for("ls:fetch_implementation");var Jl=()=>globalThis[ql]===void 0?!0:Ah??!1,Wl=t=>async(...e)=>{if(t||ne("DEBUG")==="true"){let[n,i]=e;console.log(`\u2192 ${i?.method||"GET"} ${n}`)}let r=await(globalThis[ql]??Th)(...e);return(t||ne("DEBUG")==="true")&&console.log(`\u2190 ${r.status} ${r.statusText} ${r.url}`),r};var sn=()=>ne("PROJECT")??pe("LANGCHAIN_SESSION")??"default";var Kl={};function er(t){Kl[t]||(console.warn(t),Kl[t]=!0)}var _=t=>BigInt(t),eu=_("0x9E3779B1"),tu=_("0x85EBCA77"),kh=_("0xC2B2AE3D"),Pt=_("0x9E3779B185EBCA87"),tr=_("0xC2B2AE3D27D4EB4F"),ru=_("0x165667B19E3779F9"),ps=_("0x85EBCA77C2B2AE63"),Ih=_("0x27D4EB2F165667C5"),Ch=_("0x165667919E3779F9"),Oh=_("0x9FB21C651E98DF25");function Rh(t){let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)e[r/2]=parseInt(t.substring(r,r+2),16);return e}var pt=Rh("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),jr=(_(1)<<_(128))-_(1),Z=(_(1)<<_(64))-_(1),Jn=(_(1)<<_(32))-_(1),At=64,nu=At/8,Nh=8,Vn=4;function te(t,e=0){return new Uint8Array(t.buffer,t.byteOffset+e,t.length-e)}function ie(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getBigUint64(0,!0)}function Lr(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getUint32(0,!0)}function us(t,e=0){return t[e]}var $h=t=>(t&_(255))<<_(56)|(t&_(65280))<<_(40)|(t&_(16711680))<<_(24)|(t&_(4278190080))<<_(8)|(t&_(0xff00000000))>>_(8)|(t&_(0xff0000000000))>>_(24)|(t&_(0xff000000000000))>>_(40)|(t&_(0xff00000000000000))>>_(56),Ph=t=>(t=(t&_(65535))<<_(16)|(t&_(4294901760))>>_(16),t=(t&_(16711935))<<_(8)|(t&_(4278255360))>>_(8),t),Mh=(t,e)=>(t&Jn)*(e&Jn)&Z,Dr=t=>{if(!t)throw new Error("Assert failed")};function Lh(t,e){return(t<<e|t>>_(32)-e)&Jn}function iu(t,e,r){for(let n=0;n<nu;n++){let i=ie(e,n*8),a=i^ie(r,n*8);t[n^1]+=i,t[n]+=Mh(a,a>>_(32))}return t}function Yl(t,e,r,n){for(let i=0;i<n;i++)iu(t,te(e,i*At),te(r,i*8));return t}function jh(t,e){for(let r=0;r<nu;r++){let n=ie(e,r*8),i=t[r];i=ds(i,_(47)),i^=n,i*=eu,t[r]=i&Z}return t}function Zn(t,e){return au(t[0]^ie(e,0),t[1]^ie(e,Nh))}function Xl(t,e,r){let n=r;return n+=Zn(t.slice(0),te(e,0*Vn)),n+=Zn(t.slice(2),te(e,4*Vn)),n+=Zn(t.slice(4),te(e,8*Vn)),n+=Zn(t.slice(6),te(e,12*Vn)),ht(n&Z)}function Dh(t,e,r,n,i){let a=Math.floor((r.byteLength-At)/8),s=At*a,o=Math.floor((e.byteLength-1)/s);for(let c=0;c<o;c++)t=Yl(t,te(e,c*s),r,a),t=i(t,te(r,r.byteLength-At));{let c=Math.floor((e.byteLength-1-s*o)/At);t=Yl(t,te(e,o*s),r,c),t=n(t,te(e,e.byteLength-At),te(r,r.byteLength-At-7))}return t}function Uh(t,e,r){let n=new BigUint64Array([kh,Pt,tr,ru,ps,tu,Ih,eu]);Dr(t.length>128),n=Dh(n,t,e,iu,jh),Dr(n.length*8==64);{let i=Xl(n,te(e,11),_(t.byteLength)*Pt&Z);return Xl(n,te(e,e.byteLength-At-11),~(_(t.byteLength)*tr)&Z)<<_(64)|i}}function au(t,e){let r=t*e&jr;return r&Z^r>>_(64)}function Ql(t,e,r){return au((ie(t,0)^ie(e,0)+r)&Z,(ie(t,8)^ie(e,8)-r)&Z)}function qn(t,e,r,n,i){let a=t&Z,s=t>>_(64)&Z;return a+=Ql(e,n,i),a^=ie(r,0)+ie(r,8),a&=Z,s+=Ql(r,te(n,16),i),s^=ie(e,0)+ie(e,8),s&=Z,s<<_(64)|a}function ht(t){return t^=t>>_(37),t*=Ch,t&=Z,t^=t>>_(32),t}function Wn(t){return t^=t>>_(33),t*=tr,t&=Z,t^=t>>_(29),t*=ru,t&=Z,t^=t>>_(32),t}function Bh(t,e,r){let n=t.byteLength;Dr(n>0&&n<=3);let i=_(us(t,n-1))|_(n<<8)|_(us(t,0)<<16)|_(us(t,n>>1)<<24),a=(_(Lr(e,0))^_(Lr(e,4)))+r,s=(i^a)&Z,o=(_(Lr(e,8))^_(Lr(e,12)))-r,c=(Lh(Ph(i),_(13))^o)&Z;return(Wn(c)&Z)<<_(64)|Wn(s)}function ds(t,e){return t^t>>e}function zh(t,e,r){let n=t.byteLength;Dr(n>=4&&n<=8);{let i=Lr(t,0),a=Lr(t,n-4),s=_(i)|_(a)<<_(32),o=(ie(e,16)^ie(e,24))+r&Z,l=(s^o)*(Pt+(_(n)<<_(2)))&jr;return l+=(l&Z)<<_(65),l&=jr,l^=l>>_(67),ds(ds(l&Z,_(35))*Oh&Z,_(28))|ht(l>>_(64))<<_(64)}}function Fh(t,e,r){let n=t.byteLength;Dr(n>=9&&n<=16);{let i=(ie(e,32)^ie(e,40))+r&Z,a=(ie(e,48)^ie(e,56))-r&Z,s=ie(t),o=ie(t,n-8),c=(s^o^i)*Pt,l=(c&Z)+(_(n-1)<<_(54));c=c&(jr^Z)|l,o^=a,c+=o+(o&Jn)*(tu-_(1))<<_(64),c&=jr,c^=$h(c>>_(64));let u=(c&Z)*tr;return u+=(c>>_(64))*tr<<_(64),u&=jr,ht(u&Z)|ht(u>>_(64))<<_(64)}}function Hh(t,e){let r=t.byteLength;return Dr(r<=16),r>8?Fh(t,pt,e):r>=4?zh(t,pt,e):r>0?Bh(t,pt,e):Wn(e^ie(pt,64)^ie(pt,72))|Wn(e^ie(pt,80)^ie(pt,88))<<_(64)}function fs(t){return~t+_(1)&Z}function Gh(t,e,r){let n=_(t.byteLength)*Pt&Z,i=_(t.byteLength-1)/_(32);for(;i>=0;){let o=Number(i);n=qn(n,te(t,16*o),te(t,t.byteLength-16*(o+1)),te(e,32*o),r),i--}let a=n+(n>>_(64))&Z;a=ht(a);let s=(n&Z)*Pt+(n>>_(64))*ps+(_(t.byteLength)-r&Z)*tr;return s&=Z,s=fs(ht(s)),a|s<<_(64)}function Vh(t,e,r){let n=_(t.byteLength)*Pt&Z;for(let s=32;s<160;s+=32)n=qn(n,te(t,s-32),te(t,s-16),te(e,s-32),r);n=ht(n&Z)|ht(n>>_(64))<<_(64);for(let s=160;s<=t.byteLength;s+=32)n=qn(n,te(t,s-32),te(t,s-16),te(e,3+s-160),r);n=qn(n,te(t,t.byteLength-16),te(t,t.byteLength-32),te(e,103),fs(r));let i=n+(n>>_(64))&Z;i=ht(i);let a=(n&Z)*Pt+(n>>_(64))*ps+(_(t.byteLength)-r&Z)*tr;return a&=Z,a=fs(ht(a)),i|a<<_(64)}function su(t,e=_(0)){let r=t.byteLength;return r<=16?Hh(t,e):r<=128?Gh(t,pt,e):r<=240?Vh(t,pt,e):Uh(t,pt,e)}function ou(t){let e=new Uint8Array(16),r=new DataView(e.buffer),n=t&Z,i=t>>_(64);return r.setBigUint64(0,i,!1),r.setBigUint64(8,n,!1),e}var cu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function G(t,e){if(!cu.test(t)){let r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}function Kn(t){let e=typeof t=="string"?Date.parse(t):t;return Mr({msecs:e,seq:0})}function Zh(t){if(!cu.test(t))return null;let e=t[14];return parseInt(e,16)}function qh(t){let e=t.replace(/-/g,""),r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(e.slice(n*2,n*2+2),16);return r}function Jh(t){let e=Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}var Wh=new TextEncoder;function Kh(t){let e=Wh.encode(t),r=su(e);return ou(r)}function on(t,e){let r=`${t}:${e}`,n=Kh(r),i=new Uint8Array(16);if(Zh(t)===7){let s=qh(t);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),Jh(i)}var rr={join:(...t)=>t.join("/"),dirname:t=>t.split("/").slice(0,-1).join("/")};async function lu(t){}async function Yn(t,e){}async function uu(t){return[]}async function du(t){return{size:0}}function Ur(t){return!1}function Xn(t){return""}function Yh(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}var Qn=class{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,r){if(this.maxSize===0)return;let n=this.cache.get(e);if(!n){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...n,refreshFunc:r}),this._metrics.hits+=1,n.value}set(e,r,n){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){let a=this.cache.keys().next().value;a!==void 0&&this.cache.delete(a)}let i={value:r,createdAt:Date.now(),refreshFunc:n};this.cache.delete(e),this.cache.set(e,i)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){let r={};for(let[a,s]of this.cache.entries())r[a]=s.value;let n=rr.dirname(e);Ur(n)||void 0;let i=`${e}.tmp`;try{JSON.stringify({entries:r},null,2)}catch(a){throw Ur(i)&&void 0,a}}load(e){if(!Ur(e))return 0;let r;try{let a=Xn(e);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(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){let e=[];for(let[r,n]of this.cache.entries())Yh(n,this.ttlSeconds)&&e.push([r,n]);return e}async refreshStaleEntries(){let e=this.getStaleEntries();if(e.length!==0){for(let[r,n]of e)if(n.refreshFunc!==void 0)try{let i=await n.refreshFunc();this.set(r,i,n.refreshFunc),this._metrics.refreshes+=1}catch(i){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${r}:`,i)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}},ei=new Qn;var ti="0.6.3";var mt,Xh=()=>typeof window<"u"&&typeof window.document<"u",Qh=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",em=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),mu=()=>typeof Deno<"u",tm=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!mu(),cn=()=>mt||(typeof Bun<"u"?mt="bun":Xh()?mt="browser":tm()?mt="node":Qh()?mt="webworker":em()?mt="jsdom":mu()?mt="deno":mt="other",mt),hs;function ri(){if(hs===void 0){let t=cn(),e=nm();hs={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:ti,...e}}return hs}function gs(){let t=rm(),e={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_CONFIG_FILE","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[n,i]of Object.entries(t))typeof i=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=i:e[n]=i);return e}function rm(){let t={};try{if(typeof process<"u"&&process.env)for(let[e,r]of Object.entries(process.env))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&r!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof r=="string"?t[e]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):t[e]=r)}catch{}return t}function pe(t){try{return typeof process<"u"?process.env?.[t]:void 0}catch{return}}function ne(t){return pe(`LANGSMITH_${t}`)||pe(`LANGCHAIN_${t}`)}var ms;function nm(){if(ms!==void 0)return ms;let t=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(let r of t){let n=pe(r);n!==void 0&&(e[r]=n)}return ms=e,e}function pu(){return pe("OTEL_ENABLED")==="true"||ne("OTEL_ENABLED")==="true"}var hu=new Set(["langsmith","otel"]);function ni(t){if(t!==void 0)return t;let e=ne("TRACING_MODE");if(e!==void 0&&e!==""){let r=e.toLowerCase();if(!hu.has(r))throw new Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(e)}. Must be one of: ${[...hu].sort().join(", ")}`);return pu()&&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 pu()?"otel":"langsmith"}var ws=class{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&ni()==="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()}},bs=class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new ws})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},vs=class{active(){return{}}with(e,r){return r()}},_s=Symbol.for("ls:otel_trace"),ys=Symbol.for("ls:otel_context"),gu=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),im=new bs,am=new vs,xs=class{getTraceInstance(){return globalThis[_s]??im}getContextInstance(){return globalThis[ys]??am}initializeGlobalInstances(e){globalThis[_s]===void 0&&(globalThis[_s]=e.trace),globalThis[ys]===void 0&&(globalThis[ys]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[gu]=e}getDefaultOTLPTracerComponents(){return globalThis[gu]??void 0}},Es=new xs;function ii(){return Es.getTraceInstance()}function _u(){return Es.getContextInstance()}function yu(){return Es.getDefaultOTLPTracerComponents()}var sm={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function om(t){return sm[t]||t}function cm(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}var ai=class{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,r){for(let n of e)try{if(!n.run)continue;if(n.operation==="post"){let i=this.createSpanForRun(n,n.run,r.get(n.id));i&&!n.run.end_time&&this.spans.set(n.id,i)}else this.updateSpanForRun(n,n.run)}catch(i){console.error(`Error processing operation ${n.id}:`,i)}}createSpanForRun(e,r,n){let i=n&&ii().getSpan(n);if(i)try{return this.finishSpanSetup(i,r,e)}catch(a){console.error(`Failed to create span for run ${e.id}:`,a);return}}finishSpanSetup(e,r,n){return this.setSpanAttributes(e,r,n),r.error?(e.setStatus({code:2}),e.recordException(new Error(r.error))):e.setStatus({code:1}),r.end_time&&e.end(new Date(r.end_time)),e}updateSpanForRun(e,r){try{let n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,r,e),r.error?(n.setStatus({code:2}),n.recordException(new Error(r.error))):n.setStatus({code:1});let i=r.end_time;i&&(n.end(new Date(i)),this.spans.delete(e.id))}catch(n){console.error(`Failed to update span for run ${e.id}:`,n)}}extractModelName(e){if(e.extra?.metadata){let r=e.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){let n=r.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(e,r,n){if("run_type"in r&&r.run_type){e.setAttribute(Fl,r.run_type);let o=om(r.run_type||"chain");e.setAttribute(wl,o)}"name"in r&&r.name&&e.setAttribute(Hl,r.name),"session_id"in r&&r.session_id&&e.setAttribute(Bl,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(zl,r.session_name),this.setGenAiSystem(e,r);let i=this.extractModelName(r);i&&e.setAttribute(is,i),r.extra?.metadata?.usage_metadata&&typeof r.extra.metadata.usage_metadata=="object"&&e.setAttribute(ls,JSON.stringify(r.extra.metadata.usage_metadata)),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(as,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(ss,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(os,r.total_tokens),this.setInvocationParameters(e,r);let a=r.extra?.metadata||{};for(let[o,c]of Object.entries(a))c!=null&&e.setAttribute(`${Gl}.${o}`,cm(c)?String(c):JSON.stringify(c));let s=r.tags;if(s&&Array.isArray(s)?e.setAttribute(cs,s.join(", ")):s&&e.setAttribute(cs,String(s)),"serialized"in r&&typeof r.serialized=="object"){let o=r.serialized;o.name&&e.setAttribute(Nl,String(o.name)),o.signature&&e.setAttribute($l,String(o.signature)),o.doc&&e.setAttribute(Pl,String(o.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,r){let n="langchain",i=this.extractModelName(r);if(i){let a=i.toLowerCase();a.includes("anthropic")||a.startsWith("claude")?n="anthropic":a.includes("bedrock")?n="aws.bedrock":a.includes("azure")&&a.includes("openai")?n="az.ai.openai":a.includes("azure")&&a.includes("inference")?n="az.ai.inference":a.includes("cohere")?n="cohere":a.includes("deepseek")?n="deepseek":a.includes("gemini")?n="gemini":a.includes("groq")?n="groq":a.includes("watson")||a.includes("ibm")?n="ibm.watsonx.ai":a.includes("mistral")?n="mistral_ai":a.includes("gpt")||a.includes("openai")?n="openai":a.includes("perplexity")||a.includes("sonar")?n="perplexity":a.includes("vertex")?n="vertex_ai":(a.includes("xai")||a.includes("grok"))&&(n="xai")}e.setAttribute(bl,n)}setInvocationParameters(e,r){if(!r.extra?.metadata?.invocation_params)return;let n=r.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(xl,n.max_tokens),n.temperature!==void 0&&e.setAttribute(El,n.temperature),n.top_p!==void 0&&e.setAttribute(Sl,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(Tl,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(Al,n.presence_penalty)}setIOAttributes(e,r){if(r.run.inputs)try{let n=r.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(is,n.model),n.stream!==void 0&&e.setAttribute(Vl,n.stream),n.extra_headers&&e.setAttribute(Zl,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(Ol,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(Rl,JSON.stringify(n.extra_body))),e.setAttribute(Il,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${r.id}`,n)}if(r.run.outputs)try{let n=r.run.outputs,i=this.getUnifiedRunTokens(n);if(i&&(e.setAttribute(as,i[0]),e.setAttribute(ss,i[1]),e.setAttribute(os,i[0]+i[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(vl,String(n.model)),n.id&&e.setAttribute(Ml,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&&e.setAttribute(kl,a.join(", "))}if(n.service_tier&&e.setAttribute(Ll,n.service_tier),n.system_fingerprint&&e.setAttribute(jl,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let a=n.usage_metadata;e.setAttribute(ls,JSON.stringify(a)),a.input_token_details&&e.setAttribute(Dl,JSON.stringify(a.input_token_details)),a.output_token_details&&e.setAttribute(Ul,JSON.stringify(a.output_token_details))}}e.setAttribute(Cl,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${r.id}`,n)}}getUnifiedRunTokens(e){if(!e)return null;let r=this.extractUnifiedRunTokens(e.usage_metadata);if(r)return r;let n=Object.keys(e);for(let s of n){let o=e[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=e.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(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}};var lm=Object.prototype.toString,um=t=>lm.call(t)==="[object Error]",dm=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 Ss(t){if(!(t&&um(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;let{message:r,stack:n}=t;return r==="Load failed"?n===void 0||"__sentry_captured__"in t:r.startsWith("error sending request for url")?!0:dm.has(r)}function fm(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function si(t,e,{min:r=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<r)throw new TypeError(`Expected \`${t}\` to be \u2265 ${r}.`)}}var Ts=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 pm(t,e){let r=Math.max(1,t+1),n=e.randomize?Math.random()+1:1,i=Math.round(n*e.minTimeout*e.factor**(r-1));return i=Math.min(i,e.maxTimeout),i}function wu(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function hm({error:t,attemptNumber:e,retriesConsumed:r,startTime:n,options:i}){let a=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(a instanceof Ts)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:e,retriesLeft:s,retriesConsumed:r});if(await i.onFailedAttempt(c),wu(n,o)<=0)throw a;let l=await i.shouldConsumeRetry(c),u=wu(n,o);if(u<=0||s<=0)throw a;if(a instanceof TypeError&&!Ss(a)){if(l)throw a;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw a;if(!l)return i.signal?.throwIfAborted(),!1;let d=pm(r,i),f=Math.min(d,u);return f>0&&await new Promise((p,h)=>{let g=()=>{clearTimeout(b),i.signal?.removeEventListener("abort",g),h(i.signal.reason)},b=setTimeout(()=>{i.signal?.removeEventListener("abort",g),p()},f);i.unref&&b.unref?.(),i.signal?.addEventListener("abort",g,{once:!0})}),i.signal?.throwIfAborted(),!0}async function As(t,e={}){if(e={...e},fm(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,si("factor",e.factor,{min:0,allowInfinity:!1}),si("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),si("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),si("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let r=0,n=0,i=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){r++;try{e.signal?.throwIfAborted();let a=await t(r);return e.signal?.throwIfAborted(),a}catch(a){await hm({error:a,attemptNumber:r,retriesConsumed:n,startTime:i,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var fi=Wt(di(),1),Cu="default"in fi.default?fi.default.default:fi.default;var Em=[408,425,429,500,502,503,504],un=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new Cu({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...r){return this.callWithOptions({},e,...r)}callWithOptions(e,r,...n){let i=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&i>0&&this.queueSizeBytes+i>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${i} bytes.`));i>0&&(this.queueSizeBytes+=i);let a=this.onFailedResponseHook,s=this.queue.add(()=>As(()=>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 l="response"in o?o.response:void 0;if(a&&await a(l))return;let u=l?.status??("status"in o?o.status:void 0);if(u!=null&&(typeof u=="number"||typeof u=="string")&&!Em.includes(+u))throw o},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return i>0&&(s=s.finally(()=>{this.queueSizeBytes-=i})),e.signal?Promise.race([s,new Promise((o,c)=>{e.signal?.addEventListener("abort",()=>{c(new Error("AbortError"))})})]):s}};function $s(t){return typeof t?._getType=="function"}function Ps(t){let e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}function hi(t){return`Invalid prompt identifier format: "${t}". 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 Ms=class extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}},Ls=class extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}};function mi(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}function Ou(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithConflictError"}async function C(t,e,r){let n;if(t.ok){r&&(n=await t.text());return}if(t.status===403)try{(await t.json())?.error==="org_scoped_key_requires_workspace"&&(n="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{let o=new Error(`${t.status} ${t.statusText}`);throw o.status=t?.status,o}if(n===void 0)try{n=await t.text()}catch{n=""}let i=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${n}`;if(t.status===404)throw new Ls(i);if(t.status===409)throw new Ms(i);let a=new Error(i);throw a.status=t.status,a}var Ru="ERR_CONFLICTING_ENDPOINTS",pi=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:Ru}),this.name="ConflictingEndpointsError"}};function Nu(t){return typeof t=="object"&&t!==null&&t.code===Ru}function Ee(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(hi(t));let[e,r]=t.split(":"),n=r||"latest";if(e.includes("/")){let[i,a]=e.split("/",2);if(!i||!a)throw new Error(hi(t));return[i,a,n]}else{if(!e)throw new Error(hi(t));return["-",e,n]}}var gi="https://api.smith.langchain.com",Sm="langsmith-cli",Tm=6e4,Am=1e4;function km(){let t=cn();return t==="browser"||t==="webworker"}function Im(){let t=pe("LANGSMITH_CONFIG_FILE");if(t)return t;let e=pe("HOME")??pe("USERPROFILE");if(e)return rr.join(e,".langsmith","config.json")}function Cm(t){let e=pe("LANGSMITH_PROFILE");if(e)return e;if(t.current_profile)return t.current_profile;if(t.profiles?.default)return"default"}function Om(){if(km())return;let t=Im();if(!(!t||!Ur(t)))try{let e=JSON.parse(Xn(t)),r=Cm(e),n=r?e.profiles?.[r]:void 0;return!r||!n?void 0:{configPath:t,config:e,profileName:r,profile:n}}catch{return}}function Ge(t){return t!=null&&t.trim()!==""}function Lt(t){return t?.trim().replace(/^["']|["']$/g,"")}function Rm(t){let e=t.oauth;if(!e?.refresh_token)return!1;if(!e.access_token)return!0;if(!e.expires_at)return!1;let r=Date.parse(e.expires_at);return Number.isNaN(r)?!1:r<=Date.now()+Tm}function Nm(t){let e=t;for(;e.endsWith("/");)e=e.slice(0,-1);let r="/api/v1";return e.endsWith(r)?e.slice(0,-r.length):e}function $m(t,e){t.oauth??={},e.access_token&&(t.oauth.access_token=e.access_token),e.refresh_token&&(t.oauth.refresh_token=e.refresh_token),typeof e.expires_in=="number"&&e.expires_in>0&&(t.oauth.expires_at=new Date(Date.now()+e.expires_in*1e3).toISOString())}function $u(t){return t.reason??new Error("The operation was aborted.")}async function Pm(t,e){if(!e)return t;if(e.aborted)throw $u(e);let r,n=new Promise((i,a)=>{let s=()=>{a($u(e))};e.addEventListener("abort",s,{once:!0}),r=()=>{e.removeEventListener("abort",s)}});try{return await Promise.race([t,n])}finally{r?.()}}function Pu(){let t=Om(),e=t?.profile;if(!t||!e)return{};let r=Lt(e.api_key),n=Lt(e.oauth?.access_token),i=Lt(e.oauth?.refresh_token);return{apiUrl:e.api_url,apiKey:r,workspaceId:e.workspace_id,oauthAccessToken:n,oauthRefreshToken:i,profileAuth:r||n||i?new js(t):void 0}}var js=class{constructor(e){Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"refreshPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"managedAuthorizationValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.rememberProfileAuthHeader(this.currentAuthHeader())}currentAuthHeader(){let e=Mm(this.state.profile);return this.rememberProfileAuthHeader(e),e}async getAuthHeader(e,r){Rm(this.state.profile)&&(this.refreshPromise||(this.refreshPromise=this.refreshOAuthToken(e).finally(()=>{this.refreshPromise=void 0})),await Pm(this.refreshPromise,r));let n=Mu(this.state.profile);return this.rememberProfileAuthHeader(n),n}isProfileAuthorizationHeader(e){return e===this.managedAuthorizationValue}async refreshOAuthToken(e){let r=this.state.profile.oauth?.refresh_token;if(!r)return;let n=Lt(this.state.profile.api_url)??gi;try{let i=new URLSearchParams({grant_type:"refresh_token",client_id:Sm,refresh_token:r}),a=await e(`${Nm(n)}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString(),signal:AbortSignal.timeout(Am)});if(!a.ok)return;let s=await a.json();if(!s.access_token)return;$m(this.state.profile,s),this.state.config.profiles??={},this.state.config.profiles[this.state.profileName]=this.state.profile,await Yn(this.state.configPath,`${JSON.stringify(this.state.config,null,2)}
|
|
23
|
+
`)}catch{return}}rememberProfileAuthHeader(e){this.managedAuthorizationValue=e?.name==="Authorization"?e.value:void 0}};function Mm(t){let e=Lt(t.oauth?.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};if(!Lt(t.oauth?.refresh_token))return Mu(t)}function Mu(t){let e=Lt(t.oauth?.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};let r=Lt(t.api_key);if(r)return{name:"x-api-key",value:r}}var Lu="[...]",Lm={result:"[Circular]"},yi=[],Br=[],jm=new TextEncoder;function Dm(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function _i(t){return jm.encode(t)}function ju(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}function Um(t){return function(e,r){if(t){let n=t.call(this,e,r);if(n!==void 0)return n}return ju(r)}}function Du(t){try{let i=function(u){let d=n(u);return d>r&&(r=d),d+2},a=function(u){return u===0?2:2+u*4},s=function(u){return u===void 0||typeof u=="function"||typeof u=="symbol"},o=function(u){return u===void 0||typeof u=="function"||typeof u=="symbol"?4:c(u)},c=function(u){if(u===null)return 4;if(u===void 0)return 0;let d=typeof u;if(d==="boolean")return 5;if(d==="number")return Number.isFinite(u)?u.toString().length:4;if(d==="bigint")return u.toString().length+2;if(d==="string")return i(u);if(d==="function"||d==="symbol")return 0;let f=u;if(f instanceof Date)return 26;if(f instanceof RegExp)return n(f.toString())+2;if(f instanceof Error){let h=f.name??"",g=f.message??"";return 22+n(h)+n(g)}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(e.has(f))return 24;if(typeof f.toJSON=="function"){let h;try{h=f.toJSON("")}catch{return 16}e.add(f);let g=c(h);return e.delete(f),g}e.add(f);let p;if(Array.isArray(f)){p=2;let h=f.length;for(let g=0;g<h;g++)p+=o(f[g]),g<h-1&&(p+=1)}else if(f instanceof Map){p=2;let h=0;for(let[g,b]of f){if(s(b))continue;h>0&&(p+=1);let E=typeof g=="string"?g:String(g);p+=n(E)+3,p+=c(b),h++}}else if(f instanceof Set){p=2;let h=0;for(let g of f)h>0&&(p+=1),p+=o(g),h++}else{p=2;let h=0,g=Object.keys(f);for(let b=0;b<g.length;b++){let E=g[b],v=f[E];s(v)||(h>0&&(p+=1),p+=n(E)+3,p+=c(v),h++)}}return e.delete(f),p},e=new Set,r=0,n=typeof Buffer<"u"&&typeof Buffer.byteLength=="function"?u=>Buffer.byteLength(u,"utf8"):u=>u.length;return{size:c(t),maxStringLen:r}}catch{return{size:Se(t).length,maxStringLen:0}}}function Se(t,e,r,n,i){try{let a=JSON.stringify(t,Um(r),n);return _i(a)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
|
|
24
|
+
Context: ${e}`:""}`),_i("[Unserializable]");ne("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
|
|
25
|
+
Context: ${e}`:""}`),typeof i>"u"&&(i=Dm()),Us(t,"",0,[],void 0,0,i);let s;try{Br.length===0?s=JSON.stringify(t,r,n):s=JSON.stringify(t,Bm(r),n)}catch{return _i("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;yi.length!==0;){let o=yi.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return _i(s)}}function Ds(t,e,r,n){var i=Object.getOwnPropertyDescriptor(n,r);i.get!==void 0?i.configurable?(Object.defineProperty(n,r,{value:t}),yi.push([n,r,e,i])):Br.push([e,r,t]):(n[r]=t,yi.push([n,r,e]))}function Us(t,e,r,n,i,a,s){a+=1;var o;if(typeof t=="object"&&t!==null){for(o=0;o<n.length;o++)if(n[o]===t){Ds(Lm,t,e,i);return}if(typeof s.depthLimit<"u"&&a>s.depthLimit){Ds(Lu,t,e,i);return}if(typeof s.edgesLimit<"u"&&r+1>s.edgesLimit){Ds(Lu,t,e,i);return}if(n.push(t),Array.isArray(t))for(o=0;o<t.length;o++)Us(t[o],o,o,n,t,a,s);else{t=ju(t);var c=Object.keys(t);for(o=0;o<c.length;o++){var l=c[o];Us(t[l],l,o,n,t,a,s)}}n.pop()}}function Bm(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(Br.length>0)for(var n=0;n<Br.length;n++){var i=Br[n];if(i[1]===e&&i[0]===r){r=i[2],Br.splice(n,1);break}}return t.call(this,e,r)}}var Fm=`
|
|
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 e=new null(Fm,{eval:!0});return e.on("message",r=>{let n=this.pending.get(r.id);n&&(this.pending.delete(r.id),r.error?n.reject(new Error(r.error)):r.bytes&&typeof r.length=="number"?n.resolve(new Uint8Array(r.bytes,0,r.length)):n.reject(new Error("worker returned malformed message")))}),e.on("error",r=>{for(let[,n]of this.pending)n.reject(r);this.pending.clear(),this.disabled=!0,this.worker=null}),e.on("exit",r=>{for(let[,n]of this.pending)n.reject(new Error(`worker exited with code ${r}`));this.pending.clear(),this.worker=null}),e.unref(),this.worker=e,!0}catch{return this.disabled=!0,!1}}async serialize(e){if(!await this.ensureStarted())return null;let n=this.nextId++;return new Promise((i,a)=>{this.pending.set(n,{resolve:i,reject:a});try{this.worker.postMessage({id:n,op:"serialize",payload:e})}catch(s){this.pending.delete(n),a(s)}})}async terminate(){this.worker&&(await this.worker.terminate(),this.worker=null);for(let[,e]of this.pending)e.reject(new Error("worker terminated"));this.pending.clear()}},Bs=null;function Bu(){return Bs===null&&(Bs=new zs),Bs}var Hm=64*1024,Gm=2048;function zu(t,e=Hm,r=Gm){if(t===null||typeof t!="object")return typeof t=="string"&&t.length>=e;let n=[t],i=new Set,a=0;for(;n.length>0;){if(a++>=r)return!1;let s=n.pop();if(s==null)continue;let o=typeof s;if(o==="string"){if(s.length>=e)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 u=c.length-1;u>=0;u--)n.push(c[u]);continue}if(c instanceof Map){for(let[,u]of c)n.push(u);continue}if(c instanceof Set){for(let u of c)n.push(u);continue}let l=Object.keys(c);for(let u=l.length-1;u>=0;u--)n.push(c[l[u]])}return!1}function Vm(t,e){let[r]=Ee(t);if(r!=="-"&&!e)throw new Error("Pulling a public prompt by owner/name is disabled by default because prompts may contain untrusted serialized LangChain objects. If you trust this prompt, set `dangerouslyPullPublicPrompt: true` to acknowledge the risk.")}function Fu(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}function dn(t){return{...t,start_time:Fu(t.start_time),end_time:Fu(t.end_time)}}function Hu(t,e,r){if(r)return t;let n=ri(),i=e??gs(),a=t.extra??{},s=a.metadata;return t.extra={...a,runtime:{...n,...a?.runtime},metadata:{...i,...i.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??i.revision_id}:{},...s}},t}var Zm=t=>{let e=t?.toString()??ne("TRACING_SAMPLING_RATE");if(e===void 0)return;let r=parseFloat(e);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},qm=t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};async function Jm(t){let e=[];for await(let r of t)e.push(r);return e}function wi(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}var Wm=async t=>{if(t?.status===429){let e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1};function Gu(t){return typeof t=="number"?Number(t.toFixed(4)):t}var Km=24*1024*1024,Zu=1024*1024*1024,Ym=1e4,Xm=100,Fs=class{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??Zu}peek(){return this.items[0]}push(e){let r,n=new Promise(a=>{r=a}),i=Du(e.item).size;return this.sizeBytes+i>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${i} bytes.`),r(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:r,itemPromise:n,size:i}),this.sizeBytes+=i,n)}pop({upToSizeBytes:e,upToSize:r}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let n=[],i=0;for(;i+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){let a=this.items.shift();a&&(n.push(a),i+=a.size,this.sizeBytes-=a.size)}if(n.length===0&&this.items.length>0){let a=this.items.shift();n.push(a),i+=a.size,this.sizeBytes-=a.size}return[n.map(a=>({action:a.action,item:a.payload,otelContext:a.otelContext,apiKey:a.apiKey,apiUrl:a.apiUrl,size:a.size})),()=>n.forEach(a=>a.itemPromiseResolve())]}},Mt=class t{get tracingMode(){return this._tracingMode}get _fetch(){let e=this.fetchImplementation||Wl(this.debug);return(async(r,n)=>{let i,a=this.getProfileManagedAuthorizationHeader(n);return this.apiKey!==void 0?i={name:"x-api-key",value:`${this.apiKey}`}:this.hasExplicitAuthHeader(n,a)||(i=await this.profileAuth?.getAuthHeader(e,n?.signal)),e(r,this.applyCurrentAuthHeaders(n,i,a))})}getProfileManagedAuthorizationHeader(e){if(!e?.headers||!this.profileAuth)return;let r=new Headers(e.headers).get("Authorization");if(Ge(r))return this.profileAuth.isProfileAuthorizationHeader(r??"")?r??void 0:void 0}isProfileManagedAuthorizationHeader(e,r){return e===r||this.profileAuth?.isProfileAuthorizationHeader(e)===!0}hasExplicitAuthHeader(e,r){if(!e?.headers)return!1;let n=new Headers(e.headers);if(Ge(n.get("x-api-key")))return!0;let i=n.get("Authorization");return Ge(i)?!this.isProfileManagedAuthorizationHeader(i??"",r):!1}applyCurrentAuthHeaders(e,r,n){if(!r)return e;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(Ge(d.get("x-api-key")))return d;let p=d.get("Authorization");return Ge(p)&&!this.isProfileManagedAuthorizationHeader(p??"",n)||d.set("Authorization",r.value),d}let f=d.get("Authorization");return Ge(f)&&!this.isProfileManagedAuthorizationHeader(f??"",n)||(Ge(f)&&d.delete("Authorization"),d.has("x-api-key")||d.set("x-api-key",r.value)),d};if(!e)return{headers:{[r.name]:r.value}};if(e.headers instanceof Headers)return{...e,headers:i(new Headers(e.headers))};if(Array.isArray(e.headers))return{...e,headers:i(new Headers(e.headers))};let a={...e.headers??{}},s=d=>Object.keys(a).find(f=>f.toLowerCase()===d),o=d=>{let f=s(d);return f?a[f]:void 0},c=Ge(o("x-api-key")),l=o("authorization"),u=Ge(l)&&!this.isProfileManagedAuthorizationHeader(l??"",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),{...e,headers:a}}if(r.name==="Authorization"){if(!c&&!u){let d=s("authorization");d&&d!=="Authorization"&&delete a[d],a.Authorization=r.value}return{...e,headers:a}}if(!u){let d=s("authorization");d&&delete a[d],c||(a["x-api-key"]=r.value)}return{...e,headers:a}}_trackDrain(e){this._pendingDrains.add(e),e.finally(()=>{this._pendingDrains.delete(e)})}async _serializeBody(e,r){if(this.manualFlushMode)return Se(e,r);if(!zu(e))return Se(e,r);if(this._serializeWorker===void 0&&(this._serializeWorker=Bu()),this._serializeWorker===null)return Se(e,r);try{let n=await this._serializeWorker.serialize(e);return n===null?(this._serializeWorker=null,Se(e,r)):n}catch{return Se(e,r)}}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"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=t.getDefaultClientConfig();this.tracingSampleRate=Zm(e.tracingSamplingRate),this.apiUrl=wi(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1));let n=wi(e.apiKey??r.apiKey);if(this.apiKey=Ge(n)?n:void 0,this.profileAuth=this.apiKey!==void 0?void 0:r.profileAuth,this.webUrl=wi(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=wi(e.workspaceId??r.workspaceId),this.timeout_ms=e.timeout_ms??9e4,this.caller=new un({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.failedTracesDir=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=e.maxIngestMemoryBytes??Zu;this.batchIngestCaller=new un({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:a,...e.callerOptions??{},onFailedResponseHook:Wm,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??r.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??r.hideOutputs,this.hideMetadata=e.hideMetadata??r.hideMetadata,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new Fs(a),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,this._tracingMode=ni(e.tracingMode),this._tracingMode==="otel"&&(this.langSmithToOTELTranslator=new ai),this.cachedLSEnvVarsForMetadata=gs(),e.cache!==void 0&&e.disablePromptCache&&er("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),e.cache!==void 0?(er("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."),e.cache===!1?this._promptCache=void 0:e.cache===!0?this._promptCache=ei:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=ei),this._customHeaders=e.headers??{}}static getDefaultClientConfig(){let e=Pu(),r=ne("API_KEY"),n=ne("ENDPOINT"),i=ne("WORKSPACE_ID"),a=Ge(r),s=n??e.apiUrl??gi,o=i??e.workspaceId,c=ne("HIDE_INPUTS")==="true",l=ne("HIDE_OUTPUTS")==="true",u=ne("HIDE_METADATA")==="true";return{apiUrl:s,apiKey:r,webUrl:void 0,hideInputs:c,hideOutputs:l,hideMetadata:u,workspaceId:o,oauthAccessToken:a?void 0:e.oauthAccessToken,oauthRefreshToken:a?void 0:e.oauthRefreshToken,profileAuth:a?void 0:e.profileAuth}}getHostUrl(){return this.webUrl?this.webUrl:qm(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 e={"User-Agent":`langsmith-js/${ti}`,...this._customHeaders};if(this.apiKey!==void 0)e["x-api-key"]=`${this.apiKey}`;else{let r=this.profileAuth?.currentAuthHeader();r&&(e[r.name]=r.value)}return this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}get headers(){return this._customHeaders}set headers(e){this._customHeaders=e??{}}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async processMetadata(e){return this.hideMetadata===!1?e:this.hideMetadata===!0?{}:typeof this.hideMetadata=="function"?this.hideMetadata(e):e}_filterNewTokenEvents(e){return!e||e.length===0?e:e.map(r=>{if(r.name==="new_token"){let{kwargs:n,...i}=r;return i}return r})}async prepareRunCreateOrUpdateInputs(e){let r={...e};return r.inputs!==void 0&&(r.inputs=await this.processInputs(r.inputs)),r.outputs!==void 0&&(r.outputs=await this.processOutputs(r.outputs)),r.extra!=null&&"metadata"in r.extra&&(r.extra={...r.extra,metadata:await this.processMetadata(r.extra.metadata)}),r.events!==void 0&&(r.events=this._filterNewTokenEvents(r.events)),r}async _getResponse(e,r){let n=r?.toString()??"",i=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{let s=await this._fetch(i,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(s,`fetch ${e}`),s})}async _get(e,r){return(await this._getResponse(e,r)).json()}async*_getPaginated(e,r=new URLSearchParams,n){let i=Number(r.get("offset"))||0,a=Number(r.get("limit"))||100;for(;;){r.set("offset",String(i)),r.set("limit",String(a));let s=`${this.apiUrl}${e}?${r}`,o=await this.caller.call(async()=>{let l=await this._fetch(s,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(l,`fetch ${e}`),l}),c=n?n(await o.json()):await o.json();if(c.length===0||(yield c,c.length<a))break;i+=c.length}}async*_getCursorPaginatedList(e,r=null,n="POST",i="runs"){let a=r?{...r}:{};for(;;){let s=JSON.stringify(a),c=await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await C(u,`fetch ${e}`),u})).json();if(!c||!c[i])break;yield c[i];let l=c.cursors;if(!l||!l.next)break;a.cursor=l.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,r=!1){if(this.tracingSampleRate===void 0)return e;if(r){let n=[];for(let i of e)this.filteredPostUuids.has(i.trace_id)?i.id===i.trace_id&&this.filteredPostUuids.delete(i.trace_id):n.push(i);return n}else{let n=[];for(let i of e){let a=i.trace_id??i.id;this.filteredPostUuids.has(a)||(i.id===a?this._shouldSample()?n.push(i):this.filteredPostUuids.add(a):n.push(i))}return n}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??Km}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??Xm}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[i,a]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:r});if(!i.length){a();break}let s=i.reduce((l,u)=>{let d=u.apiUrl??this.apiUrl,f=u.apiKey??this.apiKey,h=u.apiKey===this.apiKey&&u.apiUrl===this.apiUrl?"default":`${d}|${f}`;return l[h]||(l[h]=[]),l[h].push(u),l},{}),o=[];for(let[l,u]of Object.entries(s)){let d=this._processBatch(u,{apiUrl:l==="default"?void 0:l.split("|")[0],apiKey:l==="default"?void 0:l.split("|")[1]});o.push(d)}let c=Promise.all(o).finally(a);n.push(c)}return Promise.all(n)}static async _writeTraceToFallbackDir(e,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()}_${Qt().slice(0,8)}.json`,l=rr.join(e,c);if(t._fallbackDirsCreated.has(e)||(await lu(e),t._fallbackDirsCreated.add(e)),a!==void 0&&a>0)try{let d=(await uu(e)).filter(p=>p.startsWith("trace_")&&p.endsWith(".json")),f=0;for(let p of d){let{size:h}=await du(rr.join(e,p));f+=h}if(f>=a){console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${f} bytes >= ${a} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await Yn(l,o),console.warn(`LangSmith trace upload failed; data saved to ${l} for later replay.`)}catch(s){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,s)}}async _processBatch(e,r){if(!e.length)return;let n=e.reduce((i,a)=>i+(a.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let i={runCreates:e.filter(o=>o.action==="create").map(o=>o.item),runUpdates:e.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(mi(c))this._multipartDisabled=!0,await this.batchIngestRuns(i,{...r,sizeBytes:n});else throw c}}else await this.batchIngestRuns(i,{...r,sizeBytes:n})}}catch(i){console.error("Error exporting batch:",i)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let r=new Map,n=[];for(let i of e)i.item.id&&i.otelContext&&(r.set(i.item.id,i.otelContext),i.action==="create"?n.push({operation:"post",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}):n.push({operation:"patch",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=Hu(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let r=this.autoBatchQueue.push(e);if(this.manualFlushMode)return r;let n=await this._getBatchSizeLimitBytes(),i=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>i)&&this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:i})),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:i}))},this.autoBatchAggregationDelayMs)),r}async _getServerInfo(){let r=await(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(Ym),...this.fetchOptions});return await C(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(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r})}_cloneCurrentOTELContext(){let e=ii(),r=_u();if(this.langSmithToOTELTranslator!==void 0){let n=e.getActiveSpan();if(n)return e.setSpan(r.active(),n)}}async createRun(e,r){if(!this._filterForSampling([e]).length)return;let n={...this._mergedHeaders,"Content-Type":"application/json"},i=e.project_name;delete e.project_name;let a=await this.prepareRunCreateOrUpdateInputs({session_name:i,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){let c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:a,otelContext:c,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}let s=Hu(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 C(c,"create run",!0),c})}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let i=await Promise.all(e?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]),a=await Promise.all(r?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]);if(i.length>0&&a.length>0){let c=i.reduce((u,d)=>(d.id&&(u[d.id]=d),u),{}),l=[];for(let u of a)u.id!==void 0&&c[u.id]?c[u.id]={...c[u.id],...u}:l.push(u);i=Object.values(c),a=l}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 l=c,u=s[l].reverse(),d=u.pop();for(;d!==void 0;)o[l].push(d),d=u.pop()}if(o.post.length>0||o.patch.length>0){let c=o.post.map(l=>l.id).concat(o.patch.map(l=>l.id)).join(",");await this._postBatchIngestRuns(await this._serializeBody(o,`Ingesting runs with ids: ${c}`),n)}}async _postBatchIngestRuns(e,r){let n={...this._mergedHeaders,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let i=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await C(i,"batch create run",!0),i})}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let i={},a=[];for(let d of e??[]){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 l=[],u=[];for(let[d,f]of[["post",a],["patch",s]])for(let p of f){let{inputs:h,outputs:g,events:b,extra:E,error:v,serialized:k,attachments:O,...j}=p,X={inputs:h,outputs:g,events:b,extra:E,error:v,serialized:k},K=await this._serializeBody(j,`Serializing for multipart ingestion of run with id: ${j.id}`);u.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}`);u.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}u.push({name:`attachment.${j.id}.${ee}`,payload:new Blob([lt],{type:`${Ae}; length=${lt.byteLength}`})})}}}l.push(`trace=${j.trace_id},id=${j.id}`)}await this._sendMultipartRequest(u,l.join("; "),n)}async _createNodeFetchBody(e,r){let n=[];for(let s of e)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(e,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 e){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 l=o.payload.stream().getReader();try{let u;for(;!(u=await l.read()).done;)a.enqueue(u.value)}finally{l.releaseLock()}await s(`\r
|
|
130
|
+
`)}await s(`--${r}--\r
|
|
131
|
+
`),a.close()}})}async _sendMultipartRequest(e,r,n){let i="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=()=>this._createNodeFetchBody(e,i),s=()=>this._createMultipartStream(e,i),o=async c=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let l=await c(),u={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${i}`};n?.apiKey!==void 0&&(u["x-api-key"]=n.apiKey);let d=l;n?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(d=l.pipeThrough(new CompressionStream("gzip")),u["Content-Encoding"]="gzip");let f=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:u,body:d,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(f,"Failed to send multipart request",!0),f});try{let c,l=!1;Jl()&&!this.multipartStreamingDisabled&&cn()!=="bun"?(l=!0,c=await o(s)):c=await o(a),(!this.multipartStreamingDisabled||l)&&c.status===422&&(n?.apiUrl??this.apiUrl)!==gi&&(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(mi(c))throw c;if(console.warn(`${c.message.trim()}
|
|
132
|
+
|
|
133
|
+
Context: ${r}`),this.failedTracesDir){let l=await this._createNodeFetchBody(e,i).catch(()=>null);l&&await t._writeTraceToFallbackDir(this.failedTracesDir,l,{"Content-Type":`multipart/form-data; boundary=${i}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,r,n){G(e),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:e};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: ${e}`);await this.caller.call(async()=>{let o=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await C(o,"update run",!0),o})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){G(e);let n=dn(await this._get(`/runs/${e}`));return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(r!==void 0){let 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(e!==void 0){let i=await this.readRun(e);if(!i.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${i.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){let r=await Jm(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.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(e.dotted_order??"")&&a.id!==e.id&&(a.parent_run_id in n||(n[a.parent_run_id]=[]),n[a.parent_run_id].push(a),i[a.id]=a)}e.child_runs=n[e.id]||[];for(let a in n)a!==e.id&&(i[a].child_runs=n[a]);return e}async*listRuns(e){let{projectId:r,projectName:n,parentRunId:i,traceId:a,referenceExampleId:s,startTime:o,executionOrder:c,isRoot:l,runType:u,error:d,id:f,query:p,filter:h,traceFilter:g,treeFilter:b,limit:E,select:v,order:k}=e,O=[];if(r&&(O=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)));O.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:O.length?O:null,run_type:u,reference_example:s,query:p,filter:h,trace_filter:g,tree_filter:b,execution_order:c,parent_run:i,start_time:o?o.toISOString():null,error:d,id:f,limit:E,trace:a,select:v||j,is_root:l,order:k};X.select.includes("child_run_ids")&&er("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(dn);if(E){if(K>=E)break;if(ee.length+K>E){yield*ee.slice(0,E-K);break}K+=ee.length,yield*ee}else yield*ee}}async*listGroupRuns(e){let{projectId:r,projectName:n,groupBy:i,filter:a,startTime:s,endTime:o,limit:c,offset:l}=e,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(l)||0,p="/runs/group",h=`${this.apiUrl}${p}`;for(;;){let g={...d,offset:f},b=Object.fromEntries(Object.entries(g).filter(([X,K])=>K!==void 0)),E=JSON.stringify(b),k=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:E});return await C(X,`Failed to fetch ${p}`),X})).json(),{groups:O,total:j}=k;if(O.length===0)break;for(let X of O)yield X;if(f+=O.length,f>=j)break}}async*readThread(e){let{threadId:r,projectId:n,projectName:i,isRoot:a=!0,limit:s,filter:o,order:c="asc"}=e;if(!n&&!i)throw new Error("threadId requires projectId or projectName");let l=`eq(thread_id, ${JSON.stringify(r)})`,u=o?`and(${l}, ${o})`:l;yield*this.listRuns({projectId:n??void 0,projectName:i??void 0,isRoot:a,limit:s,filter:u,order:c})}async listThreads(e){let{projectId:r,projectName:n,limit:i,offset:a=0,filter:s,startTime:o,isRoot:c=!0}=e;if(!r&&!n)throw new Error("Either projectId or projectName must be provided");if(r&&n)throw new Error("Provide exactly one of projectId or projectName");let l=r??(await this.readProject({projectName:n})).id,u=o??new Date(Date.now()-1440*60*1e3),f={session:[l],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:u.toISOString()};s!=null&&(f.filter=s);let p=new Map;for await(let E of this._getCursorPaginatedList("/runs/query",f))for(let v of E){let k=dn(v),O=k.thread_id;if(O){let j=p.get(O)??[];j.push(k),p.set(O,j)}}let h=[];for(let[E,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 An=ee.dotted_order??"",en=fe.dotted_order??"";return An.localeCompare(en)});let O=[...v.map(K=>K.start_time).filter(Boolean)].sort(),j=O.length?O[0]:"",X=O.length?O[O.length-1]:"";h.push({thread_id:E,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((E,v)=>{let k=E.max_start_time??"";return(v.max_start_time??"").localeCompare(k)});let g=a>0?h.slice(a):h;return i!==void 0?g.slice(0,i):g}async getRunStats({id:e,trace:r,parentRun:n,runType:i,projectNames:a,projectIds:s,referenceExampleIds:o,startTime:c,endTime:l,error:u,query:d,filter:f,traceFilter:p,treeFilter:h,isRoot:g,dataSourceType:b}){let E=s||[];a&&(E=[...s||[],...await Promise.all(a.map(K=>this.readProject({projectName:K}).then(Q=>Q.id)))]);let k=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:i,session:E,reference_example:o,start_time:c,end_time:l,error:u,query:d,filter:f,trace_filter:p,tree_filter:h,is_root:g,data_source_type:b}).filter(([K,Q])=>Q!==void 0)),O=JSON.stringify(k);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:O});return await C(K,"get run stats"),K})).json()}async shareRun(e,{shareId:r}={}){let n={run_id:e,share_token:r||Qt()};G(e);let i=JSON.stringify(n),s=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await C(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(e){G(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(r,"unshare run",!0),r})}async readRunSharedLink(e){G(e);let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(i,"read run shared link"),i})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:r}={}){let n=new URLSearchParams({share_token:e});if(r!==void 0)for(let s of r)n.append("id",s);return G(e),(await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(s,"list shared runs"),s})).json()).map(dn)}async readDatasetSharedSchema(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id),G(e);let i=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(a,"read dataset shared schema"),a})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async shareDataset(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id);let n={dataset_id:e};G(e);let i=JSON.stringify(n),s=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await C(o,"share dataset"),o})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async unshareDataset(e){G(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(r,"unshare dataset",!0),r})}async readSharedDataset(e){return G(e),await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(i,"read shared dataset"),i})).json()}async listSharedExamples(e,r){let n={};r?.exampleIds&&(n.id=r.exampleIds);let i=new URLSearchParams;Object.entries(n).forEach(([o,c])=>{Array.isArray(c)?c.forEach(l=>i.append(o,l)):i.append(o,c)});let a=await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/public/${e}/examples?${i.toString()}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(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:e,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}`,l=a||{};n&&(l.metadata=n);let u={name:e,extra:l,description:r};s!==null&&(u.reference_dataset_id=s);let d=JSON.stringify(u);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 C(h,"create project"),h})).json()}async updateProject(e,{name:r=null,description:n=null,metadata:i=null,projectExtra:a=null,endTime:s=null}){let o=`${this.apiUrl}/sessions/${e}`,c=a;i&&(c={...c||{},metadata:i});let l=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:l});return await C(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:r}){let n="/sessions",i=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)G(e),n+=`/${e}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");let a=await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${n}?${i}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(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:e,projectName:r,includeStats:n}){let i="/sessions",a=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)G(e),i+=`/${e}`;else if(r!==void 0)a.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&a.append("include_stats",n.toString());let s=await this._get(i,a),o;if(Array.isArray(s)){if(s.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);o=s[0]}else o=s;return o}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:e,projectName:r}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:e,datasetName:r}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:i,referenceDatasetName:a,includeStats:s,datasetVersion:o,referenceFree:c,metadata:l}={}){let u=new URLSearchParams;if(e!==void 0)for(let d of e)u.append("id",d);if(r!==void 0&&u.append("name",r),n!==void 0&&u.append("name_contains",n),i!==void 0)u.append("reference_dataset",i);else if(a!==void 0){let d=await this.readDataset({datasetName:a});u.append("reference_dataset",d.id)}s!==void 0&&u.append("include_stats",s.toString()),o!==void 0&&u.append("dataset_version",o),c!==void 0&&u.append("reference_free",c.toString()),l!==void 0&&u.append("metadata",JSON.stringify(l));for await(let d of this._getPaginated("/sessions",u))yield*d}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:r})).id:n=e,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 C(i,`delete session ${n} (${r})`,!0),i})}async uploadCsv({csvFile:e,fileName:r,inputKeys:n,outputKeys:i,description:a,dataType:s,name:o}){let c=`${this.apiUrl}/datasets/upload`,l=new FormData,u=new Blob([e],{type:"text/csv"});return l.append("file",u,r),n.forEach(p=>{l.append("input_keys",p)}),i.forEach(p=>{l.append("output_keys",p)}),a&&l.append("description",a),s&&l.append("data_type",s),o&&l.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:l});return await C(p,"upload CSV"),p})).json()}async createDataset(e,{description:r,dataType:n,inputsSchema:i,outputsSchema:a,metadata:s}={}){let o={name:e,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 C(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:r}){let n="/datasets",i=new URLSearchParams({limit:"1"});if(e&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(e)G(e),n+=`/${e}`;else if(r)i.append("name",r);else throw new Error("Must provide datasetName or datasetId");let a=await this._get(n,i),s;if(Array.isArray(a)){if(a.length===0)throw new Error(`Dataset[id=${e}, name=${r}] not found`);s=a[0]}else s=a;return s}async hasDataset({datasetId:e,datasetName:r}){try{return await this.readDataset({datasetId:e,datasetName:r}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:e,datasetName:r,fromVersion:n,toVersion:i}){let a=e;if(a===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(await this.readDataset({datasetName:r})).id);let 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:e,datasetName:r}){let n="/datasets";if(e===void 0)if(r!==void 0)e=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${e}/openai_ft`)).text()).trim().split(`
|
|
137
|
+
`).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:i,datasetNameContains:a,metadata:s}={}){let o="/datasets",c=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(let l of n)c.append("id",l);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 l of this._getPaginated(o,c))yield*l}async updateDataset(e){let{datasetId:r,datasetName:n,...i}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let a=r??(await this.readDataset({datasetName:n})).id;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 C(c,"update dataset"),c})).json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:i,tag:a}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let 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 C(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",i=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(i=(await this.readDataset({datasetName:r})).id),i!==void 0)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 C(a,`delete ${n}`,!0),a})}async createExample(e,r,n){if(Vu(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let i=r?n?.datasetId:e.dataset_id,a=r?n?.datasetName:e.dataset_name;if(i===void 0&&a===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&a!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:a})).id);let s=(r?n?.createdAt:e.created_at)||new Date,o;Vu(e)?o=e:o={inputs:e,outputs:r,created_at:s?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let c=await this._uploadExamplesMultipart(i,[o]);return await this.readExample(c.example_ids?.[0]??Qt())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let v=e,k=v[0].dataset_id,O=v[0].dataset_name;if(k===void 0&&O===void 0)throw new Error("Must provide either datasetName or datasetId");if(k!==void 0&&O!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");k===void 0&&(k=(await this.readDataset({datasetName:O})).id);let j=await this._uploadExamplesMultipart(k,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:l,exampleIds:u,datasetId:d,datasetName:f}=e;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 g=r.map((v,k)=>({dataset_id:p,inputs:v,outputs:n?.[k],metadata:i?.[k],split:a?.[k],id:u?.[k],attachments:l?.[k],source_run_id:s?.[k],use_source_run_io:o?.[k],use_source_run_attachments:c?.[k]})),b=await this._uploadExamplesMultipart(p,g);return await Promise.all(b.example_ids.map(v=>this.readExample(v)))}async createLLMExample(e,r,n){return this.createExample({input:e},{output:r},n)}async createChatExample(e,r,n){let i=e.map(s=>$s(s)?Ps(s):s),a=$s(r)?Ps(r):r;return this.createExample({input:i},{output:a},n)}async readExample(e){G(e);let r=`/examples/${e}`,n=await this._get(r),{attachment_urls:i,...a}=n,s=a;return i&&(s.attachments=Object.entries(i).reduce((o,[c,l])=>(o[c.slice(11)]={presigned_url:l.presigned_url,mime_type:l.mime_type},o),{})),s}async*listExamples({datasetId:e,datasetName:r,exampleIds:n,asOf:i,splits:a,inlineS3Urls:s,metadata:o,limit:c,offset:l,filter:u,includeAttachments:d}={}){let f;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)f=e;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 g=s??!0;if(p.append("inline_s3_urls",g.toString()),n!==void 0)for(let E of n)p.append("id",E);if(a!==void 0)for(let E of a)p.append("splits",E);if(o!==void 0){let E=JSON.stringify(o);p.append("metadata",E)}c!==void 0&&p.append("limit",c.toString()),l!==void 0&&p.append("offset",l.toString()),u!==void 0&&p.append("filter",u),d===!0&&["attachment_urls","outputs","metadata"].forEach(E=>p.append("select",E));let b=0;for await(let E of this._getPaginated("/examples",p)){for(let v of E){let{attachment_urls:k,...O}=v,j=O;k&&(j.attachments=Object.entries(k).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(e){G(e);let r=`/examples/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(n,`delete ${r}`,!0),n})}async deleteExamples(e,r){if(e.forEach(n=>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:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(i,"hard delete examples",!0),i})}else{let n=new URLSearchParams;e.forEach(i=>n.append("example_ids",i)),await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/examples?${n.toString()}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(i,"delete examples",!0),i})}}async updateExample(e,r){let n;r?n=e:n=e.id,G(n);let i;r?i={id:n,...r}:i=e;let a;return i.dataset_id!==void 0?a=i.dataset_id:a=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(a,[i])}async updateExamples(e){let r;return e[0].dataset_id===void 0?r=(await this.readExample(e[0].id)).dataset_id:r=e[0].dataset_id,this._updateExamplesMultipart(r,e)}async readDatasetVersion({datasetId:e,datasetName:r,asOf:n,tag:i}){let a;if(e?a=e:a=(await this.readDataset({datasetName:r})).id,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 C(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:e,datasetName:r,asOf:n}){let i;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:r})).id:i=e,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:e,datasetName:r,splitName:n,exampleIds:i,remove:a=!1}){let s;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?s=(await this.readDataset({datasetName:r})).id:s=e,G(s);let o={split_name:n,examples:i.map(l=>(G(l),l)),remove:a},c=JSON.stringify(o);await this.caller.call(async()=>{let l=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 C(l,"update dataset splits",!0),l})}async createFeedback(e,r,{score:n,value:i,correction:a,comment:s,sourceInfo:o,feedbackSourceType:c="api",sourceRunId:l,feedbackId:u,feedbackConfig:d,projectId:f,comparativeExperimentId:p,sessionId:h,startTime:g}){if(!e&&!f)throw new Error("One of runId or projectId must be provided");if(e&&f)throw new Error("Only one of runId or projectId can be provided");let b={type:c??"api",metadata:o??{}};l!==void 0&&b?.metadata!==void 0&&!b.metadata.__run&&(b.metadata.__run={run_id:l}),b?.metadata!==void 0&&b.metadata.__run?.run_id!==void 0&&G(b.metadata.__run.run_id);let E={id:u??Mr(),run_id:e,key:r,score:Gu(n),value:i,correction:a,comment:s,feedback_source:b,comparative_experiment_id:p,feedbackConfig:d,session_id:h??f,start_time:g},v=JSON.stringify(E),k=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let O=await this._fetch(k,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:v});return await C(O,"create feedback",!0),O}),E}async updateFeedback(e,{score:r,value:n,correction:i,comment:a}){let s={};r!=null&&(s.score=Gu(r)),n!=null&&(s.value=n),i!=null&&(s.correction=i),a!=null&&(s.comment=a),G(e);let o=JSON.stringify(s);await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await C(c,"update feedback",!0),c})}async readFeedback(e){G(e);let r=`/feedback/${e}`;return await this._get(r)}async deleteFeedback(e){G(e);let r=`/feedback/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:r,feedbackSourceTypes:n}={}){let i=new URLSearchParams;if(e)for(let a of e)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(e,r,{expiration:n,feedbackConfig:i}={}){let a={run_id:e,feedback_key:r,feedback_config:i};n?typeof n=="string"?a.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(a.expires_in=n):a.expires_in={hours:3};let 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 C(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:e,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:e,experiment_ids:r,reference_dataset_id:n,description:a,created_at:(i??new Date)?.toISOString(),extra:{}};s&&(c.extra.metadata=s);let l=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:l});return await C(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(e){G(e);let r=new URLSearchParams({run_id:e});for await(let n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(e){let r;return"results"in e?r=e.results:Array.isArray(e)?r=e:r=[e],r}async _logEvaluationFeedback(e,r,n){let i=this._selectEvalResults(e),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(e,r,n){let[i]=await this._logEvaluationFeedback(e,r,n);return i}async createFeedbackConfig(e){let{feedbackKey:r,feedbackConfig:n,isLowerScoreBetter:i=!1}=e,a={feedback_key:r,feedback_config:n,is_lower_score_better:i};return(await this.caller.call(async()=>{let 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 C(o,"create feedback config"),o})).json()}async*listFeedbackConfigs(e={}){let{feedbackKeys:r,nameContains:n,limit:i}=e,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(e,r={}){let{feedbackConfig:n,isLowerScoreBetter:i}=r,a={feedback_key:e};return n!==void 0&&(a.feedback_config=n),i!==void 0&&(a.is_lower_score_better=i),(await this.caller.call(async()=>{let 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 C(o,"update feedback config"),o})).json()}async deleteFeedbackConfig(e){let r=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/feedback-configs?${r}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(n,"delete feedback config",!0),n})}async*listAnnotationQueues(e={}){let{queueIds:r,name:n,nameContains:i,limit:a}=e,s=new URLSearchParams;r&&r.forEach((c,l)=>{G(c,`queueIds[${l}]`),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(e){let{name:r,description:n,queueId:i,rubricInstructions:a,rubricItems:s}=e,o={name:r,description:n,id:i||Qt(),rubric_instructions:a,rubric_items:s},c=JSON.stringify(Object.fromEntries(Object.entries(o).filter(([u,d])=>d!==void 0)));return(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await C(u,"create annotation queue"),u})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${G(e,"queueId")}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,r){let{name:n,description:i,rubricInstructions:a,rubricItems: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 l=await this._fetch(`${this.apiUrl}/annotation-queues/${G(e,"queueId")}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await C(l,"update annotation queue",!0),l})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${G(e,"queueId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(e,r){let n=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(e,"queueId")}/runs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await C(i,"add runs to annotation queue",!0),i})}async getRunFromAnnotationQueue(e,r){let n=`/annotation-queues/${G(e,"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 C(s,"get run from annotation queue"),s})).json();return dn(a)}async deleteRunFromAnnotationQueue(e,r){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${G(e,"queueId")}/runs/${G(r,"queueRunId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${G(e,"queueId")}/size`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(e){let r=await this._getSettings();return e=="-"||r.tenant_handle===e}async _ownerConflictError(e,r){let n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
|
|
138
|
+
|
|
139
|
+
Current tenant: ${n.tenant_handle}
|
|
140
|
+
|
|
141
|
+
Requested tenant: ${r}`)}async _getLatestCommitHash(e){let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(i,"get latest commit hash"),i})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,r){let[n,i,a]=Ee(e),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 C(c,`${r?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(e){let[r,n,i]=Ee(e);if(await this._currentTenantIsOwner(r)){let a=await this._getSettings();return i!=="latest"?`${this.getHostUrl()}/prompts/${n}/${i.substring(0,8)}?organizationId=${a.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${a.id}`}else return i!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${i.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){let[r,n,i]=Ee(e);for await(let a of this._getPaginated(`/commits/${r}/${n}/`,new URLSearchParams,s=>s.commits))yield*a}async*listPrompts(e){let r=new URLSearchParams;r.append("sort_field",e?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&r.append("is_public",e.isPublic.toString()),e?.query&&r.append("query",e.query);for await(let n of this._getPaginated("/repos",r,i=>i.repos))yield*n}async getPrompt(e){let[r,n,i]=Ee(e),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 C(o,"get prompt"),o)}))?.json();return s?.repo?s.repo:null}async createPrompt(e,r){let n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
|
|
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(e);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),l=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 C(d,"create prompt"),d}),{repo:u}=await l.json();return u}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[i,a,s]=Ee(e),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}},l=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:l});return await C(f,"create commit"),f})).json();return this._getPromptUrl(`${i}/${a}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let s of r){let o=s.id,c={...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split}},l=Se(c,`Serializing body for example with id: ${o}`),u=new Blob([l],{type:"application/json"});if(n.append(o,u),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 g=new Blob([h],{type:`${p}; length=${h.byteLength}`});n.append(`${o}.attachment.${d}`,g)}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=e??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 C(s,"update examples"),s})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let a of r){let s=(a.id??Qt()).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}`),l=new Blob([c],{type:"application/json"});if(n.append(s,l),a.inputs){let u=Se(a.inputs,`Serializing inputs for uploaded example with id: ${s}`),d=new Blob([u],{type:"application/json"});n.append(`${s}.inputs`,d)}if(a.outputs){let u=Se(a.outputs,`Serializing outputs for uploaded example with id: ${s}`),d=new Blob([u],{type:"application/json"});n.append(`${s}.outputs`,d)}if(a.attachments)for(let[u,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.${u}`,h)}}return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await C(a,"upload examples"),a})).json()}async updatePrompt(e,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[n,i]=Ee(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let a={};if(r?.description!==void 0&&(a.description=r.description),r?.readme!==void 0&&(a.readme=r.readme),r?.tags!==void 0&&(a.tags=r.tags),r?.isPublic!==void 0&&(a.is_public=r.isPublic),r?.isArchived!==void 0&&(a.is_archived=r.isArchived),Object.keys(a).length===0)throw new Error("No valid update options provided");let 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 C(c,"update prompt"),c})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[r,n,i]=Ee(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(s,"delete prompt"),s})).json()}_getPromptCacheKey(e,r){return`${e}${r?":with_model":""}`}async _fetchPromptFromApi(e,r){let[n,i,a]=Ee(e),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 C(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(e,r){Vm(e,r?.dangerouslyPullPublicPrompt);let n=this._fetchPromptFromApi.bind(this,e,r);if(!r?.skipCache&&this._promptCache){let i=this._getPromptCacheKey(e,r?.includeModel),a=this._promptCache.get(i,n);if(a)return a;let s=await n();return this._promptCache.set(i,s,n),s}return this._fetchPromptFromApi(e,r)}async _pullPrompt(e,r){let n=await this.pullPromptCommit(e,{includeModel:r?.includeModel,skipCache:r?.skipCache,dangerouslyPullPublicPrompt:r?.dangerouslyPullPublicPrompt});return JSON.stringify(n.manifest)}async pushPrompt(e,r){return await this.promptExists(e)?r&&Object.keys(r).some(i=>i!=="object")&&await this.updatePrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(e,r?.object,{parentCommitHash:r?.parentCommitHash,description:r?.commitDescription}):await this._getPromptUrl(e)}async agentExists(e){let[r,n]=Ee(e);return this._repoExists(r,n)}async skillExists(e){let[r,n]=Ee(e);return this._repoExists(r,n)}async pullAgent(e,r){return await this._pullDirectory(e,"agent",r?.version)}async pullSkill(e,r){return await this._pullDirectory(e,"skill",r?.version)}async pushAgent(e,r){return this._pushDirectory(e,"agent",r)}async pushSkill(e,r){return this._pushDirectory(e,"skill",r)}async deleteAgent(e){return this._deleteDirectory(e)}async deleteSkill(e){return this._deleteDirectory(e)}async*listAgents(e){yield*this._listReposByType("agent",e)}async*listSkills(e){yield*this._listReposByType("skill",e)}async*_listReposByType(e,r){let n=new URLSearchParams;n.append("repo_type",e),n.append("is_archived",(!!r?.isArchived).toString()),r?.isPublic!==void 0&&n.append("is_public",r.isPublic.toString()),r?.query&&n.append("query",r.query);for await(let i of this._getPaginated("/repos",n,a=>a.repos))yield*i}async _pullDirectory(e,r,n){let[i,a,s]=Ee(e),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 u=await this._fetch(c.toString(),{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(u,"pull directory"),u})).json()}async _pushDirectory(e,r,n){if(n.parentCommit!==void 0&&(n.parentCommit.length<8||n.parentCommit.length>64))throw new Error("parent_commit must be 8-64 characters");let[i,a]=Ee(e);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError(`push ${r}`,i);if(await this._repoExists(i,a))(n.description!==void 0||n.readme!==void 0||n.tags!==void 0||n.isPublic!==void 0)&&await this._updateRepoMetadata(i,a,n);else{let 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 l=(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 C(d,`push ${r}`),d})).json()).commit.commit_hash,u=i;return i==="-"&&(u=(await this._getSettings()).tenant_handle||i),`${this.getHostUrl()}/hub/${u}/${a}:${l.slice(0,8)}`}async _deleteDirectory(e){let[r,n]=Ee(e);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 C(i,"delete directory"),i})}async _repoExists(e,r){try{return await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/repos/${e}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await C(n,"check repo exists"),n}),!0}catch(n){if(mi(n))return!1;throw n}}async _createRepo(e,r,n){let i={repo_handle:e,repo_type:r,is_public:!!n.isPublic};n.description!==void 0&&(i.description=n.description),n.readme!==void 0&&(i.readme=n.readme),n.tags!==void 0&&(i.tags=n.tags);try{await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await C(a,`create ${r}`),a})}catch(a){if(Ou(a))return;throw a}}async _updateRepoMetadata(e,r,n){let i={};n.description!==void 0&&(i.description=n.description),n.readme!==void 0&&(i.readme=n.readme),n.tags!==void 0&&(i.tags=n.tags),n.isPublic!==void 0&&(i.is_public=n.isPublic),Object.keys(i).length!==0&&await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/${e}/${r}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await C(a,"update repo metadata"),a})}async clonePublicDataset(e,r={}){let{sourceApiUrl:n=this.apiUrl,datasetName:i}=r,[a,s]=this.parseTokenOrUrl(e,n),o=new t({apiUrl:a,apiKey:"placeholder"}),c=await o.readSharedDataset(s),l=i||c.name;try{if(await this.hasDataset({datasetId:l})){console.log(`Dataset ${l} already exists in your tenant. Skipping.`);return}}catch{}let u=await o.listSharedExamples(s),d=await this.createDataset(l,{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:u.map(f=>f.inputs),outputs:u.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:d.id})}catch(f){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),f}}parseTokenOrUrl(e,r,n=2,i="dataset"){try{return G(e),[r,e]}catch{}try{let s=new URL(e).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: ${e}`)}catch{throw new Error(`Invalid public ${i} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();for(await new Promise(e=>setTimeout(e,1));this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await yu()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}toString(){let e=[`apiUrl=${JSON.stringify(this.apiUrl)}`];return this.webUrl!==void 0&&e.push(`webUrl=${JSON.stringify(this.webUrl)}`),this.workspaceId!==void 0&&e.push(`workspaceId=${JSON.stringify(this.workspaceId)}`),`[LangSmithClient ${e.join(" ")}]`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}};Object.defineProperty(Mt,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function Vu(t){return"dataset_id"in t||"dataset_name"in t}var qu=t=>t!==void 0?t:!!["TRACING_V2","TRACING"].find(r=>ne(r)==="true");var gt=Symbol.for("lc:context_variables");var bi=Symbol.for("langsmith:replica_trace_roots");function Hs(t,e){if(gt in t)return t[gt][e]}function Ju(t,e,r){let n=gt in t?t[gt]:{};n[e]=r,t[gt]=n}var fn=36,Qm="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function Wu(t){let r=Object.keys(t).sort().map(n=>`${n}:${t[n]??""}`).join("|");return rs(r,Qm)}function eg(t){return t.replace(/[-:.]/g,"")}function Yu(t,e=1){let r=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${r}Z`}function Gs(t,e,r=1){let n=Yu(t,r);return{dottedOrder:eg(n)+e,microsecondPrecisionDatestring:n}}var tg=new Set(["projectName","updates","reroot"]);function rg(t){let e={};for(let r of Object.keys(t))tg.has(r)&&(e[r]=t[r]);return e}var vi=class t{constructor(e,r,n,i){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=r,this.project_name=n,this.replicas=i}static fromHeader(e){let r=e.split(","),n={},i=[],a,s;for(let o of r){let[c,l]=o.split("="),u=decodeURIComponent(l);c==="langsmith-metadata"?n=JSON.parse(u):c==="langsmith-tags"?i=u.split(","):c==="langsmith-project"?a=u:c==="langsmith-replicas"&&(s=JSON.parse(u).map(f=>Array.isArray(f)?f:rg(f)))}return new t(n,i,a,s)}toHeader(){let e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}},Qe=class t{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Xu(e)){Object.assign(this,{...e});return}let r=t.getDefaultConfig(),{metadata:n,...i}=e,a=i.client??t.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=Yu(this.start_time,this.execution_order)),this.id||(this.id=Kn(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=sg(this.replicas),!this.dotted_order){let{dottedOrder:o}=Gs(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(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let e=Date.now();return{run_type:"chain",project_name:sn(),child_runs:[],api_url:pe("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:pe("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return t.sharedClient||(t.sharedClient=new Mt),t.sharedClient}createChild(e){let r=this.child_execution_order+1,n=this.replicas?.map(f=>{let{reroot:p,...h}=f;return h}),i=e.replicas??n,a=new t({...e,parent_run:this,project_name:this.project_name,replicas:i,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r}),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"),l=e.extra?.[c]??this.extra[c];if(ig(l)){let f={...l},p=ng(f.callbacks)?f.callbacks.copy?.():void 0;p&&(Object.assign(p,{_parentRunId:a.id}),p.handlers?.find(Qu)?.updateFromRunTree?.(a),f.callbacks=p),a.extra[c]=f}let u=new Set,d=this;for(;d!=null&&!u.has(d.id);)u.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(e,r,n=Date.now(),i){this.outputs=this.outputs??e,this.error=this.error??r,this.end_time=this.end_time??n,i&&Object.keys(i).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...i}}:{metadata:i})}_convertToCreate(e,r,n=!0){let i=e.extra??{};if(i?.runtime?.library===void 0&&(i.runtime||(i.runtime={}),r))for(let[o,c]of Object.entries(r))i.runtime[o]||(i.runtime[o]=c);let a=e.parent_run?.id??e.parent_run_id,s;return n?s=[]:s=e.child_runs.map(o=>this._convertToCreate(o,r,n)),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:i,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:s,parent_run_id:a,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,r){if(r.dotted_order){let n=r.dotted_order.split("."),i=null;for(let a=0;a<n.length;a++)if(n[a].slice(-fn)===e){i=a;break}if(i!==null){let a=n.slice(i+1);r.dotted_order=a.join("."),a.length>0?r.trace_id=a[0].slice(-fn):r.trace_id=r.id}}r.parent_run_id===e&&(r.parent_run_id=void 0)}_setReplicaTraceRoot(e,r){let n=Hs(this,bi)??{};n[e]=r,Ju(this,bi,n);for(let i of this.child_runs)i._setReplicaTraceRoot(e,r)}_remapForProject(e){let{projectName:r,runtimeEnv:n,excludeChildRuns:i=!0,reroot:a=!1,distributedParentId:s,apiUrl:o,apiKey:c,workspaceId:l}=e,u=this._convertToCreate(this,n,i);if(r===this.project_name)return{...u,session_name:r};if(a){if(s)this._sliceParentId(s,u);else if(u.parent_run_id=void 0,u.dotted_order){let v=u.dotted_order.split(".");v.length>0&&(u.dotted_order=v[v.length-1],u.trace_id=u.id)}let E=Wu({projectName:r,apiUrl:o,apiKey:c,workspaceId:l});this._setReplicaTraceRoot(E,u.id)}let d;if(!a){let E=Hs(this,bi)??{},v=Wu({projectName:r,apiUrl:o,apiKey:c,workspaceId:l});if(d=E[v],d&&(u.trace_id=d,u.dotted_order)){let k=u.dotted_order.split("."),O=null;for(let j=0;j<k.length;j++)if(k[j].slice(-fn)===d){O=j;break}if(O!==null){let j=k.slice(O);u.dotted_order=j.join(".")}}}let f=u.id,p=on(f,r),h;u.trace_id?h=on(u.trace_id,r):h=p;let g;u.parent_run_id&&(g=on(u.parent_run_id,r));let b;return u.dotted_order&&(b=u.dotted_order.split(".").map(k=>{let O=k.slice(-fn),j=on(O,r);return k.slice(0,-fn)+j}).join(".")),{...u,id:p,trace_id:h,parent_run_id:g,dotted_order:b,session_name:r}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let r=ri();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 l=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(l,{apiKey:i,apiUrl:a,workspaceId:s})}else{let n=this._convertToCreate(this,r,e);await this.client.createRun(n)}if(!e){er("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let n of this.child_runs)await n.postRun(!1)}this.child_runs=[]}catch(r){console.error(`Error in postRun for run ${this.id}:`,r)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:r,apiKey:n,apiUrl:i,workspaceId:a,updates:s,reroot:o,client:c}of this.replicas){let l=this._remapForProject({projectName:r??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:o,distributedParentId:this.distributedParentId,apiUrl:i,apiKey:n,workspaceId:a}),u={id:l.id,name:l.name,run_type:l.run_type,start_time:l.start_time,outputs:l.outputs,error:l.error,parent_run_id:l.parent_run_id,session_name:l.session_name,reference_example_id:l.reference_example_id,end_time:l.end_time,dotted_order:l.dotted_order,trace_id:l.trace_id,events:l.events,tags:l.tags,extra:l.extra,attachments:this.attachments,...s};e?.excludeInputs||(u.inputs=l.inputs),await(c??this.client).updateRun(l.id,u,{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};e?.excludeInputs||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,r){let n=e?.callbacks,i,a,s,o=qu();if(n){let l=n?.getParentRunId?.()??"",u=n?.handlers?.find(d=>d?.name=="langchain_tracer");i=u?.getRun?.(l),a=u?.projectName,s=u?.client,o=o||!!u}return i?new t({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(e?.tags??[]))],extra:{metadata:{...i?.extra?.metadata,...e?.metadata}}}).createChild(r):new t({...r,client:s,tracingEnabled:o,project_name:a})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,r){let n="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,i=n["langsmith-trace"];if(!i||typeof i!="string")return;let a=i.trim(),s=a.split(".").map(u=>{let[d,f]=u.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 u=vi.fromHeader(n.baggage);c.metadata=u.metadata,c.tags=u.tags,c.project_name=u.project_name,c.replicas=u.replicas}let l=new t(c);return l.distributedParentId=l.id,l}toHeaders(e){let r={"langsmith-trace":this.dotted_order,baggage:new vi(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[n,i]of Object.entries(r))e.set(n,i);return r}};Object.defineProperty(Qe,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Xu(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}function Qu(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}function Ku(t){return Array.isArray(t)&&t.some(e=>Qu(e))}function ng(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}function ig(t){let e=t?.callbacks;return t!=null&&typeof e=="object"&&(Ku(e?.handlers)||Ku(e))}function ag(){let t=pe("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{let e=JSON.parse(t);if(Array.isArray(e)){let r=[];for(let n of e){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key})}return r}else if(typeof e=="object"&&e!==null){og(e);let r=[];for(let[n,i]of Object.entries(e)){let a=n.replace(/\/$/,"");if(typeof i=="string")r.push({apiUrl:a,apiKey:i});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof i}`);continue}}return r}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(Nu(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function sg(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):ag()}function og(t){if(Object.keys(t).length>0&&ne("ENDPOINT"))throw new pi}var nS=D({BaseTracer:()=>et,isBaseTracer:()=>nr}),cg=t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t};function Zs(t,e){if(t)return new Qe({...t,start_time:t._serialized_start_time??t.start_time,parent_run:Zs(e),child_runs:t.child_runs.map(r=>Zs(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:za()},tracingEnabled:!1})}function Vs(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}function nr(t){return typeof t._addRunToRunMap=="function"}var et=class extends Xt{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(t){super(...arguments)}copy(){return this}getRunById(t){if(t!==void 0)return this.usesRunTreeMap?cg(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`
|
|
147
|
+
|
|
148
|
+
${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,e){t.child_runs.push(e)}_addRunToRunMap(t){let{dottedOrder:e,microsecondPrecisionDatestring:r}=Gs(new Date(t.start_time).getTime(),t.id,t.execution_order),n={...t},i=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?i?(this._addChildRun(i,n),i.child_execution_order=Math.max(i.child_execution_order,n.child_execution_order),n.trace_id=i.trace_id,i.dotted_order!==void 0&&(n.dotted_order=[i.dotted_order,e].join("."),n._serialized_start_time=r)):n.parent_run_id=void 0:(n.trace_id=n.id,n.dotted_order=e,n._serialized_start_time=r),this.usesRunTreeMap){let a=Zs(n,i);a!==void 0&&this.runTreeMap.set(n.id,a)}else this.runMap.set(n.id,n);return n}async _endTrace(t){let e=t.parent_run_id!==void 0&&this.getRunById(t.parent_run_id);e?e.child_execution_order=Math.max(e.child_execution_order,t.child_execution_order):await this.persistRun(t),await this.onRunUpdate?.(t),this.usesRunTreeMap?this.runTreeMap.delete(t.id):this.runMap.delete(t.id)}_getExecutionOrder(t){let e=t!==void 0&&this.getRunById(t);return e?e.child_execution_order+1:1}_createRunForLLMStart(t,e,r,n,i,a,s,o){let c=this._getExecutionOrder(n),l=Date.now(),u=s?{...i,metadata:s}:i,d={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{prompts:e},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:u??{},tags:a||[]};return this._addRunToRunMap(d)}async handleLLMStart(t,e,r,n,i,a,s,o){let c=this.getRunById(r)??this._createRunForLLMStart(t,e,r,n,i,a,s,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(t,e,r,n,i,a,s,o){let c=this._getExecutionOrder(n),l=Date.now(),u=s?{...i,metadata:s}:i,d={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{messages:e},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:u??{},tags:a||[]};return this._addRunToRunMap(d)}async handleChatModelStart(t,e,r,n,i,a,s,o){let c=this.getRunById(r)??this._createRunForChatModelStart(t,e,r,n,i,a,s,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(t,e,r,n,i){let a=this.getRunById(e);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=t,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMEnd?.(a),await this._endTrace(a),a}async handleLLMError(t,e,r,n,i){let a=this.getRunById(e);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(t),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMError?.(a),await this._endTrace(a),a}_createRunForChainStart(t,e,r,n,i,a,s,o,c){let l=this._getExecutionOrder(n),u=Date.now(),d={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:e,execution_order:l,child_execution_order:l,run_type:s??"chain",child_runs:[],extra:a?{...c,metadata:a}:{...c},tags:i||[]};return this._addRunToRunMap(d)}async handleChainStart(t,e,r,n,i,a,s,o){let c=this.getRunById(r)??this._createRunForChainStart(t,e,r,n,i,a,s,o);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(t,e,r,n,i){let a=this.getRunById(e);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=Vs(t,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=Vs(i.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(t,e,r,n,i){let a=this.getRunById(e);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(t),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=Vs(i.inputs,"input")),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(t,e,r,n,i,a,s){let o=this._getExecutionOrder(n),c=Date.now(),l={id:r,name:s??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:e},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleToolStart(t,e,r,n,i,a,s){let o=this.getRunById(r)??this._createRunForToolStart(t,e,r,n,i,a,s);return await this.onRunCreate?.(o),await this.onToolStart?.(o),o}async handleToolEnd(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="chain")return;let n=r;n.actions=n.actions||[],n.actions.push(t),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentAction?.(r)}async handleAgentEnd(t,e){let r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(t,e,r,n,i,a,s){let o=this._getExecutionOrder(n),c=Date.now(),l={id:r,name:s??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:e},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(t,e,r,n,i,a,s){let o=this.getRunById(r)??this._createRunForRetrieverStart(t,e,r,n,i,a,s);return await this.onRunCreate?.(o),await this.onRetrieverStart?.(o),o}async handleRetrieverEnd(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(t,e){let r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:t}}),await this.onText?.(r))}async handleLLMNewToken(t,e,r,n,i,a){let s=this.getRunById(r);if(!s||s?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return s.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:t,idx:e,chunk:a?.chunk}}),await this.onLLMNewToken?.(s,t,{chunk:a?.chunk}),s}};var qs=Wt(nd(),1),lS=D({ConsoleCallbackHandler:()=>xi});function Ce(t,e){return`${t.open}${e}${t.close}`}function Ve(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}function id(t){return typeof t=="string"?t.trim():t==null?t:Ve(t,t.toString())}function jt(t){if(!t.end_time)return"";let e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}var{color:Me}=qs.default,xi=class extends et{name="console_callback_handler";persistRun(t){return Promise.resolve()}getParents(t){let e=[],r=t;for(;r.parent_run_id;){let n=this.runMap.get(r.parent_run_id);if(n)e.push(n),r=n;else break}return e}getBreadcrumbs(t){let e=[...this.getParents(t).reverse(),t].map((r,n,i)=>{let a=`${r.execution_order}:${r.run_type}:${r.name}`;return n===i.length-1?Ce(qs.default.bold,a):a}).join(" > ");return Ce(Me.grey,e)}onChainStart(t){let e=this.getBreadcrumbs(t);console.log(`${Ce(Me.green,"[chain/start]")} [${e}] Entering Chain run with input: ${Ve(t.inputs,"[inputs]")}`)}onChainEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Ce(Me.cyan,"[chain/end]")} [${e}] [${jt(t)}] Exiting Chain run with output: ${Ve(t.outputs,"[outputs]")}`)}onChainError(t){let e=this.getBreadcrumbs(t);console.log(`${Ce(Me.red,"[chain/error]")} [${e}] [${jt(t)}] Chain run errored with error: ${Ve(t.error,"[error]")}`)}onLLMStart(t){let e=this.getBreadcrumbs(t),r="prompts"in t.inputs?{prompts:t.inputs.prompts.map(n=>n.trim())}:t.inputs;console.log(`${Ce(Me.green,"[llm/start]")} [${e}] Entering LLM run with input: ${Ve(r,"[inputs]")}`)}onLLMEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Ce(Me.cyan,"[llm/end]")} [${e}] [${jt(t)}] Exiting LLM run with output: ${Ve(t.outputs,"[response]")}`)}onLLMError(t){let e=this.getBreadcrumbs(t);console.log(`${Ce(Me.red,"[llm/error]")} [${e}] [${jt(t)}] LLM run errored with error: ${Ve(t.error,"[error]")}`)}onToolStart(t){let e=this.getBreadcrumbs(t);console.log(`${Ce(Me.green,"[tool/start]")} [${e}] Entering Tool run with input: "${id(t.inputs.input)}"`)}onToolEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Ce(Me.cyan,"[tool/end]")} [${e}] [${jt(t)}] Exiting Tool run with output: "${id(t.outputs?.output)}"`)}onToolError(t){let e=this.getBreadcrumbs(t);console.log(`${Ce(Me.red,"[tool/error]")} [${e}] [${jt(t)}] Tool run errored with error: ${Ve(t.error,"[error]")}`)}onRetrieverStart(t){let e=this.getBreadcrumbs(t);console.log(`${Ce(Me.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${Ve(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Ce(Me.cyan,"[retriever/end]")} [${e}] [${jt(t)}] Exiting Retriever run with output: ${Ve(t.outputs,"[outputs]")}`)}onRetrieverError(t){let e=this.getBreadcrumbs(t);console.log(`${Ce(Me.red,"[retriever/error]")} [${e}] [${jt(t)}] Retriever run errored with error: ${Ve(t.error,"[error]")}`)}onAgentAction(t){let e=t,r=this.getBreadcrumbs(t);console.log(`${Ce(Me.blue,"[agent/action]")} [${r}] Agent selected action: ${Ve(e.actions[e.actions.length-1],"[action]")}`)}};var Js,Ei=()=>(Js===void 0&&(Js=new Mt(Xe("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),Js);var Ks=class{getStore(){}run(e,r){return r()}},Ws=Symbol.for("ls:tracing_async_local_storage"),ug=new Ks,Ys=class{getInstance(){return globalThis[Ws]??ug}initializeGlobalInstance(e){globalThis[Ws]===void 0&&(globalThis[Ws]=e)}},dg=new Ys;function ad(t=!1){let e=dg.getInstance().getStore();if(!t&&e===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 e}function Si(t){return typeof t=="function"&&"langsmith:traceable"in t}var IS=D({LangChainTracer:()=>Ti});function fg(t){let e;for(let r of t)for(let n of r)Cr.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=Dn(e,n.message.usage_metadata));return e}var Ti=class sd extends et{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(e={}){super(e);let{exampleId:r,projectName:n,client:i,replicas:a}=e;this.projectName=n??sn(),this.replicas=a,this.exampleId=r,this.client=i??Ei();let s=sd.getTraceableRunTree();s&&this.updateFromRunTree(s)}async persistRun(e){}async onRunCreate(e){e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){let r=this.getRunTreeWithTracingConfig(e.id);e.extra?.lc_defers_inputs?await r?.postRun():await r?.patchRun()}onLLMEnd(e){let r=e.outputs;if(r?.generations){let n=fg(r.generations);if(n!==void 0){e.extra=e.extra??{};let i=e.extra.metadata??{};i.usage_metadata=n,e.extra.metadata=i}}}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let r=e,n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();let i=[r];for(;i.length>0;){let a=i.shift();!a||n.has(a.id)||(n.add(a.id),this.runTreeMap.set(a.id,a),a.child_runs&&i.push(...a.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(e){let r=this.runTreeMap.get(e);if(r)return new Qe({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return ad(!0)}catch{return}}};var od=Symbol.for("ls:tracing_async_local_storage"),Dt=Symbol.for("lc:context_variables"),cd=t=>{globalThis[od]=t},Ut=()=>globalThis[od];var Ai=Wt(di(),1),ir;function pg(){return new("default"in Ai.default?Ai.default.default:Ai.default)({autoStart:!0,concurrency:1})}function hg(){return typeof ir>"u"&&(ir=pg()),ir}async function oe(t,e){if(e===!0){let r=Ut();r!==void 0?await r.run(void 0,async()=>t()):await t()}else ir=hg(),ir.add(async()=>{let r=Ut();r!==void 0?await r.run(void 0,async()=>t()):await t()})}async function ld(){let t=Ei();await Promise.allSettled([typeof ir<"u"?ir.onIdle():Promise.resolve(),t.awaitPendingTraceBatches()])}var LS=D({awaitAllCallbacks:()=>ld,consumeCallback:()=>oe});var ud=t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>Xe(e)==="true");function Xs(t){let e=Ut();if(e!==void 0)return e.getStore()?.[Dt]?.[t]}var mg=Symbol("lc:configure_hooks"),dd=()=>Xs(mg)||[];var tT=D({BaseCallbackManager:()=>fd,BaseRunManager:()=>mn,CallbackManager:()=>tt,CallbackManagerForChainRun:()=>hd,CallbackManagerForLLMRun:()=>Qs,CallbackManagerForRetrieverRun:()=>pd,CallbackManagerForToolRun:()=>md,ensureHandler:()=>zr,parseCallbackConfigArg:()=>hn});function hn(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}var fd=class{setHandler(t){return this.setHandlers([t])}},mn=class{constructor(t,e,r,n,i,a,s,o){this.runId=t,this.handlers=e,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(t){await Promise.all(this.handlers.map(e=>oe(async()=>{try{await e.handleText?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleCustomEvent(t,e,r,n,i){await Promise.all(this.handlers.map(a=>oe(async()=>{try{await a.handleCustomEvent?.(t,e,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)))}},pd=class extends mn{getChild(t){let e=new tt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>oe(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw r}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>oe(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${r}`),e.raiseError)throw t}},e.awaitHandlers)))}},Qs=class extends mn{async handleLLMNewToken(t,e,r,n,i,a){await Promise.all(this.handlers.map(s=>oe(async()=>{if(!s.ignoreLLM)try{await s.handleLLMNewToken?.(t,e??{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 handleLLMError(t,e,r,n,i){await Promise.all(this.handlers.map(a=>oe(async()=>{if(!a.ignoreLLM)try{await a.handleLLMError?.(t,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(t,e,r,n,i){await Promise.all(this.handlers.map(a=>oe(async()=>{if(!a.ignoreLLM)try{await a.handleLLMEnd?.(t,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)))}},hd=class extends mn{getChild(t){let e=new tt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,r,n,i){await Promise.all(this.handlers.map(a=>oe(async()=>{if(!a.ignoreChain)try{await a.handleChainError?.(t,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(t,e,r,n,i){await Promise.all(this.handlers.map(a=>oe(async()=>{if(!a.ignoreChain)try{await a.handleChainEnd?.(t,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(t){await Promise.all(this.handlers.map(e=>oe(async()=>{if(!e.ignoreAgent)try{await e.handleAgentAction?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>oe(async()=>{if(!e.ignoreAgent)try{await e.handleAgentEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},md=class extends mn{getChild(t){let e=new tt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>oe(async()=>{if(!e.ignoreAgent)try{await e.handleToolError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEvent(t){await Promise.all(this.handlers.map(e=>oe(async()=>{if(!e.ignoreAgent)try{await e.handleToolEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if(e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>oe(async()=>{if(!e.ignoreAgent)try{await e.handleToolEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},tt=class pn extends fd{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,r){super(),this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,r,n=void 0,i=void 0,a=void 0,s=void 0,o=void 0,c=void 0){return Promise.all(r.map(async(l,u)=>{let d=u===0&&n?n:He();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return nr(f)&&f._createRunForLLMStart(e,[l],d,this._parentRunId,a,this.tags,this.metadata,c),oe(async()=>{try{await f.handleLLMStart?.(e,[l],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(e,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(l,u)=>{let d=u===0&&n?n:He();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return nr(f)&&f._createRunForChatModelStart(e,[l],d,this._parentRunId,a,this.tags,this.metadata,c),oe(async()=>{try{if(f.handleChatModelStart)await f.handleChatModelStart?.(e,[l],d,this._parentRunId,a,this.tags,this.metadata,c);else if(f.handleLLMStart){let p=Fn(l);await f.handleLLMStart?.(e,[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(e,r,n=He(),i=void 0,a=void 0,s=void 0,o=void 0,c=void 0,l=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreChain)return nr(u)&&u._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,i,o,l),oe(async()=>{try{await u.handleChainStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,i,o,l)}catch(d){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleChainStart: ${d}`),u.raiseError)throw d}},u.awaitHandlers)})),new hd(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,r,n=He(),i=void 0,a=void 0,s=void 0,o=void 0,c=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreAgent)return nr(l)&&l._createRunForToolStart(e,r,n,this._parentRunId,this.tags,this.metadata,o),oe(async()=>{try{await l.handleToolStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,o,c)}catch(u){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleToolStart: ${u}`),l.raiseError)throw u}},l.awaitHandlers)})),new md(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,r,n=He(),i=void 0,a=void 0,s=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return nr(c)&&c._createRunForRetrieverStart(e,r,n,this._parentRunId,this.tags,this.metadata,o),oe(async()=>{try{await c.handleRetrieverStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new pd(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,r,n,i,a){await Promise.all(this.handlers.map(s=>oe(async()=>{if(!s.ignoreCustomEvent)try{await s.handleCustomEvent?.(e,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(e,r=!0){this.handlers.push(e),r&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(r=>r!==e),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==e)}setHandlers(e,r=!0){this.handlers=[],this.inheritableHandlers=[];for(let n of e)this.addHandler(n,r)}addTags(e,r=!0){this.removeTags(e),this.tags.push(...e),r&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(r=>!e.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!e.includes(r))}addMetadata(e,r=!0){this.metadata={...this.metadata,...e},r&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let r of Object.keys(e))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(e=[],r=!0){let n=new pn(this._parentRunId);for(let i of this.handlers){let a=this.inheritableHandlers.includes(i);n.addHandler(i,a)}for(let i of this.tags){let a=this.inheritableTags.includes(i);n.addTags([i],a)}for(let i of Object.keys(this.metadata)){let a=Object.keys(this.inheritableMetadata).includes(i);n.addMetadata({[i]:this.metadata[i]},a)}for(let i of e)n.handlers.filter(a=>a.name==="console_callback_handler").some(a=>a.name===i.name)||n.addHandler(i,r);return n}static fromHandlers(e){class r extends Xt{name=He();constructor(){super(),Object.assign(this,e)}}let n=new this;return n.addHandler(new r),n}static configure(e,r,n,i,a,s,o){return this._configureSync(e,r,n,i,a,s,o)}static _configureSync(e,r,n,i,a,s,o){let c;(e||r)&&(Array.isArray(e)||!e?(c=new pn,c.setHandlers(e?.map(zr)??[],!0)):c=e,c=c.copy(Array.isArray(r)?r.map(zr):r?.handlers,!1));let l=Xe("LANGCHAIN_VERBOSE")==="true"||o?.verbose,u=Ti.getTraceableRunTree(),d=u?.tracingEnabled??ud();if(u?.tracingEnabled===!1&&c){let p=c.handlers.filter(h=>h.name==="langchain_tracer");for(let h of p)c.removeHandler(h)}let f=d||(Xe("LANGCHAIN_TRACING")??!1);if(l||f){if(c||(c=new pn),l&&!c.handlers.some(p=>p.name===xi.prototype.name)){let p=new xi;c.addHandler(p,!0)}if(f&&!c.handlers.some(p=>p.name==="langchain_tracer")&&d){let p=new Ti;c.addHandler(p,!0)}d&&u&&c._parentRunId===void 0&&(c._parentRunId=u.id,c.handlers.find(p=>p.name==="langchain_tracer")?.updateFromRunTree(u))}for(let{contextVar:p,inheritable:h=!0,handlerClass:g,envVar:b}of dd()){let E=b&&Xe(b)==="true"&&g,v,k=p!==void 0?Xs(p):void 0;k&&Ka(k)?v=k:E&&(v=new g({})),v!==void 0&&(c||(c=new pn),c.handlers.some(O=>O.name===v.name)||c.addHandler(v,h))}return(n||i)&&c&&(c.addTags(n??[]),c.addTags(i??[],!1)),(a||s)&&c&&(c.addMetadata(a??{}),c.addMetadata(s??{},!1)),c}};function zr(t){return"name"in t?t:Xt.fromMethods(t)}var eo=class{getStore(){}run(t,e){return e()}enterWith(t){}},gg=new eo,gd=Symbol.for("lc:child_config"),_g=class{getInstance(){return Ut()??gg}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[gd]}runWithConfig(t,e,r){let n=tt._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),i=this.getInstance(),a=i.getStore(),s=n?.getParentRunId(),o=n?.handlers?.find(l=>l?.name==="langchain_tracer"),c;return o&&s?c=o.getRunTreeWithTracingConfig(s):r||(c=new Qe({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[gd]:t}),a!==void 0&&a[Dt]!==void 0&&(c===void 0&&(c={}),c[Dt]=a[Dt]),i.run(c,e)}initializeGlobalInstance(t){Ut()===void 0&&cd(t)}},be=new _g;var yT=D({AsyncLocalStorageProviderSingleton:()=>be,MockAsyncLocalStorage:()=>eo,_CONTEXT_VARIABLES_KEY:()=>Dt});async function Ze(t){return tt._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata)}function gn(...t){let e={};for(let r of t.filter(n=>!!n))for(let n of Object.keys(r))if(n==="metadata")e[n]={...e[n],...r[n]};else if(n==="tags"){let i=e[n]??[];e[n]=[...new Set(i.concat(r[n]??[]))]}else if(n==="configurable")e[n]={...e[n],...r[n]};else if(n==="timeout")e.timeout===void 0?e.timeout=r.timeout:r.timeout!==void 0&&(e.timeout=Math.min(e.timeout,r.timeout));else if(n==="signal")e.signal===void 0?e.signal=r.signal:r.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,r.signal]):e.signal=r.signal);else if(n==="callbacks"){let i=e.callbacks,a=r.callbacks;if(Array.isArray(a))if(!i)e.callbacks=a;else if(Array.isArray(i))e.callbacks=i.concat(a);else{let s=i.copy();for(let o of a)s.addHandler(zr(o),!0);e.callbacks=s}else if(a)if(!i)e.callbacks=a;else if(Array.isArray(i)){let s=a.copy();for(let o of i)s.addHandler(zr(o),!0);e.callbacks=s}else e.callbacks=new tt(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;e[i]=r[i]??e[i]}return e}var yg=new Set(["string","number","boolean"]);function Y(t){let e=be.getRunnableConfig(),r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){let{runId:n,runName:i,...a}=e;r=Object.entries(a).reduce((s,[o,c])=>(c!==void 0&&(s[o]=c),s),r)}if(t&&(r=Object.entries(t).reduce((n,[i,a])=>(a!==void 0&&(n[i]=a),n),r)),r?.configurable)for(let n of Object.keys(r.configurable))yg.has(typeof r.configurable[n])&&!r.metadata?.[n]&&(r.metadata||(r.metadata={}),r.metadata[n]=r.configurable[n]);if(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 ue(t={},{callbacks:e,maxConcurrency:r,recursionLimit:n,runName:i,configurable:a,runId:s}={}){let o=Y(t);return e!==void 0&&(delete o.runName,o.callbacks=e),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 qe(t){if(t)return{configurable:t.configurable,recursionLimit:t.recursionLimit,callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,maxConcurrency:t.maxConcurrency,timeout:t.timeout,signal:t.signal,store:t.store}}async function rt(t,e){if(e===void 0)return t;let r;return Promise.race([t.catch(n=>{if(!e?.aborted)throw n}),new Promise((n,i)=>{r=()=>{i(Bt(e))},e.addEventListener("abort",r,{once:!0}),e.aborted&&i(Bt(e))})]).finally(()=>e.removeEventListener("abort",r))}function Bt(t){return t?.reason instanceof Error?t.reason:typeof t?.reason=="string"?new Error(t.reason):new Error("Aborted")}function ae(t){if(typeof t!="object"||t===null)return!1;let e=t;if(!("_zod"in e))return!1;let r=e._zod;return typeof r=="object"&&r!==null&&"def"in r}function he(t){if(typeof t!="object"||t===null)return!1;let e=t;if(!("_def"in e)||"_zod"in e)return!1;let r=e._def;return typeof r=="object"&&r!=null&&"typeName"in r}function AT(t){return ae(t)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),he(t)}function Fr(t){return!t||typeof t!="object"||Array.isArray(t)?!1:!!(ae(t)||he(t))}function wg(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodLiteral"}function bg(t){return ae(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="literal":!1}function kT(t){return!!(wg(t)||bg(t))}async function IT(t,e){if(ae(t))try{return{success:!0,data:await xa(t,e)}}catch(r){return{success:!1,error:r}}if(he(t))return await t.safeParseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Ii(t,e){if(ae(t))return await xa(t,e);if(he(t))return await t.parseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function CT(t,e){if(ae(t))try{return{success:!0,data:$n(t,e)}}catch(r){return{success:!1,error:r}}if(he(t))return t.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function OT(t,e){if(ae(t))return $n(t,e);if(he(t))return t.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function wd(t){if(ae(t))return $e.get(t)?.description;if(he(t)||"description"in t&&typeof t.description=="string")return t.description}function RT(t){if(!Fr(t))return!1;if(he(t)){let e=t._def;if(e.typeName==="ZodObject"){let r=t;return!r.shape||Object.keys(r.shape).length===0}if(e.typeName==="ZodRecord")return!0}if(ae(t)){let e=t._zod.def;if(e.type==="object"){let r=t;return!r.shape||Object.keys(r.shape).length===0}if(e.type==="record")return!0}return typeof t=="object"&&t!==null&&!("shape"in t)}function Ci(t){return Fr(t)?he(t)?t._def.typeName==="ZodString":ae(t)?t._zod.def.type==="string":!1:!1}function to(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodObject"}function _t(t){return ae(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="object":!1}function ro(t){return ae(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="array":!1}function vg(t){return ae(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="optional":!1}function xg(t){return ae(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="nullable":!1}function NT(t){return!!(to(t)||_t(t))}function _d(t){if(he(t))return t.shape;if(ae(t))return t._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function $T(t,e){if(he(t))return t.extend(e);if(ae(t))return va.extend(t,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function PT(t){if(he(t))return t.partial();if(ae(t))return va.partial(Ea,t,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function ki(t,e=!1){if(to(t))return t.strict();if(_t(t)){let r=t._zod.def.shape;if(e)for(let[a,s]of Object.entries(t._zod.def.shape)){if(_t(s))r[a]=ki(s,e);else if(ro(s)){let c=s._zod.def.element;_t(c)&&(c=ki(c,e)),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(t,{...t._zod.def,shape:r,catchall:Fo(Bo)}),i=$e.get(t);return i&&$e.add(n,i),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function yd(t,e=!1){if(to(t))return t.passthrough();if(_t(t)){let r=t._zod.def.shape;if(e)for(let[a,s]of Object.entries(t._zod.def.shape)){if(_t(s))r[a]=yd(s,e);else if(ro(s)){let c=s._zod.def.element;_t(c)&&(c=yd(c,e)),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(t,{...t._zod.def,shape:r,catchall:zo(Uo)}),i=$e.get(t);return i&&$e.add(n,i),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function MT(t){if(he(t))try{let e=t.parse(void 0);return()=>e}catch{return}if(ae(t))try{let e=$n(t,void 0);return()=>e}catch{return}}function Eg(t){return he(t)&&"typeName"in t._def&&t._def.typeName==="ZodEffects"}function Sg(t){return ae(t)&&t._zod.def.type==="pipe"}function ar(t,e,r){let n=r.get(t);if(n!==void 0)return n;if(he(t))return Eg(t)?ar(t._def.schema,e,r):t;if(ae(t)){let i=t;if(Sg(t)&&(i=ar(t._zod.def.in,e,r)),e){if(_t(i)){let s={};for(let[o,c]of Object.entries(i._zod.def.shape))s[o]=ar(c,e,r);i=dt(i,{...i._zod.def,shape:s})}else if(ro(i)){let s=ar(i._zod.def.element,e,r);i=dt(i,{...i._zod.def,element:s})}else if(vg(i)){let s=ar(i._zod.def.innerType,e,r);i=dt(i,{...i._zod.def,innerType:s})}else if(xg(i)){let s=ar(i._zod.def.innerType,e,r);i=dt(i,{...i._zod.def,innerType:s})}}let a=$e.get(t);return a&&$e.add(i,a),r.set(t,i),i}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function bd(t,e=!1){return ar(t,e,new WeakMap)}function LT(t,e){if(he(t)){let r=_d(t),n={};for(let[i,a]of Object.entries(r))e(i,a)?n[i]=a.optional():n[i]=a;return t.extend(n)}if(ae(t)){let r=_d(t),n={...t._zod.def.shape};for(let[s,o]of Object.entries(r))e(s,o)&&(n[s]=new Ea({type:"optional",innerType:o}));let i=dt(t,{...t._zod.def,shape:n}),a=$e.get(t);return a&&$e.add(i,a),i}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function vd(t){return t instanceof Error&&(t.constructor.name==="ZodError"||t.constructor.name==="$ZodError")}var Ed=Symbol("Let zodToJsonSchema decide on which parser to use"),xd={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"},Sd=t=>typeof t=="string"?{...xd,name:t}:{...xd,...t};var Td=t=>{let e=Sd(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};var Oi=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function se(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Oi(e,t.currentPath):e.join("/")}}function no(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function W(t,e,r,n,i){t[e]=r,no(t,e,n,i)}var vt={};pp(vt,{BRAND:()=>Kg,DIRTY:()=>sr,EMPTY_PATH:()=>Ig,INVALID:()=>L,NEVER:()=>P_,OK:()=>Te,ParseStatus:()=>ve,Schema:()=>q,ZodAny:()=>Ht,ZodArray:()=>Ot,ZodBigInt:()=>cr,ZodBoolean:()=>lr,ZodBranded:()=>yn,ZodCatch:()=>br,ZodDate:()=>ur,ZodDefault:()=>wr,ZodDiscriminatedUnion:()=>$i,ZodEffects:()=>Ke,ZodEnum:()=>_r,ZodError:()=>Le,ZodFirstPartyTypeKind:()=>w,ZodFunction:()=>Mi,ZodIntersection:()=>hr,ZodIssueCode:()=>y,ZodLazy:()=>mr,ZodLiteral:()=>gr,ZodMap:()=>Jr,ZodNaN:()=>Kr,ZodNativeEnum:()=>yr,ZodNever:()=>nt,ZodNull:()=>fr,ZodNullable:()=>bt,ZodNumber:()=>or,ZodObject:()=>je,ZodOptional:()=>Je,ZodParsedType:()=>A,ZodPipeline:()=>wn,ZodPromise:()=>Gt,ZodReadonly:()=>vr,ZodRecord:()=>Pi,ZodSchema:()=>q,ZodSet:()=>Wr,ZodString:()=>Ft,ZodSymbol:()=>Zr,ZodTransformer:()=>Ke,ZodTuple:()=>wt,ZodType:()=>q,ZodUndefined:()=>dr,ZodUnion:()=>pr,ZodUnknown:()=>Ct,ZodVoid:()=>qr,addIssueToContext:()=>x,any:()=>a_,array:()=>l_,bigint:()=>e_,boolean:()=>Ld,coerce:()=>$_,custom:()=>$d,date:()=>t_,datetimeRegex:()=>Rd,defaultErrorMap:()=>kt,discriminatedUnion:()=>p_,effect:()=>T_,enum:()=>x_,function:()=>w_,getErrorMap:()=>Hr,getParsedType:()=>yt,instanceof:()=>Xg,intersection:()=>h_,isAborted:()=>Ri,isAsync:()=>Gr,isDirty:()=>Ni,isValid:()=>zt,late:()=>Yg,lazy:()=>b_,literal:()=>v_,makeIssue:()=>_n,map:()=>__,nan:()=>Qg,nativeEnum:()=>E_,never:()=>o_,null:()=>i_,nullable:()=>k_,number:()=>Md,object:()=>u_,objectUtil:()=>io,oboolean:()=>N_,onumber:()=>R_,optional:()=>A_,ostring:()=>O_,pipeline:()=>C_,preprocess:()=>I_,promise:()=>S_,quotelessJson:()=>Tg,record:()=>g_,set:()=>y_,setErrorMap:()=>kg,strictObject:()=>d_,string:()=>Pd,symbol:()=>r_,transformer:()=>T_,tuple:()=>m_,undefined:()=>n_,union:()=>f_,unknown:()=>s_,util:()=>J,void:()=>c_});var J;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let a={};for(let s of i)a[s]=s;return a},t.getValidEnumValues=i=>{let a=t.objectKeys(i).filter(o=>typeof i[i[o]]!="number"),s={};for(let o of a)s[o]=i[o];return t.objectValues(s)},t.objectValues=i=>t.objectKeys(i).map(function(a){return i[a]}),t.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},t.find=(i,a)=>{for(let s of i)if(a(s))return s},t.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)}t.joinValues=n,t.jsonStringifyReplacer=(i,a)=>typeof a=="bigint"?a.toString():a})(J||(J={}));var io;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(io||(io={}));var A=J.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),yt=t=>{switch(typeof t){case"undefined":return A.undefined;case"string":return A.string;case"number":return Number.isNaN(t)?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(t)?A.array:t===null?A.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?A.promise:typeof Map<"u"&&t instanceof Map?A.map:typeof Set<"u"&&t instanceof Set?A.set:typeof Date<"u"&&t instanceof Date?A.date:A.object;default:return A.unknown}};var y=J.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"]),Tg=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Le=class t extends Error{get errors(){return this.issues}constructor(e){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=e}format(e){let r=e||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 l=s.path[c];c===s.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(r(s))):o[l]=o[l]||{_errors:[]},o=o[l],c++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,J.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=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(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Le.create=t=>new Le(t);var Ag=(t,e)=>{let r;switch(t.code){case y.invalid_type:t.received===A.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case y.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,J.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:r=`Unrecognized key(s) in object: ${J.joinValues(t.keys,", ")}`;break;case y.invalid_union:r="Invalid input";break;case y.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${J.joinValues(t.options)}`;break;case y.invalid_enum_value:r=`Invalid enum value. Expected ${J.joinValues(t.options)}, received '${t.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 t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:J.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case y.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case y.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.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 ${t.multipleOf}`;break;case y.not_finite:r="Number must be finite";break;default:r=e.defaultError,J.assertNever(t)}return{message:r}},kt=Ag;var Ad=kt;function kg(t){Ad=t}function Hr(){return Ad}var _n=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,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(l=>!!l).slice().reverse();for(let l of c)o=l(s,{data:e,defaultError:o}).message;return{...i,path:a,message:o}},Ig=[];function x(t,e){let r=Hr(),n=_n({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===kt?void 0:kt].filter(i=>!!i)});t.common.issues.push(n)}var ve=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return L;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let a=await i.key,s=await i.value;n.push({key:a,value:s})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:a,value:s}=i;if(a.status==="aborted"||s.status==="aborted")return L;a.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[a.value]=s.value)}return{status:e.value,value:n}}},L=Object.freeze({status:"aborted"}),sr=t=>({status:"dirty",value:t}),Te=t=>({status:"valid",value:t}),Ri=t=>t.status==="aborted",Ni=t=>t.status==="dirty",zt=t=>t.status==="valid",Gr=t=>typeof Promise<"u"&&t instanceof Promise;var P;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(P||(P={}));var We=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,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}},kd=(t,e)=>{if(zt(e))return{success:!0,data:e.value};if(!t.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 Le(t.common.issues);return this._error=r,this._error}}};function V(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,o)=>{let{message:c}=t;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(e){return yt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:yt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ve,ctx:{common:e.parent.common,data:e.data,parsedType:yt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Gr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yt(e)},i=this._parseSync({data:e,path:n.path,parent:n});return kd(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return zt(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:e,path:[],parent:r}).then(n=>zt(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yt(e)},i=this._parse({data:e,path:n.path,parent:n}),a=await(Gr(i)?i:Promise.resolve(i));return kd(n,a)}refine(e,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=e(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(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new Ke({schema:this,typeName:w.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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 Gt.create(this,this._def)}or(e){return pr.create([this,e],this._def)}and(e){return hr.create(this,e,this._def)}transform(e){return new Ke({...V(this._def),schema:this,typeName:w.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new wr({...V(this._def),innerType:this,defaultValue:r,typeName:w.ZodDefault})}brand(){return new yn({typeName:w.ZodBranded,type:this,...V(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new br({...V(this._def),innerType:this,catchValue:r,typeName:w.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return wn.create(this,e)}readonly(){return vr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Cg=/^c[^\s-]{8,}$/i,Og=/^[0-9a-z]+$/,Rg=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ng=/^[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,$g=/^[a-z0-9_-]{21}$/i,Pg=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Mg=/^[-+]?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)?)??$/,Lg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,jg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ao,Dg=/^(?:(?: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])$/,Ug=/^(?:(?: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])$/,Bg=/^(([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]))$/,zg=/^(([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])$/,Fg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Hg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Cd="((\\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])))",Gg=new RegExp(`^${Cd}$`);function Od(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Vg(t){return new RegExp(`^${Od(t)}$`)}function Rd(t){let e=`${Cd}T${Od(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Zg(t,e){return!!((e==="v4"||!e)&&Dg.test(t)||(e==="v6"||!e)&&Bg.test(t))}function qg(t,e){if(!Pg.test(t))return!1;try{let[r]=t.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||e&&i.alg!==e)}catch{return!1}}function Jg(t,e){return!!((e==="v4"||!e)&&Ug.test(t)||(e==="v6"||!e)&&zg.test(t))}var Ft=class t extends q{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==A.string){let a=this._getOrReturnCtx(e);return x(a,{code:y.invalid_type,expected:A.string,received:a.parsedType}),L}let n=new ve,i;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(i=this._getOrReturnCtx(e,i),x(i,{code:y.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(i=this._getOrReturnCtx(e,i),x(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=e.data.length>a.value,o=e.data.length<a.value;(s||o)&&(i=this._getOrReturnCtx(e,i),s?x(i,{code:y.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&x(i,{code:y.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")Lg.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"email",code:y.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")ao||(ao=new RegExp(jg,"u")),ao.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"emoji",code:y.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")Ng.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"uuid",code:y.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")$g.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"nanoid",code:y.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")Cg.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"cuid",code:y.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")Og.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"cuid2",code:y.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")Rg.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"ulid",code:y.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),x(i,{validation:"url",code:y.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"regex",code:y.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(i=this._getOrReturnCtx(e,i),x(i,{code:y.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(i=this._getOrReturnCtx(e,i),x(i,{code:y.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(i=this._getOrReturnCtx(e,i),x(i,{code:y.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?Rd(a).test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{code:y.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?Gg.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{code:y.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?Vg(a).test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{code:y.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?Mg.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"duration",code:y.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?Zg(e.data,a.version)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"ip",code:y.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?qg(e.data,a.alg)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"jwt",code:y.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?Jg(e.data,a.version)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"cidr",code:y.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?Fg.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"base64",code:y.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?Hg.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"base64url",code:y.invalid_string,message:a.message}),n.dirty()):J.assertNever(a);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:y.invalid_string,...P.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...P.errToObj(e)})}url(e){return this._addCheck({kind:"url",...P.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...P.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...P.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...P.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...P.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...P.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...P.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...P.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...P.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...P.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...P.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...P.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...P.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...P.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...P.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...P.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...P.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...P.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...P.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...P.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...P.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...P.errToObj(r)})}nonempty(e){return this.min(1,P.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Ft.create=t=>new Ft({checks:[],typeName:w.ZodString,coerce:t?.coerce??!1,...V(t)});function Wg(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,a=Number.parseInt(t.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return a%s/10**i}var or=class t extends q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==A.number){let a=this._getOrReturnCtx(e);return x(a,{code:y.invalid_type,expected:A.number,received:a.parsedType}),L}let n,i=new ve;for(let a of this._def.checks)a.kind==="int"?J.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{code:y.invalid_type,expected:"integer",received:"float",message:a.message}),i.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),x(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?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),x(n,{code:y.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="multipleOf"?Wg(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),x(n,{code:y.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{code:y.not_finite,message:a.message}),i.dirty()):J.assertNever(a);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,P.toString(r))}gt(e,r){return this.setLimit("min",e,!1,P.toString(r))}lte(e,r){return this.setLimit("max",e,!0,P.toString(r))}lt(e,r){return this.setLimit("max",e,!1,P.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:P.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:P.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:P.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&J.isInteger(e.value))}get isFinite(){let e=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"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};or.create=t=>new or({checks:[],typeName:w.ZodNumber,coerce:t?.coerce||!1,...V(t)});var cr=class t extends q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==A.bigint)return this._getInvalidInput(e);let n,i=new ve;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),x(n,{code:y.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),x(n,{code:y.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),x(n,{code:y.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):J.assertNever(a);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return x(r,{code:y.invalid_type,expected:A.bigint,received:r.parsedType}),L}gte(e,r){return this.setLimit("min",e,!0,P.toString(r))}gt(e,r){return this.setLimit("min",e,!1,P.toString(r))}lte(e,r){return this.setLimit("max",e,!0,P.toString(r))}lt(e,r){return this.setLimit("max",e,!1,P.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:P.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};cr.create=t=>new cr({checks:[],typeName:w.ZodBigInt,coerce:t?.coerce??!1,...V(t)});var lr=class extends q{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==A.boolean){let n=this._getOrReturnCtx(e);return x(n,{code:y.invalid_type,expected:A.boolean,received:n.parsedType}),L}return Te(e.data)}};lr.create=t=>new lr({typeName:w.ZodBoolean,coerce:t?.coerce||!1,...V(t)});var ur=class t extends q{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==A.date){let a=this._getOrReturnCtx(e);return x(a,{code:y.invalid_type,expected:A.date,received:a.parsedType}),L}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return x(a,{code:y.invalid_date}),L}let n=new ve,i;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(i=this._getOrReturnCtx(e,i),x(i,{code:y.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(i=this._getOrReturnCtx(e,i),x(i,{code:y.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):J.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:P.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:P.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};ur.create=t=>new ur({checks:[],coerce:t?.coerce||!1,typeName:w.ZodDate,...V(t)});var Zr=class extends q{_parse(e){if(this._getType(e)!==A.symbol){let n=this._getOrReturnCtx(e);return x(n,{code:y.invalid_type,expected:A.symbol,received:n.parsedType}),L}return Te(e.data)}};Zr.create=t=>new Zr({typeName:w.ZodSymbol,...V(t)});var dr=class extends q{_parse(e){if(this._getType(e)!==A.undefined){let n=this._getOrReturnCtx(e);return x(n,{code:y.invalid_type,expected:A.undefined,received:n.parsedType}),L}return Te(e.data)}};dr.create=t=>new dr({typeName:w.ZodUndefined,...V(t)});var fr=class extends q{_parse(e){if(this._getType(e)!==A.null){let n=this._getOrReturnCtx(e);return x(n,{code:y.invalid_type,expected:A.null,received:n.parsedType}),L}return Te(e.data)}};fr.create=t=>new fr({typeName:w.ZodNull,...V(t)});var Ht=class extends q{constructor(){super(...arguments),this._any=!0}_parse(e){return Te(e.data)}};Ht.create=t=>new Ht({typeName:w.ZodAny,...V(t)});var Ct=class extends q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Te(e.data)}};Ct.create=t=>new Ct({typeName:w.ZodUnknown,...V(t)});var nt=class extends q{_parse(e){let r=this._getOrReturnCtx(e);return x(r,{code:y.invalid_type,expected:A.never,received:r.parsedType}),L}};nt.create=t=>new nt({typeName:w.ZodNever,...V(t)});var qr=class extends q{_parse(e){if(this._getType(e)!==A.undefined){let n=this._getOrReturnCtx(e);return x(n,{code:y.invalid_type,expected:A.void,received:n.parsedType}),L}return Te(e.data)}};qr.create=t=>new qr({typeName:w.ZodVoid,...V(t)});var Ot=class t extends q{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==A.array)return x(r,{code:y.invalid_type,expected:A.array,received:r.parsedType}),L;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,o=r.data.length<i.exactLength.value;(s||o)&&(x(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&&(x(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&&(x(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 We(r,s,r.path,o)))).then(s=>ve.mergeArray(n,s));let a=[...r.data].map((s,o)=>i.type._parseSync(new We(r,s,r.path,o)));return ve.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:P.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:P.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:P.toString(r)}})}nonempty(e){return this.min(1,e)}};Ot.create=(t,e)=>new Ot({type:t,minLength:null,maxLength:null,exactLength:null,typeName:w.ZodArray,...V(e)});function Vr(t){if(t instanceof je){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Je.create(Vr(n))}return new je({...t._def,shape:()=>e})}else return t instanceof Ot?new Ot({...t._def,type:Vr(t.element)}):t instanceof Je?Je.create(Vr(t.unwrap())):t instanceof bt?bt.create(Vr(t.unwrap())):t instanceof wt?wt.create(t.items.map(e=>Vr(e))):t}var je=class t 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 e=this._def.shape(),r=J.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==A.object){let l=this._getOrReturnCtx(e);return x(l,{code:y.invalid_type,expected:A.object,received:l.parsedType}),L}let{status:n,ctx:i}=this._processInputParams(e),{shape:a,keys:s}=this._getCached(),o=[];if(!(this._def.catchall instanceof nt&&this._def.unknownKeys==="strip"))for(let l in i.data)s.includes(l)||o.push(l);let c=[];for(let l of s){let u=a[l],d=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new We(i,d,i.path,l)),alwaysSet:l in i.data})}if(this._def.catchall instanceof nt){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of o)c.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(l==="strict")o.length>0&&(x(i,{code:y.unrecognized_keys,keys:o}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of o){let d=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new We(i,d,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,f=await u.value;l.push({key:d,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>ve.mergeObjectSync(n,l)):ve.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return P.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:P.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:w.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of J.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of J.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Vr(this)}partial(e){let r={};for(let n of J.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of J.objectKeys(this.shape))if(e&&!e[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 t({...this._def,shape:()=>r})}keyof(){return Nd(J.objectKeys(this.shape))}};je.create=(t,e)=>new je({shape:()=>t,unknownKeys:"strip",catchall:nt.create(),typeName:w.ZodObject,...V(e)});je.strictCreate=(t,e)=>new je({shape:()=>t,unknownKeys:"strict",catchall:nt.create(),typeName:w.ZodObject,...V(e)});je.lazycreate=(t,e)=>new je({shape:t,unknownKeys:"strip",catchall:nt.create(),typeName:w.ZodObject,...V(e)});var pr=class extends q{_parse(e){let{ctx:r}=this._processInputParams(e),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 Le(o.ctx.common.issues));return x(r,{code:y.invalid_union,unionErrors:s}),L}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 l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!a&&(a={result:u,ctx:l}),l.common.issues.length&&s.push(l.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let o=s.map(c=>new Le(c));return x(r,{code:y.invalid_union,unionErrors:o}),L}}get options(){return this._def.options}};pr.create=(t,e)=>new pr({options:t,typeName:w.ZodUnion,...V(e)});var It=t=>t instanceof mr?It(t.schema):t instanceof Ke?It(t.innerType()):t instanceof gr?[t.value]:t instanceof _r?t.options:t instanceof yr?J.objectValues(t.enum):t instanceof wr?It(t._def.innerType):t instanceof dr?[void 0]:t instanceof fr?[null]:t instanceof Je?[void 0,...It(t.unwrap())]:t instanceof bt?[null,...It(t.unwrap())]:t instanceof yn||t instanceof vr?It(t.unwrap()):t instanceof br?It(t._def.innerType):[],$i=class t extends q{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==A.object)return x(r,{code:y.invalid_type,expected:A.object,received:r.parsedType}),L;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}):(x(r,{code:y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),L)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let a of r){let s=It(a.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of s){if(i.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);i.set(o,a)}}return new t({typeName:w.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...V(n)})}};function so(t,e){let r=yt(t),n=yt(e);if(t===e)return{valid:!0,data:t};if(r===A.object&&n===A.object){let i=J.objectKeys(e),a=J.objectKeys(t).filter(o=>i.indexOf(o)!==-1),s={...t,...e};for(let o of a){let c=so(t[o],e[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(t.length!==e.length)return{valid:!1};let i=[];for(let a=0;a<t.length;a++){let s=t[a],o=e[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&&+t==+e?{valid:!0,data:t}:{valid:!1}}var hr=class extends q{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(a,s)=>{if(Ri(a)||Ri(s))return L;let o=so(a.value,s.value);return o.valid?((Ni(a)||Ni(s))&&r.dirty(),{status:r.value,value:o.data}):(x(n,{code:y.invalid_intersection_types}),L)};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}))}};hr.create=(t,e,r)=>new hr({left:t,right:e,typeName:w.ZodIntersection,...V(r)});var wt=class t extends q{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.array)return x(n,{code:y.invalid_type,expected:A.array,received:n.parsedType}),L;if(n.data.length<this._def.items.length)return x(n,{code:y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),L;!this._def.rest&&n.data.length>this._def.items.length&&(x(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 We(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(e){return new t({...this._def,rest:e})}};wt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new wt({items:t,typeName:w.ZodTuple,rest:null,...V(e)})};var Pi=class t extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.object)return x(n,{code:y.invalid_type,expected:A.object,received:n.parsedType}),L;let i=[],a=this._def.keyType,s=this._def.valueType;for(let o in n.data)i.push({key:a._parse(new We(n,o,n.path,o)),value:s._parse(new We(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(e,r,n){return r instanceof q?new t({keyType:e,valueType:r,typeName:w.ZodRecord,...V(n)}):new t({keyType:Ft.create(),valueType:e,typeName:w.ZodRecord,...V(r)})}},Jr=class extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.map)return x(n,{code:y.invalid_type,expected:A.map,received:n.parsedType}),L;let i=this._def.keyType,a=this._def.valueType,s=[...n.data.entries()].map(([o,c],l)=>({key:i._parse(new We(n,o,n.path,[l,"key"])),value:a._parse(new We(n,c,n.path,[l,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of s){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return L;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),o.set(l.value,u.value)}return{status:r.value,value:o}})}else{let o=new Map;for(let c of s){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return L;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),o.set(l.value,u.value)}return{status:r.value,value:o}}}};Jr.create=(t,e,r)=>new Jr({valueType:e,keyType:t,typeName:w.ZodMap,...V(r)});var Wr=class t extends q{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.set)return x(n,{code:y.invalid_type,expected:A.set,received:n.parsedType}),L;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(x(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&&(x(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 l=new Set;for(let u of c){if(u.status==="aborted")return L;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let o=[...n.data.values()].map((c,l)=>a._parse(new We(n,c,n.path,l)));return n.common.async?Promise.all(o).then(c=>s(c)):s(o)}min(e,r){return new t({...this._def,minSize:{value:e,message:P.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:P.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Wr.create=(t,e)=>new Wr({valueType:t,minSize:null,maxSize:null,typeName:w.ZodSet,...V(e)});var Mi=class t extends q{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==A.function)return x(r,{code:y.invalid_type,expected:A.function,received:r.parsedType}),L;function n(o,c){return _n({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Hr(),kt].filter(l=>!!l),issueData:{code:y.invalid_arguments,argumentsError:c}})}function i(o,c){return _n({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Hr(),kt].filter(l=>!!l),issueData:{code:y.invalid_return_type,returnTypeError:c}})}let a={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof Gt){let o=this;return Te(async function(...c){let l=new Le([]),u=await o._def.args.parseAsync(c,a).catch(p=>{throw l.addIssue(n(c,p)),l}),d=await Reflect.apply(s,this,u);return await o._def.returns._def.type.parseAsync(d,a).catch(p=>{throw l.addIssue(i(d,p)),l})})}else{let o=this;return Te(function(...c){let l=o._def.args.safeParse(c,a);if(!l.success)throw new Le([n(c,l.error)]);let u=Reflect.apply(s,this,l.data),d=o._def.returns.safeParse(u,a);if(!d.success)throw new Le([i(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:wt.create(e).rest(Ct.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||wt.create([]).rest(Ct.create()),returns:r||Ct.create(),typeName:w.ZodFunction,...V(n)})}},mr=class extends q{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};mr.create=(t,e)=>new mr({getter:t,typeName:w.ZodLazy,...V(e)});var gr=class extends q{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return x(r,{received:r.data,code:y.invalid_literal,expected:this._def.value}),L}return{status:"valid",value:e.data}}get value(){return this._def.value}};gr.create=(t,e)=>new gr({value:t,typeName:w.ZodLiteral,...V(e)});function Nd(t,e){return new _r({values:t,typeName:w.ZodEnum,...V(e)})}var _r=class t extends q{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return x(r,{expected:J.joinValues(n),received:r.parsedType,code:y.invalid_type}),L}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return x(r,{received:r.data,code:y.invalid_enum_value,options:n}),L}return Te(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};_r.create=Nd;var yr=class extends q{_parse(e){let r=J.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==A.string&&n.parsedType!==A.number){let i=J.objectValues(r);return x(n,{expected:J.joinValues(i),received:n.parsedType,code:y.invalid_type}),L}if(this._cache||(this._cache=new Set(J.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=J.objectValues(r);return x(n,{received:n.data,code:y.invalid_enum_value,options:i}),L}return Te(e.data)}get enum(){return this._def.values}};yr.create=(t,e)=>new yr({values:t,typeName:w.ZodNativeEnum,...V(e)});var Gt=class extends q{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==A.promise&&r.common.async===!1)return x(r,{code:y.invalid_type,expected:A.promise,received:r.parsedType}),L;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})))}};Gt.create=(t,e)=>new Gt({type:t,typeName:w.ZodPromise,...V(e)});var Ke=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(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:s=>{x(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 L;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?L:c.status==="dirty"?sr(c.value):r.value==="dirty"?sr(c.value):c});{if(r.value==="aborted")return L;let o=this._def.schema._parseSync({data:s,path:n.path,parent:n});return o.status==="aborted"?L:o.status==="dirty"?sr(o.value):r.value==="dirty"?sr(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"?L:(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"?L:(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(!zt(s))return L;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=>zt(s)?Promise.resolve(i.transform(s.value,a)).then(o=>({status:r.value,value:o})):L);J.assertNever(i)}};Ke.create=(t,e,r)=>new Ke({schema:t,typeName:w.ZodEffects,effect:e,...V(r)});Ke.createWithPreprocess=(t,e,r)=>new Ke({schema:e,effect:{type:"preprocess",transform:t},typeName:w.ZodEffects,...V(r)});var Je=class extends q{_parse(e){return this._getType(e)===A.undefined?Te(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Je.create=(t,e)=>new Je({innerType:t,typeName:w.ZodOptional,...V(e)});var bt=class extends q{_parse(e){return this._getType(e)===A.null?Te(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};bt.create=(t,e)=>new bt({innerType:t,typeName:w.ZodNullable,...V(e)});var wr=class extends q{_parse(e){let{ctx:r}=this._processInputParams(e),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}};wr.create=(t,e)=>new wr({innerType:t,typeName:w.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...V(e)});var br=class extends q{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Gr(i)?i.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Le(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Le(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};br.create=(t,e)=>new br({innerType:t,typeName:w.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...V(e)});var Kr=class extends q{_parse(e){if(this._getType(e)!==A.nan){let n=this._getOrReturnCtx(e);return x(n,{code:y.invalid_type,expected:A.nan,received:n.parsedType}),L}return{status:"valid",value:e.data}}};Kr.create=t=>new Kr({typeName:w.ZodNaN,...V(t)});var Kg=Symbol("zod_brand"),yn=class extends q{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},wn=class t extends q{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);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"?L:a.status==="dirty"?(r.dirty(),sr(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"?L:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:w.ZodPipeline})}},vr=class extends q{_parse(e){let r=this._def.innerType._parse(e),n=i=>(zt(i)&&(i.value=Object.freeze(i.value)),i);return Gr(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};vr.create=(t,e)=>new vr({innerType:t,typeName:w.ZodReadonly,...V(e)});function Id(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function $d(t,e={},r){return t?Ht.create().superRefine((n,i)=>{let a=t(n);if(a instanceof Promise)return a.then(s=>{if(!s){let o=Id(e,n),c=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:c})}});if(!a){let s=Id(e,n),o=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:o})}}):Ht.create()}var Yg={object:je.lazycreate},w;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(w||(w={}));var Xg=(t,e={message:`Input not instance of ${t.name}`})=>$d(r=>r instanceof t,e),Pd=Ft.create,Md=or.create,Qg=Kr.create,e_=cr.create,Ld=lr.create,t_=ur.create,r_=Zr.create,n_=dr.create,i_=fr.create,a_=Ht.create,s_=Ct.create,o_=nt.create,c_=qr.create,l_=Ot.create,u_=je.create,d_=je.strictCreate,f_=pr.create,p_=$i.create,h_=hr.create,m_=wt.create,g_=Pi.create,__=Jr.create,y_=Wr.create,w_=Mi.create,b_=mr.create,v_=gr.create,x_=_r.create,E_=yr.create,S_=Gt.create,T_=Ke.create,A_=Je.create,k_=bt.create,I_=Ke.createWithPreprocess,C_=wn.create,O_=()=>Pd().optional(),R_=()=>Md().optional(),N_=()=>Ld().optional(),$_={string:(t=>Ft.create({...t,coerce:!0})),number:(t=>or.create({...t,coerce:!0})),boolean:(t=>lr.create({...t,coerce:!0})),bigint:(t=>cr.create({...t,coerce:!0})),date:(t=>ur.create({...t,coerce:!0}))};var P_=L;function jd(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==w.ZodAny&&(r.items=U(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&W(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&W(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(W(r,"minItems",t.exactLength.value,t.exactLength.message,e),W(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Dd(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?W(r,"minimum",n.value,n.message,e):W(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),W(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?W(r,"maximum",n.value,n.message,e):W(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),W(r,"maximum",n.value,n.message,e));break;case"multipleOf":W(r,"multipleOf",n.value,n.message,e);break}return r}function Ud(){return{type:"boolean"}}function Li(t,e){return U(t.type._def,e)}var Bd=(t,e)=>U(t.innerType._def,e);function oo(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(i=>oo(t,e,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 M_(t,e)}}var M_=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":W(r,"minimum",n.value,n.message,e);break;case"max":W(r,"maximum",n.value,n.message,e);break}return r};function zd(t,e){return{...U(t.innerType._def,e),default:t.defaultValue()}}function Fd(t,e){return e.effectStrategy==="input"?U(t.schema._def,e):se(e)}function Hd(t){return{type:"string",enum:Array.from(t.values)}}var L_=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Gd(t,e){let r=[U(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),U(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(a=>{if(L_(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 Vd(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var co,it={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 ji(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":W(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":W(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":at(r,"email",n.message,e);break;case"format:idn-email":at(r,"idn-email",n.message,e);break;case"pattern:zod":Oe(r,it.email,n.message,e);break}break;case"url":at(r,"uri",n.message,e);break;case"uuid":at(r,"uuid",n.message,e);break;case"regex":Oe(r,n.regex,n.message,e);break;case"cuid":Oe(r,it.cuid,n.message,e);break;case"cuid2":Oe(r,it.cuid2,n.message,e);break;case"startsWith":Oe(r,RegExp(`^${lo(n.value,e)}`),n.message,e);break;case"endsWith":Oe(r,RegExp(`${lo(n.value,e)}$`),n.message,e);break;case"datetime":at(r,"date-time",n.message,e);break;case"date":at(r,"date",n.message,e);break;case"time":at(r,"time",n.message,e);break;case"duration":at(r,"duration",n.message,e);break;case"length":W(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),W(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":Oe(r,RegExp(lo(n.value,e)),n.message,e);break;case"ip":n.version!=="v6"&&at(r,"ipv4",n.message,e),n.version!=="v4"&&at(r,"ipv6",n.message,e);break;case"base64url":Oe(r,it.base64url,n.message,e);break;case"jwt":Oe(r,it.jwt,n.message,e);break;case"cidr":n.version!=="v6"&&Oe(r,it.ipv4Cidr,n.message,e),n.version!=="v4"&&Oe(r,it.ipv6Cidr,n.message,e);break;case"emoji":Oe(r,it.emoji(),n.message,e);break;case"ulid":Oe(r,it.ulid,n.message,e);break;case"base64":switch(e.base64Strategy){case"format:binary":at(r,"binary",n.message,e);break;case"contentEncoding:base64":W(r,"contentEncoding","base64",n.message,e);break;case"pattern:zod":Oe(r,it.base64,n.message,e);break}break;case"nanoid":Oe(r,it.nanoid,n.message,e);break;case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function lo(t,e){return e.patternStrategy==="escape"?D_(t):t}var j_=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function D_(t){let e="";for(let r=0;r<t.length;r++)j_.has(t[r])||(e+="\\"),e+=t[r];return e}function at(t,e,r,n){t.format||t.anyOf?.some(i=>i.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):W(t,"format",e,r,n)}function Oe(t,e,r,n){t.pattern||t.allOf?.some(i=>i.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Zd(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):W(t,"pattern",Zd(e,n),r,n)}function Zd(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.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 ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return i}function Di(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===w.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,i)=>({...n,[i]:U(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",i]})??se(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:U(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===w.ZodString&&t.keyType._def.checks?.length){let{type:n,...i}=ji(t.keyType._def,e);return{...r,propertyNames:i}}else{if(t.keyType?._def.typeName===w.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===w.ZodBranded&&t.keyType._def.type._def.typeName===w.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...i}=Li(t.keyType._def,e);return{...r,propertyNames:i}}}return r}function qd(t,e){return e.mapStrategy==="record"?Di(t,e):{type:"array",maxItems:125,items:{type:"array",items:[U(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||se(e),U(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||se(e)],minItems:2,maxItems:2}}}function Jd(t){let e=t.values,r=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[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 Wd(t){return t.target==="openAi"?void 0:{not:se({...t,currentPath:[...t.currentPath,"not"]})}}function Kd(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var bn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Xd(t,e){if(e.target==="openApi3")return Yd(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in bn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((i,a)=>{let s=bn[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 Yd(t,e)}var Yd=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,i)=>U(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Qd(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:bn[t.innerType._def.typeName],nullable:!0}:{type:[bn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=U(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=U(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function ef(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",no(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?W(r,"minimum",n.value,n.message,e):W(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),W(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?W(r,"maximum",n.value,n.message,e):W(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),W(r,"maximum",n.value,n.message,e));break;case"multipleOf":W(r,"multipleOf",n.value,n.message,e);break}return r}function tf(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},i=[],a=t.shape();for(let o in a){let c=a[o];if(c===void 0||c._def===void 0)continue;let l=B_(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=U(c._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});u!==void 0&&(n.properties[o]=u,l||i.push(o))}i.length&&(n.required=i);let s=U_(t,e);return s!==void 0&&(n.additionalProperties=s),n}function U_(t,e){if(t.catchall._def.typeName!=="ZodNever")return U(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function B_(t){try{return t.isOptional()}catch{return!0}}var rf=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return U(t.innerType._def,e);let r=U(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:se(e)},r]}:se(e)};var nf=(t,e)=>{if(e.pipeStrategy==="input")return U(t.in._def,e);if(e.pipeStrategy==="output")return U(t.out._def,e);let r=U(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]});return{allOf:[r,U(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]})].filter(n=>n!==void 0)}};function af(t,e){return U(t.type._def,e)}function sf(t,e){let r={type:"array",uniqueItems:!0,items:U(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&W(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&W(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}function of(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>U(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:U(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>U(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function cf(t){return{not:se(t)}}function lf(t){return se(t)}var uf=(t,e)=>U(t.innerType._def,e);var df=(t,e,r)=>{switch(e){case w.ZodString:return ji(t,r);case w.ZodNumber:return ef(t,r);case w.ZodObject:return tf(t,r);case w.ZodBigInt:return Dd(t,r);case w.ZodBoolean:return Ud();case w.ZodDate:return oo(t,r);case w.ZodUndefined:return cf(r);case w.ZodNull:return Kd(r);case w.ZodArray:return jd(t,r);case w.ZodUnion:case w.ZodDiscriminatedUnion:return Xd(t,r);case w.ZodIntersection:return Gd(t,r);case w.ZodTuple:return of(t,r);case w.ZodRecord:return Di(t,r);case w.ZodLiteral:return Vd(t,r);case w.ZodEnum:return Hd(t);case w.ZodNativeEnum:return Jd(t);case w.ZodNullable:return Qd(t,r);case w.ZodOptional:return rf(t,r);case w.ZodMap:return qd(t,r);case w.ZodSet:return sf(t,r);case w.ZodLazy:return()=>t.getter()._def;case w.ZodPromise:return af(t,r);case w.ZodNaN:case w.ZodNever:return Wd(r);case w.ZodEffects:return Fd(t,r);case w.ZodAny:return se(r);case w.ZodUnknown:return lf(r);case w.ZodDefault:return zd(t,r);case w.ZodBranded:return Li(t,r);case w.ZodReadonly:return uf(t,r);case w.ZodCatch:return Bd(t,r);case w.ZodPipeline:return nf(t,r);case w.ZodFunction:case w.ZodVoid:case w.ZodSymbol:return;default:return(n=>{})(e)}};function U(t,e,r=!1){let n=e.seen.get(t);if(e.override){let o=e.override?.(t,e,n,r);if(o!==Ed)return o}if(n&&!r){let o=z_(n,e);if(o!==void 0)return o}let i={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,i);let a=df(t,t.typeName,e),s=typeof a=="function"?U(a(),e):a;if(s&&F_(t,e,s),e.postProcess){let o=e.postProcess(s,t,e);return i.jsonSchema=s,o}return i.jsonSchema=s,s}var z_=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Oi(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),se(e)):e.$refStrategy==="seen"?se(e):void 0}},F_=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var ff=(t,e)=>{let r=Td(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:U(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??se(r)}),{}):void 0,i=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=U(t._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??se(r),s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.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 Qk=D({isSerializableSchema:()=>H_,isStandardJsonSchema:()=>Ui,isStandardSchema:()=>pf});function pf(t){return(typeof t=="object"||typeof t=="function")&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"validate"in t["~standard"]}function Ui(t){return(typeof t=="object"||typeof t=="function")&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"jsonSchema"in t["~standard"]}function H_(t){return pf(t)&&Ui(t)}function Vt(t,e){let r=typeof t;if(r!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;let n=t.length;if(n!==e.length)return!1;for(let i=0;i<n;i++)if(!Vt(t[i],e[i]))return!1;return!0}if(r==="object"){if(!t||!e)return t===e;let n=Object.keys(t),i=Object.keys(e);if(n.length!==i.length)return!1;for(let s of n)if(!Vt(t[s],e[s]))return!1;return!0}return t===e}function ze(t){return encodeURI(G_(t))}function G_(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var V_={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Z_={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},q_={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},J_=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 st(t,e=Object.create(null),r=J_,n=""){if(t&&typeof t=="object"&&!Array.isArray(t)){let a=t.$id||t.id;if(a){let s=new URL(a,r.href);s.hash.length>1?e[s.href]=t:(s.hash="",n===""?r=s:st(t,e,r))}}else if(t!==!0&&t!==!1)return e;let i=r.href+(n?"#"+n:"");if(e[i]!==void 0)throw new Error(`Duplicate schema URI "${i}".`);if(e[i]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:i}),t.$ref&&t.__absolute_ref__===void 0){let a=new URL(t.$ref,r.href);a.hash=a.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:a.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){let a=new URL(t.$recursiveRef,r.href);a.hash=a.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:a.href})}if(t.$anchor){let a=new URL("#"+t.$anchor,r.href);e[a.href]=t}for(let a in t){if(q_[a])continue;let s=`${n}/${ze(a)}`,o=t[a];if(Array.isArray(o)){if(V_[a]){let c=o.length;for(let l=0;l<c;l++)st(o[l],e,r,`${s}/${l}`)}}else if(Z_[a])for(let c in o)st(o[c],e,r,`${s}/${ze(c)}`);else st(o,e,r,s)}return e}var W_=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,K_=[0,31,28,31,30,31,30,31,31,30,31,30,31],Y_=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,X_=/^(?=.{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,Q_=/^(?:[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,ey=/^(?:(?:[^\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,ty=/^(?:(?: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,ry=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,ny=/^(?:\/(?:[^~/]|~0|~1)*)*$/,iy=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,ay=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,sy=t=>{if(t[0]==='"')return!1;let[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},oy=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,cy=/^((([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,ly=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));function xt(t){return t.test.bind(t)}var uo={date:hf,time:mf.bind(void 0,!1),"date-time":fy,duration:ly,uri:my,"uri-reference":xt(Q_),"uri-template":xt(ey),url:xt(ty),email:sy,hostname:xt(X_),ipv4:xt(oy),ipv6:xt(cy),regex:_y,uuid:xt(ry),"json-pointer":xt(ny),"json-pointer-uri-fragment":xt(iy),"relative-json-pointer":xt(ay)};function uy(t){return t%4===0&&(t%100!==0||t%400===0)}function hf(t){let e=t.match(W_);if(!e)return!1;let r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&uy(r)?29:K_[n])}function mf(t,e){let r=e.match(Y_);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)&&(!t||s)}var dy=/t|\s/i;function fy(t){let e=t.split(dy);return e.length==2&&hf(e[0])&&mf(!0,e[1])}var py=/\/|:/,hy=/^(?:[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 my(t){return py.test(t)&&hy.test(t)}var gy=/[^\\]\\Z/;function _y(t){if(gy.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}var gf;(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(gf||(gf={}));function _f(t){let e=0,r=t.length,n=0,i;for(;n<r;)e++,i=t.charCodeAt(n++),i>=55296&&i<=56319&&n<r&&(i=t.charCodeAt(n),(i&64512)==56320&&n++);return e}function re(t,e,r="2019-09",n=st(e),i=!0,a=null,s="#",o="#",c=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};let l=typeof t,u;switch(l){case"boolean":case"number":case"string":u=l;break;case"object":t===null?u="null":Array.isArray(t)?u="array":u="object";break;default:throw new Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:h,const:g,enum:b,required:E,not:v,anyOf:k,allOf:O,oneOf:j,if:X,then:K,else:Q,format:ee,properties:fe,patternProperties:Ae,additionalProperties:lt,unevaluatedProperties:An,minProperties:en,maxProperties:ha,propertyNames:No,dependentRequired:ma,dependentSchemas:ga,dependencies:_a,prefixItems:ya,items:tn,additionalItems:$o,unevaluatedItems:Po,contains:Mo,minContains:Tt,maxContains:kn,minItems:wa,maxItems:ba,uniqueItems:dp,minimum:qt,maximum:Jt,exclusiveMinimum:rn,exclusiveMaximum:nn,multipleOf:In,minLength:Cn,maxLength:On,pattern:Lo,__absolute_ref__:Rn,__absolute_recursive_ref__:fp}=e,I=[];if(p===!0&&a===null&&(a=e),f==="#"){let B=a===null?n[fp]:a,M=`${o}/$recursiveRef`,H=re(t,a===null?e:a,r,n,i,B,s,M,c);H.valid||I.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:M,error:"A subschema had errors."},...H.errors)}if(d!==void 0){let M=n[Rn||d];if(M===void 0){let S=`Unresolved $ref "${d}".`;throw Rn&&Rn!==d&&(S+=` Absolute URI "${Rn}".`),S+=`
|
|
155
|
+
Known schemas:
|
|
156
|
+
- ${Object.keys(n).join(`
|
|
157
|
+
- `)}`,new Error(S)}let H=`${o}/$ref`,R=re(t,M,r,n,i,a,s,H,c);if(R.valid||I.push({instanceLocation:s,keyword:"$ref",keywordLocation:H,error:"A subschema had errors."},...R.errors),r==="4"||r==="7")return{valid:I.length===0,errors:I}}if(Array.isArray(h)){let B=h.length,M=!1;for(let H=0;H<B;H++)if(u===h[H]||h[H]==="integer"&&u==="number"&&t%1===0&&t===t){M=!0;break}M||I.push({instanceLocation:s,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${u}" is invalid. Expected "${h.join('", "')}".`})}else h==="integer"?(u!=="number"||t%1||t!==t)&&I.push({instanceLocation:s,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${u}" is invalid. Expected "${h}".`}):h!==void 0&&u!==h&&I.push({instanceLocation:s,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${u}" is invalid. Expected "${h}".`});if(g!==void 0&&(u==="object"||u==="array"?Vt(t,g)||I.push({instanceLocation:s,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(g)}.`}):t!==g&&I.push({instanceLocation:s,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(g)}.`})),b!==void 0&&(u==="object"||u==="array"?b.some(B=>Vt(t,B))||I.push({instanceLocation:s,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`}):b.some(B=>t===B)||I.push({instanceLocation:s,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`})),v!==void 0){let B=`${o}/not`;re(t,v,r,n,i,a,s,B).valid&&I.push({instanceLocation:s,keyword:"not",keywordLocation:B,error:'Instance matched "not" schema.'})}let Nn=[];if(k!==void 0){let B=`${o}/anyOf`,M=I.length,H=!1;for(let R=0;R<k.length;R++){let S=k[R],F=Object.create(c),z=re(t,S,r,n,i,p===!0?a:null,s,`${B}/${R}`,F);I.push(...z.errors),H=H||z.valid,z.valid&&Nn.push(F)}H?I.length=M:I.splice(M,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:B,error:"Instance does not match any subschemas."})}if(O!==void 0){let B=`${o}/allOf`,M=I.length,H=!0;for(let R=0;R<O.length;R++){let S=O[R],F=Object.create(c),z=re(t,S,r,n,i,p===!0?a:null,s,`${B}/${R}`,F);I.push(...z.errors),H=H&&z.valid,z.valid&&Nn.push(F)}H?I.length=M:I.splice(M,0,{instanceLocation:s,keyword:"allOf",keywordLocation:B,error:"Instance does not match every subschema."})}if(j!==void 0){let B=`${o}/oneOf`,M=I.length,H=j.filter((R,S)=>{let F=Object.create(c),z=re(t,R,r,n,i,p===!0?a:null,s,`${B}/${S}`,F);return I.push(...z.errors),z.valid&&Nn.push(F),z.valid}).length;H===1?I.length=M:I.splice(M,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:B,error:`Instance does not match exactly one subschema (${H} matches).`})}if((u==="object"||u==="array")&&Object.assign(c,...Nn),X!==void 0){let B=`${o}/if`;if(re(t,X,r,n,i,a,s,B,c).valid){if(K!==void 0){let H=re(t,K,r,n,i,a,s,`${o}/then`,c);H.valid||I.push({instanceLocation:s,keyword:"if",keywordLocation:B,error:'Instance does not match "then" schema.'},...H.errors)}}else if(Q!==void 0){let H=re(t,Q,r,n,i,a,s,`${o}/else`,c);H.valid||I.push({instanceLocation:s,keyword:"if",keywordLocation:B,error:'Instance does not match "else" schema.'},...H.errors)}}if(u==="object"){if(E!==void 0)for(let R of E)R in t||I.push({instanceLocation:s,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${R}".`});let B=Object.keys(t);if(en!==void 0&&B.length<en&&I.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${en} properties.`}),ha!==void 0&&B.length>ha&&I.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${ha} properties.`}),No!==void 0){let R=`${o}/propertyNames`;for(let S in t){let F=`${s}/${ze(S)}`,z=re(S,No,r,n,i,a,F,R);z.valid||I.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:R,error:`Property name "${S}" does not match schema.`},...z.errors)}}if(ma!==void 0){let R=`${o}/dependantRequired`;for(let S in ma)if(S in t){let F=ma[S];for(let z of F)z in t||I.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:R,error:`Instance has "${S}" but does not have "${z}".`})}}if(ga!==void 0)for(let R in ga){let S=`${o}/dependentSchemas`;if(R in t){let F=re(t,ga[R],r,n,i,a,s,`${S}/${ze(R)}`,c);F.valid||I.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:S,error:`Instance has "${R}" but does not match dependant schema.`},...F.errors)}}if(_a!==void 0){let R=`${o}/dependencies`;for(let S in _a)if(S in t){let F=_a[S];if(Array.isArray(F))for(let z of F)z in t||I.push({instanceLocation:s,keyword:"dependencies",keywordLocation:R,error:`Instance has "${S}" but does not have "${z}".`});else{let z=re(t,F,r,n,i,a,s,`${R}/${ze(S)}`);z.valid||I.push({instanceLocation:s,keyword:"dependencies",keywordLocation:R,error:`Instance has "${S}" but does not match dependant schema.`},...z.errors)}}}let M=Object.create(null),H=!1;if(fe!==void 0){let R=`${o}/properties`;for(let S in fe){if(!(S in t))continue;let F=`${s}/${ze(S)}`,z=re(t[S],fe[S],r,n,i,a,F,`${R}/${ze(S)}`);if(z.valid)c[S]=M[S]=!0;else if(H=i,I.push({instanceLocation:s,keyword:"properties",keywordLocation:R,error:`Property "${S}" does not match schema.`},...z.errors),H)break}}if(!H&&Ae!==void 0){let R=`${o}/patternProperties`;for(let S in Ae){let F=new RegExp(S,"u"),z=Ae[S];for(let Ne in t){if(!F.test(Ne))continue;let jo=`${s}/${ze(Ne)}`,Do=re(t[Ne],z,r,n,i,a,jo,`${R}/${ze(S)}`);Do.valid?c[Ne]=M[Ne]=!0:(H=i,I.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:R,error:`Property "${Ne}" matches pattern "${S}" but does not match associated schema.`},...Do.errors))}}}if(!H&<!==void 0){let R=`${o}/additionalProperties`;for(let S in t){if(M[S])continue;let F=`${s}/${ze(S)}`,z=re(t[S],lt,r,n,i,a,F,R);z.valid?c[S]=!0:(H=i,I.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:R,error:`Property "${S}" does not match additional properties schema.`},...z.errors))}}else if(!H&&An!==void 0){let R=`${o}/unevaluatedProperties`;for(let S in t)if(!c[S]){let F=`${s}/${ze(S)}`,z=re(t[S],An,r,n,i,a,F,R);z.valid?c[S]=!0:I.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:R,error:`Property "${S}" does not match unevaluated properties schema.`},...z.errors)}}}else if(u==="array"){ba!==void 0&&t.length>ba&&I.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${t.length} > ${ba}).`}),wa!==void 0&&t.length<wa&&I.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${t.length} < ${wa}).`});let B=t.length,M=0,H=!1;if(ya!==void 0){let R=`${o}/prefixItems`,S=Math.min(ya.length,B);for(;M<S;M++){let F=re(t[M],ya[M],r,n,i,a,`${s}/${M}`,`${R}/${M}`);if(c[M]=!0,!F.valid&&(H=i,I.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:R,error:"Items did not match schema."},...F.errors),H))break}}if(tn!==void 0){let R=`${o}/items`;if(Array.isArray(tn)){let S=Math.min(tn.length,B);for(;M<S;M++){let F=re(t[M],tn[M],r,n,i,a,`${s}/${M}`,`${R}/${M}`);if(c[M]=!0,!F.valid&&(H=i,I.push({instanceLocation:s,keyword:"items",keywordLocation:R,error:"Items did not match schema."},...F.errors),H))break}}else for(;M<B;M++){let S=re(t[M],tn,r,n,i,a,`${s}/${M}`,R);if(c[M]=!0,!S.valid&&(H=i,I.push({instanceLocation:s,keyword:"items",keywordLocation:R,error:"Items did not match schema."},...S.errors),H))break}if(!H&&$o!==void 0){let S=`${o}/additionalItems`;for(;M<B;M++){let F=re(t[M],$o,r,n,i,a,`${s}/${M}`,S);c[M]=!0,F.valid||(H=i,I.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:S,error:"Items did not match additional items schema."},...F.errors))}}}if(Mo!==void 0)if(B===0&&Tt===void 0)I.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&&B<Tt)I.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${B}) than minContains (${Tt}).`});else{let R=`${o}/contains`,S=I.length,F=0;for(let z=0;z<B;z++){let Ne=re(t[z],Mo,r,n,i,a,`${s}/${z}`,R);Ne.valid?(c[z]=!0,F++):I.push(...Ne.errors)}F>=(Tt||0)&&(I.length=S),Tt===void 0&&kn===void 0&&F===0?I.splice(S,0,{instanceLocation:s,keyword:"contains",keywordLocation:R,error:"Array does not contain item matching schema."}):Tt!==void 0&&F<Tt?I.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${Tt} items matching schema. Only ${F} items were found.`}):kn!==void 0&&F>kn&&I.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${kn} items matching schema. ${F} items were found.`})}if(!H&&Po!==void 0){let R=`${o}/unevaluatedItems`;for(M;M<B;M++){if(c[M])continue;let S=re(t[M],Po,r,n,i,a,`${s}/${M}`,R);c[M]=!0,S.valid||I.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:R,error:"Items did not match unevaluated items schema."},...S.errors)}}if(dp)for(let R=0;R<B;R++){let S=t[R],F=typeof S=="object"&&S!==null;for(let z=0;z<B;z++){if(R===z)continue;let Ne=t[z];(S===Ne||F&&(typeof Ne=="object"&&Ne!==null)&&Vt(S,Ne))&&(I.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${R} and ${z}.`}),R=Number.MAX_SAFE_INTEGER,z=Number.MAX_SAFE_INTEGER)}}}else if(u==="number"){if(r==="4"?(qt!==void 0&&(rn===!0&&t<=qt||t<qt)&&I.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${rn?"or equal to ":""} ${qt}.`}),Jt!==void 0&&(nn===!0&&t>=Jt||t>Jt)&&I.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${nn?"or equal to ":""} ${Jt}.`})):(qt!==void 0&&t<qt&&I.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${qt}.`}),Jt!==void 0&&t>Jt&&I.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${Jt}.`}),rn!==void 0&&t<=rn&&I.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${t} is less than ${rn}.`}),nn!==void 0&&t>=nn&&I.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${t} is greater than or equal to ${nn}.`})),In!==void 0){let B=t%In;Math.abs(0-B)>=11920929e-14&&Math.abs(In-B)>=11920929e-14&&I.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${t} is not a multiple of ${In}.`})}}else if(u==="string"){let B=Cn===void 0&&On===void 0?0:_f(t);Cn!==void 0&&B<Cn&&I.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${B} < ${Cn}).`}),On!==void 0&&B>On&&I.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${B} > ${On}).`}),Lo!==void 0&&!new RegExp(Lo,"u").test(t)&&I.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),ee!==void 0&&uo[ee]&&!uo[ee](t)&&I.push({instanceLocation:s,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${ee}".`})}return{valid:I.length===0,errors:I}}var Bi=class{schema;draft;shortCircuit;lookup;constructor(e,r="2019-09",n=!0){this.schema=e,this.draft=r,this.shortCircuit=n,this.lookup=st(e)}validate(e){return re(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,r){r&&(e={...e,$id:r}),st(e,this.lookup)}};var $I=D({Validator:()=>Bi,deepCompareStrict:()=>Vt,toJsonSchema:()=>fo,validatesOnlyStrings:()=>Yr}),yf=new WeakMap;function fo(t,e){let r=!e&&t!=null&&typeof t=="object";if(r){let i=yf.get(t);if(i)return i}let n;if(Ui(t)&&!ae(t))n=t["~standard"].jsonSchema.input({target:"draft-07"});else if(ae(t)){let i=bd(t,!0);_t(i)?n=Sa(ki(i,!0),e):n=Sa(t,e)}else he(t)?n=ff(t):n=t;return r&&n!=null&&typeof n=="object"&&yf.set(t,n),n}function Yr(t){if(!t||typeof t!="object"||Object.keys(t).length===0||Array.isArray(t))return!1;if("type"in t)return typeof t.type=="string"?t.type==="string":Array.isArray(t.type)?t.type.every(e=>e==="string"):!1;if("enum"in t)return Array.isArray(t.enum)&&t.enum.length>0&&t.enum.every(e=>typeof e=="string");if("const"in t)return typeof t.const=="string";if("allOf"in t&&Array.isArray(t.allOf))return t.allOf.some(e=>Yr(e));if("anyOf"in t&&Array.isArray(t.anyOf)||"oneOf"in t&&Array.isArray(t.oneOf)){let e="anyOf"in t?t.anyOf:t.oneOf;return e.length>0&&e.every(r=>Yr(r))}if("not"in t)return!1;if("$ref"in t&&typeof t.$ref=="string"){let e=t.$ref,r=st(t);return r[e]?Yr(r[e]):!1}return!1}function po(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}var wf=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function";function zi(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function ho(t){return t!=null&&typeof t=="object"&&typeof t.next=="function"}async function bf(t,e){try{let r=await t.next();for(;!r.done;)await e?.(r.value),r=await t.next();return r.value}finally{await t.return?.(void 0)}}function*mo(t,e){for(;;){let{value:r,done:n}=be.runWithConfig(qe(t),e.next.bind(e),!0);if(n)break;yield r}}async function*Fi(t,e){let r=e[Symbol.asyncIterator]();for(;;){let{value:n,done:i}=await be.runWithConfig(qe(t),r.next.bind(e),!0);if(i)break;yield n}}var N="0123456789abcdef".split(""),yy=[-2147483648,8388608,32768,128],ot=[24,16,8,0],Hi=[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 ct(t,e){e?(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],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}ct.prototype.update=function(t){if(!this.finalized){var e,r=typeof t;if(r!=="string"){if(r==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var n,i=0,a,s=t.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),e)for(a=this.start;i<s&&a<64;++i)o[a>>>2]|=t[i]<<ot[a++&3];else for(a=this.start;i<s&&a<64;++i)n=t.charCodeAt(i),n<128?o[a>>>2]|=n<<ot[a++&3]:n<2048?(o[a>>>2]|=(192|n>>>6)<<ot[a++&3],o[a>>>2]|=(128|n&63)<<ot[a++&3]):n<55296||n>=57344?(o[a>>>2]|=(224|n>>>12)<<ot[a++&3],o[a>>>2]|=(128|n>>>6&63)<<ot[a++&3],o[a>>>2]|=(128|n&63)<<ot[a++&3]):(n=65536+((n&1023)<<10|t.charCodeAt(++i)&1023),o[a>>>2]|=(240|n>>>18)<<ot[a++&3],o[a>>>2]|=(128|n>>>12&63)<<ot[a++&3],o[a>>>2]|=(128|n>>>6&63)<<ot[a++&3],o[a>>>2]|=(128|n&63)<<ot[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}};ct.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=yy[e&3],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}};ct.prototype.hash=function(){var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,a=this.h5,s=this.h6,o=this.h7,c=this.blocks,l,u,d,f,p,h,g,b,E,v,k;for(l=16;l<64;++l)p=c[l-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[l-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(k=e&r,l=0;l<64;l+=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):(u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),b=t&e,f=b^t&r^k,g=i&a^~i&s,p=o+d+g+Hi[l]+c[l],h=u+f,o=n+p<<0,n=p+h<<0),u=(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),E=n&t,f=E^n&e^b,g=s&o^~s&i,p=a+d+g+Hi[l+1]+c[l+1],h=u+f,s=r+p<<0,r=p+h<<0,u=(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&t^E,g=a&s^~a&o,p=i+d+g+Hi[l+2]+c[l+2],h=u+f,a=e+p<<0,e=p+h<<0,u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),k=e&r,f=k^e&n^v,g=a&s^~a&o,p=i+d+g+Hi[l+3]+c[l+3],h=u+f,i=t+p<<0,t=p+h<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+e<<0,this.h2=this.h2+r<<0,this.h3=this.h3+n<<0,this.h4=this.h4+i<<0,this.h5=this.h5+a<<0,this.h6=this.h6+s<<0,this.h7=this.h7+o<<0};ct.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,a=this.h5,s=this.h6,o=this.h7,c=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[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[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};ct.prototype.toString=ct.prototype.hex;ct.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,a=this.h5,s=this.h6,o=this.h7,c=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,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};ct.prototype.array=ct.prototype.digest;ct.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),e.setUint32(20,this.h5),e.setUint32(24,this.h6),this.is224||e.setUint32(28,this.h7),t};var Gi=(...t)=>new ct(!1,!0).update(t.join("")).hex();var FI=D({sha256:()=>Gi});var JI=D({BaseCache:()=>xf,InMemoryCache:()=>go,defaultHashKeyEncoder:()=>vf,deserializeStoredGeneration:()=>wy,serializeGeneration:()=>by}),vf=(...t)=>Gi(t.join("_"));function wy(t){return t.message!==void 0?{text:t.text,message:Ua(t.message)}:{text:t.text}}function by(t){let e={text:t.text};return t.message!==void 0&&(e.message=t.message.toDict()),e}var xf=class{keyEncoder=vf;makeDefaultKeyEncoder(t){this.keyEncoder=t}},vy=new Map,go=class Ef extends xf{cache;constructor(e){super(),this.cache=e??new Map}lookup(e,r){return Promise.resolve(this.cache.get(this.keyEncoder(e,r))??null)}async update(e,r,n){this.cache.set(this.keyEncoder(e,r),n)}static global(){return new Ef(vy)}};var xy=Object.prototype.toString,Ey=t=>xy.call(t)==="[object Error]",Sy=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 Sf(t){if(!(t&&Ey(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;let{message:e,stack:r}=t;return e==="Load failed"?r===void 0||"__sentry_captured__"in t:e.startsWith("error sending request for url")?!0:Sy.has(e)}function Ty(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Vi(t,e,{min:r=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<r)throw new TypeError(`Expected \`${t}\` to be \u2265 ${r}.`)}}var Ay=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 ky(t,e){let r=Math.max(1,t+1),n=e.randomize?Math.random()+1:1,i=Math.round(n*e.minTimeout*e.factor**(r-1));return i=Math.min(i,e.maxTimeout),i}function Tf(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function Iy({error:t,attemptNumber:e,retriesConsumed:r,startTime:n,options:i}){let a=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(a instanceof Ay)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:e,retriesLeft:s,retriesConsumed:r});if(await i.onFailedAttempt(c),Tf(n,o)<=0)throw a;let l=await i.shouldConsumeRetry(c),u=Tf(n,o);if(u<=0||s<=0)throw a;if(a instanceof TypeError&&!Sf(a)){if(l)throw a;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw a;if(!l)return i.signal?.throwIfAborted(),!1;let d=ky(r,i),f=Math.min(d,u);return f>0&&await new Promise((p,h)=>{let g=()=>{clearTimeout(b),i.signal?.removeEventListener("abort",g),h(i.signal.reason)},b=setTimeout(()=>{i.signal?.removeEventListener("abort",g),p()},f);i.unref&&b.unref?.(),i.signal?.addEventListener("abort",g,{once:!0})}),i.signal?.throwIfAborted(),!0}async function vn(t,e={}){if(e={...e},Ty(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,Vi("factor",e.factor,{min:0,allowInfinity:!1}),Vi("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Vi("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Vi("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let r=0,n=0,i=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){r++;try{e.signal?.throwIfAborted();let a=await t(r);return e.signal?.throwIfAborted(),a}catch(a){await Iy({error:a,attemptNumber:r,retriesConsumed:n,startTime:i,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Zi=Wt(di(),1),iC=D({AsyncCaller:()=>xr}),Cy=[400,401,402,403,404,405,406,407,409],Oy=t=>{if(typeof t!="object"||t===null)return;if("message"in t&&typeof t.message=="string"&&(t.message.startsWith("Cancel")||t.message.startsWith("AbortError"))||"name"in t&&typeof t.name=="string"&&t.name==="AbortError"||"code"in t&&typeof t.code=="string"&&t.code==="ECONNABORTED")throw t;let e="response"in t&&typeof t.response=="object"&&t.response!==null&&"status"in t.response&&typeof t.response.status=="number"?t.response.status:void 0,r="status"in t&&typeof t.status=="number"?t.status:void 0,n=e??r;if(n&&Cy.includes(+n))throw t;if(("error"in t&&typeof t.error=="object"&&t.error!==null&&"code"in t.error&&typeof t.error.code=="string"?t.error.code:void 0)==="insufficient_quota"){let i=new Error("message"in t&&typeof t.message=="string"?t.message:"Insufficient quota");throw i.name="InsufficientQuotaError",i}},xr=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(t){this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.onFailedAttempt=t.onFailedAttempt??Oy,this.queue=new("default"in Zi.default?Zi.default.default:Zi.default)({concurrency:this.maxConcurrency})}async call(t,...e){return this.queue.add(()=>vn(()=>t(...e).catch(r=>{throw r instanceof Error?r:new Error(r)}),{onFailedAttempt:({error:r})=>this.onFailedAttempt?.(r),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,e,...r){if(t.signal){let n;return Promise.race([this.call(e,...r),new Promise((i,a)=>{n=()=>{a(Bt(t.signal))},t.signal?.addEventListener("abort",n,{once:!0})})]).finally(()=>{t.signal&&n&&t.signal.removeEventListener("abort",n)})}return this.call(e,...r)}fetch(...t){return this.call(()=>fetch(...t).then(e=>e.ok?e:Promise.reject(e)))}};var fC=D({AsyncGeneratorWithSetup:()=>Zt,IterableReadableStream:()=>Re,atee:()=>qi,concat:()=>Ji,pipeGeneratorWithSetup:()=>yo}),Re=class _o extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){let r=this.reader.cancel();this.reader.releaseLock(),await r}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){let r=e.getReader();return new _o({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(e){return new _o({async pull(r){let{value:n,done:i}=await e.next();i&&r.close(),r.enqueue(n)},async cancel(r){await e.return(r)}})}};function qi(t,e=2){let r=Array.from({length:e},()=>[]);return r.map(async function*(i){for(;;)if(i.length===0){let a=await t.next();for(let s of r)s.push(a)}else{if(i[0].done)return;yield i.shift().value}})}function Ji(t,e){if(Array.isArray(t)&&Array.isArray(e))return t.concat(e);if(typeof t=="string"&&typeof e=="string")return t+e;if(typeof t=="number"&&typeof e=="number")return t+e;if("concat"in t&&typeof t.concat=="function")return t.concat(e);if(typeof t=="object"&&typeof e=="object"){let r={...t};for(let[n,i]of Object.entries(e))n in r&&!Array.isArray(r[n])?r[n]=Ji(r[n],i):r[n]=i;return r}else throw new Error(`Cannot concat ${typeof t} and ${typeof e}`)}var Zt=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(t){this.generator=t.generator,this.config=t.config,this.signal=t.signal??this.config?.signal,this.setup=new Promise((e,r)=>{be.runWithConfig(qe(t.config),async()=>{this.firstResult=this.signal?rt(t.generator.next(),this.signal):t.generator.next(),t.startSetup?this.firstResult.then(t.startSetup).then(e,r):this.firstResult.then(n=>e(void 0),r)},!0)})}async next(...t){return this.signal?.throwIfAborted(),this.firstResultUsed?be.runWithConfig(qe(this.config),this.signal?async()=>rt(this.generator.next(...t),this.signal):async()=>this.generator.next(...t),!0):(this.firstResultUsed=!0,this.firstResult)}async return(t){return this.generator.return(t)}async throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function yo(t,e,r,n,...i){let a=new Zt({generator:e,startSetup:r,signal:n}),s=await a.setup;return{output:t(a,s,...i),setup:s}}var Ry=Object.prototype.hasOwnProperty;function Ki(t,e){return Ry.call(t,e)}function Yi(t){if(Array.isArray(t)){let r=new Array(t.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(t);let e=[];for(let r in t)Ki(t,r)&&e.push(r);return e}function Fe(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Xi(t){let e=0,r=t.length,n;for(;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function Er(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function kf(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Wi(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(Wi(t[r]))return!0}else if(typeof t=="object"){let r=Yi(t),n=r.length;for(var e=0;e<n;e++)if(Wi(t[r[e]]))return!0}}return!1}function Af(t,e){let r=[t];for(let n in e){let i=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof i<"u"&&r.push(`${n}: ${i}`)}return r.join(`
|
|
158
|
+
`)}var If=class extends Error{constructor(t,e,r,n,i){super(Af(t,{name:e,index:r,operation:n,tree:i})),this.name=e,this.index=r,this.operation=n,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=Af(t,{name:e,index:r,operation:n,tree:i})}};var Cf=D({JsonPatchError:()=>le,_areEquals:()=>xn,applyOperation:()=>Sr,applyPatch:()=>Qr,applyReducer:()=>Py,deepClone:()=>Ny,getValueByPointer:()=>Qi,validate:()=>Of,validator:()=>ea}),le=If,Ny=Fe,Xr={add:function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=t[e];return delete t[e],{newDocument:r,removed:n}},replace:function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:function(t,e,r){let n=Qi(r,this.path);n&&(n=Fe(n));let i=Sr(r,{op:"remove",path:this.from}).removed;return Sr(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},copy:function(t,e,r){let n=Qi(r,this.from);return Sr(r,{op:"add",path:this.path,value:Fe(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:xn(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},$y={add:function(t,e,r){return Xi(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},remove:function(t,e,r){return{newDocument:r,removed:t.splice(e,1)[0]}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:Xr.move,copy:Xr.copy,test:Xr.test,_get:Xr._get};function Qi(t,e){if(e=="")return t;var r={op:"_get",path:e};return Sr(t,r),r.value}function Sr(t,e,r=!1,n=!0,i=!0,a=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):ea(e,0)),e.path===""){let s={newDocument:t};if(e.op==="add")return s.newDocument=e.value,s;if(e.op==="replace")return s.newDocument=e.value,s.removed=t,s;if(e.op==="move"||e.op==="copy")return s.newDocument=Qi(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=xn(t,e.value),s.test===!1)throw new le("Test operation failed","TEST_OPERATION_FAILED",a,e,t);return s.newDocument=t,s}else{if(e.op==="remove")return s.removed=t,s.newDocument=null,s;if(e.op==="_get")return e.value=t,s;if(r)throw new le("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",a,e,t);return s}}else{n||(t=Fe(t));let s=(e.path||"").split("/"),o=t,c=1,l=s.length,u,d,f;for(typeof r=="function"?f=r:f=ea;;){if(d=s[c],d&&d.indexOf("~")!=-1&&(d=kf(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&&u===void 0&&(o[d]===void 0?u=s.slice(0,c).join("/"):c==l-1&&(u=e.path),u!==void 0&&f(e,0,t,u)),c++,Array.isArray(o)){if(d==="-")d=o.length;else{if(r&&!Xi(d))throw new le("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",a,e,t);Xi(d)&&(d=~~d)}if(c>=l){if(r&&e.op==="add"&&d>o.length)throw new le("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,e,t);let p=$y[e.op].call(e,o,d,t);if(p.test===!1)throw new le("Test operation failed","TEST_OPERATION_FAILED",a,e,t);return p}}else if(c>=l){let p=Xr[e.op].call(e,o,d,t);if(p.test===!1)throw new le("Test operation failed","TEST_OPERATION_FAILED",a,e,t);return p}if(o=o[d],r&&c<l&&(!o||typeof o!="object"))throw new le("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",a,e,t)}}}function Qr(t,e,r,n=!0,i=!0){if(r&&!Array.isArray(e))throw new le("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=Fe(t));let a=new Array(e.length);for(let s=0,o=e.length;s<o;s++)a[s]=Sr(t,e[s],r,!0,i,s),t=a[s].newDocument;return a.newDocument=t,a}function Py(t,e,r){let n=Sr(t,e);if(n.test===!1)throw new le("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function ea(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new le("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(Xr[t.op]){if(typeof t.path!="string")throw new le("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new le('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new le("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new le("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Wi(t.value))throw new le("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var i=t.path.split("/").length,a=n.split("/").length;if(i!==a+1&&i!==a)throw new le("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new le("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var s=Of([{op:"_get",path:t.from,value:void 0}],r);if(s&&s.name==="OPERATION_PATH_UNRESOLVABLE")throw new le("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new le("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function Of(t,e,r){try{if(!Array.isArray(t))throw new le("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Qr(Fe(e),Fe(t),r||!0);else{r=r||ea;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(i){if(i instanceof le)return i;throw i}}function xn(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),i,a,s;if(r&&n){if(a=t.length,a!=e.length)return!1;for(i=a;i--!==0;)if(!xn(t[i],e[i]))return!1;return!0}if(r!=n)return!1;var o=Object.keys(t);if(a=o.length,a!==Object.keys(e).length)return!1;for(i=a;i--!==0;)if(!e.hasOwnProperty(o[i]))return!1;for(i=a;i--!==0;)if(s=o[i],!xn(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}function Rf(t,e,r,n,i){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var a=Yi(e),s=Yi(t),o=!1,c=s.length-1;c>=0;c--){var l=s[c],u=t[l];if(Ki(e,l)&&!(e[l]===void 0&&u!==void 0&&Array.isArray(e)===!1)){var d=e[l];typeof u=="object"&&u!=null&&typeof d=="object"&&d!=null&&Array.isArray(u)===Array.isArray(d)?Rf(u,d,r,n+"/"+Er(l),i):u!==d&&(i&&r.push({op:"test",path:n+"/"+Er(l),value:Fe(u)}),r.push({op:"replace",path:n+"/"+Er(l),value:Fe(d)}))}else Array.isArray(t)===Array.isArray(e)?(i&&r.push({op:"test",path:n+"/"+Er(l),value:Fe(u)}),r.push({op:"remove",path:n+"/"+Er(l)}),o=!0):(i&&r.push({op:"test",path:n,value:t}),r.push({op:"replace",path:n,value:e}))}if(!(!o&&a.length==s.length))for(var c=0;c<a.length;c++){var l=a[c];!Ki(t,l)&&e[l]!==void 0&&r.push({op:"add",path:n+"/"+Er(l),value:Fe(e[l])})}}}function xC(t,e,r=!1){var n=[];return Rf(t,e,n,"",r),n}({...Cf});var $C=D({LogStreamCallbackHandler:()=>ra,RunLog:()=>ta,RunLogPatch:()=>Et,isLogStreamHandler:()=>bo}),Et=class{ops;constructor(t){this.ops=t.ops??[]}concat(t){let e=this.ops.concat(t.ops),r=Qr({},e);return new ta({ops:e,state:r[r.length-1].newDocument})}},ta=class wo extends Et{state;constructor(e){super(e),this.state=e.state}concat(e){let r=this.ops.concat(e.ops),n=Qr(this.state,e.ops);return new wo({ops:r,state:n[n.length-1].newDocument})}static fromRunLogPatch(e){let r=Qr({},e.ops);return new wo({ops:e.ops,state:r[r.length-1].newDocument})}},bo=t=>t.name==="log_stream_tracer";async function Nf(t,e){if(e==="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}=t;if(["retriever","llm","prompt"].includes(t.run_type))return r;if(!(Object.keys(r).length===1&&r?.input===""))return r.input}async function $f(t,e){let{outputs:r}=t;return e==="original"||["retriever","llm","prompt"].includes(t.run_type)?r:r!==void 0&&Object.keys(r).length===1&&r?.output!==void 0?r.output:r}function My(t){return t!==void 0&&t.message!==void 0}var ra=class extends et{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(t){super({_awaitHandler:!0,...t}),this.autoClose=t?.autoClose??!0,this.includeNames=t?.includeNames,this.includeTypes=t?.includeTypes,this.includeTags=t?.includeTags,this.excludeNames=t?.excludeNames,this.excludeTypes=t?.excludeTypes,this.excludeTags=t?.excludeTags,this._schemaFormat=t?._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(t){}_includeRun(t){if(t.id===this.rootId)return!1;let e=t.tags??[],r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t.run_type)),this.includeTags!==void 0&&(r=r||e.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t.run_type)),this.excludeTags!==void 0&&(r=r&&e.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(t,e){for await(let r of e){if(t!==this.rootId){let n=this.keyMapByRunId[t];n&&await this.writer.write(new Et({ops:[{op:"add",path:`/logs/${n}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(t){if(this.rootId===void 0&&(this.rootId=t.id,await this.writer.write(new Et({ops:[{op:"replace",path:"",value:{id:t.id,name:t.name,type:t.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(t))return;this.counterMapByRunName[t.name]===void 0&&(this.counterMapByRunName[t.name]=0),this.counterMapByRunName[t.name]+=1;let e=this.counterMapByRunName[t.name];this.keyMapByRunId[t.id]=e===1?t.name:`${t.name}:${e}`;let r={id:t.id,name:t.name,type:t.run_type,tags:t.tags??[],metadata:t.extra?.metadata??{},start_time:new Date(t.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await Nf(t,this._schemaFormat)),await this.writer.write(new Et({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[t.id]}`,value:r}]}))}async onRunUpdate(t){try{let e=this.keyMapByRunId[t.id];if(e===void 0)return;let r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${e}/inputs`,value:await Nf(t,this._schemaFormat)}),r.push({op:"add",path:`/logs/${e}/final_output`,value:await $f(t,this._schemaFormat)}),t.end_time!==void 0&&r.push({op:"add",path:`/logs/${e}/end_time`,value:new Date(t.end_time).toISOString()});let n=new Et({ops:r});await this.writer.write(n)}finally{if(t.id===this.rootId){let e=new Et({ops:[{op:"replace",path:"/final_output",value:await $f(t,this._schemaFormat)}]});await this.writer.write(e),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(t,e,r){let n=this.keyMapByRunId[t.id];if(n===void 0)return;let i=t.inputs.messages!==void 0,a;i?My(r?.chunk)?a=r?.chunk:a=new Or({id:`run-${t.id}`,content:e}):a=e;let s=new Et({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:e},{op:"add",path:`/logs/${n}/streamed_output/-`,value:a}]});await this.writer.write(s)}};var DC=D({ChatGenerationChunk:()=>jy,GenerationChunk:()=>En,RUN_KEY:()=>Ly}),Ly="__run",En=class Pf{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new Pf({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},jy=class Mf extends En{message;constructor(e){super(e),this.message=e.message}concat(e){return new Mf({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}};function na({name:t,serialized:e}){return t!==void 0?t:e?.name!==void 0?e.name:e?.id!==void 0&&Array.isArray(e?.id)?e.id[e.id.length-1]:"Unnamed"}var Lf=t=>t.name==="event_stream_tracer",jf=class extends et{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(t){super({_awaitHandler:!0,...t}),this.autoClose=t?.autoClose??!0,this.includeNames=t?.includeNames,this.includeTypes=t?.includeTypes,this.includeTags=t?.includeTags,this.excludeNames=t?.excludeNames,this.excludeTypes=t?.excludeTypes,this.excludeTags=t?.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(t){}_includeRun(t){let e=t.tags??[],r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t.runType)),this.includeTags!==void 0&&(r=r||e.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t.runType)),this.excludeTags!==void 0&&(r=r&&e.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(t,e){let r=await e.next();if(r.done)return;let n=this.runInfoMap.get(t);if(n===void 0){yield r.value;return}function i(s,o){return s==="llm"&&typeof o=="string"?new En({text:o}):o}let a=this.tappedPromises.get(t);if(a===void 0){let s;a=new Promise(o=>{s=o}),this.tappedPromises.set(t,a);try{let o={event:`on_${n.runType}_stream`,run_id:t,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 e)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 e)yield s}}async send(t,e){this.readableStreamClosed||this._includeRun(e)&&await this.writer.write(t)}async sendEndEvent(t,e){let r=this.tappedPromises.get(t.run_id);r!==void 0?r.then(()=>{this.send(t,e)}):await this.send(t,e)}async onLLMStart(t){let e=na(t),r=t.inputs.messages!==void 0?"chat_model":"llm",n={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:r,inputs:t.inputs};this.runInfoMap.set(t.id,n);let i=`on_${r}_start`;await this.send({event:i,data:{input:t.inputs},name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},n)}async onLLMNewToken(t,e,r){let n=this.runInfoMap.get(t.id),i,a;if(n===void 0)throw new Error(`onLLMNewToken: Run ID ${t.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 Or({content:e,id:`run-${t.id}`}):i=r.chunk.message;else if(n.runType==="llm")a="on_llm_stream",r?.chunk===void 0?i=new En({text:e}):i=r.chunk;else throw new Error(`Unexpected run type ${n.runType}`);await this.send({event:a,data:{chunk:i},run_id:t.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(t){let e=this.runInfoMap.get(t.id);this.runInfoMap.delete(t.id);let r;if(e===void 0)throw new Error(`onLLMEnd: Run ID ${t.id} not found in run map.`);let n=t.outputs?.generations,i;if(e.runType==="chat_model"){for(let a of n??[]){if(i!==void 0)break;i=a[0]?.message}r="on_chat_model_end"}else if(e.runType==="llm")i={generations:n?.map(a=>a.map(s=>({text:s.text,generationInfo:s.generationInfo}))),llmOutput:t.outputs?.llmOutput??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${e.runType}`);await this.sendEndEvent({event:r,data:{output:i,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async onChainStart(t){let e=na(t),r=t.run_type??"chain",n={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:t.run_type},i={};t.inputs.input===""&&Object.keys(t.inputs).length===1?(i={},n.inputs={}):t.inputs.input!==void 0?(i.input=t.inputs.input,n.inputs=t.inputs.input):(i.input=t.inputs,n.inputs=t.inputs),this.runInfoMap.set(t.id,n),await this.send({event:`on_${r}_start`,data:i,name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},n)}async onChainEnd(t){let e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onChainEnd: Run ID ${t.id} not found in run map.`);let r=`on_${t.run_type}_end`,n=t.inputs??e.inputs??{},i={output:t.outputs?.output??t.outputs,input:n};n.input&&Object.keys(n).length===1&&(i.input=n.input,e.inputs=n.input),await this.sendEndEvent({event:r,data:i,run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata??{}},e)}async onToolStart(t){let e=na(t),r={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:"tool",inputs:t.inputs??{}};this.runInfoMap.set(t.id,r),await this.send({event:"on_tool_start",data:{input:t.inputs??{}},name:e,run_id:t.id,tags:t.tags??[],metadata:t.extra?.metadata??{}},r)}async onToolEnd(t){let e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onToolEnd: Run ID ${t.id} not found in run map.`);if(e.inputs===void 0)throw new Error(`onToolEnd: Run ID ${t.id} is a tool call, and is expected to have traced inputs.`);let r=t.outputs?.output===void 0?t.outputs:t.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async onToolError(t){let e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onToolEnd: Run ID ${t.id} not found in run map.`);if(e.inputs===void 0)throw new Error(`onToolEnd: Run ID ${t.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:e.inputs,error:t.error},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async onRetrieverStart(t){let e=na(t),r={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:"retriever",inputs:{query:t.inputs.query}};this.runInfoMap.set(t.id,r),await this.send({event:"on_retriever_start",data:{input:{query:t.inputs.query}},name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},r)}async onRetrieverEnd(t){let e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onRetrieverEnd: Run ID ${t.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:t.outputs?.documents??t.outputs,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async handleCustomEvent(t,e,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:t,tags:n.tags,metadata:n.metadata,data:e},n)}async finish(){let t=[...this.tappedPromises.values()];Promise.all(t).finally(()=>{this.writer.close()})}};var vo=class extends et{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:t,onStart:e,onEnd:r,onError:n}){super({_awaitHandler:!0}),this.config=t,this.argOnStart=e,this.argOnEnd=r,this.argOnError=n}persistRun(t){return Promise.resolve()}async onRunCreate(t){this.rootId||(this.rootId=t.id,this.argOnStart&&await this.argOnStart(t,this.config))}async onRunUpdate(t){t.id===this.rootId&&(t.error?this.argOnError&&await this.argOnError(t,this.config):this.argOnEnd&&await this.argOnEnd(t,this.config))}};function Sn(t){return t?t.lc_runnable:!1}var Df=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(t){this.includeNames=t.includeNames,this.includeTypes=t.includeTypes,this.includeTags=t.includeTags,this.excludeNames=t.excludeNames,this.excludeTypes=t.excludeTypes,this.excludeTags=t.excludeTags}includeEvent(t,e){let r=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,n=t.tags??[];return this.includeNames!==void 0&&(r=r||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e)),this.includeTags!==void 0&&(r=r||n.some(i=>this.includeTags?.includes(i))),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e)),this.excludeTags!==void 0&&(r=r&&n.every(i=>!this.excludeTags?.includes(i))),r}},Uf=t=>btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");function xo(t){return t.replace(/[^a-zA-Z-_0-9]/g,"_")}var Dy=["*","_","`"];function Uy(t){let e="";for(let[r,n]of Object.entries(t))e+=` classDef ${r} ${n};
|
|
159
|
+
`;return e}function Bf(t,e,r){let{firstNode:n,lastNode:i,nodeColors:a,withStyles:s=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=r??{},l=s?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
|
|
160
|
+
graph TD;
|
|
161
|
+
`:`graph TD;
|
|
162
|
+
`;if(s){let h="default",g={[h]:"{0}({1})"};n!==void 0&&(g[n]="{0}([{1}]):::first"),i!==void 0&&(g[i]="{0}([{1}]):::last");for(let[b,E]of Object.entries(t)){let v=E.name.split(":").pop()??"",k=Dy.some(j=>v.startsWith(j)&&v.endsWith(j))?`<p>${v}</p>`:v;Object.keys(E.metadata??{}).length&&(k+=`<hr/><small><em>${Object.entries(E.metadata??{}).map(([j,X])=>`${j} = ${X}`).join(`
|
|
163
|
+
`)}</em></small>`);let O=(g[b]??g[h]).replace("{0}",xo(b)).replace("{1}",k);l+=` ${O}
|
|
164
|
+
`}}let u={};for(let h of e){let g=h.source.split(":"),b=h.target.split(":"),E=g.filter((v,k)=>v===b[k]).join(":");u[E]||(u[E]=[]),u[E].push(h)}let d=new Set;function f(h){return[...h].sort((g,b)=>g.split(":").length-b.split(":").length)}function p(h,g){let b=h.length===1&&h[0].source===h[0].target;if(g&&!b){let v=g.split(":").pop();if(d.has(g))throw new Error(`Found duplicate subgraph '${v}' at '${g} -- 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(g),l+=` subgraph ${v}
|
|
165
|
+
`}let E=f(Object.keys(u).filter(v=>v.startsWith(`${g}:`)&&v!==g&&v.split(":").length===g.split(":").length+1));for(let v of E)p(u[v],v);for(let v of h){let{source:k,target:O,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?" -.-> ":" --> ";l+=` ${xo(k)}${K}${xo(O)};
|
|
166
|
+
`}g&&!b&&(l+=` end
|
|
167
|
+
`)}p(u[""]??[],"");for(let h in u)!h.includes(":")&&h!==""&&p(u[h],h);return s&&(l+=Uy(a??{})),l}async function zf(t,e){let r=e?.backgroundColor??"white",n=e?.imageType??"png",i=Uf(t);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 iO=D({Graph:()=>ia});function By(t,e){if(t!==void 0&&!$t(t))return t;if(Sn(e))try{let r=e.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return e.getName()}else return e.name??"UnknownSchema"}function zy(t){return Sn(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...fo(t.data.schema),title:t.data.name}}}var ia=class Gf{nodes={};edges=[];constructor(e){this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((r,n)=>{e[r.id]=$t(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:e[r.id],...zy(r)})),edges:this.edges.map(r=>{let n={source:e[r.source],target:e[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(e,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:e,name:By(r,e),metadata:n};return this.nodes[i]=a,a}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(r=>r.source!==e.id&&r.target!==e.id)}addEdge(e,r,n,i){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);let a={source:e.id,target:r.id,data:n,conditional:i};return this.edges.push(a),a}firstNode(){return Ff(this)}lastNode(){return Hf(this)}extend(e,r=""){let n=r;Object.values(e.nodes).map(c=>c.id).every($t)&&(n="");let i=c=>n?`${n}:${c}`:c;Object.entries(e.nodes).forEach(([c,l])=>{this.nodes[i(c)]={...l,id:i(c)}});let a=e.edges.map(c=>({...c,source:i(c.source),target:i(c.target)}));this.edges=[...this.edges,...a];let s=e.firstNode(),o=e.lastNode();return[s?{id:i(s.id),data:s.data}:void 0,o?{id:i(o.id),data:o.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&Ff(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&Hf(this,[e.id])&&this.removeNode(e)}reid(){let e=Object.fromEntries(Object.values(this.nodes).map(i=>[i.id,i.name])),r=new Map;Object.values(e).forEach(i=>{r.set(i,(r.get(i)||0)+1)});let n=i=>{let a=e[i];return $t(i)&&r.get(a)===1?a:i};return new Gf({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(e){let{withStyles:r,curveStyle:n,nodeColors:i={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:a}=e??{},s=this.reid(),o=s.firstNode(),c=s.lastNode();return Bf(s.nodes,s.edges,{firstNode:o?.id,lastNode:c?.id,withStyles:r,curveStyle:n,nodeColors:i,wrapLabelNWords:a})}async drawMermaidPng(e){return zf(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}};function Ff(t,e=[]){let r=new Set(t.edges.filter(i=>!e.includes(i.source)).map(i=>i.target)),n=[];for(let i of Object.values(t.nodes))!e.includes(i.id)&&!r.has(i.id)&&n.push(i);return n.length===1?n[0]:void 0}function Hf(t,e=[]){let r=new Set(t.edges.filter(i=>!e.includes(i.target)).map(i=>i.source)),n=[];for(let i of Object.values(t.nodes))!e.includes(i.id)&&!r.has(i.id)&&n.push(i);return n.length===1?n[0]:void 0}function Vf(t){let e=new TextEncoder,r=new ReadableStream({async start(n){for await(let i of t)n.enqueue(e.encode(`event: data
|
|
169
|
+
data: ${JSON.stringify(i)}
|
|
170
|
+
|
|
171
|
+
`));n.enqueue(e.encode(`event: end
|
|
172
|
+
|
|
173
|
+
`)),n.close()}});return Re.fromReadableStream(r)}function ge(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}var _e=class extends ft{lc_runnable=!0;name;getName(t){let e=this.name??this.constructor.lc_name()??this.constructor.name;return t?`${e}${t}`:e}withRetry(t){return new Wf({bound:this,kwargs:{},config:{},maxAttemptNumber:t?.stopAfterAttempt,...t})}withConfig(t){return new aa({bound:this,config:t,kwargs:{}})}withFallbacks(t){let e=Array.isArray(t)?t:t.fallbacks;return new Gy({runnable:this,fallbacks:e})}_getOptionsList(t,e=0){if(Array.isArray(t)&&t.length!==e)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${t.length} options for ${e} inputs`);if(Array.isArray(t))return t.map(Y);if(e>1&&!Array.isArray(t)&&t.runId){console.warn("Provided runId will be used only for the first element of the batch.");let r=Object.fromEntries(Object.entries(t).filter(([n])=>n!=="runId"));return Array.from({length:e},(n,i)=>Y(i===0?t:r))}return Array.from({length:e},()=>Y(t))}async batch(t,e,r){let n=this._getOptionsList(e??{},t.length),i=new xr({maxConcurrency:n[0]?.maxConcurrency??r?.maxConcurrency,onFailedAttempt:s=>{throw s}}),a=t.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(t,e){yield this.invoke(t,e)}async stream(t,e){let r=Y(e),n=new Zt({generator:this._streamIterator(t,r),config:r});return await n.setup,Re.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(t){let e;t===void 0?e=Y(t):e=Y({callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,runName:t.runName,configurable:t.configurable,recursionLimit:t.recursionLimit,maxConcurrency:t.maxConcurrency,runId:t.runId,timeout:t.timeout,signal:t.signal});let r={...t};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,[e,r]}async _callWithConfig(t,e,r){let n=Y(r),i=await(await Ze(n))?.handleChainStart(this.toJSON(),ge(e,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName());delete n.runId;let a;try{a=await rt(t.call(this,e,n,i),n.signal)}catch(s){throw await i?.handleChainError(s),s}return await i?.handleChainEnd(ge(a,"output")),a}async _batchWithConfig(t,e,r,n){let i=this._getOptionsList(r??{},e.length),a=await Promise.all(i.map(Ze)),s=await Promise.all(a.map(async(c,l)=>{let u=await c?.handleChainStart(this.toJSON(),ge(e[l],"input"),i[l].runId,i[l].runType,void 0,void 0,i[l].runName??this.getName());return delete i[l].runId,u})),o;try{o=await rt(t.call(this,e,i,s,n),i?.[0]?.signal)}catch(c){throw await Promise.all(s.map(l=>l?.handleChainError(c))),c}return await Promise.all(s.map(c=>c?.handleChainEnd(ge(o,"output")))),o}_concatOutputChunks(t,e){return Ji(t,e)}async*_transformStreamWithConfig(t,e,r){let n,i=!0,a,s=!0,o=Y(r),c=await Ze(o),l=this;async function*u(){for await(let f of t){if(i)if(n===void 0)n=f;else try{n=l._concatOutputChunks(n,f)}catch{n=void 0,i=!1}yield f}}let d;try{let f=await yo(e.bind(this),u(),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(Lf),h=f.output;p!==void 0&&d!==void 0&&(h=p.tapOutputIterable(d.runId,h));let g=d?.handlers.find(bo);g!==void 0&&d!==void 0&&(h=g.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(t){let e=new ia,r=e.addNode({name:`${this.getName()}Input`,schema:vt.any()}),n=e.addNode(this),i=e.addNode({name:`${this.getName()}Output`,schema:vt.any()});return e.addEdge(r,n),e.addEdge(n,i),e}pipe(t){return new Kf({first:this,last:Tr(t)})}pick(t){return this.pipe(new Zy(t))}assign(t){return this.pipe(new Vy(new sa({steps:t})))}async*transform(t,e){let r;for await(let n of t)r===void 0?r=n:r=this._concatOutputChunks(r,n);yield*this._streamIterator(r,Y(e))}async*streamLog(t,e,r){let n=new ra({...r,autoClose:!1,_schemaFormat:"original"}),i=Y(e);yield*this._streamLog(t,n,i)}async*_streamLog(t,e,r){let{callbacks:n}=r;if(n===void 0)r.callbacks=[e];else if(Array.isArray(n))r.callbacks=n.concat([e]);else{let o=n.copy();o.addHandler(e,!0),r.callbacks=o}let i=this.stream(t,r);async function a(){try{let o=await i;for await(let c of o){let l=new Et({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await e.writer.write(l)}}finally{await e.writer.close()}}let s=a();try{for await(let o of e)yield o}finally{await s}}streamEvents(t,e,r){let n;if(e.version==="v1")n=this._streamEventsV1(t,e,r);else if(e.version==="v2")n=this._streamEventsV2(t,e,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return e.encoding==="text/event-stream"?Vf(n):Re.fromAsyncGenerator(n)}async*_streamEventsV2(t,e,r){let n=new jf({...r,autoClose:!1}),i=Y(e),a=i.runId??He();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 l(){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(t,{...i,signal:p}),g=n.tapOutputIterable(a,h);for await(let b of g)if(o.signal.aborted)break}finally{await n.finish()}}let u=l(),d=!1,f;try{for await(let p of n){if(!d){p.data.input=t,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 u}}async*_streamEventsV1(t,e,r){let n,i=!1,a=Y(e),s=a.tags??[],o=a.metadata??{},c=a.runName??this.getName(),l=new ra({...r,autoClose:!1,_schemaFormat:"streaming_events"}),u=new Df({...r}),d=this._streamLog(t,l,a);for await(let p of d){if(n?n=n.concat(p):n=ta.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 E={...n.state},v={run_id:E.id,event:`on_${E.type}_start`,name:c,tags:s,metadata:o,data:{input:t}};u.includeEvent(v,E.type)&&(yield v)}let h=p.ops.filter(E=>E.path.startsWith("/logs/")).map(E=>E.path.split("/")[2]),g=[...new Set(h)];for(let E of g){let v,k={},O=n.state.logs[E];if(O.end_time===void 0?O.streamed_output.length>0?v="stream":v="start":v="end",v==="start")O.inputs!==void 0&&(k.input=O.inputs);else if(v==="end")O.inputs!==void 0&&(k.input=O.inputs),k.output=O.final_output;else if(v==="stream"){let j=O.streamed_output.length;if(j!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${j} instead. Encountered in: "${O.name}"`);k={chunk:O.streamed_output[0]},O.streamed_output=[]}yield{event:`on_${O.type}_${v}`,name:O.name,run_id:O.id,tags:O.tags,metadata:O.metadata,data:k}}let{state:b}=n;if(b.streamed_output.length>0){let E=b.streamed_output.length;if(E!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${E} instead. Encountered in: "${b.name}"`);let v={chunk:b.streamed_output[0]};b.streamed_output=[];let k={event:`on_${b.type}_stream`,run_id:b.id,tags:s,metadata:o,name:c,data:v};u.includeEvent(k,b.type)&&(yield k)}}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}};u.includeEvent(p,f.type)&&(yield p)}}static isRunnable(t){return Sn(t)}withListeners({onStart:t,onEnd:e,onError:r}){return new aa({bound:this,config:{},configFactories:[n=>({callbacks:[new vo({config:n,onStart:t,onEnd:e,onError:r})]})]})}asTool(t){return qy(this,t)}},aa=class qf extends _e{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(e){super(e),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){let r=gn(this.config,...e);return gn(r,...this.configFactories?await Promise.all(this.configFactories.map(async n=>await n(r))):[])}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new Wf({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,r){return this.bound.invoke(e,await this._mergeConfig(r,this.kwargs))}async batch(e,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(e,i,n)}_concatOutputChunks(e,r){return this.bound._concatOutputChunks(e,r)}async*_streamIterator(e,r){yield*this.bound._streamIterator(e,await this._mergeConfig(Y(r),this.kwargs))}async stream(e,r){return this.bound.stream(e,await this._mergeConfig(Y(r),this.kwargs))}async*transform(e,r){yield*this.bound.transform(e,await this._mergeConfig(Y(r),this.kwargs))}streamEvents(e,r,n){let i=this,a=async function*(){yield*i.bound.streamEvents(e,{...await i._mergeConfig(Y(r),i.kwargs),version:r.version},n)};return Re.fromAsyncGenerator(a())}static isRunnableBinding(e){return e.bound&&_e.isRunnable(e.bound)}withListeners({onStart:e,onEnd:r,onError:n}){return new qf({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[i=>({callbacks:[new vo({config:i,onStart:e,onEnd:r,onError:n})]})]})}},IO=class Jf extends _e{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(e){super(e),this.bound=e.bound}async invoke(e,r){return this._callWithConfig(this._invoke.bind(this),e,r)}async _invoke(e,r,n){return this.bound.batch(e,ue(r,{callbacks:n?.getChild()}))}withListeners({onStart:e,onEnd:r,onError:n}){return new Jf({bound:this.bound.withListeners({onStart:e,onEnd:r,onError:n})})}},Wf=class extends aa{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(t){super(t),this.maxAttemptNumber=t.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=t.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(t,e,r){let n=t>1?`retry:attempt:${t}`:void 0;return ue(e,{callbacks:r?.getChild(n)})}async _invoke(t,e,r){return vn(n=>super.invoke(t,this._patchConfigForRetry(n,e,r)),{onFailedAttempt:({error:n})=>this.onFailedAttempt(n,t),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(t,e){return this._callWithConfig(this._invoke.bind(this),t,e)}async _batch(t,e,r,n){let i={};try{await vn(async a=>{let s=t.map((d,f)=>f).filter(d=>i[d.toString()]===void 0||i[d.toString()]instanceof Error),o=s.map(d=>t[d]),c=s.map(d=>this._patchConfigForRetry(a,e?.[d],r?.[d])),l=await super.batch(o,c,{...n,returnExceptions:!0}),u;for(let d=0;d<l.length;d+=1){let f=l[d],p=s[d];f instanceof Error&&u===void 0&&(u=f,u.input=o[d]),i[p.toString()]=f}if(u)throw u;return l},{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(t,e,r){return this._batchWithConfig(this._batch.bind(this),t,e,r)}},Kf=class Tn extends _e{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(e){super(e),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,r){let n=Y(r),i=await(await Ze(n))?.handleChainStart(this.toJSON(),ge(e,"input"),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let a=e,s;try{let o=[this.first,...this.middle];for(let c=0;c<o.length;c+=1)a=await rt(o[c].invoke(a,ue(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,ue(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(e,r,n){let i=this._getOptionsList(r??{},e.length),a=await Promise.all(i.map(Ze)),s=await Promise.all(a.map(async(c,l)=>{let u=await c?.handleChainStart(this.toJSON(),ge(e[l],"input"),i[l].runId,void 0,void 0,void 0,i[l].runName);return delete i[l].runId,u})),o=e;try{for(let c=0;c<this.steps.length;c+=1)o=await rt(this.steps[c].batch(o,s.map((l,u)=>{let d=l?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return ue(i[u],{callbacks:d})}),n),i[0]?.signal)}catch(c){throw await Promise.all(s.map(l=>l?.handleChainError(c))),c}return await Promise.all(s.map(c=>c?.handleChainEnd(ge(o,"output")))),o}_concatOutputChunks(e,r){return this.last._concatOutputChunks(e,r)}async*_streamIterator(e,r){let n=await Ze(r),{runId:i,...a}=r??{},s=await n?.handleChainStart(this.toJSON(),ge(e,"input"),i,void 0,void 0,void 0,a?.runName),o=[this.first,...this.middle,this.last],c=!0,l;async function*u(){yield e}try{let d=o[0].transform(u(),ue(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,ue(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(l===void 0)l=f;else try{l=this._concatOutputChunks(l,f)}catch{l=void 0,c=!1}}catch(d){throw await s?.handleChainError(d),d}await s?.handleChainEnd(ge(l,"output"))}getGraph(e){let r=new ia,n=null;return this.steps.forEach((i,a)=>{let s=i.getGraph(e);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(e){return Tn.isRunnableSequence(e)?new Tn({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new Tn({first:this.first,middle:[...this.middle,this.last],last:Tr(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&_e.isRunnable(e)}static from([e,...r],n){let i={};return typeof n=="string"?i.name=n:n!==void 0&&(i=n),new Tn({...i,first:Tr(e),middle:r.slice(0,-1).map(Tr),last:Tr(r[r.length-1])})}},sa=class Yf extends _e{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),this.steps={};for(let[r,n]of Object.entries(e.steps))this.steps[r]=Tr(n)}static from(e){return new Yf({steps:e})}async invoke(e,r){let n=Y(r),i=await(await Ze(n))?.handleChainStart(this.toJSON(),{input:e},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(e,ue(n,{callbacks:i?.getChild(`map:key:${o}`)}))});await rt(Promise.all(s),n.signal)}catch(s){throw await i?.handleChainError(s),s}return await i?.handleChainEnd(a),a}async*_transform(e,r,n){let i={...this.steps},a=qi(e,Object.keys(i).length),s=new Map(Object.entries(i).map(([o,c],l)=>{let u=c.transform(a[l],ue(n,{callbacks:r?.getChild(`map:key:${o}`)}));return[o,u.next().then(d=>({key:o,gen:u,result:d}))]}));for(;s.size;){let{key:o,result:c,gen:l}=await rt(Promise.race(s.values()),n?.signal);s.delete(o),c.done||(yield{[o]:c.value},s.set(o,l.next().then(u=>({key:o,gen:l,result:u}))))}}transform(e,r){return this._transformStreamWithConfig(e,this._transform.bind(this),r)}async stream(e,r){async function*n(){yield e}let i=Y(r),a=new Zt({generator:this.transform(n(),i),config:i});return await a.setup,Re.fromAsyncGenerator(a)}},Fy=class Xf extends _e{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(e){if(super(e),!Si(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,r){let[n]=this._getOptionsList(r??{},1),i=await Ze(n);return rt(this.func(ue(n,{callbacks:i}),e),n?.signal)}async*_streamIterator(e,r){let[n]=this._getOptionsList(r??{},1),i=await this.invoke(e,r);if(zi(i)){for await(let a of i)n?.signal?.throwIfAborted(),yield a;return}if(wf(i)){for(;;){n?.signal?.throwIfAborted();let a=i.next();if(a.done)break;yield a.value}return}yield i}static from(e){return new Xf({func:e})}};function Hy(t){if(Si(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var Qf=class ep extends _e{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(e){if(Si(e.func))return Fy.from(e.func);super(e),Hy(e.func),this.func=e.func}static from(e){return new ep({func:e})}async _invoke(e,r,n){return new Promise((i,a)=>{let s=ue(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??25)-1});be.runWithConfig(qe(s),async()=>{try{let o=await this.func(e,{...s});if(o&&_e.isRunnable(o)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(e,{...s,recursionLimit:(s.recursionLimit??25)-1})}else if(zi(o)){let c;for await(let l of Fi(s,o))if(r?.signal?.throwIfAborted(),c===void 0)c=l;else try{c=this._concatOutputChunks(c,l)}catch{c=l}o=c}else if(po(o)){let c;for(let l of mo(s,o))if(r?.signal?.throwIfAborted(),c===void 0)c=l;else try{c=this._concatOutputChunks(c,l)}catch{c=l}o=c}i(o)}catch(o){a(o)}})})}async invoke(e,r){return this._callWithConfig(this._invoke.bind(this),e,r)}async*_transform(e,r,n){let i;for await(let o of e)if(i===void 0)i=o;else try{i=this._concatOutputChunks(i,o)}catch{i=o}let a=ue(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??25)-1}),s=await new Promise((o,c)=>{be.runWithConfig(qe(a),async()=>{try{o(await this.func(i,{...a,config:a}))}catch(l){c(l)}})});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 Fi(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(e,r){return this._transformStreamWithConfig(e,this._transform.bind(this),r)}async stream(e,r){async function*n(){yield e}let i=Y(r),a=new Zt({generator:this.transform(n(),i),config:i});return await a.setup,Re.fromAsyncGenerator(a)}},CO=class extends sa{},Gy=class extends _e{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(t){super(t),this.runnable=t.runnable,this.fallbacks=t.fallbacks}*runnables(){yield this.runnable;for(let t of this.fallbacks)yield t}async invoke(t,e){let r=Y(e),n=await Ze(r),{runId:i,...a}=r,s=await n?.handleChainStart(this.toJSON(),ge(t,"input"),i,void 0,void 0,void 0,a?.runName),o=ue(a,{callbacks:s?.getChild()});return await be.runWithConfig(o,async()=>{let c;for(let l of this.runnables()){r?.signal?.throwIfAborted();try{let u=await l.invoke(t,o);return await s?.handleChainEnd(ge(u,"output")),u}catch(u){c===void 0&&(c=u)}}throw c===void 0?new Error("No error stored at end of fallback."):(await s?.handleChainError(c),c)})}async*_streamIterator(t,e){let r=Y(e),n=await Ze(r),{runId:i,...a}=r,s=await n?.handleChainStart(this.toJSON(),ge(t,"input"),i,void 0,void 0,void 0,a?.runName),o,c;for(let u of this.runnables()){r?.signal?.throwIfAborted();let d=ue(a,{callbacks:s?.getChild()});try{c=Fi(d,await u.stream(t,d));break}catch(f){o===void 0&&(o=f)}}if(c===void 0){let u=o??new Error("No error stored at end of fallback.");throw await s?.handleChainError(u),u}let l;try{for await(let u of c){yield u;try{l=l===void 0?l:this._concatOutputChunks(l,u)}catch{l=void 0}}}catch(u){throw await s?.handleChainError(u),u}await s?.handleChainEnd(ge(l,"output"))}async batch(t,e,r){if(r?.returnExceptions)throw new Error("Not implemented.");let n=this._getOptionsList(e??{},t.length),i=await Promise.all(n.map(o=>Ze(o))),a=await Promise.all(i.map(async(o,c)=>{let l=await o?.handleChainStart(this.toJSON(),ge(t[c],"input"),n[c].runId,void 0,void 0,void 0,n[c].runName);return delete n[c].runId,l})),s;for(let o of this.runnables()){n[0].signal?.throwIfAborted();try{let c=await o.batch(t,a.map((l,u)=>ue(n[u],{callbacks:l?.getChild()})),r);return await Promise.all(a.map((l,u)=>l?.handleChainEnd(ge(c[u],"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 Tr(t){if(typeof t=="function")return new Qf({func:t});if(_e.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))e[r]=Tr(n);return new sa({steps:e})}else throw new Error(`Expected a Runnable, function or object.
|
|
174
|
+
Instead got an unsupported type.`)}var Vy=class extends _e{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(t){t instanceof sa&&(t={mapper:t}),super(t),this.mapper=t.mapper}async invoke(t,e){let r=await this.mapper.invoke(t,e);return{...t,...r}}async*_transform(t,e,r){let n=this.mapper.getStepsKeys(),[i,a]=qi(t),s=this.mapper.transform(a,ue(r,{callbacks:e?.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 l=Object.fromEntries(Object.entries(c).filter(([u])=>!n.includes(u)));Object.keys(l).length>0&&(yield l)}yield(await o).value;for await(let c of s)yield c}transform(t,e){return this._transformStreamWithConfig(t,this._transform.bind(this),e)}async stream(t,e){async function*r(){yield t}let n=Y(e),i=new Zt({generator:this.transform(r(),n),config:n});return await i.setup,Re.fromAsyncGenerator(i)}},Zy=class extends _e{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(t){(typeof t=="string"||Array.isArray(t))&&(t={keys:t}),super(t),this.keys=t.keys}async _pick(t){if(typeof this.keys=="string")return t[this.keys];{let e=this.keys.map(r=>[r,t[r]]).filter(r=>r[1]!==void 0);return e.length===0?void 0:Object.fromEntries(e)}}async invoke(t,e){return this._callWithConfig(this._pick.bind(this),t,e)}async*_transform(t){for await(let e of t){let r=await this._pick(e);r!==void 0&&(yield r)}}transform(t,e){return this._transformStreamWithConfig(t,this._transform.bind(this),e)}async stream(t,e){async function*r(){yield t}let n=Y(e),i=new Zt({generator:this.transform(r(),n),config:n});return await i.setup,Re.fromAsyncGenerator(i)}},Zf=class extends aa{name;description;schema;constructor(t){let e=Kf.from([Qf.from(async r=>{let n;if(Nt(r))try{n=await Ii(this.schema,r.args)}catch{throw new Ir("Received tool input did not match expected schema",JSON.stringify(r.args))}else n=r;return n}).withConfig({runName:`${t.name}:parse_input`}),t.bound]).withConfig({runName:t.name});super({bound:e,config:t.config??{}}),this.name=t.name,this.description=t.description,this.schema=t.schema}static lc_name(){return"RunnableToolLike"}};function qy(t,e){let r=e.name??t.getName(),n=e.description??wd(e.schema);return Ci(e.schema)?new Zf({name:r,description:n,schema:vt.object({input:vt.string()}).transform(i=>i.input),bound:t}):new Zf({name:r,description:n,schema:e.schema,bound:t})}var FO=D({BasePromptValue:()=>oa,ChatPromptValue:()=>So,ImagePromptValue:()=>Jy,StringPromptValue:()=>Eo}),oa=class extends ft{},Eo=class extends oa{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(t){super({value:t}),this.value=t}toString(){return this.value}toChatMessages(){return[new Yt(this.value)]}},So=class extends oa{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(t){Array.isArray(t)&&(t={messages:t}),super(t),this.messages=t.messages}toString(){return Fn(this.messages)}toChatMessages(){return this.messages}},Jy=class extends oa{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(t){"imageUrl"in t||(t={imageUrl:t}),super(t),this.imageUrl=t.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Yt({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}};var ip=Wt(np(),1),rw=Object.defineProperty,nw=(t,e,r)=>e in t?rw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,iw=(t,e,r)=>(nw(t,typeof e!="symbol"?e+"":e,r),r);function aw(t,e){let r=Array.from({length:t.length},(n,i)=>({start:i,end:i+1}));for(;r.length>1;){let n=null;for(let i=0;i<r.length-1;i++){let a=t.slice(r[i].start,r[i+1].end),s=e.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(t,e){return t.length===1?[e.get(t.join(","))]:aw(t,e).map(r=>e.get(t.slice(r.start,r.end).join(","))).filter(r=>r!=null)}function ow(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var Ao=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(t,e){this.patStr=t.pat_str;let r=t.bpe_ranks.split(`
|
|
175
|
+
`).filter(Boolean).reduce((n,i)=>{let[a,s,...o]=i.split(" "),c=Number.parseInt(s,10);return o.forEach((l,u)=>n[l]=c+u),n},{});for(let[n,i]of Object.entries(r)){let a=ip.default.toByteArray(n);this.rankMap.set(a.join(","),i),this.textMap.set(i,a)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[i,a])=>(n[a]=this.textEncoder.encode(i),n),{})}encode(t,e=[],r="all"){let n=new RegExp(this.patStr,"ug"),i=Ao.specialTokenRegex(Object.keys(this.specialTokens)),a=[],s=new Set(e==="all"?Object.keys(this.specialTokens):e),o=new Set(r==="all"?Object.keys(this.specialTokens).filter(l=>!s.has(l)):r);if(o.size>0){let l=Ao.specialTokenRegex([...o]),u=t.match(l);if(u!=null)throw new Error(`The text contains a special token that is not allowed: ${u[0]}`)}let c=0;for(;;){let l=null,u=c;for(;i.lastIndex=u,l=i.exec(t),!(l==null||s.has(l[0]));)u=l.index+1;let d=l?.index??t.length;for(let p of t.substring(c,d).matchAll(n)){let h=this.textEncoder.encode(p[0]),g=this.rankMap.get(h.join(","));if(g!=null){a.push(g);continue}a.push(...sw(h,this.rankMap))}if(l==null)break;let f=this.specialTokens[l[0]];a.push(f),c=l.index+l[0].length}return a}decode(t){let e=[],r=0;for(let a=0;a<t.length;++a){let s=t[a],o=this.textMap.get(s)??this.inverseSpecialTokens[s];o!=null&&(e.push(o),r+=o.length)}let n=new Uint8Array(r),i=0;for(let a of e)n.set(a,i),i+=a.length;return this.textDecoder.decode(n)}},la=Ao;iw(la,"specialTokenRegex",t=>new RegExp(t.map(e=>ow(e)).join("|"),"g"));function ko(t){switch(t){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 rR=D({encodingForModel:()=>da,getEncoding:()=>ap}),ua={},cw=new xr({});async function ap(t){return t in ua||(ua[t]=cw.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new la(e)).catch(e=>{throw delete ua[t],e})),await ua[t]}async function da(t){return ap(ko(t))}var dR=D({BaseLangChain:()=>pa,BaseLanguageModel:()=>pw,calculateMaxTokens:()=>dw,getEmbeddingContextSize:()=>lw,getModelContextSize:()=>sp,getModelNameForTiktoken:()=>fa,isOpenAITool:()=>uw}),fa=t=>t.startsWith("gpt-5")?"gpt-5":t.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":t.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":t.startsWith("gpt-4-32k")?"gpt-4-32k":t.startsWith("gpt-4-")?"gpt-4":t.startsWith("gpt-4o")?"gpt-4o":t,lw=t=>t==="text-embedding-ada-002"?8191:2046,sp=t=>{switch(fa(t)){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 uw(t){return typeof t!="object"||!t?!1:!!("type"in t&&t.type==="function"&&"function"in t&&typeof t.function=="object"&&t.function&&"name"in t.function&&"parameters"in t.function)}var dw=async({prompt:t,modelName:e})=>{let r;try{r=(await da(fa(e))).encode(t).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),r=Math.ceil(t.length/4)}return sp(e)-r},fw=()=>!1,pa=class extends _e{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(t){super(t),this.verbose=t.verbose??fw(),this.callbacks=t.callbacks,this.tags=t.tags??[],this.metadata=t.metadata??{},this._addVersion("@langchain/core","1.1.39")}_addVersion(t,e){let r=this.metadata?.versions;this.metadata={...this.metadata,versions:{...typeof r=="object"&&r!==null?r:{},[t]:e}}}},pw=class extends pa{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:t,callbackManager:e,...r}){let{cache:n,...i}=r;super({callbacks:t??e,...i}),typeof n=="object"?this.cache=n:n?this.cache=go.global():this.cache=void 0,this.caller=new xr(r??{})}_encoding;async getNumTokens(t){let e;typeof t=="string"?e=t:e=t.map(n=>typeof n=="string"?n:n.type==="text"&&"text"in n?n.text:"").join("");let r=Math.ceil(e.length/4);if(!this._encoding)try{this._encoding=await da("modelName"in this?fa(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(e).length}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}return r}static _convertInputToPromptValue(t){return typeof t=="string"?new Eo(t):Array.isArray(t)?new So(t.map(il)):t}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:t,...e}){let r={...this._identifyingParams(),...e,_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(t){throw new Error("Use .toJSON() instead")}get profile(){return{}}};function Io(t){return t!==void 0&&Array.isArray(t.lc_namespace)}function Co(t){return t!==void 0&&_e.isRunnable(t)&&"lc_name"in t.constructor&&typeof t.constructor.lc_name=="function"&&t.constructor.lc_name()==="RunnableToolLike"}function Oo(t){return!!t&&typeof t=="object"&&"name"in t&&"schema"in t&&(Fr(t.schema)||t.schema!=null&&typeof t.schema=="object"&&"type"in t.schema&&typeof t.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(t.schema.type))}function op(t){return Oo(t)||Co(t)||Io(t)}var LR=D({BaseToolkit:()=>hw,DynamicStructuredTool:()=>up,DynamicTool:()=>lp,StructuredTool:()=>Ro,Tool:()=>cp,ToolInputParsingException:()=>Ir,isLangChainTool:()=>op,isRunnableToolLike:()=>Co,isStructuredTool:()=>Io,isStructuredToolParams:()=>Oo,tool:()=>mw}),Ro=class extends pa{extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(t){super(t??{}),this.verboseParsingErrors=t?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=t?.responseFormat??this.responseFormat,this.defaultConfig=t?.defaultConfig??this.defaultConfig,this.metadata=t?.metadata??this.metadata,this.extras=t?.extras??this.extras}async invoke(t,e){let r,n=Y(gn(this.defaultConfig,e));return Nt(t)?(r=t.args,n={...n,toolCall:t}):r=t,this.call(r,n)}async call(t,e,r){let n=Nt(t)?t.args:t,i;if(Fr(this.schema))try{i=await Ii(this.schema,n)}catch(p){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
|
|
176
|
+
Details: ${p.message}`),vd(p)&&(h=`${h}
|
|
177
|
+
|
|
178
|
+
${Ta.prettifyError(p)}`),new Ir(h,JSON.stringify(t))}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(g=>`${g.keywordLocation}: ${g.error}`).join(`
|
|
180
|
+
`)}`),new Ir(h,JSON.stringify(t))}i=n}let a=hn(e),s=tt.configure(a.callbacks,this.callbacks,a.tags||r,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),o;Nt(t)&&(o=t.id),!o&&Kc(a)&&(o=a.toolCall.id);let c=await s?.handleToolStart(this.toJSON(),typeof t=="string"?t:JSON.stringify(t),a.runId,void 0,void 0,void 0,a.runName,o);delete a.runId;let l;try{let p=await this._call(i,c,a);l=ho(p)?await bf(p,async h=>{try{await c?.handleToolEvent(h)}catch(g){await c?.handleToolError(g)}}):p}catch(p){throw await c?.handleToolError(p),p}let u,d;if(this.responseFormat==="content_and_artifact")if(Array.isArray(l)&&l.length===2)[u,d]=l;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
|
|
181
|
+
Result: ${JSON.stringify(l)}`);else u=l;let f=gw({content:u,artifact:d,toolCallId:o,name:this.name,metadata:this.metadata});return await c?.handleToolEnd(f),f}},cp=class extends Ro{schema=vt.object({input:vt.string().optional()}).transform(t=>t.input);constructor(t){super(t)}call(t,e){let r=typeof t=="string"||t==null?{input:t}:t;return super.call(r,e)}},lp=class extends cp{static lc_name(){return"DynamicTool"}name;description;func;constructor(t){super(t),this.name=t.name,this.description=t.description,this.func=t.func,this.returnDirect=t.returnDirect??this.returnDirect}async call(t,e){let r=hn(e);return r.runName===void 0&&(r.runName=this.name),super.call(t,r)}_call(t,e,r){return this.func(t,e,r)}},up=class extends Ro{static lc_name(){return"DynamicStructuredTool"}description;func;schema;constructor(t){super(t),this.name=t.name,this.description=t.description,this.func=t.func,this.returnDirect=t.returnDirect??this.returnDirect,this.schema=t.schema}async call(t,e,r){let n=hn(e);return n.runName===void 0&&(n.runName=this.name),super.call(t,n,r)}_call(t,e,r){return this.func(t,e,r)}},hw=class{getTools(){return this.tools}};function mw(t,e){let r=Ci(e.schema),n=Yr(e.schema);if(!e.schema||r||n)return new lp({...e,description:e.description??e.schema?.description??`${e.name} tool`,func:async(s,o,c)=>new Promise((l,u)=>{let d=ue(c,{callbacks:o?.getChild()});be.runWithConfig(qe(d),async()=>{try{l(t(s,d))}catch(f){u(f)}})})});let i=e.schema,a=e.description??e.schema.description??`${e.name} tool`;return new up({...e,description:a,schema:i,func:async(s,o,c)=>new Promise((l,u)=>{let d,f=()=>{c?.signal&&d&&c.signal.removeEventListener("abort",d)};c?.signal&&(d=()=>{f(),u(Bt(c.signal))},c.signal.addEventListener("abort",d,{once:!0}));let p=ue(c,{callbacks:o?.getChild()});be.runWithConfig(qe(p),async()=>{try{let h=await t(s,p);if(ho(h)){l(h);return}if(c?.signal?.aborted){f();return}f(),l(h)}catch(h){f(),u(h)}})})})}function gw(t){let{content:e,artifact:r,toolCallId:n,metadata:i}=t;return n&&!Oa(e)?typeof e=="string"||Array.isArray(e)&&e.every(a=>typeof a=="object")?new Kt({status:"success",content:e,artifact:r,tool_call_id:n,name:t.name,metadata:i}):new Kt({status:"success",content:_w(e),artifact:r,tool_call_id:n,name:t.name,metadata:i}):e}function _w(t){try{return JSON.stringify(t)??""}catch{return`${t}`}}export{vw as a,rc as b,xp as c,nc as d,D as e,kw as f,Mn as g,ft as h,Z0 as i,ul as j,Xe as k,Gi as l,FI as m,Bb as n,Pa as o,Zp as p,qp as q,Rt as r,oc as s,cc as t,Cw as u,lc as v,Ow as w,Rw as x,ka as y,Nw as z,wc as A,Pe as B,Sc as C,ke as D,Xw as E,Mp as F,ce as G,kr as H,Tc as I,Be as J,kc as K,Ic as L,Qw as M,ib as N,Oa as O,Kt as P,Dp as Q,Ra as R,Up as S,Bp as T,Ir as U,Zb as V,La as W,Vc as X,Dn as Y,Cr as Z,B0 as _,z0 as $,Or as aa,ja as ba,Xc as ca,Wb as da,Kb as ea,Qc as fa,el as ga,e0 as ha,t0 as ia,Yt as ja,tl as ka,s0 as la,o0 as ma,rl as na,zn as oa,nl as pa,m0 as qa,g0 as ra,O0 as sa,il as ta,Fn as ua,Ua as va,R0 as wa,N0 as xa,$0 as ya,al as za,JI as Aa,Za as Ba,oh as Ca,Ev as Da,fh as Ea,Xt as Fa,Mt as Ga,nS as Ha,et as Ia,lS as Ja,IS as Ka,LS as La,tT as Ma,hn as Na,tt as Oa,be as Pa,yT as Qa,Ze as Ra,gn as Sa,Y as Ta,ue as Ua,qe as Va,rt as Wa,fC as Xa,Re as Ya,Ji as Za,Zt as _a,Qr as $a,xC as ab,$C as bb,DC as cb,Ly as db,En as eb,jy as fb,iC as gb,xr as hb,Qk as ib,H_ as jb,ae as kb,he as lb,AT as mb,Fr as nb,wg as ob,bg as pb,kT as qb,IT as rb,Ii as sb,CT as tb,OT as ub,wd as vb,RT as wb,Ci as xb,to as yb,_t as zb,ro as Ab,vg as Bb,xg as Cb,NT as Db,_d as Eb,$T as Fb,PT as Gb,ki as Hb,yd as Ib,MT as Jb,bd as Kb,LT as Lb,vd as Mb,w as Nb,vt as Ob,Vt as Pb,Bi as Qb,$I as Rb,fo as Sb,iO as Tb,ia as Ub,ge as Vb,_e as Wb,aa as Xb,IO as Yb,Wf as Zb,Kf as _b,sa as $b,Qf as ac,CO as bc,Gy as cc,Tr as dc,Vy as ec,Zy as fc,Zf as gc,FO as hc,Eo as ic,So as jc,Jy as kc,rR as lc,dR as mc,sp as nc,uw as oc,pw as pc,Io as qc,Co as rc,Oo as sc,op as tc,LR as uc,Ro as vc,mw as wc};
|