keyring-agent-core 0.2.32 → 0.2.33

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.
@@ -329,7 +329,7 @@ From: ${o}`);s=[u[0]]}else s=[];o={url:o},a=new iN.ImagePromptTemplate({template
329
329
 
330
330
  `);f(this,"prefix","");f(this,"templateFormat","f-string");f(this,"validateTemplate",!0);if(this.examples=r.examples,this.examplePrompt=r.examplePrompt,this.exampleSeparator=r.exampleSeparator??`
331
331
 
332
- `,this.exampleSelector=r.exampleSelector,this.prefix=r.prefix??"",this.suffix=r.suffix??"",this.templateFormat=r.templateFormat??"f-string",this.validateTemplate=r.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),VT.checkValidTemplate(this.prefix+this.suffix,this.templateFormat,n)}}_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}async getExamples(r){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(r);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(r){let n=await this.mergePartialAndUserVariables(r),i=await this.getExamples(n);i=i.map(a=>{let s={};return this.examplePrompt.inputVariables.forEach(l=>{s[l]=a[l]}),s});let o=[];for(let a of i){let s=await this.examplePrompt.formatMessages(a);o.push(...s)}return o}async format(r){let n=await this.mergePartialAndUserVariables(r),i=await this.getExamples(n),o=(await Promise.all(i.map(a=>this.examplePrompt.formatMessages(a)))).flat().map(a=>a.content);return VT.renderTemplate([this.prefix,...o,this.suffix].join(this.exampleSeparator),this.templateFormat,n)}async partial(r){let n=this.inputVariables.filter(o=>!(o in r)),i={...this.partialVariables??{},...r};return new gW({...this,inputVariables:n,partialVariables:i})}};cN.FewShotChatMessagePromptTemplate=POe;cN.FewShotPromptTemplate=kOe});var bW=v(_W=>{"use strict";p();var EOe=Wf(),AOe=py(),COe=class ZT extends EOe.BasePromptTemplate{constructor(r){super({...r,inputVariables:[]});f(this,"pipelinePrompts");f(this,"finalPrompt");this.pipelinePrompts=r.pipelinePrompts,this.finalPrompt=r.finalPrompt,this.inputVariables=this.computeInputValues()}static lc_name(){return"PipelinePromptTemplate"}computeInputValues(){let r=this.pipelinePrompts.map(i=>i.name),n=this.pipelinePrompts.map(i=>i.prompt.inputVariables.filter(o=>!r.includes(o))).flat();return[...new Set(n)]}static extractRequiredInputValues(r,n){return n.reduce((i,o)=>(i[o]=r[o],i),{})}async formatPipelinePrompts(r){let n=await this.mergePartialAndUserVariables(r);for(let{name:i,prompt:o}of this.pipelinePrompts){let a=ZT.extractRequiredInputValues(n,o.inputVariables);o instanceof AOe.ChatPromptTemplate?n[i]=await o.formatMessages(a):n[i]=await o.format(a)}return ZT.extractRequiredInputValues(n,this.finalPrompt.inputVariables)}async formatPromptValue(r){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(r))}async format(r){return this.finalPrompt.format(await this.formatPipelinePrompts(r))}async partial(r){let n={...this};return n.inputVariables=this.inputVariables.filter(i=>!(i in r)),n.partialVariables={...this.partialVariables??{},...r},new ZT(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};_W.PipelinePromptTemplate=COe});var TW=v(SW=>{"use strict";p();var xOe=br(),IOe=py();function vW(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function OOe(t){return typeof t=="object"&&t!=null&&"lc_id"in t&&Array.isArray(t.lc_id)&&t.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var ROe=class wW extends IOe.ChatPromptTemplate{constructor(r){super(r);f(this,"schema");f(this,"method");f(this,"lc_namespace",["langchain_core","prompts","structured"]);this.schema=r.schema,this.method=r.method}get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}pipe(r){if(vW(r))return super.pipe(r.withStructuredOutput(this.schema));if(OOe(r)&&vW(r.bound))return super.pipe(new xOe.RunnableBinding({bound:r.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:r.kwargs??{},config:r.config,configFactories:r.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(r,n,i){return wW.fromMessages(r,{schema:n,method:i})}};SW.StructuredPrompt=ROe});var OW=v(Ot=>{"use strict";p();Object.defineProperty(Ot,Symbol.toStringTag,{value:"Module"});var NOe=de(),kW=Wf(),PW=ly(),zr=Cc(),EW=qT(),AW=eN(),CW=nN(),Vr=py(),HT=yW(),xW=bW(),IW=TW(),$Oe=NOe.__exportAll({AIMessagePromptTemplate:()=>Vr.AIMessagePromptTemplate,BaseChatPromptTemplate:()=>Vr.BaseChatPromptTemplate,BaseMessagePromptTemplate:()=>Vr.BaseMessagePromptTemplate,BaseMessageStringPromptTemplate:()=>Vr.BaseMessageStringPromptTemplate,BasePromptTemplate:()=>kW.BasePromptTemplate,BaseStringPromptTemplate:()=>PW.BaseStringPromptTemplate,ChatMessagePromptTemplate:()=>Vr.ChatMessagePromptTemplate,ChatPromptTemplate:()=>Vr.ChatPromptTemplate,DEFAULT_FORMATTER_MAPPING:()=>zr.DEFAULT_FORMATTER_MAPPING,DEFAULT_PARSER_MAPPING:()=>zr.DEFAULT_PARSER_MAPPING,DictPromptTemplate:()=>CW.DictPromptTemplate,FewShotChatMessagePromptTemplate:()=>HT.FewShotChatMessagePromptTemplate,FewShotPromptTemplate:()=>HT.FewShotPromptTemplate,HumanMessagePromptTemplate:()=>Vr.HumanMessagePromptTemplate,ImagePromptTemplate:()=>AW.ImagePromptTemplate,MessagesPlaceholder:()=>Vr.MessagesPlaceholder,PipelinePromptTemplate:()=>xW.PipelinePromptTemplate,PromptTemplate:()=>EW.PromptTemplate,StructuredPrompt:()=>IW.StructuredPrompt,SystemMessagePromptTemplate:()=>Vr.SystemMessagePromptTemplate,checkValidTemplate:()=>zr.checkValidTemplate,interpolateFString:()=>zr.interpolateFString,interpolateMustache:()=>zr.interpolateMustache,parseFString:()=>zr.parseFString,parseMustache:()=>zr.parseMustache,parseTemplate:()=>zr.parseTemplate,renderTemplate:()=>zr.renderTemplate});Ot.AIMessagePromptTemplate=Vr.AIMessagePromptTemplate;Ot.BaseChatPromptTemplate=Vr.BaseChatPromptTemplate;Ot.BaseMessagePromptTemplate=Vr.BaseMessagePromptTemplate;Ot.BaseMessageStringPromptTemplate=Vr.BaseMessageStringPromptTemplate;Ot.BasePromptTemplate=kW.BasePromptTemplate;Ot.BaseStringPromptTemplate=PW.BaseStringPromptTemplate;Ot.ChatMessagePromptTemplate=Vr.ChatMessagePromptTemplate;Ot.ChatPromptTemplate=Vr.ChatPromptTemplate;Ot.DEFAULT_FORMATTER_MAPPING=zr.DEFAULT_FORMATTER_MAPPING;Ot.DEFAULT_PARSER_MAPPING=zr.DEFAULT_PARSER_MAPPING;Ot.DictPromptTemplate=CW.DictPromptTemplate;Ot.FewShotChatMessagePromptTemplate=HT.FewShotChatMessagePromptTemplate;Ot.FewShotPromptTemplate=HT.FewShotPromptTemplate;Ot.HumanMessagePromptTemplate=Vr.HumanMessagePromptTemplate;Ot.ImagePromptTemplate=AW.ImagePromptTemplate;Ot.MessagesPlaceholder=Vr.MessagesPlaceholder;Ot.PipelinePromptTemplate=xW.PipelinePromptTemplate;Ot.PromptTemplate=EW.PromptTemplate;Ot.StructuredPrompt=IW.StructuredPrompt;Ot.SystemMessagePromptTemplate=Vr.SystemMessagePromptTemplate;Ot.checkValidTemplate=zr.checkValidTemplate;Ot.interpolateFString=zr.interpolateFString;Ot.interpolateMustache=zr.interpolateMustache;Ot.parseFString=zr.parseFString;Ot.parseMustache=zr.parseMustache;Ot.parseTemplate=zr.parseTemplate;Object.defineProperty(Ot,"prompts_exports",{enumerable:!0,get:function(){return $Oe}});Ot.renderTemplate=zr.renderTemplate});var NW=v(WT=>{"use strict";p();Object.defineProperty(WT,Symbol.toStringTag,{value:"Module"});var MOe=de().__exportAll({BaseDocumentCompressor:()=>RW}),RW=class{static isBaseDocumentCompressor(t){return t?.compressDocuments!==void 0}};WT.BaseDocumentCompressor=RW;Object.defineProperty(WT,"document_compressors_exports",{enumerable:!0,get:function(){return MOe}})});var KT=v(GT=>{"use strict";p();Object.defineProperty(GT,Symbol.toStringTag,{value:"Module"});var DOe=de(),$W=Rs(),UOe=Ko(),qOe=br(),LOe=DOe.__exportAll({BaseRetriever:()=>MW}),MW=class extends qOe.Runnable{constructor(e){super(e);f(this,"callbacks");f(this,"tags");f(this,"metadata");f(this,"verbose");this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,r){throw new Error("Not implemented!")}async invoke(e,r){let n=UOe.ensureConfig($W.parseCallbackConfigArg(r)),i=await(await $W.CallbackManager.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,n.runId,void 0,void 0,void 0,n.runName);try{let o=await this._getRelevantDocuments(e,i);return await i?.handleRetrieverEnd(o),o}catch(o){throw await i?.handleRetrieverError(o),o}}};GT.BaseRetriever=MW;Object.defineProperty(GT,"retrievers_exports",{enumerable:!0,get:function(){return LOe}})});var UW=v(fy=>{"use strict";p();Object.defineProperty(fy,Symbol.toStringTag,{value:"Module"});var jOe=de(),FOe=xi(),BOe=jOe.__exportAll({BaseStore:()=>dN,InMemoryStore:()=>DW}),dN=class extends FOe.Serializable{},DW=class extends dN{constructor(){super(...arguments);f(this,"lc_namespace",["langchain","storage"]);f(this,"store",{})}async mget(e){return e.map(r=>this.store[r])}async mset(e){for(let[r,n]of e)this.store[r]=n}async mdelete(e){for(let r of e)delete this.store[r]}async*yieldKeys(e){let r=Object.keys(this.store);for(let n of r)(e===void 0||n.startsWith(e))&&(yield n)}};fy.BaseStore=dN;fy.InMemoryStore=DW;Object.defineProperty(fy,"stores_exports",{enumerable:!0,get:function(){return BOe}})});var YT=v(Vs=>{"use strict";p();var zOe={and:"and",or:"or",not:"not"},VOe={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"},ZOe=class{},pN=class{accept(t){if(this.exprName==="Operation")return t.visitOperation(this);if(this.exprName==="Comparison")return t.visitComparison(this);if(this.exprName==="StructuredQuery")return t.visitStructuredQuery(this);throw new Error("Unknown Expression type")}},fN=class extends pN{},HOe=class extends fN{constructor(e,r,n){super();f(this,"exprName","Comparison");this.comparator=e,this.attribute=r,this.value=n}},WOe=class extends fN{constructor(e,r){super();f(this,"exprName","Operation");this.operator=e,this.args=r}},GOe=class extends pN{constructor(e,r){super();f(this,"exprName","StructuredQuery");this.query=e,this.filter=r}};Vs.Comparators=VOe;Vs.Comparison=HOe;Vs.Expression=pN;Vs.FilterDirective=fN;Vs.Operation=WOe;Vs.Operators=zOe;Vs.StructuredQuery=GOe;Vs.Visitor=ZOe});var JT=v(Ql=>{"use strict";p();function qW(t){return t&&typeof t=="object"&&!Array.isArray(t)}function KOe(t){return t?typeof t=="string"&&t.length>0||typeof t=="function"?!1:qW(t)&&Object.keys(t).length===0:!0}function LW(t){if(typeof t=="number")return t%1===0;if(typeof t=="string"){let e=parseInt(t,10);return!Number.isNaN(e)&&e%1===0&&e.toString()===t}return!1}function jW(t){if(typeof t=="number")return t%1!==0;if(typeof t=="string"){let e=parseFloat(t);return!Number.isNaN(e)&&e%1!==0&&e.toString()===t}return!1}function FW(t){return typeof t=="string"&&(Number.isNaN(parseFloat(t))||parseFloat(t).toString()!==t)}function BW(t){return typeof t=="boolean"}function YOe(t){let e;if(FW(t))e=t;else if(LW(t))e=parseInt(t,10);else if(jW(t))e=parseFloat(t);else if(BW(t))e=!!t;else throw new Error("Unsupported value type");return e}Ql.castValue=YOe;Ql.isBoolean=BW;Ql.isFilterEmpty=KOe;Ql.isFloat=jW;Ql.isInt=LW;Ql.isObject=qW;Ql.isString=FW});var mN=v(hN=>{"use strict";p();var ko=YT(),Kf=JT(),zW=class extends ko.Visitor{},JOe=class extends zW{constructor(e){super();f(this,"allowedOperators");f(this,"allowedComparators");this.allowedOperators=e?.allowedOperators??[ko.Operators.and,ko.Operators.or],this.allowedComparators=e?.allowedComparators??[ko.Comparators.eq,ko.Comparators.ne,ko.Comparators.gt,ko.Comparators.gte,ko.Comparators.lt,ko.Comparators.lte]}formatFunction(e){if(e in ko.Comparators){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(e)===-1)throw new Error(`Comparator ${e} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(e in ko.Operators){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(e)===-1)throw new Error(`Operator ${e} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`)}else throw new Error("Unknown comparator or operator");return`$${e}`}visitOperation(e){let r=e.args?.map(n=>n.accept(this));return{[this.formatFunction(e.operator)]:r}}visitComparison(e){return{[e.attribute]:{[this.formatFunction(e.comparator)]:Kf.castValue(e.value)}}}visitStructuredQuery(e){let r={};return e.filter&&(r={filter:e.filter.accept(this)}),r}mergeFilters(e,r,n="and",i=!1){if(!(Kf.isFilterEmpty(e)&&Kf.isFilterEmpty(r))){if(Kf.isFilterEmpty(e)||n==="replace")return Kf.isFilterEmpty(r)?void 0:r;if(Kf.isFilterEmpty(r))return i?e:n==="and"?void 0:e;if(n==="and")return{$and:[e,r]};if(n==="or")return{$or:[e,r]};throw new Error("Unknown merge type")}}};hN.BaseTranslator=zW;hN.BasicTranslator=JOe});var ZW=v(VW=>{"use strict";p();var Ct=YT(),Yf=JT(),XOe=mN(),QOe=class extends XOe.BaseTranslator{constructor(){super(...arguments);f(this,"allowedOperators",[Ct.Operators.and,Ct.Operators.or]);f(this,"allowedComparators",[Ct.Comparators.eq,Ct.Comparators.ne,Ct.Comparators.gt,Ct.Comparators.gte,Ct.Comparators.lt,Ct.Comparators.lte])}formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(e){switch(e){case"string":return[Ct.Comparators.eq,Ct.Comparators.ne,Ct.Comparators.gt,Ct.Comparators.gte,Ct.Comparators.lt,Ct.Comparators.lte];case"number":return[Ct.Comparators.eq,Ct.Comparators.ne,Ct.Comparators.gt,Ct.Comparators.gte,Ct.Comparators.lt,Ct.Comparators.lte];case"boolean":return[Ct.Comparators.eq,Ct.Comparators.ne];default:throw new Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case Ct.Comparators.eq:return(r,n)=>r===n;case Ct.Comparators.ne:return(r,n)=>r!==n;case Ct.Comparators.gt:return(r,n)=>r>n;case Ct.Comparators.gte:return(r,n)=>r>=n;case Ct.Comparators.lt:return(r,n)=>r<n;case Ct.Comparators.lte:return(r,n)=>r<=n;default:throw new Error("Unknown comparator")}}getOperatorFunction(e){switch(e){case Ct.Operators.and:return(r,n)=>r&&n;case Ct.Operators.or:return(r,n)=>r||n;default:throw new Error("Unknown operator")}}visitOperation(e){let{operator:r,args:n}=e;if(this.allowedOperators.includes(r)){let i=this.getOperatorFunction(r);return o=>n?n.reduce((a,s)=>{let l=s.accept(this);if(typeof l=="function")return i(a,l(o));throw new Error("Filter is not a function")},!0):!0}else throw new Error("Operator not allowed")}visitComparison(e){let{comparator:r,attribute:n,value:i}=e,o=[Ct.Comparators.ne];if(this.allowedComparators.includes(r)){if(!this.getAllowedComparatorsForType(typeof i).includes(r))throw new Error(`'${r}' comparator not allowed to be used with ${typeof i}`);let a=this.getComparatorFunction(r);return s=>{let l=s.metadata[n];return l===void 0?!!o.includes(r):a(l,Yf.castValue(i))}}else throw new Error("Comparator not allowed")}visitStructuredQuery(e){if(!e.filter)return{};let r=e.filter?.accept(this);if(typeof r!="function")throw new Error("Structured query filter is not a function");return{filter:r}}mergeFilters(e,r,n="and"){if(!(Yf.isFilterEmpty(e)&&Yf.isFilterEmpty(r))){if(Yf.isFilterEmpty(e)||n==="replace")return Yf.isFilterEmpty(r)?void 0:r;if(Yf.isFilterEmpty(r))return n==="and"?void 0:e;if(n==="and")return i=>e(i)&&r(i);if(n==="or")return i=>e(i)||r(i);throw new Error("Unknown merge type")}}};VW.FunctionalTranslator=QOe});var WW=v(vr=>{"use strict";p();Object.defineProperty(vr,Symbol.toStringTag,{value:"Module"});var eRe=de(),yn=YT(),ti=JT(),XT=mN(),HW=ZW(),tRe=eRe.__exportAll({BaseTranslator:()=>XT.BaseTranslator,BasicTranslator:()=>XT.BasicTranslator,Comparators:()=>yn.Comparators,Comparison:()=>yn.Comparison,Expression:()=>yn.Expression,FilterDirective:()=>yn.FilterDirective,FunctionalTranslator:()=>HW.FunctionalTranslator,Operation:()=>yn.Operation,Operators:()=>yn.Operators,StructuredQuery:()=>yn.StructuredQuery,Visitor:()=>yn.Visitor,castValue:()=>ti.castValue,isBoolean:()=>ti.isBoolean,isFilterEmpty:()=>ti.isFilterEmpty,isFloat:()=>ti.isFloat,isInt:()=>ti.isInt,isObject:()=>ti.isObject,isString:()=>ti.isString});vr.BaseTranslator=XT.BaseTranslator;vr.BasicTranslator=XT.BasicTranslator;vr.Comparators=yn.Comparators;vr.Comparison=yn.Comparison;vr.Expression=yn.Expression;vr.FilterDirective=yn.FilterDirective;vr.FunctionalTranslator=HW.FunctionalTranslator;vr.Operation=yn.Operation;vr.Operators=yn.Operators;vr.StructuredQuery=yn.StructuredQuery;vr.Visitor=yn.Visitor;vr.castValue=ti.castValue;vr.isBoolean=ti.isBoolean;vr.isFilterEmpty=ti.isFilterEmpty;vr.isFloat=ti.isFloat;vr.isInt=ti.isInt;vr.isObject=ti.isObject;vr.isString=ti.isString;Object.defineProperty(vr,"structured_query_exports",{enumerable:!0,get:function(){return tRe}})});var oG=v(zi=>{"use strict";p();var rRe=jr(),GW=_l(),QT=Fr(),nRe=jo(),iRe=Fp();ei();function hy(t){return rRe.BaseMessage.isInstance(t)?t.constructor.name||t.type:typeof t}function ek(t,e){return function(r,n){let{isNot:i,utils:o}=this;if(!e(r))return{pass:!1,message:()=>`${o.matcherHint(`toBe${t}`,void 0,void 0)}
332
+ `,this.exampleSelector=r.exampleSelector,this.prefix=r.prefix??"",this.suffix=r.suffix??"",this.templateFormat=r.templateFormat??"f-string",this.validateTemplate=r.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),VT.checkValidTemplate(this.prefix+this.suffix,this.templateFormat,n)}}_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}async getExamples(r){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(r);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(r){let n=await this.mergePartialAndUserVariables(r),i=await this.getExamples(n);i=i.map(a=>{let s={};return this.examplePrompt.inputVariables.forEach(l=>{s[l]=a[l]}),s});let o=[];for(let a of i){let s=await this.examplePrompt.formatMessages(a);o.push(...s)}return o}async format(r){let n=await this.mergePartialAndUserVariables(r),i=await this.getExamples(n),o=(await Promise.all(i.map(a=>this.examplePrompt.formatMessages(a)))).flat().map(a=>a.content);return VT.renderTemplate([this.prefix,...o,this.suffix].join(this.exampleSeparator),this.templateFormat,n)}async partial(r){let n=this.inputVariables.filter(o=>!(o in r)),i={...this.partialVariables??{},...r};return new gW({...this,inputVariables:n,partialVariables:i})}};cN.FewShotChatMessagePromptTemplate=POe;cN.FewShotPromptTemplate=kOe});var bW=v(_W=>{"use strict";p();var EOe=Wf(),AOe=py(),COe=class ZT extends EOe.BasePromptTemplate{constructor(r){super({...r,inputVariables:[]});f(this,"pipelinePrompts");f(this,"finalPrompt");this.pipelinePrompts=r.pipelinePrompts,this.finalPrompt=r.finalPrompt,this.inputVariables=this.computeInputValues()}static lc_name(){return"PipelinePromptTemplate"}computeInputValues(){let r=this.pipelinePrompts.map(i=>i.name),n=this.pipelinePrompts.map(i=>i.prompt.inputVariables.filter(o=>!r.includes(o))).flat();return[...new Set(n)]}static extractRequiredInputValues(r,n){return n.reduce((i,o)=>(i[o]=r[o],i),{})}async formatPipelinePrompts(r){let n=await this.mergePartialAndUserVariables(r);for(let{name:i,prompt:o}of this.pipelinePrompts){let a=ZT.extractRequiredInputValues(n,o.inputVariables);o instanceof AOe.ChatPromptTemplate?n[i]=await o.formatMessages(a):n[i]=await o.format(a)}return ZT.extractRequiredInputValues(n,this.finalPrompt.inputVariables)}async formatPromptValue(r){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(r))}async format(r){return this.finalPrompt.format(await this.formatPipelinePrompts(r))}async partial(r){let n={...this};return n.inputVariables=this.inputVariables.filter(i=>!(i in r)),n.partialVariables={...this.partialVariables??{},...r},new ZT(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};_W.PipelinePromptTemplate=COe});var TW=v(SW=>{"use strict";p();var xOe=br(),IOe=py();function vW(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function OOe(t){return typeof t=="object"&&t!=null&&"lc_id"in t&&Array.isArray(t.lc_id)&&t.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var ROe=class wW extends IOe.ChatPromptTemplate{constructor(r){super(r);f(this,"schema");f(this,"method");f(this,"lc_namespace",["langchain_core","prompts","structured"]);this.schema=r.schema,this.method=r.method}get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}pipe(r){if(vW(r))return super.pipe(r.withStructuredOutput(this.schema));if(OOe(r)&&vW(r.bound))return super.pipe(new xOe.RunnableBinding({bound:r.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:r.kwargs??{},config:r.config,configFactories:r.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(r,n,i){return wW.fromMessages(r,{schema:n,method:i})}};SW.StructuredPrompt=ROe});var OW=v(Ot=>{"use strict";p();Object.defineProperty(Ot,Symbol.toStringTag,{value:"Module"});var NOe=de(),kW=Wf(),PW=ly(),zr=Cc(),EW=qT(),AW=eN(),CW=nN(),Vr=py(),HT=yW(),xW=bW(),IW=TW(),$Oe=NOe.__exportAll({AIMessagePromptTemplate:()=>Vr.AIMessagePromptTemplate,BaseChatPromptTemplate:()=>Vr.BaseChatPromptTemplate,BaseMessagePromptTemplate:()=>Vr.BaseMessagePromptTemplate,BaseMessageStringPromptTemplate:()=>Vr.BaseMessageStringPromptTemplate,BasePromptTemplate:()=>kW.BasePromptTemplate,BaseStringPromptTemplate:()=>PW.BaseStringPromptTemplate,ChatMessagePromptTemplate:()=>Vr.ChatMessagePromptTemplate,ChatPromptTemplate:()=>Vr.ChatPromptTemplate,DEFAULT_FORMATTER_MAPPING:()=>zr.DEFAULT_FORMATTER_MAPPING,DEFAULT_PARSER_MAPPING:()=>zr.DEFAULT_PARSER_MAPPING,DictPromptTemplate:()=>CW.DictPromptTemplate,FewShotChatMessagePromptTemplate:()=>HT.FewShotChatMessagePromptTemplate,FewShotPromptTemplate:()=>HT.FewShotPromptTemplate,HumanMessagePromptTemplate:()=>Vr.HumanMessagePromptTemplate,ImagePromptTemplate:()=>AW.ImagePromptTemplate,MessagesPlaceholder:()=>Vr.MessagesPlaceholder,PipelinePromptTemplate:()=>xW.PipelinePromptTemplate,PromptTemplate:()=>EW.PromptTemplate,StructuredPrompt:()=>IW.StructuredPrompt,SystemMessagePromptTemplate:()=>Vr.SystemMessagePromptTemplate,checkValidTemplate:()=>zr.checkValidTemplate,interpolateFString:()=>zr.interpolateFString,interpolateMustache:()=>zr.interpolateMustache,parseFString:()=>zr.parseFString,parseMustache:()=>zr.parseMustache,parseTemplate:()=>zr.parseTemplate,renderTemplate:()=>zr.renderTemplate});Ot.AIMessagePromptTemplate=Vr.AIMessagePromptTemplate;Ot.BaseChatPromptTemplate=Vr.BaseChatPromptTemplate;Ot.BaseMessagePromptTemplate=Vr.BaseMessagePromptTemplate;Ot.BaseMessageStringPromptTemplate=Vr.BaseMessageStringPromptTemplate;Ot.BasePromptTemplate=kW.BasePromptTemplate;Ot.BaseStringPromptTemplate=PW.BaseStringPromptTemplate;Ot.ChatMessagePromptTemplate=Vr.ChatMessagePromptTemplate;Ot.ChatPromptTemplate=Vr.ChatPromptTemplate;Ot.DEFAULT_FORMATTER_MAPPING=zr.DEFAULT_FORMATTER_MAPPING;Ot.DEFAULT_PARSER_MAPPING=zr.DEFAULT_PARSER_MAPPING;Ot.DictPromptTemplate=CW.DictPromptTemplate;Ot.FewShotChatMessagePromptTemplate=HT.FewShotChatMessagePromptTemplate;Ot.FewShotPromptTemplate=HT.FewShotPromptTemplate;Ot.HumanMessagePromptTemplate=Vr.HumanMessagePromptTemplate;Ot.ImagePromptTemplate=AW.ImagePromptTemplate;Ot.MessagesPlaceholder=Vr.MessagesPlaceholder;Ot.PipelinePromptTemplate=xW.PipelinePromptTemplate;Ot.PromptTemplate=EW.PromptTemplate;Ot.StructuredPrompt=IW.StructuredPrompt;Ot.SystemMessagePromptTemplate=Vr.SystemMessagePromptTemplate;Ot.checkValidTemplate=zr.checkValidTemplate;Ot.interpolateFString=zr.interpolateFString;Ot.interpolateMustache=zr.interpolateMustache;Ot.parseFString=zr.parseFString;Ot.parseMustache=zr.parseMustache;Ot.parseTemplate=zr.parseTemplate;Object.defineProperty(Ot,"prompts_exports",{enumerable:!0,get:function(){return $Oe}});Ot.renderTemplate=zr.renderTemplate});var NW=v(WT=>{"use strict";p();Object.defineProperty(WT,Symbol.toStringTag,{value:"Module"});var MOe=de().__exportAll({BaseDocumentCompressor:()=>RW}),RW=class{static isBaseDocumentCompressor(t){return t?.compressDocuments!==void 0}};WT.BaseDocumentCompressor=RW;Object.defineProperty(WT,"document_compressors_exports",{enumerable:!0,get:function(){return MOe}})});var KT=v(GT=>{"use strict";p();Object.defineProperty(GT,Symbol.toStringTag,{value:"Module"});var DOe=de(),$W=Rs(),UOe=Ko(),qOe=br(),LOe=DOe.__exportAll({BaseRetriever:()=>MW}),MW=class extends qOe.Runnable{constructor(e){super(e);f(this,"callbacks");f(this,"tags");f(this,"metadata");f(this,"verbose");this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,r){throw new Error("Not implemented!")}async invoke(e,r){let n=UOe.ensureConfig($W.parseCallbackConfigArg(r)),i=await(await $W.CallbackManager.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,n.runId,void 0,void 0,void 0,n.runName);try{let o=await this._getRelevantDocuments(e,i);return await i?.handleRetrieverEnd(o),o}catch(o){throw await i?.handleRetrieverError(o),o}}};GT.BaseRetriever=MW;Object.defineProperty(GT,"retrievers_exports",{enumerable:!0,get:function(){return LOe}})});var UW=v(fy=>{"use strict";p();Object.defineProperty(fy,Symbol.toStringTag,{value:"Module"});var jOe=de(),FOe=xi(),BOe=jOe.__exportAll({BaseStore:()=>dN,InMemoryStore:()=>DW}),dN=class extends FOe.Serializable{},DW=class extends dN{constructor(){super(...arguments);f(this,"lc_namespace",["langchain","storage"]);f(this,"store",{})}async mget(e){return e.map(r=>this.store[r])}async mset(e){for(let[r,n]of e)this.store[r]=n}async mdelete(e){for(let r of e)delete this.store[r]}async*yieldKeys(e){let r=Object.keys(this.store);for(let n of r)(e===void 0||n.startsWith(e))&&(yield n)}};fy.BaseStore=dN;fy.InMemoryStore=DW;Object.defineProperty(fy,"stores_exports",{enumerable:!0,get:function(){return BOe}})});var YT=v(Vs=>{"use strict";p();var zOe={and:"and",or:"or",not:"not"},VOe={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"},ZOe=class{},pN=class{accept(t){if(this.exprName==="Operation")return t.visitOperation(this);if(this.exprName==="Comparison")return t.visitComparison(this);if(this.exprName==="StructuredQuery")return t.visitStructuredQuery(this);throw new Error("Unknown Expression type")}},fN=class extends pN{},HOe=class extends fN{constructor(e,r,n){super();f(this,"exprName","Comparison");this.comparator=e,this.attribute=r,this.value=n}},WOe=class extends fN{constructor(e,r){super();f(this,"exprName","Operation");this.operator=e,this.args=r}},GOe=class extends pN{constructor(e,r){super();f(this,"exprName","StructuredQuery");this.query=e,this.filter=r}};Vs.Comparators=VOe;Vs.Comparison=HOe;Vs.Expression=pN;Vs.FilterDirective=fN;Vs.Operation=WOe;Vs.Operators=zOe;Vs.StructuredQuery=GOe;Vs.Visitor=ZOe});var JT=v(Ql=>{"use strict";p();function qW(t){return t&&typeof t=="object"&&!Array.isArray(t)}function KOe(t){return t?typeof t=="string"&&t.length>0||typeof t=="function"?!1:qW(t)&&Object.keys(t).length===0:!0}function LW(t){if(typeof t=="number")return t%1===0;if(typeof t=="string"){let e=parseInt(t,10);return!Number.isNaN(e)&&e%1===0&&e.toString()===t}return!1}function jW(t){if(typeof t=="number")return t%1!==0;if(typeof t=="string"){let e=parseFloat(t);return!Number.isNaN(e)&&e%1!==0&&e.toString()===t}return!1}function FW(t){return typeof t=="string"&&(Number.isNaN(parseFloat(t))||parseFloat(t).toString()!==t)}function BW(t){return typeof t=="boolean"}function YOe(t){let e;if(FW(t))e=t;else if(LW(t))e=parseInt(t,10);else if(jW(t))e=parseFloat(t);else if(BW(t))e=!!t;else throw new Error("Unsupported value type");return e}Ql.castValue=YOe;Ql.isBoolean=BW;Ql.isFilterEmpty=KOe;Ql.isFloat=jW;Ql.isInt=LW;Ql.isObject=qW;Ql.isString=FW});var mN=v(hN=>{"use strict";p();var ko=YT(),Kf=JT(),zW=class extends ko.Visitor{},JOe=class extends zW{constructor(e){super();f(this,"allowedOperators");f(this,"allowedComparators");this.allowedOperators=e?.allowedOperators??[ko.Operators.and,ko.Operators.or],this.allowedComparators=e?.allowedComparators??[ko.Comparators.eq,ko.Comparators.ne,ko.Comparators.gt,ko.Comparators.gte,ko.Comparators.lt,ko.Comparators.lte]}formatFunction(e){if(e in ko.Comparators){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(e)===-1)throw new Error(`Comparator ${e} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(e in ko.Operators){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(e)===-1)throw new Error(`Operator ${e} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`)}else throw new Error("Unknown comparator or operator");return`$${e}`}visitOperation(e){let r=e.args?.map(n=>n.accept(this));return{[this.formatFunction(e.operator)]:r}}visitComparison(e){return{[e.attribute]:{[this.formatFunction(e.comparator)]:Kf.castValue(e.value)}}}visitStructuredQuery(e){let r={};return e.filter&&(r={filter:e.filter.accept(this)}),r}mergeFilters(e,r,n="and",i=!1){if(!(Kf.isFilterEmpty(e)&&Kf.isFilterEmpty(r))){if(Kf.isFilterEmpty(e)||n==="replace")return Kf.isFilterEmpty(r)?void 0:r;if(Kf.isFilterEmpty(r))return i?e:n==="and"?void 0:e;if(n==="and")return{$and:[e,r]};if(n==="or")return{$or:[e,r]};throw new Error("Unknown merge type")}}};hN.BaseTranslator=zW;hN.BasicTranslator=JOe});var ZW=v(VW=>{"use strict";p();var Ct=YT(),Yf=JT(),XOe=mN(),QOe=class extends XOe.BaseTranslator{constructor(){super(...arguments);f(this,"allowedOperators",[Ct.Operators.and,Ct.Operators.or]);f(this,"allowedComparators",[Ct.Comparators.eq,Ct.Comparators.ne,Ct.Comparators.gt,Ct.Comparators.gte,Ct.Comparators.lt,Ct.Comparators.lte])}formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(e){switch(e){case"string":return[Ct.Comparators.eq,Ct.Comparators.ne,Ct.Comparators.gt,Ct.Comparators.gte,Ct.Comparators.lt,Ct.Comparators.lte];case"number":return[Ct.Comparators.eq,Ct.Comparators.ne,Ct.Comparators.gt,Ct.Comparators.gte,Ct.Comparators.lt,Ct.Comparators.lte];case"boolean":return[Ct.Comparators.eq,Ct.Comparators.ne];default:throw new Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case Ct.Comparators.eq:return(r,n)=>r===n;case Ct.Comparators.ne:return(r,n)=>r!==n;case Ct.Comparators.gt:return(r,n)=>r>n;case Ct.Comparators.gte:return(r,n)=>r>=n;case Ct.Comparators.lt:return(r,n)=>r<n;case Ct.Comparators.lte:return(r,n)=>r<=n;default:throw new Error("Unknown comparator")}}getOperatorFunction(e){switch(e){case Ct.Operators.and:return(r,n)=>r&&n;case Ct.Operators.or:return(r,n)=>r||n;default:throw new Error("Unknown operator")}}visitOperation(e){let{operator:r,args:n}=e;if(this.allowedOperators.includes(r)){let i=this.getOperatorFunction(r);return o=>n?n.reduce((a,s)=>{let l=s.accept(this);if(typeof l=="function")return i(a,l(o));throw new Error("Filter is not a function")},!0):!0}else throw new Error("Operator not allowed")}visitComparison(e){let{comparator:r,attribute:n,value:i}=e,o=[Ct.Comparators.ne];if(this.allowedComparators.includes(r)){if(!this.getAllowedComparatorsForType(typeof i).includes(r))throw new Error(`'${r}' comparator not allowed to be used with ${typeof i}`);let a=this.getComparatorFunction(r);return s=>{let l=s.metadata[n];return l===void 0?!!o.includes(r):a(l,Yf.castValue(i))}}else throw new Error("Comparator not allowed")}visitStructuredQuery(e){if(!e.filter)return{};let r=e.filter?.accept(this);if(typeof r!="function")throw new Error("Structured query filter is not a function");return{filter:r}}mergeFilters(e,r,n="and"){if(!(Yf.isFilterEmpty(e)&&Yf.isFilterEmpty(r))){if(Yf.isFilterEmpty(e)||n==="replace")return Yf.isFilterEmpty(r)?void 0:r;if(Yf.isFilterEmpty(r))return n==="and"?void 0:e;if(n==="and")return i=>e(i)&&r(i);if(n==="or")return i=>e(i)||r(i);throw new Error("Unknown merge type")}}};VW.FunctionalTranslator=QOe});var WW=v(vr=>{"use strict";p();Object.defineProperty(vr,Symbol.toStringTag,{value:"Module"});var eRe=de(),yn=YT(),ti=JT(),XT=mN(),HW=ZW(),tRe=eRe.__exportAll({BaseTranslator:()=>XT.BaseTranslator,BasicTranslator:()=>XT.BasicTranslator,Comparators:()=>yn.Comparators,Comparison:()=>yn.Comparison,Expression:()=>yn.Expression,FilterDirective:()=>yn.FilterDirective,FunctionalTranslator:()=>HW.FunctionalTranslator,Operation:()=>yn.Operation,Operators:()=>yn.Operators,StructuredQuery:()=>yn.StructuredQuery,Visitor:()=>yn.Visitor,castValue:()=>ti.castValue,isBoolean:()=>ti.isBoolean,isFilterEmpty:()=>ti.isFilterEmpty,isFloat:()=>ti.isFloat,isInt:()=>ti.isInt,isObject:()=>ti.isObject,isString:()=>ti.isString});vr.BaseTranslator=XT.BaseTranslator;vr.BasicTranslator=XT.BasicTranslator;vr.Comparators=yn.Comparators;vr.Comparison=yn.Comparison;vr.Expression=yn.Expression;vr.FilterDirective=yn.FilterDirective;vr.FunctionalTranslator=HW.FunctionalTranslator;vr.Operation=yn.Operation;vr.Operators=yn.Operators;vr.StructuredQuery=yn.StructuredQuery;vr.Visitor=yn.Visitor;vr.castValue=ti.castValue;vr.isBoolean=ti.isBoolean;vr.isFilterEmpty=ti.isFilterEmpty;vr.isFloat=ti.isFloat;vr.isInt=ti.isInt;vr.isObject=ti.isObject;vr.isString=ti.isString;Object.defineProperty(vr,"structured_query_exports",{enumerable:!0,get:function(){return tRe}})});var o8=v(zi=>{"use strict";p();var rRe=jr(),GW=_l(),QT=Fr(),nRe=jo(),iRe=Fp();ei();function hy(t){return rRe.BaseMessage.isInstance(t)?t.constructor.name||t.type:typeof t}function ek(t,e){return function(r,n){let{isNot:i,utils:o}=this;if(!e(r))return{pass:!1,message:()=>`${o.matcherHint(`toBe${t}`,void 0,void 0)}
333
333
 
334
334
  Expected: ${i?"not ":""}${t}
335
335
  Received: ${hy(r)}`,actual:hy(r),expected:t};if(n===void 0)return{pass:!0,message:()=>`${o.matcherHint(`toBe${t}`,void 0,void 0)}
@@ -352,19 +352,19 @@ Could not find matching tool call(s) for:
352
352
  ${n.printExpected(o)}
353
353
  Received tool calls: ${n.printReceived(i.map(a=>({name:a.name,id:a.id,args:a.args})))}`,actual:i.map(a=>({name:a.name,id:a.id,args:a.args})),expected:e}:{pass:!0,message:()=>`${n.matcherHint("toHaveToolCalls")}
354
354
 
355
- Expected AIMessage not to have matching tool calls`}}function eG(t,e){let{isNot:r,utils:n}=this;if(!QT.AIMessage.isInstance(t))return{pass:!1,message:()=>`${n.matcherHint("toHaveToolCallCount")}
355
+ Expected AIMessage not to have matching tool calls`}}function e8(t,e){let{isNot:r,utils:n}=this;if(!QT.AIMessage.isInstance(t))return{pass:!1,message:()=>`${n.matcherHint("toHaveToolCallCount")}
356
356
 
357
357
  Expected: AIMessage
358
358
  Received: ${hy(t)}`};let i=t.tool_calls?.length??0;return{pass:i===e,message:()=>`${n.matcherHint("toHaveToolCallCount")}
359
359
 
360
360
  Expected ${r?"not ":""}${e} tool call(s)
361
- Received: ${i}`,actual:i,expected:e}}function tG(t,e){let{isNot:r,utils:n}=this;if(!QT.AIMessage.isInstance(t))return{pass:!1,message:()=>`${n.matcherHint("toContainToolCall")}
361
+ Received: ${i}`,actual:i,expected:e}}function t8(t,e){let{isNot:r,utils:n}=this;if(!QT.AIMessage.isInstance(t))return{pass:!1,message:()=>`${n.matcherHint("toContainToolCall")}
362
362
 
363
363
  Expected: AIMessage
364
364
  Received: ${hy(t)}`};let i=t.tool_calls??[];return{pass:i.some(o=>Object.entries(e).every(([a,s])=>this.equals(o[a],s))),message:()=>`${n.matcherHint("toContainToolCall")}
365
365
 
366
366
  Expected AIMessage ${r?"not ":""}to contain a tool call matching ${n.printExpected(e)}
367
- Received tool calls: ${n.printReceived(i.map(o=>({name:o.name,id:o.id})))}`,actual:i.map(o=>({name:o.name,id:o.id})),expected:e}}function rG(t,e){let{isNot:r,utils:n}=this;if(!Array.isArray(t))return{pass:!1,message:()=>`${n.matcherHint("toHaveToolMessages")}
367
+ Received tool calls: ${n.printReceived(i.map(o=>({name:o.name,id:o.id})))}`,actual:i.map(o=>({name:o.name,id:o.id})),expected:e}}function r8(t,e){let{isNot:r,utils:n}=this;if(!Array.isArray(t))return{pass:!1,message:()=>`${n.matcherHint("toHaveToolMessages")}
368
368
 
369
369
  Expected an array of messages
370
370
  Received: ${typeof t}`};let i=t.filter(GW.ToolMessage.isInstance);if(i.length!==e.length)return{pass:!1,message:()=>`${n.matcherHint("toHaveToolMessages")}
@@ -375,7 +375,7 @@ Tool message at index ${o} did not match:
375
375
  Expected: ${n.printExpected(e[o])}
376
376
  Received: ${n.printReceived(a)}`},actual:i[o],expected:e[o]};return{pass:!0,message:()=>`${n.matcherHint("toHaveToolMessages")}
377
377
 
378
- Expected messages not to contain matching tool messages`}}function nG(t,e){let{isNot:r,utils:n}=this,i=t?.__interrupt__;if(!(Array.isArray(i)&&i.length>0))return{pass:!1,message:()=>`${n.matcherHint("toHaveBeenInterrupted")}
378
+ Expected messages not to contain matching tool messages`}}function n8(t,e){let{isNot:r,utils:n}=this,i=t?.__interrupt__;if(!(Array.isArray(i)&&i.length>0))return{pass:!1,message:()=>`${n.matcherHint("toHaveBeenInterrupted")}
379
379
 
380
380
  Expected result ${r?"not ":""}to have been interrupted
381
381
  Received __interrupt__: ${n.printReceived(i)}`};if(e===void 0)return{pass:!0,message:()=>`${n.matcherHint("toHaveBeenInterrupted")}
@@ -384,7 +384,7 @@ Expected result not to have been interrupted
384
384
  Received ${i.length} interrupt(s)`};let o=i[0]?.value;return{pass:this.equals(o,e),message:()=>`${n.matcherHint("toHaveBeenInterrupted")}
385
385
 
386
386
  Expected interrupt value: ${n.printExpected(e)}
387
- Received interrupt value: ${n.printReceived(o)}`,actual:o,expected:e}}function iG(t,e){let{isNot:r,utils:n}=this,i=t?.structuredResponse;return i===void 0?{pass:!1,message:()=>`${n.matcherHint("toHaveStructuredResponse")}
387
+ Received interrupt value: ${n.printReceived(o)}`,actual:o,expected:e}}function i8(t,e){let{isNot:r,utils:n}=this,i=t?.structuredResponse;return i===void 0?{pass:!1,message:()=>`${n.matcherHint("toHaveStructuredResponse")}
388
388
 
389
389
  Expected result ${r?"not ":""}to have a structured response
390
390
  Received structuredResponse: undefined`}:e===void 0?{pass:!0,message:()=>`${n.matcherHint("toHaveStructuredResponse")}
@@ -392,22 +392,22 @@ Received structuredResponse: undefined`}:e===void 0?{pass:!0,message:()=>`${n.ma
392
392
  Expected result not to have a structured response`}:{pass:Object.entries(e).every(([o,a])=>this.equals(i[o],a)),message:()=>`${n.matcherHint("toHaveStructuredResponse")}
393
393
 
394
394
  Expected structured response: ${n.printExpected(e)}
395
- Received structured response: ${n.printReceived(i)}`,actual:i,expected:e}}var oRe={toBeHumanMessage:KW,toBeAIMessage:YW,toBeSystemMessage:JW,toBeToolMessage:XW,toHaveToolCalls:QW,toHaveToolCallCount:eG,toContainToolCall:tG,toHaveToolMessages:rG,toHaveBeenInterrupted:nG,toHaveStructuredResponse:iG};zi.langchainMatchers=oRe;zi.toBeAIMessage=YW;zi.toBeHumanMessage=KW;zi.toBeSystemMessage=JW;zi.toBeToolMessage=XW;zi.toContainToolCall=tG;zi.toHaveBeenInterrupted=nG;zi.toHaveStructuredResponse=iG;zi.toHaveToolCallCount=eG;zi.toHaveToolCalls=QW;zi.toHaveToolMessages=rG});var cG=v(gN=>{"use strict";p();var aG=jr(),aRe=Fr(),sRe=br();ei();var lRe=MT();function uRe(t){return t.map(e=>e.text).filter(Boolean).join("-")}var sG=0;function cRe(){return sG+=1,`fake_tc_${sG}`}var lG=class uG extends lRe.BaseChatModel{constructor(){super({});f(this,"queue",[]);f(this,"_alwaysThrowError");f(this,"_structuredResponseValue");f(this,"_tools",[]);f(this,"_state",{callIndex:0,calls:[]})}get calls(){return this._state.calls}get callCount(){return this._state.calls.length}_llmType(){return"fake-model-builder"}_combineLLMOutput(){return[]}respond(r){return typeof r=="function"?this.queue.push({kind:"factory",factory:r}):aG.BaseMessage.isInstance(r)?this.queue.push({kind:"message",message:r}):this.queue.push({kind:"error",error:r}),this}respondWithTools(r){return this.queue.push({kind:"toolCalls",toolCalls:r.map(n=>({name:n.name,args:n.args,id:n.id??cRe(),type:"tool_call"}))}),this}alwaysThrow(r){return this._alwaysThrowError=r,this}structuredResponse(r){return this._structuredResponseValue=r,this}bindTools(r){let n=[...this._tools,...r],i=new uG;return i.queue=this.queue,i._alwaysThrowError=this._alwaysThrowError,i._structuredResponseValue=this._structuredResponseValue,i._tools=n,i._state=this._state,i.withConfig({})}withStructuredOutput(r,n){let{_structuredResponseValue:i}=this;return sRe.RunnableLambda.from(async()=>i)}async _generate(r,n,i){this._state.calls.push({messages:[...r],options:n});let o=this._state.callIndex;if(this._state.callIndex+=1,this._alwaysThrowError)throw this._alwaysThrowError;let a=this.queue[o];if(!a)throw new Error(`FakeModel: no response queued for invocation ${o} (${this.queue.length} total queued).`);if(a.kind==="error")throw a.error;if(a.kind==="factory"){let l=a.factory(r);if(!aG.BaseMessage.isInstance(l))throw l;return{generations:[{text:"",message:l}]}}if(a.kind==="message")return{generations:[{text:"",message:a.message}]};let s=uRe(r);return{generations:[{text:s,message:new aRe.AIMessage({content:s,id:o.toString(),tool_calls:a.toolCalls.length>0?a.toolCalls.map(l=>({...l,type:"tool_call"})):void 0})}],llmOutput:{}}}};function dRe(){return new lG}gN.FakeBuiltModel=lG;gN.fakeModel=dRe});var dG=v(_n=>{"use strict";p();Object.defineProperty(_n,Symbol.toStringTag,{value:"Module"});var pRe=de(),pr=oG(),tk=cG(),fRe=pRe.__exportAll({FakeBuiltModel:()=>tk.FakeBuiltModel,fakeModel:()=>tk.fakeModel,langchainMatchers:()=>pr.langchainMatchers,toBeAIMessage:()=>pr.toBeAIMessage,toBeHumanMessage:()=>pr.toBeHumanMessage,toBeSystemMessage:()=>pr.toBeSystemMessage,toBeToolMessage:()=>pr.toBeToolMessage,toContainToolCall:()=>pr.toContainToolCall,toHaveBeenInterrupted:()=>pr.toHaveBeenInterrupted,toHaveStructuredResponse:()=>pr.toHaveStructuredResponse,toHaveToolCallCount:()=>pr.toHaveToolCallCount,toHaveToolCalls:()=>pr.toHaveToolCalls,toHaveToolMessages:()=>pr.toHaveToolMessages});_n.FakeBuiltModel=tk.FakeBuiltModel;_n.fakeModel=tk.fakeModel;_n.langchainMatchers=pr.langchainMatchers;Object.defineProperty(_n,"testing_exports",{enumerable:!0,get:function(){return fRe}});_n.toBeAIMessage=pr.toBeAIMessage;_n.toBeHumanMessage=pr.toBeHumanMessage;_n.toBeSystemMessage=pr.toBeSystemMessage;_n.toBeToolMessage=pr.toBeToolMessage;_n.toContainToolCall=pr.toContainToolCall;_n.toHaveBeenInterrupted=pr.toHaveBeenInterrupted;_n.toHaveStructuredResponse=pr.toHaveStructuredResponse;_n.toHaveToolCallCount=pr.toHaveToolCallCount;_n.toHaveToolCalls=pr.toHaveToolCalls;_n.toHaveToolMessages=pr.toHaveToolMessages});var yN=v(my=>{"use strict";p();var hRe=Wa(),mRe=br();function pG(t){return t!==void 0&&Array.isArray(t.lc_namespace)}function fG(t){return t!==void 0&&mRe.Runnable.isRunnable(t)&&"lc_name"in t.constructor&&typeof t.constructor.lc_name=="function"&&t.constructor.lc_name()==="RunnableToolLike"}function hG(t){return!!t&&typeof t=="object"&&"name"in t&&"schema"in t&&(hRe.isInteropZodSchema(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 gRe(t){return hG(t)||fG(t)||pG(t)}my.isLangChainTool=gRe;my.isRunnableToolLike=fG;my.isStructuredTool=pG;my.isStructuredToolParams=hG});var rk=v(Ne=>{"use strict";p();Object.defineProperty(Ne,"__esModule",{value:!0});Ne.slugify=Ne.toUpperCase=Ne.toLowerCase=Ne.trim=Ne.normalize=Ne.overwrite=Ne.mime=Ne.property=Ne.endsWith=Ne.startsWith=Ne.includes=Ne.uppercase=Ne.lowercase=Ne.regex=Ne.length=Ne.minLength=Ne.maxLength=Ne.size=Ne.minSize=Ne.maxSize=Ne.multipleOf=Ne.nonnegative=Ne.nonpositive=Ne.negative=Ne.positive=Ne.gte=Ne.gt=Ne.lte=Ne.lt=void 0;var Dt=fn();Object.defineProperty(Ne,"lt",{enumerable:!0,get:function(){return Dt._lt}});Object.defineProperty(Ne,"lte",{enumerable:!0,get:function(){return Dt._lte}});Object.defineProperty(Ne,"gt",{enumerable:!0,get:function(){return Dt._gt}});Object.defineProperty(Ne,"gte",{enumerable:!0,get:function(){return Dt._gte}});Object.defineProperty(Ne,"positive",{enumerable:!0,get:function(){return Dt._positive}});Object.defineProperty(Ne,"negative",{enumerable:!0,get:function(){return Dt._negative}});Object.defineProperty(Ne,"nonpositive",{enumerable:!0,get:function(){return Dt._nonpositive}});Object.defineProperty(Ne,"nonnegative",{enumerable:!0,get:function(){return Dt._nonnegative}});Object.defineProperty(Ne,"multipleOf",{enumerable:!0,get:function(){return Dt._multipleOf}});Object.defineProperty(Ne,"maxSize",{enumerable:!0,get:function(){return Dt._maxSize}});Object.defineProperty(Ne,"minSize",{enumerable:!0,get:function(){return Dt._minSize}});Object.defineProperty(Ne,"size",{enumerable:!0,get:function(){return Dt._size}});Object.defineProperty(Ne,"maxLength",{enumerable:!0,get:function(){return Dt._maxLength}});Object.defineProperty(Ne,"minLength",{enumerable:!0,get:function(){return Dt._minLength}});Object.defineProperty(Ne,"length",{enumerable:!0,get:function(){return Dt._length}});Object.defineProperty(Ne,"regex",{enumerable:!0,get:function(){return Dt._regex}});Object.defineProperty(Ne,"lowercase",{enumerable:!0,get:function(){return Dt._lowercase}});Object.defineProperty(Ne,"uppercase",{enumerable:!0,get:function(){return Dt._uppercase}});Object.defineProperty(Ne,"includes",{enumerable:!0,get:function(){return Dt._includes}});Object.defineProperty(Ne,"startsWith",{enumerable:!0,get:function(){return Dt._startsWith}});Object.defineProperty(Ne,"endsWith",{enumerable:!0,get:function(){return Dt._endsWith}});Object.defineProperty(Ne,"property",{enumerable:!0,get:function(){return Dt._property}});Object.defineProperty(Ne,"mime",{enumerable:!0,get:function(){return Dt._mime}});Object.defineProperty(Ne,"overwrite",{enumerable:!0,get:function(){return Dt._overwrite}});Object.defineProperty(Ne,"normalize",{enumerable:!0,get:function(){return Dt._normalize}});Object.defineProperty(Ne,"trim",{enumerable:!0,get:function(){return Dt._trim}});Object.defineProperty(Ne,"toLowerCase",{enumerable:!0,get:function(){return Dt._toLowerCase}});Object.defineProperty(Ne,"toUpperCase",{enumerable:!0,get:function(){return Dt._toUpperCase}});Object.defineProperty(Ne,"slugify",{enumerable:!0,get:function(){return Dt._slugify}})});var gy=v(er=>{"use strict";p();var yRe=er&&er.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),_Re=er&&er.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),mG=er&&er.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&yRe(e,t,r);return _Re(e,t),e};Object.defineProperty(er,"__esModule",{value:!0});er.ZodISODuration=er.ZodISOTime=er.ZodISODate=er.ZodISODateTime=void 0;er.datetime=bRe;er.date=vRe;er.time=wRe;er.duration=SRe;var Vi=mG(fn()),nk=mG(yy());er.ZodISODateTime=Vi.$constructor("ZodISODateTime",(t,e)=>{Vi.$ZodISODateTime.init(t,e),nk.ZodStringFormat.init(t,e)});function bRe(t){return Vi._isoDateTime(er.ZodISODateTime,t)}er.ZodISODate=Vi.$constructor("ZodISODate",(t,e)=>{Vi.$ZodISODate.init(t,e),nk.ZodStringFormat.init(t,e)});function vRe(t){return Vi._isoDate(er.ZodISODate,t)}er.ZodISOTime=Vi.$constructor("ZodISOTime",(t,e)=>{Vi.$ZodISOTime.init(t,e),nk.ZodStringFormat.init(t,e)});function wRe(t){return Vi._isoTime(er.ZodISOTime,t)}er.ZodISODuration=Vi.$constructor("ZodISODuration",(t,e)=>{Vi.$ZodISODuration.init(t,e),nk.ZodStringFormat.init(t,e)});function SRe(t){return Vi._isoDuration(er.ZodISODuration,t)}});var _N=v(Zi=>{"use strict";p();var TRe=Zi&&Zi.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),kRe=Zi&&Zi.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),yG=Zi&&Zi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&TRe(e,t,r);return kRe(e,t),e};Object.defineProperty(Zi,"__esModule",{value:!0});Zi.ZodRealError=Zi.ZodError=void 0;var ik=yG(fn()),PRe=fn(),gG=yG(Oe()),_G=(t,e)=>{PRe.$ZodError.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>ik.formatError(t,r)},flatten:{value:r=>ik.flattenError(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,gG.jsonStringifyReplacer,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,gG.jsonStringifyReplacer,2)}},isEmpty:{get(){return t.issues.length===0}}})};Zi.ZodError=ik.$constructor("ZodError",_G);Zi.ZodRealError=ik.$constructor("ZodError",_G,{Parent:Error})});var bN=v(Pt=>{"use strict";p();var ERe=Pt&&Pt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),ARe=Pt&&Pt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),CRe=Pt&&Pt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&ERe(e,t,r);return ARe(e,t),e};Object.defineProperty(Pt,"__esModule",{value:!0});Pt.safeDecodeAsync=Pt.safeEncodeAsync=Pt.safeDecode=Pt.safeEncode=Pt.decodeAsync=Pt.encodeAsync=Pt.decode=Pt.encode=Pt.safeParseAsync=Pt.safeParse=Pt.parseAsync=Pt.parse=void 0;var Hi=CRe(fn()),Wi=_N();Pt.parse=Hi._parse(Wi.ZodRealError);Pt.parseAsync=Hi._parseAsync(Wi.ZodRealError);Pt.safeParse=Hi._safeParse(Wi.ZodRealError);Pt.safeParseAsync=Hi._safeParseAsync(Wi.ZodRealError);Pt.encode=Hi._encode(Wi.ZodRealError);Pt.decode=Hi._decode(Wi.ZodRealError);Pt.encodeAsync=Hi._encodeAsync(Wi.ZodRealError);Pt.decodeAsync=Hi._decodeAsync(Wi.ZodRealError);Pt.safeEncode=Hi._safeEncode(Wi.ZodRealError);Pt.safeDecode=Hi._safeDecode(Wi.ZodRealError);Pt.safeEncodeAsync=Hi._safeEncodeAsync(Wi.ZodRealError);Pt.safeDecodeAsync=Hi._safeDecodeAsync(Wi.ZodRealError)});var yy=v(S=>{"use strict";p();var xRe=S&&S.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),IRe=S&&S.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),_y=S&&S.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&xRe(e,t,r);return IRe(e,t),e};Object.defineProperty(S,"__esModule",{value:!0});S.ZodLiteral=S.ZodEnum=S.ZodSet=S.ZodMap=S.ZodRecord=S.ZodTuple=S.ZodIntersection=S.ZodDiscriminatedUnion=S.ZodXor=S.ZodUnion=S.ZodObject=S.ZodArray=S.ZodDate=S.ZodVoid=S.ZodNever=S.ZodUnknown=S.ZodAny=S.ZodNull=S.ZodUndefined=S.ZodSymbol=S.ZodBigIntFormat=S.ZodBigInt=S.ZodBoolean=S.ZodNumberFormat=S.ZodNumber=S.ZodCustomStringFormat=S.ZodJWT=S.ZodE164=S.ZodBase64URL=S.ZodBase64=S.ZodCIDRv6=S.ZodCIDRv4=S.ZodIPv6=S.ZodMAC=S.ZodIPv4=S.ZodKSUID=S.ZodXID=S.ZodULID=S.ZodCUID2=S.ZodCUID=S.ZodNanoID=S.ZodEmoji=S.ZodURL=S.ZodUUID=S.ZodGUID=S.ZodEmail=S.ZodStringFormat=S.ZodString=S._ZodString=S.ZodType=void 0;S.stringbool=S.meta=S.describe=S.ZodCustom=S.ZodFunction=S.ZodPromise=S.ZodLazy=S.ZodTemplateLiteral=S.ZodReadonly=S.ZodPreprocess=S.ZodCodec=S.ZodPipe=S.ZodNaN=S.ZodCatch=S.ZodSuccess=S.ZodNonOptional=S.ZodPrefault=S.ZodDefault=S.ZodNullable=S.ZodExactOptional=S.ZodOptional=S.ZodTransform=S.ZodFile=void 0;S.string=ak;S.email=ORe;S.guid=RRe;S.uuid=NRe;S.uuidv4=$Re;S.uuidv6=MRe;S.uuidv7=DRe;S.url=URe;S.httpUrl=qRe;S.emoji=LRe;S.nanoid=jRe;S.cuid=FRe;S.cuid2=BRe;S.ulid=zRe;S.xid=VRe;S.ksuid=ZRe;S.ipv4=HRe;S.mac=WRe;S.ipv6=GRe;S.cidrv4=KRe;S.cidrv6=YRe;S.base64=JRe;S.base64url=XRe;S.e164=QRe;S.jwt=eNe;S.stringFormat=tNe;S.hostname=rNe;S.hex=nNe;S.hash=iNe;S.number=vG;S.int=wN;S.float32=oNe;S.float64=aNe;S.int32=sNe;S.uint32=lNe;S.boolean=wG;S.bigint=uNe;S.int64=cNe;S.uint64=dNe;S.symbol=pNe;S.undefined=fNe;S.null=SG;S.any=hNe;S.unknown=Jf;S.never=TN;S.void=mNe;S.date=gNe;S.array=uk;S.keyof=yNe;S.object=_Ne;S.strictObject=bNe;S.looseObject=vNe;S.union=kN;S.xor=wNe;S.discriminatedUnion=SNe;S.intersection=TG;S.tuple=kG;S.record=PG;S.partialRecord=TNe;S.looseRecord=kNe;S.map=PNe;S.set=ENe;S.enum=PN;S.nativeEnum=ANe;S.literal=CNe;S.file=xNe;S.transform=EN;S.optional=sk;S.exactOptional=EG;S.nullable=lk;S.nullish=INe;S._default=AG;S.prefault=CG;S.nonoptional=xG;S.success=ONe;S.catch=IG;S.nan=RNe;S.pipe=SN;S.codec=NNe;S.invertCodec=$Ne;S.readonly=OG;S.templateLiteral=MNe;S.lazy=RG;S.promise=DNe;S._function=ck;S.function=ck;S._function=ck;S.function=ck;S.check=UNe;S.custom=qNe;S.refine=NG;S.superRefine=$G;S.instanceof=LNe;S.json=FNe;S.preprocess=BNe;var N=_y(fn()),yt=fn(),lt=_y(Og()),vN=Ig(),Qe=_y(rk()),ok=_y(gy()),Gi=_y(bN()),bG=new WeakMap;function by(t,e,r){let n=Object.getPrototypeOf(t),i=bG.get(n);if(i||(i=new Set,bG.set(n,i)),!i.has(e)){i.add(e);for(let o in r){let a=r[o];Object.defineProperty(n,o,{configurable:!0,enumerable:!1,get(){let s=a.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:s}),s},set(s){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:s})}})}}}S.ZodType=N.$constructor("ZodType",(t,e)=>(N.$ZodType.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:(0,vN.createStandardJSONSchemaMethod)(t,"input"),output:(0,vN.createStandardJSONSchemaMethod)(t,"output")}}),t.toJSONSchema=(0,vN.createToJSONSchemaMethod)(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>Gi.parse(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Gi.safeParse(t,r,n),t.parseAsync=async(r,n)=>Gi.parseAsync(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Gi.safeParseAsync(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>Gi.encode(t,r,n),t.decode=(r,n)=>Gi.decode(t,r,n),t.encodeAsync=async(r,n)=>Gi.encodeAsync(t,r,n),t.decodeAsync=async(r,n)=>Gi.decodeAsync(t,r,n),t.safeEncode=(r,n)=>Gi.safeEncode(t,r,n),t.safeDecode=(r,n)=>Gi.safeDecode(t,r,n),t.safeEncodeAsync=async(r,n)=>Gi.safeEncodeAsync(t,r,n),t.safeDecodeAsync=async(r,n)=>Gi.safeDecodeAsync(t,r,n),by(t,"ZodType",{check(...r){let n=this.def;return this.clone(yt.util.mergeDefs(n,{checks:[...n.checks??[],...r.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return N.clone(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(NG(r,n))},superRefine(r,n){return this.check($G(r,n))},overwrite(r){return this.check(Qe.overwrite(r))},optional(){return sk(this)},exactOptional(){return EG(this)},nullable(){return lk(this)},nullish(){return sk(lk(this))},nonoptional(r){return xG(this,r)},array(){return uk(this)},or(r){return kN([this,r])},and(r){return TG(this,r)},transform(r){return SN(this,EN(r))},default(r){return AG(this,r)},prefault(r){return CG(this,r)},catch(r){return IG(this,r)},pipe(r){return SN(this,r)},readonly(){return OG(this)},describe(r){let n=this.clone();return N.globalRegistry.add(n,{description:r}),n},meta(...r){if(r.length===0)return N.globalRegistry.get(this);let n=this.clone();return N.globalRegistry.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return N.globalRegistry.get(t)?.description},configurable:!0}),t));S._ZodString=N.$constructor("_ZodString",(t,e)=>{N.$ZodString.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(n,i,o)=>lt.stringProcessor(t,n,i,o);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,by(t,"_ZodString",{regex(...n){return this.check(Qe.regex(...n))},includes(...n){return this.check(Qe.includes(...n))},startsWith(...n){return this.check(Qe.startsWith(...n))},endsWith(...n){return this.check(Qe.endsWith(...n))},min(...n){return this.check(Qe.minLength(...n))},max(...n){return this.check(Qe.maxLength(...n))},length(...n){return this.check(Qe.length(...n))},nonempty(...n){return this.check(Qe.minLength(1,...n))},lowercase(n){return this.check(Qe.lowercase(n))},uppercase(n){return this.check(Qe.uppercase(n))},trim(){return this.check(Qe.trim())},normalize(...n){return this.check(Qe.normalize(...n))},toLowerCase(){return this.check(Qe.toLowerCase())},toUpperCase(){return this.check(Qe.toUpperCase())},slugify(){return this.check(Qe.slugify())}})});S.ZodString=N.$constructor("ZodString",(t,e)=>{N.$ZodString.init(t,e),S._ZodString.init(t,e),t.email=r=>t.check(N._email(S.ZodEmail,r)),t.url=r=>t.check(N._url(S.ZodURL,r)),t.jwt=r=>t.check(N._jwt(S.ZodJWT,r)),t.emoji=r=>t.check(N._emoji(S.ZodEmoji,r)),t.guid=r=>t.check(N._guid(S.ZodGUID,r)),t.uuid=r=>t.check(N._uuid(S.ZodUUID,r)),t.uuidv4=r=>t.check(N._uuidv4(S.ZodUUID,r)),t.uuidv6=r=>t.check(N._uuidv6(S.ZodUUID,r)),t.uuidv7=r=>t.check(N._uuidv7(S.ZodUUID,r)),t.nanoid=r=>t.check(N._nanoid(S.ZodNanoID,r)),t.guid=r=>t.check(N._guid(S.ZodGUID,r)),t.cuid=r=>t.check(N._cuid(S.ZodCUID,r)),t.cuid2=r=>t.check(N._cuid2(S.ZodCUID2,r)),t.ulid=r=>t.check(N._ulid(S.ZodULID,r)),t.base64=r=>t.check(N._base64(S.ZodBase64,r)),t.base64url=r=>t.check(N._base64url(S.ZodBase64URL,r)),t.xid=r=>t.check(N._xid(S.ZodXID,r)),t.ksuid=r=>t.check(N._ksuid(S.ZodKSUID,r)),t.ipv4=r=>t.check(N._ipv4(S.ZodIPv4,r)),t.ipv6=r=>t.check(N._ipv6(S.ZodIPv6,r)),t.cidrv4=r=>t.check(N._cidrv4(S.ZodCIDRv4,r)),t.cidrv6=r=>t.check(N._cidrv6(S.ZodCIDRv6,r)),t.e164=r=>t.check(N._e164(S.ZodE164,r)),t.datetime=r=>t.check(ok.datetime(r)),t.date=r=>t.check(ok.date(r)),t.time=r=>t.check(ok.time(r)),t.duration=r=>t.check(ok.duration(r))});function ak(t){return N._string(S.ZodString,t)}S.ZodStringFormat=N.$constructor("ZodStringFormat",(t,e)=>{N.$ZodStringFormat.init(t,e),S._ZodString.init(t,e)});S.ZodEmail=N.$constructor("ZodEmail",(t,e)=>{N.$ZodEmail.init(t,e),S.ZodStringFormat.init(t,e)});function ORe(t){return N._email(S.ZodEmail,t)}S.ZodGUID=N.$constructor("ZodGUID",(t,e)=>{N.$ZodGUID.init(t,e),S.ZodStringFormat.init(t,e)});function RRe(t){return N._guid(S.ZodGUID,t)}S.ZodUUID=N.$constructor("ZodUUID",(t,e)=>{N.$ZodUUID.init(t,e),S.ZodStringFormat.init(t,e)});function NRe(t){return N._uuid(S.ZodUUID,t)}function $Re(t){return N._uuidv4(S.ZodUUID,t)}function MRe(t){return N._uuidv6(S.ZodUUID,t)}function DRe(t){return N._uuidv7(S.ZodUUID,t)}S.ZodURL=N.$constructor("ZodURL",(t,e)=>{N.$ZodURL.init(t,e),S.ZodStringFormat.init(t,e)});function URe(t){return N._url(S.ZodURL,t)}function qRe(t){return N._url(S.ZodURL,{protocol:N.regexes.httpProtocol,hostname:N.regexes.domain,...yt.util.normalizeParams(t)})}S.ZodEmoji=N.$constructor("ZodEmoji",(t,e)=>{N.$ZodEmoji.init(t,e),S.ZodStringFormat.init(t,e)});function LRe(t){return N._emoji(S.ZodEmoji,t)}S.ZodNanoID=N.$constructor("ZodNanoID",(t,e)=>{N.$ZodNanoID.init(t,e),S.ZodStringFormat.init(t,e)});function jRe(t){return N._nanoid(S.ZodNanoID,t)}S.ZodCUID=N.$constructor("ZodCUID",(t,e)=>{N.$ZodCUID.init(t,e),S.ZodStringFormat.init(t,e)});function FRe(t){return N._cuid(S.ZodCUID,t)}S.ZodCUID2=N.$constructor("ZodCUID2",(t,e)=>{N.$ZodCUID2.init(t,e),S.ZodStringFormat.init(t,e)});function BRe(t){return N._cuid2(S.ZodCUID2,t)}S.ZodULID=N.$constructor("ZodULID",(t,e)=>{N.$ZodULID.init(t,e),S.ZodStringFormat.init(t,e)});function zRe(t){return N._ulid(S.ZodULID,t)}S.ZodXID=N.$constructor("ZodXID",(t,e)=>{N.$ZodXID.init(t,e),S.ZodStringFormat.init(t,e)});function VRe(t){return N._xid(S.ZodXID,t)}S.ZodKSUID=N.$constructor("ZodKSUID",(t,e)=>{N.$ZodKSUID.init(t,e),S.ZodStringFormat.init(t,e)});function ZRe(t){return N._ksuid(S.ZodKSUID,t)}S.ZodIPv4=N.$constructor("ZodIPv4",(t,e)=>{N.$ZodIPv4.init(t,e),S.ZodStringFormat.init(t,e)});function HRe(t){return N._ipv4(S.ZodIPv4,t)}S.ZodMAC=N.$constructor("ZodMAC",(t,e)=>{N.$ZodMAC.init(t,e),S.ZodStringFormat.init(t,e)});function WRe(t){return N._mac(S.ZodMAC,t)}S.ZodIPv6=N.$constructor("ZodIPv6",(t,e)=>{N.$ZodIPv6.init(t,e),S.ZodStringFormat.init(t,e)});function GRe(t){return N._ipv6(S.ZodIPv6,t)}S.ZodCIDRv4=N.$constructor("ZodCIDRv4",(t,e)=>{N.$ZodCIDRv4.init(t,e),S.ZodStringFormat.init(t,e)});function KRe(t){return N._cidrv4(S.ZodCIDRv4,t)}S.ZodCIDRv6=N.$constructor("ZodCIDRv6",(t,e)=>{N.$ZodCIDRv6.init(t,e),S.ZodStringFormat.init(t,e)});function YRe(t){return N._cidrv6(S.ZodCIDRv6,t)}S.ZodBase64=N.$constructor("ZodBase64",(t,e)=>{N.$ZodBase64.init(t,e),S.ZodStringFormat.init(t,e)});function JRe(t){return N._base64(S.ZodBase64,t)}S.ZodBase64URL=N.$constructor("ZodBase64URL",(t,e)=>{N.$ZodBase64URL.init(t,e),S.ZodStringFormat.init(t,e)});function XRe(t){return N._base64url(S.ZodBase64URL,t)}S.ZodE164=N.$constructor("ZodE164",(t,e)=>{N.$ZodE164.init(t,e),S.ZodStringFormat.init(t,e)});function QRe(t){return N._e164(S.ZodE164,t)}S.ZodJWT=N.$constructor("ZodJWT",(t,e)=>{N.$ZodJWT.init(t,e),S.ZodStringFormat.init(t,e)});function eNe(t){return N._jwt(S.ZodJWT,t)}S.ZodCustomStringFormat=N.$constructor("ZodCustomStringFormat",(t,e)=>{N.$ZodCustomStringFormat.init(t,e),S.ZodStringFormat.init(t,e)});function tNe(t,e,r={}){return N._stringFormat(S.ZodCustomStringFormat,t,e,r)}function rNe(t){return N._stringFormat(S.ZodCustomStringFormat,"hostname",N.regexes.hostname,t)}function nNe(t){return N._stringFormat(S.ZodCustomStringFormat,"hex",N.regexes.hex,t)}function iNe(t,e){let r=e?.enc??"hex",n=`${t}_${r}`,i=N.regexes[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return N._stringFormat(S.ZodCustomStringFormat,n,i,e)}S.ZodNumber=N.$constructor("ZodNumber",(t,e)=>{N.$ZodNumber.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(n,i,o)=>lt.numberProcessor(t,n,i,o),by(t,"ZodNumber",{gt(n,i){return this.check(Qe.gt(n,i))},gte(n,i){return this.check(Qe.gte(n,i))},min(n,i){return this.check(Qe.gte(n,i))},lt(n,i){return this.check(Qe.lt(n,i))},lte(n,i){return this.check(Qe.lte(n,i))},max(n,i){return this.check(Qe.lte(n,i))},int(n){return this.check(wN(n))},safe(n){return this.check(wN(n))},positive(n){return this.check(Qe.gt(0,n))},nonnegative(n){return this.check(Qe.gte(0,n))},negative(n){return this.check(Qe.lt(0,n))},nonpositive(n){return this.check(Qe.lte(0,n))},multipleOf(n,i){return this.check(Qe.multipleOf(n,i))},step(n,i){return this.check(Qe.multipleOf(n,i))},finite(){return this}});let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function vG(t){return N._number(S.ZodNumber,t)}S.ZodNumberFormat=N.$constructor("ZodNumberFormat",(t,e)=>{N.$ZodNumberFormat.init(t,e),S.ZodNumber.init(t,e)});function wN(t){return N._int(S.ZodNumberFormat,t)}function oNe(t){return N._float32(S.ZodNumberFormat,t)}function aNe(t){return N._float64(S.ZodNumberFormat,t)}function sNe(t){return N._int32(S.ZodNumberFormat,t)}function lNe(t){return N._uint32(S.ZodNumberFormat,t)}S.ZodBoolean=N.$constructor("ZodBoolean",(t,e)=>{N.$ZodBoolean.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.booleanProcessor(t,r,n,i)});function wG(t){return N._boolean(S.ZodBoolean,t)}S.ZodBigInt=N.$constructor("ZodBigInt",(t,e)=>{N.$ZodBigInt.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(n,i,o)=>lt.bigintProcessor(t,n,i,o),t.gte=(n,i)=>t.check(Qe.gte(n,i)),t.min=(n,i)=>t.check(Qe.gte(n,i)),t.gt=(n,i)=>t.check(Qe.gt(n,i)),t.gte=(n,i)=>t.check(Qe.gte(n,i)),t.min=(n,i)=>t.check(Qe.gte(n,i)),t.lt=(n,i)=>t.check(Qe.lt(n,i)),t.lte=(n,i)=>t.check(Qe.lte(n,i)),t.max=(n,i)=>t.check(Qe.lte(n,i)),t.positive=n=>t.check(Qe.gt(BigInt(0),n)),t.negative=n=>t.check(Qe.lt(BigInt(0),n)),t.nonpositive=n=>t.check(Qe.lte(BigInt(0),n)),t.nonnegative=n=>t.check(Qe.gte(BigInt(0),n)),t.multipleOf=(n,i)=>t.check(Qe.multipleOf(n,i));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});function uNe(t){return N._bigint(S.ZodBigInt,t)}S.ZodBigIntFormat=N.$constructor("ZodBigIntFormat",(t,e)=>{N.$ZodBigIntFormat.init(t,e),S.ZodBigInt.init(t,e)});function cNe(t){return N._int64(S.ZodBigIntFormat,t)}function dNe(t){return N._uint64(S.ZodBigIntFormat,t)}S.ZodSymbol=N.$constructor("ZodSymbol",(t,e)=>{N.$ZodSymbol.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.symbolProcessor(t,r,n,i)});function pNe(t){return N._symbol(S.ZodSymbol,t)}S.ZodUndefined=N.$constructor("ZodUndefined",(t,e)=>{N.$ZodUndefined.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.undefinedProcessor(t,r,n,i)});function fNe(t){return N._undefined(S.ZodUndefined,t)}S.ZodNull=N.$constructor("ZodNull",(t,e)=>{N.$ZodNull.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.nullProcessor(t,r,n,i)});function SG(t){return N._null(S.ZodNull,t)}S.ZodAny=N.$constructor("ZodAny",(t,e)=>{N.$ZodAny.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.anyProcessor(t,r,n,i)});function hNe(){return N._any(S.ZodAny)}S.ZodUnknown=N.$constructor("ZodUnknown",(t,e)=>{N.$ZodUnknown.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.unknownProcessor(t,r,n,i)});function Jf(){return N._unknown(S.ZodUnknown)}S.ZodNever=N.$constructor("ZodNever",(t,e)=>{N.$ZodNever.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.neverProcessor(t,r,n,i)});function TN(t){return N._never(S.ZodNever,t)}S.ZodVoid=N.$constructor("ZodVoid",(t,e)=>{N.$ZodVoid.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.voidProcessor(t,r,n,i)});function mNe(t){return N._void(S.ZodVoid,t)}S.ZodDate=N.$constructor("ZodDate",(t,e)=>{N.$ZodDate.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(n,i,o)=>lt.dateProcessor(t,n,i,o),t.min=(n,i)=>t.check(Qe.gte(n,i)),t.max=(n,i)=>t.check(Qe.lte(n,i));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});function gNe(t){return N._date(S.ZodDate,t)}S.ZodArray=N.$constructor("ZodArray",(t,e)=>{N.$ZodArray.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.arrayProcessor(t,r,n,i),t.element=e.element,by(t,"ZodArray",{min(r,n){return this.check(Qe.minLength(r,n))},nonempty(r){return this.check(Qe.minLength(1,r))},max(r,n){return this.check(Qe.maxLength(r,n))},length(r,n){return this.check(Qe.length(r,n))},unwrap(){return this.element}})});function uk(t,e){return N._array(S.ZodArray,t,e)}function yNe(t){let e=t._zod.def.shape;return PN(Object.keys(e))}S.ZodObject=N.$constructor("ZodObject",(t,e)=>{N.$ZodObjectJIT.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.objectProcessor(t,r,n,i),yt.util.defineLazy(t,"shape",()=>e.shape),by(t,"ZodObject",{keyof(){return PN(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Jf()})},loose(){return this.clone({...this._zod.def,catchall:Jf()})},strict(){return this.clone({...this._zod.def,catchall:TN()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return yt.util.extend(this,r)},safeExtend(r){return yt.util.safeExtend(this,r)},merge(r){return yt.util.merge(this,r)},pick(r){return yt.util.pick(this,r)},omit(r){return yt.util.omit(this,r)},partial(...r){return yt.util.partial(S.ZodOptional,this,r[0])},required(...r){return yt.util.required(S.ZodNonOptional,this,r[0])}})});function _Ne(t,e){let r={type:"object",shape:t??{},...yt.util.normalizeParams(e)};return new S.ZodObject(r)}function bNe(t,e){return new S.ZodObject({type:"object",shape:t,catchall:TN(),...yt.util.normalizeParams(e)})}function vNe(t,e){return new S.ZodObject({type:"object",shape:t,catchall:Jf(),...yt.util.normalizeParams(e)})}S.ZodUnion=N.$constructor("ZodUnion",(t,e)=>{N.$ZodUnion.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.unionProcessor(t,r,n,i),t.options=e.options});function kN(t,e){return new S.ZodUnion({type:"union",options:t,...yt.util.normalizeParams(e)})}S.ZodXor=N.$constructor("ZodXor",(t,e)=>{S.ZodUnion.init(t,e),N.$ZodXor.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.unionProcessor(t,r,n,i),t.options=e.options});function wNe(t,e){return new S.ZodXor({type:"union",options:t,inclusive:!1,...yt.util.normalizeParams(e)})}S.ZodDiscriminatedUnion=N.$constructor("ZodDiscriminatedUnion",(t,e)=>{S.ZodUnion.init(t,e),N.$ZodDiscriminatedUnion.init(t,e)});function SNe(t,e,r){return new S.ZodDiscriminatedUnion({type:"union",options:e,discriminator:t,...yt.util.normalizeParams(r)})}S.ZodIntersection=N.$constructor("ZodIntersection",(t,e)=>{N.$ZodIntersection.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.intersectionProcessor(t,r,n,i)});function TG(t,e){return new S.ZodIntersection({type:"intersection",left:t,right:e})}S.ZodTuple=N.$constructor("ZodTuple",(t,e)=>{N.$ZodTuple.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.tupleProcessor(t,r,n,i),t.rest=r=>t.clone({...t._zod.def,rest:r})});function kG(t,e,r){let n=e instanceof N.$ZodType,i=n?r:e,o=n?e:null;return new S.ZodTuple({type:"tuple",items:t,rest:o,...yt.util.normalizeParams(i)})}S.ZodRecord=N.$constructor("ZodRecord",(t,e)=>{N.$ZodRecord.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.recordProcessor(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function PG(t,e,r){return!e||!e._zod?new S.ZodRecord({type:"record",keyType:ak(),valueType:t,...yt.util.normalizeParams(e)}):new S.ZodRecord({type:"record",keyType:t,valueType:e,...yt.util.normalizeParams(r)})}function TNe(t,e,r){let n=N.clone(t);return n._zod.values=void 0,new S.ZodRecord({type:"record",keyType:n,valueType:e,...yt.util.normalizeParams(r)})}function kNe(t,e,r){return new S.ZodRecord({type:"record",keyType:t,valueType:e,mode:"loose",...yt.util.normalizeParams(r)})}S.ZodMap=N.$constructor("ZodMap",(t,e)=>{N.$ZodMap.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.mapProcessor(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(N._minSize(...r)),t.nonempty=r=>t.check(N._minSize(1,r)),t.max=(...r)=>t.check(N._maxSize(...r)),t.size=(...r)=>t.check(N._size(...r))});function PNe(t,e,r){return new S.ZodMap({type:"map",keyType:t,valueType:e,...yt.util.normalizeParams(r)})}S.ZodSet=N.$constructor("ZodSet",(t,e)=>{N.$ZodSet.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.setProcessor(t,r,n,i),t.min=(...r)=>t.check(N._minSize(...r)),t.nonempty=r=>t.check(N._minSize(1,r)),t.max=(...r)=>t.check(N._maxSize(...r)),t.size=(...r)=>t.check(N._size(...r))});function ENe(t,e){return new S.ZodSet({type:"set",valueType:t,...yt.util.normalizeParams(e)})}S.ZodEnum=N.$constructor("ZodEnum",(t,e)=>{N.$ZodEnum.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(n,i,o)=>lt.enumProcessor(t,n,i,o),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let o={};for(let a of n)if(r.has(a))o[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new S.ZodEnum({...e,checks:[],...yt.util.normalizeParams(i),entries:o})},t.exclude=(n,i)=>{let o={...e.entries};for(let a of n)if(r.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new S.ZodEnum({...e,checks:[],...yt.util.normalizeParams(i),entries:o})}});function PN(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new S.ZodEnum({type:"enum",entries:r,...yt.util.normalizeParams(e)})}function ANe(t,e){return new S.ZodEnum({type:"enum",entries:t,...yt.util.normalizeParams(e)})}S.ZodLiteral=N.$constructor("ZodLiteral",(t,e)=>{N.$ZodLiteral.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.literalProcessor(t,r,n,i),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function CNe(t,e){return new S.ZodLiteral({type:"literal",values:Array.isArray(t)?t:[t],...yt.util.normalizeParams(e)})}S.ZodFile=N.$constructor("ZodFile",(t,e)=>{N.$ZodFile.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.fileProcessor(t,r,n,i),t.min=(r,n)=>t.check(N._minSize(r,n)),t.max=(r,n)=>t.check(N._maxSize(r,n)),t.mime=(r,n)=>t.check(N._mime(Array.isArray(r)?r:[r],n))});function xNe(t){return N._file(S.ZodFile,t)}S.ZodTransform=N.$constructor("ZodTransform",(t,e)=>{N.$ZodTransform.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.transformProcessor(t,r,n,i),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new N.$ZodEncodeError(t.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(yt.util.issue(o,r.value,e));else{let a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),r.issues.push(yt.util.issue(a))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(o=>(r.value=o,r.fallback=!0,r)):(r.value=i,r.fallback=!0,r)}});function EN(t){return new S.ZodTransform({type:"transform",transform:t})}S.ZodOptional=N.$constructor("ZodOptional",(t,e)=>{N.$ZodOptional.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.optionalProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function sk(t){return new S.ZodOptional({type:"optional",innerType:t})}S.ZodExactOptional=N.$constructor("ZodExactOptional",(t,e)=>{N.$ZodExactOptional.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.optionalProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function EG(t){return new S.ZodExactOptional({type:"optional",innerType:t})}S.ZodNullable=N.$constructor("ZodNullable",(t,e)=>{N.$ZodNullable.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.nullableProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function lk(t){return new S.ZodNullable({type:"nullable",innerType:t})}function INe(t){return sk(lk(t))}S.ZodDefault=N.$constructor("ZodDefault",(t,e)=>{N.$ZodDefault.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.defaultProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function AG(t,e){return new S.ZodDefault({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():yt.util.shallowClone(e)}})}S.ZodPrefault=N.$constructor("ZodPrefault",(t,e)=>{N.$ZodPrefault.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.prefaultProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function CG(t,e){return new S.ZodPrefault({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():yt.util.shallowClone(e)}})}S.ZodNonOptional=N.$constructor("ZodNonOptional",(t,e)=>{N.$ZodNonOptional.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.nonoptionalProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function xG(t,e){return new S.ZodNonOptional({type:"nonoptional",innerType:t,...yt.util.normalizeParams(e)})}S.ZodSuccess=N.$constructor("ZodSuccess",(t,e)=>{N.$ZodSuccess.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.successProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function ONe(t){return new S.ZodSuccess({type:"success",innerType:t})}S.ZodCatch=N.$constructor("ZodCatch",(t,e)=>{N.$ZodCatch.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.catchProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function IG(t,e){return new S.ZodCatch({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}S.ZodNaN=N.$constructor("ZodNaN",(t,e)=>{N.$ZodNaN.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.nanProcessor(t,r,n,i)});function RNe(t){return N._nan(S.ZodNaN,t)}S.ZodPipe=N.$constructor("ZodPipe",(t,e)=>{N.$ZodPipe.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.pipeProcessor(t,r,n,i),t.in=e.in,t.out=e.out});function SN(t,e){return new S.ZodPipe({type:"pipe",in:t,out:e})}S.ZodCodec=N.$constructor("ZodCodec",(t,e)=>{S.ZodPipe.init(t,e),N.$ZodCodec.init(t,e)});function NNe(t,e,r){return new S.ZodCodec({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function $Ne(t){let e=t._zod.def;return new S.ZodCodec({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}S.ZodPreprocess=N.$constructor("ZodPreprocess",(t,e)=>{S.ZodPipe.init(t,e),N.$ZodPreprocess.init(t,e)});S.ZodReadonly=N.$constructor("ZodReadonly",(t,e)=>{N.$ZodReadonly.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.readonlyProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function OG(t){return new S.ZodReadonly({type:"readonly",innerType:t})}S.ZodTemplateLiteral=N.$constructor("ZodTemplateLiteral",(t,e)=>{N.$ZodTemplateLiteral.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.templateLiteralProcessor(t,r,n,i)});function MNe(t,e){return new S.ZodTemplateLiteral({type:"template_literal",parts:t,...yt.util.normalizeParams(e)})}S.ZodLazy=N.$constructor("ZodLazy",(t,e)=>{N.$ZodLazy.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.lazyProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.getter()});function RG(t){return new S.ZodLazy({type:"lazy",getter:t})}S.ZodPromise=N.$constructor("ZodPromise",(t,e)=>{N.$ZodPromise.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.promiseProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function DNe(t){return new S.ZodPromise({type:"promise",innerType:t})}S.ZodFunction=N.$constructor("ZodFunction",(t,e)=>{N.$ZodFunction.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.functionProcessor(t,r,n,i)});function ck(t){return new S.ZodFunction({type:"function",input:Array.isArray(t?.input)?kG(t?.input):t?.input??uk(Jf()),output:t?.output??Jf()})}S.ZodCustom=N.$constructor("ZodCustom",(t,e)=>{N.$ZodCustom.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.customProcessor(t,r,n,i)});function UNe(t){let e=new N.$ZodCheck({check:"custom"});return e._zod.check=t,e}function qNe(t,e){return N._custom(S.ZodCustom,t??(()=>!0),e)}function NG(t,e={}){return N._refine(S.ZodCustom,t,e)}function $G(t,e){return N._superRefine(t,e)}S.describe=N.describe;S.meta=N.meta;function LNe(t,e={}){let r=new S.ZodCustom({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...yt.util.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=n=>{n.value instanceof t||n.issues.push({code:"invalid_type",expected:t.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}var jNe=(...t)=>N._stringbool({Codec:S.ZodCodec,Boolean:S.ZodBoolean,String:S.ZodString},...t);S.stringbool=jNe;function FNe(t){let e=RG(()=>kN([ak(t),vG(),wG(),SG(),uk(e),PG(ak(),e)]));return e}function BNe(t,e){return new S.ZodPreprocess({type:"pipe",in:EN(t),out:e})}});var qG=v(Zr=>{"use strict";p();var zNe=Zr&&Zr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),VNe=Zr&&Zr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),ZNe=Zr&&Zr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&zNe(e,t,r);return VNe(e,t),e};Object.defineProperty(Zr,"__esModule",{value:!0});Zr.ZodFirstPartyTypeKind=Zr.config=Zr.$brand=Zr.ZodIssueCode=void 0;Zr.setErrorMap=HNe;Zr.getErrorMap=WNe;var DG=ZNe(fn());Zr.ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var UG=fn();Object.defineProperty(Zr,"$brand",{enumerable:!0,get:function(){return UG.$brand}});Object.defineProperty(Zr,"config",{enumerable:!0,get:function(){return UG.config}});function HNe(t){DG.config({customError:t})}function WNe(){return DG.config().customError}var MG;MG||(Zr.ZodFirstPartyTypeKind=MG={})});var jG=v(Zs=>{"use strict";p();var GNe=Zs&&Zs.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),KNe=Zs&&Zs.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),AN=Zs&&Zs.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&GNe(e,t,r);return KNe(e,t),e};Object.defineProperty(Zs,"__esModule",{value:!0});Zs.fromJSONSchema=n$e;var YNe=Ag(),JNe=AN(rk()),XNe=AN(gy()),QNe=AN(yy()),ge={...QNe,...JNe,iso:XNe},e$e=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function t$e(t,e){let r=t.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function r$e(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=t.slice(1).split("/").filter(Boolean);if(r.length===0)return e.rootSchema;let n=e.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===n){let i=r[1];if(!i||!e.defs[i])throw new Error(`Reference not found: ${t}`);return e.defs[i]}throw new Error(`Reference not found: ${t}`)}function LG(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return ge.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let i=t.$ref;if(e.refs.has(i))return e.refs.get(i);if(e.processing.has(i))return ge.lazy(()=>{if(!e.refs.has(i))throw new Error(`Circular reference not resolved: ${i}`);return e.refs.get(i)});e.processing.add(i);let o=r$e(i,e),a=bn(o,e);return e.refs.set(i,a),e.processing.delete(i),a}if(t.enum!==void 0){let i=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&i.length===1&&i[0]===null)return ge.null();if(i.length===0)return ge.never();if(i.length===1)return ge.literal(i[0]);if(i.every(a=>typeof a=="string"))return ge.enum(i);let o=i.map(a=>ge.literal(a));return o.length<2?o[0]:ge.union([o[0],o[1],...o.slice(2)])}if(t.const!==void 0)return ge.literal(t.const);let r=t.type;if(Array.isArray(r)){let i=r.map(o=>{let a={...t,type:o};return LG(a,e)});return i.length===0?ge.never():i.length===1?i[0]:ge.union(i)}if(!r)return ge.any();let n;switch(r){case"string":{let i=ge.string();if(t.format){let o=t.format;o==="email"?i=i.check(ge.email()):o==="uri"||o==="uri-reference"?i=i.check(ge.url()):o==="uuid"||o==="guid"?i=i.check(ge.uuid()):o==="date-time"?i=i.check(ge.iso.datetime()):o==="date"?i=i.check(ge.iso.date()):o==="time"?i=i.check(ge.iso.time()):o==="duration"?i=i.check(ge.iso.duration()):o==="ipv4"?i=i.check(ge.ipv4()):o==="ipv6"?i=i.check(ge.ipv6()):o==="mac"?i=i.check(ge.mac()):o==="cidr"?i=i.check(ge.cidrv4()):o==="cidr-v6"?i=i.check(ge.cidrv6()):o==="base64"?i=i.check(ge.base64()):o==="base64url"?i=i.check(ge.base64url()):o==="e164"?i=i.check(ge.e164()):o==="jwt"?i=i.check(ge.jwt()):o==="emoji"?i=i.check(ge.emoji()):o==="nanoid"?i=i.check(ge.nanoid()):o==="cuid"?i=i.check(ge.cuid()):o==="cuid2"?i=i.check(ge.cuid2()):o==="ulid"?i=i.check(ge.ulid()):o==="xid"?i=i.check(ge.xid()):o==="ksuid"&&(i=i.check(ge.ksuid()))}typeof t.minLength=="number"&&(i=i.min(t.minLength)),typeof t.maxLength=="number"&&(i=i.max(t.maxLength)),t.pattern&&(i=i.regex(new RegExp(t.pattern))),n=i;break}case"number":case"integer":{let i=r==="integer"?ge.number().int():ge.number();typeof t.minimum=="number"&&(i=i.min(t.minimum)),typeof t.maximum=="number"&&(i=i.max(t.maximum)),typeof t.exclusiveMinimum=="number"?i=i.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(i=i.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?i=i.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(i=i.lt(t.maximum)),typeof t.multipleOf=="number"&&(i=i.multipleOf(t.multipleOf)),n=i;break}case"boolean":{n=ge.boolean();break}case"null":{n=ge.null();break}case"object":{let i={},o=t.properties||{},a=new Set(t.required||[]);for(let[l,u]of Object.entries(o)){let c=bn(u,e);i[l]=a.has(l)?c:c.optional()}if(t.propertyNames){let l=bn(t.propertyNames,e),u=t.additionalProperties&&typeof t.additionalProperties=="object"?bn(t.additionalProperties,e):ge.any();if(Object.keys(i).length===0){n=ge.record(l,u);break}let c=ge.object(i).passthrough(),d=ge.looseRecord(l,u);n=ge.intersection(c,d);break}if(t.patternProperties){let l=t.patternProperties,u=Object.keys(l),c=[];for(let h of u){let m=bn(l[h],e),g=ge.string().regex(new RegExp(h));c.push(ge.looseRecord(g,m))}let d=[];if(Object.keys(i).length>0&&d.push(ge.object(i).passthrough()),d.push(...c),d.length===0)n=ge.object({}).passthrough();else if(d.length===1)n=d[0];else{let h=ge.intersection(d[0],d[1]);for(let m=2;m<d.length;m++)h=ge.intersection(h,d[m]);n=h}break}let s=ge.object(i);t.additionalProperties===!1?n=s.strict():typeof t.additionalProperties=="object"?n=s.catchall(bn(t.additionalProperties,e)):n=s.passthrough();break}case"array":{let i=t.prefixItems,o=t.items;if(i&&Array.isArray(i)){let a=i.map(l=>bn(l,e)),s=o&&typeof o=="object"&&!Array.isArray(o)?bn(o,e):void 0;s?n=ge.tuple(a).rest(s):n=ge.tuple(a),typeof t.minItems=="number"&&(n=n.check(ge.minLength(t.minItems))),typeof t.maxItems=="number"&&(n=n.check(ge.maxLength(t.maxItems)))}else if(Array.isArray(o)){let a=o.map(l=>bn(l,e)),s=t.additionalItems&&typeof t.additionalItems=="object"?bn(t.additionalItems,e):void 0;s?n=ge.tuple(a).rest(s):n=ge.tuple(a),typeof t.minItems=="number"&&(n=n.check(ge.minLength(t.minItems))),typeof t.maxItems=="number"&&(n=n.check(ge.maxLength(t.maxItems)))}else if(o!==void 0){let a=bn(o,e),s=ge.array(a);typeof t.minItems=="number"&&(s=s.min(t.minItems)),typeof t.maxItems=="number"&&(s=s.max(t.maxItems)),n=s}else n=ge.array(ge.any());break}default:throw new Error(`Unsupported type: ${r}`)}return n}function bn(t,e){if(typeof t=="boolean")return t?ge.any():ge.never();let r=LG(t,e),n=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let s=t.anyOf.map(u=>bn(u,e)),l=ge.union(s);r=n?ge.intersection(r,l):l}if(t.oneOf&&Array.isArray(t.oneOf)){let s=t.oneOf.map(u=>bn(u,e)),l=ge.xor(s);r=n?ge.intersection(r,l):l}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=n?r:ge.any();else{let s=n?r:bn(t.allOf[0],e),l=n?0:1;for(let u=l;u<t.allOf.length;u++)s=ge.intersection(s,bn(t.allOf[u],e));r=s}t.nullable===!0&&e.version==="openapi-3.0"&&(r=ge.nullable(r)),t.readOnly===!0&&(r=ge.readonly(r)),t.default!==void 0&&(r=r.default(t.default));let i={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let s of o)s in t&&(i[s]=t[s]);let a=["contentEncoding","contentMediaType","contentSchema"];for(let s of a)s in t&&(i[s]=t[s]);for(let s of Object.keys(t))e$e.has(s)||(i[s]=t[s]);return Object.keys(i).length>0&&e.registry.add(r,i),t.description&&(r=r.describe(t.description)),r}function n$e(t,e){if(typeof t=="boolean")return t?ge.any():ge.never();let r;try{r=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let n=t$e(r,e?.defaultTarget),i=r.$defs||r.definitions||{},o={version:n,defs:i,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??YNe.globalRegistry};return bn(r,o)}});var BG=v(yi=>{"use strict";p();var i$e=yi&&yi.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),o$e=yi&&yi.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),FG=yi&&yi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&i$e(e,t,r);return o$e(e,t),e};Object.defineProperty(yi,"__esModule",{value:!0});yi.string=a$e;yi.number=s$e;yi.boolean=l$e;yi.bigint=u$e;yi.date=c$e;var vy=FG(fn()),wy=FG(yy());function a$e(t){return vy._coercedString(wy.ZodString,t)}function s$e(t){return vy._coercedNumber(wy.ZodNumber,t)}function l$e(t){return vy._coercedBoolean(wy.ZodBoolean,t)}function u$e(t){return vy._coercedBigint(wy.ZodBigInt,t)}function c$e(t){return vy._coercedDate(wy.ZodDate,t)}});var CN=v(Pe=>{"use strict";p();var zG=Pe&&Pe.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),d$e=Pe&&Pe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),dk=Pe&&Pe.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&zG(e,t,r);return d$e(e,t),e},Sy=Pe&&Pe.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&zG(e,t,r)},p$e=Pe&&Pe.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Pe,"__esModule",{value:!0});Pe.coerce=Pe.iso=Pe.ZodISODuration=Pe.ZodISOTime=Pe.ZodISODate=Pe.ZodISODateTime=Pe.locales=Pe.fromJSONSchema=Pe.toJSONSchema=Pe.NEVER=Pe.util=Pe.TimePrecision=Pe.flattenError=Pe.formatError=Pe.prettifyError=Pe.treeifyError=Pe.regexes=Pe.clone=Pe.$brand=Pe.$input=Pe.$output=Pe.config=Pe.registry=Pe.globalRegistry=Pe.core=void 0;Pe.core=dk(fn());Sy(yy(),Pe);Sy(rk(),Pe);Sy(_N(),Pe);Sy(bN(),Pe);Sy(qG(),Pe);var f$e=fn(),h$e=p$e($I());(0,f$e.config)((0,h$e.default)());var Nn=fn();Object.defineProperty(Pe,"globalRegistry",{enumerable:!0,get:function(){return Nn.globalRegistry}});Object.defineProperty(Pe,"registry",{enumerable:!0,get:function(){return Nn.registry}});Object.defineProperty(Pe,"config",{enumerable:!0,get:function(){return Nn.config}});Object.defineProperty(Pe,"$output",{enumerable:!0,get:function(){return Nn.$output}});Object.defineProperty(Pe,"$input",{enumerable:!0,get:function(){return Nn.$input}});Object.defineProperty(Pe,"$brand",{enumerable:!0,get:function(){return Nn.$brand}});Object.defineProperty(Pe,"clone",{enumerable:!0,get:function(){return Nn.clone}});Object.defineProperty(Pe,"regexes",{enumerable:!0,get:function(){return Nn.regexes}});Object.defineProperty(Pe,"treeifyError",{enumerable:!0,get:function(){return Nn.treeifyError}});Object.defineProperty(Pe,"prettifyError",{enumerable:!0,get:function(){return Nn.prettifyError}});Object.defineProperty(Pe,"formatError",{enumerable:!0,get:function(){return Nn.formatError}});Object.defineProperty(Pe,"flattenError",{enumerable:!0,get:function(){return Nn.flattenError}});Object.defineProperty(Pe,"TimePrecision",{enumerable:!0,get:function(){return Nn.TimePrecision}});Object.defineProperty(Pe,"util",{enumerable:!0,get:function(){return Nn.util}});Object.defineProperty(Pe,"NEVER",{enumerable:!0,get:function(){return Nn.NEVER}});var m$e=Og();Object.defineProperty(Pe,"toJSONSchema",{enumerable:!0,get:function(){return m$e.toJSONSchema}});var g$e=jG();Object.defineProperty(Pe,"fromJSONSchema",{enumerable:!0,get:function(){return g$e.fromJSONSchema}});Pe.locales=dk(UI());var pk=gy();Object.defineProperty(Pe,"ZodISODateTime",{enumerable:!0,get:function(){return pk.ZodISODateTime}});Object.defineProperty(Pe,"ZodISODate",{enumerable:!0,get:function(){return pk.ZodISODate}});Object.defineProperty(Pe,"ZodISOTime",{enumerable:!0,get:function(){return pk.ZodISOTime}});Object.defineProperty(Pe,"ZodISODuration",{enumerable:!0,get:function(){return pk.ZodISODuration}});Pe.iso=dk(gy());Pe.coerce=dk(BG())});var xN=v(ri=>{"use strict";p();var VG=ri&&ri.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),y$e=ri&&ri.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),_$e=ri&&ri.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&VG(e,t,r);return y$e(e,t),e},b$e=ri&&ri.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&VG(e,t,r)};Object.defineProperty(ri,"__esModule",{value:!0});ri.z=void 0;var ZG=_$e(CN());ri.z=ZG;b$e(CN(),ri);ri.default=ZG});var fk=v(as=>{"use strict";p();var v$e=as&&as.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),w$e=as&&as.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&v$e(e,t,r)},S$e=as&&as.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(as,"__esModule",{value:!0});var T$e=S$e(xN());w$e(xN(),as);as.default=T$e.default});var MN=v(ni=>{"use strict";p();Object.defineProperty(ni,Symbol.toStringTag,{value:"Module"});var k$e=de(),eu=ow(),IN=_l(),mk=Rs(),HG=Qu();fi();var Xf=Ko(),P$e=uf(),hk=Wa(),E$e=Ll(),ON=GO(),A$e=Yg(),tu=yN(),WG=Dl(),C$e=rT(),x$e=fk(),I$e=k$e.__exportAll({BaseToolkit:()=>GG,DynamicStructuredTool:()=>$N,DynamicTool:()=>NN,StructuredTool:()=>gk,Tool:()=>RN,ToolInputParsingException:()=>eu.ToolInputParsingException,isLangChainTool:()=>tu.isLangChainTool,isRunnableToolLike:()=>tu.isRunnableToolLike,isStructuredTool:()=>tu.isStructuredTool,isStructuredToolParams:()=>tu.isStructuredToolParams,tool:()=>KG}),gk=class extends A$e.BaseLangChain{constructor(e){super(e??{});f(this,"extras");f(this,"returnDirect",!1);f(this,"verboseParsingErrors",!1);f(this,"responseFormat","content");f(this,"defaultConfig");this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata,this.extras=e?.extras??this.extras}get lc_namespace(){return["langchain","tools"]}async invoke(e,r){let n,i=Xf.ensureConfig(Xf.mergeConfigs(this.defaultConfig,r));return eu._isToolCall(e)?(n=e.args,i={...i,toolCall:e}):n=e,this.call(n,i)}async call(e,r,n){let i=eu._isToolCall(e)?e.args:e,o;if(hk.isInteropZodSchema(this.schema))try{o=await hk.interopParseAsync(this.schema,i)}catch(g){let y="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(y=`${y}
395
+ Received structured response: ${n.printReceived(i)}`,actual:i,expected:e}}var oRe={toBeHumanMessage:KW,toBeAIMessage:YW,toBeSystemMessage:JW,toBeToolMessage:XW,toHaveToolCalls:QW,toHaveToolCallCount:e8,toContainToolCall:t8,toHaveToolMessages:r8,toHaveBeenInterrupted:n8,toHaveStructuredResponse:i8};zi.langchainMatchers=oRe;zi.toBeAIMessage=YW;zi.toBeHumanMessage=KW;zi.toBeSystemMessage=JW;zi.toBeToolMessage=XW;zi.toContainToolCall=t8;zi.toHaveBeenInterrupted=n8;zi.toHaveStructuredResponse=i8;zi.toHaveToolCallCount=e8;zi.toHaveToolCalls=QW;zi.toHaveToolMessages=r8});var c8=v(gN=>{"use strict";p();var a8=jr(),aRe=Fr(),sRe=br();ei();var lRe=MT();function uRe(t){return t.map(e=>e.text).filter(Boolean).join("-")}var s8=0;function cRe(){return s8+=1,`fake_tc_${s8}`}var l8=class u8 extends lRe.BaseChatModel{constructor(){super({});f(this,"queue",[]);f(this,"_alwaysThrowError");f(this,"_structuredResponseValue");f(this,"_tools",[]);f(this,"_state",{callIndex:0,calls:[]})}get calls(){return this._state.calls}get callCount(){return this._state.calls.length}_llmType(){return"fake-model-builder"}_combineLLMOutput(){return[]}respond(r){return typeof r=="function"?this.queue.push({kind:"factory",factory:r}):a8.BaseMessage.isInstance(r)?this.queue.push({kind:"message",message:r}):this.queue.push({kind:"error",error:r}),this}respondWithTools(r){return this.queue.push({kind:"toolCalls",toolCalls:r.map(n=>({name:n.name,args:n.args,id:n.id??cRe(),type:"tool_call"}))}),this}alwaysThrow(r){return this._alwaysThrowError=r,this}structuredResponse(r){return this._structuredResponseValue=r,this}bindTools(r){let n=[...this._tools,...r],i=new u8;return i.queue=this.queue,i._alwaysThrowError=this._alwaysThrowError,i._structuredResponseValue=this._structuredResponseValue,i._tools=n,i._state=this._state,i.withConfig({})}withStructuredOutput(r,n){let{_structuredResponseValue:i}=this;return sRe.RunnableLambda.from(async()=>i)}async _generate(r,n,i){this._state.calls.push({messages:[...r],options:n});let o=this._state.callIndex;if(this._state.callIndex+=1,this._alwaysThrowError)throw this._alwaysThrowError;let a=this.queue[o];if(!a)throw new Error(`FakeModel: no response queued for invocation ${o} (${this.queue.length} total queued).`);if(a.kind==="error")throw a.error;if(a.kind==="factory"){let l=a.factory(r);if(!a8.BaseMessage.isInstance(l))throw l;return{generations:[{text:"",message:l}]}}if(a.kind==="message")return{generations:[{text:"",message:a.message}]};let s=uRe(r);return{generations:[{text:s,message:new aRe.AIMessage({content:s,id:o.toString(),tool_calls:a.toolCalls.length>0?a.toolCalls.map(l=>({...l,type:"tool_call"})):void 0})}],llmOutput:{}}}};function dRe(){return new l8}gN.FakeBuiltModel=l8;gN.fakeModel=dRe});var d8=v(_n=>{"use strict";p();Object.defineProperty(_n,Symbol.toStringTag,{value:"Module"});var pRe=de(),pr=o8(),tk=c8(),fRe=pRe.__exportAll({FakeBuiltModel:()=>tk.FakeBuiltModel,fakeModel:()=>tk.fakeModel,langchainMatchers:()=>pr.langchainMatchers,toBeAIMessage:()=>pr.toBeAIMessage,toBeHumanMessage:()=>pr.toBeHumanMessage,toBeSystemMessage:()=>pr.toBeSystemMessage,toBeToolMessage:()=>pr.toBeToolMessage,toContainToolCall:()=>pr.toContainToolCall,toHaveBeenInterrupted:()=>pr.toHaveBeenInterrupted,toHaveStructuredResponse:()=>pr.toHaveStructuredResponse,toHaveToolCallCount:()=>pr.toHaveToolCallCount,toHaveToolCalls:()=>pr.toHaveToolCalls,toHaveToolMessages:()=>pr.toHaveToolMessages});_n.FakeBuiltModel=tk.FakeBuiltModel;_n.fakeModel=tk.fakeModel;_n.langchainMatchers=pr.langchainMatchers;Object.defineProperty(_n,"testing_exports",{enumerable:!0,get:function(){return fRe}});_n.toBeAIMessage=pr.toBeAIMessage;_n.toBeHumanMessage=pr.toBeHumanMessage;_n.toBeSystemMessage=pr.toBeSystemMessage;_n.toBeToolMessage=pr.toBeToolMessage;_n.toContainToolCall=pr.toContainToolCall;_n.toHaveBeenInterrupted=pr.toHaveBeenInterrupted;_n.toHaveStructuredResponse=pr.toHaveStructuredResponse;_n.toHaveToolCallCount=pr.toHaveToolCallCount;_n.toHaveToolCalls=pr.toHaveToolCalls;_n.toHaveToolMessages=pr.toHaveToolMessages});var yN=v(my=>{"use strict";p();var hRe=Wa(),mRe=br();function p8(t){return t!==void 0&&Array.isArray(t.lc_namespace)}function f8(t){return t!==void 0&&mRe.Runnable.isRunnable(t)&&"lc_name"in t.constructor&&typeof t.constructor.lc_name=="function"&&t.constructor.lc_name()==="RunnableToolLike"}function h8(t){return!!t&&typeof t=="object"&&"name"in t&&"schema"in t&&(hRe.isInteropZodSchema(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 gRe(t){return h8(t)||f8(t)||p8(t)}my.isLangChainTool=gRe;my.isRunnableToolLike=f8;my.isStructuredTool=p8;my.isStructuredToolParams=h8});var rk=v(Ne=>{"use strict";p();Object.defineProperty(Ne,"__esModule",{value:!0});Ne.slugify=Ne.toUpperCase=Ne.toLowerCase=Ne.trim=Ne.normalize=Ne.overwrite=Ne.mime=Ne.property=Ne.endsWith=Ne.startsWith=Ne.includes=Ne.uppercase=Ne.lowercase=Ne.regex=Ne.length=Ne.minLength=Ne.maxLength=Ne.size=Ne.minSize=Ne.maxSize=Ne.multipleOf=Ne.nonnegative=Ne.nonpositive=Ne.negative=Ne.positive=Ne.gte=Ne.gt=Ne.lte=Ne.lt=void 0;var Dt=fn();Object.defineProperty(Ne,"lt",{enumerable:!0,get:function(){return Dt._lt}});Object.defineProperty(Ne,"lte",{enumerable:!0,get:function(){return Dt._lte}});Object.defineProperty(Ne,"gt",{enumerable:!0,get:function(){return Dt._gt}});Object.defineProperty(Ne,"gte",{enumerable:!0,get:function(){return Dt._gte}});Object.defineProperty(Ne,"positive",{enumerable:!0,get:function(){return Dt._positive}});Object.defineProperty(Ne,"negative",{enumerable:!0,get:function(){return Dt._negative}});Object.defineProperty(Ne,"nonpositive",{enumerable:!0,get:function(){return Dt._nonpositive}});Object.defineProperty(Ne,"nonnegative",{enumerable:!0,get:function(){return Dt._nonnegative}});Object.defineProperty(Ne,"multipleOf",{enumerable:!0,get:function(){return Dt._multipleOf}});Object.defineProperty(Ne,"maxSize",{enumerable:!0,get:function(){return Dt._maxSize}});Object.defineProperty(Ne,"minSize",{enumerable:!0,get:function(){return Dt._minSize}});Object.defineProperty(Ne,"size",{enumerable:!0,get:function(){return Dt._size}});Object.defineProperty(Ne,"maxLength",{enumerable:!0,get:function(){return Dt._maxLength}});Object.defineProperty(Ne,"minLength",{enumerable:!0,get:function(){return Dt._minLength}});Object.defineProperty(Ne,"length",{enumerable:!0,get:function(){return Dt._length}});Object.defineProperty(Ne,"regex",{enumerable:!0,get:function(){return Dt._regex}});Object.defineProperty(Ne,"lowercase",{enumerable:!0,get:function(){return Dt._lowercase}});Object.defineProperty(Ne,"uppercase",{enumerable:!0,get:function(){return Dt._uppercase}});Object.defineProperty(Ne,"includes",{enumerable:!0,get:function(){return Dt._includes}});Object.defineProperty(Ne,"startsWith",{enumerable:!0,get:function(){return Dt._startsWith}});Object.defineProperty(Ne,"endsWith",{enumerable:!0,get:function(){return Dt._endsWith}});Object.defineProperty(Ne,"property",{enumerable:!0,get:function(){return Dt._property}});Object.defineProperty(Ne,"mime",{enumerable:!0,get:function(){return Dt._mime}});Object.defineProperty(Ne,"overwrite",{enumerable:!0,get:function(){return Dt._overwrite}});Object.defineProperty(Ne,"normalize",{enumerable:!0,get:function(){return Dt._normalize}});Object.defineProperty(Ne,"trim",{enumerable:!0,get:function(){return Dt._trim}});Object.defineProperty(Ne,"toLowerCase",{enumerable:!0,get:function(){return Dt._toLowerCase}});Object.defineProperty(Ne,"toUpperCase",{enumerable:!0,get:function(){return Dt._toUpperCase}});Object.defineProperty(Ne,"slugify",{enumerable:!0,get:function(){return Dt._slugify}})});var gy=v(er=>{"use strict";p();var yRe=er&&er.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),_Re=er&&er.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),m8=er&&er.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&yRe(e,t,r);return _Re(e,t),e};Object.defineProperty(er,"__esModule",{value:!0});er.ZodISODuration=er.ZodISOTime=er.ZodISODate=er.ZodISODateTime=void 0;er.datetime=bRe;er.date=vRe;er.time=wRe;er.duration=SRe;var Vi=m8(fn()),nk=m8(yy());er.ZodISODateTime=Vi.$constructor("ZodISODateTime",(t,e)=>{Vi.$ZodISODateTime.init(t,e),nk.ZodStringFormat.init(t,e)});function bRe(t){return Vi._isoDateTime(er.ZodISODateTime,t)}er.ZodISODate=Vi.$constructor("ZodISODate",(t,e)=>{Vi.$ZodISODate.init(t,e),nk.ZodStringFormat.init(t,e)});function vRe(t){return Vi._isoDate(er.ZodISODate,t)}er.ZodISOTime=Vi.$constructor("ZodISOTime",(t,e)=>{Vi.$ZodISOTime.init(t,e),nk.ZodStringFormat.init(t,e)});function wRe(t){return Vi._isoTime(er.ZodISOTime,t)}er.ZodISODuration=Vi.$constructor("ZodISODuration",(t,e)=>{Vi.$ZodISODuration.init(t,e),nk.ZodStringFormat.init(t,e)});function SRe(t){return Vi._isoDuration(er.ZodISODuration,t)}});var _N=v(Zi=>{"use strict";p();var TRe=Zi&&Zi.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),kRe=Zi&&Zi.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),y8=Zi&&Zi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&TRe(e,t,r);return kRe(e,t),e};Object.defineProperty(Zi,"__esModule",{value:!0});Zi.ZodRealError=Zi.ZodError=void 0;var ik=y8(fn()),PRe=fn(),g8=y8(Oe()),_8=(t,e)=>{PRe.$ZodError.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>ik.formatError(t,r)},flatten:{value:r=>ik.flattenError(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,g8.jsonStringifyReplacer,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,g8.jsonStringifyReplacer,2)}},isEmpty:{get(){return t.issues.length===0}}})};Zi.ZodError=ik.$constructor("ZodError",_8);Zi.ZodRealError=ik.$constructor("ZodError",_8,{Parent:Error})});var bN=v(Pt=>{"use strict";p();var ERe=Pt&&Pt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),ARe=Pt&&Pt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),CRe=Pt&&Pt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&ERe(e,t,r);return ARe(e,t),e};Object.defineProperty(Pt,"__esModule",{value:!0});Pt.safeDecodeAsync=Pt.safeEncodeAsync=Pt.safeDecode=Pt.safeEncode=Pt.decodeAsync=Pt.encodeAsync=Pt.decode=Pt.encode=Pt.safeParseAsync=Pt.safeParse=Pt.parseAsync=Pt.parse=void 0;var Hi=CRe(fn()),Wi=_N();Pt.parse=Hi._parse(Wi.ZodRealError);Pt.parseAsync=Hi._parseAsync(Wi.ZodRealError);Pt.safeParse=Hi._safeParse(Wi.ZodRealError);Pt.safeParseAsync=Hi._safeParseAsync(Wi.ZodRealError);Pt.encode=Hi._encode(Wi.ZodRealError);Pt.decode=Hi._decode(Wi.ZodRealError);Pt.encodeAsync=Hi._encodeAsync(Wi.ZodRealError);Pt.decodeAsync=Hi._decodeAsync(Wi.ZodRealError);Pt.safeEncode=Hi._safeEncode(Wi.ZodRealError);Pt.safeDecode=Hi._safeDecode(Wi.ZodRealError);Pt.safeEncodeAsync=Hi._safeEncodeAsync(Wi.ZodRealError);Pt.safeDecodeAsync=Hi._safeDecodeAsync(Wi.ZodRealError)});var yy=v(S=>{"use strict";p();var xRe=S&&S.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),IRe=S&&S.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),_y=S&&S.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&xRe(e,t,r);return IRe(e,t),e};Object.defineProperty(S,"__esModule",{value:!0});S.ZodLiteral=S.ZodEnum=S.ZodSet=S.ZodMap=S.ZodRecord=S.ZodTuple=S.ZodIntersection=S.ZodDiscriminatedUnion=S.ZodXor=S.ZodUnion=S.ZodObject=S.ZodArray=S.ZodDate=S.ZodVoid=S.ZodNever=S.ZodUnknown=S.ZodAny=S.ZodNull=S.ZodUndefined=S.ZodSymbol=S.ZodBigIntFormat=S.ZodBigInt=S.ZodBoolean=S.ZodNumberFormat=S.ZodNumber=S.ZodCustomStringFormat=S.ZodJWT=S.ZodE164=S.ZodBase64URL=S.ZodBase64=S.ZodCIDRv6=S.ZodCIDRv4=S.ZodIPv6=S.ZodMAC=S.ZodIPv4=S.ZodKSUID=S.ZodXID=S.ZodULID=S.ZodCUID2=S.ZodCUID=S.ZodNanoID=S.ZodEmoji=S.ZodURL=S.ZodUUID=S.ZodGUID=S.ZodEmail=S.ZodStringFormat=S.ZodString=S._ZodString=S.ZodType=void 0;S.stringbool=S.meta=S.describe=S.ZodCustom=S.ZodFunction=S.ZodPromise=S.ZodLazy=S.ZodTemplateLiteral=S.ZodReadonly=S.ZodPreprocess=S.ZodCodec=S.ZodPipe=S.ZodNaN=S.ZodCatch=S.ZodSuccess=S.ZodNonOptional=S.ZodPrefault=S.ZodDefault=S.ZodNullable=S.ZodExactOptional=S.ZodOptional=S.ZodTransform=S.ZodFile=void 0;S.string=ak;S.email=ORe;S.guid=RRe;S.uuid=NRe;S.uuidv4=$Re;S.uuidv6=MRe;S.uuidv7=DRe;S.url=URe;S.httpUrl=qRe;S.emoji=LRe;S.nanoid=jRe;S.cuid=FRe;S.cuid2=BRe;S.ulid=zRe;S.xid=VRe;S.ksuid=ZRe;S.ipv4=HRe;S.mac=WRe;S.ipv6=GRe;S.cidrv4=KRe;S.cidrv6=YRe;S.base64=JRe;S.base64url=XRe;S.e164=QRe;S.jwt=eNe;S.stringFormat=tNe;S.hostname=rNe;S.hex=nNe;S.hash=iNe;S.number=v8;S.int=wN;S.float32=oNe;S.float64=aNe;S.int32=sNe;S.uint32=lNe;S.boolean=w8;S.bigint=uNe;S.int64=cNe;S.uint64=dNe;S.symbol=pNe;S.undefined=fNe;S.null=S8;S.any=hNe;S.unknown=Jf;S.never=TN;S.void=mNe;S.date=gNe;S.array=uk;S.keyof=yNe;S.object=_Ne;S.strictObject=bNe;S.looseObject=vNe;S.union=kN;S.xor=wNe;S.discriminatedUnion=SNe;S.intersection=T8;S.tuple=k8;S.record=P8;S.partialRecord=TNe;S.looseRecord=kNe;S.map=PNe;S.set=ENe;S.enum=PN;S.nativeEnum=ANe;S.literal=CNe;S.file=xNe;S.transform=EN;S.optional=sk;S.exactOptional=E8;S.nullable=lk;S.nullish=INe;S._default=A8;S.prefault=C8;S.nonoptional=x8;S.success=ONe;S.catch=I8;S.nan=RNe;S.pipe=SN;S.codec=NNe;S.invertCodec=$Ne;S.readonly=O8;S.templateLiteral=MNe;S.lazy=R8;S.promise=DNe;S._function=ck;S.function=ck;S._function=ck;S.function=ck;S.check=UNe;S.custom=qNe;S.refine=N8;S.superRefine=$8;S.instanceof=LNe;S.json=FNe;S.preprocess=BNe;var N=_y(fn()),yt=fn(),lt=_y(Og()),vN=Ig(),Qe=_y(rk()),ok=_y(gy()),Gi=_y(bN()),b8=new WeakMap;function by(t,e,r){let n=Object.getPrototypeOf(t),i=b8.get(n);if(i||(i=new Set,b8.set(n,i)),!i.has(e)){i.add(e);for(let o in r){let a=r[o];Object.defineProperty(n,o,{configurable:!0,enumerable:!1,get(){let s=a.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:s}),s},set(s){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:s})}})}}}S.ZodType=N.$constructor("ZodType",(t,e)=>(N.$ZodType.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:(0,vN.createStandardJSONSchemaMethod)(t,"input"),output:(0,vN.createStandardJSONSchemaMethod)(t,"output")}}),t.toJSONSchema=(0,vN.createToJSONSchemaMethod)(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>Gi.parse(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Gi.safeParse(t,r,n),t.parseAsync=async(r,n)=>Gi.parseAsync(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Gi.safeParseAsync(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>Gi.encode(t,r,n),t.decode=(r,n)=>Gi.decode(t,r,n),t.encodeAsync=async(r,n)=>Gi.encodeAsync(t,r,n),t.decodeAsync=async(r,n)=>Gi.decodeAsync(t,r,n),t.safeEncode=(r,n)=>Gi.safeEncode(t,r,n),t.safeDecode=(r,n)=>Gi.safeDecode(t,r,n),t.safeEncodeAsync=async(r,n)=>Gi.safeEncodeAsync(t,r,n),t.safeDecodeAsync=async(r,n)=>Gi.safeDecodeAsync(t,r,n),by(t,"ZodType",{check(...r){let n=this.def;return this.clone(yt.util.mergeDefs(n,{checks:[...n.checks??[],...r.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return N.clone(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(N8(r,n))},superRefine(r,n){return this.check($8(r,n))},overwrite(r){return this.check(Qe.overwrite(r))},optional(){return sk(this)},exactOptional(){return E8(this)},nullable(){return lk(this)},nullish(){return sk(lk(this))},nonoptional(r){return x8(this,r)},array(){return uk(this)},or(r){return kN([this,r])},and(r){return T8(this,r)},transform(r){return SN(this,EN(r))},default(r){return A8(this,r)},prefault(r){return C8(this,r)},catch(r){return I8(this,r)},pipe(r){return SN(this,r)},readonly(){return O8(this)},describe(r){let n=this.clone();return N.globalRegistry.add(n,{description:r}),n},meta(...r){if(r.length===0)return N.globalRegistry.get(this);let n=this.clone();return N.globalRegistry.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return N.globalRegistry.get(t)?.description},configurable:!0}),t));S._ZodString=N.$constructor("_ZodString",(t,e)=>{N.$ZodString.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(n,i,o)=>lt.stringProcessor(t,n,i,o);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,by(t,"_ZodString",{regex(...n){return this.check(Qe.regex(...n))},includes(...n){return this.check(Qe.includes(...n))},startsWith(...n){return this.check(Qe.startsWith(...n))},endsWith(...n){return this.check(Qe.endsWith(...n))},min(...n){return this.check(Qe.minLength(...n))},max(...n){return this.check(Qe.maxLength(...n))},length(...n){return this.check(Qe.length(...n))},nonempty(...n){return this.check(Qe.minLength(1,...n))},lowercase(n){return this.check(Qe.lowercase(n))},uppercase(n){return this.check(Qe.uppercase(n))},trim(){return this.check(Qe.trim())},normalize(...n){return this.check(Qe.normalize(...n))},toLowerCase(){return this.check(Qe.toLowerCase())},toUpperCase(){return this.check(Qe.toUpperCase())},slugify(){return this.check(Qe.slugify())}})});S.ZodString=N.$constructor("ZodString",(t,e)=>{N.$ZodString.init(t,e),S._ZodString.init(t,e),t.email=r=>t.check(N._email(S.ZodEmail,r)),t.url=r=>t.check(N._url(S.ZodURL,r)),t.jwt=r=>t.check(N._jwt(S.ZodJWT,r)),t.emoji=r=>t.check(N._emoji(S.ZodEmoji,r)),t.guid=r=>t.check(N._guid(S.ZodGUID,r)),t.uuid=r=>t.check(N._uuid(S.ZodUUID,r)),t.uuidv4=r=>t.check(N._uuidv4(S.ZodUUID,r)),t.uuidv6=r=>t.check(N._uuidv6(S.ZodUUID,r)),t.uuidv7=r=>t.check(N._uuidv7(S.ZodUUID,r)),t.nanoid=r=>t.check(N._nanoid(S.ZodNanoID,r)),t.guid=r=>t.check(N._guid(S.ZodGUID,r)),t.cuid=r=>t.check(N._cuid(S.ZodCUID,r)),t.cuid2=r=>t.check(N._cuid2(S.ZodCUID2,r)),t.ulid=r=>t.check(N._ulid(S.ZodULID,r)),t.base64=r=>t.check(N._base64(S.ZodBase64,r)),t.base64url=r=>t.check(N._base64url(S.ZodBase64URL,r)),t.xid=r=>t.check(N._xid(S.ZodXID,r)),t.ksuid=r=>t.check(N._ksuid(S.ZodKSUID,r)),t.ipv4=r=>t.check(N._ipv4(S.ZodIPv4,r)),t.ipv6=r=>t.check(N._ipv6(S.ZodIPv6,r)),t.cidrv4=r=>t.check(N._cidrv4(S.ZodCIDRv4,r)),t.cidrv6=r=>t.check(N._cidrv6(S.ZodCIDRv6,r)),t.e164=r=>t.check(N._e164(S.ZodE164,r)),t.datetime=r=>t.check(ok.datetime(r)),t.date=r=>t.check(ok.date(r)),t.time=r=>t.check(ok.time(r)),t.duration=r=>t.check(ok.duration(r))});function ak(t){return N._string(S.ZodString,t)}S.ZodStringFormat=N.$constructor("ZodStringFormat",(t,e)=>{N.$ZodStringFormat.init(t,e),S._ZodString.init(t,e)});S.ZodEmail=N.$constructor("ZodEmail",(t,e)=>{N.$ZodEmail.init(t,e),S.ZodStringFormat.init(t,e)});function ORe(t){return N._email(S.ZodEmail,t)}S.ZodGUID=N.$constructor("ZodGUID",(t,e)=>{N.$ZodGUID.init(t,e),S.ZodStringFormat.init(t,e)});function RRe(t){return N._guid(S.ZodGUID,t)}S.ZodUUID=N.$constructor("ZodUUID",(t,e)=>{N.$ZodUUID.init(t,e),S.ZodStringFormat.init(t,e)});function NRe(t){return N._uuid(S.ZodUUID,t)}function $Re(t){return N._uuidv4(S.ZodUUID,t)}function MRe(t){return N._uuidv6(S.ZodUUID,t)}function DRe(t){return N._uuidv7(S.ZodUUID,t)}S.ZodURL=N.$constructor("ZodURL",(t,e)=>{N.$ZodURL.init(t,e),S.ZodStringFormat.init(t,e)});function URe(t){return N._url(S.ZodURL,t)}function qRe(t){return N._url(S.ZodURL,{protocol:N.regexes.httpProtocol,hostname:N.regexes.domain,...yt.util.normalizeParams(t)})}S.ZodEmoji=N.$constructor("ZodEmoji",(t,e)=>{N.$ZodEmoji.init(t,e),S.ZodStringFormat.init(t,e)});function LRe(t){return N._emoji(S.ZodEmoji,t)}S.ZodNanoID=N.$constructor("ZodNanoID",(t,e)=>{N.$ZodNanoID.init(t,e),S.ZodStringFormat.init(t,e)});function jRe(t){return N._nanoid(S.ZodNanoID,t)}S.ZodCUID=N.$constructor("ZodCUID",(t,e)=>{N.$ZodCUID.init(t,e),S.ZodStringFormat.init(t,e)});function FRe(t){return N._cuid(S.ZodCUID,t)}S.ZodCUID2=N.$constructor("ZodCUID2",(t,e)=>{N.$ZodCUID2.init(t,e),S.ZodStringFormat.init(t,e)});function BRe(t){return N._cuid2(S.ZodCUID2,t)}S.ZodULID=N.$constructor("ZodULID",(t,e)=>{N.$ZodULID.init(t,e),S.ZodStringFormat.init(t,e)});function zRe(t){return N._ulid(S.ZodULID,t)}S.ZodXID=N.$constructor("ZodXID",(t,e)=>{N.$ZodXID.init(t,e),S.ZodStringFormat.init(t,e)});function VRe(t){return N._xid(S.ZodXID,t)}S.ZodKSUID=N.$constructor("ZodKSUID",(t,e)=>{N.$ZodKSUID.init(t,e),S.ZodStringFormat.init(t,e)});function ZRe(t){return N._ksuid(S.ZodKSUID,t)}S.ZodIPv4=N.$constructor("ZodIPv4",(t,e)=>{N.$ZodIPv4.init(t,e),S.ZodStringFormat.init(t,e)});function HRe(t){return N._ipv4(S.ZodIPv4,t)}S.ZodMAC=N.$constructor("ZodMAC",(t,e)=>{N.$ZodMAC.init(t,e),S.ZodStringFormat.init(t,e)});function WRe(t){return N._mac(S.ZodMAC,t)}S.ZodIPv6=N.$constructor("ZodIPv6",(t,e)=>{N.$ZodIPv6.init(t,e),S.ZodStringFormat.init(t,e)});function GRe(t){return N._ipv6(S.ZodIPv6,t)}S.ZodCIDRv4=N.$constructor("ZodCIDRv4",(t,e)=>{N.$ZodCIDRv4.init(t,e),S.ZodStringFormat.init(t,e)});function KRe(t){return N._cidrv4(S.ZodCIDRv4,t)}S.ZodCIDRv6=N.$constructor("ZodCIDRv6",(t,e)=>{N.$ZodCIDRv6.init(t,e),S.ZodStringFormat.init(t,e)});function YRe(t){return N._cidrv6(S.ZodCIDRv6,t)}S.ZodBase64=N.$constructor("ZodBase64",(t,e)=>{N.$ZodBase64.init(t,e),S.ZodStringFormat.init(t,e)});function JRe(t){return N._base64(S.ZodBase64,t)}S.ZodBase64URL=N.$constructor("ZodBase64URL",(t,e)=>{N.$ZodBase64URL.init(t,e),S.ZodStringFormat.init(t,e)});function XRe(t){return N._base64url(S.ZodBase64URL,t)}S.ZodE164=N.$constructor("ZodE164",(t,e)=>{N.$ZodE164.init(t,e),S.ZodStringFormat.init(t,e)});function QRe(t){return N._e164(S.ZodE164,t)}S.ZodJWT=N.$constructor("ZodJWT",(t,e)=>{N.$ZodJWT.init(t,e),S.ZodStringFormat.init(t,e)});function eNe(t){return N._jwt(S.ZodJWT,t)}S.ZodCustomStringFormat=N.$constructor("ZodCustomStringFormat",(t,e)=>{N.$ZodCustomStringFormat.init(t,e),S.ZodStringFormat.init(t,e)});function tNe(t,e,r={}){return N._stringFormat(S.ZodCustomStringFormat,t,e,r)}function rNe(t){return N._stringFormat(S.ZodCustomStringFormat,"hostname",N.regexes.hostname,t)}function nNe(t){return N._stringFormat(S.ZodCustomStringFormat,"hex",N.regexes.hex,t)}function iNe(t,e){let r=e?.enc??"hex",n=`${t}_${r}`,i=N.regexes[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return N._stringFormat(S.ZodCustomStringFormat,n,i,e)}S.ZodNumber=N.$constructor("ZodNumber",(t,e)=>{N.$ZodNumber.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(n,i,o)=>lt.numberProcessor(t,n,i,o),by(t,"ZodNumber",{gt(n,i){return this.check(Qe.gt(n,i))},gte(n,i){return this.check(Qe.gte(n,i))},min(n,i){return this.check(Qe.gte(n,i))},lt(n,i){return this.check(Qe.lt(n,i))},lte(n,i){return this.check(Qe.lte(n,i))},max(n,i){return this.check(Qe.lte(n,i))},int(n){return this.check(wN(n))},safe(n){return this.check(wN(n))},positive(n){return this.check(Qe.gt(0,n))},nonnegative(n){return this.check(Qe.gte(0,n))},negative(n){return this.check(Qe.lt(0,n))},nonpositive(n){return this.check(Qe.lte(0,n))},multipleOf(n,i){return this.check(Qe.multipleOf(n,i))},step(n,i){return this.check(Qe.multipleOf(n,i))},finite(){return this}});let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function v8(t){return N._number(S.ZodNumber,t)}S.ZodNumberFormat=N.$constructor("ZodNumberFormat",(t,e)=>{N.$ZodNumberFormat.init(t,e),S.ZodNumber.init(t,e)});function wN(t){return N._int(S.ZodNumberFormat,t)}function oNe(t){return N._float32(S.ZodNumberFormat,t)}function aNe(t){return N._float64(S.ZodNumberFormat,t)}function sNe(t){return N._int32(S.ZodNumberFormat,t)}function lNe(t){return N._uint32(S.ZodNumberFormat,t)}S.ZodBoolean=N.$constructor("ZodBoolean",(t,e)=>{N.$ZodBoolean.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.booleanProcessor(t,r,n,i)});function w8(t){return N._boolean(S.ZodBoolean,t)}S.ZodBigInt=N.$constructor("ZodBigInt",(t,e)=>{N.$ZodBigInt.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(n,i,o)=>lt.bigintProcessor(t,n,i,o),t.gte=(n,i)=>t.check(Qe.gte(n,i)),t.min=(n,i)=>t.check(Qe.gte(n,i)),t.gt=(n,i)=>t.check(Qe.gt(n,i)),t.gte=(n,i)=>t.check(Qe.gte(n,i)),t.min=(n,i)=>t.check(Qe.gte(n,i)),t.lt=(n,i)=>t.check(Qe.lt(n,i)),t.lte=(n,i)=>t.check(Qe.lte(n,i)),t.max=(n,i)=>t.check(Qe.lte(n,i)),t.positive=n=>t.check(Qe.gt(BigInt(0),n)),t.negative=n=>t.check(Qe.lt(BigInt(0),n)),t.nonpositive=n=>t.check(Qe.lte(BigInt(0),n)),t.nonnegative=n=>t.check(Qe.gte(BigInt(0),n)),t.multipleOf=(n,i)=>t.check(Qe.multipleOf(n,i));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});function uNe(t){return N._bigint(S.ZodBigInt,t)}S.ZodBigIntFormat=N.$constructor("ZodBigIntFormat",(t,e)=>{N.$ZodBigIntFormat.init(t,e),S.ZodBigInt.init(t,e)});function cNe(t){return N._int64(S.ZodBigIntFormat,t)}function dNe(t){return N._uint64(S.ZodBigIntFormat,t)}S.ZodSymbol=N.$constructor("ZodSymbol",(t,e)=>{N.$ZodSymbol.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.symbolProcessor(t,r,n,i)});function pNe(t){return N._symbol(S.ZodSymbol,t)}S.ZodUndefined=N.$constructor("ZodUndefined",(t,e)=>{N.$ZodUndefined.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.undefinedProcessor(t,r,n,i)});function fNe(t){return N._undefined(S.ZodUndefined,t)}S.ZodNull=N.$constructor("ZodNull",(t,e)=>{N.$ZodNull.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.nullProcessor(t,r,n,i)});function S8(t){return N._null(S.ZodNull,t)}S.ZodAny=N.$constructor("ZodAny",(t,e)=>{N.$ZodAny.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.anyProcessor(t,r,n,i)});function hNe(){return N._any(S.ZodAny)}S.ZodUnknown=N.$constructor("ZodUnknown",(t,e)=>{N.$ZodUnknown.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.unknownProcessor(t,r,n,i)});function Jf(){return N._unknown(S.ZodUnknown)}S.ZodNever=N.$constructor("ZodNever",(t,e)=>{N.$ZodNever.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.neverProcessor(t,r,n,i)});function TN(t){return N._never(S.ZodNever,t)}S.ZodVoid=N.$constructor("ZodVoid",(t,e)=>{N.$ZodVoid.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.voidProcessor(t,r,n,i)});function mNe(t){return N._void(S.ZodVoid,t)}S.ZodDate=N.$constructor("ZodDate",(t,e)=>{N.$ZodDate.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(n,i,o)=>lt.dateProcessor(t,n,i,o),t.min=(n,i)=>t.check(Qe.gte(n,i)),t.max=(n,i)=>t.check(Qe.lte(n,i));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});function gNe(t){return N._date(S.ZodDate,t)}S.ZodArray=N.$constructor("ZodArray",(t,e)=>{N.$ZodArray.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.arrayProcessor(t,r,n,i),t.element=e.element,by(t,"ZodArray",{min(r,n){return this.check(Qe.minLength(r,n))},nonempty(r){return this.check(Qe.minLength(1,r))},max(r,n){return this.check(Qe.maxLength(r,n))},length(r,n){return this.check(Qe.length(r,n))},unwrap(){return this.element}})});function uk(t,e){return N._array(S.ZodArray,t,e)}function yNe(t){let e=t._zod.def.shape;return PN(Object.keys(e))}S.ZodObject=N.$constructor("ZodObject",(t,e)=>{N.$ZodObjectJIT.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.objectProcessor(t,r,n,i),yt.util.defineLazy(t,"shape",()=>e.shape),by(t,"ZodObject",{keyof(){return PN(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Jf()})},loose(){return this.clone({...this._zod.def,catchall:Jf()})},strict(){return this.clone({...this._zod.def,catchall:TN()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return yt.util.extend(this,r)},safeExtend(r){return yt.util.safeExtend(this,r)},merge(r){return yt.util.merge(this,r)},pick(r){return yt.util.pick(this,r)},omit(r){return yt.util.omit(this,r)},partial(...r){return yt.util.partial(S.ZodOptional,this,r[0])},required(...r){return yt.util.required(S.ZodNonOptional,this,r[0])}})});function _Ne(t,e){let r={type:"object",shape:t??{},...yt.util.normalizeParams(e)};return new S.ZodObject(r)}function bNe(t,e){return new S.ZodObject({type:"object",shape:t,catchall:TN(),...yt.util.normalizeParams(e)})}function vNe(t,e){return new S.ZodObject({type:"object",shape:t,catchall:Jf(),...yt.util.normalizeParams(e)})}S.ZodUnion=N.$constructor("ZodUnion",(t,e)=>{N.$ZodUnion.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.unionProcessor(t,r,n,i),t.options=e.options});function kN(t,e){return new S.ZodUnion({type:"union",options:t,...yt.util.normalizeParams(e)})}S.ZodXor=N.$constructor("ZodXor",(t,e)=>{S.ZodUnion.init(t,e),N.$ZodXor.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.unionProcessor(t,r,n,i),t.options=e.options});function wNe(t,e){return new S.ZodXor({type:"union",options:t,inclusive:!1,...yt.util.normalizeParams(e)})}S.ZodDiscriminatedUnion=N.$constructor("ZodDiscriminatedUnion",(t,e)=>{S.ZodUnion.init(t,e),N.$ZodDiscriminatedUnion.init(t,e)});function SNe(t,e,r){return new S.ZodDiscriminatedUnion({type:"union",options:e,discriminator:t,...yt.util.normalizeParams(r)})}S.ZodIntersection=N.$constructor("ZodIntersection",(t,e)=>{N.$ZodIntersection.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.intersectionProcessor(t,r,n,i)});function T8(t,e){return new S.ZodIntersection({type:"intersection",left:t,right:e})}S.ZodTuple=N.$constructor("ZodTuple",(t,e)=>{N.$ZodTuple.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.tupleProcessor(t,r,n,i),t.rest=r=>t.clone({...t._zod.def,rest:r})});function k8(t,e,r){let n=e instanceof N.$ZodType,i=n?r:e,o=n?e:null;return new S.ZodTuple({type:"tuple",items:t,rest:o,...yt.util.normalizeParams(i)})}S.ZodRecord=N.$constructor("ZodRecord",(t,e)=>{N.$ZodRecord.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.recordProcessor(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function P8(t,e,r){return!e||!e._zod?new S.ZodRecord({type:"record",keyType:ak(),valueType:t,...yt.util.normalizeParams(e)}):new S.ZodRecord({type:"record",keyType:t,valueType:e,...yt.util.normalizeParams(r)})}function TNe(t,e,r){let n=N.clone(t);return n._zod.values=void 0,new S.ZodRecord({type:"record",keyType:n,valueType:e,...yt.util.normalizeParams(r)})}function kNe(t,e,r){return new S.ZodRecord({type:"record",keyType:t,valueType:e,mode:"loose",...yt.util.normalizeParams(r)})}S.ZodMap=N.$constructor("ZodMap",(t,e)=>{N.$ZodMap.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.mapProcessor(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(N._minSize(...r)),t.nonempty=r=>t.check(N._minSize(1,r)),t.max=(...r)=>t.check(N._maxSize(...r)),t.size=(...r)=>t.check(N._size(...r))});function PNe(t,e,r){return new S.ZodMap({type:"map",keyType:t,valueType:e,...yt.util.normalizeParams(r)})}S.ZodSet=N.$constructor("ZodSet",(t,e)=>{N.$ZodSet.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.setProcessor(t,r,n,i),t.min=(...r)=>t.check(N._minSize(...r)),t.nonempty=r=>t.check(N._minSize(1,r)),t.max=(...r)=>t.check(N._maxSize(...r)),t.size=(...r)=>t.check(N._size(...r))});function ENe(t,e){return new S.ZodSet({type:"set",valueType:t,...yt.util.normalizeParams(e)})}S.ZodEnum=N.$constructor("ZodEnum",(t,e)=>{N.$ZodEnum.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(n,i,o)=>lt.enumProcessor(t,n,i,o),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let o={};for(let a of n)if(r.has(a))o[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new S.ZodEnum({...e,checks:[],...yt.util.normalizeParams(i),entries:o})},t.exclude=(n,i)=>{let o={...e.entries};for(let a of n)if(r.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new S.ZodEnum({...e,checks:[],...yt.util.normalizeParams(i),entries:o})}});function PN(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new S.ZodEnum({type:"enum",entries:r,...yt.util.normalizeParams(e)})}function ANe(t,e){return new S.ZodEnum({type:"enum",entries:t,...yt.util.normalizeParams(e)})}S.ZodLiteral=N.$constructor("ZodLiteral",(t,e)=>{N.$ZodLiteral.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.literalProcessor(t,r,n,i),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function CNe(t,e){return new S.ZodLiteral({type:"literal",values:Array.isArray(t)?t:[t],...yt.util.normalizeParams(e)})}S.ZodFile=N.$constructor("ZodFile",(t,e)=>{N.$ZodFile.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.fileProcessor(t,r,n,i),t.min=(r,n)=>t.check(N._minSize(r,n)),t.max=(r,n)=>t.check(N._maxSize(r,n)),t.mime=(r,n)=>t.check(N._mime(Array.isArray(r)?r:[r],n))});function xNe(t){return N._file(S.ZodFile,t)}S.ZodTransform=N.$constructor("ZodTransform",(t,e)=>{N.$ZodTransform.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.transformProcessor(t,r,n,i),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new N.$ZodEncodeError(t.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(yt.util.issue(o,r.value,e));else{let a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),r.issues.push(yt.util.issue(a))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(o=>(r.value=o,r.fallback=!0,r)):(r.value=i,r.fallback=!0,r)}});function EN(t){return new S.ZodTransform({type:"transform",transform:t})}S.ZodOptional=N.$constructor("ZodOptional",(t,e)=>{N.$ZodOptional.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.optionalProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function sk(t){return new S.ZodOptional({type:"optional",innerType:t})}S.ZodExactOptional=N.$constructor("ZodExactOptional",(t,e)=>{N.$ZodExactOptional.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.optionalProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function E8(t){return new S.ZodExactOptional({type:"optional",innerType:t})}S.ZodNullable=N.$constructor("ZodNullable",(t,e)=>{N.$ZodNullable.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.nullableProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function lk(t){return new S.ZodNullable({type:"nullable",innerType:t})}function INe(t){return sk(lk(t))}S.ZodDefault=N.$constructor("ZodDefault",(t,e)=>{N.$ZodDefault.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.defaultProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function A8(t,e){return new S.ZodDefault({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():yt.util.shallowClone(e)}})}S.ZodPrefault=N.$constructor("ZodPrefault",(t,e)=>{N.$ZodPrefault.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.prefaultProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function C8(t,e){return new S.ZodPrefault({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():yt.util.shallowClone(e)}})}S.ZodNonOptional=N.$constructor("ZodNonOptional",(t,e)=>{N.$ZodNonOptional.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.nonoptionalProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function x8(t,e){return new S.ZodNonOptional({type:"nonoptional",innerType:t,...yt.util.normalizeParams(e)})}S.ZodSuccess=N.$constructor("ZodSuccess",(t,e)=>{N.$ZodSuccess.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.successProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function ONe(t){return new S.ZodSuccess({type:"success",innerType:t})}S.ZodCatch=N.$constructor("ZodCatch",(t,e)=>{N.$ZodCatch.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.catchProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function I8(t,e){return new S.ZodCatch({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}S.ZodNaN=N.$constructor("ZodNaN",(t,e)=>{N.$ZodNaN.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.nanProcessor(t,r,n,i)});function RNe(t){return N._nan(S.ZodNaN,t)}S.ZodPipe=N.$constructor("ZodPipe",(t,e)=>{N.$ZodPipe.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.pipeProcessor(t,r,n,i),t.in=e.in,t.out=e.out});function SN(t,e){return new S.ZodPipe({type:"pipe",in:t,out:e})}S.ZodCodec=N.$constructor("ZodCodec",(t,e)=>{S.ZodPipe.init(t,e),N.$ZodCodec.init(t,e)});function NNe(t,e,r){return new S.ZodCodec({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function $Ne(t){let e=t._zod.def;return new S.ZodCodec({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}S.ZodPreprocess=N.$constructor("ZodPreprocess",(t,e)=>{S.ZodPipe.init(t,e),N.$ZodPreprocess.init(t,e)});S.ZodReadonly=N.$constructor("ZodReadonly",(t,e)=>{N.$ZodReadonly.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.readonlyProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function O8(t){return new S.ZodReadonly({type:"readonly",innerType:t})}S.ZodTemplateLiteral=N.$constructor("ZodTemplateLiteral",(t,e)=>{N.$ZodTemplateLiteral.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.templateLiteralProcessor(t,r,n,i)});function MNe(t,e){return new S.ZodTemplateLiteral({type:"template_literal",parts:t,...yt.util.normalizeParams(e)})}S.ZodLazy=N.$constructor("ZodLazy",(t,e)=>{N.$ZodLazy.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.lazyProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.getter()});function R8(t){return new S.ZodLazy({type:"lazy",getter:t})}S.ZodPromise=N.$constructor("ZodPromise",(t,e)=>{N.$ZodPromise.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.promiseProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function DNe(t){return new S.ZodPromise({type:"promise",innerType:t})}S.ZodFunction=N.$constructor("ZodFunction",(t,e)=>{N.$ZodFunction.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.functionProcessor(t,r,n,i)});function ck(t){return new S.ZodFunction({type:"function",input:Array.isArray(t?.input)?k8(t?.input):t?.input??uk(Jf()),output:t?.output??Jf()})}S.ZodCustom=N.$constructor("ZodCustom",(t,e)=>{N.$ZodCustom.init(t,e),S.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lt.customProcessor(t,r,n,i)});function UNe(t){let e=new N.$ZodCheck({check:"custom"});return e._zod.check=t,e}function qNe(t,e){return N._custom(S.ZodCustom,t??(()=>!0),e)}function N8(t,e={}){return N._refine(S.ZodCustom,t,e)}function $8(t,e){return N._superRefine(t,e)}S.describe=N.describe;S.meta=N.meta;function LNe(t,e={}){let r=new S.ZodCustom({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...yt.util.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=n=>{n.value instanceof t||n.issues.push({code:"invalid_type",expected:t.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}var jNe=(...t)=>N._stringbool({Codec:S.ZodCodec,Boolean:S.ZodBoolean,String:S.ZodString},...t);S.stringbool=jNe;function FNe(t){let e=R8(()=>kN([ak(t),v8(),w8(),S8(),uk(e),P8(ak(),e)]));return e}function BNe(t,e){return new S.ZodPreprocess({type:"pipe",in:EN(t),out:e})}});var q8=v(Zr=>{"use strict";p();var zNe=Zr&&Zr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),VNe=Zr&&Zr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),ZNe=Zr&&Zr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&zNe(e,t,r);return VNe(e,t),e};Object.defineProperty(Zr,"__esModule",{value:!0});Zr.ZodFirstPartyTypeKind=Zr.config=Zr.$brand=Zr.ZodIssueCode=void 0;Zr.setErrorMap=HNe;Zr.getErrorMap=WNe;var D8=ZNe(fn());Zr.ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var U8=fn();Object.defineProperty(Zr,"$brand",{enumerable:!0,get:function(){return U8.$brand}});Object.defineProperty(Zr,"config",{enumerable:!0,get:function(){return U8.config}});function HNe(t){D8.config({customError:t})}function WNe(){return D8.config().customError}var M8;M8||(Zr.ZodFirstPartyTypeKind=M8={})});var j8=v(Zs=>{"use strict";p();var GNe=Zs&&Zs.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),KNe=Zs&&Zs.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),AN=Zs&&Zs.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&GNe(e,t,r);return KNe(e,t),e};Object.defineProperty(Zs,"__esModule",{value:!0});Zs.fromJSONSchema=n$e;var YNe=Ag(),JNe=AN(rk()),XNe=AN(gy()),QNe=AN(yy()),ge={...QNe,...JNe,iso:XNe},e$e=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function t$e(t,e){let r=t.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function r$e(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=t.slice(1).split("/").filter(Boolean);if(r.length===0)return e.rootSchema;let n=e.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===n){let i=r[1];if(!i||!e.defs[i])throw new Error(`Reference not found: ${t}`);return e.defs[i]}throw new Error(`Reference not found: ${t}`)}function L8(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return ge.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let i=t.$ref;if(e.refs.has(i))return e.refs.get(i);if(e.processing.has(i))return ge.lazy(()=>{if(!e.refs.has(i))throw new Error(`Circular reference not resolved: ${i}`);return e.refs.get(i)});e.processing.add(i);let o=r$e(i,e),a=bn(o,e);return e.refs.set(i,a),e.processing.delete(i),a}if(t.enum!==void 0){let i=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&i.length===1&&i[0]===null)return ge.null();if(i.length===0)return ge.never();if(i.length===1)return ge.literal(i[0]);if(i.every(a=>typeof a=="string"))return ge.enum(i);let o=i.map(a=>ge.literal(a));return o.length<2?o[0]:ge.union([o[0],o[1],...o.slice(2)])}if(t.const!==void 0)return ge.literal(t.const);let r=t.type;if(Array.isArray(r)){let i=r.map(o=>{let a={...t,type:o};return L8(a,e)});return i.length===0?ge.never():i.length===1?i[0]:ge.union(i)}if(!r)return ge.any();let n;switch(r){case"string":{let i=ge.string();if(t.format){let o=t.format;o==="email"?i=i.check(ge.email()):o==="uri"||o==="uri-reference"?i=i.check(ge.url()):o==="uuid"||o==="guid"?i=i.check(ge.uuid()):o==="date-time"?i=i.check(ge.iso.datetime()):o==="date"?i=i.check(ge.iso.date()):o==="time"?i=i.check(ge.iso.time()):o==="duration"?i=i.check(ge.iso.duration()):o==="ipv4"?i=i.check(ge.ipv4()):o==="ipv6"?i=i.check(ge.ipv6()):o==="mac"?i=i.check(ge.mac()):o==="cidr"?i=i.check(ge.cidrv4()):o==="cidr-v6"?i=i.check(ge.cidrv6()):o==="base64"?i=i.check(ge.base64()):o==="base64url"?i=i.check(ge.base64url()):o==="e164"?i=i.check(ge.e164()):o==="jwt"?i=i.check(ge.jwt()):o==="emoji"?i=i.check(ge.emoji()):o==="nanoid"?i=i.check(ge.nanoid()):o==="cuid"?i=i.check(ge.cuid()):o==="cuid2"?i=i.check(ge.cuid2()):o==="ulid"?i=i.check(ge.ulid()):o==="xid"?i=i.check(ge.xid()):o==="ksuid"&&(i=i.check(ge.ksuid()))}typeof t.minLength=="number"&&(i=i.min(t.minLength)),typeof t.maxLength=="number"&&(i=i.max(t.maxLength)),t.pattern&&(i=i.regex(new RegExp(t.pattern))),n=i;break}case"number":case"integer":{let i=r==="integer"?ge.number().int():ge.number();typeof t.minimum=="number"&&(i=i.min(t.minimum)),typeof t.maximum=="number"&&(i=i.max(t.maximum)),typeof t.exclusiveMinimum=="number"?i=i.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(i=i.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?i=i.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(i=i.lt(t.maximum)),typeof t.multipleOf=="number"&&(i=i.multipleOf(t.multipleOf)),n=i;break}case"boolean":{n=ge.boolean();break}case"null":{n=ge.null();break}case"object":{let i={},o=t.properties||{},a=new Set(t.required||[]);for(let[l,u]of Object.entries(o)){let c=bn(u,e);i[l]=a.has(l)?c:c.optional()}if(t.propertyNames){let l=bn(t.propertyNames,e),u=t.additionalProperties&&typeof t.additionalProperties=="object"?bn(t.additionalProperties,e):ge.any();if(Object.keys(i).length===0){n=ge.record(l,u);break}let c=ge.object(i).passthrough(),d=ge.looseRecord(l,u);n=ge.intersection(c,d);break}if(t.patternProperties){let l=t.patternProperties,u=Object.keys(l),c=[];for(let h of u){let m=bn(l[h],e),g=ge.string().regex(new RegExp(h));c.push(ge.looseRecord(g,m))}let d=[];if(Object.keys(i).length>0&&d.push(ge.object(i).passthrough()),d.push(...c),d.length===0)n=ge.object({}).passthrough();else if(d.length===1)n=d[0];else{let h=ge.intersection(d[0],d[1]);for(let m=2;m<d.length;m++)h=ge.intersection(h,d[m]);n=h}break}let s=ge.object(i);t.additionalProperties===!1?n=s.strict():typeof t.additionalProperties=="object"?n=s.catchall(bn(t.additionalProperties,e)):n=s.passthrough();break}case"array":{let i=t.prefixItems,o=t.items;if(i&&Array.isArray(i)){let a=i.map(l=>bn(l,e)),s=o&&typeof o=="object"&&!Array.isArray(o)?bn(o,e):void 0;s?n=ge.tuple(a).rest(s):n=ge.tuple(a),typeof t.minItems=="number"&&(n=n.check(ge.minLength(t.minItems))),typeof t.maxItems=="number"&&(n=n.check(ge.maxLength(t.maxItems)))}else if(Array.isArray(o)){let a=o.map(l=>bn(l,e)),s=t.additionalItems&&typeof t.additionalItems=="object"?bn(t.additionalItems,e):void 0;s?n=ge.tuple(a).rest(s):n=ge.tuple(a),typeof t.minItems=="number"&&(n=n.check(ge.minLength(t.minItems))),typeof t.maxItems=="number"&&(n=n.check(ge.maxLength(t.maxItems)))}else if(o!==void 0){let a=bn(o,e),s=ge.array(a);typeof t.minItems=="number"&&(s=s.min(t.minItems)),typeof t.maxItems=="number"&&(s=s.max(t.maxItems)),n=s}else n=ge.array(ge.any());break}default:throw new Error(`Unsupported type: ${r}`)}return n}function bn(t,e){if(typeof t=="boolean")return t?ge.any():ge.never();let r=L8(t,e),n=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let s=t.anyOf.map(u=>bn(u,e)),l=ge.union(s);r=n?ge.intersection(r,l):l}if(t.oneOf&&Array.isArray(t.oneOf)){let s=t.oneOf.map(u=>bn(u,e)),l=ge.xor(s);r=n?ge.intersection(r,l):l}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=n?r:ge.any();else{let s=n?r:bn(t.allOf[0],e),l=n?0:1;for(let u=l;u<t.allOf.length;u++)s=ge.intersection(s,bn(t.allOf[u],e));r=s}t.nullable===!0&&e.version==="openapi-3.0"&&(r=ge.nullable(r)),t.readOnly===!0&&(r=ge.readonly(r)),t.default!==void 0&&(r=r.default(t.default));let i={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let s of o)s in t&&(i[s]=t[s]);let a=["contentEncoding","contentMediaType","contentSchema"];for(let s of a)s in t&&(i[s]=t[s]);for(let s of Object.keys(t))e$e.has(s)||(i[s]=t[s]);return Object.keys(i).length>0&&e.registry.add(r,i),t.description&&(r=r.describe(t.description)),r}function n$e(t,e){if(typeof t=="boolean")return t?ge.any():ge.never();let r;try{r=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let n=t$e(r,e?.defaultTarget),i=r.$defs||r.definitions||{},o={version:n,defs:i,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??YNe.globalRegistry};return bn(r,o)}});var B8=v(yi=>{"use strict";p();var i$e=yi&&yi.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),o$e=yi&&yi.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),F8=yi&&yi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&i$e(e,t,r);return o$e(e,t),e};Object.defineProperty(yi,"__esModule",{value:!0});yi.string=a$e;yi.number=s$e;yi.boolean=l$e;yi.bigint=u$e;yi.date=c$e;var vy=F8(fn()),wy=F8(yy());function a$e(t){return vy._coercedString(wy.ZodString,t)}function s$e(t){return vy._coercedNumber(wy.ZodNumber,t)}function l$e(t){return vy._coercedBoolean(wy.ZodBoolean,t)}function u$e(t){return vy._coercedBigint(wy.ZodBigInt,t)}function c$e(t){return vy._coercedDate(wy.ZodDate,t)}});var CN=v(Pe=>{"use strict";p();var z8=Pe&&Pe.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),d$e=Pe&&Pe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),dk=Pe&&Pe.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&z8(e,t,r);return d$e(e,t),e},Sy=Pe&&Pe.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&z8(e,t,r)},p$e=Pe&&Pe.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Pe,"__esModule",{value:!0});Pe.coerce=Pe.iso=Pe.ZodISODuration=Pe.ZodISOTime=Pe.ZodISODate=Pe.ZodISODateTime=Pe.locales=Pe.fromJSONSchema=Pe.toJSONSchema=Pe.NEVER=Pe.util=Pe.TimePrecision=Pe.flattenError=Pe.formatError=Pe.prettifyError=Pe.treeifyError=Pe.regexes=Pe.clone=Pe.$brand=Pe.$input=Pe.$output=Pe.config=Pe.registry=Pe.globalRegistry=Pe.core=void 0;Pe.core=dk(fn());Sy(yy(),Pe);Sy(rk(),Pe);Sy(_N(),Pe);Sy(bN(),Pe);Sy(q8(),Pe);var f$e=fn(),h$e=p$e($I());(0,f$e.config)((0,h$e.default)());var Nn=fn();Object.defineProperty(Pe,"globalRegistry",{enumerable:!0,get:function(){return Nn.globalRegistry}});Object.defineProperty(Pe,"registry",{enumerable:!0,get:function(){return Nn.registry}});Object.defineProperty(Pe,"config",{enumerable:!0,get:function(){return Nn.config}});Object.defineProperty(Pe,"$output",{enumerable:!0,get:function(){return Nn.$output}});Object.defineProperty(Pe,"$input",{enumerable:!0,get:function(){return Nn.$input}});Object.defineProperty(Pe,"$brand",{enumerable:!0,get:function(){return Nn.$brand}});Object.defineProperty(Pe,"clone",{enumerable:!0,get:function(){return Nn.clone}});Object.defineProperty(Pe,"regexes",{enumerable:!0,get:function(){return Nn.regexes}});Object.defineProperty(Pe,"treeifyError",{enumerable:!0,get:function(){return Nn.treeifyError}});Object.defineProperty(Pe,"prettifyError",{enumerable:!0,get:function(){return Nn.prettifyError}});Object.defineProperty(Pe,"formatError",{enumerable:!0,get:function(){return Nn.formatError}});Object.defineProperty(Pe,"flattenError",{enumerable:!0,get:function(){return Nn.flattenError}});Object.defineProperty(Pe,"TimePrecision",{enumerable:!0,get:function(){return Nn.TimePrecision}});Object.defineProperty(Pe,"util",{enumerable:!0,get:function(){return Nn.util}});Object.defineProperty(Pe,"NEVER",{enumerable:!0,get:function(){return Nn.NEVER}});var m$e=Og();Object.defineProperty(Pe,"toJSONSchema",{enumerable:!0,get:function(){return m$e.toJSONSchema}});var g$e=j8();Object.defineProperty(Pe,"fromJSONSchema",{enumerable:!0,get:function(){return g$e.fromJSONSchema}});Pe.locales=dk(UI());var pk=gy();Object.defineProperty(Pe,"ZodISODateTime",{enumerable:!0,get:function(){return pk.ZodISODateTime}});Object.defineProperty(Pe,"ZodISODate",{enumerable:!0,get:function(){return pk.ZodISODate}});Object.defineProperty(Pe,"ZodISOTime",{enumerable:!0,get:function(){return pk.ZodISOTime}});Object.defineProperty(Pe,"ZodISODuration",{enumerable:!0,get:function(){return pk.ZodISODuration}});Pe.iso=dk(gy());Pe.coerce=dk(B8())});var xN=v(ri=>{"use strict";p();var V8=ri&&ri.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),y$e=ri&&ri.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),_$e=ri&&ri.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&V8(e,t,r);return y$e(e,t),e},b$e=ri&&ri.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&V8(e,t,r)};Object.defineProperty(ri,"__esModule",{value:!0});ri.z=void 0;var Z8=_$e(CN());ri.z=Z8;b$e(CN(),ri);ri.default=Z8});var fk=v(as=>{"use strict";p();var v$e=as&&as.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),w$e=as&&as.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&v$e(e,t,r)},S$e=as&&as.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(as,"__esModule",{value:!0});var T$e=S$e(xN());w$e(xN(),as);as.default=T$e.default});var MN=v(ni=>{"use strict";p();Object.defineProperty(ni,Symbol.toStringTag,{value:"Module"});var k$e=de(),eu=ow(),IN=_l(),mk=Rs(),H8=Qu();fi();var Xf=Ko(),P$e=uf(),hk=Wa(),E$e=Ll(),ON=GO(),A$e=Yg(),tu=yN(),W8=Dl(),C$e=rT(),x$e=fk(),I$e=k$e.__exportAll({BaseToolkit:()=>G8,DynamicStructuredTool:()=>$N,DynamicTool:()=>NN,StructuredTool:()=>gk,Tool:()=>RN,ToolInputParsingException:()=>eu.ToolInputParsingException,isLangChainTool:()=>tu.isLangChainTool,isRunnableToolLike:()=>tu.isRunnableToolLike,isStructuredTool:()=>tu.isStructuredTool,isStructuredToolParams:()=>tu.isStructuredToolParams,tool:()=>K8}),gk=class extends A$e.BaseLangChain{constructor(e){super(e??{});f(this,"extras");f(this,"returnDirect",!1);f(this,"verboseParsingErrors",!1);f(this,"responseFormat","content");f(this,"defaultConfig");this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata,this.extras=e?.extras??this.extras}get lc_namespace(){return["langchain","tools"]}async invoke(e,r){let n,i=Xf.ensureConfig(Xf.mergeConfigs(this.defaultConfig,r));return eu._isToolCall(e)?(n=e.args,i={...i,toolCall:e}):n=e,this.call(n,i)}async call(e,r,n){let i=eu._isToolCall(e)?e.args:e,o;if(hk.isInteropZodSchema(this.schema))try{o=await hk.interopParseAsync(this.schema,i)}catch(g){let y="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(y=`${y}
396
396
  Details: ${g.message}`),hk.isInteropZodError(g)&&(y=`${y}
397
397
 
398
398
  ${x$e.z.prettifyError(g)}`),new eu.ToolInputParsingException(y,JSON.stringify(e))}else{let g=(0,C$e.validate)(i,this.schema);if(!g.valid){let y="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(y=`${y}
399
399
  Details: ${g.errors.map(_=>`${_.keywordLocation}: ${_.error}`).join(`
400
400
  `)}`),new eu.ToolInputParsingException(y,JSON.stringify(e))}o=i}let a=mk.parseCallbackConfigArg(r),s=mk.CallbackManager.configure(a.callbacks,this.callbacks,a.tags||n,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),l;eu._isToolCall(e)&&(l=e.id),!l&&eu._configHasToolCallId(a)&&(l=a.toolCall.id);let u=await s?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),a.runId,void 0,void 0,void 0,a.runName,l);delete a.runId;let c;try{let g=await this._call(o,u,a);c=ON.isAsyncGenerator(g)?await ON.consumeAsyncGenerator(g,async y=>{try{await u?.handleToolEvent(y)}catch(_){await u?.handleToolError(_)}}):g}catch(g){throw await u?.handleToolError(g),g}let d,h;if(this.responseFormat==="content_and_artifact")if(Array.isArray(c)&&c.length===2)[d,h]=c;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
401
- Result: ${JSON.stringify(c)}`);else d=c;let m=O$e({content:d,artifact:h,toolCallId:l,name:this.name,metadata:this.metadata});return await u?.handleToolEnd(m),m}},RN=class extends gk{constructor(e){super(e);f(this,"schema",WG.z.object({input:WG.z.string().optional()}).transform(e=>e.input))}call(e,r){let n=typeof e=="string"||e==null?{input:e}:e;return super.call(n,r)}},NN=class extends RN{constructor(e){super(e);f(this,"name");f(this,"description");f(this,"func");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}static lc_name(){return"DynamicTool"}async call(e,r){let n=mk.parseCallbackConfigArg(r);return n.runName===void 0&&(n.runName=this.name),super.call(e,n)}_call(e,r,n){return this.func(e,r,n)}},$N=class extends gk{constructor(e){super(e);f(this,"description");f(this,"func");f(this,"schema");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}static lc_name(){return"DynamicStructuredTool"}async call(e,r,n){let i=mk.parseCallbackConfigArg(r);return i.runName===void 0&&(i.runName=this.name),super.call(e,i,n)}_call(e,r,n){return this.func(e,r,n)}},GG=class{getTools(){return this.tools}};function KG(t,e){let r=hk.isSimpleStringZodSchema(e.schema),n=E$e.validatesOnlyStrings(e.schema);if(!e.schema||r||n)return new NN({...e,description:e.description??e.schema?.description??`${e.name} tool`,func:async(a,s,l)=>new Promise((u,c)=>{let d=Xf.patchConfig(l,{callbacks:s?.getChild()});HG.AsyncLocalStorageProviderSingleton.runWithConfig(Xf.pickRunnableConfigKeys(d),async()=>{try{u(t(a,d))}catch(h){c(h)}})})});let i=e.schema,o=e.description??e.schema.description??`${e.name} tool`;return new $N({...e,description:o,schema:i,func:async(a,s,l)=>new Promise((u,c)=>{let d,h=()=>{l?.signal&&d&&l.signal.removeEventListener("abort",d)};l?.signal&&(d=()=>{h(),c(P$e.getAbortSignalError(l.signal))},l.signal.addEventListener("abort",d,{once:!0}));let m=Xf.patchConfig(l,{callbacks:s?.getChild()});HG.AsyncLocalStorageProviderSingleton.runWithConfig(Xf.pickRunnableConfigKeys(m),async()=>{try{let g=await t(a,m);if(ON.isAsyncGenerator(g)){u(g);return}if(l?.signal?.aborted){h();return}h(),u(g)}catch(g){h(),c(g)}})})})}function O$e(t){let{content:e,artifact:r,toolCallId:n,metadata:i}=t;return n&&!IN.isDirectToolOutput(e)?typeof e=="string"||Array.isArray(e)&&e.every(o=>typeof o=="object")?new IN.ToolMessage({status:"success",content:e,artifact:r,tool_call_id:n,name:t.name,metadata:i}):new IN.ToolMessage({status:"success",content:R$e(e),artifact:r,tool_call_id:n,name:t.name,metadata:i}):e}function R$e(t){try{return JSON.stringify(t)??""}catch{return`${t}`}}ni.BaseToolkit=GG;ni.DynamicStructuredTool=$N;ni.DynamicTool=NN;ni.StructuredTool=gk;ni.Tool=RN;ni.ToolInputParsingException=eu.ToolInputParsingException;ni.isLangChainTool=tu.isLangChainTool;ni.isRunnableToolLike=tu.isRunnableToolLike;ni.isStructuredTool=tu.isStructuredTool;ni.isStructuredToolParams=tu.isStructuredToolParams;ni.tool=KG;Object.defineProperty(ni,"tools_exports",{enumerable:!0,get:function(){return I$e}})});var JG=v(yk=>{"use strict";p();Object.defineProperty(yk,Symbol.toStringTag,{value:"Module"});var N$e=de(),$$e=yo(),M$e=N$e.__exportAll({RunCollectorCallbackHandler:()=>YG}),YG=class extends $$e.BaseTracer{constructor({exampleId:e}={}){super({_awaitHandler:!0});f(this,"name","run_collector");f(this,"exampleId");f(this,"tracedRuns");this.exampleId=e,this.tracedRuns=[]}async persistRun(e){let r={...e};r.reference_example_id=this.exampleId,this.tracedRuns.push(r)}};yk.RunCollectorCallbackHandler=YG;Object.defineProperty(yk,"run_collector_exports",{enumerable:!0,get:function(){return M$e}})});var XG=v(DN=>{"use strict";p();Object.defineProperty(DN,Symbol.toStringTag,{value:"Module"});var D$e=de().__exportAll({});Object.defineProperty(DN,"stream_exports",{enumerable:!0,get:function(){return D$e}})});var e8=v(_k=>{"use strict";p();Object.defineProperty(_k,Symbol.toStringTag,{value:"Module"});var U$e=de().__exportAll({chunkArray:()=>QG}),QG=(t,e)=>t.reduce((r,n,i)=>{let o=Math.floor(i/e);return r[o]=(r[o]||[]).concat([n]),r},[]);_k.chunkArray=QG;Object.defineProperty(_k,"chunk_array_exports",{enumerable:!0,get:function(){return U$e}})});var r8=v(bk=>{"use strict";p();Object.defineProperty(bk,Symbol.toStringTag,{value:"Module"});var q$e=de().__exportAll({context:()=>t8});function t8(t,...e){let r=t.raw,n="";for(let i=0;i<r.length;i++){let o=r[i].replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{");if(n+=o,i<e.length){let a=L$e(e[i],n);n+=typeof a=="string"?a:JSON.stringify(a)}}return n=j$e(n),n=n.trim(),n=n.replace(/\\n/g,`
401
+ Result: ${JSON.stringify(c)}`);else d=c;let m=O$e({content:d,artifact:h,toolCallId:l,name:this.name,metadata:this.metadata});return await u?.handleToolEnd(m),m}},RN=class extends gk{constructor(e){super(e);f(this,"schema",W8.z.object({input:W8.z.string().optional()}).transform(e=>e.input))}call(e,r){let n=typeof e=="string"||e==null?{input:e}:e;return super.call(n,r)}},NN=class extends RN{constructor(e){super(e);f(this,"name");f(this,"description");f(this,"func");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}static lc_name(){return"DynamicTool"}async call(e,r){let n=mk.parseCallbackConfigArg(r);return n.runName===void 0&&(n.runName=this.name),super.call(e,n)}_call(e,r,n){return this.func(e,r,n)}},$N=class extends gk{constructor(e){super(e);f(this,"description");f(this,"func");f(this,"schema");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}static lc_name(){return"DynamicStructuredTool"}async call(e,r,n){let i=mk.parseCallbackConfigArg(r);return i.runName===void 0&&(i.runName=this.name),super.call(e,i,n)}_call(e,r,n){return this.func(e,r,n)}},G8=class{getTools(){return this.tools}};function K8(t,e){let r=hk.isSimpleStringZodSchema(e.schema),n=E$e.validatesOnlyStrings(e.schema);if(!e.schema||r||n)return new NN({...e,description:e.description??e.schema?.description??`${e.name} tool`,func:async(a,s,l)=>new Promise((u,c)=>{let d=Xf.patchConfig(l,{callbacks:s?.getChild()});H8.AsyncLocalStorageProviderSingleton.runWithConfig(Xf.pickRunnableConfigKeys(d),async()=>{try{u(t(a,d))}catch(h){c(h)}})})});let i=e.schema,o=e.description??e.schema.description??`${e.name} tool`;return new $N({...e,description:o,schema:i,func:async(a,s,l)=>new Promise((u,c)=>{let d,h=()=>{l?.signal&&d&&l.signal.removeEventListener("abort",d)};l?.signal&&(d=()=>{h(),c(P$e.getAbortSignalError(l.signal))},l.signal.addEventListener("abort",d,{once:!0}));let m=Xf.patchConfig(l,{callbacks:s?.getChild()});H8.AsyncLocalStorageProviderSingleton.runWithConfig(Xf.pickRunnableConfigKeys(m),async()=>{try{let g=await t(a,m);if(ON.isAsyncGenerator(g)){u(g);return}if(l?.signal?.aborted){h();return}h(),u(g)}catch(g){h(),c(g)}})})})}function O$e(t){let{content:e,artifact:r,toolCallId:n,metadata:i}=t;return n&&!IN.isDirectToolOutput(e)?typeof e=="string"||Array.isArray(e)&&e.every(o=>typeof o=="object")?new IN.ToolMessage({status:"success",content:e,artifact:r,tool_call_id:n,name:t.name,metadata:i}):new IN.ToolMessage({status:"success",content:R$e(e),artifact:r,tool_call_id:n,name:t.name,metadata:i}):e}function R$e(t){try{return JSON.stringify(t)??""}catch{return`${t}`}}ni.BaseToolkit=G8;ni.DynamicStructuredTool=$N;ni.DynamicTool=NN;ni.StructuredTool=gk;ni.Tool=RN;ni.ToolInputParsingException=eu.ToolInputParsingException;ni.isLangChainTool=tu.isLangChainTool;ni.isRunnableToolLike=tu.isRunnableToolLike;ni.isStructuredTool=tu.isStructuredTool;ni.isStructuredToolParams=tu.isStructuredToolParams;ni.tool=K8;Object.defineProperty(ni,"tools_exports",{enumerable:!0,get:function(){return I$e}})});var J8=v(yk=>{"use strict";p();Object.defineProperty(yk,Symbol.toStringTag,{value:"Module"});var N$e=de(),$$e=yo(),M$e=N$e.__exportAll({RunCollectorCallbackHandler:()=>Y8}),Y8=class extends $$e.BaseTracer{constructor({exampleId:e}={}){super({_awaitHandler:!0});f(this,"name","run_collector");f(this,"exampleId");f(this,"tracedRuns");this.exampleId=e,this.tracedRuns=[]}async persistRun(e){let r={...e};r.reference_example_id=this.exampleId,this.tracedRuns.push(r)}};yk.RunCollectorCallbackHandler=Y8;Object.defineProperty(yk,"run_collector_exports",{enumerable:!0,get:function(){return M$e}})});var X8=v(DN=>{"use strict";p();Object.defineProperty(DN,Symbol.toStringTag,{value:"Module"});var D$e=de().__exportAll({});Object.defineProperty(DN,"stream_exports",{enumerable:!0,get:function(){return D$e}})});var eG=v(_k=>{"use strict";p();Object.defineProperty(_k,Symbol.toStringTag,{value:"Module"});var U$e=de().__exportAll({chunkArray:()=>Q8}),Q8=(t,e)=>t.reduce((r,n,i)=>{let o=Math.floor(i/e);return r[o]=(r[o]||[]).concat([n]),r},[]);_k.chunkArray=Q8;Object.defineProperty(_k,"chunk_array_exports",{enumerable:!0,get:function(){return U$e}})});var rG=v(bk=>{"use strict";p();Object.defineProperty(bk,Symbol.toStringTag,{value:"Module"});var q$e=de().__exportAll({context:()=>tG});function tG(t,...e){let r=t.raw,n="";for(let i=0;i<r.length;i++){let o=r[i].replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{");if(n+=o,i<e.length){let a=L$e(e[i],n);n+=typeof a=="string"?a:JSON.stringify(a)}}return n=j$e(n),n=n.trim(),n=n.replace(/\\n/g,`
402
402
  `),n}function L$e(t,e){if(typeof t!="string"||!t.includes(`
403
403
  `))return t;let r=e.slice(e.lastIndexOf(`
404
404
  `)+1).match(/^(\s+)/);if(r){let n=r[1];return t.replace(/\n/g,`
405
405
  ${n}`)}return t}function j$e(t){let e=t.split(`
406
406
  `),r=null;for(let n of e){let i=n.match(/^(\s+)\S+/);if(i){let o=i[1].length;r===null?r=o:r=Math.min(r,o)}}return r===null?t:e.map(n=>n[0]===" "||n[0]===" "?n.slice(r):n).join(`
407
- `)}bk.context=t8;Object.defineProperty(bk,"context_exports",{enumerable:!0,get:function(){return q$e}})});var o8=v(ru=>{"use strict";p();Object.defineProperty(ru,Symbol.toStringTag,{value:"Module"});var F$e=de(),B$e=Ri(),z$e=F$e.__exportAll({EventStreamContentType:()=>n8,convertEventStreamToIterableReadableDataStream:()=>i8,getBytes:()=>qN,getLines:()=>LN,getMessages:()=>jN}),n8="text/event-stream";async function qN(t,e){if(t instanceof ReadableStream){let r=t.getReader();for(;;){let n=await r.read();if(n.done){e(new Uint8Array,!0);break}e(n.value)}}else try{for await(let r of t)e(new Uint8Array(r));e(new Uint8Array,!0)}catch(r){throw new Error(["Parsing event source stream failed.","Ensure your implementation of fetch returns a web or Node readable stream.",`Error: ${r.message}`].join(`
407
+ `)}bk.context=tG;Object.defineProperty(bk,"context_exports",{enumerable:!0,get:function(){return q$e}})});var oG=v(ru=>{"use strict";p();Object.defineProperty(ru,Symbol.toStringTag,{value:"Module"});var F$e=de(),B$e=Ri(),z$e=F$e.__exportAll({EventStreamContentType:()=>nG,convertEventStreamToIterableReadableDataStream:()=>iG,getBytes:()=>qN,getLines:()=>LN,getMessages:()=>jN}),nG="text/event-stream";async function qN(t,e){if(t instanceof ReadableStream){let r=t.getReader();for(;;){let n=await r.read();if(n.done){e(new Uint8Array,!0);break}e(n.value)}}else try{for await(let r of t)e(new Uint8Array(r));e(new Uint8Array,!0)}catch(r){throw new Error(["Parsing event source stream failed.","Ensure your implementation of fetch returns a web or Node readable stream.",`Error: ${r.message}`].join(`
408
408
  `))}}function LN(t){let e,r,n,i=!1;return function(a,s){if(s){t(a,0,!0);return}e===void 0?(e=a,r=0,n=-1):e=V$e(e,a);let l=e.length,u=0;for(;r<l;){i&&(e[r]===10&&(u=++r),i=!1);let c=-1;for(;r<l&&c===-1;++r)switch(e[r]){case 58:n===-1&&(n=r-u);break;case 13:i=!0;case 10:c=r;break}if(c===-1)break;t(e.subarray(u,c),n),u=r,n=-1}u===l?e=void 0:u!==0&&(e=e.subarray(u),r-=u)}}function jN(t,e,r){let n=UN(),i=new TextDecoder;return function(a,s,l){if(l){Z$e(n)||(t?.(n),n=UN());return}if(a.length===0)t?.(n),n=UN();else if(s>0){let u=i.decode(a.subarray(0,s)),c=s+(a[s+1]===32?2:1),d=i.decode(a.subarray(c));switch(u){case"data":n.data=n.data?n.data+`
409
- `+d:d;break;case"event":n.event=d;break;case"id":e?.(n.id=d);break;case"retry":{let h=parseInt(d,10);Number.isNaN(h)||r?.(n.retry=h);break}}}}}function V$e(t,e){let r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}function UN(){return{data:"",event:"",id:"",retry:void 0}}function i8(t,e){let r=new ReadableStream({async start(n){let i=jN(a=>{if(a.event==="error")throw new Error(a.data??"Unspecified event streaming error.");a.event==="metadata"?e?.(a):a.data&&n.enqueue(a.data)});await qN(t,LN((a,s,l)=>{i(a,s,l),l&&n.close()}))}});return B$e.IterableReadableStream.fromReadableStream(r)}function Z$e(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}ru.EventStreamContentType=n8;ru.convertEventStreamToIterableReadableDataStream=i8;Object.defineProperty(ru,"event_source_parse_exports",{enumerable:!0,get:function(){return z$e}});ru.getBytes=qN;ru.getLines=LN;ru.getMessages=jN});var a8=v(FN=>{"use strict";p();Object.defineProperty(FN,Symbol.toStringTag,{value:"Module"});var H$e=de().__exportAll({});Object.defineProperty(FN,"format_exports",{enumerable:!0,get:function(){return H$e}})});var l8=v(Ws=>{"use strict";p();Object.defineProperty(Ws,Symbol.toStringTag,{value:"Module"});var W$e=de(),G$e=Ll(),Hs=yN(),K$e=W$e.__exportAll({convertToOpenAIFunction:()=>BN,convertToOpenAITool:()=>s8,isLangChainTool:()=>Hs.isLangChainTool,isRunnableToolLike:()=>Hs.isRunnableToolLike,isStructuredTool:()=>Hs.isStructuredTool,isStructuredToolParams:()=>Hs.isStructuredToolParams});function BN(t,e){let r=typeof e=="number"?void 0:e;return{name:t.name,description:t.description,parameters:G$e.toJsonSchema(t.schema),...r?.strict!==void 0?{strict:r.strict}:{}}}function s8(t,e){let r=typeof e=="number"?void 0:e,n;return Hs.isLangChainTool(t)?n={type:"function",function:BN(t)}:n=t,r?.strict!==void 0&&(n.function.strict=r.strict),n}Ws.convertToOpenAIFunction=BN;Ws.convertToOpenAITool=s8;Object.defineProperty(Ws,"function_calling_exports",{enumerable:!0,get:function(){return K$e}});Ws.isLangChainTool=Hs.isLangChainTool;Ws.isRunnableToolLike=Hs.isRunnableToolLike;Ws.isStructuredTool=Hs.isStructuredTool;Ws.isStructuredToolParams=Hs.isStructuredToolParams});var zN=v(u8=>{"use strict";p();function Y$e(t,e){let r=0,n=0,i=0;for(let o=0;o<t.length;o++)r+=t[o]*e[o],n+=t[o]*t[o],i+=e[o]*e[o];return r/(Math.sqrt(n)*Math.sqrt(i))}u8.cosine=Y$e});var d8=v(c8=>{"use strict";p();function J$e(t,e){let r=0;for(let n=0;n<t.length;n++)r+=t[n]*e[n];return r}c8.innerProduct=J$e});var f8=v(p8=>{"use strict";p();function X$e(t,e){let r=0;for(let n=0;n<t.length;n++)r+=(t[n]-e[n])*(t[n]-e[n]);return r}function Q$e(t,e){return Math.sqrt(X$e(t,e))}p8.euclidean=Q$e});var b8=v(Gs=>{"use strict";p();Object.defineProperty(Gs,Symbol.toStringTag,{value:"Module"});var e1e=de(),t1e=zN(),r1e=d8(),n1e=f8(),i1e=e1e.__exportAll({cosineSimilarity:()=>vk,euclideanDistance:()=>g8,innerProduct:()=>m8,matrixFunc:()=>Ty,maximalMarginalRelevance:()=>y8,normalize:()=>h8});function Ty(t,e,r){if(t.length===0||t[0].length===0||e.length===0||e[0].length===0)return[[]];if(t[0].length!==e[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[t.length,t[0].length]} and Y has shape ${[e.length,e[0].length]}.`);return t.map(n=>e.map(i=>r(n,i)).map(i=>Number.isNaN(i)?0:i))}function h8(t,e=!1){let r=o1e(t);return t.map(n=>n.map(i=>e?1-i/r:i/r))}function vk(t,e){return Ty(t,e,t1e.cosine)}function m8(t,e){return Ty(t,e,r1e.innerProduct)}function g8(t,e){return Ty(t,e,n1e.euclidean)}function y8(t,e,r=.5,n=4){if(Math.min(n,e.length)<=0)return[];let i=vk(Array.isArray(t[0])?t:[t],e)[0],o=_8(i).maxIndex,a=[e[o]],s=[o];for(;s.length<Math.min(n,e.length);){let l=-1/0,u=-1,c=vk(e,a);i.forEach((d,h)=>{if(s.includes(h))return;let m=Math.max(...c[h]),g=r*d-(1-r)*m;g>l&&(l=g,u=h)}),a.push(e[u]),s.push(u)}return s}function _8(t){if(t.length===0)return{maxIndex:-1,maxValue:NaN};let e=t[0],r=0;for(let n=1;n<t.length;n+=1)t[n]>e&&(r=n,e=t[n]);return{maxIndex:r,maxValue:e}}function o1e(t){return t.reduce((e,r)=>Math.max(e,_8(r).maxValue),0)}Gs.cosineSimilarity=vk;Gs.euclideanDistance=g8;Gs.innerProduct=m8;Object.defineProperty(Gs,"math_exports",{enumerable:!0,get:function(){return i1e}});Gs.matrixFunc=Ty;Gs.maximalMarginalRelevance=y8;Gs.normalize=h8});var E8=v(Ks=>{"use strict";p();Object.defineProperty(Ks,Symbol.toStringTag,{value:"Module"});var a1e=de().__exportAll({isCloudMetadata:()=>wk,isLocalhost:()=>Sk,isPrivateIp:()=>VN,isSafeUrl:()=>k8,isSameOrigin:()=>P8,validateSafeUrl:()=>ZN}),s1e=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","127.0.0.0/8","169.254.0.0/16","0.0.0.0/8","::1/128","fc00::/7","fe80::/10","ff00::/8"],l1e=["169.254.169.254","169.254.170.2","100.100.100.200"],u1e=["metadata.google.internal","metadata","instance-data"],c1e=["localhost","localhost.localdomain"],d1e=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function v8(t){return d1e.test(t)}function Tk(t){return T8(t)!==null}function w8(t){return v8(t)||Tk(t)}function S8(t){if(v8(t))return t.split(".").map(e=>parseInt(e,10));if(Tk(t)){let e=T8(t);if(!e)return null;let r=e.split(":"),n=[];for(let i of r)n.push(parseInt(i,16));return n}return null}function T8(t){if(!t||typeof t!="string"||!t.includes(":")||!/^[0-9a-fA-F:]+$/.test(t))return null;let e=t;if(e.includes("::")){let n=e.split("::");if(n.length>2)return null;let[i,o]=n,a=i?i.split(":"):[],s=o?o.split(":"):[],l=8-(a.length+s.length);if(l<0)return null;let u=Array(l).fill("0");e=[...a,...u,...s].filter(c=>c!=="").join(":")}let r=e.split(":");if(r.length!==8)return null;for(let n of r)if(n.length===0||n.length>4||!/^[0-9a-fA-F]+$/.test(n))return null;return r.map(n=>n.padStart(4,"0").toLowerCase()).join(":")}function p1e(t){let[e,r]=t.split("/");if(!e||!r)return null;let n=S8(e);if(!n)return null;let i=parseInt(r,10);if(isNaN(i))return null;let o=Tk(e);return o&&i>128||!o&&i>32?null:{addr:n,prefixLen:i,isIpv6:o}}function f1e(t,e){let r=S8(t);if(!r)return!1;let n=p1e(e);if(!n)return!1;let i=Tk(t);if(i!==n.isIpv6)return!1;let{addr:o,prefixLen:a}=n;if(i)for(let s=0;s<Math.ceil(a/16);s++){let l=65535<<16-Math.min(16,a-s*16)&65535;if((r[s]&l)!==(o[s]&l))return!1}else for(let s=0;s<Math.ceil(a/8);s++){let l=255<<8-Math.min(8,a-s*8)&255;if((r[s]&l)!==(o[s]&l))return!1}return!0}function VN(t){if(!w8(t))return!1;for(let e of s1e)if(f1e(t,e))return!0;return!1}function wk(t,e){if(l1e.includes(e||""))return!0;let r=t.toLowerCase();return!!u1e.includes(r)}function Sk(t,e){if(e&&(e==="127.0.0.1"||e==="::1"||e==="0.0.0.0"||e.startsWith("127.")))return!0;let r=t.toLowerCase();return!!c1e.includes(r)}function ZN(t,e){let r=e?.allowPrivate??!1,n=e?.allowHttp??!1;try{let i;try{i=new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}let o=i.hostname;if(!o)throw new Error("URL missing hostname.");if(wk(o))throw new Error(`URL points to cloud metadata endpoint: ${o}`);if(Sk(o)){if(!r)throw new Error(`URL points to localhost: ${o}`);return t}let a=i.protocol;if(a!=="http:"&&a!=="https:")throw new Error(`Invalid URL scheme: ${a}. Only http and https are allowed.`);if(a==="http:"&&!n)throw new Error("HTTP scheme not allowed. Use HTTPS or set allowHttp: true.");if(w8(o)){let s=o;if(Sk(o,s)){if(!r)throw new Error(`URL points to localhost: ${o}`);return t}if(wk(o,s))throw new Error(`URL resolves to cloud metadata IP: ${s} (${o})`);if(VN(s)&&!r)throw new Error(`URL resolves to private IP: ${s} (${o}). Set allowPrivate: true to allow.`);return t}return t}catch(i){throw i&&typeof i=="object"&&"message"in i?i:new Error(`URL validation failed: ${i}`)}}function k8(t,e){try{return ZN(t,e),!0}catch{return!1}}function P8(t,e){try{return new URL(t).origin===new URL(e).origin}catch{return!1}}Ks.isCloudMetadata=wk;Ks.isLocalhost=Sk;Ks.isPrivateIp=VN;Ks.isSafeUrl=k8;Ks.isSameOrigin=P8;Object.defineProperty(Ks,"ssrf_exports",{enumerable:!0,get:function(){return a1e}});Ks.validateSafeUrl=ZN});var WN=v(Qf=>{"use strict";p();Object.defineProperty(Qf,Symbol.toStringTag,{value:"Module"});var h1e=de(),m1e=xi(),g1e=KT(),y1e=h1e.__exportAll({SaveableVectorStore:()=>A8,VectorStore:()=>HN,VectorStoreRetriever:()=>ky}),ky=class extends g1e.BaseRetriever{constructor(e){super(e);f(this,"vectorStore");f(this,"k",4);f(this,"searchType","similarity");f(this,"searchKwargs");f(this,"filter");this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType==="mmr"&&(this.searchKwargs=e.searchKwargs)}static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}_vectorstoreType(){return this.vectorStore._vectorstoreType()}async _getRelevantDocuments(e,r){if(this.searchType==="mmr"){if(typeof this.vectorStore.maxMarginalRelevanceSearch!="function")throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},r?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,r?.getChild("vectorstore"))}async addDocuments(e,r){return this.vectorStore.addDocuments(e,r)}},HN=class extends m1e.Serializable{constructor(e,r){super(r);f(this,"lc_namespace",["langchain","vectorstores",this._vectorstoreType()]);f(this,"embeddings");this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,r=4,n=void 0,i=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),r,n)).map(o=>o[0])}async similaritySearchWithScore(e,r=4,n=void 0,i=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),r,n)}static fromTexts(e,r,n,i){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,r,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,r,n,i,o,a){if(typeof e=="number")return new ky({vectorStore:this,k:e,filter:r,tags:[...i??[],this._vectorstoreType()],metadata:o,verbose:a,callbacks:n});{let s={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType==="mmr"?new ky({...s,searchKwargs:e.searchKwargs}):new ky({...s})}}},A8=class extends HN{static load(t,e){throw new Error("Not implemented")}};Qf.SaveableVectorStore=A8;Qf.VectorStore=HN;Qf.VectorStoreRetriever=ky;Object.defineProperty(Qf,"vectorstores_exports",{enumerable:!0,get:function(){return y1e}})});var I8=v(kk=>{"use strict";p();var nu=Fr(),GN=tc(),iu=Ll(),_1e=br();ei();var KN=MT(),b1e=class extends KN.BaseChatModel{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(t,e,r){if(e?.stop?.length)return{generations:[{message:new nu.AIMessage(e.stop[0]),text:e.stop[0]}]};let n=t.map(i=>typeof i.content=="string"?i.content:JSON.stringify(i.content,null,2)).join(`
410
- `);return await r?.handleLLMNewToken(n),{generations:[{message:new nu.AIMessage(n),text:n}],llmOutput:{}}}},v1e=class C8 extends KN.BaseChatModel{constructor({sleep:r=50,responses:n=[],chunks:i=[],toolStyle:o="openai",thrownErrorString:a,...s}){super(s);f(this,"sleep",50);f(this,"responses",[]);f(this,"chunks",[]);f(this,"toolStyle","openai");f(this,"thrownErrorString");f(this,"tools",[]);this.sleep=r,this.responses=n,this.chunks=i,this.toolStyle=o,this.thrownErrorString=a}_llmType(){return"fake"}bindTools(r){let n=[...this.tools,...r],i=n.map(s=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:s.name,description:s.description,parameters:iu.toJsonSchema(s.schema)}};case"anthropic":return{name:s.name,description:s.description,input_schema:iu.toJsonSchema(s.schema)};case"bedrock":return{toolSpec:{name:s.name,description:s.description,inputSchema:iu.toJsonSchema(s.schema)}};case"google":return{name:s.name,description:s.description,parameters:iu.toJsonSchema(s.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),o=this.toolStyle==="google"?[{functionDeclarations:i}]:i,a=new C8({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return a.tools=n,a.withConfig({tools:o})}async _generate(r,n,i){if(this.thrownErrorString)throw new Error(this.thrownErrorString);return{generations:[{text:"",message:new nu.AIMessage({content:this.responses?.[0]?.content??r[0].content??"",tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(r,n,i){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(let s of this.chunks){let l=new GN.ChatGenerationChunk({message:new nu.AIMessageChunk({content:s.content,tool_calls:s.tool_calls,additional_kwargs:s.additional_kwargs??{}}),text:s.content?.toString()??""});if(n.signal?.aborted)break;yield l,await i?.handleLLMNewToken(s.content,void 0,void 0,void 0,void 0,{chunk:l})}return}let o=this.responses?.[0]??new nu.AIMessage(typeof r[0].content=="string"?r[0].content:""),a=typeof o.content=="string"?o.content:"";for(let s of a){await new Promise(u=>setTimeout(u,this.sleep));let l=new GN.ChatGenerationChunk({message:new nu.AIMessageChunk({content:s}),text:s});if(n.signal?.aborted)break;yield l,await i?.handleLLMNewToken(s,void 0,void 0,void 0,void 0,{chunk:l})}}},w1e=class x8 extends KN.BaseChatModel{constructor(r){super(r);f(this,"lc_serializable",!0);f(this,"responses");f(this,"i",0);f(this,"sleep");f(this,"emitCustomEvent",!1);f(this,"generationInfo");f(this,"tools",[]);f(this,"toolStyle","openai");let{responses:n,sleep:i,emitCustomEvent:o,generationInfo:a}=r;this.responses=n,this.sleep=i,this.emitCustomEvent=o??this.emitCustomEvent,this.generationInfo=a}static lc_name(){return"FakeListChatModel"}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(r,n,i){if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);if(this.emitCustomEvent&&await i?.handleCustomEvent("some_test_event",{someval:!0}),n?.stop?.length)return{generations:[this._formatGeneration(n.stop[0])]};{let o=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(o)],llmOutput:{}}}}_formatGeneration(r){return{message:new nu.AIMessage(r),text:r}}async*_streamResponseChunks(r,n,i){let o=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await i?.handleCustomEvent("some_test_event",{someval:!0});let a=[...o];for(let s=0;s<a.length;s++){let l=a[s],u=s===a.length-1;if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);let c=this._createResponseChunk(l,u?this.generationInfo:void 0);if(n.signal?.aborted)break;yield c,i?.handleLLMNewToken(l)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(r=>{setTimeout(()=>r(),this.sleep)})}_createResponseChunk(r,n){return new GN.ChatGenerationChunk({message:new nu.AIMessageChunk({content:r}),text:r,generationInfo:n})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(r){let n=[...this.tools,...r],i=n.map(s=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:s.name,description:s.description,parameters:iu.toJsonSchema(s.schema)}};case"anthropic":return{name:s.name,description:s.description,input_schema:iu.toJsonSchema(s.schema)};case"bedrock":return{toolSpec:{name:s.name,description:s.description,inputSchema:iu.toJsonSchema(s.schema)}};case"google":return{name:s.name,description:s.description,parameters:iu.toJsonSchema(s.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),o=this.toolStyle==="google"?[{functionDeclarations:i}]:i,a=new x8({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return a.tools=n,a.toolStyle=this.toolStyle,a.i=this.i,a.withConfig({tools:o})}withStructuredOutput(r,n){return _1e.RunnableLambda.from(async i=>{let o=await this.invoke(i);if(o.tool_calls?.[0]?.args)return o.tool_calls[0].args;if(typeof o.content=="string")return JSON.parse(o.content);throw new Error("No structured output found")})}};kk.FakeChatModel=b1e;kk.FakeListChatModel=w1e;kk.FakeStreamingChatModel=v1e});var R8=v(YN=>{"use strict";p();var O8=lR(),S1e=class extends O8.Embeddings{constructor(e){super(e??{});f(this,"vectorSize");this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(r=>this.embedQuery(r)))}async embedQuery(e){let r=e;r=r.toLowerCase().replaceAll(/[^a-z ]/g,"");let n=r.length%this.vectorSize,i=n===0?0:this.vectorSize-n,o=r.length+i;r=r.padEnd(o," ");let a=r.length/this.vectorSize,s=[];for(let l=0;l<r.length;l+=a)s.push(r.slice(l,l+a));return s.map(l=>{let u=0;for(let c=0;c<l.length;c+=1)u+=l===" "?0:l.charCodeAt(c);return u%26/26})}},T1e=class extends O8.Embeddings{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}};YN.FakeEmbeddings=T1e;YN.SyntheticEmbeddings=S1e});var $8=v(JN=>{"use strict";p();var N8=GR(),k1e=class extends N8.LLM{constructor(e){super(e);f(this,"response");f(this,"thrownErrorString");this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e,r,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let i=this.response??e;return await n?.handleLLMNewToken(i),i}},P1e=class extends N8.LLM{constructor(e){super(e);f(this,"sleep",50);f(this,"responses");f(this,"thrownErrorString");this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let r=this.responses?.[0];return this.responses=this.responses?.slice(1),r??e}async*_streamResponseChunks(e,r,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let i=this.responses?.[0];this.responses=this.responses?.slice(1);for(let o of i??e)await new Promise(a=>setTimeout(a,this.sleep)),yield{text:o,generationInfo:{}},await n?.handleLLMNewToken(o)}};JN.FakeLLM=k1e;JN.FakeStreamingLLM=P1e});var D8=v(Pk=>{"use strict";p();var E1e=Fr(),A1e=jo(),C1e=yo();ei();var M8=oR(),x1e=class extends M8.BaseChatMessageHistory{constructor(){super();f(this,"lc_namespace",["langchain_core","message","fake"]);f(this,"messages",[])}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new A1e.HumanMessage(e))}async addAIMessage(e){this.messages.push(new E1e.AIMessage(e))}async clear(){this.messages=[]}},I1e=class extends M8.BaseListChatMessageHistory{constructor(){super();f(this,"lc_namespace",["langchain_core","message","fake"]);f(this,"messages",[])}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},O1e=class extends C1e.BaseTracer{constructor(){super();f(this,"name","fake_tracer");f(this,"runs",[])}persistRun(e){return this.runs.push(e),Promise.resolve()}};Pk.FakeChatMessageHistory=x1e;Pk.FakeListChatMessageHistory=I1e;Pk.FakeTracer=O1e});var q8=v(U8=>{"use strict";p();var R1e=Bs(),N1e=class extends R1e.BaseOutputParser{constructor(){super(...arguments);f(this,"lc_namespace",["tests","fake"])}getFormatInstructions(){return""}async parse(e){return e.split(",").map(r=>r.trim())}};U8.FakeSplitIntoListParser=N1e});var F8=v(j8=>{"use strict";p();var L8=Rf(),$1e=KT(),M1e=class extends $1e.BaseRetriever{constructor(e){super();f(this,"lc_namespace",["test","fake"]);f(this,"output",[new L8.Document({pageContent:"foo"}),new L8.Document({pageContent:"bar"})]);this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}};j8.FakeRetriever=M1e});var z8=v(B8=>{"use strict";p();var D1e=br(),U1e=class extends D1e.Runnable{constructor(e){super(e);f(this,"lc_namespace",["tests","fake"]);f(this,"returnOptions");this.returnOptions=e.returnOptions}async invoke(e,r){return this.returnOptions?r??{}:{input:e}}};B8.FakeRunnable=U1e});var Z8=v(V8=>{"use strict";p();var q1e=MN(),L1e=class extends q1e.StructuredTool{constructor(e){super(e);f(this,"name");f(this,"description");f(this,"schema");this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,r){return JSON.stringify(e)}};V8.FakeTool=L1e});var W8=v(H8=>{"use strict";p();var j1e=yo(),F1e=class extends j1e.BaseTracer{constructor(){super();f(this,"runPromiseResolver");f(this,"runPromise");f(this,"name","single_run_extractor");this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}};H8.SingleRunExtractor=F1e});var Y8=v(K8=>{"use strict";p();var XN=Rf(),B1e=zN(),z1e=WN(),V1e=class G8 extends z1e.VectorStore{constructor(r,{similarity:n,...i}={}){super(r,i);f(this,"memoryVectors",[]);f(this,"similarity");this.similarity=n??B1e.cosine}_vectorstoreType(){return"memory"}async addDocuments(r){let n=r.map(({pageContent:i})=>i);return this.addVectors(await this.embeddings.embedDocuments(n),r)}async addVectors(r,n){let i=r.map((o,a)=>({content:n[a].pageContent,embedding:o,metadata:n[a].metadata}));this.memoryVectors=this.memoryVectors.concat(i)}async similaritySearchVectorWithScore(r,n,i){let o=s=>i?i(new XN.Document({metadata:s.metadata,pageContent:s.content})):!0,a=this.memoryVectors.filter(o);return a.map((s,l)=>({similarity:this.similarity(r,s.embedding),index:l})).sort((s,l)=>s.similarity>l.similarity?-1:0).slice(0,n).map(s=>[new XN.Document({metadata:a[s.index].metadata,pageContent:a[s.index].content}),s.similarity])}static async fromTexts(r,n,i,o){let a=[];for(let s=0;s<r.length;s+=1){let l=Array.isArray(n)?n[s]:n,u=new XN.Document({pageContent:r[s],metadata:l});a.push(u)}return G8.fromDocuments(a,i,o)}static async fromDocuments(r,n,i){let o=new this(n,i);return await o.addDocuments(r),o}static async fromExistingIndex(r,n){return new this(r,n)}};K8.FakeVectorStore=V1e});var n9=v(Dr=>{"use strict";p();Object.defineProperty(Dr,Symbol.toStringTag,{value:"Module"});var Z1e=de(),eh=I8(),Ek=R8(),Ak=$8(),th=D8(),J8=q8(),X8=F8(),Q8=z8(),e9=Z8(),t9=W8(),r9=Y8(),H1e=Z1e.__exportAll({FakeChatMessageHistory:()=>th.FakeChatMessageHistory,FakeChatModel:()=>eh.FakeChatModel,FakeEmbeddings:()=>Ek.FakeEmbeddings,FakeLLM:()=>Ak.FakeLLM,FakeListChatMessageHistory:()=>th.FakeListChatMessageHistory,FakeListChatModel:()=>eh.FakeListChatModel,FakeRetriever:()=>X8.FakeRetriever,FakeRunnable:()=>Q8.FakeRunnable,FakeSplitIntoListParser:()=>J8.FakeSplitIntoListParser,FakeStreamingChatModel:()=>eh.FakeStreamingChatModel,FakeStreamingLLM:()=>Ak.FakeStreamingLLM,FakeTool:()=>e9.FakeTool,FakeTracer:()=>th.FakeTracer,FakeVectorStore:()=>r9.FakeVectorStore,SingleRunExtractor:()=>t9.SingleRunExtractor,SyntheticEmbeddings:()=>Ek.SyntheticEmbeddings});Dr.FakeChatMessageHistory=th.FakeChatMessageHistory;Dr.FakeChatModel=eh.FakeChatModel;Dr.FakeEmbeddings=Ek.FakeEmbeddings;Dr.FakeLLM=Ak.FakeLLM;Dr.FakeListChatMessageHistory=th.FakeListChatMessageHistory;Dr.FakeListChatModel=eh.FakeListChatModel;Dr.FakeRetriever=X8.FakeRetriever;Dr.FakeRunnable=Q8.FakeRunnable;Dr.FakeSplitIntoListParser=J8.FakeSplitIntoListParser;Dr.FakeStreamingChatModel=eh.FakeStreamingChatModel;Dr.FakeStreamingLLM=Ak.FakeStreamingLLM;Dr.FakeTool=e9.FakeTool;Dr.FakeTracer=th.FakeTracer;Dr.FakeVectorStore=r9.FakeVectorStore;Dr.SingleRunExtractor=t9.SingleRunExtractor;Dr.SyntheticEmbeddings=Ek.SyntheticEmbeddings;Object.defineProperty(Dr,"testing_exports",{enumerable:!0,get:function(){return H1e}})});var o9=v(i9=>{"use strict";p();var W1e=de(),G1e=mL(),K1e=gL(),Y1e=Qv(),J1e=zu(),X1e=xi(),Q1e=_l(),eMe=wC(),tMe=Wu(),rMe=ks(),nMe=Cs(),iMe=yo(),oMe=Ux(),aMe=Zx(),sMe=Gx(),lMe=Rs(),uMe=fi(),cMe=Ri(),dMe=hI(),pMe=tc(),fMe=hf(),hMe=Sg(),mMe=Ll(),gMe=aT(),yMe=ei(),_Me=oR(),bMe=M3(),vMe=sR(),wMe=q3(),SMe=lR(),TMe=Q3(),kMe=lH(),PMe=$f(),EMe=gR(),AMe=Yg(),CMe=Bi(),xMe=Qg(),IMe=ER(),OMe=jf(),RMe=xR(),NMe=Vf(),$Me=DR(),MMe=MT(),DMe=R5(),UMe=GR(),qMe=$5(),LMe=j5(),jMe=H5(),FMe=W5(),BMe=OW(),zMe=NW(),VMe=KT(),ZMe=UW(),HMe=WW(),WMe=dG(),GMe=MN(),KMe=JG(),YMe=XG(),JMe=e8(),XMe=r8(),QMe=o8(),eDe=a8(),tDe=l8(),rDe=b8(),nDe=E8(),iDe=WN(),oDe=n9(),aDe=W1e.__exportAll({agents:()=>K1e.agents_exports,caches:()=>eMe.caches_exports,callbacks__base:()=>nMe.base_exports,callbacks__manager:()=>lMe.manager_exports,callbacks__promises:()=>sMe.promises_exports,chat_history:()=>_Me.chat_history_exports,document_loaders__base:()=>vMe.base_exports,document_loaders__langsmith:()=>wMe.langsmith_exports,documents:()=>bMe.documents_exports,embeddings:()=>SMe.embeddings_exports,errors:()=>J1e.errors_exports,example_selectors:()=>TMe.example_selectors_exports,index:()=>G1e.src_exports,indexing:()=>kMe.indexing_exports,language_models__base:()=>AMe.base_exports,language_models__chat_models:()=>MMe.chat_models_exports,language_models__compat:()=>$Me.compat_exports,language_models__event:()=>DMe.event_exports,language_models__llms:()=>UMe.llms_exports,language_models__profile:()=>qMe.profile_exports,language_models__stream:()=>NMe.stream_exports,language_models__structured_output:()=>RMe.structured_output_exports,load__serializable:()=>X1e.serializable_exports,memory:()=>LMe.memory_exports,messages:()=>yMe.messages_exports,messages__tool:()=>Q1e.tool_exports,output_parsers:()=>IMe.output_parsers_exports,output_parsers__openai_functions:()=>jMe.openai_functions_exports,output_parsers__openai_tools:()=>FMe.openai_tools_exports,outputs:()=>pMe.outputs_exports,prompt_values:()=>PMe.prompt_values_exports,prompts:()=>BMe.prompts_exports,retrievers:()=>VMe.retrievers_exports,retrievers__document_compressors:()=>zMe.document_compressors_exports,runnables:()=>CMe.runnables_exports,runnables__graph:()=>gMe.graph_exports,singletons:()=>uMe.singletons_exports,stores:()=>ZMe.stores_exports,structured_query:()=>HMe.structured_query_exports,testing:()=>WMe.testing_exports,tools:()=>GMe.tools_exports,tracers__base:()=>iMe.base_exports,tracers__console:()=>oMe.console_exports,tracers__log_stream:()=>dMe.log_stream_exports,tracers__run_collector:()=>KMe.run_collector_exports,tracers__tracer_langchain:()=>aMe.tracer_langchain_exports,types__stream:()=>YMe.stream_exports,utils__async_caller:()=>fMe.async_caller_exports,utils__chunk_array:()=>JMe.chunk_array_exports,utils__context:()=>XMe.context_exports,utils__env:()=>rMe.env_exports,utils__event_source_parse:()=>QMe.event_source_parse_exports,utils__format:()=>eDe.format_exports,utils__function_calling:()=>tDe.function_calling_exports,utils__hash:()=>Y1e.hash_exports,utils__json_patch:()=>xMe.json_patch_exports,utils__json_schema:()=>mMe.json_schema_exports,utils__math:()=>rDe.math_exports,utils__ssrf:()=>nDe.ssrf_exports,utils__standard_schema:()=>hMe.standard_schema_exports,utils__stream:()=>cMe.stream_exports,utils__testing:()=>oDe.testing_exports,utils__tiktoken:()=>EMe.tiktoken_exports,utils__types:()=>OMe.types_exports,utils__uuid:()=>tMe.uuid_exports,vectorstores:()=>iDe.vectorstores_exports});Object.defineProperty(i9,"import_map_exports",{enumerable:!0,get:function(){return aDe}})});var l9=v(QN=>{"use strict";p();Object.defineProperty(QN,Symbol.toStringTag,{value:"Module"});var a9=HA(),s9=KA(),sDe=xi(),lDe=ks(),uDe=hL(),cDe=o9(),dDe=50;function pDe(t){let e={};for(let r=t;r&&r.prototype;r=Object.getPrototypeOf(r))Object.assign(e,Reflect.get(r.prototype,"lc_aliases"));return Object.entries(e).reduce((r,[n,i])=>(r[i]=n,r),{})}async function Ck(t){let{optionalImportsMap:e,optionalImportEntrypoints:r,importMap:n,secretsMap:i,secretsFromEnv:o,path:a,depth:s,maxDepth:l}=this,u=a.join(".");if(s>l)throw new Error(`Maximum recursion depth (${l}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof t!="object"||t==null)return t;if(Array.isArray(t))return Promise.all(t.map((h,m)=>Ck.call({...this,path:[...a,`${m}`],depth:s+1},h)));let c=t;if(s9.isEscapedObject(c))return s9.unescapeValue(c);if("lc"in c&&"type"in c&&"id"in c&&c.lc===1&&c.type==="secret"){let[h]=c.id;if(h in i)return i[h];if(o){let m=lDe.getEnvironmentVariable(h);if(m)return m}throw new Error(`Missing secret "${h}" at ${u}`)}if("lc"in c&&"type"in c&&"id"in c&&c.lc===1&&c.type==="not_implemented"){let h=JSON.stringify(c);throw new Error(`Trying to load an object that doesn't implement serialization: ${u} -> ${h}`)}if("lc"in c&&"type"in c&&"id"in c&&"kwargs"in c&&c.lc===1&&c.type==="constructor"){let h=c,m=JSON.stringify(h),[g,...y]=h.id.slice().reverse(),_=y.reverse(),b={langchain_core:cDe.import_map_exports,langchain:n},w=null,T=[_.join("/")];_[0]==="langchain_community"&&T.push(["langchain",..._.slice(1)].join("/"));let E=T.find(D=>D in e);if(uDe.optionalImportEntrypoints.concat(r).includes(_.join("/"))||E)if(E!==void 0)w=await e[E];else throw new Error(`Missing key "${_.join("/")}" for ${u} in load(optionalImportsMap={})`);else{let D;if(_[0]==="langchain"||_[0]==="langchain_core")D=b[_[0]],_.shift();else throw new Error(`Invalid namespace: ${u} -> ${m}`);if(_.length===0)throw new Error(`Invalid namespace: ${u} -> ${m}`);let A;do{if(A=_.join("__"),A in D)break;_.pop()}while(_.length>0);A in D&&(w=D[A])}if(typeof w!="object"||w===null)throw new Error(`Invalid namespace: ${u} -> ${m}`);let C=w[g]??Object.values(w).find(D=>typeof D=="function"&&sDe.get_lc_unique_name(D)===g);if(typeof C!="function")throw new Error(`Invalid identifer: ${u} -> ${m}`);let R=new C(a9.mapKeys(await Ck.call({...this,path:[...a,"kwargs"],depth:s+1},h.kwargs),a9.keyFromJson,pDe(C)));return Object.defineProperty(R.constructor,"name",{value:g}),R}let d={};for(let[h,m]of Object.entries(c))d[h]=await Ck.call({...this,path:[...a,h],depth:s+1},m);return d}async function fDe(t,e){let r=JSON.parse(t),n={optionalImportsMap:e?.optionalImportsMap??{},optionalImportEntrypoints:e?.optionalImportEntrypoints??[],secretsMap:e?.secretsMap??{},secretsFromEnv:e?.secretsFromEnv??!1,importMap:e?.importMap??{},path:["$"],depth:0,maxDepth:e?.maxDepth??dDe};return Ck.call(n,r)}QN.load=fDe});var t$=v(u9=>{"use strict";p();var hDe=nL(),mDe=l9();function gDe(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function e$(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(e=>e$(e)));{let e={};for(let[r,n]of Object.entries(t))e[r]=await e$(n);if(e.lc===2&&e.type==="undefined")return;if(e.lc===2&&e.type==="constructor"&&Array.isArray(e.id))try{let r=e.id[e.id.length-1],n;switch(r){case"Set":n=Set;break;case"Map":n=Map;break;case"RegExp":n=RegExp;break;case"Error":n=Error;break;case"Uint8Array":n=Uint8Array;break;default:return e}return e.method?n[e.method](...e.args||[]):new n(...e.args||[])}catch{return e}else if(gDe(e))return(0,mDe.load)(JSON.stringify(e));return e}}return t}function xk(t,e,r,n){return{lc:2,type:"constructor",id:[t.name],method:e??null,args:r??[],kwargs:n??{}}}function yDe(t){return t===void 0?{lc:2,type:"undefined"}:t instanceof Set||t instanceof Map?xk(t.constructor,void 0,[Array.from(t)]):t instanceof RegExp?xk(RegExp,void 0,[t.source,t.flags]):t instanceof Error?xk(t.constructor,void 0,[t.message]):t?.lg_name==="Send"?{node:t.node,args:t.args}:t instanceof Uint8Array?xk(Uint8Array,"from",[Array.from(t)]):t}var _De=class{_dumps(t){return new TextEncoder().encode(hDe.stringify(t,(e,r)=>yDe(r)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){return e$(JSON.parse(t))}async loadsTyped(t,e){if(t==="bytes")return typeof e=="string"?new TextEncoder().encode(e):e;if(t==="json")return this._loads(typeof e=="string"?e:new TextDecoder().decode(e));throw new Error(`Unknown serialization type: ${t}`)}};u9.JsonPlusSerializer=_De});var n$=v(Ys=>{"use strict";p();var bDe=zA(),Ik=Zv(),vDe=t$();function r$(t){if(typeof t!="object"||t===null)return t;let e=Array.isArray(t)?[]:{};for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=r$(t[r]));return e}function wDe(){return{v:4,id:bDe.uuid6(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function SDe(t){return{v:t.v,id:t.id,ts:t.ts,channel_values:{...t.channel_values},channel_versions:{...t.channel_versions},versions_seen:r$(t.versions_seen)}}var TDe=class{constructor(t){f(this,"serde",new vDe.JsonPlusSerializer);this.serde=t||this.serde}async get(t){let e=await this.getTuple(t);return e?e.checkpoint:void 0}getNextVersion(t){if(typeof t=="string")throw new Error("Please override this method to use string versions.");return t!==void 0&&typeof t=="number"?t+1:1}};function c9(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function kDe(...t){return t.reduce((e,r,n)=>n===0?r:c9(e,r)>=0?e:r)}var PDe={[Ik.ERROR]:-1,[Ik.SCHEDULED]:-2,[Ik.INTERRUPT]:-3,[Ik.RESUME]:-4};function EDe(t){return t.configurable?.checkpoint_id||t.configurable?.thread_ts||""}Ys.BaseCheckpointSaver=TDe;Ys.WRITES_IDX_MAP=PDe;Ys.compareChannelVersions=c9;Ys.copyCheckpoint=SDe;Ys.deepCopy=r$;Ys.emptyCheckpoint=wDe;Ys.getCheckpointId=EDe;Ys.maxChannelVersion=kDe});var p9=v(d9=>{"use strict";p();var i$=Zv(),Py=n$();function Ey(t,e,r){return JSON.stringify([t,e,r])}function ADe(t){let[e,r,n]=JSON.parse(t);return{threadId:e,checkpointNamespace:r,checkpointId:n}}var CDe=class extends Py.BaseCheckpointSaver{constructor(e){super(e);f(this,"storage",{});f(this,"writes",{})}async _migratePendingSends(e,r,n,i){let o=e,a=Ey(r,n,i),s=await Promise.all(Object.values(this.writes[a]??{}).filter(([l,u])=>u===i$.TASKS).map(async([l,u,c])=>await this.serde.loadsTyped("json",c)));o.channel_values??(o.channel_values={}),o.channel_values[i$.TASKS]=s,o.channel_versions??(o.channel_versions={}),o.channel_versions[i$.TASKS]=Object.keys(o.channel_versions).length>0?Py.maxChannelVersion(...Object.values(o.channel_versions)):this.getNextVersion(void 0)}async getTuple(e){let r=e.configurable?.thread_id,n=e.configurable?.checkpoint_ns??"",i=Py.getCheckpointId(e);if(i){let o=this.storage[r]?.[n]?.[i];if(o!==void 0){let[a,s,l]=o,u=Ey(r,n,i),c=await this.serde.loadsTyped("json",a);c.v<4&&l!==void 0&&await this._migratePendingSends(c,r,n,l);let d=await Promise.all(Object.values(this.writes[u]||{}).map(async([m,g,y])=>[m,g,await this.serde.loadsTyped("json",y)])),h={config:e,checkpoint:c,metadata:await this.serde.loadsTyped("json",s),pendingWrites:d};return l!==void 0&&(h.parentConfig={configurable:{thread_id:r,checkpoint_ns:n,checkpoint_id:l}}),h}}else{let o=this.storage[r]?.[n];if(o!==void 0){i=Object.keys(o).sort((m,g)=>g.localeCompare(m))[0];let[a,s,l]=o[i],u=Ey(r,n,i),c=await this.serde.loadsTyped("json",a);c.v<4&&l!==void 0&&await this._migratePendingSends(c,r,n,l);let d=await Promise.all(Object.values(this.writes[u]||{}).map(async([m,g,y])=>[m,g,await this.serde.loadsTyped("json",y)])),h={config:{configurable:{thread_id:r,checkpoint_id:i,checkpoint_ns:n}},checkpoint:c,metadata:await this.serde.loadsTyped("json",s),pendingWrites:d};return l!==void 0&&(h.parentConfig={configurable:{thread_id:r,checkpoint_ns:n,checkpoint_id:l}}),h}}}async*list(e,r){let{before:n,limit:i,filter:o}=r??{},a=e.configurable?.thread_id?[e.configurable?.thread_id]:Object.keys(this.storage),s=e.configurable?.checkpoint_ns,l=e.configurable?.checkpoint_id;for(let u of a)for(let c of Object.keys(this.storage[u]??{})){if(s!==void 0&&c!==s)continue;let d=this.storage[u]?.[c]??{},h=Object.entries(d).sort((m,g)=>g[0].localeCompare(m[0]));for(let[m,[g,y,_]]of h){if(l&&m!==l||n&&n.configurable?.checkpoint_id&&m>=n.configurable.checkpoint_id)continue;let b=await this.serde.loadsTyped("json",y);if(o&&!Object.entries(o).every(([D,A])=>b[D]===A))continue;if(i!==void 0){if(i<=0)break;i-=1}let w=Ey(u,c,m),T=Object.values(this.writes[w]||{}),E=await Promise.all(T.map(async([D,A,U])=>[D,A,await this.serde.loadsTyped("json",U)])),C=await this.serde.loadsTyped("json",g);C.v<4&&_!==void 0&&await this._migratePendingSends(C,u,c,_);let R={config:{configurable:{thread_id:u,checkpoint_ns:c,checkpoint_id:m}},checkpoint:C,metadata:b,pendingWrites:E};_!==void 0&&(R.parentConfig={configurable:{thread_id:u,checkpoint_ns:c,checkpoint_id:_}}),yield R}}}async put(e,r,n){let i=Py.copyCheckpoint(r),o=e.configurable?.thread_id,a=e.configurable?.checkpoint_ns??"";if(o===void 0)throw new Error('Failed to put checkpoint. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property. When using a checkpointer, you must pass a "thread_id" so the checkpointer knows which conversation thread to persist state for. Example: graph.stream(input, { configurable: { thread_id: "my-thread-id" } })');this.storage[o]||(this.storage[o]={}),this.storage[o][a]||(this.storage[o][a]={});let[[,s],[,l]]=await Promise.all([this.serde.dumpsTyped(i),this.serde.dumpsTyped(n)]);return this.storage[o][a][r.id]=[s,l,e.configurable?.checkpoint_id],{configurable:{thread_id:o,checkpoint_ns:a,checkpoint_id:r.id}}}async putWrites(e,r,n){let i=e.configurable?.thread_id,o=e.configurable?.checkpoint_ns,a=e.configurable?.checkpoint_id;if(i===void 0)throw new Error('Failed to put writes. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property. When using a checkpointer, you must pass a "thread_id" so the checkpointer knows which conversation thread to persist state for. Example: graph.stream(input, { configurable: { thread_id: "my-thread-id" } })');if(a===void 0)throw new Error('Failed to put writes. The passed RunnableConfig is missing a required "checkpoint_id" field in its "configurable" property.');let s=Ey(i,o,a),l=this.writes[s];this.writes[s]===void 0&&(this.writes[s]={}),await Promise.all(r.map(async([u,c],d)=>{let[,h]=await this.serde.dumpsTyped(c),m=[n,Py.WRITES_IDX_MAP[u]||d],g=`${m[0]},${m[1]}`;m[1]>=0&&l&&g in l||(this.writes[s][g]=[n,u,h])}))}async deleteThread(e){delete this.storage[e];for(let r of Object.keys(this.writes))ADe(r).threadId===e&&delete this.writes[r]}};d9.MemorySaver=CDe});var Ok=v(Ay=>{"use strict";p();var rh=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function xDe(t){if(t.length===0)throw new rh("Namespace cannot be empty.");for(let e of t){if(typeof e!="string")throw new rh(`Invalid namespace label '${e}' found in ${t}. Namespace labels must be strings, but got ${typeof e}.`);if(e.includes("."))throw new rh(`Invalid namespace label '${e}' found in ${t}. Namespace labels cannot contain periods ('.').`);if(e==="")throw new rh(`Namespace labels cannot be empty strings. Got ${e} in ${t}`)}if(t[0]==="langgraph")throw new rh(`Root label for namespace cannot be "langgraph". Got: ${t}`)}function IDe(t,e){let r=e.split("."),n=t;for(let i of r){if(i.includes("[")){let[o,a]=i.split("["),s=a.replace("]","");if(!n[o])return[];if(s==="*"){let u=[];for(let c of n[o])typeof c=="string"&&u.push(c);return u}let l=parseInt(s,10);if(Number.isNaN(l))return[];n=n[o][l]}else n=n[i];if(n===void 0)return[]}return typeof n=="string"?[n]:[]}function ODe(t){return t.split(".")}var RDe=class{async get(t,e){return(await this.batch([{namespace:t,key:e}]))[0]}async search(t,e={}){let{filter:r,limit:n=10,offset:i=0,query:o}=e;return(await this.batch([{namespacePrefix:t,filter:r,limit:n,offset:i,query:o}]))[0]}async put(t,e,r,n){xDe(t),await this.batch([{namespace:t,key:e,value:r,index:n}])}async delete(t,e){await this.batch([{namespace:t,key:e,value:null}])}async listNamespaces(t={}){let{prefix:e,suffix:r,maxDepth:n,limit:i=100,offset:o=0}=t,a=[];return e&&a.push({matchType:"prefix",path:e}),r&&a.push({matchType:"suffix",path:r}),(await this.batch([{matchConditions:a.length?a:void 0,maxDepth:n,limit:i,offset:o}]))[0]}start(){}stop(){}};Ay.BaseStore=RDe;Ay.InvalidNamespaceError=rh;Ay.getTextAtPath=IDe;Ay.tokenizePath=ODe});var h9=v(f9=>{"use strict";p();var NDe=Ok(),$De=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t,MDe=class extends NDe.BaseStore{constructor(e){super();f(this,"lg_name","AsyncBatchedStore");f(this,"store");f(this,"queue",new Map);f(this,"nextKey",0);f(this,"running",!1);f(this,"processingTask",null);this.store=$De(e)}get isRunning(){return this.running}async batch(e){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,r){return this.enqueueOperation({namespace:e,key:r})}async search(e,r){let{filter:n,limit:i=10,offset:o=0,query:a}=r||{};return this.enqueueOperation({namespacePrefix:e,filter:n,limit:i,offset:o,query:a})}async put(e,r,n){return this.enqueueOperation({namespace:e,key:r,value:n})}async delete(e,r){return this.enqueueOperation({namespace:e,key:r,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((r,n)=>{let i=this.nextKey;this.nextKey+=1,this.queue.set(i,{operation:e,resolve:r,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(r=>{setTimeout(r,0)}),this.queue.size===0)continue;let e=new Map(this.queue);this.queue.clear();try{let r=Array.from(e.values()).map(({operation:i})=>i),n=await this.store.batch(r);e.forEach(({resolve:i},o)=>{i(n[Array.from(e.keys()).indexOf(o)])})}catch(r){e.forEach(({reject:n})=>{n(r)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}};f9.AsyncBatchedStore=MDe});var m9=v(Rk=>{"use strict";p();function o$(t){if(!t)return[];let e=[],r=[],n=0;for(;n<t.length;){let i=t[n];if(i==="["){r.length&&(e.push(r.join("")),r=[]);let o=1,a=["["];for(n+=1;n<t.length&&o>0;)t[n]==="["?o+=1:t[n]==="]"&&(o-=1),a.push(t[n]),n+=1;e.push(a.join(""));continue}else if(i==="{"){r.length&&(e.push(r.join("")),r=[]);let o=1,a=["{"];for(n+=1;n<t.length&&o>0;)t[n]==="{"?o+=1:t[n]==="}"&&(o-=1),a.push(t[n]),n+=1;e.push(a.join(""));continue}else i==="."?r.length&&(e.push(r.join("")),r=[]):r.push(i);n+=1}return r.length&&e.push(r.join("")),e}function DDe(t){return typeof t=="object"&&t!==null&&Object.keys(t).every(e=>e==="$eq"||e==="$ne"||e==="$gt"||e==="$gte"||e==="$lt"||e==="$lte"||e==="$in"||e==="$nin")}function UDe(t,e){return DDe(e)?Object.keys(e).filter(r=>r.startsWith("$")).every(r=>{let n=e[r];switch(r){case"$eq":return t===n;case"$ne":return t!==n;case"$gt":return Number(t)>Number(n);case"$gte":return Number(t)>=Number(n);case"$lt":return Number(t)<Number(n);case"$lte":return Number(t)<=Number(n);case"$in":return Array.isArray(n)?n.includes(t):!1;case"$nin":return Array.isArray(n)?!n.includes(t):!0;default:return!1}}):t===e}function qDe(t,e){if(!e||e==="$")return[JSON.stringify(t,null,2)];let r=Array.isArray(e)?e:o$(e);function n(i,o,a){if(a>=o.length)return typeof i=="string"||typeof i=="number"||typeof i=="boolean"?[String(i)]:i==null?[]:Array.isArray(i)||typeof i=="object"?[JSON.stringify(i,null,2)]:[];let s=o[a],l=[];if(a===0&&s==="$"&&l.push(JSON.stringify(i,null,2)),s.startsWith("[")&&s.endsWith("]")){if(!Array.isArray(i))return[];let u=s.slice(1,-1);if(u==="*")for(let c of i)l.push(...n(c,o,a+1));else try{let c=parseInt(u,10);c<0&&(c=i.length+c),c>=0&&c<i.length&&l.push(...n(i[c],o,a+1))}catch{return[]}}else if(s.startsWith("{")&&s.endsWith("}")){if(typeof i!="object"||i===null)return[];let u=s.slice(1,-1).split(",").map(c=>c.trim());for(let c of u){let d=o$(c);if(d.length){let h=i;for(let m of d)if(h&&typeof h=="object"&&m in h)h=h[m];else{h=void 0;break}h!==void 0&&(typeof h=="string"||typeof h=="number"||typeof h=="boolean"?l.push(String(h)):(Array.isArray(h)||typeof h=="object")&&l.push(JSON.stringify(h,null,2)))}}}else if(s==="*"){if(Array.isArray(i))for(let u of i)l.push(...n(u,o,a+1));else if(typeof i=="object"&&i!==null)for(let u of Object.values(i))l.push(...n(u,o,a+1))}else typeof i=="object"&&i!==null&&s in i&&l.push(...n(i[s],o,a+1));return l}return n(t,r,0)}Rk.compareValues=UDe;Rk.getTextAtPath=qDe;Rk.tokenizePath=o$});var y9=v(a$=>{"use strict";p();var LDe=Ok(),Nk=m9(),g9=class extends LDe.BaseStore{constructor(e){super();f(this,"data",new Map);f(this,"vectors",new Map);f(this,"_indexConfig");e?.index&&(this._indexConfig={...e.index,__tokenizedFields:(e.index.fields??["$"]).map(r=>[r,r==="$"?[r]:Nk.tokenizePath(r)])})}async batch(e){let r=[],n=new Map,i=new Map;for(let o=0;o<e.length;o+=1){let a=e[o];if("key"in a&&"namespace"in a&&!("value"in a))r.push(this.getOperation(a));else if("namespacePrefix"in a){let s=this.filterItems(a);i.set(o,[a,s]),r.push(null)}else if("value"in a){let s=`${a.namespace.join(":")}:${a.key}`;n.set(s,a),r.push(null)}else"matchConditions"in a&&r.push(this.listNamespacesOperation(a))}if(i.size>0)if(this._indexConfig?.embeddings){let o=new Set;for(let[l]of i.values())l.query&&o.add(l.query);let a=o.size>0?await Promise.all(Array.from(o).map(l=>this._indexConfig.embeddings.embedQuery(l))):[],s=Object.fromEntries(Array.from(o).map((l,u)=>[l,a[u]]));for(let[l,[u,c]]of i.entries())if(u.query&&s[u.query]){let d=s[u.query];r[l]=this.scoreResults(c,d,u.offset??0,u.limit??10)}else r[l]=this.paginateResults(c.map(d=>({...d,score:void 0})),u.offset??0,u.limit??10)}else for(let[o,[a,s]]of i.entries())r[o]=this.paginateResults(s.map(l=>({...l,score:void 0})),a.offset??0,a.limit??10);if(n.size>0&&this._indexConfig?.embeddings){let o=this.extractTexts(Array.from(n.values()));if(Object.keys(o).length>0){let a=await this._indexConfig.embeddings.embedDocuments(Object.keys(o));this.insertVectors(o,a)}}for(let o of n.values())this.putOperation(o);return r}getOperation(e){let r=e.namespace.join(":");return this.data.get(r)?.get(e.key)??null}putOperation(e){let r=e.namespace.join(":");this.data.has(r)||this.data.set(r,new Map);let n=this.data.get(r);if(e.value===null)n.delete(e.key);else{let i=new Date;if(n.has(e.key)){let o=n.get(e.key);o.value=e.value,o.updatedAt=i}else n.set(e.key,{value:e.value,key:e.key,namespace:e.namespace,createdAt:i,updatedAt:i})}}listNamespacesOperation(e){let r=Array.from(this.data.keys()).map(n=>n.split(":"));return e.matchConditions&&e.matchConditions.length>0&&(r=r.filter(n=>e.matchConditions.every(i=>this.doesMatch(i,n)))),e.maxDepth!==void 0&&(r=Array.from(new Set(r.map(n=>n.slice(0,e.maxDepth).join(":")))).map(n=>n.split(":"))),r.sort((n,i)=>n.join(":").localeCompare(i.join(":"))),r.slice(e.offset??0,(e.offset??0)+(e.limit??r.length))}doesMatch(e,r){let{matchType:n,path:i}=e;if(n==="prefix")return i.length>r.length?!1:i.every((o,a)=>{let s=r[a];return o==="*"||s===o});if(n==="suffix")return i.length>r.length?!1:i.every((o,a)=>{let s=r[r.length-i.length+a];return o==="*"||s===o});throw new Error(`Unsupported match type: ${n}`)}filterItems(e){let r=[];for(let[i,o]of this.data.entries())i.startsWith(e.namespacePrefix.join(":"))&&r.push(...o.values());let n=r;return e.filter&&(n=r.filter(i=>Object.entries(e.filter).every(([o,a])=>Nk.compareValues(i.value[o],a)))),n}scoreResults(e,r,n=0,i=10){let o=[],a=[],s=[];for(let d of e){let h=this.getVectors(d);if(h.length)for(let m of h)o.push(d),a.push(m);else s.push(d)}let l=this.cosineSimilarity(r,a).map((d,h)=>[d,o[h]]).sort((d,h)=>h[0]-d[0]),u=new Set,c=[];for(let[d,h]of l){let m=`${h.namespace.join(":")}:${h.key}`;if(u.has(m))continue;let g=u.size;if(g>=n+i)break;if(g<n){u.add(m);continue}u.add(m),c.push([d,h])}if(s.length&&c.length<i)for(let d of s.slice(0,i-c.length)){let h=`${d.namespace.join(":")}:${d.key}`;u.has(h)||(u.add(h),c.push([void 0,d]))}return c.map(([d,h])=>({...h,score:d}))}paginateResults(e,r,n){return e.slice(r,r+n)}extractTexts(e){if(!e.length||!this._indexConfig)return{};let r={};for(let n of e)if(n.value!==null&&n.index!==!1){let i=n.index===null||n.index===void 0?this._indexConfig.__tokenizedFields??[]:n.index.map(o=>[o,Nk.tokenizePath(o)]);for(let[o,a]of i){let s=Nk.getTextAtPath(n.value,a);s.length&&(s.length>1?s.forEach((l,u)=>{r[l]||(r[l]=[]),r[l].push([n.namespace,n.key,`${o}.${u}`])}):(r[s[0]]||(r[s[0]]=[]),r[s[0]].push([n.namespace,n.key,o])))}}return r}insertVectors(e,r){for(let[n,i]of Object.entries(e)){let o=r.shift();if(!o)throw new Error(`No embedding found for text: ${n}`);for(let[a,s,l]of i){let u=a.join(":");this.vectors.has(u)||this.vectors.set(u,new Map);let c=this.vectors.get(u);c.has(s)||c.set(s,new Map),c.get(s).set(l,o)}}}getVectors(e){let r=e.namespace.join(":"),n=e.key;if(!this.vectors.has(r))return[];let i=this.vectors.get(r);if(!i.has(n))return[];let o=i.get(n),a=Array.from(o.values());return a.length?a:[]}cosineSimilarity(e,r){if(!r.length)return[];let n=r.map(a=>a.reduce((s,l,u)=>s+l*e[u],0)),i=Math.sqrt(e.reduce((a,s)=>a+s*s,0)),o=r.map(a=>Math.sqrt(a.reduce((s,l)=>s+l*l,0)));return n.map((a,s)=>{let l=o[s];return i&&l?a/(i*l):0})}get indexConfig(){return this._indexConfig}},jDe=class extends g9{};a$.InMemoryStore=g9;a$.MemoryStore=jDe});var $k=v(_9=>{"use strict";p();var FDe=t$(),BDe=class{constructor(t){f(this,"serde",new FDe.JsonPlusSerializer);this.serde=t||this.serde}};_9.BaseCache=BDe});var s$=v(b9=>{"use strict";p();var zDe=$k(),VDe=class extends zDe.BaseCache{constructor(){super(...arguments);f(this,"cache",{})}async get(e){if(!e.length)return[];let r=Date.now();return(await Promise.all(e.map(async n=>{let[i,o]=n,a=i.join(",");if(a in this.cache&&o in this.cache[a]){let s=this.cache[a][o];if(s.exp==null||r<s.exp)return[{key:n,value:await this.serde.loadsTyped(s.enc,s.val)}];delete this.cache[a][o]}return[]}))).flat()}async set(e){var n;let r=Date.now();for(let{key:i,value:o,ttl:a}of e){let[s,l]=i,u=s.join(","),[c,d]=await this.serde.dumpsTyped(o),h=a!=null?a*1e3+r:null;(n=this.cache)[u]??(n[u]={}),this.cache[u][l]={enc:c,val:d,exp:h}}}async clear(e){if(!e.length){this.cache={};return}for(let r of e){let n=r.join(",");n in this.cache&&delete this.cache[n]}}};b9.InMemoryCache=VDe});var v9=v(()=>{"use strict";p();$k();s$()});var nh=v(Bt=>{"use strict";p();Object.defineProperty(Bt,Symbol.toStringTag,{value:"Module"});var w9=zA(),Cy=Zv(),ou=n$(),ZDe=p9(),Mk=Ok(),HDe=h9(),S9=y9(),WDe=$k(),GDe=s$();v9();Bt.AsyncBatchedStore=HDe.AsyncBatchedStore;Bt.BaseCache=WDe.BaseCache;Bt.BaseCheckpointSaver=ou.BaseCheckpointSaver;Bt.BaseStore=Mk.BaseStore;Bt.ERROR=Cy.ERROR;Bt.INTERRUPT=Cy.INTERRUPT;Bt.InMemoryCache=GDe.InMemoryCache;Bt.InMemoryStore=S9.InMemoryStore;Bt.InvalidNamespaceError=Mk.InvalidNamespaceError;Bt.MemorySaver=ZDe.MemorySaver;Bt.MemoryStore=S9.MemoryStore;Bt.RESUME=Cy.RESUME;Bt.SCHEDULED=Cy.SCHEDULED;Bt.TASKS=Cy.TASKS;Bt.WRITES_IDX_MAP=ou.WRITES_IDX_MAP;Bt.compareChannelVersions=ou.compareChannelVersions;Bt.copyCheckpoint=ou.copyCheckpoint;Bt.deepCopy=ou.deepCopy;Bt.emptyCheckpoint=ou.emptyCheckpoint;Bt.getCheckpointId=ou.getCheckpointId;Bt.getTextAtPath=Mk.getTextAtPath;Bt.maxChannelVersion=ou.maxChannelVersion;Bt.tokenizePath=Mk.tokenizePath;Bt.uuid5=w9.uuid5;Bt.uuid6=w9.uuid6});var $n=v(ih=>{"use strict";p();var T9=gr(),KDe=nh();function k9(t){return t!=null&&t.lg_is_channel===!0}var YDe=class{constructor(){f(this,"ValueType");f(this,"UpdateType");f(this,"lg_is_channel",!0)}consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(t){if(t.name===T9.EmptyChannelError.unminifiable_name)return!1;throw t}}equals(t){return this===t}},l$=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function P9(t){if(t[l$]===!0)return t;let e={};for(let r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;let n=t[r];k9(n)&&(e[r]=n)}return Object.assign(e,{[l$]:!0}),e}function JDe(t,e){let r=P9(t),n={};for(let i in r){if(!Object.prototype.hasOwnProperty.call(r,i))continue;let o=e.channel_values[i];n[i]=r[i].fromCheckpoint(o)}return Object.assign(n,{[l$]:!0}),n}function XDe(t,e,r,n){let i;if(e===void 0)i=t.channel_values;else{i={};for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o))try{i[o]=e[o].checkpoint()}catch(a){if(a.name!==T9.EmptyChannelError.unminifiable_name)throw a}}return{v:4,id:n?.id??(0,KDe.uuid6)(r),ts:new Date().toISOString(),channel_values:i,channel_versions:t.channel_versions,versions_seen:t.versions_seen}}ih.BaseChannel=YDe;ih.createCheckpoint=XDe;ih.emptyChannels=JDe;ih.getOnlyChannels=P9;ih.isBaseChannel=k9});var oh=v(A9=>{"use strict";p();var u$=Zt(),c$=gr(),QDe=$n(),eUe=t=>t!=null&&t.lc_graph_name==="BinaryOperatorAggregate",tUe=class E9 extends QDe.BaseChannel{constructor(r,n){super();f(this,"lc_graph_name","BinaryOperatorAggregate");f(this,"value");f(this,"operator");f(this,"initialValueFactory");this.operator=r,this.initialValueFactory=n,this.value=n?.()}fromCheckpoint(r){let n=new E9(this.operator,this.initialValueFactory);return typeof r<"u"&&(n.value=r),n}update(r){let n=r;if(!n.length)return!1;if(this.value===void 0){let o=n[0],[a,s]=u$._getOverwriteValue(o);a?this.value=s:this.value=o,n=n.slice(1)}let i=!1;for(let o of n)if(u$._isOverwriteValue(o)){if(i)throw new c$.InvalidUpdateError("Can receive only one Overwrite value per step.");let[,a]=u$._getOverwriteValue(o);this.value=a,i=!0;continue}else!i&&this.value!==void 0&&(this.value=this.operator(this.value,o));return!0}get(){if(this.value===void 0)throw new c$.EmptyChannelError;return this.value}checkpoint(){if(this.value===void 0)throw new c$.EmptyChannelError;return this.value}isAvailable(){return this.value!==void 0}equals(r){return this===r?!0:eUe(r)?this.operator===r.operator:!1}};A9.BinaryOperatorAggregate=tUe});var xc=v(d$=>{"use strict";p();var Dk=gr(),C9=$n(),rUe=class x9 extends C9.BaseChannel{constructor(r){super();f(this,"lc_graph_name","LastValue");f(this,"value",[]);this.initialValueFactory=r,r&&(this.value=[r()])}fromCheckpoint(r){let n=new x9(this.initialValueFactory);return typeof r<"u"&&(n.value=[r]),n}update(r){if(r.length===0)return!1;if(r.length!==1)throw new Dk.InvalidUpdateError("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[r[r.length-1]],!0}get(){if(this.value.length===0)throw new Dk.EmptyChannelError;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Dk.EmptyChannelError;return this.value[0]}isAvailable(){return this.value.length!==0}},nUe=class I9 extends C9.BaseChannel{constructor(){super(...arguments);f(this,"lc_graph_name","LastValueAfterFinish");f(this,"value",[]);f(this,"finished",!1)}fromCheckpoint(r){let n=new I9;if(typeof r<"u"){let[i,o]=r;n.value=[i],n.finished=o}return n}update(r){return r.length===0?!1:(this.finished=!1,this.value=[r[r.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new Dk.EmptyChannelError;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}};d$.LastValue=rUe;d$.LastValueAfterFinish=nUe});var xy=v(Uk=>{"use strict";p();var O9=oh(),R9=xc(),N9=class{constructor(t){f(this,"lc_graph_name","AnnotationRoot");f(this,"spec");this.spec=t}static isInstance(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}},$9=function(t){return t?M9(t):new R9.LastValue};$9.Root=t=>new N9(t);function M9(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new O9.BinaryOperatorAggregate(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new O9.BinaryOperatorAggregate(t.value,t.default):new R9.LastValue}Uk.Annotation=$9;Uk.AnnotationRoot=N9;Uk.getChannel=M9});var ah=v(Js=>{"use strict";p();var iUe=Zt(),Iy=fi(),oUe=["tags","metadata","callbacks","configurable"],aUe=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal","executionInfo","serverInfo"],sUe=25,lUe=new Set(["thread_id","checkpoint_id","checkpoint_ns","task_id","run_id","assistant_id","graph_id"]);function D9(t,e){if(!t)return e;let r=e??{};for(let n of lUe){if(n in r)continue;let i=t[n];i!==void 0&&(r[n]=i)}return r}function uUe(...t){let e={tags:[],metadata:{},callbacks:void 0,recursionLimit:sUe,configurable:{}},r=Iy.AsyncLocalStorageProviderSingleton.getRunnableConfig();if(r!==void 0){for(let[n,i]of Object.entries(r))if(i!==void 0)if(oUe.includes(n)){let o;Array.isArray(i)?o=[...i]:typeof i=="object"?n==="callbacks"&&"copy"in i&&typeof i.copy=="function"?o=i.copy():o={...i}:o=i,e[n]=o}else e[n]=i}for(let n of t)if(n!==void 0)for(let[i,o]of Object.entries(n))o!==void 0&&aUe.includes(i)&&(e[i]=o);return e.metadata=D9(e.configurable,e.metadata)??{},e}function cUe(t){let e=t??Iy.AsyncLocalStorageProviderSingleton.getRunnableConfig();if(e===void 0)throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.","If you're running `getStore` in such environment, pass the `config` from the node function directly."].join(`
409
+ `+d:d;break;case"event":n.event=d;break;case"id":e?.(n.id=d);break;case"retry":{let h=parseInt(d,10);Number.isNaN(h)||r?.(n.retry=h);break}}}}}function V$e(t,e){let r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}function UN(){return{data:"",event:"",id:"",retry:void 0}}function iG(t,e){let r=new ReadableStream({async start(n){let i=jN(a=>{if(a.event==="error")throw new Error(a.data??"Unspecified event streaming error.");a.event==="metadata"?e?.(a):a.data&&n.enqueue(a.data)});await qN(t,LN((a,s,l)=>{i(a,s,l),l&&n.close()}))}});return B$e.IterableReadableStream.fromReadableStream(r)}function Z$e(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}ru.EventStreamContentType=nG;ru.convertEventStreamToIterableReadableDataStream=iG;Object.defineProperty(ru,"event_source_parse_exports",{enumerable:!0,get:function(){return z$e}});ru.getBytes=qN;ru.getLines=LN;ru.getMessages=jN});var aG=v(FN=>{"use strict";p();Object.defineProperty(FN,Symbol.toStringTag,{value:"Module"});var H$e=de().__exportAll({});Object.defineProperty(FN,"format_exports",{enumerable:!0,get:function(){return H$e}})});var lG=v(Ws=>{"use strict";p();Object.defineProperty(Ws,Symbol.toStringTag,{value:"Module"});var W$e=de(),G$e=Ll(),Hs=yN(),K$e=W$e.__exportAll({convertToOpenAIFunction:()=>BN,convertToOpenAITool:()=>sG,isLangChainTool:()=>Hs.isLangChainTool,isRunnableToolLike:()=>Hs.isRunnableToolLike,isStructuredTool:()=>Hs.isStructuredTool,isStructuredToolParams:()=>Hs.isStructuredToolParams});function BN(t,e){let r=typeof e=="number"?void 0:e;return{name:t.name,description:t.description,parameters:G$e.toJsonSchema(t.schema),...r?.strict!==void 0?{strict:r.strict}:{}}}function sG(t,e){let r=typeof e=="number"?void 0:e,n;return Hs.isLangChainTool(t)?n={type:"function",function:BN(t)}:n=t,r?.strict!==void 0&&(n.function.strict=r.strict),n}Ws.convertToOpenAIFunction=BN;Ws.convertToOpenAITool=sG;Object.defineProperty(Ws,"function_calling_exports",{enumerable:!0,get:function(){return K$e}});Ws.isLangChainTool=Hs.isLangChainTool;Ws.isRunnableToolLike=Hs.isRunnableToolLike;Ws.isStructuredTool=Hs.isStructuredTool;Ws.isStructuredToolParams=Hs.isStructuredToolParams});var zN=v(uG=>{"use strict";p();function Y$e(t,e){let r=0,n=0,i=0;for(let o=0;o<t.length;o++)r+=t[o]*e[o],n+=t[o]*t[o],i+=e[o]*e[o];return r/(Math.sqrt(n)*Math.sqrt(i))}uG.cosine=Y$e});var dG=v(cG=>{"use strict";p();function J$e(t,e){let r=0;for(let n=0;n<t.length;n++)r+=t[n]*e[n];return r}cG.innerProduct=J$e});var fG=v(pG=>{"use strict";p();function X$e(t,e){let r=0;for(let n=0;n<t.length;n++)r+=(t[n]-e[n])*(t[n]-e[n]);return r}function Q$e(t,e){return Math.sqrt(X$e(t,e))}pG.euclidean=Q$e});var bG=v(Gs=>{"use strict";p();Object.defineProperty(Gs,Symbol.toStringTag,{value:"Module"});var e1e=de(),t1e=zN(),r1e=dG(),n1e=fG(),i1e=e1e.__exportAll({cosineSimilarity:()=>vk,euclideanDistance:()=>gG,innerProduct:()=>mG,matrixFunc:()=>Ty,maximalMarginalRelevance:()=>yG,normalize:()=>hG});function Ty(t,e,r){if(t.length===0||t[0].length===0||e.length===0||e[0].length===0)return[[]];if(t[0].length!==e[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[t.length,t[0].length]} and Y has shape ${[e.length,e[0].length]}.`);return t.map(n=>e.map(i=>r(n,i)).map(i=>Number.isNaN(i)?0:i))}function hG(t,e=!1){let r=o1e(t);return t.map(n=>n.map(i=>e?1-i/r:i/r))}function vk(t,e){return Ty(t,e,t1e.cosine)}function mG(t,e){return Ty(t,e,r1e.innerProduct)}function gG(t,e){return Ty(t,e,n1e.euclidean)}function yG(t,e,r=.5,n=4){if(Math.min(n,e.length)<=0)return[];let i=vk(Array.isArray(t[0])?t:[t],e)[0],o=_G(i).maxIndex,a=[e[o]],s=[o];for(;s.length<Math.min(n,e.length);){let l=-1/0,u=-1,c=vk(e,a);i.forEach((d,h)=>{if(s.includes(h))return;let m=Math.max(...c[h]),g=r*d-(1-r)*m;g>l&&(l=g,u=h)}),a.push(e[u]),s.push(u)}return s}function _G(t){if(t.length===0)return{maxIndex:-1,maxValue:NaN};let e=t[0],r=0;for(let n=1;n<t.length;n+=1)t[n]>e&&(r=n,e=t[n]);return{maxIndex:r,maxValue:e}}function o1e(t){return t.reduce((e,r)=>Math.max(e,_G(r).maxValue),0)}Gs.cosineSimilarity=vk;Gs.euclideanDistance=gG;Gs.innerProduct=mG;Object.defineProperty(Gs,"math_exports",{enumerable:!0,get:function(){return i1e}});Gs.matrixFunc=Ty;Gs.maximalMarginalRelevance=yG;Gs.normalize=hG});var EG=v(Ks=>{"use strict";p();Object.defineProperty(Ks,Symbol.toStringTag,{value:"Module"});var a1e=de().__exportAll({isCloudMetadata:()=>wk,isLocalhost:()=>Sk,isPrivateIp:()=>VN,isSafeUrl:()=>kG,isSameOrigin:()=>PG,validateSafeUrl:()=>ZN}),s1e=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","127.0.0.0/8","169.254.0.0/16","0.0.0.0/8","::1/128","fc00::/7","fe80::/10","ff00::/8"],l1e=["169.254.169.254","169.254.170.2","100.100.100.200"],u1e=["metadata.google.internal","metadata","instance-data"],c1e=["localhost","localhost.localdomain"],d1e=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function vG(t){return d1e.test(t)}function Tk(t){return TG(t)!==null}function wG(t){return vG(t)||Tk(t)}function SG(t){if(vG(t))return t.split(".").map(e=>parseInt(e,10));if(Tk(t)){let e=TG(t);if(!e)return null;let r=e.split(":"),n=[];for(let i of r)n.push(parseInt(i,16));return n}return null}function TG(t){if(!t||typeof t!="string"||!t.includes(":")||!/^[0-9a-fA-F:]+$/.test(t))return null;let e=t;if(e.includes("::")){let n=e.split("::");if(n.length>2)return null;let[i,o]=n,a=i?i.split(":"):[],s=o?o.split(":"):[],l=8-(a.length+s.length);if(l<0)return null;let u=Array(l).fill("0");e=[...a,...u,...s].filter(c=>c!=="").join(":")}let r=e.split(":");if(r.length!==8)return null;for(let n of r)if(n.length===0||n.length>4||!/^[0-9a-fA-F]+$/.test(n))return null;return r.map(n=>n.padStart(4,"0").toLowerCase()).join(":")}function p1e(t){let[e,r]=t.split("/");if(!e||!r)return null;let n=SG(e);if(!n)return null;let i=parseInt(r,10);if(isNaN(i))return null;let o=Tk(e);return o&&i>128||!o&&i>32?null:{addr:n,prefixLen:i,isIpv6:o}}function f1e(t,e){let r=SG(t);if(!r)return!1;let n=p1e(e);if(!n)return!1;let i=Tk(t);if(i!==n.isIpv6)return!1;let{addr:o,prefixLen:a}=n;if(i)for(let s=0;s<Math.ceil(a/16);s++){let l=65535<<16-Math.min(16,a-s*16)&65535;if((r[s]&l)!==(o[s]&l))return!1}else for(let s=0;s<Math.ceil(a/8);s++){let l=255<<8-Math.min(8,a-s*8)&255;if((r[s]&l)!==(o[s]&l))return!1}return!0}function VN(t){if(!wG(t))return!1;for(let e of s1e)if(f1e(t,e))return!0;return!1}function wk(t,e){if(l1e.includes(e||""))return!0;let r=t.toLowerCase();return!!u1e.includes(r)}function Sk(t,e){if(e&&(e==="127.0.0.1"||e==="::1"||e==="0.0.0.0"||e.startsWith("127.")))return!0;let r=t.toLowerCase();return!!c1e.includes(r)}function ZN(t,e){let r=e?.allowPrivate??!1,n=e?.allowHttp??!1;try{let i;try{i=new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}let o=i.hostname;if(!o)throw new Error("URL missing hostname.");if(wk(o))throw new Error(`URL points to cloud metadata endpoint: ${o}`);if(Sk(o)){if(!r)throw new Error(`URL points to localhost: ${o}`);return t}let a=i.protocol;if(a!=="http:"&&a!=="https:")throw new Error(`Invalid URL scheme: ${a}. Only http and https are allowed.`);if(a==="http:"&&!n)throw new Error("HTTP scheme not allowed. Use HTTPS or set allowHttp: true.");if(wG(o)){let s=o;if(Sk(o,s)){if(!r)throw new Error(`URL points to localhost: ${o}`);return t}if(wk(o,s))throw new Error(`URL resolves to cloud metadata IP: ${s} (${o})`);if(VN(s)&&!r)throw new Error(`URL resolves to private IP: ${s} (${o}). Set allowPrivate: true to allow.`);return t}return t}catch(i){throw i&&typeof i=="object"&&"message"in i?i:new Error(`URL validation failed: ${i}`)}}function kG(t,e){try{return ZN(t,e),!0}catch{return!1}}function PG(t,e){try{return new URL(t).origin===new URL(e).origin}catch{return!1}}Ks.isCloudMetadata=wk;Ks.isLocalhost=Sk;Ks.isPrivateIp=VN;Ks.isSafeUrl=kG;Ks.isSameOrigin=PG;Object.defineProperty(Ks,"ssrf_exports",{enumerable:!0,get:function(){return a1e}});Ks.validateSafeUrl=ZN});var WN=v(Qf=>{"use strict";p();Object.defineProperty(Qf,Symbol.toStringTag,{value:"Module"});var h1e=de(),m1e=xi(),g1e=KT(),y1e=h1e.__exportAll({SaveableVectorStore:()=>AG,VectorStore:()=>HN,VectorStoreRetriever:()=>ky}),ky=class extends g1e.BaseRetriever{constructor(e){super(e);f(this,"vectorStore");f(this,"k",4);f(this,"searchType","similarity");f(this,"searchKwargs");f(this,"filter");this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType==="mmr"&&(this.searchKwargs=e.searchKwargs)}static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}_vectorstoreType(){return this.vectorStore._vectorstoreType()}async _getRelevantDocuments(e,r){if(this.searchType==="mmr"){if(typeof this.vectorStore.maxMarginalRelevanceSearch!="function")throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},r?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,r?.getChild("vectorstore"))}async addDocuments(e,r){return this.vectorStore.addDocuments(e,r)}},HN=class extends m1e.Serializable{constructor(e,r){super(r);f(this,"lc_namespace",["langchain","vectorstores",this._vectorstoreType()]);f(this,"embeddings");this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,r=4,n=void 0,i=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),r,n)).map(o=>o[0])}async similaritySearchWithScore(e,r=4,n=void 0,i=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),r,n)}static fromTexts(e,r,n,i){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,r,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,r,n,i,o,a){if(typeof e=="number")return new ky({vectorStore:this,k:e,filter:r,tags:[...i??[],this._vectorstoreType()],metadata:o,verbose:a,callbacks:n});{let s={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType==="mmr"?new ky({...s,searchKwargs:e.searchKwargs}):new ky({...s})}}},AG=class extends HN{static load(t,e){throw new Error("Not implemented")}};Qf.SaveableVectorStore=AG;Qf.VectorStore=HN;Qf.VectorStoreRetriever=ky;Object.defineProperty(Qf,"vectorstores_exports",{enumerable:!0,get:function(){return y1e}})});var IG=v(kk=>{"use strict";p();var nu=Fr(),GN=tc(),iu=Ll(),_1e=br();ei();var KN=MT(),b1e=class extends KN.BaseChatModel{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(t,e,r){if(e?.stop?.length)return{generations:[{message:new nu.AIMessage(e.stop[0]),text:e.stop[0]}]};let n=t.map(i=>typeof i.content=="string"?i.content:JSON.stringify(i.content,null,2)).join(`
410
+ `);return await r?.handleLLMNewToken(n),{generations:[{message:new nu.AIMessage(n),text:n}],llmOutput:{}}}},v1e=class CG extends KN.BaseChatModel{constructor({sleep:r=50,responses:n=[],chunks:i=[],toolStyle:o="openai",thrownErrorString:a,...s}){super(s);f(this,"sleep",50);f(this,"responses",[]);f(this,"chunks",[]);f(this,"toolStyle","openai");f(this,"thrownErrorString");f(this,"tools",[]);this.sleep=r,this.responses=n,this.chunks=i,this.toolStyle=o,this.thrownErrorString=a}_llmType(){return"fake"}bindTools(r){let n=[...this.tools,...r],i=n.map(s=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:s.name,description:s.description,parameters:iu.toJsonSchema(s.schema)}};case"anthropic":return{name:s.name,description:s.description,input_schema:iu.toJsonSchema(s.schema)};case"bedrock":return{toolSpec:{name:s.name,description:s.description,inputSchema:iu.toJsonSchema(s.schema)}};case"google":return{name:s.name,description:s.description,parameters:iu.toJsonSchema(s.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),o=this.toolStyle==="google"?[{functionDeclarations:i}]:i,a=new CG({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return a.tools=n,a.withConfig({tools:o})}async _generate(r,n,i){if(this.thrownErrorString)throw new Error(this.thrownErrorString);return{generations:[{text:"",message:new nu.AIMessage({content:this.responses?.[0]?.content??r[0].content??"",tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(r,n,i){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(let s of this.chunks){let l=new GN.ChatGenerationChunk({message:new nu.AIMessageChunk({content:s.content,tool_calls:s.tool_calls,additional_kwargs:s.additional_kwargs??{}}),text:s.content?.toString()??""});if(n.signal?.aborted)break;yield l,await i?.handleLLMNewToken(s.content,void 0,void 0,void 0,void 0,{chunk:l})}return}let o=this.responses?.[0]??new nu.AIMessage(typeof r[0].content=="string"?r[0].content:""),a=typeof o.content=="string"?o.content:"";for(let s of a){await new Promise(u=>setTimeout(u,this.sleep));let l=new GN.ChatGenerationChunk({message:new nu.AIMessageChunk({content:s}),text:s});if(n.signal?.aborted)break;yield l,await i?.handleLLMNewToken(s,void 0,void 0,void 0,void 0,{chunk:l})}}},w1e=class xG extends KN.BaseChatModel{constructor(r){super(r);f(this,"lc_serializable",!0);f(this,"responses");f(this,"i",0);f(this,"sleep");f(this,"emitCustomEvent",!1);f(this,"generationInfo");f(this,"tools",[]);f(this,"toolStyle","openai");let{responses:n,sleep:i,emitCustomEvent:o,generationInfo:a}=r;this.responses=n,this.sleep=i,this.emitCustomEvent=o??this.emitCustomEvent,this.generationInfo=a}static lc_name(){return"FakeListChatModel"}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(r,n,i){if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);if(this.emitCustomEvent&&await i?.handleCustomEvent("some_test_event",{someval:!0}),n?.stop?.length)return{generations:[this._formatGeneration(n.stop[0])]};{let o=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(o)],llmOutput:{}}}}_formatGeneration(r){return{message:new nu.AIMessage(r),text:r}}async*_streamResponseChunks(r,n,i){let o=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await i?.handleCustomEvent("some_test_event",{someval:!0});let a=[...o];for(let s=0;s<a.length;s++){let l=a[s],u=s===a.length-1;if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);let c=this._createResponseChunk(l,u?this.generationInfo:void 0);if(n.signal?.aborted)break;yield c,i?.handleLLMNewToken(l)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(r=>{setTimeout(()=>r(),this.sleep)})}_createResponseChunk(r,n){return new GN.ChatGenerationChunk({message:new nu.AIMessageChunk({content:r}),text:r,generationInfo:n})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(r){let n=[...this.tools,...r],i=n.map(s=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:s.name,description:s.description,parameters:iu.toJsonSchema(s.schema)}};case"anthropic":return{name:s.name,description:s.description,input_schema:iu.toJsonSchema(s.schema)};case"bedrock":return{toolSpec:{name:s.name,description:s.description,inputSchema:iu.toJsonSchema(s.schema)}};case"google":return{name:s.name,description:s.description,parameters:iu.toJsonSchema(s.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),o=this.toolStyle==="google"?[{functionDeclarations:i}]:i,a=new xG({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return a.tools=n,a.toolStyle=this.toolStyle,a.i=this.i,a.withConfig({tools:o})}withStructuredOutput(r,n){return _1e.RunnableLambda.from(async i=>{let o=await this.invoke(i);if(o.tool_calls?.[0]?.args)return o.tool_calls[0].args;if(typeof o.content=="string")return JSON.parse(o.content);throw new Error("No structured output found")})}};kk.FakeChatModel=b1e;kk.FakeListChatModel=w1e;kk.FakeStreamingChatModel=v1e});var RG=v(YN=>{"use strict";p();var OG=lR(),S1e=class extends OG.Embeddings{constructor(e){super(e??{});f(this,"vectorSize");this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(r=>this.embedQuery(r)))}async embedQuery(e){let r=e;r=r.toLowerCase().replaceAll(/[^a-z ]/g,"");let n=r.length%this.vectorSize,i=n===0?0:this.vectorSize-n,o=r.length+i;r=r.padEnd(o," ");let a=r.length/this.vectorSize,s=[];for(let l=0;l<r.length;l+=a)s.push(r.slice(l,l+a));return s.map(l=>{let u=0;for(let c=0;c<l.length;c+=1)u+=l===" "?0:l.charCodeAt(c);return u%26/26})}},T1e=class extends OG.Embeddings{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}};YN.FakeEmbeddings=T1e;YN.SyntheticEmbeddings=S1e});var $G=v(JN=>{"use strict";p();var NG=GR(),k1e=class extends NG.LLM{constructor(e){super(e);f(this,"response");f(this,"thrownErrorString");this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e,r,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let i=this.response??e;return await n?.handleLLMNewToken(i),i}},P1e=class extends NG.LLM{constructor(e){super(e);f(this,"sleep",50);f(this,"responses");f(this,"thrownErrorString");this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let r=this.responses?.[0];return this.responses=this.responses?.slice(1),r??e}async*_streamResponseChunks(e,r,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let i=this.responses?.[0];this.responses=this.responses?.slice(1);for(let o of i??e)await new Promise(a=>setTimeout(a,this.sleep)),yield{text:o,generationInfo:{}},await n?.handleLLMNewToken(o)}};JN.FakeLLM=k1e;JN.FakeStreamingLLM=P1e});var DG=v(Pk=>{"use strict";p();var E1e=Fr(),A1e=jo(),C1e=yo();ei();var MG=oR(),x1e=class extends MG.BaseChatMessageHistory{constructor(){super();f(this,"lc_namespace",["langchain_core","message","fake"]);f(this,"messages",[])}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new A1e.HumanMessage(e))}async addAIMessage(e){this.messages.push(new E1e.AIMessage(e))}async clear(){this.messages=[]}},I1e=class extends MG.BaseListChatMessageHistory{constructor(){super();f(this,"lc_namespace",["langchain_core","message","fake"]);f(this,"messages",[])}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},O1e=class extends C1e.BaseTracer{constructor(){super();f(this,"name","fake_tracer");f(this,"runs",[])}persistRun(e){return this.runs.push(e),Promise.resolve()}};Pk.FakeChatMessageHistory=x1e;Pk.FakeListChatMessageHistory=I1e;Pk.FakeTracer=O1e});var qG=v(UG=>{"use strict";p();var R1e=Bs(),N1e=class extends R1e.BaseOutputParser{constructor(){super(...arguments);f(this,"lc_namespace",["tests","fake"])}getFormatInstructions(){return""}async parse(e){return e.split(",").map(r=>r.trim())}};UG.FakeSplitIntoListParser=N1e});var FG=v(jG=>{"use strict";p();var LG=Rf(),$1e=KT(),M1e=class extends $1e.BaseRetriever{constructor(e){super();f(this,"lc_namespace",["test","fake"]);f(this,"output",[new LG.Document({pageContent:"foo"}),new LG.Document({pageContent:"bar"})]);this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}};jG.FakeRetriever=M1e});var zG=v(BG=>{"use strict";p();var D1e=br(),U1e=class extends D1e.Runnable{constructor(e){super(e);f(this,"lc_namespace",["tests","fake"]);f(this,"returnOptions");this.returnOptions=e.returnOptions}async invoke(e,r){return this.returnOptions?r??{}:{input:e}}};BG.FakeRunnable=U1e});var ZG=v(VG=>{"use strict";p();var q1e=MN(),L1e=class extends q1e.StructuredTool{constructor(e){super(e);f(this,"name");f(this,"description");f(this,"schema");this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,r){return JSON.stringify(e)}};VG.FakeTool=L1e});var WG=v(HG=>{"use strict";p();var j1e=yo(),F1e=class extends j1e.BaseTracer{constructor(){super();f(this,"runPromiseResolver");f(this,"runPromise");f(this,"name","single_run_extractor");this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}};HG.SingleRunExtractor=F1e});var YG=v(KG=>{"use strict";p();var XN=Rf(),B1e=zN(),z1e=WN(),V1e=class GG extends z1e.VectorStore{constructor(r,{similarity:n,...i}={}){super(r,i);f(this,"memoryVectors",[]);f(this,"similarity");this.similarity=n??B1e.cosine}_vectorstoreType(){return"memory"}async addDocuments(r){let n=r.map(({pageContent:i})=>i);return this.addVectors(await this.embeddings.embedDocuments(n),r)}async addVectors(r,n){let i=r.map((o,a)=>({content:n[a].pageContent,embedding:o,metadata:n[a].metadata}));this.memoryVectors=this.memoryVectors.concat(i)}async similaritySearchVectorWithScore(r,n,i){let o=s=>i?i(new XN.Document({metadata:s.metadata,pageContent:s.content})):!0,a=this.memoryVectors.filter(o);return a.map((s,l)=>({similarity:this.similarity(r,s.embedding),index:l})).sort((s,l)=>s.similarity>l.similarity?-1:0).slice(0,n).map(s=>[new XN.Document({metadata:a[s.index].metadata,pageContent:a[s.index].content}),s.similarity])}static async fromTexts(r,n,i,o){let a=[];for(let s=0;s<r.length;s+=1){let l=Array.isArray(n)?n[s]:n,u=new XN.Document({pageContent:r[s],metadata:l});a.push(u)}return GG.fromDocuments(a,i,o)}static async fromDocuments(r,n,i){let o=new this(n,i);return await o.addDocuments(r),o}static async fromExistingIndex(r,n){return new this(r,n)}};KG.FakeVectorStore=V1e});var n9=v(Dr=>{"use strict";p();Object.defineProperty(Dr,Symbol.toStringTag,{value:"Module"});var Z1e=de(),eh=IG(),Ek=RG(),Ak=$G(),th=DG(),JG=qG(),XG=FG(),QG=zG(),e9=ZG(),t9=WG(),r9=YG(),H1e=Z1e.__exportAll({FakeChatMessageHistory:()=>th.FakeChatMessageHistory,FakeChatModel:()=>eh.FakeChatModel,FakeEmbeddings:()=>Ek.FakeEmbeddings,FakeLLM:()=>Ak.FakeLLM,FakeListChatMessageHistory:()=>th.FakeListChatMessageHistory,FakeListChatModel:()=>eh.FakeListChatModel,FakeRetriever:()=>XG.FakeRetriever,FakeRunnable:()=>QG.FakeRunnable,FakeSplitIntoListParser:()=>JG.FakeSplitIntoListParser,FakeStreamingChatModel:()=>eh.FakeStreamingChatModel,FakeStreamingLLM:()=>Ak.FakeStreamingLLM,FakeTool:()=>e9.FakeTool,FakeTracer:()=>th.FakeTracer,FakeVectorStore:()=>r9.FakeVectorStore,SingleRunExtractor:()=>t9.SingleRunExtractor,SyntheticEmbeddings:()=>Ek.SyntheticEmbeddings});Dr.FakeChatMessageHistory=th.FakeChatMessageHistory;Dr.FakeChatModel=eh.FakeChatModel;Dr.FakeEmbeddings=Ek.FakeEmbeddings;Dr.FakeLLM=Ak.FakeLLM;Dr.FakeListChatMessageHistory=th.FakeListChatMessageHistory;Dr.FakeListChatModel=eh.FakeListChatModel;Dr.FakeRetriever=XG.FakeRetriever;Dr.FakeRunnable=QG.FakeRunnable;Dr.FakeSplitIntoListParser=JG.FakeSplitIntoListParser;Dr.FakeStreamingChatModel=eh.FakeStreamingChatModel;Dr.FakeStreamingLLM=Ak.FakeStreamingLLM;Dr.FakeTool=e9.FakeTool;Dr.FakeTracer=th.FakeTracer;Dr.FakeVectorStore=r9.FakeVectorStore;Dr.SingleRunExtractor=t9.SingleRunExtractor;Dr.SyntheticEmbeddings=Ek.SyntheticEmbeddings;Object.defineProperty(Dr,"testing_exports",{enumerable:!0,get:function(){return H1e}})});var o9=v(i9=>{"use strict";p();var W1e=de(),G1e=mL(),K1e=gL(),Y1e=Qv(),J1e=zu(),X1e=xi(),Q1e=_l(),eMe=wC(),tMe=Wu(),rMe=ks(),nMe=Cs(),iMe=yo(),oMe=Ux(),aMe=Zx(),sMe=Gx(),lMe=Rs(),uMe=fi(),cMe=Ri(),dMe=hI(),pMe=tc(),fMe=hf(),hMe=Sg(),mMe=Ll(),gMe=aT(),yMe=ei(),_Me=oR(),bMe=M3(),vMe=sR(),wMe=q3(),SMe=lR(),TMe=Q3(),kMe=lH(),PMe=$f(),EMe=gR(),AMe=Yg(),CMe=Bi(),xMe=Qg(),IMe=ER(),OMe=jf(),RMe=xR(),NMe=Vf(),$Me=DR(),MMe=MT(),DMe=R5(),UMe=GR(),qMe=$5(),LMe=j5(),jMe=H5(),FMe=W5(),BMe=OW(),zMe=NW(),VMe=KT(),ZMe=UW(),HMe=WW(),WMe=d8(),GMe=MN(),KMe=J8(),YMe=X8(),JMe=eG(),XMe=rG(),QMe=oG(),eDe=aG(),tDe=lG(),rDe=bG(),nDe=EG(),iDe=WN(),oDe=n9(),aDe=W1e.__exportAll({agents:()=>K1e.agents_exports,caches:()=>eMe.caches_exports,callbacks__base:()=>nMe.base_exports,callbacks__manager:()=>lMe.manager_exports,callbacks__promises:()=>sMe.promises_exports,chat_history:()=>_Me.chat_history_exports,document_loaders__base:()=>vMe.base_exports,document_loaders__langsmith:()=>wMe.langsmith_exports,documents:()=>bMe.documents_exports,embeddings:()=>SMe.embeddings_exports,errors:()=>J1e.errors_exports,example_selectors:()=>TMe.example_selectors_exports,index:()=>G1e.src_exports,indexing:()=>kMe.indexing_exports,language_models__base:()=>AMe.base_exports,language_models__chat_models:()=>MMe.chat_models_exports,language_models__compat:()=>$Me.compat_exports,language_models__event:()=>DMe.event_exports,language_models__llms:()=>UMe.llms_exports,language_models__profile:()=>qMe.profile_exports,language_models__stream:()=>NMe.stream_exports,language_models__structured_output:()=>RMe.structured_output_exports,load__serializable:()=>X1e.serializable_exports,memory:()=>LMe.memory_exports,messages:()=>yMe.messages_exports,messages__tool:()=>Q1e.tool_exports,output_parsers:()=>IMe.output_parsers_exports,output_parsers__openai_functions:()=>jMe.openai_functions_exports,output_parsers__openai_tools:()=>FMe.openai_tools_exports,outputs:()=>pMe.outputs_exports,prompt_values:()=>PMe.prompt_values_exports,prompts:()=>BMe.prompts_exports,retrievers:()=>VMe.retrievers_exports,retrievers__document_compressors:()=>zMe.document_compressors_exports,runnables:()=>CMe.runnables_exports,runnables__graph:()=>gMe.graph_exports,singletons:()=>uMe.singletons_exports,stores:()=>ZMe.stores_exports,structured_query:()=>HMe.structured_query_exports,testing:()=>WMe.testing_exports,tools:()=>GMe.tools_exports,tracers__base:()=>iMe.base_exports,tracers__console:()=>oMe.console_exports,tracers__log_stream:()=>dMe.log_stream_exports,tracers__run_collector:()=>KMe.run_collector_exports,tracers__tracer_langchain:()=>aMe.tracer_langchain_exports,types__stream:()=>YMe.stream_exports,utils__async_caller:()=>fMe.async_caller_exports,utils__chunk_array:()=>JMe.chunk_array_exports,utils__context:()=>XMe.context_exports,utils__env:()=>rMe.env_exports,utils__event_source_parse:()=>QMe.event_source_parse_exports,utils__format:()=>eDe.format_exports,utils__function_calling:()=>tDe.function_calling_exports,utils__hash:()=>Y1e.hash_exports,utils__json_patch:()=>xMe.json_patch_exports,utils__json_schema:()=>mMe.json_schema_exports,utils__math:()=>rDe.math_exports,utils__ssrf:()=>nDe.ssrf_exports,utils__standard_schema:()=>hMe.standard_schema_exports,utils__stream:()=>cMe.stream_exports,utils__testing:()=>oDe.testing_exports,utils__tiktoken:()=>EMe.tiktoken_exports,utils__types:()=>OMe.types_exports,utils__uuid:()=>tMe.uuid_exports,vectorstores:()=>iDe.vectorstores_exports});Object.defineProperty(i9,"import_map_exports",{enumerable:!0,get:function(){return aDe}})});var l9=v(QN=>{"use strict";p();Object.defineProperty(QN,Symbol.toStringTag,{value:"Module"});var a9=HA(),s9=KA(),sDe=xi(),lDe=ks(),uDe=hL(),cDe=o9(),dDe=50;function pDe(t){let e={};for(let r=t;r&&r.prototype;r=Object.getPrototypeOf(r))Object.assign(e,Reflect.get(r.prototype,"lc_aliases"));return Object.entries(e).reduce((r,[n,i])=>(r[i]=n,r),{})}async function Ck(t){let{optionalImportsMap:e,optionalImportEntrypoints:r,importMap:n,secretsMap:i,secretsFromEnv:o,path:a,depth:s,maxDepth:l}=this,u=a.join(".");if(s>l)throw new Error(`Maximum recursion depth (${l}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof t!="object"||t==null)return t;if(Array.isArray(t))return Promise.all(t.map((h,m)=>Ck.call({...this,path:[...a,`${m}`],depth:s+1},h)));let c=t;if(s9.isEscapedObject(c))return s9.unescapeValue(c);if("lc"in c&&"type"in c&&"id"in c&&c.lc===1&&c.type==="secret"){let[h]=c.id;if(h in i)return i[h];if(o){let m=lDe.getEnvironmentVariable(h);if(m)return m}throw new Error(`Missing secret "${h}" at ${u}`)}if("lc"in c&&"type"in c&&"id"in c&&c.lc===1&&c.type==="not_implemented"){let h=JSON.stringify(c);throw new Error(`Trying to load an object that doesn't implement serialization: ${u} -> ${h}`)}if("lc"in c&&"type"in c&&"id"in c&&"kwargs"in c&&c.lc===1&&c.type==="constructor"){let h=c,m=JSON.stringify(h),[g,...y]=h.id.slice().reverse(),_=y.reverse(),b={langchain_core:cDe.import_map_exports,langchain:n},w=null,T=[_.join("/")];_[0]==="langchain_community"&&T.push(["langchain",..._.slice(1)].join("/"));let E=T.find(D=>D in e);if(uDe.optionalImportEntrypoints.concat(r).includes(_.join("/"))||E)if(E!==void 0)w=await e[E];else throw new Error(`Missing key "${_.join("/")}" for ${u} in load(optionalImportsMap={})`);else{let D;if(_[0]==="langchain"||_[0]==="langchain_core")D=b[_[0]],_.shift();else throw new Error(`Invalid namespace: ${u} -> ${m}`);if(_.length===0)throw new Error(`Invalid namespace: ${u} -> ${m}`);let A;do{if(A=_.join("__"),A in D)break;_.pop()}while(_.length>0);A in D&&(w=D[A])}if(typeof w!="object"||w===null)throw new Error(`Invalid namespace: ${u} -> ${m}`);let C=w[g]??Object.values(w).find(D=>typeof D=="function"&&sDe.get_lc_unique_name(D)===g);if(typeof C!="function")throw new Error(`Invalid identifer: ${u} -> ${m}`);let R=new C(a9.mapKeys(await Ck.call({...this,path:[...a,"kwargs"],depth:s+1},h.kwargs),a9.keyFromJson,pDe(C)));return Object.defineProperty(R.constructor,"name",{value:g}),R}let d={};for(let[h,m]of Object.entries(c))d[h]=await Ck.call({...this,path:[...a,h],depth:s+1},m);return d}async function fDe(t,e){let r=JSON.parse(t),n={optionalImportsMap:e?.optionalImportsMap??{},optionalImportEntrypoints:e?.optionalImportEntrypoints??[],secretsMap:e?.secretsMap??{},secretsFromEnv:e?.secretsFromEnv??!1,importMap:e?.importMap??{},path:["$"],depth:0,maxDepth:e?.maxDepth??dDe};return Ck.call(n,r)}QN.load=fDe});var t$=v(u9=>{"use strict";p();var hDe=nL(),mDe=l9();function gDe(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function e$(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(e=>e$(e)));{let e={};for(let[r,n]of Object.entries(t))e[r]=await e$(n);if(e.lc===2&&e.type==="undefined")return;if(e.lc===2&&e.type==="constructor"&&Array.isArray(e.id))try{let r=e.id[e.id.length-1],n;switch(r){case"Set":n=Set;break;case"Map":n=Map;break;case"RegExp":n=RegExp;break;case"Error":n=Error;break;case"Uint8Array":n=Uint8Array;break;default:return e}return e.method?n[e.method](...e.args||[]):new n(...e.args||[])}catch{return e}else if(gDe(e))return(0,mDe.load)(JSON.stringify(e));return e}}return t}function xk(t,e,r,n){return{lc:2,type:"constructor",id:[t.name],method:e??null,args:r??[],kwargs:n??{}}}function yDe(t){return t===void 0?{lc:2,type:"undefined"}:t instanceof Set||t instanceof Map?xk(t.constructor,void 0,[Array.from(t)]):t instanceof RegExp?xk(RegExp,void 0,[t.source,t.flags]):t instanceof Error?xk(t.constructor,void 0,[t.message]):t?.lg_name==="Send"?{node:t.node,args:t.args}:t instanceof Uint8Array?xk(Uint8Array,"from",[Array.from(t)]):t}var _De=class{_dumps(t){return new TextEncoder().encode(hDe.stringify(t,(e,r)=>yDe(r)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){return e$(JSON.parse(t))}async loadsTyped(t,e){if(t==="bytes")return typeof e=="string"?new TextEncoder().encode(e):e;if(t==="json")return this._loads(typeof e=="string"?e:new TextDecoder().decode(e));throw new Error(`Unknown serialization type: ${t}`)}};u9.JsonPlusSerializer=_De});var n$=v(Ys=>{"use strict";p();var bDe=zA(),Ik=Zv(),vDe=t$();function r$(t){if(typeof t!="object"||t===null)return t;let e=Array.isArray(t)?[]:{};for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=r$(t[r]));return e}function wDe(){return{v:4,id:bDe.uuid6(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function SDe(t){return{v:t.v,id:t.id,ts:t.ts,channel_values:{...t.channel_values},channel_versions:{...t.channel_versions},versions_seen:r$(t.versions_seen)}}var TDe=class{constructor(t){f(this,"serde",new vDe.JsonPlusSerializer);this.serde=t||this.serde}async get(t){let e=await this.getTuple(t);return e?e.checkpoint:void 0}getNextVersion(t){if(typeof t=="string")throw new Error("Please override this method to use string versions.");return t!==void 0&&typeof t=="number"?t+1:1}};function c9(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function kDe(...t){return t.reduce((e,r,n)=>n===0?r:c9(e,r)>=0?e:r)}var PDe={[Ik.ERROR]:-1,[Ik.SCHEDULED]:-2,[Ik.INTERRUPT]:-3,[Ik.RESUME]:-4};function EDe(t){return t.configurable?.checkpoint_id||t.configurable?.thread_ts||""}Ys.BaseCheckpointSaver=TDe;Ys.WRITES_IDX_MAP=PDe;Ys.compareChannelVersions=c9;Ys.copyCheckpoint=SDe;Ys.deepCopy=r$;Ys.emptyCheckpoint=wDe;Ys.getCheckpointId=EDe;Ys.maxChannelVersion=kDe});var p9=v(d9=>{"use strict";p();var i$=Zv(),Py=n$();function Ey(t,e,r){return JSON.stringify([t,e,r])}function ADe(t){let[e,r,n]=JSON.parse(t);return{threadId:e,checkpointNamespace:r,checkpointId:n}}var CDe=class extends Py.BaseCheckpointSaver{constructor(e){super(e);f(this,"storage",{});f(this,"writes",{})}async _migratePendingSends(e,r,n,i){let o=e,a=Ey(r,n,i),s=await Promise.all(Object.values(this.writes[a]??{}).filter(([l,u])=>u===i$.TASKS).map(async([l,u,c])=>await this.serde.loadsTyped("json",c)));o.channel_values??(o.channel_values={}),o.channel_values[i$.TASKS]=s,o.channel_versions??(o.channel_versions={}),o.channel_versions[i$.TASKS]=Object.keys(o.channel_versions).length>0?Py.maxChannelVersion(...Object.values(o.channel_versions)):this.getNextVersion(void 0)}async getTuple(e){let r=e.configurable?.thread_id,n=e.configurable?.checkpoint_ns??"",i=Py.getCheckpointId(e);if(i){let o=this.storage[r]?.[n]?.[i];if(o!==void 0){let[a,s,l]=o,u=Ey(r,n,i),c=await this.serde.loadsTyped("json",a);c.v<4&&l!==void 0&&await this._migratePendingSends(c,r,n,l);let d=await Promise.all(Object.values(this.writes[u]||{}).map(async([m,g,y])=>[m,g,await this.serde.loadsTyped("json",y)])),h={config:e,checkpoint:c,metadata:await this.serde.loadsTyped("json",s),pendingWrites:d};return l!==void 0&&(h.parentConfig={configurable:{thread_id:r,checkpoint_ns:n,checkpoint_id:l}}),h}}else{let o=this.storage[r]?.[n];if(o!==void 0){i=Object.keys(o).sort((m,g)=>g.localeCompare(m))[0];let[a,s,l]=o[i],u=Ey(r,n,i),c=await this.serde.loadsTyped("json",a);c.v<4&&l!==void 0&&await this._migratePendingSends(c,r,n,l);let d=await Promise.all(Object.values(this.writes[u]||{}).map(async([m,g,y])=>[m,g,await this.serde.loadsTyped("json",y)])),h={config:{configurable:{thread_id:r,checkpoint_id:i,checkpoint_ns:n}},checkpoint:c,metadata:await this.serde.loadsTyped("json",s),pendingWrites:d};return l!==void 0&&(h.parentConfig={configurable:{thread_id:r,checkpoint_ns:n,checkpoint_id:l}}),h}}}async*list(e,r){let{before:n,limit:i,filter:o}=r??{},a=e.configurable?.thread_id?[e.configurable?.thread_id]:Object.keys(this.storage),s=e.configurable?.checkpoint_ns,l=e.configurable?.checkpoint_id;for(let u of a)for(let c of Object.keys(this.storage[u]??{})){if(s!==void 0&&c!==s)continue;let d=this.storage[u]?.[c]??{},h=Object.entries(d).sort((m,g)=>g[0].localeCompare(m[0]));for(let[m,[g,y,_]]of h){if(l&&m!==l||n&&n.configurable?.checkpoint_id&&m>=n.configurable.checkpoint_id)continue;let b=await this.serde.loadsTyped("json",y);if(o&&!Object.entries(o).every(([D,A])=>b[D]===A))continue;if(i!==void 0){if(i<=0)break;i-=1}let w=Ey(u,c,m),T=Object.values(this.writes[w]||{}),E=await Promise.all(T.map(async([D,A,U])=>[D,A,await this.serde.loadsTyped("json",U)])),C=await this.serde.loadsTyped("json",g);C.v<4&&_!==void 0&&await this._migratePendingSends(C,u,c,_);let R={config:{configurable:{thread_id:u,checkpoint_ns:c,checkpoint_id:m}},checkpoint:C,metadata:b,pendingWrites:E};_!==void 0&&(R.parentConfig={configurable:{thread_id:u,checkpoint_ns:c,checkpoint_id:_}}),yield R}}}async put(e,r,n){let i=Py.copyCheckpoint(r),o=e.configurable?.thread_id,a=e.configurable?.checkpoint_ns??"";if(o===void 0)throw new Error('Failed to put checkpoint. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property. When using a checkpointer, you must pass a "thread_id" so the checkpointer knows which conversation thread to persist state for. Example: graph.stream(input, { configurable: { thread_id: "my-thread-id" } })');this.storage[o]||(this.storage[o]={}),this.storage[o][a]||(this.storage[o][a]={});let[[,s],[,l]]=await Promise.all([this.serde.dumpsTyped(i),this.serde.dumpsTyped(n)]);return this.storage[o][a][r.id]=[s,l,e.configurable?.checkpoint_id],{configurable:{thread_id:o,checkpoint_ns:a,checkpoint_id:r.id}}}async putWrites(e,r,n){let i=e.configurable?.thread_id,o=e.configurable?.checkpoint_ns,a=e.configurable?.checkpoint_id;if(i===void 0)throw new Error('Failed to put writes. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property. When using a checkpointer, you must pass a "thread_id" so the checkpointer knows which conversation thread to persist state for. Example: graph.stream(input, { configurable: { thread_id: "my-thread-id" } })');if(a===void 0)throw new Error('Failed to put writes. The passed RunnableConfig is missing a required "checkpoint_id" field in its "configurable" property.');let s=Ey(i,o,a),l=this.writes[s];this.writes[s]===void 0&&(this.writes[s]={}),await Promise.all(r.map(async([u,c],d)=>{let[,h]=await this.serde.dumpsTyped(c),m=[n,Py.WRITES_IDX_MAP[u]||d],g=`${m[0]},${m[1]}`;m[1]>=0&&l&&g in l||(this.writes[s][g]=[n,u,h])}))}async deleteThread(e){delete this.storage[e];for(let r of Object.keys(this.writes))ADe(r).threadId===e&&delete this.writes[r]}};d9.MemorySaver=CDe});var Ok=v(Ay=>{"use strict";p();var rh=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function xDe(t){if(t.length===0)throw new rh("Namespace cannot be empty.");for(let e of t){if(typeof e!="string")throw new rh(`Invalid namespace label '${e}' found in ${t}. Namespace labels must be strings, but got ${typeof e}.`);if(e.includes("."))throw new rh(`Invalid namespace label '${e}' found in ${t}. Namespace labels cannot contain periods ('.').`);if(e==="")throw new rh(`Namespace labels cannot be empty strings. Got ${e} in ${t}`)}if(t[0]==="langgraph")throw new rh(`Root label for namespace cannot be "langgraph". Got: ${t}`)}function IDe(t,e){let r=e.split("."),n=t;for(let i of r){if(i.includes("[")){let[o,a]=i.split("["),s=a.replace("]","");if(!n[o])return[];if(s==="*"){let u=[];for(let c of n[o])typeof c=="string"&&u.push(c);return u}let l=parseInt(s,10);if(Number.isNaN(l))return[];n=n[o][l]}else n=n[i];if(n===void 0)return[]}return typeof n=="string"?[n]:[]}function ODe(t){return t.split(".")}var RDe=class{async get(t,e){return(await this.batch([{namespace:t,key:e}]))[0]}async search(t,e={}){let{filter:r,limit:n=10,offset:i=0,query:o}=e;return(await this.batch([{namespacePrefix:t,filter:r,limit:n,offset:i,query:o}]))[0]}async put(t,e,r,n){xDe(t),await this.batch([{namespace:t,key:e,value:r,index:n}])}async delete(t,e){await this.batch([{namespace:t,key:e,value:null}])}async listNamespaces(t={}){let{prefix:e,suffix:r,maxDepth:n,limit:i=100,offset:o=0}=t,a=[];return e&&a.push({matchType:"prefix",path:e}),r&&a.push({matchType:"suffix",path:r}),(await this.batch([{matchConditions:a.length?a:void 0,maxDepth:n,limit:i,offset:o}]))[0]}start(){}stop(){}};Ay.BaseStore=RDe;Ay.InvalidNamespaceError=rh;Ay.getTextAtPath=IDe;Ay.tokenizePath=ODe});var h9=v(f9=>{"use strict";p();var NDe=Ok(),$De=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t,MDe=class extends NDe.BaseStore{constructor(e){super();f(this,"lg_name","AsyncBatchedStore");f(this,"store");f(this,"queue",new Map);f(this,"nextKey",0);f(this,"running",!1);f(this,"processingTask",null);this.store=$De(e)}get isRunning(){return this.running}async batch(e){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,r){return this.enqueueOperation({namespace:e,key:r})}async search(e,r){let{filter:n,limit:i=10,offset:o=0,query:a}=r||{};return this.enqueueOperation({namespacePrefix:e,filter:n,limit:i,offset:o,query:a})}async put(e,r,n){return this.enqueueOperation({namespace:e,key:r,value:n})}async delete(e,r){return this.enqueueOperation({namespace:e,key:r,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((r,n)=>{let i=this.nextKey;this.nextKey+=1,this.queue.set(i,{operation:e,resolve:r,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(r=>{setTimeout(r,0)}),this.queue.size===0)continue;let e=new Map(this.queue);this.queue.clear();try{let r=Array.from(e.values()).map(({operation:i})=>i),n=await this.store.batch(r);e.forEach(({resolve:i},o)=>{i(n[Array.from(e.keys()).indexOf(o)])})}catch(r){e.forEach(({reject:n})=>{n(r)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}};f9.AsyncBatchedStore=MDe});var m9=v(Rk=>{"use strict";p();function o$(t){if(!t)return[];let e=[],r=[],n=0;for(;n<t.length;){let i=t[n];if(i==="["){r.length&&(e.push(r.join("")),r=[]);let o=1,a=["["];for(n+=1;n<t.length&&o>0;)t[n]==="["?o+=1:t[n]==="]"&&(o-=1),a.push(t[n]),n+=1;e.push(a.join(""));continue}else if(i==="{"){r.length&&(e.push(r.join("")),r=[]);let o=1,a=["{"];for(n+=1;n<t.length&&o>0;)t[n]==="{"?o+=1:t[n]==="}"&&(o-=1),a.push(t[n]),n+=1;e.push(a.join(""));continue}else i==="."?r.length&&(e.push(r.join("")),r=[]):r.push(i);n+=1}return r.length&&e.push(r.join("")),e}function DDe(t){return typeof t=="object"&&t!==null&&Object.keys(t).every(e=>e==="$eq"||e==="$ne"||e==="$gt"||e==="$gte"||e==="$lt"||e==="$lte"||e==="$in"||e==="$nin")}function UDe(t,e){return DDe(e)?Object.keys(e).filter(r=>r.startsWith("$")).every(r=>{let n=e[r];switch(r){case"$eq":return t===n;case"$ne":return t!==n;case"$gt":return Number(t)>Number(n);case"$gte":return Number(t)>=Number(n);case"$lt":return Number(t)<Number(n);case"$lte":return Number(t)<=Number(n);case"$in":return Array.isArray(n)?n.includes(t):!1;case"$nin":return Array.isArray(n)?!n.includes(t):!0;default:return!1}}):t===e}function qDe(t,e){if(!e||e==="$")return[JSON.stringify(t,null,2)];let r=Array.isArray(e)?e:o$(e);function n(i,o,a){if(a>=o.length)return typeof i=="string"||typeof i=="number"||typeof i=="boolean"?[String(i)]:i==null?[]:Array.isArray(i)||typeof i=="object"?[JSON.stringify(i,null,2)]:[];let s=o[a],l=[];if(a===0&&s==="$"&&l.push(JSON.stringify(i,null,2)),s.startsWith("[")&&s.endsWith("]")){if(!Array.isArray(i))return[];let u=s.slice(1,-1);if(u==="*")for(let c of i)l.push(...n(c,o,a+1));else try{let c=parseInt(u,10);c<0&&(c=i.length+c),c>=0&&c<i.length&&l.push(...n(i[c],o,a+1))}catch{return[]}}else if(s.startsWith("{")&&s.endsWith("}")){if(typeof i!="object"||i===null)return[];let u=s.slice(1,-1).split(",").map(c=>c.trim());for(let c of u){let d=o$(c);if(d.length){let h=i;for(let m of d)if(h&&typeof h=="object"&&m in h)h=h[m];else{h=void 0;break}h!==void 0&&(typeof h=="string"||typeof h=="number"||typeof h=="boolean"?l.push(String(h)):(Array.isArray(h)||typeof h=="object")&&l.push(JSON.stringify(h,null,2)))}}}else if(s==="*"){if(Array.isArray(i))for(let u of i)l.push(...n(u,o,a+1));else if(typeof i=="object"&&i!==null)for(let u of Object.values(i))l.push(...n(u,o,a+1))}else typeof i=="object"&&i!==null&&s in i&&l.push(...n(i[s],o,a+1));return l}return n(t,r,0)}Rk.compareValues=UDe;Rk.getTextAtPath=qDe;Rk.tokenizePath=o$});var y9=v(a$=>{"use strict";p();var LDe=Ok(),Nk=m9(),g9=class extends LDe.BaseStore{constructor(e){super();f(this,"data",new Map);f(this,"vectors",new Map);f(this,"_indexConfig");e?.index&&(this._indexConfig={...e.index,__tokenizedFields:(e.index.fields??["$"]).map(r=>[r,r==="$"?[r]:Nk.tokenizePath(r)])})}async batch(e){let r=[],n=new Map,i=new Map;for(let o=0;o<e.length;o+=1){let a=e[o];if("key"in a&&"namespace"in a&&!("value"in a))r.push(this.getOperation(a));else if("namespacePrefix"in a){let s=this.filterItems(a);i.set(o,[a,s]),r.push(null)}else if("value"in a){let s=`${a.namespace.join(":")}:${a.key}`;n.set(s,a),r.push(null)}else"matchConditions"in a&&r.push(this.listNamespacesOperation(a))}if(i.size>0)if(this._indexConfig?.embeddings){let o=new Set;for(let[l]of i.values())l.query&&o.add(l.query);let a=o.size>0?await Promise.all(Array.from(o).map(l=>this._indexConfig.embeddings.embedQuery(l))):[],s=Object.fromEntries(Array.from(o).map((l,u)=>[l,a[u]]));for(let[l,[u,c]]of i.entries())if(u.query&&s[u.query]){let d=s[u.query];r[l]=this.scoreResults(c,d,u.offset??0,u.limit??10)}else r[l]=this.paginateResults(c.map(d=>({...d,score:void 0})),u.offset??0,u.limit??10)}else for(let[o,[a,s]]of i.entries())r[o]=this.paginateResults(s.map(l=>({...l,score:void 0})),a.offset??0,a.limit??10);if(n.size>0&&this._indexConfig?.embeddings){let o=this.extractTexts(Array.from(n.values()));if(Object.keys(o).length>0){let a=await this._indexConfig.embeddings.embedDocuments(Object.keys(o));this.insertVectors(o,a)}}for(let o of n.values())this.putOperation(o);return r}getOperation(e){let r=e.namespace.join(":");return this.data.get(r)?.get(e.key)??null}putOperation(e){let r=e.namespace.join(":");this.data.has(r)||this.data.set(r,new Map);let n=this.data.get(r);if(e.value===null)n.delete(e.key);else{let i=new Date;if(n.has(e.key)){let o=n.get(e.key);o.value=e.value,o.updatedAt=i}else n.set(e.key,{value:e.value,key:e.key,namespace:e.namespace,createdAt:i,updatedAt:i})}}listNamespacesOperation(e){let r=Array.from(this.data.keys()).map(n=>n.split(":"));return e.matchConditions&&e.matchConditions.length>0&&(r=r.filter(n=>e.matchConditions.every(i=>this.doesMatch(i,n)))),e.maxDepth!==void 0&&(r=Array.from(new Set(r.map(n=>n.slice(0,e.maxDepth).join(":")))).map(n=>n.split(":"))),r.sort((n,i)=>n.join(":").localeCompare(i.join(":"))),r.slice(e.offset??0,(e.offset??0)+(e.limit??r.length))}doesMatch(e,r){let{matchType:n,path:i}=e;if(n==="prefix")return i.length>r.length?!1:i.every((o,a)=>{let s=r[a];return o==="*"||s===o});if(n==="suffix")return i.length>r.length?!1:i.every((o,a)=>{let s=r[r.length-i.length+a];return o==="*"||s===o});throw new Error(`Unsupported match type: ${n}`)}filterItems(e){let r=[];for(let[i,o]of this.data.entries())i.startsWith(e.namespacePrefix.join(":"))&&r.push(...o.values());let n=r;return e.filter&&(n=r.filter(i=>Object.entries(e.filter).every(([o,a])=>Nk.compareValues(i.value[o],a)))),n}scoreResults(e,r,n=0,i=10){let o=[],a=[],s=[];for(let d of e){let h=this.getVectors(d);if(h.length)for(let m of h)o.push(d),a.push(m);else s.push(d)}let l=this.cosineSimilarity(r,a).map((d,h)=>[d,o[h]]).sort((d,h)=>h[0]-d[0]),u=new Set,c=[];for(let[d,h]of l){let m=`${h.namespace.join(":")}:${h.key}`;if(u.has(m))continue;let g=u.size;if(g>=n+i)break;if(g<n){u.add(m);continue}u.add(m),c.push([d,h])}if(s.length&&c.length<i)for(let d of s.slice(0,i-c.length)){let h=`${d.namespace.join(":")}:${d.key}`;u.has(h)||(u.add(h),c.push([void 0,d]))}return c.map(([d,h])=>({...h,score:d}))}paginateResults(e,r,n){return e.slice(r,r+n)}extractTexts(e){if(!e.length||!this._indexConfig)return{};let r={};for(let n of e)if(n.value!==null&&n.index!==!1){let i=n.index===null||n.index===void 0?this._indexConfig.__tokenizedFields??[]:n.index.map(o=>[o,Nk.tokenizePath(o)]);for(let[o,a]of i){let s=Nk.getTextAtPath(n.value,a);s.length&&(s.length>1?s.forEach((l,u)=>{r[l]||(r[l]=[]),r[l].push([n.namespace,n.key,`${o}.${u}`])}):(r[s[0]]||(r[s[0]]=[]),r[s[0]].push([n.namespace,n.key,o])))}}return r}insertVectors(e,r){for(let[n,i]of Object.entries(e)){let o=r.shift();if(!o)throw new Error(`No embedding found for text: ${n}`);for(let[a,s,l]of i){let u=a.join(":");this.vectors.has(u)||this.vectors.set(u,new Map);let c=this.vectors.get(u);c.has(s)||c.set(s,new Map),c.get(s).set(l,o)}}}getVectors(e){let r=e.namespace.join(":"),n=e.key;if(!this.vectors.has(r))return[];let i=this.vectors.get(r);if(!i.has(n))return[];let o=i.get(n),a=Array.from(o.values());return a.length?a:[]}cosineSimilarity(e,r){if(!r.length)return[];let n=r.map(a=>a.reduce((s,l,u)=>s+l*e[u],0)),i=Math.sqrt(e.reduce((a,s)=>a+s*s,0)),o=r.map(a=>Math.sqrt(a.reduce((s,l)=>s+l*l,0)));return n.map((a,s)=>{let l=o[s];return i&&l?a/(i*l):0})}get indexConfig(){return this._indexConfig}},jDe=class extends g9{};a$.InMemoryStore=g9;a$.MemoryStore=jDe});var $k=v(_9=>{"use strict";p();var FDe=t$(),BDe=class{constructor(t){f(this,"serde",new FDe.JsonPlusSerializer);this.serde=t||this.serde}};_9.BaseCache=BDe});var s$=v(b9=>{"use strict";p();var zDe=$k(),VDe=class extends zDe.BaseCache{constructor(){super(...arguments);f(this,"cache",{})}async get(e){if(!e.length)return[];let r=Date.now();return(await Promise.all(e.map(async n=>{let[i,o]=n,a=i.join(",");if(a in this.cache&&o in this.cache[a]){let s=this.cache[a][o];if(s.exp==null||r<s.exp)return[{key:n,value:await this.serde.loadsTyped(s.enc,s.val)}];delete this.cache[a][o]}return[]}))).flat()}async set(e){var n;let r=Date.now();for(let{key:i,value:o,ttl:a}of e){let[s,l]=i,u=s.join(","),[c,d]=await this.serde.dumpsTyped(o),h=a!=null?a*1e3+r:null;(n=this.cache)[u]??(n[u]={}),this.cache[u][l]={enc:c,val:d,exp:h}}}async clear(e){if(!e.length){this.cache={};return}for(let r of e){let n=r.join(",");n in this.cache&&delete this.cache[n]}}};b9.InMemoryCache=VDe});var v9=v(()=>{"use strict";p();$k();s$()});var nh=v(Bt=>{"use strict";p();Object.defineProperty(Bt,Symbol.toStringTag,{value:"Module"});var w9=zA(),Cy=Zv(),ou=n$(),ZDe=p9(),Mk=Ok(),HDe=h9(),S9=y9(),WDe=$k(),GDe=s$();v9();Bt.AsyncBatchedStore=HDe.AsyncBatchedStore;Bt.BaseCache=WDe.BaseCache;Bt.BaseCheckpointSaver=ou.BaseCheckpointSaver;Bt.BaseStore=Mk.BaseStore;Bt.ERROR=Cy.ERROR;Bt.INTERRUPT=Cy.INTERRUPT;Bt.InMemoryCache=GDe.InMemoryCache;Bt.InMemoryStore=S9.InMemoryStore;Bt.InvalidNamespaceError=Mk.InvalidNamespaceError;Bt.MemorySaver=ZDe.MemorySaver;Bt.MemoryStore=S9.MemoryStore;Bt.RESUME=Cy.RESUME;Bt.SCHEDULED=Cy.SCHEDULED;Bt.TASKS=Cy.TASKS;Bt.WRITES_IDX_MAP=ou.WRITES_IDX_MAP;Bt.compareChannelVersions=ou.compareChannelVersions;Bt.copyCheckpoint=ou.copyCheckpoint;Bt.deepCopy=ou.deepCopy;Bt.emptyCheckpoint=ou.emptyCheckpoint;Bt.getCheckpointId=ou.getCheckpointId;Bt.getTextAtPath=Mk.getTextAtPath;Bt.maxChannelVersion=ou.maxChannelVersion;Bt.tokenizePath=Mk.tokenizePath;Bt.uuid5=w9.uuid5;Bt.uuid6=w9.uuid6});var $n=v(ih=>{"use strict";p();var T9=gr(),KDe=nh();function k9(t){return t!=null&&t.lg_is_channel===!0}var YDe=class{constructor(){f(this,"ValueType");f(this,"UpdateType");f(this,"lg_is_channel",!0)}consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(t){if(t.name===T9.EmptyChannelError.unminifiable_name)return!1;throw t}}equals(t){return this===t}},l$=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function P9(t){if(t[l$]===!0)return t;let e={};for(let r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;let n=t[r];k9(n)&&(e[r]=n)}return Object.assign(e,{[l$]:!0}),e}function JDe(t,e){let r=P9(t),n={};for(let i in r){if(!Object.prototype.hasOwnProperty.call(r,i))continue;let o=e.channel_values[i];n[i]=r[i].fromCheckpoint(o)}return Object.assign(n,{[l$]:!0}),n}function XDe(t,e,r,n){let i;if(e===void 0)i=t.channel_values;else{i={};for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o))try{i[o]=e[o].checkpoint()}catch(a){if(a.name!==T9.EmptyChannelError.unminifiable_name)throw a}}return{v:4,id:n?.id??(0,KDe.uuid6)(r),ts:new Date().toISOString(),channel_values:i,channel_versions:t.channel_versions,versions_seen:t.versions_seen}}ih.BaseChannel=YDe;ih.createCheckpoint=XDe;ih.emptyChannels=JDe;ih.getOnlyChannels=P9;ih.isBaseChannel=k9});var oh=v(A9=>{"use strict";p();var u$=Zt(),c$=gr(),QDe=$n(),eUe=t=>t!=null&&t.lc_graph_name==="BinaryOperatorAggregate",tUe=class E9 extends QDe.BaseChannel{constructor(r,n){super();f(this,"lc_graph_name","BinaryOperatorAggregate");f(this,"value");f(this,"operator");f(this,"initialValueFactory");this.operator=r,this.initialValueFactory=n,this.value=n?.()}fromCheckpoint(r){let n=new E9(this.operator,this.initialValueFactory);return typeof r<"u"&&(n.value=r),n}update(r){let n=r;if(!n.length)return!1;if(this.value===void 0){let o=n[0],[a,s]=u$._getOverwriteValue(o);a?this.value=s:this.value=o,n=n.slice(1)}let i=!1;for(let o of n)if(u$._isOverwriteValue(o)){if(i)throw new c$.InvalidUpdateError("Can receive only one Overwrite value per step.");let[,a]=u$._getOverwriteValue(o);this.value=a,i=!0;continue}else!i&&this.value!==void 0&&(this.value=this.operator(this.value,o));return!0}get(){if(this.value===void 0)throw new c$.EmptyChannelError;return this.value}checkpoint(){if(this.value===void 0)throw new c$.EmptyChannelError;return this.value}isAvailable(){return this.value!==void 0}equals(r){return this===r?!0:eUe(r)?this.operator===r.operator:!1}};A9.BinaryOperatorAggregate=tUe});var xc=v(d$=>{"use strict";p();var Dk=gr(),C9=$n(),rUe=class x9 extends C9.BaseChannel{constructor(r){super();f(this,"lc_graph_name","LastValue");f(this,"value",[]);this.initialValueFactory=r,r&&(this.value=[r()])}fromCheckpoint(r){let n=new x9(this.initialValueFactory);return typeof r<"u"&&(n.value=[r]),n}update(r){if(r.length===0)return!1;if(r.length!==1)throw new Dk.InvalidUpdateError("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[r[r.length-1]],!0}get(){if(this.value.length===0)throw new Dk.EmptyChannelError;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Dk.EmptyChannelError;return this.value[0]}isAvailable(){return this.value.length!==0}},nUe=class I9 extends C9.BaseChannel{constructor(){super(...arguments);f(this,"lc_graph_name","LastValueAfterFinish");f(this,"value",[]);f(this,"finished",!1)}fromCheckpoint(r){let n=new I9;if(typeof r<"u"){let[i,o]=r;n.value=[i],n.finished=o}return n}update(r){return r.length===0?!1:(this.finished=!1,this.value=[r[r.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new Dk.EmptyChannelError;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}};d$.LastValue=rUe;d$.LastValueAfterFinish=nUe});var xy=v(Uk=>{"use strict";p();var O9=oh(),R9=xc(),N9=class{constructor(t){f(this,"lc_graph_name","AnnotationRoot");f(this,"spec");this.spec=t}static isInstance(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}},$9=function(t){return t?M9(t):new R9.LastValue};$9.Root=t=>new N9(t);function M9(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new O9.BinaryOperatorAggregate(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new O9.BinaryOperatorAggregate(t.value,t.default):new R9.LastValue}Uk.Annotation=$9;Uk.AnnotationRoot=N9;Uk.getChannel=M9});var ah=v(Js=>{"use strict";p();var iUe=Zt(),Iy=fi(),oUe=["tags","metadata","callbacks","configurable"],aUe=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal","executionInfo","serverInfo"],sUe=25,lUe=new Set(["thread_id","checkpoint_id","checkpoint_ns","task_id","run_id","assistant_id","graph_id"]);function D9(t,e){if(!t)return e;let r=e??{};for(let n of lUe){if(n in r)continue;let i=t[n];i!==void 0&&(r[n]=i)}return r}function uUe(...t){let e={tags:[],metadata:{},callbacks:void 0,recursionLimit:sUe,configurable:{}},r=Iy.AsyncLocalStorageProviderSingleton.getRunnableConfig();if(r!==void 0){for(let[n,i]of Object.entries(r))if(i!==void 0)if(oUe.includes(n)){let o;Array.isArray(i)?o=[...i]:typeof i=="object"?n==="callbacks"&&"copy"in i&&typeof i.copy=="function"?o=i.copy():o={...i}:o=i,e[n]=o}else e[n]=i}for(let n of t)if(n!==void 0)for(let[i,o]of Object.entries(n))o!==void 0&&aUe.includes(i)&&(e[i]=o);return e.metadata=D9(e.configurable,e.metadata)??{},e}function cUe(t){let e=t??Iy.AsyncLocalStorageProviderSingleton.getRunnableConfig();if(e===void 0)throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.","If you're running `getStore` in such environment, pass the `config` from the node function directly."].join(`
411
411
  `));return e?.store}function dUe(t){let e=t??Iy.AsyncLocalStorageProviderSingleton.getRunnableConfig();if(e===void 0)throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.","If you're running `getWriter` in such environment, pass the `config` from the node function directly."].join(`
412
412
  `));return e?.writer||e?.configurable?.writer}function pUe(){return Iy.AsyncLocalStorageProviderSingleton.getRunnableConfig()}function fUe(t){let e=t??Iy.AsyncLocalStorageProviderSingleton.getRunnableConfig();if(e===void 0)throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.","If you're running `getCurrentTaskInput` in such environment, pass the `config` from the node function directly."].join(`
413
413
  `));if(e.configurable?.__pregel_scratchpad?.currentTaskInput===void 0)throw new Error("BUG: internal scratchpad not initialized.");return e.configurable[iUe.CONFIG_KEY_SCRATCHPAD].currentTaskInput}function hUe(t){return t.split("|").filter(e=>!e.match(/^\d+$/)).map(e=>e.split(":")[0]).join("|")}function mUe(t){let e=t.split("|");for(;e.length>1&&e[e.length-1].match(/^\d+$/);)e.pop();return e.slice(0,-1).join("|")}Js.ensureLangGraphConfig=uUe;Js.getConfig=pUe;Js.getCurrentTaskInput=fUe;Js.getParentCheckpointNamespace=mUe;Js.getStore=cUe;Js.getWriter=dUe;Js.propagateConfigurableToMetadata=D9;Js.recastCheckpointNamespace=hUe});var Rc=v(f$=>{"use strict";p();var p$=Symbol.for("langgraph.stream_channel"),U9,ss,Oy,Ic,sh,Ry,lh,qk,Oc,q9=(Oc=class{constructor(e){wt(this,lh);f(this,U9,!0);f(this,"channelName");wt(this,ss,[]);wt(this,Oy,[]);wt(this,Ic,!1);wt(this,sh);wt(this,Ry);this.channelName=e}static local(){return new Oc}static remote(e){return new Oc(e)}static isInstance(e){return typeof e=="object"&&e!==null&&p$ in e&&e[p$]===!0}push(e){var r;Me(this,ss).push(e),Kc(this,lh,qk).call(this),(r=Me(this,Ry))==null||r.call(this,e)}iterate(e=0){let r=e;return{next:async()=>{for(;;){if(r<Me(this,ss).length)return{value:Me(this,ss)[r++],done:!1};if(Me(this,Ic)){if(Me(this,sh))throw Me(this,sh);return{value:void 0,done:!0}}await new Promise(n=>Me(this,Oy).push(n))}}}}toAsyncIterable(e=0){return{[Symbol.asyncIterator]:()=>this.iterate(e)}}toEventStream(e={}){let r=new TextEncoder,n=this.iterate(e.startAt),i=e.event??this.channelName,o=e.serialize??(a=>JSON.stringify(a)??"null");return new ReadableStream({async pull(a){try{let s=await n.next();if(s.done){a.close();return}let l=[];i!=null&&l.push(`event: ${i}`);for(let u of o(s.value).split(/\r\n|\r|\n/))l.push(`data: ${u}`);a.enqueue(r.encode(`${l.join(`
@@ -437,9 +437,9 @@ NodeInterrupt should only be thrown inside a node, not in edge conditions.`),i}}
437
437
  `);return a===-1?"":i.stack.slice(a+1)})();try{if(!n.stack)n.stack=o;else if(o){let a=o.indexOf(`
438
438
  `),s=a===-1?-1:o.indexOf(`
439
439
  `,a+1),l=s===-1?"":o.slice(s+1);String(n.stack).endsWith(l)||(n.stack+=`
440
- `+o)}}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=oo(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&om.assertOptions(n,{silentJSONParsing:ki.transitional(ki.boolean),forcedJSONParsing:ki.transitional(ki.boolean),clarifyTimeoutError:ki.transitional(ki.boolean),legacyInterceptorReqResOrdering:ki.transitional(ki.boolean)},!1),i!=null&&(F.isFunction(i)?r.paramsSerializer={serialize:i}:om.assertOptions(i,{encode:ki.function,serialize:ki.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),om.assertOptions(r,{baseUrl:ki.spelling("baseURL"),withXsrfToken:ki.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let a=o&&F.merge(o.common,o[r.method]);o&&F.forEach(["delete","get","head","post","put","patch","query","common"],g=>{delete o[g]}),r.headers=hr.concat(a,o);let s=[],l=!0;this.interceptors.request.forEach(function(y){if(typeof y.runWhen=="function"&&y.runWhen(r)===!1)return;l=l&&y.synchronous;let _=r.transitional||ud;_&&_.legacyInterceptorReqResOrdering?s.unshift(y.fulfilled,y.rejected):s.push(y.fulfilled,y.rejected)});let u=[];this.interceptors.response.forEach(function(y){u.push(y.fulfilled,y.rejected)});let c,d=0,h;if(!l){let g=[Bb.bind(this),void 0];for(g.unshift(...s),g.push(...u),h=g.length,c=Promise.resolve(r);d<h;)c=c.then(g[d++],g[d++]);return c}h=s.length;let m=r;for(;d<h;){let g=s[d++],y=s[d++];try{m=g(m)}catch(_){y.call(this,_);break}}try{c=Bb.call(this,m)}catch(g){return Promise.reject(g)}for(d=0,h=u.length;d<h;)c=c.then(u[d++],u[d++]);return c}getUri(e){e=oo(this.defaults,e);let r=im(e.baseURL,e.url,e.allowAbsoluteUrls);return em(r,e.params,e.paramsSerializer)}};F.forEach(["delete","get","head","options"],function(e){hd.prototype[e]=function(r,n){return this.request(oo(n||{},{method:e,url:r,data:(n||{}).data}))}});F.forEach(["post","put","patch","query"],function(e){function r(n){return function(o,a,s){return this.request(oo(s||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}hd.prototype[e]=r(),e!=="query"&&(hd.prototype[e+"Form"]=r(!0))});var am=hd;p();var YE=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,a=new Promise(s=>{n.subscribe(s),o=s}).then(i);return a.cancel=function(){n.unsubscribe(o)},a},e(function(o,a,s){n.reason||(n.reason=new Oo(o,a,s),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},BD=YE;p();function JE(t){return function(r){return t.apply(null,r)}}p();function XE(t){return F.isObject(t)&&t.isAxiosError===!0}p();var QE={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(QE).forEach(([t,e])=>{QE[e]=t});var zD=QE;function VD(t){let e=new am(t),r=Kh(am.prototype.request,e);return F.extend(r,am.prototype,e,{allOwnKeys:!0}),F.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return VD(oo(t,i))},r}var Tr=VD(dd);Tr.Axios=am;Tr.CanceledError=Oo;Tr.CancelToken=BD;Tr.isCancel=rm;Tr.VERSION=fd;Tr.toFormData=ll;Tr.AxiosError=$e;Tr.Cancel=Tr.CanceledError;Tr.all=function(e){return Promise.all(e)};Tr.spread=JE;Tr.isAxiosError=XE;Tr.mergeConfig=oo;Tr.AxiosHeaders=hr;Tr.formToJSON=t=>qb(F.isHTMLForm(t)?new FormData(t):t);Tr.getAdapter=Fb.getAdapter;Tr.HttpStatusCode=zD;Tr.default=Tr;var Vb=Tr;var{Axios:l6e,AxiosError:u6e,CanceledError:c6e,isCancel:d6e,CancelToken:p6e,VERSION:f6e,all:h6e,Cancel:m6e,isAxiosError:g6e,spread:y6e,toFormData:_6e,AxiosHeaders:b6e,HttpStatusCode:v6e,formToJSON:w6e,getAdapter:S6e,mergeConfig:T6e,create:k6e}=Vb;var ZD="0.2.32";var EX=`keyring-agent-core/${ZD} (Keyring Chatbot Agent; +https://keyring.app)`,AX=3e4,CX=typeof process<"u"&&process.versions?.node!=null,eA=class{constructor(e={}){f(this,"instance");this.instance=Vb.create({baseURL:e.baseURL,timeout:e.timeout??AX,validateStatus:()=>!0,headers:{Accept:"application/json",...CX?{"User-Agent":e.userAgent??EX}:{},...e.headers}})}async request(e,r,n,i={}){let o=await this.instance.request({...i,method:e,url:r,data:n}),a={};for(let[s,l]of Object.entries(o.headers??{}))l!=null&&(a[s.toLowerCase()]=String(l));return{ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,data:o.data,headers:a}}get(e,r){return this.request("GET",e,void 0,r)}post(e,r,n){return this.request("POST",e,r,n)}put(e,r,n){return this.request("PUT",e,r,n)}patch(e,r,n){return this.request("PATCH",e,r,n)}delete(e,r){return this.request("DELETE",e,void 0,r)}},Fe=new eA;function dt(t){let{data:e,status:r,statusText:n}=t,i=n?`HTTP ${r} ${n}`:`HTTP ${r}`;if(typeof e=="string")return e.trim()||i;if(e&&typeof e=="object"){let o=e,a=l=>l&&typeof l=="object"?l.message:void 0,s=[o.message,o.errorMessage,o.error,o.error_description,o.detail,a(o.error),a(o.data)];for(let l of s)if(typeof l=="string"&&l.trim())return l.trim()}return i}p();var Du=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function md(t){if(!t||typeof t!="object")return!1;let e=t;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function tA(t){if(t?.aborted)throw new Du}function HD(t,e){if(!e)return{signal:t.signal,cleanup:()=>{}};if(e.aborted)return t.abort(),{signal:t.signal,cleanup:()=>{}};let r=()=>t.abort();return e.addEventListener("abort",r),{signal:t.signal,cleanup:()=>e.removeEventListener("abort",r)}}var WD={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},xX="https://nft.keyring.app/api/gemini-stable",IX=new Set([408,429,500,502,503,504]),GD=3e4,Zb=t=>new Promise(e=>setTimeout(e,t));function Hb(t,e,r){if(r!=null&&r>0)return Math.min(r,GD);let n=Math.min(e*2**(t-1),GD);return n/2+Math.random()*(n/2)}function OX(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var rn=class{constructor(e){f(this,"model");f(this,"maxTokens");f(this,"temperature");f(this,"baseUrl");f(this,"requestSignal");this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.baseUrl=e.baseUrl??xX}setRequestSignal(e){this.requestSignal=e}async chat(e,r,n){let{systemInstruction:i,contents:o}=this.toContents(e),{maxRetries:a=5,retryDelayMs:s=1e3}=n??{},l=n?.signal??this.requestSignal;tA(l);let u=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of u){let g=m.parts.map(y=>y.functionCall?`fc:${y.functionCall.name}`:y.functionResponse?`fr:${y.functionResponse.name}`:`text:${(y.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${g}]`)}}let c={contents:u,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};i&&(c.systemInstruction=i),r?.length?(c.tools=[{functionDeclarations:this.toFunctionDeclarations(r)}],n?.forceToolUse&&(c.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(c.tools=[{googleSearch:{}}]);let d=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,h="Unknown error";for(let m=1;m<=a;m++){tA(l);let g;try{g=await Fe.post(d,c,{headers:{"Content-Type":"application/json"},signal:l})}catch(C){if(md(C))throw C;if(h=C instanceof Error?C.message:String(C),m>=a)break;await Zb(Hb(m,s));continue}if(!g.ok){let C=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(h=`Gemini proxy error ${g.status}: ${C}`,!IX.has(g.status))throw new Error(h);if(m>=a)break;let R=OX(g.headers["retry-after"]??null);await Zb(Hb(m,s,R));continue}if(g.data==null||typeof g.data!="object"){if(h="Gemini proxy returned invalid JSON",m>=a)break;await Zb(Hb(m,s));continue}let y=g.data,_=y.candidates?.[0];if(!_)return{text:"",toolCalls:[]};let b="",w=[],T=_.content?.parts;if(!Array.isArray(T)||T.length===0){let C=_.finishReason;if(!(C==="SAFETY"||C==="RECITATION")&&m<a){h=`Gemini returned an empty turn (finishReason=${C??"none"})`,await Zb(Hb(m,s));continue}return{text:"",toolCalls:[]}}for(let C of T)C.text&&(b+=C.text),C.functionCall&&w.push({toolName:C.functionCall.name,args:C.functionCall.args??{},callId:C.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let E=y.usageMetadata?{promptTokens:y.usageMetadata.promptTokenCount??0,completionTokens:y.usageMetadata.candidatesTokenCount??0,totalTokens:y.usageMetadata.totalTokenCount??0}:void 0;return{text:b,toolCalls:w,usage:E}}throw new Error(h)}toContents(e){let r=[],n=[];for(let s of e){if(s.role==="system"){r.push(s.content);continue}if(s.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:s.toolName??"unknown",response:{result:s.content},...s.toolCallId?{id:s.toolCallId}:{}}}]});continue}if(s.role==="assistant"&&s.toolCalls?.length){n.push({role:"model",parts:s.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:s.role==="assistant"?"model":"user",parts:[{text:s.content}]})}let i=[];for(let s of n){let l=i[i.length-1],u=s.parts.some(d=>d.functionCall),c=l?.parts.some(d=>d.functionCall);l&&l.role===s.role&&!u&&!c?l.parts.push(...s.parts):i.push({...s,parts:[...s.parts]})}let o=[];for(let s=0;s<i.length;s++){let l=i[s],u=o[o.length-1];l.role==="function"&&!u?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(i[s+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:r.length?{role:"user",parts:[{text:r.join(`
441
- `)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(r=>{let n={},i=[];for(let o of r.parameters){let a={type:WD[o.type]??"STRING",description:o.description};o.type==="array"&&(a.items={type:WD[o.items?.type??"string"]??"STRING"}),n[o.name]=a,o.required&&i.push(o.name)}return{name:r.name,description:r.description,parameters:{type:"OBJECT",properties:n,required:i}}})}};p();var gd=class{constructor(){f(this,"tools",new Map)}register(e){if(this.tools.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getDefinitions(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,parameters:e.parameters,category:e.category,kind:e.kind}))}getDefinitionsByCategory(e){return this.getDefinitions().filter(r=>r.category===e)}async execute(e,r,n){let i=this.tools.get(e);if(!i)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let o=Date.now();try{return{...await i.execute(r,n),duration:Date.now()-o}}catch(a){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-o}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};p();p();p();p();p();var yd=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708"],RX=new Set(yd),ul=[...yd],KD=new Set(ul),Ro="0x1",Uu="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea";function NX(t){return t.map(e=>bd[e]??e).join(", ")}function Wb(t){let e=new Set;if(t)for(let n of t){let i=Gb(n);i&&e.add(i)}let r=yd.filter(n=>!e.has(n));ul=r.length>0?[...r]:[...yd],KD=new Set(ul),Ro=ul.includes("0x1")?"0x1":ul[0],Uu=NX(ul)}var $X={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708"};function Ln(t){let e=Gb(t);return e&&KD.has(e)?e:null}function Gb(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let r=$X[e];if(r)return r;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&RX.has(n)?n:null}function Kb(t){return Ln(t)!==null}function Pi(){return[...ul]}var _d=class extends Error{constructor(r){super(`Chain "${r}" is not supported. Supported chains: ${Uu}.`);f(this,"requested",r);f(this,"code","unsupported_chain");this.name="UnsupportedChainError"}},cl=t=>typeof t=="string"&&t.trim()!=="";function jn(t,e){if(cl(t)){let r=Ln(t);if(r)return r;throw new _d(t.trim())}if(cl(e?.chain)){let r=Ln(e.chain);if(r)return r;throw new _d(e.chain.trim())}return null}function Yb(t,e){return Ln(t)??Ln(e?.chain)??void 0}var bd={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea"};function Ye(t){let e=Gb(t);return e&&bd[e]?bd[e]:typeof t=="string"&&t.trim()?t.trim():"the requested chain"}var MX={"0x1":"https://etherscan.io","0xa":"https://optimistic.etherscan.io","0x38":"https://bscscan.com","0x89":"https://polygonscan.com","0x2105":"https://basescan.org","0xa4b1":"https://arbiscan.io","0xa86a":"https://snowtrace.io","0xe708":"https://lineascan.build"};function YD(t,e){let r=Gb(t),n=r?MX[r]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var DX={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a"};function JD(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();return e?DX[e]??null:null}var UX={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH"};function XD(t){let e=Ln(t);return e?UX[e]??null:null}function vd(t,e){if(!cl(t))return null;let r=Ln(t),n=Ln(e?.chain);return!r||!n||r===n?null:{requested:r,connected:n,requestedLabel:bd[r]??r,connectedLabel:bd[n]??n}}function QD(t){let e=typeof t=="string"?t.trim():"";return ul.map(r=>{let n=bd[r]??r;return{label:n,prompt:e?`${e} (${n})`:n}})}function wd(t,e){return{actionButtons:QD(e),_instructions:`The user wants to ${t} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var Ir=class extends Error{constructor(r){super("Wallet is connected but no chain is set \u2014 ask the user to pick one.");f(this,"code","needs_chain_selection");f(this,"buttons");this.name="NeedsChainSelectionError",this.buttons=QD(r)}},sm=class extends Error{constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one.");f(this,"code","no_wallet_connected");this.name="NoWalletConnectedError"}};function kr(t,e){if(cl(t))return t.trim();if(cl(e?.walletAddress))return e.walletAddress.trim();throw new sm}function vt(t,e){if(cl(t)){let r=Ln(t);if(r)return r;throw new _d(t.trim())}if(cl(e?.chain)){let r=Ln(e.chain);if(r)return r;throw new _d(e.chain.trim())}if(cl(e?.walletAddress))throw new Ir(typeof e?.query=="string"?e.query:void 0);return Ro}var oe=class{constructor(){f(this,"category")}async execute(e,r){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,i=Date.now();try{let o=await this.run(e,r),a=qX(o);return{toolName:this.name,callId:n,success:!0,data:a.data,duration:Date.now()-i,...a.actionButtons?{actionButtons:a.actionButtons}:{}}}catch(o){return o instanceof Ir?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-i,actionButtons:o.buttons}:o instanceof sm?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has not connected a wallet. In the user's language, tell them this action needs a wallet \u2014 they can either connect their wallet or include a wallet address (0x\u2026) directly in their question. Keep it short and friendly."},duration:Date.now()-i}:{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-i}}}};function qX(t){if(!t||typeof t!="object")return{data:t};let e=t,r=e.actionButtons;if(!Array.isArray(r)||r.length===0)return{data:t};let{actionButtons:n,...i}=e;return{data:i,actionButtons:r}}p();p();var eU=eb(Xb());function zt(t){return typeof t=="string"&&/^0x[0-9a-fA-F]{40}$/.test(t)}function LX(t){return new Uint8Array(eU.keccak256.arrayBuffer(t))}function lm(t){let e=t.startsWith("0x")?t.slice(2):t,r=e.length%2?"0"+e:e,n=new Uint8Array(r.length/2);for(let i=0;i<n.length;i++)n[i]=parseInt(r.slice(i*2,i*2+2),16);return n}function tU(t){return"0x"+Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function rU(t){return new TextEncoder().encode(t)}function qu(...t){let e=t.reduce((i,o)=>i+o.length,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function jX(t,e=32){let r=new Uint8Array(e);return r.set(t,e-t.length),r}function FX(t,e=32){let r=new Uint8Array(e);return r.set(t),r}function nU(t){let e=((t%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return lm(e)}function um(t){return nU(BigInt(t))}function iU(t){return t==="uint"?"uint256":t==="int"?"int256":t.match(/^uint$/)?"uint256":t.match(/^int$/)?"int256":t.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function oU(t){let e=iU(t.type);if(e==="tuple"||e.startsWith("tuple[")){let r=(t.components??[]).map(oU).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${r})${n}`}return e}function BX(t){let e=(t.inputs??[]).map(oU).join(",");return`${t.name??""}(${e})`}function rA(t,e){let r=ZX(t.type);if(r){let[i,o]=r;return zX({...t,type:o},e,i)}if(t.type==="tuple")return VX(t,e);if(t.type==="address"){let i=String(e),o=i.startsWith("0x")?i.slice(2):i;return{dynamic:!1,encoded:jX(lm(o.toLowerCase()))}}if(t.type==="bool"){let i=new Uint8Array(32);return i[31]=e?1:0,{dynamic:!1,encoded:i}}let n=iU(t.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:um(BigInt(e))};if(/^int\d*$/.test(n)){let i=BigInt(e);return i<0n&&(i=i+(1n<<256n)),{dynamic:!1,encoded:nU(i)}}if(/^bytes(\d+)$/.test(n)){let i=parseInt(n.slice(5),10),o=typeof e=="string"?lm(e):e;if(o.length!==i)throw new Error(`bytes${i} expects exactly ${i} bytes, got ${o.length}`);return{dynamic:!1,encoded:FX(o)}}if(n==="bytes"){let i=typeof e=="string"?lm(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:qu(um(i.length),a)}}if(n==="string"){let i=typeof e=="string"?rU(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:qu(um(i.length),a)}}throw new Error(`Unsupported ABI type: ${t.type}`)}function nA(t){let e=0;for(let{dynamic:o,encoded:a}of t)e+=o?32:a.length;let r=[],n=[],i=0;for(let{dynamic:o,encoded:a}of t)o?(r.push(um(e+i)),n.push(a),i+=a.length):r.push(a);return qu(...r,...n)}function zX(t,e,r){let n=r===null;if(!n&&e.length!==r)throw new Error(`Array length mismatch: expected ${r}, got ${e.length}`);let i=!1,o=[];for(let a of e){let s=rA(t,a);s.dynamic&&(i=!0),o.push(s)}if(n||i){let a=nA(o);if(n){let s=um(o.length);return{dynamic:!0,encoded:o.length>0?qu(s,a):s}}return{dynamic:!0,encoded:a}}return{dynamic:!1,encoded:qu(...o.map(a=>a.encoded))}}function VX(t,e){let r=t.components??[],n=!1,i=[];for(let o=0;o<r.length;o++){let a=r[o],s=Array.isArray(e)?e[o]:e[a.name??""],l=rA(a,s);l.dynamic&&(n=!0),i.push(l)}return{dynamic:n,encoded:n?nA(i):qu(...i.map(o=>o.encoded))}}function ZX(t){let e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function HX(t,e){if(t.length!==e.length)throw new Error(`Expected ${t.length} values, got ${e.length}`);if(t.length===0)return"0x";let r=t.map((i,o)=>rA(i,e[o])),n=nA(r);return tU(n)}function Sd({abi:t,functionName:e,args:r=[]}){let n=t.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let i=BX(n),o=LX(rU(i)).slice(0,4),a=n.inputs??[],s=a.length===0||r.length===0?new Uint8Array(0):lm(HX(a,r).slice(2));return tU(qu(o,s))}p();var WX="https://wallet-api.pantograph.app",GX="0x0000000000000000000000000000000000000000",lU={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},uU={"0x1":["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"],"0xa":["0x4200000000000000000000000000000000000006","0x68f180fcce6836688e9084f035309e29bf0a2095","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0x38":["0x2170ed0880ac9a755fd29b2688956bd959f933f8","0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c"],"0x89":["0x7ceb23fd6bc0add59e62ac25578270cff1b9f619","0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6"],"0x2105":["0x4200000000000000000000000000000000000006","0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0xa4b1":["0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f"],"0xa86a":["0x49d5c2bdffac6ce2bfdb6640f4f80f226bc10bab","0x0555e30da8f98308edb960aa94c0db47230d2b9c"],"0xe708":["0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f","0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4"]};function cm(t){return lU[t.toLowerCase()]||t}function aU(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function iA(t){let e=t,r=e.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):NaN,i=e.price,o=i!=null?parseFloat(String(i)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function wn(t){if(t==null)return null;let e=typeof t=="number"?t:parseFloat(String(t));return Number.isFinite(e)?e:null}function sU(t,e){let r=t.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):null,i=wn(t.price_change_percentage_24h)??wn(t.priceChange24h)??wn(t.usd_price_24hr_percent_change)??wn(t.price_change_24h)??wn(t.priceChange);return{chainId:e,tokenAddress:t.address??t.token_address??"",name:t.name??null,symbol:t.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:t.logoURI??t.icon_image??t.logo??null,usdPrice:wn(t.price)??wn(t.usd_price),marketCap:wn(t.market_cap)??wn(t.marketCap),totalVolume:{"24h":wn(t.total_volume)??wn(t.volume24h)},pricePercentChange:{"24h":i}}}var Sn=class{constructor(e){f(this,"baseUrl");this.baseUrl=(e?.baseUrl??WX).replace(/\/+$/,"")}async enrichTokenPrices(e,r){if(e.length!==0)try{let n=cm(r),i=e.map(c=>c.token_address).join(","),o=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(i)}`,a=await Fe.get(o);if(!a.ok)return;let s=a.data,l=Array.isArray(s)?s:Array.isArray(s.data)?s.data:[],u=new Map;for(let c of l)c.address&&u.set(c.address.toLowerCase(),{price:c.price!=null?parseFloat(String(c.price)):NaN,icon_image:c.icon_image});for(let c=0;c<e.length;c++){let d=u.get(e[c].token_address.toLowerCase());d&&(d.icon_image&&(e[c].logo=d.icon_image,e[c].thumbnail=d.icon_image),isNaN(d.price)||(e[c].usd_price=d.price,e[c].usd_value=parseFloat(e[c].balance_formatted||"0")*d.price))}}catch{}}async getTokenMetadata(e,r){try{let n=cm(r),i=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(e)}`,o=await Fe.get(i);if(!o.ok)return null;let a=o.data,s=Array.isArray(a)?a:Array.isArray(a.data)?a.data:[],l=e.toLowerCase()===GX,u=s.find(c=>c.address?.toLowerCase()===e.toLowerCase()||l&&c.address===""||c.token_address?.toLowerCase()===e.toLowerCase()||l&&c.token_address==="");return u?iA(u):null}catch{return null}}async getTokensMetadata(e,r){let n={};if(e.length===0)return n;try{let i=cm(r),o=`${this.baseUrl}/keyrings/tokens/${i}/v2?addresses=${encodeURIComponent(e.join(","))}`,a=await Fe.get(o);if(!a.ok)return n;let s=a.data,l=Array.isArray(s)?s:Array.isArray(s.data)?s.data:[],u=new Set(e.map(c=>c.toLowerCase()));for(let c of l){let d=c.address?.toLowerCase()||c.token_address?.toLowerCase()||(c.address===""?"":null);d&&u.has(d)&&(n[d]=iA(c))}}catch{}return n}async searchTokensByKey(e){let{key:r,chain:n}=e;if(!r)return{success:!1,error:"Search key is required"};let o=parseInt(n||Ro,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=aU({chainId:o,key:r}),s=`${this.baseUrl}/token-list?${a}`,l=await Fe.get(s);if(!l.ok)throw new Error(dt(l));let u=l.data,c=[];return u?.data?c=Array.isArray(u.data)?u.data:Object.values(u.data).flat():typeof u=="object"&&!Array.isArray(u)&&(c=Object.values(u).flat()),{success:!0,data:c.map(iA)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let r=e?.chain||Ro,n=5,i=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=uU[r.toLowerCase()]??[],a=i!=null?i+o.length:n+o.length,[s,l]=await Promise.allSettled([this.fetchTopGainers(r,a),o.length>0?this.getTokensMetadata(o,r):Promise.resolve({})]),u=s.status==="fulfilled"?s.value:[],c=l.status==="fulfilled"?o.map(y=>l.value[y.toLowerCase()]).filter(y=>y!=null).map(y=>sU(y,r)):[],d=new Set,h=[];for(let y of c){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),h.push(y))}let m=[];for(let y of u){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),m.push(y))}let g=i!=null?[...h,...m].slice(0,i):[...h,...m.slice(0,n)];return await this.enrichTrendingMarketData(g,r),{success:!0,data:g}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,r){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let i=await this.getTokensMetadata(n.map(o=>o.tokenAddress),r);for(let o of n){let a=i[o.tokenAddress.toLowerCase()];a&&(o.marketCap==null&&(o.marketCap=wn(a.market_cap)??wn(a.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":wn(a.total_volume)??wn(a.volume24h)}))}}async fetchTopGainers(e,r,n="24h"){let i=cm(e),o=aU({duration:n,limit:r}),a=`${this.baseUrl}/token-list/top-gainers/${i}${o?`?${o}`:""}`,s=[];for(let l=0;l<5;l++){let u=await Fe.get(a);if(!u.ok)throw new Error(dt(u));let c=u.data;if(s=Array.isArray(c)?c:Array.isArray(c.data)?c.data:[],s.length>0)break;l<4&&await new Promise(d=>setTimeout(d,2e3))}return s.map(l=>sU(l,e))}async getTopGainers(e){let r=e?.chain||Ro,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,i=e?.duration||"24h";try{let o=await this.fetchTopGainers(r,n,i);return await this.enrichTrendingMarketData(o,r),{success:!0,data:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}};var KX="https://nft.keyring.app",YX="https://nft.keyring.app",JX=.01,tt=5,ir=1e3,XX="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",QX="0x0000000000000000000000000000000000000000",rt=class extends Error{constructor(r,n){super(n);f(this,"status",r);this.name="MoralisHttpError"}};function mr(t){return t||Ro}function or(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function ar(t){return new Promise(e=>setTimeout(e,t))}function eQ(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result.map(r=>({protocol_id:r.protocolId,protocol_name:r.protocolName,protocol_url:r.protocolUrl??"",protocol_logo:r.protocolLogo??"",position:{label:r.position.label,address:r.position.address,balance_usd:r.position.balanceUsd??0,total_unclaimed_usd_value:r.position.unclaimedUsd??0,position_details:r.position.details,tokens:r.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}function oA(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result:Object.keys(e).filter(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}var pt=class{constructor(e){f(this,"baseUrl");f(this,"v1BaseUrl");f(this,"pantograph");this.baseUrl=(e?.baseUrl??KX).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??YX).replace(/\/+$/,""),this.pantograph=new Sn({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:r,chain:n,tokenAddresses:i,excludeSpam:o=!1,excludeUnverifiedContracts:a=!1}=e;if(!r)return{success:!1,error:"Address is required"};let s=mr(n),l="Unknown error";for(let u=1;u<=tt;u++)try{let c={chain:s,exclude_spam:o,exclude_unverified_contracts:a,limit:100};i&&(c.token_addresses=i);let d=[],h=null;do{h&&(c.cursor=h);let g=or(c),y=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/tokens?${g}`,_=await Fe.get(y);if(!_.ok)throw new rt(_.status,dt(_));let b=_.data,w=b?.data??b;w?.result?.length>0&&d.push(...w.result),h=w?.cursor??null}while(h);let m={result:d};return m?.result?.length>0&&(m.result=m.result.filter(g=>parseFloat(g.balance||"0")>0),m.result=m.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===XX?QX:g.token_address})),await this.enrichTokenPrices(m.result,s),m.result=m.result.filter(g=>g.usd_value==null||g.usd_value>=JX)),{success:!0,data:m}}catch(c){if(l=c instanceof Error?c.message:"Unknown error",c instanceof rt&&c.status===400)break;u<tt&&await ar(ir)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token address is required"};let i=mr(n),o="Unknown error",a=await this.pantograph.getTokenMetadata(r,i);if(a)return{success:!0,data:a};for(let s=1;s<=tt;s++)try{let[l,u]=await Promise.allSettled([Fe.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${or({chain:i,addresses:[r]})}`),Fe.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/price?${or({chain:i,include:"percent_change"})}`)]),c=null;if(l.status==="fulfilled"&&l.value.ok){let h=l.value.data;c=(Array.isArray(h)?h:Array.isArray(h?.data)?h.data:[])[0]??null}if(!c){o="Token metadata not found",s<tt&&await ar(ir);continue}let d=null;if(u.status==="fulfilled"&&u.value.ok){let h=u.value.data;d=h?.data??h}return{success:!0,data:{...c,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof rt&&l.status===400)break;s<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:r,chain:n,limit:i=10,excludeSpam:o=!0,cursor:a,tokenAddresses:s,includePrices:l,format:u="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};let c=mr(n),d="Unknown error";for(let h=1;h<=tt;h++)try{let m={chain:c,format:u,limit:i,exclude_spam:o,media_items:!0,normalizeMetadata:!0};a&&(m.cursor=a),l&&(m.include_prices=!0),s&&s.length>0&&(m.token_addresses=s);let g=or(m),y=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft?${g}`,_=await Fe.get(y);if(!_.ok)throw new rt(_.status,dt(_));let b=_.data;return{success:!0,data:b?.data??b}}catch(m){if(d=m instanceof Error?m.message:"Unknown error",m instanceof rt&&m.status===400)break;h<tt&&await ar(ir)}return{success:!1,error:d}}async getNftMetadata(e){let{address:r,tokenId:n,chain:i,format:o="decimal",normalizeMetadata:a=!0,mediaItems:s=!0,include:l}=e;if(!r)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!zt(r))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let u=mr(i),c="Unknown error";for(let d=1;d<=tt;d++)try{let h={chain:u,format:o,normalizeMetadata:a,media_items:s};l&&(h.include=l);let m=or(h),g=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/${encodeURIComponent(n)}?${m}`,y=await Fe.get(g);if(!y.ok)throw new rt(y.status,dt(y));let _=y.data;return{success:!0,data:_?.data??_}}catch(h){if(c=h instanceof Error?h.message:"Unknown error",h instanceof rt&&h.status===400)break;d<tt&&await ar(ir)}return{success:!1,error:c}}async getNftContractMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};let i=mr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/metadata?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletHistory(e){let{address:r,chain:n,limit:i=25,fromDate:o,toDate:a,fromBlock:s,toBlock:l,cursor:u,order:c="DESC",includeInternalTransactions:d,nftMetadata:h}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=mr(n),g=Math.max(1,Math.min(100,Math.floor(i))),y="Unknown error";for(let _=1;_<=tt;_++)try{let b={chain:m,limit:g,order:c};o&&(b.from_date=o),a&&(b.to_date=a),s!=null&&(b.from_block=s),l!=null&&(b.to_block=l),u&&(b.cursor=u),d!=null&&(b.include_internal_transactions=d),h!=null&&(b.nft_metadata=h);let w=or(b),T=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/history?${w}`,E=await Fe.get(T);if(!E.ok)throw new rt(E.status,dt(E));let C=E.data;return{success:!0,data:C?.data??C}}catch(b){if(y=b instanceof Error?b.message:"Unknown error",b instanceof rt&&b.status===400)break;_<tt&&await ar(ir)}return{success:!1,error:y}}async getWalletTokenTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:u,cursor:c,order:d="DESC"}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let h=mr(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=tt;y++)try{let _={chain:h,limit:m,order:d};a&&(_.from_date=a),s&&(_.to_date=s),l!=null&&(_.from_block=l),u!=null&&(_.to_block=u),c&&(_.cursor=c),i?.length&&(_.contract_addresses=i);let b=or(_),w=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/erc20/transfers?${b}`,T=await Fe.get(w);if(!T.ok)throw new rt(T.status,dt(T));let E=T.data;return{success:!0,data:E?.data??E}}catch(_){if(g=_ instanceof Error?_.message:"Unknown error",_ instanceof rt&&_.status===400)break;y<tt&&await ar(ir)}return{success:!1,error:g}}async getWalletNftTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:u,cursor:c,order:d="DESC",includePrices:h,format:m="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let g=mr(n),y=Math.max(1,Math.min(100,Math.floor(o))),_="Unknown error";for(let b=1;b<=tt;b++)try{let w={chain:g,limit:y,order:d,format:m};a&&(w.from_date=a),s&&(w.to_date=s),l!=null&&(w.from_block=l),u!=null&&(w.to_block=u),c&&(w.cursor=c),i?.length&&(w.contract_addresses=i),h!=null&&(w.include_prices=h);let T=or(w),E=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/transfers?${T}`,C=await Fe.get(E);if(!C.ok)throw new rt(C.status,dt(C));let R=C.data;return{success:!0,data:R?.data??R}}catch(w){if(_=w instanceof Error?w.message:"Unknown error",w instanceof rt&&w.status===400)break;b<tt&&await ar(ir)}return{success:!1,error:_}}async getTokenHolders(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};if(!zt(r))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/holders?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:r,chain:n,days:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=mr(n),a="Unknown error";for(let s=1;s<=tt;s++)try{let l={chain:o};i&&(l.days=i);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability/summary?${u}`,d=await Fe.get(c);if(!d.ok)throw new rt(d.status,dt(d));let h=d.data;return{success:!0,data:h?.data??h}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof rt&&l.status===400)break;s<tt&&await ar(ir)}return{success:!1,error:a}}async getWalletPnl(e){let{address:r,chain:n,days:i,tokenAddresses:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=mr(n),s="Unknown error";for(let l=1;l<=tt;l++)try{let u={chain:a};i&&(u.days=i),o&&o.length>0&&(u.token_addresses=o.slice(0,25));let c=or(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability?${c}`,h=await Fe.get(d);if(!h.ok)throw new rt(h.status,dt(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(u){if(s=u instanceof Error?u.message:"Unknown error",u instanceof rt&&u.status===400)break;l<tt&&await ar(ir)}return{success:!1,error:s}}async getTransactionByHash(e){let{transactionHash:r,chain:n}=e;if(!r)return{success:!1,error:"Transaction hash is required"};let i=mr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(r)}/verbose?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:r,chain:n,limit:i,cursor:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=mr(n),s="Unknown error";for(let l=1;l<=tt;l++)try{let u={chain:a};i!=null&&(u.limit=i),o&&(u.cursor=o);let c=or(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/approvals?${c}`,h=await Fe.get(d);if(!h.ok)throw new rt(h.status,dt(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(u){if(s=u instanceof Error?u.message:"Unknown error",u instanceof rt&&u.status===400)break;l<tt&&await ar(ir)}return{success:!1,error:s}}async getWalletDefiSummary(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/summary?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/positions?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data,d=c?.data??c;return{success:!0,data:eQ(d)}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:r,protocol:n,chain:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!zt(r))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=mr(i),a="Unknown error";for(let s=1;s<=tt;s++)try{let l=or({chains:o}),u=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/${encodeURIComponent(n)}/positions?${l}`,c=await Fe.get(u);if(!c.ok)throw new rt(c.status,dt(c));let m=c.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(y=>({label:y.label,address:y.address,balance_usd:y.balanceUsd??0,total_unclaimed_usd_value:y.unclaimedUsd??0,position_details:y.details,tokens:y.tokens.map(_=>({token_type:_.tokenType,address:_.address,contract_address:_.address,name:_.name??"",symbol:_.symbol??"",decimals:_.decimals??18,logo:_.logo,balance:_.balance??"0",balance_formatted:_.balanceFormatted??"0",usd_price:_.usdPrice,usd_value:_.usdValue}))}))}}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof rt&&l.status===400)break;s<tt&&await ar(ir)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!zt(r))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/analytics?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getTokenScore(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!zt(r))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/score?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getTrendingTokens(e){let r=e?.chain,n=e?.limit,i="Unknown error";for(let o=1;o<=tt;o++)try{let a={};r&&(a.chain=mr(r)),n!=null&&(a.limit=n);let s=or(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${s?`?${s}`:""}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data,d=c?.data??c;return{success:!0,data:oA(d)}}catch(a){if(i=a instanceof Error?a.message:"Unknown error",a instanceof rt&&a.status===400)break;o<tt&&await ar(ir)}return{success:!1,error:i}}async getTopGainers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=tt;s++)try{let l={};r&&(l.chain=mr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${u?`?${u}`:""}`,d=await Fe.get(c);if(!d.ok)throw new rt(d.status,dt(d));let h=d.data,m=h?.data??h;return{success:!0,data:oA(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof rt&&l.status===400)break;s<tt&&await ar(ir)}return{success:!1,error:a}}async getTopLosers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=tt;s++)try{let l={};r&&(l.chain=mr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${u?`?${u}`:""}`,d=await Fe.get(c);if(!d.ok)throw new rt(d.status,dt(d));let h=d.data,m=h?.data??h;return{success:!0,data:oA(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof rt&&l.status===400)break;s<tt&&await ar(ir)}return{success:!1,error:a}}async enrichTokenPrices(e,r){return this.pantograph.enrichTokenPrices(e,r)}};var Td=class extends oe{constructor(r){super();f(this,"name","get-token-info");f(this,"description",'Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea');f(this,"category","blockchain-data");f(this,"parameters",[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,required:!0},{name:"buy_button_label",type:"string",description:`Label for the "Buy" suggestion button shown under the token info, IN THE USER'S CURRENT LANGUAGE. Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "Buy {token}". Vietnamese example: "Mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_prompt_template",type:"string",description:`A short "buy" command IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the Buy button is clicked. Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0}]);f(this,"service");f(this,"llm");this.service=new pt(r),this.llm=new rn({})}async run(r,n){let i=r.keyword||"",o=vt(r.chain,n),a=r.prompt||"",s=r.buy_button_label||"",l=r.buy_prompt_template||"",u=n?.walletAddress||void 0;return i?await this.searchToken(i,o,a,s,l,u):{error:"Missing required parameter: keyword"}}async execute(r,n){let i=await super.execute(r,n),o=i.data;return i.success&&o&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(i.actionButtons=o.actionButtons),i}async searchToken(r,n,i,o,a,s){let l=[s?`User's connected wallet address: ${s}`:null,n?`Current chain (hex chain ID): ${n}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
442
- `),[u,c,d]=await Promise.all([this.service.searchTokensByKey({key:r,chain:n}),s?this.findTokenInWallet(s,n,r):Promise.resolve(null),i?this.askGeminiWithSearch(i,l):Promise.resolve(null)]),h=u.success&&u.data?Array.isArray(u.data)?u.data:[]:[],m=r.toLowerCase(),g=C=>C.symbol?.toLowerCase()===m||C.token_address?.toLowerCase()===m,y=[...h].sort((C,R)=>(g(C)?0:1)-(g(R)?0:1)),_=null,b=y[0];if(b?.token_address){let C=await this.service.getTokenMetadata({address:b.token_address,chain:n});C.success&&C.data&&(_=C.data)}!_&&b&&(_={...b});let w=_?.symbol?.trim(),T=w?[{label:this.fillTemplate(o,w,"Buy {token}"),prompt:this.fillTemplate(a,w,"buy {token}")}]:[];return{_instructions:'Present the token info in a clear summary. Include: token name & symbol, contract address (shortened), current USD price, 24h price change % (prefix "+" for positive, "-" for negative), market cap, fully diluted valuation, 24h trading volume, liquidity, and holder count (if available). If the user holds this token, prominently show their balance and USD value. If research is present, weave its substance naturally into your answer \u2014 fold the relevant points into the description, context, and any notable news or risks. When the research explains WHY the price moved, surface that catalyst clearly (what happened, roughly when), summarize the most relevant recent news, and close with a brief, clearly-hedged sense of market direction (do not give financial advice or price predictions). Do NOT add a labelled "AI Analysis" section or any similar heading, and do NOT mention that the analysis came from AI; just write it as part of the token summary. Format numbers in a human-readable way (e.g. $1.23, +5.67%, $12.5M). If a field is null, omit it. A "Buy" button is shown below your reply automatically \u2014 do NOT mention it, list it, or repeat its text.',chain:n,userHoldsToken:!!c,walletBalance:c,token:_,...h.length>1?{searchResults:y.slice(0,10)}:{},research:d,...T.length>0?{actionButtons:T}:{}}}fillTemplate(r,n,i){return(r&&r.includes("{token}")?r:i).replace(/\{token\}/g,n).replace(/\s+/g," ").trim()}async askGeminiWithSearch(r,n){let i=Date.now();try{return(await this.llm.chat([...n?[{role:"system",content:n,timestamp:i}]:[],{role:"user",content:r,timestamp:i}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(r,n,i){if(!i)return null;let o=await this.service.getWalletTokenBalances({address:r,chain:n,excludeSpam:!0,excludeUnverifiedContracts:!0});if(!o.success||!o.data?.result)return null;let a=i.toLowerCase(),s=o.data.result.find(l=>l.token_address.toLowerCase()===a||l.symbol?.toLowerCase()===a||l.name?.toLowerCase().includes(a));return s||null}};p();var kd=class extends oe{constructor(r){super();f(this,"name","get-token-holders");f(this,"description",'Get holder statistics and analytics for an ERC-20 token. Returns: total holder count, holder count changes over time (5min/1h/6h/24h/3d/7d/30d), how holders acquired the token (swap/transfer/airdrop), supply concentration (% held by top 10/25/50/100/250/500 holders), and holder size distribution (whales, sharks, dolphins, fish, octopus, crabs, shrimps). Use tokenSymbol (e.g. "USDC") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How many holders does USDC have?" (tokenSymbol=USDC), "Is USDC gaining or losing holders?" (tokenSymbol=USDC \u2192 holderChange), "How many new holders did ETH get in the last 7 days?" (tokenSymbol=WETH), "How concentrated is USDC ownership?" (tokenSymbol=USDC \u2192 holderSupply), "What % of supply do the top 10 holders control?" (tokenSymbol=USDC), "How many whales hold USDT?" (tokenSymbol=USDT \u2192 holderDistribution), "Did most holders buy via swap or transfer?" (tokenSymbol=USDC \u2192 holdersByAcquisition). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea. ');f(this,"category","blockchain-data");f(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=vt(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let l,u;if(a){let h=await this.resolveContractAddress(a,i,o);if(!h)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Ye(i):"the selected chain"}. Try passing contractAddress directly.`};s=h.address,l=h.symbol,u=h.name}let c=await this.service.getTokenHolders({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let d=c.data;return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},totalHolders:d.totalHolders,holdersByAcquisition:d.holdersByAcquisition,holderChange:d.holderChange,holderSupply:d.holderSupply,holderDistribution:d.holderDistribution}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Pd=class extends oe{constructor(r){super();f(this,"name","get-token-analytics");f(this,"description",`Get detailed trading analytics for a single ERC-20 token, broken down across 5min / 1h / 6h / 24h windows. Returns: buy volume, sell volume, unique buyers, unique sellers, buy/sell transaction counts, unique wallets, price % change, current USD price, total liquidity and fully-diluted valuation (FDV). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How is PEPE trading today?" (tokenSymbol=PEPE), "24h buy vs sell volume for USDC?" (tokenSymbol=USDC \u2192 totalBuyVolume vs totalSellVolume), "Is buying or selling pressure stronger for this token?", "How many unique wallets touched this token in the last hour?" (\u2192 uniqueWallets.1h), "What's the FDV and liquidity of X?" (\u2192 totalFullyDilutedValuation, totalLiquidity), "Price change over 6h?" (\u2192 pricePercentChange.6h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=vt(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let l,u;if(a){let h=await this.resolveContractAddress(a,i,o);if(!h)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Ye(i):"the selected chain"}. Try passing contractAddress directly.`};s=h.address,l=h.symbol,u=h.name}let c=await this.service.getTokenAnalytics({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let d=c.data??{};return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},usdPrice:d.usdPrice??null,totalLiquidity:d.totalLiquidity??null,totalFullyDilutedValuation:d.totalFullyDilutedValuation??null,totalBuyVolume:d.totalBuyVolume??null,totalSellVolume:d.totalSellVolume??null,totalBuyers:d.totalBuyers??null,totalSellers:d.totalSellers??null,totalBuys:d.totalBuys??null,totalSells:d.totalSells??null,uniqueWallets:d.uniqueWallets??null,pricePercentChange:d.pricePercentChange??null}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Ed=class extends oe{constructor(r){super();f(this,"name","get-token-score");f(this,"description",`Get a composite 0\u2013100 health/safety score for a single ERC-20 token, plus the metrics behind it. Returns: overall score, last-updated timestamp, current USD price, paired liquidity, multi-timeframe volume buckets (10m / 30m / 1h / 4h / 12h / 1d / 7d / 30d), same buckets for transaction counts, and supply info (total supply + % held by top 10 holders). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "Is PEPE a safe token?" (tokenSymbol=PEPE \u2192 score), "What's the health/score of USDC?", "How concentrated is X's supply among whales?" (\u2192 metrics.supply.top10Percent), "How much volume did this token do over the last 7 days?" (\u2192 metrics.volumeUsd.7d), "Transaction count for this token in the last hour?" (\u2192 metrics.transactions.1h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=vt(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let l,u;if(a){let m=await this.resolveContractAddress(a,i,o);if(!m)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Ye(i):"the selected chain"}. Try passing contractAddress directly.`};s=m.address,l=m.symbol,u=m.name}let c=await this.service.getTokenScore({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token score"};let d=c.data??{},h=d.metrics??{};return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},score:d.score??null,updatedAt:d.updatedAt??null,metrics:{usdPrice:h.usdPrice??null,liquidityUsd:h.liquidityUsd??null,volumeUsd:h.volumeUsd??null,transactions:h.transactions??null,supply:h.supply??null}}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Ad=class extends oe{constructor(r){super();f(this,"name","get-trending-tokens");f(this,"description",'List tokens trending on-chain right now, ranked by trading activity, volume, liquidity and holder growth. Returns price, market cap, liquidity, holder count, and multi-timeframe buckets (1h / 4h / 12h / 24h) of price change, volume, transaction counts, and unique buyers/sellers. Cross-chain by default \u2014 omit `chain` for a global ranking, or pass it to filter to one network. Use this tool for questions like: "What tokens are trending right now?", "Show me hot tokens", "What\'s popular on Base today?", "Which tokens have the highest 24h volume?", "Biggest movers in the last hour?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, and more.');f(this,"category","blockchain-data");f(this,"parameters",[{name:"chain",type:"string",description:'Optional hex chain ID to scope results to a single network: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user names a chain. Omit to return cross-chain trending results.',required:!1},{name:"limit",type:"number",description:'Total number of trending tokens to return (chain default tokens + top gainers combined). Only set this when the user asks for a specific count (e.g. "show 20 trending tokens" \u2192 20). Omit otherwise \u2014 when omitted, returns all default tokens plus 5 top gainers.',required:!1},{name:"buy_button_label",type:"string",description:`Label template for the per-token "Buy" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. One button is rendered per trending token, with "{token}" replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "Buy {token}". Vietnamese example: "Mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_prompt_template",type:"string",description:`A short "buy" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a token's Buy button is clicked. "{token}" is replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0}]);f(this,"service");this.service=new Sn({baseUrl:r?.pantographUrl})}async run(r,n){let i=Yb(r.chain,n),o=r.buy_button_label||"",a=r.buy_prompt_template||"",s=typeof r.limit=="number"&&Number.isFinite(r.limit)&&r.limit>0?Math.floor(r.limit):void 0,l=await this.service.getTrendingTokens({chain:i,limit:s});if(!l.success)return{error:l.error||"Failed to fetch trending tokens"};let u=l.data??[],c=new Set,d=[];for(let h of u){let m=h.symbol?.trim();!m||c.has(m.toLowerCase())||(c.add(m.toLowerCase()),d.push({label:this.fillTemplate(o,m,"Buy {token}"),prompt:this.fillTemplate(a,m,"buy {token}")}))}return{_instructions:`Start with a one-line header like "Here are some of the top trending tokens on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
440
+ `+o)}}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=oo(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&om.assertOptions(n,{silentJSONParsing:ki.transitional(ki.boolean),forcedJSONParsing:ki.transitional(ki.boolean),clarifyTimeoutError:ki.transitional(ki.boolean),legacyInterceptorReqResOrdering:ki.transitional(ki.boolean)},!1),i!=null&&(F.isFunction(i)?r.paramsSerializer={serialize:i}:om.assertOptions(i,{encode:ki.function,serialize:ki.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),om.assertOptions(r,{baseUrl:ki.spelling("baseURL"),withXsrfToken:ki.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let a=o&&F.merge(o.common,o[r.method]);o&&F.forEach(["delete","get","head","post","put","patch","query","common"],g=>{delete o[g]}),r.headers=hr.concat(a,o);let s=[],l=!0;this.interceptors.request.forEach(function(y){if(typeof y.runWhen=="function"&&y.runWhen(r)===!1)return;l=l&&y.synchronous;let _=r.transitional||ud;_&&_.legacyInterceptorReqResOrdering?s.unshift(y.fulfilled,y.rejected):s.push(y.fulfilled,y.rejected)});let u=[];this.interceptors.response.forEach(function(y){u.push(y.fulfilled,y.rejected)});let c,d=0,h;if(!l){let g=[Bb.bind(this),void 0];for(g.unshift(...s),g.push(...u),h=g.length,c=Promise.resolve(r);d<h;)c=c.then(g[d++],g[d++]);return c}h=s.length;let m=r;for(;d<h;){let g=s[d++],y=s[d++];try{m=g(m)}catch(_){y.call(this,_);break}}try{c=Bb.call(this,m)}catch(g){return Promise.reject(g)}for(d=0,h=u.length;d<h;)c=c.then(u[d++],u[d++]);return c}getUri(e){e=oo(this.defaults,e);let r=im(e.baseURL,e.url,e.allowAbsoluteUrls);return em(r,e.params,e.paramsSerializer)}};F.forEach(["delete","get","head","options"],function(e){hd.prototype[e]=function(r,n){return this.request(oo(n||{},{method:e,url:r,data:(n||{}).data}))}});F.forEach(["post","put","patch","query"],function(e){function r(n){return function(o,a,s){return this.request(oo(s||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}hd.prototype[e]=r(),e!=="query"&&(hd.prototype[e+"Form"]=r(!0))});var am=hd;p();var YE=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,a=new Promise(s=>{n.subscribe(s),o=s}).then(i);return a.cancel=function(){n.unsubscribe(o)},a},e(function(o,a,s){n.reason||(n.reason=new Oo(o,a,s),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},BD=YE;p();function JE(t){return function(r){return t.apply(null,r)}}p();function XE(t){return F.isObject(t)&&t.isAxiosError===!0}p();var QE={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(QE).forEach(([t,e])=>{QE[e]=t});var zD=QE;function VD(t){let e=new am(t),r=Kh(am.prototype.request,e);return F.extend(r,am.prototype,e,{allOwnKeys:!0}),F.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return VD(oo(t,i))},r}var Tr=VD(dd);Tr.Axios=am;Tr.CanceledError=Oo;Tr.CancelToken=BD;Tr.isCancel=rm;Tr.VERSION=fd;Tr.toFormData=ll;Tr.AxiosError=$e;Tr.Cancel=Tr.CanceledError;Tr.all=function(e){return Promise.all(e)};Tr.spread=JE;Tr.isAxiosError=XE;Tr.mergeConfig=oo;Tr.AxiosHeaders=hr;Tr.formToJSON=t=>qb(F.isHTMLForm(t)?new FormData(t):t);Tr.getAdapter=Fb.getAdapter;Tr.HttpStatusCode=zD;Tr.default=Tr;var Vb=Tr;var{Axios:l6e,AxiosError:u6e,CanceledError:c6e,isCancel:d6e,CancelToken:p6e,VERSION:f6e,all:h6e,Cancel:m6e,isAxiosError:g6e,spread:y6e,toFormData:_6e,AxiosHeaders:b6e,HttpStatusCode:v6e,formToJSON:w6e,getAdapter:S6e,mergeConfig:T6e,create:k6e}=Vb;var ZD="0.2.33";var EX=`keyring-agent-core/${ZD} (Keyring Chatbot Agent; +https://keyring.app)`,AX=3e4,CX=typeof process<"u"&&process.versions?.node!=null,eA=class{constructor(e={}){f(this,"instance");this.instance=Vb.create({baseURL:e.baseURL,timeout:e.timeout??AX,validateStatus:()=>!0,headers:{Accept:"application/json",...CX?{"User-Agent":e.userAgent??EX}:{},...e.headers}})}async request(e,r,n,i={}){let o=await this.instance.request({...i,method:e,url:r,data:n}),a={};for(let[s,l]of Object.entries(o.headers??{}))l!=null&&(a[s.toLowerCase()]=String(l));return{ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,data:o.data,headers:a}}get(e,r){return this.request("GET",e,void 0,r)}post(e,r,n){return this.request("POST",e,r,n)}put(e,r,n){return this.request("PUT",e,r,n)}patch(e,r,n){return this.request("PATCH",e,r,n)}delete(e,r){return this.request("DELETE",e,void 0,r)}},Fe=new eA;function dt(t){let{data:e,status:r,statusText:n}=t,i=n?`HTTP ${r} ${n}`:`HTTP ${r}`;if(typeof e=="string")return e.trim()||i;if(e&&typeof e=="object"){let o=e,a=l=>l&&typeof l=="object"?l.message:void 0,s=[o.message,o.errorMessage,o.error,o.error_description,o.detail,a(o.error),a(o.data)];for(let l of s)if(typeof l=="string"&&l.trim())return l.trim()}return i}p();var Du=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function md(t){if(!t||typeof t!="object")return!1;let e=t;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function tA(t){if(t?.aborted)throw new Du}function HD(t,e){if(!e)return{signal:t.signal,cleanup:()=>{}};if(e.aborted)return t.abort(),{signal:t.signal,cleanup:()=>{}};let r=()=>t.abort();return e.addEventListener("abort",r),{signal:t.signal,cleanup:()=>e.removeEventListener("abort",r)}}var WD={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},xX="https://nft.keyring.app/api/gemini-stable",IX=new Set([408,429,500,502,503,504]),GD=3e4,Zb=t=>new Promise(e=>setTimeout(e,t));function Hb(t,e,r){if(r!=null&&r>0)return Math.min(r,GD);let n=Math.min(e*2**(t-1),GD);return n/2+Math.random()*(n/2)}function OX(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var rn=class{constructor(e){f(this,"model");f(this,"maxTokens");f(this,"temperature");f(this,"baseUrl");f(this,"requestSignal");this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.baseUrl=e.baseUrl??xX}setRequestSignal(e){this.requestSignal=e}async chat(e,r,n){let{systemInstruction:i,contents:o}=this.toContents(e),{maxRetries:a=5,retryDelayMs:s=1e3}=n??{},l=n?.signal??this.requestSignal;tA(l);let u=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of u){let g=m.parts.map(y=>y.functionCall?`fc:${y.functionCall.name}`:y.functionResponse?`fr:${y.functionResponse.name}`:`text:${(y.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${g}]`)}}let c={contents:u,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};i&&(c.systemInstruction=i),r?.length?(c.tools=[{functionDeclarations:this.toFunctionDeclarations(r)}],n?.forceToolUse&&(c.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(c.tools=[{googleSearch:{}}]);let d=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,h="Unknown error";for(let m=1;m<=a;m++){tA(l);let g;try{g=await Fe.post(d,c,{headers:{"Content-Type":"application/json"},signal:l})}catch(C){if(md(C))throw C;if(h=C instanceof Error?C.message:String(C),m>=a)break;await Zb(Hb(m,s));continue}if(!g.ok){let C=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(h=`Gemini proxy error ${g.status}: ${C}`,!IX.has(g.status))throw new Error(h);if(m>=a)break;let R=OX(g.headers["retry-after"]??null);await Zb(Hb(m,s,R));continue}if(g.data==null||typeof g.data!="object"){if(h="Gemini proxy returned invalid JSON",m>=a)break;await Zb(Hb(m,s));continue}let y=g.data,_=y.candidates?.[0];if(!_)return{text:"",toolCalls:[]};let b="",w=[],T=_.content?.parts;if(!Array.isArray(T)||T.length===0){let C=_.finishReason;if(!(C==="SAFETY"||C==="RECITATION")&&m<a){h=`Gemini returned an empty turn (finishReason=${C??"none"})`,await Zb(Hb(m,s));continue}return{text:"",toolCalls:[]}}for(let C of T)C.text&&(b+=C.text),C.functionCall&&w.push({toolName:C.functionCall.name,args:C.functionCall.args??{},callId:C.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let E=y.usageMetadata?{promptTokens:y.usageMetadata.promptTokenCount??0,completionTokens:y.usageMetadata.candidatesTokenCount??0,totalTokens:y.usageMetadata.totalTokenCount??0}:void 0;return{text:b,toolCalls:w,usage:E}}throw new Error(h)}toContents(e){let r=[],n=[];for(let s of e){if(s.role==="system"){r.push(s.content);continue}if(s.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:s.toolName??"unknown",response:{result:s.content},...s.toolCallId?{id:s.toolCallId}:{}}}]});continue}if(s.role==="assistant"&&s.toolCalls?.length){n.push({role:"model",parts:s.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:s.role==="assistant"?"model":"user",parts:[{text:s.content}]})}let i=[];for(let s of n){let l=i[i.length-1],u=s.parts.some(d=>d.functionCall),c=l?.parts.some(d=>d.functionCall);l&&l.role===s.role&&!u&&!c?l.parts.push(...s.parts):i.push({...s,parts:[...s.parts]})}let o=[];for(let s=0;s<i.length;s++){let l=i[s],u=o[o.length-1];l.role==="function"&&!u?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(i[s+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:r.length?{role:"user",parts:[{text:r.join(`
441
+ `)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(r=>{let n={},i=[];for(let o of r.parameters){let a={type:WD[o.type]??"STRING",description:o.description};o.type==="array"&&(a.items={type:WD[o.items?.type??"string"]??"STRING"}),n[o.name]=a,o.required&&i.push(o.name)}return{name:r.name,description:r.description,parameters:{type:"OBJECT",properties:n,required:i}}})}};p();var gd=class{constructor(){f(this,"tools",new Map)}register(e){if(this.tools.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getDefinitions(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,parameters:e.parameters,category:e.category,kind:e.kind}))}getDefinitionsByCategory(e){return this.getDefinitions().filter(r=>r.category===e)}async execute(e,r,n){let i=this.tools.get(e);if(!i)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let o=Date.now();try{return{...await i.execute(r,n),duration:Date.now()-o}}catch(a){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-o}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};p();p();p();p();p();var yd=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708"],RX=new Set(yd),ul=[...yd],KD=new Set(ul),Ro="0x1",Uu="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea";function NX(t){return t.map(e=>bd[e]??e).join(", ")}function Wb(t){let e=new Set;if(t)for(let n of t){let i=Gb(n);i&&e.add(i)}let r=yd.filter(n=>!e.has(n));ul=r.length>0?[...r]:[...yd],KD=new Set(ul),Ro=ul.includes("0x1")?"0x1":ul[0],Uu=NX(ul)}var $X={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708"};function Ln(t){let e=Gb(t);return e&&KD.has(e)?e:null}function Gb(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let r=$X[e];if(r)return r;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&RX.has(n)?n:null}function Kb(t){return Ln(t)!==null}function Pi(){return[...ul]}var _d=class extends Error{constructor(r){super(`Chain "${r}" is not supported. Supported chains: ${Uu}.`);f(this,"requested",r);f(this,"code","unsupported_chain");this.name="UnsupportedChainError"}},cl=t=>typeof t=="string"&&t.trim()!=="";function jn(t,e){if(cl(t)){let r=Ln(t);if(r)return r;throw new _d(t.trim())}if(cl(e?.chain)){let r=Ln(e.chain);if(r)return r;throw new _d(e.chain.trim())}return null}function Yb(t,e){return Ln(t)??Ln(e?.chain)??void 0}var bd={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea"};function Ye(t){let e=Gb(t);return e&&bd[e]?bd[e]:typeof t=="string"&&t.trim()?t.trim():"the requested chain"}var MX={"0x1":"https://etherscan.io","0xa":"https://optimistic.etherscan.io","0x38":"https://bscscan.com","0x89":"https://polygonscan.com","0x2105":"https://basescan.org","0xa4b1":"https://arbiscan.io","0xa86a":"https://snowtrace.io","0xe708":"https://lineascan.build"};function YD(t,e){let r=Gb(t),n=r?MX[r]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var DX={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a"};function JD(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();return e?DX[e]??null:null}var UX={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH"};function XD(t){let e=Ln(t);return e?UX[e]??null:null}function vd(t,e){if(!cl(t))return null;let r=Ln(t),n=Ln(e?.chain);return!r||!n||r===n?null:{requested:r,connected:n,requestedLabel:bd[r]??r,connectedLabel:bd[n]??n}}function QD(t){let e=typeof t=="string"?t.trim():"";return ul.map(r=>{let n=bd[r]??r;return{label:n,prompt:e?`${e} (${n})`:n}})}function wd(t,e){return{actionButtons:QD(e),_instructions:`The user wants to ${t} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var Ir=class extends Error{constructor(r){super("Wallet is connected but no chain is set \u2014 ask the user to pick one.");f(this,"code","needs_chain_selection");f(this,"buttons");this.name="NeedsChainSelectionError",this.buttons=QD(r)}},sm=class extends Error{constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one.");f(this,"code","no_wallet_connected");this.name="NoWalletConnectedError"}};function kr(t,e){if(cl(t))return t.trim();if(cl(e?.walletAddress))return e.walletAddress.trim();throw new sm}function vt(t,e){if(cl(t)){let r=Ln(t);if(r)return r;throw new _d(t.trim())}if(cl(e?.chain)){let r=Ln(e.chain);if(r)return r;throw new _d(e.chain.trim())}if(cl(e?.walletAddress))throw new Ir(typeof e?.query=="string"?e.query:void 0);return Ro}var oe=class{constructor(){f(this,"category")}async execute(e,r){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,i=Date.now();try{let o=await this.run(e,r),a=qX(o);return{toolName:this.name,callId:n,success:!0,data:a.data,duration:Date.now()-i,...a.actionButtons?{actionButtons:a.actionButtons}:{}}}catch(o){return o instanceof Ir?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-i,actionButtons:o.buttons}:o instanceof sm?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has not connected a wallet. In the user's language, tell them this action needs a wallet \u2014 they can either connect their wallet or include a wallet address (0x\u2026) directly in their question. Keep it short and friendly."},duration:Date.now()-i}:{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-i}}}};function qX(t){if(!t||typeof t!="object")return{data:t};let e=t,r=e.actionButtons;if(!Array.isArray(r)||r.length===0)return{data:t};let{actionButtons:n,...i}=e;return{data:i,actionButtons:r}}p();p();var eU=eb(Xb());function zt(t){return typeof t=="string"&&/^0x[0-9a-fA-F]{40}$/.test(t)}function LX(t){return new Uint8Array(eU.keccak256.arrayBuffer(t))}function lm(t){let e=t.startsWith("0x")?t.slice(2):t,r=e.length%2?"0"+e:e,n=new Uint8Array(r.length/2);for(let i=0;i<n.length;i++)n[i]=parseInt(r.slice(i*2,i*2+2),16);return n}function tU(t){return"0x"+Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function rU(t){return new TextEncoder().encode(t)}function qu(...t){let e=t.reduce((i,o)=>i+o.length,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function jX(t,e=32){let r=new Uint8Array(e);return r.set(t,e-t.length),r}function FX(t,e=32){let r=new Uint8Array(e);return r.set(t),r}function nU(t){let e=((t%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return lm(e)}function um(t){return nU(BigInt(t))}function iU(t){return t==="uint"?"uint256":t==="int"?"int256":t.match(/^uint$/)?"uint256":t.match(/^int$/)?"int256":t.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function oU(t){let e=iU(t.type);if(e==="tuple"||e.startsWith("tuple[")){let r=(t.components??[]).map(oU).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${r})${n}`}return e}function BX(t){let e=(t.inputs??[]).map(oU).join(",");return`${t.name??""}(${e})`}function rA(t,e){let r=ZX(t.type);if(r){let[i,o]=r;return zX({...t,type:o},e,i)}if(t.type==="tuple")return VX(t,e);if(t.type==="address"){let i=String(e),o=i.startsWith("0x")?i.slice(2):i;return{dynamic:!1,encoded:jX(lm(o.toLowerCase()))}}if(t.type==="bool"){let i=new Uint8Array(32);return i[31]=e?1:0,{dynamic:!1,encoded:i}}let n=iU(t.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:um(BigInt(e))};if(/^int\d*$/.test(n)){let i=BigInt(e);return i<0n&&(i=i+(1n<<256n)),{dynamic:!1,encoded:nU(i)}}if(/^bytes(\d+)$/.test(n)){let i=parseInt(n.slice(5),10),o=typeof e=="string"?lm(e):e;if(o.length!==i)throw new Error(`bytes${i} expects exactly ${i} bytes, got ${o.length}`);return{dynamic:!1,encoded:FX(o)}}if(n==="bytes"){let i=typeof e=="string"?lm(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:qu(um(i.length),a)}}if(n==="string"){let i=typeof e=="string"?rU(e):e,o=Math.ceil(i.length/32)*32,a=new Uint8Array(o);return a.set(i),{dynamic:!0,encoded:qu(um(i.length),a)}}throw new Error(`Unsupported ABI type: ${t.type}`)}function nA(t){let e=0;for(let{dynamic:o,encoded:a}of t)e+=o?32:a.length;let r=[],n=[],i=0;for(let{dynamic:o,encoded:a}of t)o?(r.push(um(e+i)),n.push(a),i+=a.length):r.push(a);return qu(...r,...n)}function zX(t,e,r){let n=r===null;if(!n&&e.length!==r)throw new Error(`Array length mismatch: expected ${r}, got ${e.length}`);let i=!1,o=[];for(let a of e){let s=rA(t,a);s.dynamic&&(i=!0),o.push(s)}if(n||i){let a=nA(o);if(n){let s=um(o.length);return{dynamic:!0,encoded:o.length>0?qu(s,a):s}}return{dynamic:!0,encoded:a}}return{dynamic:!1,encoded:qu(...o.map(a=>a.encoded))}}function VX(t,e){let r=t.components??[],n=!1,i=[];for(let o=0;o<r.length;o++){let a=r[o],s=Array.isArray(e)?e[o]:e[a.name??""],l=rA(a,s);l.dynamic&&(n=!0),i.push(l)}return{dynamic:n,encoded:n?nA(i):qu(...i.map(o=>o.encoded))}}function ZX(t){let e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function HX(t,e){if(t.length!==e.length)throw new Error(`Expected ${t.length} values, got ${e.length}`);if(t.length===0)return"0x";let r=t.map((i,o)=>rA(i,e[o])),n=nA(r);return tU(n)}function Sd({abi:t,functionName:e,args:r=[]}){let n=t.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let i=BX(n),o=LX(rU(i)).slice(0,4),a=n.inputs??[],s=a.length===0||r.length===0?new Uint8Array(0):lm(HX(a,r).slice(2));return tU(qu(o,s))}p();var WX="https://wallet-api.pantograph.app",GX="0x0000000000000000000000000000000000000000",lU={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},uU={"0x1":["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"],"0xa":["0x4200000000000000000000000000000000000006","0x68f180fcce6836688e9084f035309e29bf0a2095","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0x38":["0x2170ed0880ac9a755fd29b2688956bd959f933f8","0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c"],"0x89":["0x7ceb23fd6bc0add59e62ac25578270cff1b9f619","0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6"],"0x2105":["0x4200000000000000000000000000000000000006","0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0xa4b1":["0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f"],"0xa86a":["0x49d5c2bdffac6ce2bfdb6640f4f80f226bc10bab","0x0555e30da8f98308edb960aa94c0db47230d2b9c"],"0xe708":["0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f","0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4"]};function cm(t){return lU[t.toLowerCase()]||t}function aU(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function iA(t){let e=t,r=e.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):NaN,i=e.price,o=i!=null?parseFloat(String(i)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function wn(t){if(t==null)return null;let e=typeof t=="number"?t:parseFloat(String(t));return Number.isFinite(e)?e:null}function sU(t,e){let r=t.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):null,i=wn(t.price_change_percentage_24h)??wn(t.priceChange24h)??wn(t.usd_price_24hr_percent_change)??wn(t.price_change_24h)??wn(t.priceChange);return{chainId:e,tokenAddress:t.address??t.token_address??"",name:t.name??null,symbol:t.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:t.logoURI??t.icon_image??t.logo??null,usdPrice:wn(t.price)??wn(t.usd_price),marketCap:wn(t.market_cap)??wn(t.marketCap),totalVolume:{"24h":wn(t.total_volume)??wn(t.volume24h)},pricePercentChange:{"24h":i}}}var Sn=class{constructor(e){f(this,"baseUrl");this.baseUrl=(e?.baseUrl??WX).replace(/\/+$/,"")}async enrichTokenPrices(e,r){if(e.length!==0)try{let n=cm(r),i=e.map(c=>c.token_address).join(","),o=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(i)}`,a=await Fe.get(o);if(!a.ok)return;let s=a.data,l=Array.isArray(s)?s:Array.isArray(s.data)?s.data:[],u=new Map;for(let c of l)c.address&&u.set(c.address.toLowerCase(),{price:c.price!=null?parseFloat(String(c.price)):NaN,icon_image:c.icon_image});for(let c=0;c<e.length;c++){let d=u.get(e[c].token_address.toLowerCase());d&&(d.icon_image&&(e[c].logo=d.icon_image,e[c].thumbnail=d.icon_image),isNaN(d.price)||(e[c].usd_price=d.price,e[c].usd_value=parseFloat(e[c].balance_formatted||"0")*d.price))}}catch{}}async getTokenMetadata(e,r){try{let n=cm(r),i=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(e)}`,o=await Fe.get(i);if(!o.ok)return null;let a=o.data,s=Array.isArray(a)?a:Array.isArray(a.data)?a.data:[],l=e.toLowerCase()===GX,u=s.find(c=>c.address?.toLowerCase()===e.toLowerCase()||l&&c.address===""||c.token_address?.toLowerCase()===e.toLowerCase()||l&&c.token_address==="");return u?iA(u):null}catch{return null}}async getTokensMetadata(e,r){let n={};if(e.length===0)return n;try{let i=cm(r),o=`${this.baseUrl}/keyrings/tokens/${i}/v2?addresses=${encodeURIComponent(e.join(","))}`,a=await Fe.get(o);if(!a.ok)return n;let s=a.data,l=Array.isArray(s)?s:Array.isArray(s.data)?s.data:[],u=new Set(e.map(c=>c.toLowerCase()));for(let c of l){let d=c.address?.toLowerCase()||c.token_address?.toLowerCase()||(c.address===""?"":null);d&&u.has(d)&&(n[d]=iA(c))}}catch{}return n}async searchTokensByKey(e){let{key:r,chain:n}=e;if(!r)return{success:!1,error:"Search key is required"};let o=parseInt(n||Ro,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=aU({chainId:o,key:r}),s=`${this.baseUrl}/token-list?${a}`,l=await Fe.get(s);if(!l.ok)throw new Error(dt(l));let u=l.data,c=[];return u?.data?c=Array.isArray(u.data)?u.data:Object.values(u.data).flat():typeof u=="object"&&!Array.isArray(u)&&(c=Object.values(u).flat()),{success:!0,data:c.map(iA)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let r=e?.chain||Ro,n=5,i=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=uU[r.toLowerCase()]??[],a=i!=null?i+o.length:n+o.length,[s,l]=await Promise.allSettled([this.fetchTopGainers(r,a),o.length>0?this.getTokensMetadata(o,r):Promise.resolve({})]),u=s.status==="fulfilled"?s.value:[],c=l.status==="fulfilled"?o.map(y=>l.value[y.toLowerCase()]).filter(y=>y!=null).map(y=>sU(y,r)):[],d=new Set,h=[];for(let y of c){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),h.push(y))}let m=[];for(let y of u){let _=y.tokenAddress?.toLowerCase();!_||d.has(_)||(d.add(_),m.push(y))}let g=i!=null?[...h,...m].slice(0,i):[...h,...m.slice(0,n)];return await this.enrichTrendingMarketData(g,r),{success:!0,data:g}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,r){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let i=await this.getTokensMetadata(n.map(o=>o.tokenAddress),r);for(let o of n){let a=i[o.tokenAddress.toLowerCase()];a&&(o.marketCap==null&&(o.marketCap=wn(a.market_cap)??wn(a.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":wn(a.total_volume)??wn(a.volume24h)}))}}async fetchTopGainers(e,r,n="24h"){let i=cm(e),o=aU({duration:n,limit:r}),a=`${this.baseUrl}/token-list/top-gainers/${i}${o?`?${o}`:""}`,s=[];for(let l=0;l<5;l++){let u=await Fe.get(a);if(!u.ok)throw new Error(dt(u));let c=u.data;if(s=Array.isArray(c)?c:Array.isArray(c.data)?c.data:[],s.length>0)break;l<4&&await new Promise(d=>setTimeout(d,2e3))}return s.map(l=>sU(l,e))}async getTopGainers(e){let r=e?.chain||Ro,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,i=e?.duration||"24h";try{let o=await this.fetchTopGainers(r,n,i);return await this.enrichTrendingMarketData(o,r),{success:!0,data:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}};var KX="https://nft.keyring.app",YX="https://nft.keyring.app",JX=.01,tt=5,ir=1e3,XX="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",QX="0x0000000000000000000000000000000000000000",rt=class extends Error{constructor(r,n){super(n);f(this,"status",r);this.name="MoralisHttpError"}};function mr(t){return t||Ro}function or(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function ar(t){return new Promise(e=>setTimeout(e,t))}function eQ(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result.map(r=>({protocol_id:r.protocolId,protocol_name:r.protocolName,protocol_url:r.protocolUrl??"",protocol_logo:r.protocolLogo??"",position:{label:r.position.label,address:r.position.address,balance_usd:r.position.balanceUsd??0,total_unclaimed_usd_value:r.position.unclaimedUsd??0,position_details:r.position.details,tokens:r.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}function oA(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result:Object.keys(e).filter(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}var pt=class{constructor(e){f(this,"baseUrl");f(this,"v1BaseUrl");f(this,"pantograph");this.baseUrl=(e?.baseUrl??KX).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??YX).replace(/\/+$/,""),this.pantograph=new Sn({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:r,chain:n,tokenAddresses:i,excludeSpam:o=!1,excludeUnverifiedContracts:a=!1}=e;if(!r)return{success:!1,error:"Address is required"};let s=mr(n),l="Unknown error";for(let u=1;u<=tt;u++)try{let c={chain:s,exclude_spam:o,exclude_unverified_contracts:a,limit:100};i&&(c.token_addresses=i);let d=[],h=null;do{h&&(c.cursor=h);let g=or(c),y=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/tokens?${g}`,_=await Fe.get(y);if(!_.ok)throw new rt(_.status,dt(_));let b=_.data,w=b?.data??b;w?.result?.length>0&&d.push(...w.result),h=w?.cursor??null}while(h);let m={result:d};return m?.result?.length>0&&(m.result=m.result.filter(g=>parseFloat(g.balance||"0")>0),m.result=m.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===XX?QX:g.token_address})),await this.enrichTokenPrices(m.result,s),m.result=m.result.filter(g=>g.usd_value==null||g.usd_value>=JX)),{success:!0,data:m}}catch(c){if(l=c instanceof Error?c.message:"Unknown error",c instanceof rt&&c.status===400)break;u<tt&&await ar(ir)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token address is required"};let i=mr(n),o="Unknown error",a=await this.pantograph.getTokenMetadata(r,i);if(a)return{success:!0,data:a};for(let s=1;s<=tt;s++)try{let[l,u]=await Promise.allSettled([Fe.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${or({chain:i,addresses:[r]})}`),Fe.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/price?${or({chain:i,include:"percent_change"})}`)]),c=null;if(l.status==="fulfilled"&&l.value.ok){let h=l.value.data;c=(Array.isArray(h)?h:Array.isArray(h?.data)?h.data:[])[0]??null}if(!c){o="Token metadata not found",s<tt&&await ar(ir);continue}let d=null;if(u.status==="fulfilled"&&u.value.ok){let h=u.value.data;d=h?.data??h}return{success:!0,data:{...c,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof rt&&l.status===400)break;s<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:r,chain:n,limit:i=10,excludeSpam:o=!0,cursor:a,tokenAddresses:s,includePrices:l,format:u="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};let c=mr(n),d="Unknown error";for(let h=1;h<=tt;h++)try{let m={chain:c,format:u,limit:i,exclude_spam:o,media_items:!0,normalizeMetadata:!0};a&&(m.cursor=a),l&&(m.include_prices=!0),s&&s.length>0&&(m.token_addresses=s);let g=or(m),y=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft?${g}`,_=await Fe.get(y);if(!_.ok)throw new rt(_.status,dt(_));let b=_.data;return{success:!0,data:b?.data??b}}catch(m){if(d=m instanceof Error?m.message:"Unknown error",m instanceof rt&&m.status===400)break;h<tt&&await ar(ir)}return{success:!1,error:d}}async getNftMetadata(e){let{address:r,tokenId:n,chain:i,format:o="decimal",normalizeMetadata:a=!0,mediaItems:s=!0,include:l}=e;if(!r)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!zt(r))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let u=mr(i),c="Unknown error";for(let d=1;d<=tt;d++)try{let h={chain:u,format:o,normalizeMetadata:a,media_items:s};l&&(h.include=l);let m=or(h),g=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/${encodeURIComponent(n)}?${m}`,y=await Fe.get(g);if(!y.ok)throw new rt(y.status,dt(y));let _=y.data;return{success:!0,data:_?.data??_}}catch(h){if(c=h instanceof Error?h.message:"Unknown error",h instanceof rt&&h.status===400)break;d<tt&&await ar(ir)}return{success:!1,error:c}}async getNftContractMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};let i=mr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/metadata?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletHistory(e){let{address:r,chain:n,limit:i=25,fromDate:o,toDate:a,fromBlock:s,toBlock:l,cursor:u,order:c="DESC",includeInternalTransactions:d,nftMetadata:h}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=mr(n),g=Math.max(1,Math.min(100,Math.floor(i))),y="Unknown error";for(let _=1;_<=tt;_++)try{let b={chain:m,limit:g,order:c};o&&(b.from_date=o),a&&(b.to_date=a),s!=null&&(b.from_block=s),l!=null&&(b.to_block=l),u&&(b.cursor=u),d!=null&&(b.include_internal_transactions=d),h!=null&&(b.nft_metadata=h);let w=or(b),T=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/history?${w}`,E=await Fe.get(T);if(!E.ok)throw new rt(E.status,dt(E));let C=E.data;return{success:!0,data:C?.data??C}}catch(b){if(y=b instanceof Error?b.message:"Unknown error",b instanceof rt&&b.status===400)break;_<tt&&await ar(ir)}return{success:!1,error:y}}async getWalletTokenTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:u,cursor:c,order:d="DESC"}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let h=mr(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=tt;y++)try{let _={chain:h,limit:m,order:d};a&&(_.from_date=a),s&&(_.to_date=s),l!=null&&(_.from_block=l),u!=null&&(_.to_block=u),c&&(_.cursor=c),i?.length&&(_.contract_addresses=i);let b=or(_),w=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/erc20/transfers?${b}`,T=await Fe.get(w);if(!T.ok)throw new rt(T.status,dt(T));let E=T.data;return{success:!0,data:E?.data??E}}catch(_){if(g=_ instanceof Error?_.message:"Unknown error",_ instanceof rt&&_.status===400)break;y<tt&&await ar(ir)}return{success:!1,error:g}}async getWalletNftTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:o=25,fromDate:a,toDate:s,fromBlock:l,toBlock:u,cursor:c,order:d="DESC",includePrices:h,format:m="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let g=mr(n),y=Math.max(1,Math.min(100,Math.floor(o))),_="Unknown error";for(let b=1;b<=tt;b++)try{let w={chain:g,limit:y,order:d,format:m};a&&(w.from_date=a),s&&(w.to_date=s),l!=null&&(w.from_block=l),u!=null&&(w.to_block=u),c&&(w.cursor=c),i?.length&&(w.contract_addresses=i),h!=null&&(w.include_prices=h);let T=or(w),E=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/transfers?${T}`,C=await Fe.get(E);if(!C.ok)throw new rt(C.status,dt(C));let R=C.data;return{success:!0,data:R?.data??R}}catch(w){if(_=w instanceof Error?w.message:"Unknown error",w instanceof rt&&w.status===400)break;b<tt&&await ar(ir)}return{success:!1,error:_}}async getTokenHolders(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};if(!zt(r))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/holders?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:r,chain:n,days:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=mr(n),a="Unknown error";for(let s=1;s<=tt;s++)try{let l={chain:o};i&&(l.days=i);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability/summary?${u}`,d=await Fe.get(c);if(!d.ok)throw new rt(d.status,dt(d));let h=d.data;return{success:!0,data:h?.data??h}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof rt&&l.status===400)break;s<tt&&await ar(ir)}return{success:!1,error:a}}async getWalletPnl(e){let{address:r,chain:n,days:i,tokenAddresses:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=mr(n),s="Unknown error";for(let l=1;l<=tt;l++)try{let u={chain:a};i&&(u.days=i),o&&o.length>0&&(u.token_addresses=o.slice(0,25));let c=or(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability?${c}`,h=await Fe.get(d);if(!h.ok)throw new rt(h.status,dt(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(u){if(s=u instanceof Error?u.message:"Unknown error",u instanceof rt&&u.status===400)break;l<tt&&await ar(ir)}return{success:!1,error:s}}async getTransactionByHash(e){let{transactionHash:r,chain:n}=e;if(!r)return{success:!1,error:"Transaction hash is required"};let i=mr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(r)}/verbose?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:r,chain:n,limit:i,cursor:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=mr(n),s="Unknown error";for(let l=1;l<=tt;l++)try{let u={chain:a};i!=null&&(u.limit=i),o&&(u.cursor=o);let c=or(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/approvals?${c}`,h=await Fe.get(d);if(!h.ok)throw new rt(h.status,dt(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(u){if(s=u instanceof Error?u.message:"Unknown error",u instanceof rt&&u.status===400)break;l<tt&&await ar(ir)}return{success:!1,error:s}}async getWalletDefiSummary(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/summary?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!zt(r))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/positions?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data,d=c?.data??c;return{success:!0,data:eQ(d)}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:r,protocol:n,chain:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!zt(r))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=mr(i),a="Unknown error";for(let s=1;s<=tt;s++)try{let l=or({chains:o}),u=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/${encodeURIComponent(n)}/positions?${l}`,c=await Fe.get(u);if(!c.ok)throw new rt(c.status,dt(c));let m=c.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(y=>({label:y.label,address:y.address,balance_usd:y.balanceUsd??0,total_unclaimed_usd_value:y.unclaimedUsd??0,position_details:y.details,tokens:y.tokens.map(_=>({token_type:_.tokenType,address:_.address,contract_address:_.address,name:_.name??"",symbol:_.symbol??"",decimals:_.decimals??18,logo:_.logo,balance:_.balance??"0",balance_formatted:_.balanceFormatted??"0",usd_price:_.usdPrice,usd_value:_.usdValue}))}))}}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof rt&&l.status===400)break;s<tt&&await ar(ir)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!zt(r))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/analytics?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getTokenScore(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!zt(r))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let i=mr(n),o="Unknown error";for(let a=1;a<=tt;a++)try{let s=or({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/score?${s}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(s){if(o=s instanceof Error?s.message:"Unknown error",s instanceof rt&&s.status===400)break;a<tt&&await ar(ir)}return{success:!1,error:o}}async getTrendingTokens(e){let r=e?.chain,n=e?.limit,i="Unknown error";for(let o=1;o<=tt;o++)try{let a={};r&&(a.chain=mr(r)),n!=null&&(a.limit=n);let s=or(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${s?`?${s}`:""}`,u=await Fe.get(l);if(!u.ok)throw new rt(u.status,dt(u));let c=u.data,d=c?.data??c;return{success:!0,data:oA(d)}}catch(a){if(i=a instanceof Error?a.message:"Unknown error",a instanceof rt&&a.status===400)break;o<tt&&await ar(ir)}return{success:!1,error:i}}async getTopGainers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=tt;s++)try{let l={};r&&(l.chain=mr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${u?`?${u}`:""}`,d=await Fe.get(c);if(!d.ok)throw new rt(d.status,dt(d));let h=d.data,m=h?.data??h;return{success:!0,data:oA(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof rt&&l.status===400)break;s<tt&&await ar(ir)}return{success:!1,error:a}}async getTopLosers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:o}=e??{},a="Unknown error";for(let s=1;s<=tt;s++)try{let l={};r&&(l.chain=mr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),o!=null&&(l.security_score=o);let u=or(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${u?`?${u}`:""}`,d=await Fe.get(c);if(!d.ok)throw new rt(d.status,dt(d));let h=d.data,m=h?.data??h;return{success:!0,data:oA(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof rt&&l.status===400)break;s<tt&&await ar(ir)}return{success:!1,error:a}}async enrichTokenPrices(e,r){return this.pantograph.enrichTokenPrices(e,r)}};var Td=class extends oe{constructor(r){super();f(this,"name","get-token-info");f(this,"description",'Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea');f(this,"category","blockchain-data");f(this,"parameters",[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,required:!0}]);f(this,"service");f(this,"llm");this.service=new pt(r),this.llm=new rn({})}async run(r,n){let i=r.keyword||"",o=vt(r.chain,n),a=r.prompt||"",s=n?.walletAddress||void 0;return i?await this.searchToken(i,o,a,s):{error:"Missing required parameter: keyword"}}async searchToken(r,n,i,o){let a=[o?`User's connected wallet address: ${o}`:null,n?`Current chain (hex chain ID): ${n}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
442
+ `),[s,l,u]=await Promise.all([this.service.searchTokensByKey({key:r,chain:n}),o?this.findTokenInWallet(o,n,r):Promise.resolve(null),i?this.askGeminiWithSearch(i,a):Promise.resolve(null)]),c=s.success&&s.data?Array.isArray(s.data)?s.data:[]:[],d=r.toLowerCase(),h=b=>b.symbol?.toLowerCase()===d||b.token_address?.toLowerCase()===d,m=[...c].sort((b,w)=>(h(b)?0:1)-(h(w)?0:1)),g=null,y=m[0];if(y?.token_address){let b=await this.service.getTokenMetadata({address:y.token_address,chain:n});b.success&&b.data&&(g=b.data)}return!g&&y&&(g={...y}),{_instructions:'Present the token info in a clear summary. Include: token name & symbol, contract address (shortened), current USD price, 24h price change % (prefix "+" for positive, "-" for negative), market cap, fully diluted valuation, 24h trading volume, liquidity, and holder count (if available). If the user holds this token, prominently show their balance and USD value. If research is present, weave its substance naturally into your answer \u2014 fold the relevant points into the description, context, and any notable news or risks. When the research explains WHY the price moved, surface that catalyst clearly (what happened, roughly when), summarize the most relevant recent news, and close with a brief, clearly-hedged sense of market direction (do not give financial advice or price predictions). Do NOT add a labelled "AI Analysis" section or any similar heading, and do NOT mention that the analysis came from AI; just write it as part of the token summary. Format numbers in a human-readable way (e.g. $1.23, +5.67%, $12.5M). If a field is null, omit it.',chain:n,userHoldsToken:!!l,walletBalance:l,token:g,...c.length>1?{searchResults:m.slice(0,10)}:{},research:u}}async askGeminiWithSearch(r,n){let i=Date.now();try{return(await this.llm.chat([...n?[{role:"system",content:n,timestamp:i}]:[],{role:"user",content:r,timestamp:i}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(r,n,i){if(!i)return null;let o=await this.service.getWalletTokenBalances({address:r,chain:n,excludeSpam:!0,excludeUnverifiedContracts:!0});if(!o.success||!o.data?.result)return null;let a=i.toLowerCase(),s=o.data.result.find(l=>l.token_address.toLowerCase()===a||l.symbol?.toLowerCase()===a||l.name?.toLowerCase().includes(a));return s||null}};p();var kd=class extends oe{constructor(r){super();f(this,"name","get-token-holders");f(this,"description",'Get holder statistics and analytics for an ERC-20 token. Returns: total holder count, holder count changes over time (5min/1h/6h/24h/3d/7d/30d), how holders acquired the token (swap/transfer/airdrop), supply concentration (% held by top 10/25/50/100/250/500 holders), and holder size distribution (whales, sharks, dolphins, fish, octopus, crabs, shrimps). Use tokenSymbol (e.g. "USDC") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How many holders does USDC have?" (tokenSymbol=USDC), "Is USDC gaining or losing holders?" (tokenSymbol=USDC \u2192 holderChange), "How many new holders did ETH get in the last 7 days?" (tokenSymbol=WETH), "How concentrated is USDC ownership?" (tokenSymbol=USDC \u2192 holderSupply), "What % of supply do the top 10 holders control?" (tokenSymbol=USDC), "How many whales hold USDT?" (tokenSymbol=USDT \u2192 holderDistribution), "Did most holders buy via swap or transfer?" (tokenSymbol=USDC \u2192 holdersByAcquisition). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea. ');f(this,"category","blockchain-data");f(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=vt(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let l,u;if(a){let h=await this.resolveContractAddress(a,i,o);if(!h)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Ye(i):"the selected chain"}. Try passing contractAddress directly.`};s=h.address,l=h.symbol,u=h.name}let c=await this.service.getTokenHolders({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let d=c.data;return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},totalHolders:d.totalHolders,holdersByAcquisition:d.holdersByAcquisition,holderChange:d.holderChange,holderSupply:d.holderSupply,holderDistribution:d.holderDistribution}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Pd=class extends oe{constructor(r){super();f(this,"name","get-token-analytics");f(this,"description",`Get detailed trading analytics for a single ERC-20 token, broken down across 5min / 1h / 6h / 24h windows. Returns: buy volume, sell volume, unique buyers, unique sellers, buy/sell transaction counts, unique wallets, price % change, current USD price, total liquidity and fully-diluted valuation (FDV). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How is PEPE trading today?" (tokenSymbol=PEPE), "24h buy vs sell volume for USDC?" (tokenSymbol=USDC \u2192 totalBuyVolume vs totalSellVolume), "Is buying or selling pressure stronger for this token?", "How many unique wallets touched this token in the last hour?" (\u2192 uniqueWallets.1h), "What's the FDV and liquidity of X?" (\u2192 totalFullyDilutedValuation, totalLiquidity), "Price change over 6h?" (\u2192 pricePercentChange.6h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=vt(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let l,u;if(a){let h=await this.resolveContractAddress(a,i,o);if(!h)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Ye(i):"the selected chain"}. Try passing contractAddress directly.`};s=h.address,l=h.symbol,u=h.name}let c=await this.service.getTokenAnalytics({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let d=c.data??{};return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},usdPrice:d.usdPrice??null,totalLiquidity:d.totalLiquidity??null,totalFullyDilutedValuation:d.totalFullyDilutedValuation??null,totalBuyVolume:d.totalBuyVolume??null,totalSellVolume:d.totalSellVolume??null,totalBuyers:d.totalBuyers??null,totalSellers:d.totalSellers??null,totalBuys:d.totalBuys??null,totalSells:d.totalSells??null,uniqueWallets:d.uniqueWallets??null,pricePercentChange:d.pricePercentChange??null}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Ed=class extends oe{constructor(r){super();f(this,"name","get-token-score");f(this,"description",`Get a composite 0\u2013100 health/safety score for a single ERC-20 token, plus the metrics behind it. Returns: overall score, last-updated timestamp, current USD price, paired liquidity, multi-timeframe volume buckets (10m / 30m / 1h / 4h / 12h / 1d / 7d / 30d), same buckets for transaction counts, and supply info (total supply + % held by top 10 holders). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "Is PEPE a safe token?" (tokenSymbol=PEPE \u2192 score), "What's the health/score of USDC?", "How concentrated is X's supply among whales?" (\u2192 metrics.supply.top10Percent), "How much volume did this token do over the last 7 days?" (\u2192 metrics.volumeUsd.7d), "Transaction count for this token in the last hour?" (\u2192 metrics.transactions.1h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.`);f(this,"category","blockchain-data");f(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);f(this,"service");this.service=new pt(r)}async run(r,n){let i=vt(r.chain,n),o=n?.walletAddress||void 0,a=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,s=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!a&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let l,u;if(a){let m=await this.resolveContractAddress(a,i,o);if(!m)return{error:`Cannot resolve token symbol "${a}" to a contract address on ${i?Ye(i):"the selected chain"}. Try passing contractAddress directly.`};s=m.address,l=m.symbol,u=m.name}let c=await this.service.getTokenScore({address:s,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token score"};let d=c.data??{},h=d.metrics??{};return{token:{symbol:l??a??null,name:u??null,contractAddress:s,chain:i||"default"},score:d.score??null,updatedAt:d.updatedAt??null,metrics:{usdPrice:h.usdPrice??null,liquidityUsd:h.liquidityUsd??null,volumeUsd:h.volumeUsd??null,transactions:h.transactions??null,supply:h.supply??null}}}async resolveContractAddress(r,n,i){let o=r.toLowerCase();if(i){let s=await this.service.getWalletTokenBalances({address:i,chain:n});if(s.success&&s.data?.result?.length){let l=s.data.result.find(u=>(u.symbol??"").toLowerCase()===o);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let a=await this.service.searchTokensByKey({key:r,chain:n});if(a.success&&a.data?.length){let l=a.data.find(u=>(u.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};p();var Ad=class extends oe{constructor(r){super();f(this,"name","get-trending-tokens");f(this,"description",'List tokens trending on-chain right now, ranked by trading activity, volume, liquidity and holder growth. Returns price, market cap, liquidity, holder count, and multi-timeframe buckets (1h / 4h / 12h / 24h) of price change, volume, transaction counts, and unique buyers/sellers. Cross-chain by default \u2014 omit `chain` for a global ranking, or pass it to filter to one network. Use this tool for questions like: "What tokens are trending right now?", "Show me hot tokens", "What\'s popular on Base today?", "Which tokens have the highest 24h volume?", "Biggest movers in the last hour?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, and more.');f(this,"category","blockchain-data");f(this,"parameters",[{name:"chain",type:"string",description:'Optional hex chain ID to scope results to a single network: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user names a chain. Omit to return cross-chain trending results.',required:!1},{name:"limit",type:"number",description:'Total number of trending tokens to return (chain default tokens + top gainers combined). Only set this when the user asks for a specific count (e.g. "show 20 trending tokens" \u2192 20). Omit otherwise \u2014 when omitted, returns all default tokens plus 5 top gainers.',required:!1},{name:"buy_button_label",type:"string",description:`Label template for the per-token "Buy" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. One button is rendered per trending token, with "{token}" replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "Buy {token}". Vietnamese example: "Mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_prompt_template",type:"string",description:`A short "buy" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a token's Buy button is clicked. "{token}" is replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0}]);f(this,"service");this.service=new Sn({baseUrl:r?.pantographUrl})}async run(r,n){let i=Yb(r.chain,n),o=r.buy_button_label||"",a=r.buy_prompt_template||"",s=typeof r.limit=="number"&&Number.isFinite(r.limit)&&r.limit>0?Math.floor(r.limit):void 0,l=await this.service.getTrendingTokens({chain:i,limit:s});if(!l.success)return{error:l.error||"Failed to fetch trending tokens"};let u=l.data??[],c=new Set,d=[];for(let h of u){let m=h.symbol?.trim();!m||c.has(m.toLowerCase())||(c.add(m.toLowerCase()),d.push({label:this.fillTemplate(o,m,"Buy {token}"),prompt:this.fillTemplate(a,m,"buy {token}")}))}return{_instructions:`Start with a one-line header like "Here are some of the top trending tokens on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
443
443
  <rank>. <name> (<symbol>)
444
444
  - Price: <usdPrice>
445
445
  - Market Cap: <marketCap>