diff --git a/.gitattributes b/.gitattributes
index 0e0c2db98..f460effb1 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,4 +1,6 @@
-resources/ filter=lfs diff=lfs merge=lfs -text
+resources/media/nxtscape-productivity.gif filter=lfs diff=lfs merge=lfs -text
resources/nxtscape-productivity.gif filter=lfs diff=lfs merge=lfs -text
+resources/media/nxtscape-agent.gif filter=lfs diff=lfs merge=lfs -text
+resources/media/nxtscape-chat.gif filter=lfs diff=lfs merge=lfs -text
docs/images/** filter=lfs diff=lfs merge=lfs -text
docs/videos/** filter=lfs diff=lfs merge=lfs -text
diff --git a/.gitignore b/.gitignore
index c20d58e27..c8657471c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,8 +1,7 @@
**/.DS_Store
.gcs_entries
-build/
-dmg/
-scripts/__pycache__/
-scripts/patches/__pycache__/
-releases/
-.vscode/
\ No newline at end of file
+**/dmg
+**/env
+**/logs
+**/old-scripts
+**/__pycache__/**
diff --git a/CHROMIUM_VERSION b/CHROMIUM_VERSION
new file mode 100644
index 000000000..5aefa8b84
--- /dev/null
+++ b/CHROMIUM_VERSION
@@ -0,0 +1,4 @@
+MAJOR=137
+MINOR=0
+BUILD=7151
+PATCH=69
\ No newline at end of file
diff --git a/README.md b/README.md
index 6cc503064..0883073de 100644
--- a/README.md
+++ b/README.md
@@ -13,7 +13,7 @@
-
+
@@ -33,7 +33,7 @@
## What makes NXTscape special
+
+
+
+
${e}
`:e;Object.keys(s.metadata??{}).length&&(i+=`=(U||0)&&(ne.length=u),void 0===U&&void 0===B&&0===d?ne.splice(u,0,{instanceLocation:a,keyword:"contains",keywordLocation:l,error:"Array does not contain item matching schema."}):void 0!==U&&dB&&ne.push({instanceLocation:a,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${B} items matching schema. ${d} items were found.`})}if(!u&&void 0!==D){const u=`${o}/unevaluatedItems`;for(;l=G||e>G)&&ne.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${Y?"or equal to ":""} ${G}.`})):(void 0!==K&&e G&&ne.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${G}.`}),void 0!==V&&e<=V&&ne.push({instanceLocation:a,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${e} is less than ${V}.`}),void 0!==Y&&e>=Y&&ne.push({instanceLocation:a,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Y}.`})),void 0!==J){const t=e%J;Math.abs(0-t)>=1.1920929e-7&&Math.abs(J-t)>=1.1920929e-7&&ne.push({instanceLocation:a,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${e} is not a multiple of ${J}.`})}}else if("string"===u){const t=void 0===Z&&void 0===X?0:function(e){let t,n=0,r=e.length,s=0;for(;s =55296&&t<=56319&&s X&&ne.push({instanceLocation:a,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${t} > ${X}).`}),void 0===Q||new RegExp(Q,"u").test(e)||ne.push({instanceLocation:a,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),void 0!==x&&Gt[x]&&!Gt[x](e)&&ne.push({instanceLocation:a,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${x}".`})}return{valid:0===ne.length,errors:ne}}!function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"}(en||(en={}));class nn{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Bt(e)}validate(e){return tn(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Bt(e,this.lookup)}}var rn=s(3490);class sn extends Rt{async*_transform(e){for await(const t of e)"string"==typeof t?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:"parser"})}}class an extends sn{constructor(e){super(e),Object.defineProperty(this,"diff",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.diff=e?.diff??this.diff}async*_transform(e){let t,n;for await(const r of e){if("string"!=typeof r&&"string"!=typeof r.content)throw new Error("Cannot handle non-string output.");let e;if((0,rn.AJ)(r)){if("string"!=typeof r.content)throw new Error("Cannot handle non-string message output.");e=new wt.ChatGenerationChunk({message:r,text:r.content})}else if((0,rn.ny)(r)){if("string"!=typeof r.content)throw new Error("Cannot handle non-string message output.");e=new wt.ChatGenerationChunk({message:(0,Ee.ih)(r),text:r.content})}else e=new wt.GenerationChunk({text:r});n=void 0===n?e:n.concat(e);const s=await this.parsePartialResult([n]);null==s||jt(s,t)||(this.diff?yield this._diff(t,s):yield s,t=s)}}getFormatInstructions(){return""}}class on extends sn{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","bytes"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"textEncoder",{enumerable:!0,configurable:!0,writable:!0,value:new TextEncoder})}static lc_name(){return"BytesOutputParser"}parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}}class cn extends sn{constructor(){super(...arguments),Object.defineProperty(this,"re",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async*_transform(e){let t="";for await(const n of e)if(t+="string"==typeof n?n:n.content,this.re){const e=[...t.matchAll(this.re)];if(e.length>1){let n=0;for(const t of e.slice(0,-1))yield[t[1]],n+=(t.index??0)+t[0].length;t=t.slice(n)}}else{const e=await this.parse(t);if(e.length>1){for(const t of e.slice(0,-1))yield[t];t=e[e.length-1]}}for(const e of await this.parse(t))yield[e]}}class ln extends cn{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","list"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"CommaSeparatedListOutputParser"}async parse(e){try{return e.trim().split(",").map((e=>e.trim()))}catch(t){throw new Nt(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}}class un extends cn{constructor({length:e,separator:t}){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","list"]}),Object.defineProperty(this,"length",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"separator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.length=e,this.separator=t||","}async parse(e){try{const t=e.trim().split(this.separator).map((e=>e.trim()));if(void 0!==this.length&&t.length!==this.length)throw new Nt(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){if(Object.getPrototypeOf(t)===Nt.prototype)throw t;throw new Nt(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${void 0===this.length?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}}class dn extends cn{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","list"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"re",{enumerable:!0,configurable:!0,writable:!0,value:/\d+\.\s([^\n]+)/g})}static lc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return"Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz"}async parse(e){return[...e.matchAll(this.re)??[]].map((e=>e[1]))}}class hn extends cn{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","list"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"re",{enumerable:!0,configurable:!0,writable:!0,value:/^\s*[-*]\s([^\n]+)$/gm})}static lc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return"Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz"}async parse(e){return[...e.matchAll(this.re)??[]].map((e=>e[1]))}}class pn extends sn{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","string"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"StrOutputParser"}parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentComplexToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce(((e,t)=>e+this._messageContentComplexToString(t)),"")}}class fn extends Rt{static lc_name(){return"StructuredOutputParser"}toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","structured"]})}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){return new this(R.z.object(Object.fromEntries(Object.entries(e).map((([e,t])=>[e,R.z.string().describe(t)])))))}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.\n\n"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.\n\nFor example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}\nwould match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.\nThus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.\n\nYour output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!\n\nHere is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:\n\`\`\`json\n${JSON.stringify((0,bt.Ik)(this.schema))}\n\`\`\`\n`}async parse(e){try{const t=(e.includes("```")?e.trim().split(/```(?:json)?/)[1]:e.trim()).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,((e,t)=>`"${t.replace(/\n/g,"\\n")}"`)).replace(/\n/g,"");return await this.schema.parseAsync(JSON.parse(t))}catch(t){throw new Nt(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}}class mn extends fn{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(e){const t=e?.interpolationDepth??1;if(t<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:\n\`\`\`json\n${this._schemaToInstruction((0,bt.Ik)(this.schema)).replaceAll("{","{".repeat(t)).replaceAll("}","}".repeat(t))}\n\`\`\``}_schemaToInstruction(e,t=2){const n=e;if("type"in n){let e,r=!1;if(Array.isArray(n.type)){const t=n.type.findIndex((e=>"null"===e));-1!==t&&(r=!0,n.type.splice(t,1)),e=n.type.join(" | ")}else e=n.type;if("object"===n.type&&n.properties){const e=n.description?` // ${n.description}`:"",r=Object.entries(n.properties).map((([e,r])=>{const s=n.required?.includes(e)?"":" (optional)";return`${" ".repeat(t)}"${e}": ${this._schemaToInstruction(r,t+2)}${s}`})).join("\n");return`{\n${r}\n${" ".repeat(t-2)}}${e}`}if("array"===n.type&&n.items){const e=n.description?` // ${n.description}`:"";return`array[\n${" ".repeat(t)}${this._schemaToInstruction(n.items,t+2)}\n${" ".repeat(t-2)}] ${e}`}const s=r?" (nullable)":"";return`${e}${n.description?` // ${n.description}`:""}${s}`}if("anyOf"in n)return n.anyOf.map((e=>this._schemaToInstruction(e,t))).join(`\n${" ".repeat(t-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){return new this(R.z.object(Object.fromEntries(Object.entries(e).map((([e,t])=>[e,R.z.string().describe(t)])))))}}class gn extends Rt{constructor({inputSchema:e}){super(...arguments),Object.defineProperty(this,"structuredInputParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.structuredInputParser=new mn(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(t){throw new Nt(`Failed to parse. Text: "${e}". Error: ${t}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}}var yn=s(6150),bn=s(780);class wn extends an{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"JsonOutputParser"}_diff(e,t){if(t)return e?(0,yn.UD)(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return(0,bn.D)(e[0].text)}async parse(e){return(0,bn.D)(e,JSON.parse)}getFormatInstructions(){return""}}const vn=function(){const e={parser:function(e,t){return new n(e,t)}};e.SAXParser=n,e.SAXStream=i,e.createStream=function(e,t){return new i(e,t)},e.MAX_BUFFER_LENGTH=65536;const t=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];function n(r,s){if(!(this instanceof n))return new n(r,s);var i=this;!function(e){for(var n=0,r=t.length;n "===i?(E(r,"onsgmldeclaration",r.sgmlDecl),r.sgmlDecl="",r.state=S.TEXT):g(i)?(r.state=S.SGML_DECL_QUOTED,r.sgmlDecl+=i):r.sgmlDecl+=i;continue;case S.SGML_DECL_QUOTED:i===r.q&&(r.state=S.SGML_DECL,r.q=""),r.sgmlDecl+=i;continue;case S.DOCTYPE:">"===i?(r.state=S.TEXT,E(r,"ondoctype",r.doctype),r.doctype=!0):(r.doctype+=i,"["===i?r.state=S.DOCTYPE_DTD:g(i)&&(r.state=S.DOCTYPE_QUOTED,r.q=i));continue;case S.DOCTYPE_QUOTED:r.doctype+=i,i===r.q&&(r.q="",r.state=S.DOCTYPE);continue;case S.DOCTYPE_DTD:r.doctype+=i,"]"===i?r.state=S.DOCTYPE:g(i)&&(r.state=S.DOCTYPE_DTD_QUOTED,r.q=i);continue;case S.DOCTYPE_DTD_QUOTED:r.doctype+=i,i===r.q&&(r.state=S.DOCTYPE_DTD,r.q="");continue;case S.COMMENT:"-"===i?r.state=S.COMMENT_ENDING:r.comment+=i;continue;case S.COMMENT_ENDING:"-"===i?(r.state=S.COMMENT_ENDED,r.comment=P(r.opt,r.comment),r.comment&&E(r,"oncomment",r.comment),r.comment=""):(r.comment+="-"+i,r.state=S.COMMENT);continue;case S.COMMENT_ENDED:">"!==i?(O(r,"Malformed comment"),r.comment+="--"+i,r.state=S.COMMENT):r.state=S.TEXT;continue;case S.CDATA:"]"===i?r.state=S.CDATA_ENDING:r.cdata+=i;continue;case S.CDATA_ENDING:"]"===i?r.state=S.CDATA_ENDING_2:(r.cdata+="]"+i,r.state=S.CDATA);continue;case S.CDATA_ENDING_2:">"===i?(r.cdata&&E(r,"oncdata",r.cdata),E(r,"onclosecdata"),r.cdata="",r.state=S.TEXT):"]"===i?r.cdata+="]":(r.cdata+="]]"+i,r.state=S.CDATA);continue;case S.PROC_INST:"?"===i?r.state=S.PROC_INST_ENDING:m(i)?r.state=S.PROC_INST_BODY:r.procInstName+=i;continue;case S.PROC_INST_BODY:if(!r.procInstBody&&m(i))continue;"?"===i?r.state=S.PROC_INST_ENDING:r.procInstBody+=i;continue;case S.PROC_INST_ENDING:">"===i?(E(r,"onprocessinginstruction",{name:r.procInstName,body:r.procInstBody}),r.procInstName=r.procInstBody="",r.state=S.TEXT):(r.procInstBody+="?"+i,r.state=S.PROC_INST_BODY);continue;case S.OPEN_TAG:b(h,i)?r.tagName+=i:($(r),">"===i?N(r):"/"===i?r.state=S.OPEN_TAG_SLASH:(m(i)||O(r,"Invalid character in tag name"),r.state=S.ATTRIB));continue;case S.OPEN_TAG_SLASH:">"===i?(N(r,!0),j(r)):(O(r,"Forward-slash in opening tag not followed by >"),r.state=S.ATTRIB);continue;case S.ATTRIB:if(m(i))continue;">"===i?N(r):"/"===i?r.state=S.OPEN_TAG_SLASH:b(d,i)?(r.attribName=i,r.attribValue="",r.state=S.ATTRIB_NAME):O(r,"Invalid attribute name");continue;case S.ATTRIB_NAME:"="===i?r.state=S.ATTRIB_VALUE:">"===i?(O(r,"Attribute without value"),r.attribValue=r.attribName,R(r),N(r)):m(i)?r.state=S.ATTRIB_NAME_SAW_WHITE:b(h,i)?r.attribName+=i:O(r,"Invalid attribute name");continue;case S.ATTRIB_NAME_SAW_WHITE:if("="===i)r.state=S.ATTRIB_VALUE;else{if(m(i))continue;O(r,"Attribute without value"),r.tag.attributes[r.attribName]="",r.attribValue="",E(r,"onattribute",{name:r.attribName,value:""}),r.attribName="",">"===i?N(r):b(d,i)?(r.attribName=i,r.state=S.ATTRIB_NAME):(O(r,"Invalid attribute name"),r.state=S.ATTRIB)}continue;case S.ATTRIB_VALUE:if(m(i))continue;g(i)?(r.q=i,r.state=S.ATTRIB_VALUE_QUOTED):(O(r,"Unquoted attribute value"),r.state=S.ATTRIB_VALUE_UNQUOTED,r.attribValue=i);continue;case S.ATTRIB_VALUE_QUOTED:if(i!==r.q){"&"===i?r.state=S.ATTRIB_VALUE_ENTITY_Q:r.attribValue+=i;continue}R(r),r.q="",r.state=S.ATTRIB_VALUE_CLOSED;continue;case S.ATTRIB_VALUE_CLOSED:m(i)?r.state=S.ATTRIB:">"===i?N(r):"/"===i?r.state=S.OPEN_TAG_SLASH:b(d,i)?(O(r,"No whitespace between attributes"),r.attribName=i,r.attribValue="",r.state=S.ATTRIB_NAME):O(r,"Invalid attribute name");continue;case S.ATTRIB_VALUE_UNQUOTED:if(!y(i)){"&"===i?r.state=S.ATTRIB_VALUE_ENTITY_U:r.attribValue+=i;continue}R(r),">"===i?N(r):r.state=S.ATTRIB;continue;case S.CLOSE_TAG:if(r.tagName)">"===i?j(r):b(h,i)?r.tagName+=i:r.script?(r.script+=""+r.tagName,r.tagName="",r.state=S.SCRIPT):(m(i)||O(r,"Invalid tagname in closing tag"),r.state=S.CLOSE_TAG_SAW_WHITE);else{if(m(i))continue;w(d,i)?r.script?(r.script+=""+i,r.state=S.SCRIPT):O(r,"Invalid tagname in closing tag."):r.tagName=i}continue;case S.CLOSE_TAG_SAW_WHITE:if(m(i))continue;">"===i?j(r):O(r,"Invalid characters in closing tag");continue;case S.TEXT_ENTITY:case S.ATTRIB_VALUE_ENTITY_Q:case S.ATTRIB_VALUE_ENTITY_U:var u,v;switch(r.state){case S.TEXT_ENTITY:u=S.TEXT,v="textNode";break;case S.ATTRIB_VALUE_ENTITY_Q:u=S.ATTRIB_VALUE_QUOTED,v="attribValue";break;case S.ATTRIB_VALUE_ENTITY_U:u=S.ATTRIB_VALUE_UNQUOTED,v="attribValue"}if(";"===i)if(r.opt.unparsedEntities){var _=F(r);r.entity="",r.state=u,r.write(_)}else r[v]+=F(r),r.entity="",r.state=u;else b(r.entity.length?f:p,i)?r.entity+=i:(O(r,"Invalid character in entity name"),r[v]+="&"+r.entity+i,r.entity="",r.state=u);continue;default:throw new Error(r,"Unknown state: "+r.state)}r.position>=r.bufferCheckPosition&&function(n){for(var r=Math.max(e.MAX_BUFFER_LENGTH,10),s=0,i=0,a=t.length;ir)switch(t[i]){case"textNode":C(n);break;case"cdata":E(n,"oncdata",n.cdata),n.cdata="";break;case"script":E(n,"onscript",n.script),n.script="";break;default:I(n,"Max buffer length exceeded: "+t[i])}s=Math.max(s,o)}var c=e.MAX_BUFFER_LENGTH-s;n.bufferCheckPosition=c+n.position}(r);return r},resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){var e;C(e=this),""!==e.cdata&&(E(e,"oncdata",e.cdata),e.cdata=""),""!==e.script&&(E(e,"onscript",e.script),e.script="")}};var r=ReadableStream;r||(r=function(){});var s=e.EVENTS.filter((function(e){return"error"!==e&&"end"!==e}));function i(e,t){if(!(this instanceof i))return new i(e,t);r.apply(this),this._parser=new n(e,t),this.writable=!0,this.readable=!0;var a=this;this._parser.onend=function(){a.emit("end")},this._parser.onerror=function(e){a.emit("error",e),a._parser.error=null},this._decoder=null,s.forEach((function(e){Object.defineProperty(a,"on"+e,{get:function(){return a._parser["on"+e]},set:function(t){if(!t)return a.removeAllListeners(e),a._parser["on"+e]=t,t;a.on(e,t)},enumerable:!0,configurable:!1})}))}i.prototype=Object.create(r.prototype,{constructor:{value:i}}),i.prototype.write=function(e){return this._parser.write(e.toString()),this.emit("data",e),!0},i.prototype.end=function(e){return e&&e.length&&this.write(e),this._parser.end(),!0},i.prototype.on=function(e,t){var n=this;return n._parser["on"+e]||-1===s.indexOf(e)||(n._parser["on"+e]=function(){var t=1===arguments.length?[arguments[0]]:Array.apply(null,arguments);t.splice(0,0,e),n.emit.apply(n,t)}),r.prototype.on.call(n,e,t)};var a="[CDATA[",o="DOCTYPE",c="http://www.w3.org/XML/1998/namespace",l="http://www.w3.org/2000/xmlns/",u={xml:c,xmlns:l},d=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,h=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,p=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,f=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function m(e){return" "===e||"\n"===e||"\r"===e||"\t"===e}function g(e){return'"'===e||"'"===e}function y(e){return">"===e||m(e)}function b(e,t){return e.test(t)}function w(e,t){return!b(e,t)}var v,_,k,S=0;for(var T in e.STATE={BEGIN:S++,BEGIN_WHITESPACE:S++,TEXT:S++,TEXT_ENTITY:S++,OPEN_WAKA:S++,SGML_DECL:S++,SGML_DECL_QUOTED:S++,DOCTYPE:S++,DOCTYPE_QUOTED:S++,DOCTYPE_DTD:S++,DOCTYPE_DTD_QUOTED:S++,COMMENT_STARTING:S++,COMMENT:S++,COMMENT_ENDING:S++,COMMENT_ENDED:S++,CDATA:S++,CDATA_ENDING:S++,CDATA_ENDING_2:S++,PROC_INST:S++,PROC_INST_BODY:S++,PROC_INST_ENDING:S++,OPEN_TAG:S++,OPEN_TAG_SLASH:S++,ATTRIB:S++,ATTRIB_NAME:S++,ATTRIB_NAME_SAW_WHITE:S++,ATTRIB_VALUE:S++,ATTRIB_VALUE_QUOTED:S++,ATTRIB_VALUE_CLOSED:S++,ATTRIB_VALUE_UNQUOTED:S++,ATTRIB_VALUE_ENTITY_Q:S++,ATTRIB_VALUE_ENTITY_U:S++,CLOSE_TAG:S++,CLOSE_TAG_SAW_WHITE:S++,SCRIPT:S++,SCRIPT_ENDING:S++},e.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},e.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(e.ENTITIES).forEach((function(t){var n=e.ENTITIES[t],r="number"==typeof n?String.fromCharCode(n):n;e.ENTITIES[t]=r})),e.STATE)e.STATE[e.STATE[T]]=T;function x(e,t,n){e[t]&&e[t](n)}function E(e,t,n){e.textNode&&C(e),x(e,t,n)}function C(e){e.textNode=P(e.opt,e.textNode),e.textNode&&x(e,"ontext",e.textNode),e.textNode=""}function P(e,t){return e.trim&&(t=t.trim()),e.normalize&&(t=t.replace(/\s+/g," ")),t}function I(e,t){return C(e),e.trackPosition&&(t+="\nLine: "+e.line+"\nColumn: "+e.column+"\nChar: "+e.c),t=new Error(t),e.error=t,x(e,"onerror",t),e}function A(e){return e.sawRoot&&!e.closedRoot&&O(e,"Unclosed root tag"),e.state!==S.BEGIN&&e.state!==S.BEGIN_WHITESPACE&&e.state!==S.TEXT&&I(e,"Unexpected end"),C(e),e.c="",e.closed=!0,x(e,"onend"),n.call(e,e.strict,e.opt),e}function O(e,t){if("object"!=typeof e||!(e instanceof n))throw new Error("bad call to strictFail");e.strict&&I(e,t)}function $(e){e.strict||(e.tagName=e.tagName[e.looseCase]());var t=e.tags[e.tags.length-1]||e,n=e.tag={name:e.tagName,attributes:{}};e.opt.xmlns&&(n.ns=t.ns),e.attribList.length=0,E(e,"onopentagstart",n)}function M(e,t){var n=e.indexOf(":")<0?["",e]:e.split(":"),r=n[0],s=n[1];return t&&"xmlns"===e&&(r="xmlns",s=""),{prefix:r,local:s}}function R(e){if(e.strict||(e.attribName=e.attribName[e.looseCase]()),-1!==e.attribList.indexOf(e.attribName)||e.tag.attributes.hasOwnProperty(e.attribName))e.attribName=e.attribValue="";else{if(e.opt.xmlns){var t=M(e.attribName,!0),n=t.prefix,r=t.local;if("xmlns"===n)if("xml"===r&&e.attribValue!==c)O(e,"xml: prefix must be bound to "+c+"\nActual: "+e.attribValue);else if("xmlns"===r&&e.attribValue!==l)O(e,"xmlns: prefix must be bound to "+l+"\nActual: "+e.attribValue);else{var s=e.tag,i=e.tags[e.tags.length-1]||e;s.ns===i.ns&&(s.ns=Object.create(i.ns)),s.ns[r]=e.attribValue}e.attribList.push([e.attribName,e.attribValue])}else e.tag.attributes[e.attribName]=e.attribValue,E(e,"onattribute",{name:e.attribName,value:e.attribValue});e.attribName=e.attribValue=""}}function N(e,t){if(e.opt.xmlns){var n=e.tag,r=M(e.tagName);n.prefix=r.prefix,n.local=r.local,n.uri=n.ns[r.prefix]||"",n.prefix&&!n.uri&&(O(e,"Unbound namespace prefix: "+JSON.stringify(e.tagName)),n.uri=r.prefix);var s=e.tags[e.tags.length-1]||e;n.ns&&s.ns!==n.ns&&Object.keys(n.ns).forEach((function(t){E(e,"onopennamespace",{prefix:t,uri:n.ns[t]})}));for(var i=0,a=e.attribList.length;i",void(e.state=S.TEXT);if(e.script){if("script"!==e.tagName)return e.script+=""+e.tagName+">",e.tagName="",void(e.state=S.SCRIPT);E(e,"onscript",e.script),e.script=""}var t=e.tags.length,n=e.tagName;e.strict||(n=n[e.looseCase]());for(var r=n;t--;){if(e.tags[t].name===r)break;O(e,"Unexpected close tag")}if(t<0)return O(e,"Unmatched closing tag: "+e.tagName),e.textNode+=""+e.tagName+">",void(e.state=S.TEXT);e.tagName=n;for(var s=e.tags.length;s-- >t;){var i=e.tag=e.tags.pop();e.tagName=e.tag.name,E(e,"onclosetag",e.tagName);var a={};for(var o in i.ns)a[o]=i.ns[o];var c=e.tags[e.tags.length-1]||e;e.opt.xmlns&&i.ns!==c.ns&&Object.keys(i.ns).forEach((function(t){var n=i.ns[t];E(e,"onclosenamespace",{prefix:t,uri:n})}))}0===t&&(e.closedRoot=!0),e.tagName=e.attribValue=e.attribName="",e.attribList.length=0,e.state=S.TEXT}function F(e){var t,n=e.entity,r=n.toLowerCase(),s="";return e.ENTITIES[n]?e.ENTITIES[n]:e.ENTITIES[r]?e.ENTITIES[r]:("#"===(n=r).charAt(0)&&("x"===n.charAt(1)?(n=n.slice(2),s=(t=parseInt(n,16)).toString(16)):(n=n.slice(1),s=(t=parseInt(n,10)).toString(10))),n=n.replace(/^0+/,""),isNaN(t)||s.toLowerCase()!==n?(O(e,"Invalid character entity"),"&"+e.entity+";"):String.fromCodePoint(t))}function L(e,t){"<"===t?(e.state=S.OPEN_WAKA,e.startTagPosition=e.position):m(t)||(O(e,"Non-whitespace before first tag."),e.textNode=t,e.state=S.TEXT)}function D(e,t){var n="";return t 1114111||_(a)!==a)throw RangeError("Invalid code point: "+a);a<=65535?n.push(a):(e=55296+((a-=65536)>>10),t=a%1024+56320,n.push(e,t)),(r+1===s||n.length>16384)&&(i+=v.apply(null,n),n.length=0)}return i},Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:k,configurable:!0,writable:!0}):String.fromCodePoint=k),e},_n=vn(),kn='The output should be formatted as a XML file.\n1. Output should conform to the tags below. \n2. If tags are not given, make them on your own.\n3. Remember to always open and close all the tags.\n\nAs an example, for the tags ["foo", "bar", "baz"]:\n1. String " \n " is a well-formatted instance of the schema. \n2. String "\n \n\n \n " is a badly-formatted instance.\n3. String "\n \n " is a badly-formatted instance.\n\nHere are the output tags:\n```\n{tags}\n```';class Sn extends an{constructor(e){super(e),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.tags=e?.tags}static lc_name(){return"XMLOutputParser"}_diff(e,t){if(t)return e?(0,yn.UD)(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return En(e[0].text)}async parse(e){return En(e)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?kn.replace("{tags}",this.tags?.join(", ")??""):kn}}const Tn=e=>e.split("\n").map((e=>e.replace(/^\s+/,""))).join("\n").trim(),xn=e=>{if(0===Object.keys(e).length)return{};const t={};return e.children.length>0?(t[e.name]=e.children.map(xn),t):(t[e.name]=e.text??void 0,t)};function En(e){const t=Tn(e),n=_n.parser(!0);let r={};const s=[];n.onopentag=e=>{const t={name:e.name,attributes:e.attributes,children:[],text:"",isSelfClosing:e.isSelfClosing};if(s.length>0){s[s.length-1].children.push(t)}else r=t;e.isSelfClosing||s.push(t)},n.onclosetag=()=>{if(s.length>0){const e=s.pop();0===s.length&&e&&(r=e)}},n.ontext=e=>{if(s.length>0){s[s.length-1].text+=e}},n.onattribute=e=>{if(s.length>0){s[s.length-1].attributes[e.name]=e.value}};const i=/```(xml)?(.*)```/s.exec(t),a=i?i[2]:t;return n.write(a).close(),r&&"?xml"===r.name&&(r=r.children[0]),xn(r)}var Cn=s(6993),Pn=s(3766),In=s(2771);class An extends Cn.m{static lc_name(){return"PipelinePromptTemplate"}constructor(e){super({...e,inputVariables:[]}),Object.defineProperty(this,"pipelinePrompts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"finalPrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.pipelinePrompts=e.pipelinePrompts,this.finalPrompt=e.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){const e=this.pipelinePrompts.map((e=>e.name)),t=this.pipelinePrompts.map((t=>t.prompt.inputVariables.filter((t=>!e.includes(t))))).flat();return[...new Set(t)]}static extractRequiredInputValues(e,t){return t.reduce(((t,n)=>(t[n]=e[n],t)),{})}async formatPipelinePrompts(e){const t=await this.mergePartialAndUserVariables(e);for(const{name:e,prompt:n}of this.pipelinePrompts){const r=An.extractRequiredInputValues(t,n.inputVariables);n instanceof Pn.RZ?t[e]=await n.formatMessages(r):t[e]=await n.format(r)}return An.extractRequiredInputValues(t,this.finalPrompt.inputVariables)}async formatPromptValue(e){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(e))}async format(e){return this.finalPrompt.format(await this.formatPipelinePrompts(e))}async partial(e){const t={...this};return t.inputVariables=this.inputVariables.filter((t=>!(t in e))),t.partialVariables={...this.partialVariables??{},...e},new An(t)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}}var On=s(3650),$n=s(329),Mn=s(9849),Rn=s(6279);function Nn(e){return"object"==typeof e&&null!=e&&"withStructuredOutput"in e&&"function"==typeof e.withStructuredOutput}class jn extends Pn.RZ{get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"method",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","structured"]}),this.schema=e.schema,this.method=e.method}pipe(e){if(Nn(e))return super.pipe(e.withStructuredOutput(this.schema));if(function(e){return"object"==typeof e&&null!=e&&"lc_id"in e&&Array.isArray(e.lc_id)&&"langchain_core/runnables/RunnableBinding"===e.lc_id.join("/")}(e)&&Nn(e.bound))return super.pipe(this.method?e.bound.withStructuredOutput(this.schema,{method:this.method}).bind(e.kwargs??{}).withConfig(e.config):e.bound.withStructuredOutput(this.schema).bind(e.kwargs??{}).withConfig(e.config));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(e,t,n){return jn.fromMessages(e,{schema:t,method:n})}}var Fn=s(4552);class Ln extends j.YN{constructor(e){super(e),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw new Error("Not implemented!")}async invoke(e,t){return this.getRelevantDocuments(e,(0,F.ZI)(t))}async getRelevantDocuments(e,t){const n=(0,F.ZI)((0,Re.parseCallbackConfigArg)(t)),r=await Re.CallbackManager.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}),s=await(r?.handleRetrieverStart(this.toJSON(),e,n.runId,void 0,void 0,void 0,n.runName));try{const t=await this._getRelevantDocuments(e,s);return await(s?.handleRetrieverEnd(t)),t}catch(e){throw await(s?.handleRetrieverError(e)),e}}}class Dn extends be.Serializable{}class zn extends Dn{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","storage"]}),Object.defineProperty(this,"store",{enumerable:!0,configurable:!0,writable:!0,value:{}})}async mget(e){return e.map((e=>this.store[e]))}async mset(e){for(const[t,n]of e)this.store[t]=n}async mdelete(e){for(const t of e)delete this.store[t]}async*yieldKeys(e){const t=Object.keys(this.store);for(const n of t)(void 0===e||n.startsWith(e))&&(yield n)}}var Un=s(8009),Bn=s(4350),qn=s(199);function Wn(e){return vt(e)?(0,bt.Ik)(e):e}function Hn(e){if(!e||"object"!=typeof e||0===Object.keys(e).length||Array.isArray(e))return!1;if("type"in e)return"string"==typeof e.type?"string"===e.type:!!Array.isArray(e.type)&&e.type.every((e=>"string"===e));if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every((e=>"string"==typeof e));if("const"in e)return"string"==typeof e.const;if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some((e=>Hn(e)));if("anyOf"in e&&Array.isArray(e.anyOf)||"oneOf"in e&&Array.isArray(e.oneOf)){const t="anyOf"in e?e.anyOf:e.oneOf;return t.length>0&&t.every((e=>Hn(e)))}if("not"in e)return!1;if("$ref"in e&&"string"==typeof e.$ref){const t=e.$ref,n=Bt(e);return!!n[t]&&Hn(n[t])}return!1}function Kn(e){return void 0!==e&&Array.isArray(e.lc_namespace)}function Gn(e){return void 0!==e&&j.YN.isRunnable(e)&&"lc_name"in e.constructor&&"function"==typeof e.constructor.lc_name&&"RunnableToolLike"===e.constructor.lc_name()}function Vn(e){return!!e&&"object"==typeof e&&"name"in e&&"schema"in e&&(vt(e.schema)||null!=e.schema&&"object"==typeof e.schema&&"type"in e.schema&&"string"==typeof e.schema.type&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function Yn(e){return Vn(e)||Gn(e)||Kn(e)}class Jn extends gt{get lc_namespace(){return["langchain","tools"]}constructor(e){super(e??{}),Object.defineProperty(this,"returnDirect",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"verboseParsingErrors",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"responseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"content"}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat}async invoke(e,t){let n,r=(0,F.ZI)(t);return(0,qn.Ky)(e)?(n=e.args,r={...r,toolCall:e}):n=e,this.call(n,r)}async call(e,t,n){const r=(0,qn.Ky)(e)?e.args:e;let s;if(vt(this.schema))try{s=await this.schema.parseAsync(r)}catch(t){let n="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(n=`${n}\nDetails: ${t.message}`),new qn.qe(n,JSON.stringify(e))}else{const t=tn(r,this.schema);if(!t.valid){let n="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(n=`${n}\nDetails: ${t.errors.map((e=>`${e.keywordLocation}: ${e.error}`)).join("\n")}`),new qn.qe(n,JSON.stringify(e))}s=r}const i=(0,Re.parseCallbackConfigArg)(t),a=Re.CallbackManager.configure(i.callbacks,this.callbacks,i.tags||n,this.tags,i.metadata,this.metadata,{verbose:this.verbose}),o=await(a?.handleToolStart(this.toJSON(),"string"==typeof e?e:JSON.stringify(e),i.runId,void 0,void 0,void 0,i.runName));let c,l,u,d;delete i.runId;try{c=await this._call(s,o,i)}catch(e){throw await(o?.handleToolError(e)),e}if("content_and_artifact"===this.responseFormat){if(!Array.isArray(c)||2!==c.length)throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(c)}`);[l,u]=c}else l=c;(0,qn.Ky)(e)&&(d=e.id),!d&&(0,qn.hR)(i)&&(d=i.toolCall.id);const h=function(e){const{content:t,artifact:n,toolCallId:r}=e;return r&&!(0,Un.fK)(t)?"string"==typeof t||Array.isArray(t)&&t.every((e=>"object"==typeof e))?new Un.uf({content:t,artifact:n,tool_call_id:r,name:e.name}):new Un.uf({content:nr(t),artifact:n,tool_call_id:r,name:e.name}):t}({content:l,artifact:u,toolCallId:d,name:this.name});return await(o?.handleToolEnd(h)),h}}class Zn extends Jn{constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:R.z.object({input:R.z.string().optional()}).transform((e=>e.input))})}call(e,t){const n="string"==typeof e||null==e?{input:e}:e;return super.call(n,t)}}class Xn extends Zn{static lc_name(){return"DynamicTool"}constructor(e){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,t){const n=(0,Re.parseCallbackConfigArg)(t);return void 0===n.runName&&(n.runName=this.name),super.call(e,n)}async _call(e,t,n){return this.func(e,t,n)}}class Qn extends Jn{static lc_name(){return"DynamicStructuredTool"}constructor(e){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,t,n){const r=(0,Re.parseCallbackConfigArg)(t);return void 0===r.runName&&(r.runName=this.name),super.call(e,r,n)}_call(e,t,n){return this.func(e,t,n)}}class er{getTools(){return this.tools}}function tr(e,t){const n=t.schema&&vt(t.schema)&&(!("shape"in t.schema)||!t.schema.shape),r=Hn(t.schema);if(!t.schema||n||r)return new Xn({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(t,n,r)=>new Promise(((s,i)=>{const a=(0,F.tn)(r,{callbacks:n?.getChild()});Bn.Nx.runWithConfig((0,F.DY)(a),(async()=>{try{s(e(t,a))}catch(e){i(e)}}))}))});const s=t.schema,i=t.description??t.schema.description??`${t.name} tool`;return new Qn({...t,description:i,schema:s,func:async(t,n,r)=>new Promise(((s,i)=>{const a=(0,F.tn)(r,{callbacks:n?.getChild()});Bn.Nx.runWithConfig((0,F.DY)(a),(async()=>{try{s(e(t,a))}catch(e){i(e)}}))}))})}function nr(e){try{return JSON.stringify(e,null,2)}catch(t){return`${e}`}}var rr=s(1590),sr=s(6906),ir=s(3997),ar=s(9583);class or extends rr.BaseTracer{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"endpoint",{enumerable:!0,configurable:!0,writable:!0,value:(0,ar.getEnvironmentVariable)("LANGCHAIN_ENDPOINT")||"http://localhost:1984"}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:{"Content-Type":"application/json"}}),Object.defineProperty(this,"session",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const e=(0,ar.getEnvironmentVariable)("LANGCHAIN_API_KEY");e&&(this.headers["x-api-key"]=e)}async newSession(e){const t={start_time:Date.now(),name:e},n=await this.persistSession(t);return this.session=n,n}async loadSession(e){const t=`${this.endpoint}/sessions?name=${e}`;return this._handleSessionResponse(t)}async loadDefaultSession(){const e=`${this.endpoint}/sessions?name=default`;return this._handleSessionResponse(e)}async convertV2RunToRun(e){const t=this.session??await this.loadDefaultSession(),n=e.serialized;let r;if("llm"===e.run_type){const s=e.inputs.prompts?e.inputs.prompts:e.inputs.messages.map((e=>(0,Ee.Sw)(e)));r={uuid:e.id,start_time:e.start_time,end_time:e.end_time,execution_order:e.execution_order,child_execution_order:e.child_execution_order,serialized:n,type:e.run_type,session_id:t.id,prompts:s,response:e.outputs}}else if("chain"===e.run_type){const s=await Promise.all(e.child_runs.map((e=>this.convertV2RunToRun(e))));r={uuid:e.id,start_time:e.start_time,end_time:e.end_time,execution_order:e.execution_order,child_execution_order:e.child_execution_order,serialized:n,type:e.run_type,session_id:t.id,inputs:e.inputs,outputs:e.outputs,child_llm_runs:s.filter((e=>"llm"===e.type)),child_chain_runs:s.filter((e=>"chain"===e.type)),child_tool_runs:s.filter((e=>"tool"===e.type))}}else{if("tool"!==e.run_type)throw new Error(`Unknown run type: ${e.run_type}`);{const s=await Promise.all(e.child_runs.map((e=>this.convertV2RunToRun(e))));r={uuid:e.id,start_time:e.start_time,end_time:e.end_time,execution_order:e.execution_order,child_execution_order:e.child_execution_order,serialized:n,type:e.run_type,session_id:t.id,tool_input:e.inputs.input,output:e.outputs?.output,action:JSON.stringify(n),child_llm_runs:s.filter((e=>"llm"===e.type)),child_chain_runs:s.filter((e=>"chain"===e.type)),child_tool_runs:s.filter((e=>"tool"===e.type))}}}return r}async persistRun(e){let t,n;n=void 0!==e.run_type?await this.convertV2RunToRun(e):e,t="llm"===n.type?`${this.endpoint}/llm-runs`:"chain"===n.type?`${this.endpoint}/chain-runs`:`${this.endpoint}/tool-runs`;(await fetch(t,{method:"POST",headers:this.headers,body:JSON.stringify(n)})).ok}async persistSession(e){const t=`${this.endpoint}/sessions`,n=await fetch(t,{method:"POST",headers:this.headers,body:JSON.stringify(e)});return n.ok?{id:(await n.json()).id,...e}:{id:1,...e}}async _handleSessionResponse(e){const t=await fetch(e,{method:"GET",headers:this.headers});let n;if(!t.ok)return n={id:1,start_time:Date.now()},this.session=n,n;const r=await t.json();return 0===r.length?(n={id:1,start_time:Date.now()},this.session=n,n):([n]=r,this.session=n,n)}}async function cr(e){const t=new or;return e?await t.loadSession(e):await t.loadDefaultSession(),t}async function lr(){return new ir.LangChainTracer}var ur=s(1060);class dr extends rr.BaseTracer{constructor({exampleId:e}={}){super({_awaitHandler:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"run_collector"}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracedRuns",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.exampleId=e,this.tracedRuns=[]}async persistRun(e){const t={...e};t.reference_example_id=this.exampleId,this.tracedRuns.push(t)}}const hr=(e,t)=>e.reduce(((e,n,r)=>{const s=Math.floor(r/t),i=e[s]||[];return e[s]=i.concat([n]),e}),[]);function pr(e,t){const n="number"==typeof t?void 0:t;return{name:e.name,description:e.description,parameters:Wn(e.schema),...void 0!==n?.strict?{strict:n.strict}:{}}}function fr(e,t){const n="number"==typeof t?void 0:t;let r;return r=Yn(e)?{type:"function",function:pr(e)}:e,void 0!==n?.strict&&(r.function.strict=n.strict),r}function mr(e,t){let n=0,r=0,s=0;for(let i=0;i\n \nt.map((t=>n(e,t))).map((e=>Number.isNaN(e)?0:e))))}function wr(e,t=!1){const n=e.reduce(((e,t)=>Math.max(e,Tr(t).maxValue)),0);return e.map((e=>e.map((e=>t?1-e/n:e/n))))}function vr(e,t){return br(e,t,mr)}function _r(e,t){return br(e,t,gr)}function kr(e,t){return br(e,t,yr)}function Sr(e,t,n=.5,r=4){if(Math.min(r,t.length)<=0)return[];const s=vr(Array.isArray(e[0])?e:[e],t)[0],i=Tr(s).maxIndex,a=[t[i]],o=[i];for(;o.length {if(o.includes(s))return;const a=Math.max(...i[s]),c=n*t-(1-n)*a;c>e&&(e=c,r=s)})),a.push(t[r]),o.push(r)}return o}function Tr(e){if(0===e.length)return{maxIndex:-1,maxValue:NaN};let t=e[0],n=0;for(let r=1;r t&&(n=r,t=e[r]);return{maxIndex:n,maxValue:t}}class xr extends Ln{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),Object.defineProperty(this,"vectorStore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"k",{enumerable:!0,configurable:!0,writable:!0,value:4}),Object.defineProperty(this,"searchType",{enumerable:!0,configurable:!0,writable:!0,value:"similarity"}),Object.defineProperty(this,"searchKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,"mmr"===e.searchType&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if("mmr"===this.searchType){if("function"!=typeof this.vectorStore.maxMarginalRelevanceSearch)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},t?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild("vectorstore"))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}}class Er extends be.Serializable{constructor(e,t){super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","vectorstores",this._vectorstoreType()]}),Object.defineProperty(this,"embeddings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,t=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)).map((e=>e[0]))}async similaritySearchWithScore(e,t=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)}static fromTexts(e,t,n,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,t,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,t,n,r,s,i){if("number"==typeof e)return new xr({vectorStore:this,k:e,filter:t,tags:[...r??[],this._vectorstoreType()],metadata:s,verbose:i,callbacks:n});{const t={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 new xr("mmr"===e?.searchType?{...t,searchKwargs:e.searchKwargs}:{...t})}}}class Cr extends Er{static load(e,t){throw new Error("Not implemented")}}class Pr extends Rt{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["tests","fake"]})}getFormatInstructions(){return""}async parse(e){return e.split(",").map((e=>e.trim()))}}class Ir extends j.YN{constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["tests","fake"]}),Object.defineProperty(this,"returnOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}}class Ar extends Et{constructor(e){super(e),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thrownErrorString",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e,t,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const r=this.response??e;return await(n?.handleLLMNewToken(r)),r}}class Or extends Et{constructor(e){super(e),Object.defineProperty(this,"sleep",{enumerable:!0,configurable:!0,writable:!0,value:50}),Object.defineProperty(this,"responses",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thrownErrorString",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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);const t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const r=this.responses?.[0];this.responses=this.responses?.slice(1);for(const t of r??e)await new Promise((e=>setTimeout(e,this.sleep))),yield{text:t,generationInfo:{}},await(n?.handleLLMNewToken(t))}}class $r extends St{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(e,t,n){if(t?.stop?.length)return{generations:[{message:new N.AIMessage(t.stop[0]),text:t.stop[0]}]};const r=e.map((e=>"string"==typeof e.content?e.content:JSON.stringify(e.content,null,2))).join("\n");return await(n?.handleLLMNewToken(r)),{generations:[{message:new N.AIMessage(r),text:r}],llmOutput:{}}}}class Mr extends St{constructor({sleep:e=50,responses:t=[],chunks:n=[],toolStyle:r="openai",thrownErrorString:s,...i}){super(i),Object.defineProperty(this,"sleep",{enumerable:!0,configurable:!0,writable:!0,value:50}),Object.defineProperty(this,"responses",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"toolStyle",{enumerable:!0,configurable:!0,writable:!0,value:"openai"}),Object.defineProperty(this,"thrownErrorString",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tools",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.sleep=e,this.responses=t,this.chunks=n,this.toolStyle=r,this.thrownErrorString=s}_llmType(){return"fake"}bindTools(e){const t=[...this.tools,...e],n=t.map((e=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:e.name,description:e.description,parameters:Wn(e.schema)}};case"anthropic":return{name:e.name,description:e.description,input_schema:Wn(e.schema)};case"bedrock":return{toolSpec:{name:e.name,description:e.description,inputSchema:Wn(e.schema)}};case"google":return{name:e.name,description:e.description,parameters:Wn(e.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}})),r="google"===this.toolStyle?[{functionDeclarations:n}]:n,s=new Mr({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return s.tools=t,s.bind({tools:r})}async _generate(e,t,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const r=this.responses?.[0]?.content??e[0].content??"";return{generations:[{text:"",message:new N.AIMessage({content:r,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(const e of this.chunks){const t=new wt.ChatGenerationChunk({message:new N.AIMessageChunk({content:e.content,tool_calls:e.tool_calls,additional_kwargs:e.additional_kwargs??{}}),text:e.content?.toString()??""});yield t,await(n?.handleLLMNewToken(e.content,void 0,void 0,void 0,void 0,{chunk:t}))}return}const r=this.responses?.[0]??new N.AIMessage("string"==typeof e[0].content?e[0].content:""),s="string"==typeof r.content?r.content:"";for(const e of s){await new Promise((e=>setTimeout(e,this.sleep)));const t=new wt.ChatGenerationChunk({message:new N.AIMessageChunk({content:e}),text:e});yield t,await(n?.handleLLMNewToken(e,void 0,void 0,void 0,void 0,{chunk:t}))}}}class Rr extends Ln{constructor(e){super(),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["test","fake"]}),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:[new De({pageContent:"foo"}),new De({pageContent:"bar"})]}),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}}class Nr extends St{static lc_name(){return"FakeListChatModel"}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"responses",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"i",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"sleep",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"emitCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1});const{responses:t,sleep:n,emitCustomEvent:r}=e;this.responses=t,this.sleep=n,this.emitCustomEvent=r??this.emitCustomEvent}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(e,t,n){if(await this._sleepIfRequested(),t?.thrownErrorString)throw new Error(t.thrownErrorString);if(this.emitCustomEvent&&await(n?.handleCustomEvent("some_test_event",{someval:!0})),t?.stop?.length)return{generations:[this._formatGeneration(t.stop[0])]};{const e=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(e)],llmOutput:{}}}}_formatGeneration(e){return{message:new N.AIMessage(e),text:e}}async*_streamResponseChunks(e,t,n){const r=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await(n?.handleCustomEvent("some_test_event",{someval:!0}));for await(const e of r){if(await this._sleepIfRequested(),t?.thrownErrorString)throw new Error(t.thrownErrorString);const r=this._createResponseChunk(e);yield r,n?.handleLLMNewToken(e)}}async _sleepIfRequested(){void 0!==this.sleep&&await this._sleep()}async _sleep(){return new Promise((e=>{setTimeout((()=>e()),this.sleep)}))}_createResponseChunk(e){return new wt.ChatGenerationChunk({message:new N.AIMessageChunk({content:e}),text:e})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i {const t=await this.invoke(e);if(t.tool_calls?.[0]?.args)return t.tool_calls[0].args;if("string"==typeof t.content)return JSON.parse(t.content);throw new Error("No structured output found")}))}}class jr extends je{constructor(){super(),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","message","fake"]}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:[]})}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new N.HumanMessage(e))}async addAIChatMessage(e){this.messages.push(new N.AIMessage(e))}async clear(){this.messages=[]}}class Fr extends Fe{constructor(){super(),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","message","fake"]}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:[]})}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}}class Lr extends rr.BaseTracer{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"fake_tracer"}),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:[]})}persistRun(e){return this.runs.push(e),Promise.resolve()}}class Dr extends Jn{constructor(e){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}}class zr extends qe{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map((()=>[.1,.2,.3,.4])))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}}class Ur extends qe{constructor(e){super(e??{}),Object.defineProperty(this,"vectorSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map((e=>this.embedQuery(e))))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,"");const n=t.length%this.vectorSize,r=0===n?0:this.vectorSize-n,s=t.length+r;t=t.padEnd(s," ");const i=t.length/this.vectorSize,a=[];for(let e=0;e {let t=0;for(let n=0;n {this.runPromiseResolver=e}))}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}}class qr extends Er{_vectorstoreType(){return"memory"}constructor(e,{similarity:t,...n}={}){super(e,n),Object.defineProperty(this,"memoryVectors",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"similarity",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.similarity=t??mr}async addDocuments(e){const t=e.map((({pageContent:e})=>e));return this.addVectors(await this.embeddings.embedDocuments(t),e)}async addVectors(e,t){const n=e.map(((e,n)=>({content:t[n].pageContent,embedding:e,metadata:t[n].metadata})));this.memoryVectors=this.memoryVectors.concat(n)}async similaritySearchVectorWithScore(e,t,n){const r=this.memoryVectors.filter((e=>{if(!n)return!0;const t=new De({metadata:e.metadata,pageContent:e.content});return n(t)})),s=r.map(((t,n)=>({similarity:this.similarity(e,t.embedding),index:n}))).sort(((e,t)=>e.similarity>t.similarity?-1:0)).slice(0,t);return s.map((e=>[new De({metadata:r[e.index].metadata,pageContent:r[e.index].content}),e.similarity]))}static async fromTexts(e,t,n,r){const s=[];for(let n=0;n 0===n?t:Gr(e,t)>=0?e:t))}const Yr={[fe]:-1,[me]:-2,[ge]:-3,[ye]:-4};class Jr extends Error{constructor(e){super(e),this.name="InvalidNamespaceError"}}class Zr{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){const{filter:n,limit:r=10,offset:s=0,query:i}=t;return(await this.batch([{namespacePrefix:e,filter:n,limit:r,offset:s,query:i}]))[0]}async put(e,t,n,r){!function(e){if(0===e.length)throw new Jr("Namespace cannot be empty.");for(const t of e){if("string"!=typeof t)throw new Jr(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes("."))throw new Jr(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(""===t)throw new Jr(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if("langgraph"===e[0])throw new Jr(`Root label for namespace cannot be "langgraph". Got: ${e}`)}(e),await this.batch([{namespace:e,key:t,value:n,index:r}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){const{prefix:t,suffix:n,maxDepth:r,limit:s=100,offset:i=0}=e,a=[];return t&&a.push({matchType:"prefix",path:t}),n&&a.push({matchType:"suffix",path:n}),(await this.batch([{matchConditions:a.length?a:void 0,maxDepth:r,limit:s,offset:i}]))[0]}start(){}stop(){}}class Xr extends Zr{constructor(e){var t;super(),Object.defineProperty(this,"lg_name",{enumerable:!0,configurable:!0,writable:!0,value:"AsyncBatchedStore"}),Object.defineProperty(this,"store",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"nextKey",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"running",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"processingTask",{enumerable:!0,configurable:!0,writable:!0,value:null}),this.store="lg_name"in(t=e)&&"AsyncBatchedStore"===t.lg_name?t.store:t}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,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){const{filter:n,limit:r=10,offset:s=0,query:i}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:n,limit:r,offset:s,query:i})}async put(e,t,n){return this.enqueueOperation({namespace:e,key:t,value:n})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,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(((t,n)=>{const r=this.nextKey;this.nextKey+=1,this.queue.set(r,{operation:e,resolve:t,reject:n})}))}async processBatchQueue(){for(;this.running;){if(await new Promise((e=>{setTimeout(e,0)})),0===this.queue.size)continue;const e=new Map(this.queue);this.queue.clear();try{const t=Array.from(e.values()).map((({operation:e})=>e)),n=await this.store.batch(t);e.forEach((({resolve:t},r)=>{const s=Array.from(e.keys()).indexOf(r);t(n[s])}))}catch(t){e.forEach((({reject:e})=>{e(t)}))}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}}class Qr extends Error{constructor(e,t){let n=e??"";t?.lc_error_code&&(n=`${n}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t.lc_error_code}/\n`),super(n),Object.defineProperty(this,"lc_error_code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lc_error_code=t?.lc_error_code}}class es extends Qr{get is_bubble_up(){return!0}}class ts extends Qr{constructor(e,t){super(e,t),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}}class ns extends Qr{constructor(e,t){super(e,t),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}}class rs extends es{constructor(e,t){super(JSON.stringify(e,null,2),t),Object.defineProperty(this,"interrupts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="GraphInterrupt",this.interrupts=e??[]}static get unminifiable_name(){return"GraphInterrupt"}}class ss extends rs{constructor(e,t){super([{value:e,when:"during"}],t),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}}class is extends es{constructor(e){super(),Object.defineProperty(this,"command",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="ParentCommand",this.command=e}static get unminifiable_name(){return"ParentCommand"}}function as(e){return void 0!==e&&e.name===is.unminifiable_name}function os(e){return void 0!==e&&!0===e.is_bubble_up}function cs(e){return void 0!==e&&[rs.unminifiable_name,ss.unminifiable_name].includes(e.name)}class ls extends Qr{constructor(e,t){super(e,t),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}}class us extends Qr{constructor(e,t){super(e,t),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}}class ds extends Qr{constructor(e,t){super(e,t),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}}class hs extends Qr{constructor(e,t){super(e,t),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}}function ps(e){return null!=e&&!0===e.lg_is_channel}class fs{constructor(){Object.defineProperty(this,"ValueType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"UpdateType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lg_is_channel",{enumerable:!0,configurable:!0,writable:!0,value:!0})}consume(){return!1}}function ms(e,t){const n=Object.fromEntries(Object.entries(e).filter((([,e])=>ps(e)))),r={};for(const e in n)if(Object.prototype.hasOwnProperty.call(n,e)){const s=t.channel_values[e];r[e]=n[e].fromCheckpoint(s)}return r}function gs(e,t,n){let r;if(void 0===t)r=e.channel_values;else{r={};for(const e of Object.keys(t))try{r[e]=t[e].checkpoint()}catch(e){if(e.name!==us.unminifiable_name)throw e}}return{v:1,id:he(n),ts:(new Date).toISOString(),channel_values:r,channel_versions:{...e.channel_versions},versions_seen:Wr(e.versions_seen),pending_sends:e.pending_sends??[]}}var ys=s(9137);const bs=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;const ws=function(e){return"string"==typeof e&&bs.test(e)},vs="__start__",_s="__end__",ks="__input__",Ss="__error__",Ts="__pregel_send",xs="__pregel_call",Es="__pregel_read",Cs="__pregel_checkpointer",Ps="__pregel_resuming",Is="__pregel_task_id",As="__pregel_stream",Os="__pregel_scratchpad",$s="__pregel_previous",Ms="checkpoint_ns",Rs="checkpoint_map",Ns="__pregel_abort_signals",js="__interrupt__",Fs="__resume__",Ls="__no_writes__",Ds="__return__",zs="__previous__",Us="__pregel_runtime_placeholder__",Bs="langsmith:hidden",qs="__self__",Ws="__pregel_tasks",Hs="__pregel_push",Ks="__pregel_pull",Gs="00000000-0000-0000-0000-000000000000",Vs=[Bs,ks,js,Fs,Ss,Ls,Ws,Ts,Es,Cs,As,Ps,Is,xs,"__pregel_resume_value",Os,$s,Rs,Ms,"checkpoint_id"],Ys="|",Js=":";function Zs(e){const t=e;return null!=t&&"string"==typeof t.node&&void 0!==t.args}class Xs{constructor(e,t){Object.defineProperty(this,"lg_name",{enumerable:!0,configurable:!0,writable:!0,value:"Send"}),Object.defineProperty(this,"node",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.node=e,this.args=ni(t)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}}function Qs(e){return e instanceof Xs}class ei{constructor(e){Object.defineProperty(this,"lg_name",{enumerable:!0,configurable:!0,writable:!0,value:"Command"}),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"graph",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"update",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resume",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"goto",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?ni(e.goto):[ni(e.goto)])}_updateAsTuples(){return this.update&&"object"==typeof this.update&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]))?this.update:[["__root__",this.update]]}toJSON(){let e;return e="string"==typeof this.goto?this.goto:Qs(this.goto)?this.goto.toJSON():this.goto?.map((e=>"string"==typeof e?e:e.toJSON())),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}}function ti(e){return"object"==typeof e&&(null!=e&&("lg_name"in e&&"Command"===e.lg_name))}function ni(e,t=new Map){if(null!=e&&"object"==typeof e){if(t.has(e))return t.get(e);let n;if(Array.isArray(e))n=[],t.set(e,n),e.forEach(((e,r)=>{n[r]=ni(e,t)}));else if(!ti(e)||e instanceof ei)if(!Zs(e)||e instanceof Xs)if(ti(e)||Qs(e))n=e,t.set(e,n);else if("lc_serializable"in e&&e.lc_serializable)n=e,t.set(e,n);else{n={},t.set(e,n);for(const[r,s]of Object.entries(e))n[r]=ni(s,t)}else n=new Xs(e.node,e.args),t.set(e,n);else n=new ei(e),t.set(e,n);return n}return e}Object.defineProperty(ei,"PARENT",{enumerable:!0,configurable:!0,writable:!0,value:"__parent__"});const ri=["tags","metadata","callbacks","configurable"],si=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interruptBefore","interruptAfter","signal"];function ii(...e){const t={tags:[],metadata:{},callbacks:void 0,recursionLimit:25,configurable:{}},n=Bn.Nx.getRunnableConfig();if(void 0!==n)for(const[e,r]of Object.entries(n))if(void 0!==r)if(ri.includes(e)){let n;n=Array.isArray(r)?[...r]:"object"==typeof r?"callbacks"===e&&"copy"in r&&"function"==typeof r.copy?r.copy():{...r}:r,t[e]=n}else t[e]=r;for(const n of e)if(void 0!==n)for(const[e,r]of Object.entries(n))void 0!==r&&si.includes(e)&&(t[e]=r);for(const[e,n]of Object.entries(t.configurable))t.metadata=t.metadata??{},e.startsWith("__")||"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||e in t.metadata||(t.metadata[e]=n);return t}function ai(e){return e.split(Ys).filter((e=>!e.match(/^\d+$/))).map((e=>e.split(Js)[0])).join(Ys)}function oi(e){const t=e.split(Ys);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(Ys)}class ci extends j.YN{constructor(e){super(),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langgraph"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"recurse",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,t,n){return new Promise(((r,s)=>{const i=(0,F.tn)(t,{callbacks:n?.getChild()});Bn.Nx.runWithConfig(i,(async()=>{try{const t=await this.func(e,i);r(t)}catch(e){s(e)}}))}))}async invoke(e,t){let n;const r=ii(t),s=(0,F.SV)(this.config,r);return n=this.trace?await this._callWithConfig(this._tracedInvoke,e,s):await Bn.Nx.runWithConfig(s,(async()=>this.func(e,s))),j.YN.isRunnable(n)&&this.recurse?await Bn.Nx.runWithConfig(s,(async()=>n.invoke(e,s))):n}}function*li(e,t){if(void 0===t)yield*e;else for(const n of e)yield[t,n]}async function ui(e){const t=[];for await(const n of await e)t.push(n);return t}function di(e){const t=[];for(const n of e)t.push(n);return t}function hi(e,t){return e?"configurable"in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}Symbol.for("LG_SKIP_WRITE");function pi(e){return"object"==typeof e&&void 0!==e?.[Symbol.for("LG_SKIP_WRITE")]}const fi={[Symbol.for("LG_PASSTHROUGH")]:!0};function mi(e){return"object"==typeof e&&void 0!==e?.[Symbol.for("LG_PASSTHROUGH")]}const gi=Symbol("IS_WRITER");class yi extends ci{constructor(e,t){const n=`ChannelWrite<${e.map((e=>Qs(e)?e.node:"channel"in e?e.channel:"...")).join(",")}>`;super({writes:e,name:n,tags:t,func:async(e,t)=>this._write(e,t??{})}),Object.defineProperty(this,"writes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.writes=e}async _write(e,t){const n=this.writes.map((t=>wi(t)&&mi(t.value)?{mapper:t.mapper,value:e}:bi(t)&&mi(t.value)?{channel:t.channel,value:e,skipNone:t.skipNone,mapper:t.mapper}:t));return await yi.doWrite(t,n),e}static async doWrite(e,t){for(const e of t){if(bi(e)){if(e.channel===Ws)throw new ds("Cannot write to the reserved channel TASKS");if(mi(e.value))throw new ds("PASSTHROUGH value must be replaced")}if(wi(e)&&mi(e.value))throw new ds("PASSTHROUGH value must be replaced")}const n=[];for(const r of t)if(Qs(r))n.push([Ws,r]);else if(wi(r)){const t=await r.mapper.invoke(r.value,e);null!=t&&t.length>0&&n.push(...t)}else{if(!bi(r))throw new Error(`Invalid write entry: ${JSON.stringify(r)}`);{const t=void 0!==r.mapper?await r.mapper.invoke(r.value,e):r.value;if(pi(t))continue;if(r.skipNone&&void 0===t)continue;n.push([r.channel,t])}}const r=e.configurable?.[Ts];r(n)}static isWriter(e){return e instanceof yi||gi in e&&!!e[gi]}static registerWriter(e){return Object.defineProperty(e,gi,{value:!0})}}function bi(e){return void 0!==e&&"string"==typeof e.channel}function wi(e){return void 0!==e&&!bi(e)&&j.YN.isRunnable(e.mapper)}class vi extends ci{constructor(e,t,n=!1){super({func:(e,t)=>vi.doRead(t,this.channel,this.fresh,this.mapper)}),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"ChannelRead"}),Object.defineProperty(this,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fresh",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.fresh=n,this.mapper=t,this.channel=e,this.name=Array.isArray(e)?`ChannelRead<${e.join(",")}>`:`ChannelRead<${e}>`}static doRead(e,t,n,r){const s=e.configurable?.[Es];if(!s)throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");return r?r(s(t,n)):s(t,n)}}const _i=new D;class ki extends j.fJ{constructor(e){const{channels:t,triggers:n,mapper:r,writers:s,bound:i,kwargs:a,metadata:o,retryPolicy:c,tags:l,subgraphs:u,ends:d}=e,h=[...e.config?.tags?e.config.tags:[],...l??[]];super({...e,bound:e.bound??_i,config:{...e.config?e.config:{},tags:h}}),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"PregelNode"}),Object.defineProperty(this,"channels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"triggers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:_i}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"retryPolicy",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subgraphs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ends",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.channels=t,this.triggers=n,this.mapper=r,this.writers=s??this.writers,this.bound=i??this.bound,this.kwargs=a??this.kwargs,this.metadata=o??this.metadata,this.tags=h,this.retryPolicy=c,this.subgraphs=u,this.ends=d}getWriters(){const e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof yi&&e[e.length-2]instanceof yi;){const t=e.slice(-2),n=t[0].writes.concat(t[1].writes);e[e.length-2]=new yi(n,t[0].config?.tags),e.pop()}return e}getNode(){const e=this.getWriters();return this.bound===_i&&0===e.length?void 0:this.bound===_i&&1===e.length?e[0]:this.bound===_i?new j.zZ({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new j.zZ({first:this.bound,middle:e.slice(0,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):this.bound}join(e){if(!Array.isArray(e))throw new Error("channels must be a list");if("object"!=typeof this.channels)throw new Error("all channels must be named when using .join()");return new ki({channels:{...this.channels,...Object.fromEntries(e.map((e=>[e,e])))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy})}pipe(e){return yi.isWriter(e)?new ki({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,e],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy}):this.bound===_i?new ki({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:(0,j.Bp)(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy}):new ki({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy})}}class Si extends Error{constructor(e){super(e),this.name="GraphValidationError"}}function Ti(e,t){if(Array.isArray(e)){for(const n of e)if(!(n in t))throw new Error(`Key ${String(n)} not found in channels`)}else if(!(e in t))throw new Error(`Key ${String(e)} not found in channels`)}function xi(e,t,n=!0,r=!1){try{return e[t].get()}catch(e){if(e.name===us.unminifiable_name){if(r)return e;if(n)return null}throw e}}function Ei(e,t,n=!0){if(Array.isArray(t)){const r={};for(const s of t)try{r[s]=xi(e,s,!n)}catch(e){if(e.name===us.unminifiable_name)continue}return r}return xi(e,t)}function*Ci(e,t){if(null!=t)if(Array.isArray(e)&&"object"==typeof t&&!Array.isArray(t))for(const n in t)e.includes(n)&&(yield[n,t[n]]);else{if(Array.isArray(e))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[e,t]}}function*Pi(e,t,n){Array.isArray(e)?(!0===t||t.find((([t,n])=>e.includes(t))))&&(yield Ei(n,e)):(!0===t||t.some((([t,n])=>t===e)))&&(yield xi(n,e))}function*Ii(e,t,n){const r=t.filter((([e,t])=>(void 0===e.config||!e.config.tags?.includes(Bs))&&t[0][0]!==Ss&&t[0][0]!==js));if(!r.length)return;let s;s=r.some((([e])=>e.writes.some((([e,t])=>e===Ds))))?r.flatMap((([e])=>e.writes.filter((([e,t])=>e===Ds)).map((([t,n])=>[e.name,n])))):Array.isArray(e)?r.flatMap((([t])=>{const{writes:n}=t,r={};for(const[t]of n)e.includes(t)&&(r[t]=(r[t]||0)+1);return Object.values(r).some((e=>e>1))?n.filter((([t])=>e.includes(t))).map((([e,n])=>[t.name,{[e]:n}])):[[t.name,Object.fromEntries(n.filter((([t])=>e.includes(t))))]]})):r.flatMap((([t])=>t.writes.filter((([t,n])=>t===e)).map((([e,n])=>[t.name,n]))));const i={};for(const[e,t]of s)e in i||(i[e]=[]),i[e].push(t);const a={};for(const e in i)if(1===i[e].length){const[t]=i[e];a[e]=t}else a[e]=i[e];n&&(a.__metadata__={cached:n}),yield a}function Ai(e){return"steps"in e&&Array.isArray(e.steps)}function Oi(e){return"lg_is_pregel"in e&&!0===e.lg_is_pregel}function $i(e){const t=[e];for(const e of t){if(Oi(e))return e;Ai(e)&&t.push(...e.steps)}}function*Mi(e,t){const n=(new Date).toISOString();for(const{id:r,name:s,input:i,config:a,triggers:o,writes:c}of t){if(a?.tags?.includes(Bs))continue;const t=c.filter((([e,t])=>e===r&&t===js)).map((([,e])=>e));yield{type:"task",timestamp:n,step:e,payload:{id:r,name:s,input:i,triggers:o,interrupts:t}}}}function Ri(e,t,n){return e.map((e=>{const r=t.find((([t,n])=>t===e.id&&n===Ss))?.[2],s=t.filter((([t,n])=>t===e.id&&n===js)).map((([,,e])=>e));if(r)return{id:e.id,name:e.name,path:e.path,error:r,interrupts:s};const i=n?.[e.id];return{id:e.id,name:e.name,path:e.path,interrupts:s,...void 0!==i?{state:i}:{}}}))}function Ni(e,t){t.length}function ji(e,t,n){const r={};for(const[e,s]of t)n.includes(e)&&(r[e]||(r[e]=[]),r[e].push(s))}class Fi{constructor({func:e,name:t,input:n,retry:r,callbacks:s}){Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"retry",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"__lg_type",{enumerable:!0,configurable:!0,writable:!0,value:"call"}),this.func=e,this.name=t,this.input=n,this.retry=r,this.callbacks=s}}function Li(e){const t=Object.values(e),n=t.length>0?typeof t[0]:void 0;let r;return"number"===n?r=0:"string"===n&&(r=""),r}function Di(e,t){if(Object.keys(e).length>0){const n=Li(t);return Object.fromEntries(Object.entries(t).filter((([t,r])=>r>(e[t]??n))))}return t}function zi(e,t){return null===e?{configurable:t}:void 0===e?.configurable?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function Ui(e,t){const n=t?.parents??{};return Object.keys(n).length>0?zi(e,{[Rs]:{...n,[e.configurable?.checkpoint_ns??""]:e.configurable?.checkpoint_id}}):e}function Bi(...e){if(1===e.length)return e[0];if("any"in AbortSignal)return AbortSignal.any(e);const t=new AbortController,n=()=>{t.abort(),e.forEach((e=>e.removeEventListener("abort",n)))};return e.forEach((e=>e.addEventListener("abort",n))),e.some((e=>e.aborted))&&t.abort(),t.signal}const qi=e=>void 0!==e?e+1:1;function Wi(e,t,n){const r=Object.values(e.channel_versions),s=r.length>0?typeof r[0]:void 0;let i;"number"===s?i=0:"string"===s&&(i="");const a=e.versions_seen[js]??{},o=Object.entries(e.channel_versions).some((([e,t])=>t>(a[e]??i))),c=n.some((e=>"*"===t?!e.config?.tags?.includes(Bs):t.includes(e.name)));return o&&c}function Hi(e,t,n,r,s,i,a=!1){let o,c=[],l=new Set;if(Array.isArray(i))c=i.filter((e=>r.get(e))),i=i.filter((e=>!r.get(e))),l=new Set(i.filter((e=>s.writes.some((([t,n])=>t===e)))));else{for(const[e]of s.writes)if(e===i){l=new Set([e]);break}l=l||new Set}if(a&&l.size>0){const e=Object.fromEntries(Object.entries(n).filter((([e,t])=>l.has(e)))),r=gs(t,e,-1),a=ms(e,r);Vi(Kr(r),a,[s]),o=Ei({...n,...a},i)}else o=Ei(n,i);if(c.length>0)for(const t of c){const n=r.get(t);if(n){const r=n.call(e);o[t]=r}}return o}function Ki(e,t,n,r,s){for(const[t,i]of s)if([Hs,Ws].includes(t)&&null!=i){if(!Qs(i))throw new ds(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(i)}`);if(!(i.node in n))throw new ds(`Invalid node name "${i.node}" in Send packet`);r.replaceRuntimeValues(e,i.args)}t(s)}const Gi=new Set([Ls,Hs,Fs,js,Ds,Ss]);function Vi(e,t,n,r){n.sort(((e,t)=>{const n=e.path?.slice(0,3)||[],r=t.path?.slice(0,3)||[];for(let e=0;e r[e])return 1}return n.length-r.length}));const s=n.some((e=>e.triggers.length>0)),i=Object.fromEntries(Object.entries(t).filter((([e,t])=>ps(t))));for(const t of n){void 0===e.versions_seen[t.name]&&(e.versions_seen[t.name]={});for(const n of t.triggers)n in e.channel_versions&&(e.versions_seen[t.name][n]=e.channel_versions[n])}let a;Object.keys(e.channel_versions).length>0&&(a=Vr(...Object.values(e.channel_versions)));const o=new Set(n.flatMap((e=>e.triggers)).filter((e=>!Vs.includes(e))));for(const t of o)t in i&&i[t].consume()&&void 0!==r&&(e.channel_versions[t]=r(a,i[t]));e.pending_sends?.length&&s&&(e.pending_sends=[]);const c={},l={};for(const t of n)for(const[n,r]of t.writes)Gi.has(n)||(n===Ws?e.pending_sends.push({node:r.node,args:r.args}):n in i?n in c?c[n].push(r):c[n]=[r]:n in l?l[n].push(r):l[n]=[r]);a=void 0,Object.keys(e.channel_versions).length>0&&(a=Vr(...Object.values(e.channel_versions)));const u=new Set;for(const[t,n]of Object.entries(c))if(t in i){let s;try{s=i[t].update(n)}catch(e){if(e.name===ds.unminifiable_name){const r=new ds(`Invalid update for channel "${t}" with values ${JSON.stringify(n)}: ${e.message}`);throw r.lc_error_code=e.lc_error_code,r}throw e}s&&void 0!==r&&(e.channel_versions[t]=r(a,i[t])),u.add(t)}if(s)for(const t of Object.keys(i))if(!u.has(t)){i[t].update([])&&void 0!==r&&(e.channel_versions[t]=r(a,i[t]))}return l}function Yi(e,t,n,r,s,i,a,o){const c={};for(let l=0;l t(...e),name:e,trace:!1,recurse:!1});return new j.zZ({name:e,first:n,last:new yi([{channel:Ds,value:fi}],[Bs])})}(f.name,f.func),g=[Hs],y=""===p?f.name:`${p}${Ys}${f.name}`,b=pe(JSON.stringify([y,l.toString(),f.name,Hs,e[1],e[2]]),t.id),w=`${y}${Js}${b}`,v={langgraph_step:l,langgraph_node:f.name,langgraph_triggers:g,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:w};if(o){const o=[];return{name:f.name,input:f.input,proc:m,writes:o,config:(0,F.tn)((0,F.SV)(a,{metadata:v,store:c.store??a.store}),{runName:f.name,callbacks:d?.getChild(`graph:step:${l}`),configurable:{[Is]:b,[Ts]:e=>Ki(l,(e=>o.push(...e)),r,i,e),[Es]:(n,r=!1)=>Hi(l,t,s,i,{name:f.name,writes:o,triggers:g,path:e.slice(0,3)},n,r),[Cs]:u??h[Cs],[Rs]:{...h[Rs],[p]:t.id},[Os]:Zi({pendingWrites:n??[],taskId:b,currentTaskInput:f.input}),[$s]:t.channel_values[zs],checkpoint_id:void 0,checkpoint_ns:w}}),triggers:g,retry_policy:f.retry,id:b,path:e.slice(0,3),writers:[]}}return{id:b,name:f.name,interrupts:[],path:e.slice(0,3)}}if(e[0]===Hs){const f="number"==typeof e[1]?e[1]:parseInt(e[1],10);if(f>=t.pending_sends.length)return;const m=Zs(t.pending_sends[f])&&!Qs(t.pending_sends[f])?new Xs(t.pending_sends[f].node,t.pending_sends[f].args):t.pending_sends[f];if(!Zs(m))return;if(!(m.node in r))return;const g=[Hs],y=""===p?m.node:`${p}${Ys}${m.node}`,b=pe(JSON.stringify([y,l.toString(),m.node,Hs,f.toString()]),t.id),w=`${y}${Js}${b}`;let v={langgraph_step:l,langgraph_node:m.node,langgraph_triggers:g,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:w};if(!o)return{id:b,name:m.node,interrupts:[],path:e};{const o=r[m.node],f=o.getNode();if(void 0!==f){i.replaceRuntimePlaceholders(l,m.args),void 0!==o.metadata&&(v={...v,...o.metadata});const y=[];return{name:m.node,input:m.args,proc:f,subgraphs:o.subgraphs,writes:y,config:(0,F.tn)((0,F.SV)(a,{metadata:v,tags:o.tags,store:c.store??a.store}),{runName:m.node,callbacks:d?.getChild(`graph:step:${l}`),configurable:{[Is]:b,[Ts]:e=>Ki(l,(e=>y.push(...e)),r,i,e),[Es]:(n,r=!1)=>Hi(l,t,s,i,{name:m.node,writes:y,triggers:g,path:e},n,r),[Cs]:u??h[Cs],[Rs]:{...h[Rs],[p]:t.id},[Os]:Zi({pendingWrites:n??[],taskId:b,currentTaskInput:m.args}),[$s]:t.channel_values[zs],checkpoint_id:void 0,checkpoint_ns:w}}),triggers:g,retry_policy:o.retryPolicy,id:b,path:e,writers:o.getWriters()}}}}else if(e[0]===Ks){const f=e[1].toString(),m=r[f];if(void 0===m)return;if(n?.length){const e=""===p?f:`${p}${Ys}${f}`,r=pe(JSON.stringify([e,l.toString(),f,Ks,f]),t.id),s=n.some((e=>e[0]===r&&e[1]!==Ss));if(s)return}const g=Li(t.channel_versions);if(void 0===g)return;const y=t.versions_seen[f]??{},b=m.triggers.filter((e=>{const n=xi(s,e,!1,!0);return!(n instanceof Error&&n.name===us.unminifiable_name)&&(t.channel_versions[e]??g)>(y[e]??g)})).sort();if(b.length>0){const g=function(e,t,n,r,s){let i;if("object"!=typeof t.channels||Array.isArray(t.channels)){if(!Array.isArray(t.channels))throw new Error(`Invalid channels type, expected list or dict, got ${t.channels}`);{let e=!1;for(const n of t.channels)try{i=xi(r,n,!1),e=!0;break}catch(e){if(e.name===us.unminifiable_name)continue;throw e}if(!e)return}}else{i={};for(const[s,a]of Object.entries(t.channels))if(t.triggers.includes(a))try{i[s]=xi(r,a,!1)}catch(e){if(e.name===us.unminifiable_name)return;throw e}else if(a in r)try{i[s]=xi(r,a,!1)}catch(e){if(e.name===us.unminifiable_name)continue;throw e}else i[s]=n.get(s)?.call(e)}s&&void 0!==t.mapper&&(i=t.mapper(i));return i}(l,m,i,s,o);if(void 0===g)return;const y=""===p?f:`${p}${Ys}${f}`,w=pe(JSON.stringify([y,l.toString(),f,Ks,b]),t.id),v=`${y}${Js}${w}`;let _={langgraph_step:l,langgraph_node:f,langgraph_triggers:b,langgraph_path:e,langgraph_checkpoint_ns:v};if(!o)return{id:w,name:f,interrupts:[],path:e};{const o=m.getNode();if(void 0!==o){void 0!==m.metadata&&(_={..._,...m.metadata});const y=[];return{name:f,input:g,proc:o,subgraphs:m.subgraphs,writes:y,config:(0,F.tn)((0,F.SV)(a,{metadata:_,tags:m.tags,store:c.store??a.store}),{runName:f,callbacks:d?.getChild(`graph:step:${l}`),configurable:{[Is]:w,[Ts]:e=>Ki(l,(e=>{y.push(...e)}),r,i,e),[Es]:(n,r=!1)=>Hi(l,t,s,i,{name:f,writes:y,triggers:b,path:e},n,r),[Cs]:u??h[Cs],[Rs]:{...h[Rs],[p]:t.id},[Os]:Zi({pendingWrites:n??[],taskId:w,currentTaskInput:g}),[$s]:t.channel_values[zs],checkpoint_id:void 0,checkpoint_ns:v}}),triggers:b,retry_policy:m.retryPolicy,id:w,path:e,writers:m.getWriters()}}}}}}function Zi({pendingWrites:e,taskId:t,currentTaskInput:n}){const r=e.find((([e,t])=>e===Gs&&t===Fs))?.[2],s={callCounter:0,interruptCounter:-1,resume:e.filter((([e,n])=>e===t&&n===Fs)).flatMap((([e,t,n])=>n)),nullResume:r,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(s.nullResume)return delete s.nullResume,e.splice(e.findIndex((([e,t])=>e===Gs&&t===Fs)),1),r}};return s}class Xi extends L.IterableReadableStream{constructor(e,t){const n=e.getReader(),r=t??new AbortController;super({start:e=>function t(){return n.read().then((({done:n,value:r})=>{if(!n)return e.enqueue(r),t();e.close()}))}()}),Object.defineProperty(this,"_abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._abortController=r,this._reader=n}async cancel(e){this._abortController.abort(e),this._reader.releaseLock()}get signal(){return this._abortController.signal}}class Qi extends L.IterableReadableStream{get closed(){return this._closed}constructor(e){let t;const n=new Promise((e=>{t=e}));super({start:e=>{t(e)}}),Object.defineProperty(this,"modes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"passthroughFn",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_closed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),n.then((e=>{this.controller=e})),this.passthroughFn=e.passthroughFn,this.modes=e.modes}push(e){this.passthroughFn?.(e),this.controller.enqueue(e)}close(){try{this.controller.close()}catch(e){}finally{this._closed=!0}}error(e){this.controller.error(e)}}const ea=Symbol.for("INPUT_DONE"),ta=Symbol.for("INPUT_RESUMING");class na{get isResuming(){const e=0!==Object.keys(this.checkpoint.channel_versions).length,t=void 0!==this.config.configurable?.[Ps]&&this.config.configurable?.[Ps],n=null===this.input||void 0===this.input,r=ti(this.input)&&null!=this.input.resume,s=this.input===ta;return e&&(t||n||r||s)}constructor(e){Object.defineProperty(this,"input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointerGetNextVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"channels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"managed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpoint",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointNamespace",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointPendingWrites",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"checkpointPreviousVersions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"step",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputKeys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamKeys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"skipDoneTasks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"prevCheckpointConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:"pending"}),Object.defineProperty(this,"tasks",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointerPromises",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"isNested",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_checkpointerChainedPromise",{enumerable:!0,configurable:!0,writable:!0,value:Promise.resolve()}),Object.defineProperty(this,"store",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"interruptAfter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"interruptBefore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"toInterrupt",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.input=e.input,this.checkpointer=e.checkpointer,void 0!==this.checkpointer?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=qi,this.checkpoint=e.checkpoint,this.checkpointMetadata=e.checkpointMetadata,this.checkpointPreviousVersions=e.checkpointPreviousVersions,this.channels=e.channels,this.managed=e.managed,this.checkpointPendingWrites=e.checkpointPendingWrites,this.step=e.step,this.stop=e.stop,this.config=e.config,this.checkpointConfig=e.checkpointConfig,this.isNested=e.isNested,this.manager=e.manager,this.outputKeys=e.outputKeys,this.streamKeys=e.streamKeys,this.nodes=e.nodes,this.skipDoneTasks=e.skipDoneTasks,this.store=e.store,this.stream=e.stream,this.checkpointNamespace=e.checkpointNamespace,this.prevCheckpointConfig=e.prevCheckpointConfig,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.debug=e.debug}static async initialize(e){let{config:t,stream:n}=e;void 0!==n&&void 0!==t.configurable?.[As]&&(n=function(...e){return new Qi({passthroughFn:t=>{for(const n of e)n.modes.has(t[1])&&n.push(t)},modes:new Set(e.flatMap((e=>Array.from(e.modes))))})}(n,t.configurable[As]));const r=!t.configurable||!("checkpoint_id"in t.configurable),s=t.configurable?.[Os];t.configurable&&s&&(s.subgraphCounter>0&&(t=zi(t,{[Ms]:[t.configurable[Ms],s.subgraphCounter.toString()].join(Ys)})),s.subgraphCounter+=1);const i=Es in(t.configurable??{});i||void 0===t.configurable?.checkpoint_ns||""===t.configurable?.checkpoint_ns||(t=zi(t,{checkpoint_ns:"",checkpoint_id:void 0}));let a=t;void 0!==t.configurable?.[Rs]&&t.configurable?.[Rs]?.[t.configurable?.checkpoint_ns]&&(a=zi(t,{checkpoint_id:t.configurable[Rs][t.configurable?.checkpoint_ns]}));const o=t.configurable?.checkpoint_ns?.split(Ys)??[],c=await(e.checkpointer?.getTuple(a))??{config:t,checkpoint:Hr(),metadata:{source:"input",step:-2,writes:null,parents:{}},pendingWrites:[]};a={...t,...c.config,configurable:{checkpoint_ns:"",...t.configurable,...c.config.configurable}};const l=c.parentConfig,u=Kr(c.checkpoint),d={...c.metadata},h=c.pendingWrites??[],p=ms(e.channelSpecs,u),f=(d.step??0)+1,m=f+(t.recursionLimit??25)+1,g={...u.channel_versions},y=e.store?new Xr(e.store):void 0;return y&&y.start(),new na({input:e.input,config:t,checkpointer:e.checkpointer,checkpoint:u,checkpointMetadata:d,checkpointConfig:a,prevCheckpointConfig:l,checkpointNamespace:o,channels:p,managed:e.managed,isNested:i,manager:e.manager,skipDoneTasks:r,step:f,stop:m,checkpointPreviousVersions:g,checkpointPendingWrites:h,outputKeys:e.outputKeys??[],streamKeys:e.streamKeys??[],nodes:e.nodes,stream:n,store:y,interruptAfter:e.interruptAfter,interruptBefore:e.interruptBefore,debug:e.debug})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then((()=>this.checkpointer?.put(e.config,e.checkpoint,e.metadata,e.newVersions))),this.checkpointerPromises.push(this._checkpointerChainedPromise)}async updateManagedValues(e,t){const n=this.managed.get(e);n&&"update"in n&&"function"==typeof n.update&&await n.update(t)}putWrites(e,t){let n=t;if(0===n.length)return;n.every((([e])=>e in Yr))&&(n=Array.from(new Map(n.map((e=>[e[0],e]))).values()));for(const[t,r]of n){const n=this.checkpointPendingWrites.findIndex((n=>n[0]===e&&n[1]===t));t in Yr&&-1!==n?this.checkpointPendingWrites[n]=[e,t,r]:this.checkpointPendingWrites.push([e,t,r])}const r=this.checkpointer?.putWrites({...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_ns:this.config.configurable?.checkpoint_ns??"",checkpoint_id:this.checkpoint.id}},n,e);void 0!==r&&this.checkpointerPromises.push(r),this.tasks&&this._outputWrites(e,n)}_outputWrites(e,t,n=!1){const r=this.tasks[e];if(void 0!==r){if(void 0!==r.config&&(r.config.tags??[]).includes(Bs))return;t.length>0&&t[0][0]!==Ss&&t[0][0]!==js&&this._emit(di(li(Ii(this.outputKeys,[[r,t]],n),"updates"))),n||this._emit(di(li(function*(e,t,n){const r=(new Date).toISOString();for(const[{id:s,name:i,config:a},o]of t)a?.tags?.includes(Bs)||(yield{type:"task_result",timestamp:r,step:e,payload:{id:s,name:i,result:o.filter((([e])=>Array.isArray(n)?n.includes(e):e===n)),interrupts:o.filter((e=>e[0]===js)).map((e=>e[1]))}})}(this.step,[[r,t]],this.streamKeys),"debug")))}}async tick(e){this.store&&!this.store.isRunning&&this.store?.start();const{inputKeys:t=[]}=e;if("pending"!==this.status)throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if([ea,ta].includes(this.input)){if(this.toInterrupt.length>0)throw this.status="interrupt_before",new rs;if(!Object.values(this.tasks).every((e=>e.writes.length>0)))return!1;{const e=Object.values(this.tasks).flatMap((e=>e.writes)),t=Vi(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion);for(const[e,n]of Object.entries(t))await this.updateManagedValues(e,n);const n=await ui(li(Pi(this.outputKeys,e,this.channels),"values"));if(this._emit(n),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop",writes:Ii(this.outputKeys,Object.values(this.tasks).map((e=>[e,e.writes]))).next().value??null}),Wi(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new rs;void 0!==this.config.configurable?.[Ps]&&delete this.config.configurable?.[Ps]}}else await this._first(t);if(this.step>this.stop)return this.status="out_of_steps",!1;const n=Yi(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.managed,this.config,!0,{step:this.step,checkpointer:this.checkpointer,isResuming:this.isResuming,manager:this.manager,store:this.store,stream:this.stream});if(this.tasks=n,this.checkpointer&&this._emit(await ui(li(function*(e,t,n,r,s,i,a,o){function c(e){const t={};return null!=e.callbacks&&(t.callbacks=e.callbacks),null!=e.configurable&&(t.configurable=e.configurable),null!=e.maxConcurrency&&(t.max_concurrency=e.maxConcurrency),null!=e.metadata&&(t.metadata=e.metadata),null!=e.recursionLimit&&(t.recursion_limit=e.recursionLimit),null!=e.runId&&(t.run_id=e.runId),null!=e.runName&&(t.run_name=e.runName),null!=e.tags&&(t.tags=e.tags),t}const l=t.configurable?.checkpoint_ns,u={};for(const e of i){if(!(e.subgraphs?.length?e.subgraphs:[e.proc]).find($i))continue;let n=`${e.name}:${e.id}`;l&&(n=`${l}|${n}`),u[e.id]={configurable:{thread_id:t.configurable?.thread_id,checkpoint_ns:n}}}const d=(new Date).toISOString();yield{type:"checkpoint",timestamp:d,step:e,payload:{config:c(t),values:Ei(n,r),metadata:s,next:i.map((e=>e.name)),tasks:Ri(i,a,u),parentConfig:o?c(o):void 0}}}(this.step-1,this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig),"debug"))),0===Object.values(this.tasks).length)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(const[e,t,n]of this.checkpointPendingWrites){if(t===Ss||t===js||t===Fs)continue;const r=Object.values(this.tasks).find((t=>t.id===e));r&&r.writes.push([t,n])}for(const e of Object.values(this.tasks))e.writes.length>0&&this._outputWrites(e.id,e.writes,!0)}if(Object.values(this.tasks).every((e=>e.writes.length>0)))return this.tick({inputKeys:t});if(Wi(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new rs;const r=await ui(li(Mi(this.step,Object.values(this.tasks)),"debug"));return this._emit(r),!0}async finishAndHandleError(e){const t=this._suppressInterrupt(e);if((t||void 0===e)&&(this.output=Ei(this.channels,this.outputKeys)),t){if(void 0!==this.tasks&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some((e=>e.writes.length>0))){const e=Vi(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion);for(const[t,n]of Object.entries(e))await this.updateManagedValues(t,n);this._emit(di(li(Pi(this.outputKeys,Object.values(this.tasks).flatMap((e=>e.writes)),this.channels),"values")))}this._emit([["updates",{[js]:e.interrupts}]])}return t}acceptPush(e,t,n){if(this.interruptAfter?.length>0&&Wi(this.checkpoint,this.interruptAfter,[e]))return void this.toInterrupt.push(e);const r=Ji([Hs,e.path??[],t,e.id,n],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.managed,e.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});return r?this.interruptBefore?.length>0&&Wi(this.checkpoint,this.interruptBefore,[r])?void this.toInterrupt.push(r):(this._emit(di(li(Mi(this.step,[r]),"debug"))),this.debug&&Ni(this.step,[r]),this.tasks[r.id]=r,this.skipDoneTasks&&this._matchWrites({[r.id]:r}),r):void 0}_suppressInterrupt(e){return cs(e)&&!this.isNested}async _first(e){const{configurable:t}=this.config,n=t?.[Os];if(n&&void 0!==n.nullResume&&this.putWrites(Gs,[[Fs,n.nullResume]]),ti(this.input)){if(null!=this.input.resume&&null==this.checkpointer)throw new Error("Cannot use Command(resume=...) without checkpointer");const e={};for(const[t,n,r]of function*(e,t){if(e.graph===ei.PARENT)throw new ds("There is no parent graph.");if(e.goto){let t;t=Array.isArray(e.goto)?e.goto:[e.goto];for(const e of t)if(Qs(e))yield[Gs,Ws,e];else{if("string"!=typeof e)throw new Error("In Command.send, expected Send or string, got "+typeof e);yield[Gs,`branch:__start__:${qs}:${e}`,"__start__"]}}if(e.resume)if("object"==typeof e.resume&&Object.keys(e.resume).length&&Object.keys(e.resume).every(ws))for(const[n,r]of Object.entries(e.resume)){const e=t.filter((e=>e[0]===n&&e[1]===Fs)).map((e=>e[2])).slice(0,1)??[];e.push(r),yield[n,Fs,e]}else yield[Gs,Fs,e.resume];if(e.update){if("object"!=typeof e.update||!e.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(e.update))for(const[t,n]of e.update)yield[Gs,t,n];else for(const[t,n]of Object.entries(e.update))yield[Gs,t,n]}}(this.input,this.checkpointPendingWrites))void 0===e[t]&&(e[t]=[]),e[t].push([n,r]);if(0===Object.keys(e).length)throw new ls("Received empty Command input");for(const[t,n]of Object.entries(e))this.putWrites(t,n)}const r=(this.checkpointPendingWrites??[]).filter((e=>e[0]===Gs)).map((e=>e.slice(1)));r.length>0&&Vi(this.checkpoint,this.channels,[{name:ks,writes:r,triggers:[]}],this.checkpointerGetNextVersion);const s=ti(this.input)&&r.length>0;if(this.isResuming||s){for(const e of Object.keys(this.channels))if(void 0!==this.checkpoint.channel_versions[e]){const t=this.checkpoint.channel_versions[e];this.checkpoint.versions_seen[js]={...this.checkpoint.versions_seen[js],[e]:t}}const e=await ui(li(Pi(this.outputKeys,!0,this.channels),"values"));this._emit(e)}if(this.isResuming)this.input=ta;else if(s)await this._putCheckpoint({source:"input",writes:{}}),this.input=ea;else{const t=await ui(Ci(e,this.input));if(t.length>0){const e=Yi(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.managed,this.config,!0,{step:this.step});Vi(this.checkpoint,this.channels,Object.values(e).concat([{name:ks,writes:t,triggers:[]}]),this.checkpointerGetNextVersion),await this._putCheckpoint({source:"input",writes:Object.fromEntries(t)}),this.input=ea}else{if(!(Ps in(this.config.configurable??{})))throw new ls(`Received no input writes for ${JSON.stringify(e,null,2)}`);this.input=ea}}this.isNested||(this.config=zi(this.config,{[Ps]:this.isResuming}))}_emit(e){for(const t of e)this.stream.modes.has(t[0])&&this.stream.push([this.checkpointNamespace,...t])}async _putCheckpoint(e){const t={...e,step:this.step,parents:this.config.configurable?.[Rs]??{}};if(void 0!==this.checkpointer){this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointMetadata=t,this.checkpoint=gs(this.checkpoint,this.channels,this.step),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_ns:this.config.configurable?.checkpoint_ns??""}};const e={...this.checkpoint.channel_versions},n=Di(this.checkpointPreviousVersions,e);this.checkpointPreviousVersions=e,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:Kr(this.checkpoint),metadata:{...this.checkpointMetadata},newVersions:n}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}}this.step+=1}_matchWrites(e){for(const[t,n,r]of this.checkpointPendingWrites){if(n===Ss||n===js||n===Fs)continue;const s=Object.values(e).find((e=>e.id===t));s&&s.writes.push([n,r])}for(const t of Object.values(e))t.writes.length>0&&this._outputWrites(t.id,t.writes,!0)}}class ra{constructor(e,t){Object.defineProperty(this,"runtime",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_promises",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"lg_is_managed_value",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.config=e}static async initialize(e,t){throw new Error("Not implemented")}async promises(){return Promise.all(this._promises)}addPromise(e){this._promises.push(e)}}class sa extends Map{constructor(e){super(e?Array.from(e):void 0)}replaceRuntimeValues(e,t){if(0!==this.size&&t&&!Array.from(this.values()).every((e=>!e.runtime)))if("object"!=typeof t||Array.isArray(t)){if("object"==typeof t&&"constructor"in t)for(const n of Object.getOwnPropertyNames(Object.getPrototypeOf(t)))try{const r=t[n];for(const[s,i]of this.entries())i.runtime&&i.call(e)===r&&(t[n]={[Us]:s})}catch(e){if(e.name!==TypeError.name)throw e}}else for(const[n,r]of Object.entries(t))for(const[s,i]of this.entries())i.runtime&&i.call(e)===r&&(t[n]={[Us]:s})}replaceRuntimePlaceholders(e,t){if(0!==this.size&&t&&!Array.from(this.values()).every((e=>!e.runtime)))if("object"!=typeof t||Array.isArray(t)){if("object"==typeof t&&"constructor"in t)for(const n of Object.getOwnPropertyNames(Object.getPrototypeOf(t)))try{const r=t[n];if("object"==typeof r&&null!==r&&Us in r){const s=this.get(r[Us]);s&&(t[n]=s.call(e))}}catch(e){if(e.name!==TypeError.name)throw e}}else for(const[n,r]of Object.entries(t))if("object"==typeof r&&null!==r&&Us in r){const s=r[Us];"string"==typeof s&&(t[n]=this.get(s)?.call(e))}}}function ia(e){return!!("object"==typeof e&&e&&"cls"in e&&"params"in e)}class aa extends ra{call(){}static async initialize(e,t){return Promise.resolve(new aa(e))}}class oa extends Me.BaseCallbackHandler{constructor(e){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"StreamMessagesHandler"}),Object.defineProperty(this,"streamFn",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadatas",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"seen",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"emittedChatModelRunIds",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"stableMessageIdMap",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.streamFn=e}_emit(e,t,n,r=!1){if(r&&void 0!==t.id&&void 0!==this.seen[t.id])return;let s=t.id;(0,N.isToolMessage)(t)?s??=`run-${n}-tool-${t.tool_call_id}`:(null!=s&&s!==`run-${n}`||(s=this.stableMessageIdMap[n]??s??`run-${n}`),this.stableMessageIdMap[n]??=s),s!==t.id&&(t.id=s,t.lc_kwargs.id=s),null!=t.id&&(this.seen[t.id]=t),this.streamFn([e[0],"messages",[t,e[1]]])}handleChatModelStart(e,t,n,r,s,i,a,o){!a||i&&(i.includes("langsmith:nostream")||i.includes("nostream"))||(this.metadatas[n]=[a.langgraph_checkpoint_ns.split("|"),{tags:i,name:o,...a}])}handleLLMNewToken(e,t,n,r,s,i){const a=i?.chunk;this.emittedChatModelRunIds[n]=!0,void 0!==this.metadatas[n]&&(!function(e){return(0,N.isBaseMessage)(e?.message)}(a)?this._emit(this.metadatas[n],new N.AIMessageChunk({content:e}),n):this._emit(this.metadatas[n],a.message,n))}handleLLMEnd(e,t){if(!this.emittedChatModelRunIds[t]){const n=e.generations?.[0]?.[0];(0,N.isBaseMessage)(n?.message)&&this._emit(this.metadatas[t],n?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,n,r,s,i,a,o){if(void 0!==i&&o===i.langgraph_node&&(void 0===s||!s.includes(Bs))&&(this.metadatas[n]=[i.langgraph_checkpoint_ns.split("|"),{tags:s,name:o,...i}],"object"==typeof t))for(const e of Object.values(t))if(((0,N.isBaseMessage)(e)||(0,N.isBaseMessageChunk)(e))&&void 0!==e.id)this.seen[e.id]=e;else if(Array.isArray(e))for(const t of e)((0,N.isBaseMessage)(t)||(0,N.isBaseMessageChunk)(t))&&void 0!==t.id&&(this.seen[t.id]=t)}handleChainEnd(e,t){const n=this.metadatas[t];if(delete this.metadatas[t],void 0!==n)if((0,N.isBaseMessage)(e))this._emit(n,e,t,!0);else if(Array.isArray(e))for(const r of e)(0,N.isBaseMessage)(r)&&this._emit(n,r,t,!0);else if(null!=e&&"object"==typeof e)for(const r of Object.values(e))if((0,N.isBaseMessage)(r))this._emit(n,r,t,!0);else if(Array.isArray(r))for(const e of r)(0,N.isBaseMessage)(e)&&this._emit(n,e,t,!0)}handleChainError(e,t){delete this.metadatas[t]}}const ca=[400,401,402,403,404,405,406,407,409],la=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||"AbortError"===e.name)return!1;if("ECONNABORTED"===e?.code)return!1;const t=e?.response?.status??e?.status;return(!t||!ca.includes(+t))&&"insufficient_quota"!==e?.error?.code};async function ua(e,t,n,r){const s=e.retry_policy??t;let i,a,o=void 0!==s?s.initialInterval??500:0,c=0,{config:l}=e;for(n&&(l=zi(l,n)),l={...l,signal:r};!r?.aborted;){e.writes.splice(0,e.writes.length),i=void 0;try{a=await e.proc.invoke(e.input,l);break}catch(t){if(i=t,i.pregelTaskId=e.id,as(i)){const t=l?.configurable?.checkpoint_ns,n=i.command;if(n.graph===t){for(const t of e.writers)await t.invoke(n,l);i=void 0;break}if(n.graph===ei.PARENT){const e=oi(t);i.command=new ei({...i.command,graph:e})}}if(os(i))break;if(void 0===s)break;if(c+=1,c>=(s.maxAttempts??3))break;if(!(s.retryOn??la)(i))break;o=Math.min(s.maxInterval??128e3,o*(s.backoffFactor??2));const n=s.jitter?Math.floor(o+1e3*Math.random()):o;await new Promise((e=>setTimeout(e,n)));i.name??i.constructor.unminifiable_name??i.constructor.name;l=zi(l,{[Ps]:!0})}}return{task:e,result:a,error:i,signalAborted:r?.aborted}}class da{constructor({loop:e,nodeFinished:t}){Object.defineProperty(this,"nodeFinished",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"loop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.loop=e,this.nodeFinished=t}async tick(e={}){const{timeout:t,retryPolicy:n,onStepWrite:r,maxConcurrency:s}=e,i=new Set;let a;const o=new AbortController,c=Object.values(this.loop.tasks).filter((e=>0===e.writes.length)),l=this._initializeAbortSignals({exceptionSignalController:o,timeout:t,signal:e.signal}),u=this._executeTasksWithRetry(c,{signals:l,retryPolicy:n,maxConcurrency:s});for await(const{task:e,error:t,signalAborted:n}of u)this._commit(e,t),cs(t)||os(t)&&!cs(a)?a=t:!t||0!==i.size&&n||(o.abort(),i.add(t));if(r?.(this.loop.step,Object.values(this.loop.tasks).map((e=>e.writes)).flat()),1===i.size)throw Array.from(i)[0];if(i.size>1)throw new AggregateError(Array.from(i),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(cs(a))throw a;if(os(a)&&this.loop.isNested)throw a}_initializeAbortSignals({exceptionSignalController:e,timeout:t,signal:n}){const r=this.loop.config.configurable?.[Ns]??{},s=n&&r.composedAbortSignal&&n!==r.composedAbortSignal?Bi(r.externalAbortSignal,n):r.externalAbortSignal??n,i=r.errorAbortSignal?Bi(r.errorAbortSignal,e.signal):e.signal,a=t?AbortSignal.timeout(t):void 0,o={externalAbortSignal:s,errorAbortSignal:i,timeoutAbortSignal:a,composedAbortSignal:Bi(...s?[s]:[],...a?[a]:[],i)};return this.loop.config=zi(this.loop.config,{[Ns]:o}),o}async*_executeTasksWithRetry(e,t){const{retryPolicy:n,maxConcurrency:r,signals:s}=t??{},i=Symbol.for("promiseAdded");let a,o;o=new Promise((function e(t){a=()=>{o=new Promise(e),t(i)}}));const c={};function l(e,t,r,{calls:s}={}){if(r.every((([e])=>e!==Hs)))return t.config?.configurable?.[Ts]?.(r)??[];const i=t.config?.configurable?.[Os];if(!i)throw new Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);const o={};for(const[d,h]of r.entries()){const[r]=h;if(r!==Hs)continue;const p=s?.[d],f=i.callCounter;if(i.callCounter+=1,null==p)throw new Error("BUG: No call found");const m=e.loop.acceptPush(t,f,p);if(!m)continue;const g=c[m.id];if(void 0!==g)o[d]=g;else if(m.writes.length>0){const e=m.writes.filter((([e])=>e===Ds)),t=m.writes.filter((([e])=>e===Ss));if(e.length>0){if(1!==e.length)throw new Error(`BUG: multiple returns found for task ${m.name}__${m.id}`);o[d]=Promise.resolve(e[0][1])}else if(t.length>0){if(1!==t.length)throw new Error(`BUG: multiple errors found for task ${m.name}__${m.id}`);{const e=t[0][1],n=e instanceof Error?e:new Error(String(e));o[d]=Promise.reject(n)}}}else{const t=ua(m,n,{[Ts]:l.bind(null,e,m),[xs]:u.bind(null,e,m)});c[m.id]=t,a(),o[d]=t.then((({result:e,error:t})=>t?Promise.reject(t):e))}}return Object.values(o)}function u(e,t,n,r,s,i={}){const a=l(e,t,[[Hs,null]],{calls:[new Fi({func:n,name:r,input:s,retry:i.retry,callbacks:i.callbacks})]});return void 0!==a?1===a.length?a[0]:Promise.all(a):Promise.resolve()}if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let d,h=0;const p=s?.externalAbortSignal||s?.timeoutAbortSignal?Bi(...s.externalAbortSignal?[s.externalAbortSignal]:[],...s.timeoutAbortSignal?[s.timeoutAbortSignal]:[]):void 0,f=p?new Promise(((e,t)=>{d=()=>t(new Error("Abort")),p.addEventListener("abort",d,{once:!0})})):void 0;for(;(0===h||Object.keys(c).length>0)&&e.length;){for(;Object.values(c).length<(r??e.length)&&h ({task:t,error:e,signalAborted:s?.composedAbortSignal?.aborted})))}const t=await Promise.race([...Object.values(c),...f?[f]:[],o]);t!==i&&(yield t,delete c[t.task.id])}}_commit(e,t){if(void 0!==t)if(cs(t)){if(t.interrupts.length){const n=t.interrupts.map((e=>[js,e])),r=e.writes.filter((e=>e[0]===Fs));r.length&&n.push(...r),this.loop.putWrites(e.id,n)}}else os(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):this.loop.putWrites(e.id,[[Ss,{message:t.message,name:t.name}]]);else!this.nodeFinished||null!=e.config?.tags&&e.config.tags.includes(Bs)||this.nodeFinished(String(e.name)),0===e.writes.length&&e.writes.push([Ls,null]),this.loop.putWrites(e.id,e.writes)}}class ha{static subscribeTo(e,t){const{key:n,tags:r}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&void 0!==n)throw new Error("Can't specify a key when subscribing to multiple channels");let s;s=function(e){return"string"==typeof e}(e)?n?{[n]:e}:[e]:Object.fromEntries(e.map((e=>[e,e])));const i=Array.isArray(e)?e:[e];return new ki({channels:s,triggers:i,tags:r})}static writeTo(e,t){const n=[];for(const t of e)n.push({channel:t,value:fi,skipNone:!1});for(const[e,r]of Object.entries(t??{}))j.YN.isRunnable(r)||"function"==typeof r?n.push({channel:e,value:fi,skipNone:!0,mapper:(0,j.Bp)(r)}):n.push({channel:e,value:r,skipNone:!1});return new yi(n)}}class pa extends j.YN{static lc_name(){return"LangGraph"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langgraph","pregel"]}),Object.defineProperty(this,"lg_is_pregel",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"channels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputChannels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputChannels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoValidate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"streamMode",{enumerable:!0,configurable:!0,writable:!0,value:["values"]}),Object.defineProperty(this,"streamChannels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"interruptAfter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"interruptBefore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stepTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"checkpointer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"retryPolicy",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"store",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{streamMode:t}=e;null==t||Array.isArray(t)||(t=[t]),this.nodes=e.nodes,this.channels=e.channels,this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.name=e.name,this.autoValidate&&this.validate()}withConfig(e){const t=(0,F.SV)(this.config,e);return new this.constructor({...this,config:t})}validate(){return function({nodes:e,channels:t,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:i,interruptBeforeNodes:a}){if(!t)throw new Si("Channels not provided");const o=new Set,c=new Set;for(const[t,n]of Object.entries(e)){if(t===js)throw new Si(`"Node name ${js} is reserved"`);if(n.constructor!==ki)throw new Si(`Invalid node type ${typeof n}, expected PregelNode`);n.triggers.forEach((e=>o.add(e)))}for(const e of o)if(!(e in t))throw new Si(`Subcribed channel '${String(e)}' not in channels`);if(Array.isArray(n)){if(n.every((e=>!o.has(e))))throw new Si(`None of the input channels ${n} are subscribed to by any node`)}else if(!o.has(n))throw new Si(`Input channel ${String(n)} is not subscribed to by any node`);Array.isArray(r)?r.forEach((e=>c.add(e))):c.add(r),s&&!Array.isArray(s)?c.add(s):Array.isArray(s)&&s.forEach((e=>c.add(e)));for(const e of c)if(!(e in t))throw new Si(`Output channel '${String(e)}' not in channels`);if(i&&"*"!==i)for(const t of i)if(!(t in e))throw new Si(`Node ${String(t)} not in nodes`);if(a&&"*"!==a)for(const t of a)if(!(t in e))throw new Si(`Node ${String(t)} not in nodes`)}({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore}),this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,t){for(const[n,r]of Object.entries(this.nodes)){if(void 0!==e&&!e.startsWith(n))continue;const s=r.subgraphs?.length?r.subgraphs:[r.bound];for(const r of s){const s=$i(r);if(void 0!==s){if(n===e)return void(yield[n,s]);if(void 0===e&&(yield[n,s]),t){let r=e;void 0!==e&&(r=e.slice(n.length+1));for(const[e,i]of s.getSubgraphs(r,t))yield[`${n}${Ys}${e}`,i]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:n,applyPendingWrites:r=!1}){if(void 0===t)return{values:{},next:[],config:e,tasks:[]};const{managed:s}=await this.prepareSpecs(e,{skipManaged:!0}),i=ms(this.channels,t.checkpoint);if(t.pendingWrites?.length){const e=t.pendingWrites.filter((([e,t])=>e===Gs)).map((([e,t,n])=>[String(t),n]));e.length>0&&Vi(t.checkpoint,i,[{name:ks,writes:e,triggers:[]}])}const a=Object.values(Yi(t.checkpoint,t.pendingWrites,this.nodes,i,s,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),o=await ui(this.getSubgraphsAsync()),c=t.config.configurable?.checkpoint_ns??"",l={};for(const e of a){const r=o.find((([t])=>t===e.name));if(!r)continue;let s=`${String(e.name)}${Js}${e.id}`;if(c&&(s=`${c}${Ys}${s}`),void 0===n){const n={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:s}};l[e.id]=n}else{const i={configurable:{[Cs]:n,thread_id:t.config.configurable?.thread_id,checkpoint_ns:s}},a=r[1];l[e.id]=await a.getState(i,{subgraphs:!0})}}if(r&&t.pendingWrites?.length){const e=Object.fromEntries(a.map((e=>[e.id,e])));for(const[n,r,s]of t.pendingWrites)[Ss,js,me].includes(r)||n in e&&e[n].writes.push([String(r),s]);const n=a.filter((e=>e.writes.length>0));n.length>0&&Vi(t.checkpoint,i,n)}let u=t?.metadata;u&&t?.config?.configurable?.thread_id&&(u={...u,thread_id:t.config.configurable.thread_id});const d=a.filter((e=>0===e.writes.length)).map((e=>e.name));return{values:Ei(i,this.streamChannelsAsIs),next:d,tasks:Ri(a,t?.pendingWrites??[],l),metadata:u,config:Ui(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){const n=e.configurable?.[Cs]??this.checkpointer;if(!n)throw new ns("No checkpointer set");const r=e.configurable?.checkpoint_ns??"";if(""!==r&&void 0===e.configurable?.[Cs]){const s=ai(r);for await(const[r,i]of this.getSubgraphsAsync(s,!0))if(r===s)return await i.getState(hi(e,{[Cs]:n}),{subgraphs:t?.subgraphs});throw new Error(`Subgraph with namespace "${s}" not found.`)}const s=(0,F.SV)(this.config,e),i=await n.getTuple(e);return await this._prepareStateSnapshot({config:s,saved:i,subgraphCheckpointer:t?.subgraphs?n:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){const n=e.configurable?.[Cs]??this.checkpointer;if(!n)throw new Error("No checkpointer set");const r=e.configurable?.checkpoint_ns??"";if(""!==r&&void 0===e.configurable?.[Cs]){const s=ai(r);for await(const[r,i]of this.getSubgraphsAsync(s,!0))if(r===s)return void(yield*i.getStateHistory(hi(e,{[Cs]:n}),t));throw new Error(`Subgraph with namespace "${s}" not found.`)}const s=(0,F.SV)(this.config,e,{configurable:{checkpoint_ns:r}});for await(const e of n.list(s,t))yield this._prepareStateSnapshot({config:e.config,saved:e})}async bulkUpdateState(e,t){const n=e.configurable?.[Cs]??this.checkpointer;if(!n)throw new ns("No checkpointer set");if(0===t.length)throw new Error("No supersteps provided");if(t.some((e=>0===e.updates.length)))throw new Error("No updates provided");const r=e.configurable?.checkpoint_ns??"";if(""!==r&&void 0===e.configurable?.[Cs]){const s=ai(r);for await(const[,r]of this.getSubgraphsAsync(s,!0))return await r.bulkUpdateState(hi(e,{[Cs]:n}),t);throw new Error(`Subgraph "${s}" not found`)}const s=async(e,t)=>{const r=this.config?(0,F.SV)(this.config,e):e,s=await n.getTuple(r),i=void 0!==s?Kr(s.checkpoint):Hr(),a={...s?.checkpoint.channel_versions},o=s?.metadata?.step??-1;let c=hi(r,{checkpoint_ns:r.configurable?.checkpoint_ns??""}),l=r.metadata??{};s?.config.configurable&&(c=hi(r,s.config.configurable),l={...s.metadata,...l});const{values:u,asNode:d}=t[0];if(null==u&&void 0===d){if(t.length>1)throw new ds("Cannot create empty checkpoint with multiple updates");return Ui(await n.put(c,gs(i,void 0,o),{source:"update",step:o+1,writes:{},parents:s?.metadata?.parents??{}},{}),s?s.metadata:void 0)}const h=ms(this.channels,i),{managed:p}=await this.prepareSpecs(r,{skipManaged:!0});if(null===u&&d===_s){if(t.length>1)throw new ds("Cannot apply multiple updates when clearing state");if(s){const e=Yi(i,s.pendingWrites||[],this.nodes,h,p,s.config,!0,{step:(s.metadata?.step??-1)+1,checkpointer:this.checkpointer||void 0,store:this.store}),t=(s.pendingWrites||[]).filter((e=>e[0]===Gs)).map((e=>e.slice(1)));t.length>0&&Vi(s.checkpoint,h,[{name:ks,writes:t,triggers:[]}]);for(const[t,n,r]of s.pendingWrites||[])[Ss,js,me].includes(n)||t in e&&e[t].writes.push([n,r]);Vi(i,h,Object.values(e))}return Ui(await n.put(c,gs(i,void 0,o),{...l,source:"update",step:o+1,writes:{},parents:s?.metadata?.parents??{}},{}),s?s.metadata:void 0)}if(null==u&&"__copy__"===d){if(t.length>1)throw new ds("Cannot copy checkpoint with multiple updates");return Ui(await n.put(s?.parentConfig??c,gs(i,void 0,o),{source:"fork",step:o+1,writes:{},parents:s?.metadata?.parents??{}},{}),s?s.metadata:void 0)}if(d===ks){if(t.length>1)throw new ds("Cannot apply multiple updates when updating as input");const e=await ui(Ci(this.inputChannels,u));if(0===e.length)throw new ds(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);Vi(i,h,[{name:ks,writes:e,triggers:[]}],n.getNextVersion.bind(this.checkpointer));const r=null!=s?.metadata?.step?s.metadata.step+1:-1,o=await n.put(c,gs(i,h,r),{source:"input",step:r,writes:Object.fromEntries(e),parents:s?.metadata?.parents??{}},Di(a,i.channel_versions));return await n.putWrites(o,e,pe(ks,i.id)),Ui(o,s?s.metadata:void 0)}if(void 0===r.configurable?.checkpoint_id&&void 0!==s?.pendingWrites&&s.pendingWrites.length>0){const e=Yi(i,s.pendingWrites,this.nodes,h,p,s.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(s.metadata?.step??-1)+1}),t=(s.pendingWrites??[]).filter((e=>e[0]===Gs)).map((e=>e.slice(1)));t.length>0&&Vi(s.checkpoint,h,[{name:ks,writes:t,triggers:[]}]);for(const[t,n,r]of s.pendingWrites)[Ss,js,me].includes(n)||void 0===e[t]||e[t].writes.push([n,r]);const n=Object.values(e).filter((e=>e.writes.length>0));n.length>0&&Vi(i,h,n)}const f=Object.values(i.versions_seen).map((e=>Object.values(e))).flat().find((e=>!!e)),m=[];if(1===t.length){let{values:e,asNode:n}=t[0];if(void 0===n&&1===Object.keys(this.nodes).length)[n]=Object.keys(this.nodes);else if(void 0===n&&void 0===f)"string"==typeof this.inputChannels&&void 0!==this.nodes[this.inputChannels]&&(n=this.inputChannels);else if(void 0===n){const e=Object.entries(i.versions_seen).map((([e,t])=>Object.values(t).map((t=>[t,e])))).flat().sort((([e],[t])=>Gr(e,t)));e&&(1===e.length?n=e[0][1]:e[e.length-1][0]!==e[e.length-2][0]&&(n=e[e.length-1][1]))}if(void 0===n)throw new ds('Ambiguous update, specify "asNode"');m.push({values:e,asNode:n})}else for(const{asNode:e,values:n}of t){if(null==e)throw new ds('"asNode" is required when applying multiple updates');m.push({values:n,asNode:e})}const g=[];for(const{asNode:e,values:t}of m){if(void 0===this.nodes[e])throw new ds(`Node "${e.toString()}" does not exist`);const n=this.nodes[e].getWriters();if(!n.length)throw new ds(`No writers found for node "${e.toString()}"`);g.push({name:e,input:t,proc:n.length>1?j.zZ.from(n,{omitSequenceTags:!0}):n[0],writes:[],triggers:[js],id:pe(js,i.id),writers:[]})}for(const e of g)await e.proc.invoke(e.input,(0,F.tn)({...r,store:r?.store??this.store},{runName:r.runName??`${this.getName()}UpdateState`,configurable:{[Ts]:t=>e.writes.push(...t),[Es]:(t,n=!1)=>Hi(o,i,h,p,e,t,n)}}));for(const e of g){const t=e.writes.filter((e=>e[0]!==Hs));void 0!==s&&t.length>0&&await n.putWrites(c,t,e.id)}Vi(i,h,g,n.getNextVersion.bind(this.checkpointer));const y=Di(a,i.channel_versions),b=await n.put(c,gs(i,h,o+1),{source:"update",step:o+1,writes:Object.fromEntries(m.map((e=>[e.asNode,e.values]))),parents:s?.metadata?.parents??{}},y);for(const e of g){const t=e.writes.filter((e=>e[0]===Hs));t.length>0&&await n.putWrites(b,t,e.id)}return Ui(b,s?s.metadata:void 0)};let i=e;for(const{updates:e}of t)i=await s(i,e);return i}async updateState(e,t,n){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:n}]}])}_defaults(e){const{debug:t,streamMode:n,inputKeys:r,outputKeys:s,interruptAfter:i,interruptBefore:a,...o}=e;let c=!0;const l=void 0!==t?t:this.debug;let u=s;void 0===u?u=this.streamChannelsAsIs:Ti(u,this.channels);let d=r;void 0===d?d=this.inputChannels:Ti(d,this.channels);const h=a??this.interruptBefore??[],p=i??this.interruptAfter??[];let f,m;void 0!==n?(f=Array.isArray(n)?n:[n],c="string"==typeof n):(f=this.streamMode,c=!0),void 0!==e.configurable?.[Is]&&(f=["values"]),m=!1===this.checkpointer?void 0:void 0!==e&&void 0!==e.configurable?.[Cs]?e.configurable[Cs]:this.checkpointer;return[l,f,d,u,o,h,p,m,e.store??this.store,c]}async stream(e,t){const n=new AbortController,r={recursionLimit:this.config?.recursionLimit,...t,signal:t?.signal?Bi(t.signal,n.signal):n.signal};return new Xi(await super.stream(e,r),n)}streamEvents(e,t,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,callbacks:this.config?.callbacks,...t,signal:t?.signal?Bi(t.signal,r.signal):r.signal};return new Xi(super.streamEvents(e,s,n),r)}async prepareSpecs(e,t){const n={...e,store:this.store},r={},s={};for(const[e,n]of Object.entries(this.channels))ps(n)?r[e]=n:s[e]=t?.skipManaged?{cls:aa,params:{config:{}}}:n;const i=new sa(await Object.entries(s).reduce((async(e,[t,r])=>{const s=await e;let i;return ia(r)?("key"in r.params&&"__channel_key_placeholder__"===r.params.key&&(r.params.key=t),i=await r.cls.initialize(n,r.params)):i=await r.initialize(n),void 0!==i&&s.push([t,i]),s}),Promise.resolve([])));return{channelSpecs:r,managed:i}}async _validateInput(e){return e}async _validateConfigurable(e){return e}async*_streamIterator(e,t){const n=t?.subgraphs,r=ii(this.config,t);if(void 0===r.recursionLimit||r.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(void 0!==this.checkpointer&&!1!==this.checkpointer&&void 0===r.configurable)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');const s=await this._validateInput(e),{runId:i,...a}=r,[o,c,,l,u,d,h,p,f,m]=this._defaults(a);u.configurable=await this._validateConfigurable(u.configurable);const g=new Qi({modes:new Set(c)});if(c.includes("messages")){const e=new oa((e=>g.push(e))),{callbacks:t}=u;if(void 0===t)u.callbacks=[e];else if(Array.isArray(t))u.callbacks=t.concat(e);else{const n=t.copy();n.addHandler(e,!0),u.callbacks=n}}c.includes("custom")&&(u.writer=e=>g.push([[],"custom",e]));const y=await(0,F.kJ)(u),b=await(y?.handleChainStart(this.toJSON(),function(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}(e,"input"),i,void 0,void 0,void 0,u?.runName??this.getName())),{channelSpecs:w,managed:v}=await this.prepareSpecs(u);let _,k;const S=(async()=>{try{_=await na.initialize({input:s,config:u,checkpointer:p,nodes:this.nodes,channelSpecs:w,managed:v,outputKeys:l,streamKeys:this.streamChannelsAsIs,store:f,stream:g,interruptAfter:h,interruptBefore:d,manager:b,debug:this.debug});const e=new da({loop:_,nodeFinished:u.configurable?.__pregel_node_finished});t?.subgraphs&&(_.config.configurable={..._.config.configurable,[As]:_.stream}),await this._runLoop({loop:_,runner:e,debug:o,config:u})}catch(e){k=e}finally{try{_&&await(_.store?.stop()),await Promise.all([..._?.checkpointerPromises??[],...Array.from(v.values()).map((e=>e.promises()))])}catch(e){k=k??e}k?g.error(k):g.close()}})();try{for await(const e of g){if(void 0===e)throw new Error("Data structure error.");const[t,r,s]=e;c.includes(r)&&(n&&!m?yield[t,r,s]:m?n?yield[t,s]:yield s:yield[r,s])}}catch(e){throw await(b?.handleChainError(k)),e}finally{await S}await(b?.handleChainEnd(_?.output??{},i,void 0,void 0,void 0))}async invoke(e,t){const n=t?.streamMode??"values",r={...t,outputKeys:t?.outputKeys??this.outputChannels,streamMode:n},s=[],i=await this.stream(e,r);for await(const e of i)s.push(e);return"values"===n?s[s.length-1]:s}async _runLoop(e){const{loop:t,runner:n,debug:r,config:s}=e;let i;try{for(;await t.tick({inputKeys:this.inputChannels});)r&&(t.checkpointMetadata.step,t.channels,this.streamChannelsList),r&&Ni(t.step,Object.values(t.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(e,t)=>{r&&ji(0,t,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal});if("out_of_steps"===t.status)throw new ts([`Recursion limit of ${s.recursionLimit} reached`,"without hitting a stop condition. You can increase the",'limit by setting the "recursionLimit" config key.'].join(" "),{lc_error_code:"GRAPH_RECURSION_LIMIT"})}catch(e){i=e;if(!await t.finishAndHandleError(i))throw e}finally{void 0===i&&await t.finishAndHandleError()}}}class fa extends fs{constructor(e,t){super(),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"BinaryOperatorAggregate"}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"operator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialValueFactory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.operator=e,this.initialValueFactory=t,this.value=t?.()}fromCheckpoint(e){const t=new fa(this.operator,this.initialValueFactory);return e&&(t.value=e),t}update(e){let t=e;if(!t.length)return!1;void 0===this.value&&([this.value]=t,t=t.slice(1));for(const e of t)void 0!==this.value&&(this.value=this.operator(this.value,e));return!0}get(){if(void 0===this.value)throw new us;return this.value}checkpoint(){if(void 0===this.value)throw new us;return this.value}}class ma extends fs{constructor(e=!0){super(),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"EphemeralValue"}),Object.defineProperty(this,"guard",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.guard=e}fromCheckpoint(e){const t=new ma(this.guard);return e&&(t.value=[e]),t}update(e){if(0===e.length){const e=this.value.length>0;return this.value=[],e}if(1!==e.length&&this.guard)throw new ds("EphemeralValue can only receive one value per step.");return this.value=[e[e.length-1]],!0}get(){if(0===this.value.length)throw new us;return this.value[0]}checkpoint(){if(0===this.value.length)throw new us;return this.value[0]}}class ga{constructor(e){Object.defineProperty(this,"condition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ends",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),j.YN.isRunnable(e.path)?this.condition=e.path:this.condition=(0,j.Bp)(e.path).withConfig({runName:"Branch"}),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce(((e,t)=>(e[t]=t,e)),{}):e.pathMap}run(e,t){return yi.registerWriter(new ci({name:" ",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,e,t)}catch(e){throw e.name,ss.unminifiable_name,e}}}))}async _route(e,t,n,r){let s,i=await this.condition.invoke(r?r(t):e,t);if(Array.isArray(i)||(i=[i]),s=this.ends?i.map((e=>Qs(e)?e:this.ends[e])):i,s.some((e=>!e)))throw new Error("Branch condition returned unknown or null destination");if(s.filter(Qs).some((e=>e.node===_s)))throw new ds("Cannot send a packet to the END node");return await n(s,t)??e}}class ya{constructor(){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"branches",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"entryPoint",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"compiled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(e){this.compiled}get allEdges(){return this.edges}addNode(e,t,n){for(const t of[Ys,Js])if(e.includes(t))throw new Error(`"${t}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),e in this.nodes)throw new Error(`Node \`${e}\` already present.`);if(e===_s)throw new Error(`Node \`${e}\` is reserved.`);const r=(0,j.Bp)(t);return this.nodes[e]={runnable:r,metadata:n?.metadata,subgraphs:Oi(r)?[r]:n?.subgraphs,ends:n?.ends},this}addEdge(e,t){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),e===_s)throw new Error("END cannot be a start node");if(t===vs)throw new Error("START cannot be an end node");if(Array.from(this.edges).some((([t])=>t===e))&&!("channels"in this))throw new Error(`Already found path for ${e}. For multiple edges, use StateGraph.`);return this.edges.add([e,t]),this}addConditionalEdges(e,t,n){const r="object"==typeof e?e:{source:e,path:t,pathMap:n};if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),!j.YN.isRunnable(r.path)){const e=Array.isArray(r.pathMap)?r.pathMap.join(","):Object.keys(r.pathMap??{}).join(",");r.path=(0,j.Bp)(r.path).withConfig({runName:`Branch<${r.source}${""!==e?`,${e}`:""}>`.slice(0,63)})}const s="RunnableLambda"===r.path.getName()?"condition":r.path.getName();if(this.branches[r.source]&&this.branches[r.source][s])throw new Error(`Condition \`${s}\` already present for node \`${e}\``);return this.branches[r.source]||(this.branches[r.source]={}),this.branches[r.source][s]=new ga(r),this}setEntryPoint(e){return this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(vs,e)}setFinishPoint(e){return this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(e,_s)}compile({checkpointer:e,interruptBefore:t,interruptAfter:n,name:r}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(n)?n:[]]);const s=new ba({builder:this,checkpointer:e,interruptAfter:n,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[vs]:new ma,[_s]:new ma},inputChannels:vs,outputChannels:_s,streamChannels:[],streamMode:"values",name:r});for(const[e,t]of Object.entries(this.nodes))s.attachNode(e,t);for(const[e,t]of this.edges)s.attachEdge(e,t);for(const[e,t]of Object.entries(this.branches))for(const[n,r]of Object.entries(t))s.attachBranch(e,n,r);return s.validate()}validate(e){const t=new Set([...this.allEdges].map((([e,t])=>e)));for(const[e]of Object.entries(this.branches))t.add(e);for(const e of t)if(e!==vs&&!(e in this.nodes))throw new Error(`Found edge starting at unknown node \`${e}\``);const n=new Set([...this.allEdges].map((([e,t])=>t)));for(const[e,t]of Object.entries(this.branches))for(const r of Object.values(t))if(r.ends)for(const e of Object.values(r.ends))n.add(e);else{n.add(_s);for(const t of Object.keys(this.nodes))t!==e&&n.add(t)}for(const e of Object.values(this.nodes))for(const t of e.ends??[])n.add(t);for(const e of Object.keys(this.nodes))if(!n.has(e))throw new hs([`Node \`${e}\` is not reachable.`,"","If you are returning Command objects from your node,",'make sure you are passing names of potential destination nodes as an "ends" array','into ".addNode(..., { ends: ["node1", "node2"] })".'].join("\n"),{lc_error_code:"UNREACHABLE_NODE"});for(const e of n)if(e!==_s&&!(e in this.nodes))throw new Error(`Found edge ending at unknown node \`${e}\``);if(e)for(const t of e)if(!(t in this.nodes))throw new Error(`Interrupt node \`${t}\` is not present`);this.compiled=!0}}class ba extends pa{constructor({builder:e,...t}){super(t),Object.defineProperty(this,"builder",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.builder=e}attachNode(e,t){this.channels[e]=new ma,this.nodes[e]=new ki({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new yi([{channel:e,value:fi}],[Bs])),this.streamChannels.push(e)}attachEdge(e,t){if(t===_s){if(e===vs)throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new yi([{channel:_s,value:fi}],[Bs]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,n){e!==vs||this.nodes[vs]||(this.nodes[vs]=ha.subscribeTo(vs,{tags:[Bs]})),this.nodes[e].pipe(n.run((n=>{const r=n.map((n=>Qs(n)?n:{channel:n===_s?_s:`branch:${e}:${t}:${n}`,value:fi}));return new yi(r,[Bs])})));const r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(const n of r)if(n!==_s){const r=`branch:${e}:${t}:${n}`;this.channels[r]=new ma,this.nodes[n].triggers.push(r),this.nodes[n].channels.push(r)}}async getGraphAsync(e){const t=e?.xray,n=new ys.T,r={[vs]:n.addNode({schema:R.z.any()},vs)},s={};let i={};function a(e,t,i,a=!1){if(t===_s&&void 0===s[_s]&&(s[_s]=n.addNode({schema:R.z.any()},_s)),void 0!==r[e]){if(void 0===s[t])throw new Error(`End node ${t} not found!`);return n.addEdge(r[e],s[t],i!==t?i:void 0,a)}}t&&(i=Object.fromEntries((await ui(this.getSubgraphsAsync())).filter((e=>wa(e[1])))));for(const[c,l]of Object.entries(this.builder.nodes)){const u=va(c),d=l.runnable,h=l.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?h.__interrupt="before,after":this.interruptBefore?.includes(c)?h.__interrupt="before":this.interruptAfter?.includes(c)&&(h.__interrupt="after"),t){const p="number"==typeof t?t-1:t,f=void 0!==i[c]?await i[c].getGraphAsync({...e,xray:p}):d.getGraph(e);if(f.trimFirstNode(),f.trimLastNode(),Object.keys(f.nodes).length>1){const[m,g]=n.extend(f,u);if(void 0===m)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);function y(e,t){if(void 0!==e&&!ws(e))return e;if(!(n=t)||!n.lc_runnable)return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e,e}catch(e){return t.getName()}var n}void 0!==g&&(r[u]={name:y(g.id,g.data),...g}),s[u]={name:y(m.id,m.data),...m}}else{const b=n.addNode(d,u,h);r[u]=b,s[u]=b}}else{const w=n.addNode(d,u,h);r[u]=w,s[u]=w}}const o=[...this.builder.allEdges].sort((([e],[t])=>e e?1:0));for(const[v,_]of o)a(va(v),va(_));for(const[k,S]of Object.entries(this.builder.branches)){const T={...Object.fromEntries(Object.keys(this.builder.nodes).filter((e=>e!==k)).map((e=>[va(e),va(e)]))),[_s]:_s};for(const x of Object.values(S)){let E;E=void 0!==x.ends?x.ends:T;for(const[C,P]of Object.entries(E))a(va(k),va(P),C,!0)}}for(const[I,A]of Object.entries(this.builder.nodes))if(void 0!==A.ends)for(const O of A.ends)a(va(I),va(O),void 0,!0);return n}getGraph(e){const t=e?.xray,n=new ys.T,r={[vs]:n.addNode({schema:R.z.any()},vs)},s={};let i={};function a(e,t,i,a=!1){return t===_s&&void 0===s[_s]&&(s[_s]=n.addNode({schema:R.z.any()},_s)),n.addEdge(r[e],s[t],i!==t?i:void 0,a)}t&&(i=Object.fromEntries(di(this.getSubgraphs()).filter((e=>wa(e[1])))));for(const[c,l]of Object.entries(this.builder.nodes)){const u=va(c),d=l.runnable,h=l.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?h.__interrupt="before,after":this.interruptBefore?.includes(c)?h.__interrupt="before":this.interruptAfter?.includes(c)&&(h.__interrupt="after"),t){const p="number"==typeof t?t-1:t,f=void 0!==i[c]?i[c].getGraph({...e,xray:p}):d.getGraph(e);if(f.trimFirstNode(),f.trimLastNode(),Object.keys(f.nodes).length>1){const[m,g]=n.extend(f,u);if(void 0===m)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);function y(e,t){if(void 0!==e&&!ws(e))return e;if(!(n=t)||!n.lc_runnable)return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e,e}catch(e){return t.getName()}var n}void 0!==g&&(r[u]={name:y(g.id,g.data),...g}),s[u]={name:y(m.id,m.data),...m}}else{const b=n.addNode(d,u,h);r[u]=b,s[u]=b}}else{const w=n.addNode(d,u,h);r[u]=w,s[u]=w}}const o=[...this.builder.allEdges].sort((([e],[t])=>e e?1:0));for(const[v,_]of o)a(va(v),va(_));for(const[k,S]of Object.entries(this.builder.branches)){const T={...Object.fromEntries(Object.keys(this.builder.nodes).filter((e=>e!==k)).map((e=>[va(e),va(e)]))),[_s]:_s};for(const x of Object.values(S)){let E;E=void 0!==x.ends?x.ends:T;for(const[C,P]of Object.entries(E))a(va(k),va(P),C,!0)}}return n}}function wa(e){return"function"==typeof e.attachNode&&"function"==typeof e.attachEdge}function va(e){return"subgraph"===e?`"${e}"`:e}const _a=(e,t)=>e.size===t.size&&[...e].every((e=>t.has(e)));class ka extends fs{constructor(e){super(),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"NamedBarrierValue"}),Object.defineProperty(this,"names",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"seen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.names=e,this.seen=new Set}fromCheckpoint(e){const t=new ka(this.names);return e&&(t.seen=new Set(e)),t}update(e){let t=!1;for(const n of e){if(!this.names.has(n))throw new ds(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);this.seen.has(n)||(this.seen.add(n),t=!0)}return t}get(){if(!_a(this.names,this.seen))throw new us}checkpoint(){return[...this.seen]}consume(){return!!(this.seen&&this.names&&_a(this.seen,this.names))&&(this.seen=new Set,!0)}}class Sa extends fs{constructor(){super(...arguments),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"LastValue"}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:[]})}fromCheckpoint(e){const t=new Sa;return e&&(t.value=[e]),t}update(e){if(0===e.length)return!1;if(1!==e.length)throw new ds("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[e[e.length-1]],!0}get(){if(0===this.value.length)throw new us;return this.value[0]}checkpoint(){if(0===this.value.length)throw new us;return this.value[0]}}class Ta{constructor(e){Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"AnnotationRoot"}),Object.defineProperty(this,"spec",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.spec=e}}const xa=function(e){return ia(e)?e:e?Ea(e):new Sa};function Ea(e){return"object"==typeof e&&e&&"reducer"in e&&e.reducer?new fa(e.reducer,e.default):"object"==typeof e&&e&&"value"in e&&e.value?new fa(e.value,e.default):new Sa}xa.Root=e=>new Ta(e);const Ca=new WeakMap;function Pa(e){return"object"==typeof e&&null!=e&&"_parse"in e&&"function"==typeof e._parse}function Ia(e){return Pa(e)&&"partial"in e&&"function"==typeof e.partial}function Aa(e){return Ca.get(e)}function Oa(e){const t={};for(const n in e.shape)if(Object.prototype.hasOwnProperty.call(e.shape,n)){const r=Aa(e.shape[n]);t[n]=r?.reducer?new fa(r.reducer.fn,r.default):new Sa}return t}const $a="__root__";class Ma extends ya{constructor(e,t){if(super(),Object.defineProperty(this,"channels",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"waitingEdges",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_schemaDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaRuntimeDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_inputDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_inputRuntimeDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_outputDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_outputRuntimeDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaDefinitions",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_configSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_configRuntimeSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),function(e){if("object"!=typeof e||null==e)return!1;if(!("state"in e)||!Ia(e.state))return!1;if("input"in e&&!Ia(e.input))return!1;if("output"in e&&!Ia(e.output))return!1;return!0}(e)){const t=Oa(e.state),n=null!=e.input?Oa(e.input):t,r=null!=e.output?Oa(e.output):t;this._schemaDefinition=t,this._schemaRuntimeDefinition=e.state,this._inputDefinition=n,this._inputRuntimeDefinition=e.input??e.state.partial(),this._outputDefinition=r,this._outputRuntimeDefinition=e.output??e.state}else if(Ia(e)){const t=Oa(e);this._schemaDefinition=t,this._schemaRuntimeDefinition=e,this._inputDefinition=t,this._inputRuntimeDefinition=e.partial(),this._outputDefinition=t,this._outputRuntimeDefinition=e}else if(function(e){return"object"==typeof e&&null!==e&&void 0===e.stateSchema&&void 0!==e.input&&void 0!==e.output}(e))this._schemaDefinition=e.input.spec,this._inputDefinition=e.input.spec,this._outputDefinition=e.output.spec;else if(function(e){return"object"==typeof e&&null!==e&&void 0!==e.stateSchema}(e))this._schemaDefinition=e.stateSchema.spec,this._inputDefinition=e.input?.spec??this._schemaDefinition,this._outputDefinition=e.output?.spec??this._schemaDefinition;else if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every((e=>"function"==typeof e||ps(e)))}(e)||Na(e)){const t=Na(e)?e.spec:e;this._schemaDefinition=t}else{if(!function(e){return"object"==typeof e&&null!==e&&void 0!==e.channels}(e))throw new Error("Invalid StateGraph input.");{const t=function(e){const t={};for(const[n,r]of Object.entries(e))if(n===$a)t[n]=Ea(r);else{t[n]=Ea(r)}return t}(e.channels);this._schemaDefinition=t}}this._inputDefinition??=this._schemaDefinition,this._outputDefinition??=this._schemaDefinition,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),Ia(t)&&(this._configRuntimeSchema=t.passthrough())}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap((([e,t])=>e.map((e=>[e,t]))))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(const[t,n]of Object.entries(e)){let e;if(e="function"==typeof n?n():n,void 0!==this.channels[t]){if(this.channels[t]!==e&&!ia(e)&&"LastValue"!==e.lc_graph_name)throw new Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=e}}}addNode(e,t,n){if(e in this.channels)throw new Error(`${e} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(const t of[Ys,Js])if(e.includes(t))throw new Error(`"${t}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),e in this.nodes)throw new Error(`Node \`${e}\` already present.`);if(e===_s||e===vs)throw new Error(`Node \`${e}\` is reserved.`);let r;void 0!==n?.input&&this._addSchema(n.input.spec),r=j.YN.isRunnable(t)?t:"function"==typeof t?new ci({func:t,name:e,trace:!1}):(0,j.Bp)(t);const s={runnable:r,retryPolicy:n?.retryPolicy,metadata:n?.metadata,input:n?.input?.spec??this._schemaDefinition,subgraphs:Oi(r)?[r]:n?.subgraphs,ends:n?.ends};return this.nodes[e]=s,this}addEdge(e,t){if("string"==typeof e)return super.addEdge(e,t);this.compiled;for(const t of e){if(t===_s)throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some((e=>e===t)))throw new Error(`Need to add a node named "${t}" first`)}if(t===_s)throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some((e=>e===t)))throw new Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}compile({checkpointer:e,store:t,interruptBefore:n,interruptAfter:r,name:s}={}){this.validate([...Array.isArray(n)?n:[],...Array.isArray(r)?r:[]]);const i=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),a=1===i.length&&i[0]===$a?$a:i,o=Object.keys(this.channels),c=1===o.length&&o[0]===$a?$a:o,l=new Ra({builder:this,checkpointer:e,interruptAfter:r,interruptBefore:n,autoValidate:!1,nodes:{},channels:{...this.channels,[vs]:new ma},inputChannels:vs,outputChannels:a,streamChannels:c,streamMode:"updates",store:t,name:s});l.attachNode(vs);for(const[e,t]of Object.entries(this.nodes))l.attachNode(e,t);l.attachBranch(vs,qs,Fa(),{withReader:!1});for(const[e]of Object.entries(this.nodes))l.attachBranch(e,qs,Fa(),{withReader:!1});for(const[e,t]of this.edges)l.attachEdge(e,t);for(const[e,t]of this.waitingEdges)l.attachEdge(e,t);for(const[e,t]of Object.entries(this.branches))for(const[n,r]of Object.entries(t))l.attachBranch(e,n,r);return l.validate()}}class Ra extends ba{attachNode(e,t){let n;n=e===vs?Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).filter((([e,t])=>!ia(t))).map((([e])=>e)):Object.keys(this.builder.channels);const r=e;const s=[{value:fi,mapper:new ci({func:n.length&&n[0]===$a?function(e){if(ti(e))return e.graph===ei.PARENT?null:e._updateAsTuples();if(Array.isArray(e)&&e.length>0&&e.some((e=>ti(e)))){const t=[];for(const n of e)if(ti(n)){if(n.graph===ei.PARENT)continue;t.push(...n._updateAsTuples())}else t.push([$a,n]);return t}return null!=e?[[$a,e]]:null}:function e(t){if(t){if(ti(t))return t.graph===ei.PARENT?null:t._updateAsTuples().filter((([e])=>n.includes(e)));if(Array.isArray(t)&&t.length>0&&t.some(ti)){const r=[];for(const s of t)if(ti(s)){if(s.graph===ei.PARENT)continue;r.push(...s._updateAsTuples().filter((([e])=>n.includes(e))))}else{const t=e(s);t&&r.push(...t??[])}return r}if("object"!=typeof t||Array.isArray(t)){const e=Array.isArray(t)?"array":typeof t;throw new ds(`Expected node "${r.toString()}" to return an object or an array containing at least one Command object, received ${e}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}return Object.entries(t).filter((([e])=>n.includes(e)))}return null},trace:!1,recurse:!1})}];if(e===vs)this.nodes[e]=new ki({tags:[Bs],triggers:[vs],channels:[vs],writers:[new yi(s,[Bs])]});else{const n=t?.input??this.builder._schemaDefinition,r=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(n)).map((e=>[e,e]))),i=1===Object.keys(r).length&&$a in r;this.channels[e]=new ma(!1),this.nodes[e]=new ki({triggers:[],channels:i?Object.keys(r):r,writers:[new yi(s.concat({channel:e,value:e}),[Bs])],mapper:i?void 0:e=>Object.fromEntries(Object.entries(e).filter((([e])=>e in r))),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,subgraphs:t?.subgraphs,ends:t?.ends})}}attachEdge(e,t){if(t!==_s)if(Array.isArray(e)){const n=`join:${e.join("+")}:${t}`;this.channels[n]=new ka(new Set(e)),this.nodes[t].triggers.push(n);for(const t of e)this.nodes[t].writers.push(new yi([{channel:n,value:t}],[Bs]))}else if(e===vs){const e=`${vs}:${t}`;this.channels[e]=new ma,this.nodes[t].triggers.push(e),this.nodes[vs].writers.push(new yi([{channel:e,value:vs}],[Bs]))}else this.nodes[t].triggers.push(e)}attachBranch(e,t,n,r={withReader:!0}){this.nodes[e].writers.push(n.run((async(n,r)=>{const s=n.filter((e=>e!==_s));if(!s.length)return;const i=s.map((n=>Qs(n)?n:{channel:`branch:${e}:${t}:${n}`,value:e}));await yi.doWrite({...r,tags:(r.tags??[]).concat([Bs])},i)}),r.withReader?e=>vi.doRead(e,this.streamChannels??this.outputChannels,!0):void 0));const s=n.ends?Object.values(n.ends):Object.keys(this.builder.nodes);for(const n of s){if(n===_s)continue;const r=`branch:${e}:${t}:${n}`;this.channels[r]=new ma(!1),this.nodes[n].triggers.push(r)}}async _validateInput(e){const t=this.builder._inputRuntimeDefinition;if(ti(e)){const n=e;return e.update&&Ia(t)&&(n.update=t.parse(e.update)),n}return Ia(t)?t.parse(e):e}async _validateConfigurable(e){const t=this.builder._configRuntimeSchema;return Ia(t)&&t.parse(e),e}}function Na(e){return"object"==typeof e&&null!==e&&"lc_graph_name"in e&&"AnnotationRoot"===e.lc_graph_name}function ja(e){if(Qs(e))return[e];const t=[];ti(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(ti));const n=[];for(const e of t){if(e.graph===ei.PARENT)throw new is(e);Qs(e.goto)||"string"==typeof e.goto?n.push(e.goto):Array.isArray(e.goto)&&n.push(...e.goto)}return n}function Fa(){const e=new ci({func:ja,tags:[Bs],trace:!1,recurse:!1,name:" "});return new ga({path:e})}const La={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};var Da,za=new Uint8Array(16);function Ua(){if(!Da&&!(Da="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Da(za)}for(var Ba=[],qa=0;qa<256;++qa)Ba.push((qa+256).toString(16).slice(1));function Wa(e,t=0){return(Ba[e[t+0]]+Ba[e[t+1]]+Ba[e[t+2]]+Ba[e[t+3]]+"-"+Ba[e[t+4]]+Ba[e[t+5]]+"-"+Ba[e[t+6]]+Ba[e[t+7]]+"-"+Ba[e[t+8]]+Ba[e[t+9]]+"-"+Ba[e[t+10]]+Ba[e[t+11]]+Ba[e[t+12]]+Ba[e[t+13]]+Ba[e[t+14]]+Ba[e[t+15]]).toLowerCase()}const Ha=function(e,t,n){if(La.randomUUID&&!t&&!e)return La.randomUUID();var r=(e=e||{}).random||(e.rng||Ua)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){n=n||0;for(var s=0;s<16;++s)t[n+s]=r[s];return t}return Wa(r)};function Ka(e,t){const n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t],s=n.map(N.coerceMessageLikeToMessage),i=r.map(N.coerceMessageLikeToMessage);for(const e of s)null!==e.id&&void 0!==e.id||(e.id=Ha(),e.lc_kwargs.id=e.id);for(const e of i)null!==e.id&&void 0!==e.id||(e.id=Ha(),e.lc_kwargs.id=e.id);const a=[...s],o=new Map(a.map(((e,t)=>[e.id,t]))),c=new Set;for(const e of i){const t=o.get(e.id);if(void 0!==t)"remove"===e._getType()?c.add(e.id):(c.delete(e.id),a[t]=e);else{if("remove"===e._getType())throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${e.id}')`);o.set(e.id,a.length),a.push(e)}}return a.filter((e=>!c.has(e.id)))}class Ga extends ci{constructor(e,t){const{name:n,tags:r,handleToolErrors:s}=t??{};super({name:n,tags:r,func:(e,t)=>this.run(e,t)}),Object.defineProperty(this,"tools",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handleToolErrors",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"trace",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.tools=e,this.handleToolErrors=s??this.handleToolErrors}async run(e,t){const n=Array.isArray(e)?e[e.length-1]:e.messages[e.messages.length-1];if("ai"!==n?._getType())throw new Error("ToolNode only accepts AIMessages as input.");const r=await Promise.all(n.tool_calls?.map((async e=>{const n=this.tools.find((t=>t.name===e.name));try{if(void 0===n)throw new Error(`Tool "${e.name}" not found.`);const r=await n.invoke({...e,type:"tool_call"},t);return(0,N.isBaseMessage)(r)&&"tool"===r._getType()||ti(r)?r:new N.ToolMessage({name:n.name,content:"string"==typeof r?r:JSON.stringify(r),tool_call_id:e.id})}catch(t){if(!this.handleToolErrors)throw t;if(cs(t))throw t;return new N.ToolMessage({content:`Error: ${t.message}\n Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}))??[]);if(!r.some(ti))return Array.isArray(e)?r:{messages:r};const s=[];let i=null;for(const t of r)ti(t)?t.graph===ei.PARENT&&Array.isArray(t.goto)&&t.goto.every((e=>Qs(e)))?i?i.goto.push(...t.goto):i=new ei({graph:ei.PARENT,goto:t.goto}):s.push(t):s.push(Array.isArray(e)?[t]:{messages:[t]});return i&&s.push(i),s}}const Va=/ (.*?)<\/name>/s,Ya=/ (.*?)<\/content>/s;function Ja(e){if(!((0,N.isBaseMessage)(e)&&((0,N.isAIMessage)(e)||(0,N.isBaseMessageChunk)(e)&&(0,N.isAIMessageChunk)(e)))||!e.name)return e;const{name:t}=e;if("string"==typeof e.content)return new N.AIMessage({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:` ${t} ${e.content} `,name:void 0});const n=[];let r=0;for(const s of e.content)"string"==typeof s?(r+=1,n.push(`${t} ${s} `)):"object"==typeof s&&"type"in s&&"text"===s.type?(r+=1,n.push({...s,text:`${t} ${s.text} `})):n.push(s);return r||n.unshift({type:"text",text:`${t} `}),new N.AIMessage({...e.lc_kwargs,content:n,name:void 0})}function Za(e){if(!(0,N.isAIMessage)(e)||!e.content)return e;let t,n=[];if(Array.isArray(e.content))n=e.content.filter((e=>{if("text"===e.type){const n=e.text.match(Va),r=e.text.match(Ya);return!(n&&(!r||""===r[1]))||(t=n[1],!1)}return!0})).map((e=>{if("text"===e.type){const n=e.text.match(Va),r=e.text.match(Ya);return n&&r?(t=n[1],{...e,text:r[1]}):e}return e}));else{const r=e.content,s=r.match(Va),i=r.match(Ya);if(!s||!i)return e;t=s[1],n=i[1]}return new N.AIMessage({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:n,name:t})}const Xa="prompt";function Qa(e,t,n){const r=[e,t,n].filter((e=>null!=e)).length;if(r>1)throw new Error("Expected only one of prompt, stateModifier, or messageModifier, got multiple values");let s=e;return null!=t?s=t:null!=n&&(s=function(e){if("string"==typeof e||(0,N.isBaseMessage)(e)&&"system"===e._getType())return e;if("function"==typeof e)return async t=>e(t.messages);if(j.YN.isRunnable(e))return j.jY.from((e=>e.messages)).pipe(e);throw new Error("Unexpected type for messageModifier: "+typeof e)}(n)),function(e){let t;if(null==e)t=j.jY.from((e=>e.messages)).withConfig({runName:Xa});else if("string"==typeof e){const n=new N.SystemMessage(e);t=j.jY.from((e=>[n,...e.messages??[]])).withConfig({runName:Xa})}else if((0,N.isBaseMessage)(e)&&"system"===e._getType())t=j.jY.from((t=>[e,...t.messages])).withConfig({runName:Xa});else if("function"==typeof e)t=j.jY.from(e).withConfig({runName:Xa});else{if(!j.YN.isRunnable(e))throw new Error("Got unexpected type for 'prompt': "+typeof e);t=e}return t}(s)}function eo(e){return"invoke"in e&&"function"==typeof e.invoke&&"_modelType"in e}function to(e){return"_queuedMethodOperations"in e&&"_model"in e&&"function"==typeof e._model}async function no(e){let t=e;if(j.zZ.isRunnableSequence(t)&&(t=t.steps.find((e=>j.fJ.isRunnableBinding(e)||eo(e)||to(e)))||t),to(t)&&(t=await t._model()),j.fJ.isRunnableBinding(t)&&(t=t.bound),!eo(t))throw new Error(`Expected \`llm\` to be a ChatModel or RunnableBinding (e.g. llm.bind_tools(...)) with invoke() and generate() methods, got ${t.constructor.name}`);return t}function ro(e){const{llm:t,tools:n,messageModifier:r,stateModifier:s,prompt:i,stateSchema:a,checkpointSaver:o,checkpointer:c,interruptBefore:l,interruptAfter:u,store:d,responseFormat:h,name:p,includeAgentName:f}=e;let m,g;Array.isArray(n)?(m=n,g=new Ga(n)):(m=n.tools,g=n);let y=null;const b=async e=>{if(y)return y;let t;if(await async function(e,t){let n=e;if(j.zZ.isRunnableSequence(n)&&(n=n.steps.find((e=>j.fJ.isRunnableBinding(e)||eo(e)||to(e)))||n),to(n)&&(n=await n._model()),!j.fJ.isRunnableBinding(n))return!0;if(!n.kwargs||"object"!=typeof n.kwargs||!("tools"in n.kwargs))return!0;let r=n.kwargs.tools;if(1===r.length&&"functionDeclarations"in r[0]&&(r=r[0].functionDeclarations),t.length!==r.length)throw new Error("Number of tools in the model.bindTools() and tools passed to createReactAgent must match");const s=new Set(t.map((e=>e.name))),i=new Set;for(const e of r){let t;if("type"in e&&"function"===e.type)t=e.function.name;else if("name"in e)t=e.name;else{if(!("toolSpec"in e)||!("name"in e.toolSpec))continue;t=e.toolSpec.name}t&&i.add(t)}const a=[...s].filter((e=>!i.has(e)));if(a.length>0)throw new Error(`Missing tools '${a}' in the model.bindTools().Tools in the model.bindTools() must match the tools passed to createReactAgent.`);return!1}(e,m)){if(!("bindTools"in e)||"function"!=typeof e.bindTools)throw new Error(`llm ${e} must define bindTools method.`);t=e.bindTools(m)}else t=e;const n=Qa(i,s,r),a="inline"===f?n.pipe(function(e,t){let n,r;if("inline"!==t)throw new Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);return n=Ja,r=Za,j.zZ.from([j.jY.from((function(e){return e.map(n)})),e,j.jY.from(r)])}(t,f)):n.pipe(t);return y=a,a},w=new Set(m.filter((e=>"returnDirect"in e&&e.returnDirect)).map((e=>e.name))),v=e=>{const{messages:t}=e,n=t[t.length-1];return!(0,N.isAIMessage)(n)||n.tool_calls&&0!==n.tool_calls.length?"continue":null!=h?"generate_structured_response":_s},_=async(e,n)=>{if(null==h)throw new Error("Attempted to generate structured output with no passed response schema. Please contact us for help.");const r=[...e.messages];let s;if("object"==typeof h&&"prompt"in h&&"schema"in h){const{prompt:e,schema:n}=h;s=(await no(t)).withStructuredOutput(n),r.unshift(new N.SystemMessage({content:e}))}else s=(await no(t)).withStructuredOutput(h);return{structuredResponse:await s.invoke(r,n)}},k=new Ma(a??xa.Root({messages:xa({reducer:Ka,default:()=>[]}),structuredResponse:xa})).addNode("agent",(async(e,n)=>{const r=await b(t),s=await r.invoke(e,n);return s.name=p,s.lc_kwargs.name=p,{messages:[s]}})).addNode("tools",g).addEdge(vs,"agent");void 0!==h?k.addNode("generate_structured_response",_).addEdge("generate_structured_response",_s).addConditionalEdges("agent",v,{continue:"tools",[_s]:_s,generate_structured_response:"generate_structured_response"}):k.addConditionalEdges("agent",v,{continue:"tools",[_s]:_s});const S=e=>{for(let t=e.messages.length-1;t>=0;t-=1){const n=e.messages[t];if(!(0,N.isToolMessage)(n))break;if(void 0!==n.name&&w.has(n.name))return _s}return"agent"};return w.size>0?k.addConditionalEdges("tools",S,["agent",_s]):k.addEdge("tools","agent"),k.compile({checkpointer:c??o,interruptBefore:l,interruptAfter:u,store:d,name:p})}const so=R.z.object({width:R.z.number().int().positive(),height:R.z.number().int().positive()}),io=R.z.object({minimumWaitPageLoadTime:R.z.number().default(.25),waitForNetworkIdlePageLoadTime:R.z.number().default(.5),maximumWaitPageLoadTime:R.z.number().default(5),waitBetweenActions:R.z.number().default(.5),browserWindowSize:so.default({width:1280,height:1100}),viewportExpansion:R.z.number().int().default(0),allowedUrls:R.z.array(R.z.string()).default([]),deniedUrls:R.z.array(R.z.string()).default([]),includeDynamicAttributes:R.z.boolean().default(!0),homePageUrl:R.z.string().default("https://www.google.com"),displayHighlights:R.z.boolean().default(!0)}).parse({}),ao=R.z.object({tabId:R.z.number().int().positive(),url:R.z.string(),title:R.z.string(),screenshot:R.z.string().nullable(),pixelsAbove:R.z.number().int().min(0),pixelsBelow:R.z.number().int().min(0)}),oo=R.z.object({id:R.z.number().int().positive(),url:R.z.string(),title:R.z.string()});ao.extend({tabs:R.z.array(oo),browser_errors:R.z.array(R.z.string())});class co extends Error{constructor(e){super(e),this.name="BrowserError"}}class lo extends co{constructor(e){super(e),this.name="URLNotAllowedError"}}var uo=function(e,t){return uo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},uo(e,t)};function ho(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}uo(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function po(e,t,n,r){return new(n||(n=Promise))((function(s,i){function a(e){try{c(r.next(e))}catch(e){i(e)}}function o(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){e.done?s(e.value):function(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(a,o)}c((r=r.apply(e,t||[])).next())}))}function fo(e,t){var n,r,s,i={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(o){return function(c){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,o[0]&&(i=0)),i;)try{if(n=1,r&&(s=2&o[0]?r.return:o[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,o[1])).done)return s;switch(r=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return i.label++,{value:o[1],done:!1};case 5:i.label++,r=o[1],o=[0];continue;case 7:o=i.ops.pop(),i.trys.pop();continue;default:if(!(s=i.trys,(s=s.length>0&&s[s.length-1])||6!==o[0]&&2!==o[0])){i=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1] =e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function go(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,s,i=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(e){s={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(s)throw s.error}}return a}function yo(e,t,n){if(n||2===arguments.length)for(var r,s=0,i=t.length;s1||o(e,t)}))},t&&(r[e]=t(r[e])))}function o(e,t){try{!function(e){e.value instanceof bo?Promise.resolve(e.value.v).then(c,l):u(i[0][2],e)}(s[e](t))}catch(e){u(i[0][3],e)}}function c(e){o("next",e)}function l(e){o("throw",e)}function u(e,t){e(t),i.shift(),i.length&&o(i[0][0],i[0][1])}}function vo(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=mo(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise((function(r,s){(function(e,t,n,r){Promise.resolve(r).then((function(t){e({value:t,done:n})}),t)})(r,s,(t=e[n](t)).done,t.value)}))}}}function _o(e){return"function"==typeof e}function ko(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var So=ko((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function To(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var xo=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,n,r,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=mo(i),o=a.next();!o.done;o=a.next()){o.value.remove(this)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else i.remove(this);var c=this.initialTeardown;if(_o(c))try{c()}catch(e){s=e instanceof So?e.errors:[e]}var l=this._finalizers;if(l){this._finalizers=null;try{for(var u=mo(l),d=u.next();!d.done;d=u.next()){var h=d.value;try{Po(h)}catch(e){s=null!=s?s:[],e instanceof So?s=yo(yo([],go(s)),go(e.errors)):s.push(e)}}}catch(e){n={error:e}}finally{try{d&&!d.done&&(r=u.return)&&r.call(u)}finally{if(n)throw n.error}}}if(s)throw new So(s)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Po(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&To(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&To(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}(),Eo=xo.EMPTY;function Co(e){return e instanceof xo||e&&"closed"in e&&_o(e.remove)&&_o(e.add)&&_o(e.unsubscribe)}function Po(e){_o(e)?e():e.unsubscribe()}var Io=null,Ao=null,Oo=void 0,$o=!1,Mo=!1,Ro={setTimeout:function(e,t){for(var n=[],r=2;r0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,n=this,r=n.hasError,s=n.isStopped,i=n.observers;return r||s?Eo:(this.currentObservers=null,i.push(e),new xo((function(){t.currentObservers=null,To(i,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,n=t.hasError,r=t.thrownError,s=t.isStopped;n?e.error(r):s&&e.complete()},t.prototype.asObservable=function(){var e=new Xo;return e.source=this,e},t.create=function(e,t){return new ic(e,t)},t}(Xo),ic=function(e){function t(t,n){var r=e.call(this)||this;return r.destination=t,r.source=n,r}return ho(t,e),t.prototype.next=function(e){var t,n;null===(n=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===n||n.call(t,e)},t.prototype.error=function(e){var t,n;null===(n=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===n||n.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,n;return null!==(n=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==n?n:Eo},t}(sc),ac={now:function(){return(ac.delegate||Date).now()},delegate:void 0},oc=function(e){function t(t,n,r){void 0===t&&(t=1/0),void 0===n&&(n=1/0),void 0===r&&(r=ac);var s=e.call(this)||this;return s._bufferSize=t,s._windowTime=n,s._timestampProvider=r,s._buffer=[],s._infiniteTimeWindow=!0,s._infiniteTimeWindow=n===1/0,s._bufferSize=Math.max(1,t),s._windowTime=Math.max(1,n),s}return ho(t,e),t.prototype.next=function(t){var n=this,r=n.isStopped,s=n._buffer,i=n._infiniteTimeWindow,a=n._timestampProvider,o=n._windowTime;r||(s.push(t),!i&&s.push(a.now()+o)),this._trimBuffer(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){this._throwIfClosed(),this._trimBuffer();for(var t=this._innerSubscribe(e),n=this._infiniteTimeWindow,r=this._buffer.slice(),s=0;s =2;return function(r){return r.pipe(e?nl((function(t,n){return e(t,n,r)})):Jo,al(1),n?il(t):cl((function(){return new jc})))}}function dl(){for(var e=[],t=0;t 1){let t=null;for(const n of e.reverse())t=null===t?n:new bl(n,t);throw t}}[Symbol.toStringTag]="DisposableStack"}class yl{#t=!1;#n=[];get disposed(){return this.#t}async dispose(){await this[ml]()}use(e){if(e){const t=e[ml],n=e[fl];"function"==typeof t?this.#n.push(e):"function"==typeof n&&this.#n.push({[ml]:async()=>{e[fl]()}})}return e}adopt(e,t){return this.#n.push({[ml]:()=>t(e)}),e}defer(e){this.#n.push({[ml]:()=>e()})}move(){if(this.#t)throw new ReferenceError("A disposed stack can not use anything new");const e=new yl;return e.#n=this.#n,this.#n=[],this.#t=!0,e}async[ml](){if(this.#t)return;this.#t=!0;const e=[];for(const t of this.#n.reverse())try{await t[ml]()}catch(t){e.push(t)}if(1===e.length)throw e[0];if(e.length>1){let t=null;for(const n of e.reverse())t=null===t?n:new bl(n,t);throw t}}[Symbol.toStringTag]="AsyncDisposableStack"}class bl extends Error{#r;#s;constructor(e,t,n="An error was suppressed during disposal"){super(n),this.name="SuppressedError",this.#r=e,this.#s=t}get error(){return this.#r}get suppressed(){return this.#s}}class wl{#i;#a=new Map;constructor(e=function(e){return{all:e=e||new Map,on:function(t,n){var r=e.get(t);r?r.push(n):e.set(t,[n])},off:function(t,n){var r=e.get(t);r&&(n?r.splice(r.indexOf(n)>>>0,1):e.set(t,[]))},emit:function(t,n){var r=e.get(t);r&&r.slice().map((function(e){e(n)})),(r=e.get("*"))&&r.slice().map((function(e){e(t,n)}))}}}(new Map)){this.#i=e}on(e,t){const n=this.#a.get(e);return void 0===n?this.#a.set(e,[t]):n.push(t),this.#i.on(e,t),this}off(e,t){const n=this.#a.get(e)??[];if(void 0===t){for(const t of n)this.#i.off(e,t);return this.#a.delete(e),this}const r=n.lastIndexOf(t);return r>-1&&this.#i.off(e,...n.splice(r,1)),this}emit(e,t){return this.#i.emit(e,t),this.listenerCount(e)>0}once(e,t){const n=r=>{t(r),this.off(e,n)};return this.on(e,n)}listenerCount(e){return this.#a.get(e)?.length||0}removeAllListeners(e){return void 0!==e?this.off(e):(this[fl](),this)}[fl](){for(const[e,t]of this.#a)for(const n of t)this.#i.off(e,n);this.#a.clear()}}const vl=!("undefined"==typeof process||!process.version),_l={value:{get fs(){throw new Error("fs is not available in this environment")},get ScreenRecorder(){throw new Error("ScreenRecorder is not available in this environment")}}};var kl=s(809);const Sl=(e,t)=>{if(!e)throw new Error(t)};function Tl(e,t=!1){return t?"function"==typeof Buffer?Buffer.from(e,"base64"):Uint8Array.from(atob(e),(e=>e.codePointAt(0))):(new TextEncoder).encode(e)}function xl(e){const t=[];for(let n=0;n vl?async(...t)=>{Il&&Pl.push(e+t),(await async function(){return El||(El=(await Promise.resolve().then(s.t.bind(s,7833,19))).default),El}())(e)(t)}:(...t)=>{const n=globalThis.__PUPPETEER_DEBUG;if(!n)return;"*"===n||n.endsWith("*")&&e.startsWith(n)};let Pl=[],Il=!1;class Al extends Error{constructor(e,t){super(e,t),this.name=this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}class Ol extends Al{}class $l extends Al{}class Ml extends Al{#o;#c="";set code(e){this.#o=e}get code(){return this.#o}set originalMessage(e){this.#c=e}get originalMessage(){return this.#c}}class Rl extends Al{}class Nl extends Ml{}const jl={letter:{cm:{width:21.59,height:27.94},in:{width:8.5,height:11}},legal:{cm:{width:21.59,height:35.56},in:{width:8.5,height:14}},tabloid:{cm:{width:27.94,height:43.18},in:{width:11,height:17}},ledger:{cm:{width:43.18,height:27.94},in:{width:17,height:11}},a0:{cm:{width:84.1,height:118.9},in:{width:33.1102,height:46.811}},a1:{cm:{width:59.4,height:84.1},in:{width:23.3858,height:33.1102}},a2:{cm:{width:42,height:59.4},in:{width:16.5354,height:23.3858}},a3:{cm:{width:29.7,height:42},in:{width:11.6929,height:16.5354}},a4:{cm:{width:21,height:29.7},in:{width:8.2677,height:11.6929}},a5:{cm:{width:14.8,height:21},in:{width:5.8268,height:8.2677}},a6:{cm:{width:10.5,height:14.8},in:{width:4.1339,height:5.8268}}},Fl=Cl("puppeteer:error"),Ll=Object.freeze({width:800,height:600}),Dl=Symbol("Source URL for Puppeteer evaluation scripts");class zl{static INTERNAL_URL="pptr:internal";static fromCallSite(e,t){const n=new zl;return n.#l=e,n.#u=t.toString(),n}static parse=e=>{e=e.slice(5);const[t="",n=""]=e.split(";"),r=new zl;return r.#l=t,r.#u=decodeURIComponent(n),r};static isPuppeteerURL=e=>e.startsWith("pptr:");#l;#u;get functionName(){return this.#l}get siteString(){return this.#u}toString(){return`pptr:${[this.#l,encodeURIComponent(this.#u)].join(";")}`}}const Ul=(e,t)=>{if(Object.prototype.hasOwnProperty.call(t,Dl))return t;const n=Error.prepareStackTrace;Error.prepareStackTrace=(e,t)=>t[2];const r=(new Error).stack;return Error.prepareStackTrace=n,Object.assign(t,{[Dl]:zl.fromCallSite(e,r)})},Bl=e=>"string"==typeof e||e instanceof String;function ql(e,...t){if(Bl(e))return Sl(0===t.length,"Cannot evaluate a string with arguments"),e;return`(${e})(${t.map((function(e){return Object.is(e,void 0)?"undefined":JSON.stringify(e)})).join(",")})`}async function Wl(e,t){const n=[],r=e.getReader();if(t){const e=await _l.value.fs.promises.open(t,"w+");try{for(;;){const{done:t,value:s}=await r.read();if(t)break;n.push(s),await e.writeFile(s)}}finally{await e.close()}}else for(;;){const{done:e,value:t}=await r.read();if(e)break;n.push(t)}try{const e=function(e){let t=0;for(const n of e)t+=n.length;const n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return n}(n);return 0===e.length?null:e}catch(e){return Fl(e),null}}async function Hl(e,t){return new ReadableStream({async pull(n){const{data:r,base64Encoded:s,eof:i}=await e.send("IO.read",{handle:t});n.enqueue(Tl(r,s??!1)),i&&(await e.send("IO.close",{handle:t}),n.close())}})}function Kl(e,t){return 0===e?Qc:Zc(e).pipe(Lc((()=>{throw new Ol(`Timed out after waiting ${e}ms`,{cause:t})})))}const Gl="__puppeteer_utility_world__"+kl.T,Vl=/^[\x20\t]*\/\/[@#] sourceURL=\s{0,10}(\S*?)\s{0,10}$/m;const Yl=500;const Jl={px:1,in:96,cm:37.8,mm:3.78};function Zl(e,t="in"){if(void 0===e)return;let n;if((e=>"number"==typeof e||e instanceof Number)(e))n=e;else{if(!Bl(e))throw new Error("page.pdf() Cannot handle parameter type: "+typeof e);{const t=e;let r=t.substring(t.length-2).toLowerCase(),s="";r in Jl?s=t.substring(0,t.length-2):(r="px",s=t);const i=Number(s);Sl(!isNaN(i),"Failed to parse parameter value: "+t),n=i*Jl[r]}}return n/Jl[t]}function Xl(e,t){return new Xo((n=>{const r=e=>{n.next(e)};return e.on(t,r),()=>{e.off(t,r)}}))}function Ql(e,t){return e?Yc(e,"abort").pipe(Lc((()=>{if(e.reason instanceof Error)throw e.reason.cause=t,e.reason;throw new Error(e.reason,{cause:t})}))):Qc}function eu(e){return Bc((t=>Rc(Promise.resolve(e(t))).pipe(nl((e=>e)),Lc((()=>t)))))}const tu=new Map([["accelerometer","sensors"],["ambient-light-sensor","sensors"],["background-sync","backgroundSync"],["camera","videoCapture"],["clipboard-read","clipboardReadWrite"],["clipboard-sanitized-write","clipboardSanitizedWrite"],["clipboard-write","clipboardReadWrite"],["geolocation","geolocation"],["gyroscope","sensors"],["idle-detection","idleDetection"],["keyboard-lock","keyboardLock"],["magnetometer","sensors"],["microphone","audioCapture"],["midi","midi"],["notifications","notifications"],["payment-handler","paymentHandler"],["persistent-storage","durableStorage"],["pointer-lock","pointerLock"],["midi-sysex","midiSysex"]]);class nu extends wl{constructor(){super()}async waitForTarget(e,t={}){const{timeout:n=3e4,signal:r}=t;return await Fc(Xc(Xl(this,"targetcreated"),Xl(this,"targetchanged"),Rc(this.targets())).pipe(eu(e),dl(Ql(r),Kl(n))))}async pages(){const e=await Promise.all(this.browserContexts().map((e=>e.pages())));return e.reduce(((e,t)=>e.concat(t)),[])}async cookies(){return await this.defaultBrowserContext().cookies()}async setCookie(...e){return await this.defaultBrowserContext().setCookie(...e)}async deleteCookie(...e){return await this.defaultBrowserContext().deleteCookie(...e)}isConnected(){return this.connected}[fl](){this.process()?this.close().catch(Fl):this.disconnect().catch(Fl)}[ml](){return this.process()?this.close():this.disconnect()}}class ru{static create(e){return new ru(e)}static async race(e){const t=new Set;try{const n=e.map((e=>e instanceof ru?(e.#d&&t.add(e),e.valueOrThrow()):e));return await Promise.race(n)}finally{for(const e of t)e.reject(new Error("Timeout cleared"))}}#h=!1;#p=!1;#f;#m;#g=new Promise((e=>{this.#m=e}));#d;#y;constructor(e){e&&e.timeout>0&&(this.#y=new Ol(e.message),this.#d=setTimeout((()=>{this.reject(this.#y)}),e.timeout))}#b(e){clearTimeout(this.#d),this.#f=e,this.#m()}resolve(e){this.#p||this.#h||(this.#h=!0,this.#b(e))}reject(e){this.#p||this.#h||(this.#p=!0,this.#b(e))}resolved(){return this.#h}finished(){return this.#h||this.#p}value(){return this.#f}#w;valueOrThrow(){return this.#w||(this.#w=(async()=>{if(await this.#g,this.#p)throw this.#f;return this.#f})()),this.#w}}class su{static Guard=class{#v;#_;constructor(e,t){this.#v=e,this.#_=t}[fl](){return this.#_?.(),this.#v.release()}};#k=!1;#S=[];async acquire(e){if(!this.#k)return this.#k=!0,new su.Guard(this);const t=ru.create();return this.#S.push(t.resolve.bind(t)),await t.valueOrThrow(),new su.Guard(this,e)}release(){const e=this.#S.shift();e?e():this.#k=!1}}class iu extends wl{constructor(){super()}#T;#x=0;startScreenshot(){const e=this.#T||new su;return this.#T=e,this.#x++,e.acquire((()=>{this.#x--,0===this.#x&&(this.#T=void 0)}))}waitForScreenshotOperations(){return this.#T?.acquire()}async waitForTarget(e,t={}){const{timeout:n=3e4}=t;return await Fc(Xc(Xl(this,"targetcreated"),Xl(this,"targetchanged"),Rc(this.targets())).pipe(eu(e),dl(Kl(n))))}async deleteCookie(...e){return await this.setCookie(...e.map((e=>({...e,expires:1}))))}get closed(){return!this.browser().browserContexts().includes(this)}get id(){}[fl](){this.close().catch(Fl)}[ml](){return this.close()}}var au;!function(e){e.Disconnected=Symbol("CDPSession.Disconnected"),e.Swapped=Symbol("CDPSession.Swapped"),e.Ready=Symbol("CDPSession.Ready"),e.SessionAttached="sessionattached",e.SessionDetached="sessiondetached"}(au||(au={}));class ou extends wl{constructor(){super()}parentSession(){}}const cu=Symbol("_isElementHandle");function lu(e){return"object"==typeof e&&null!==e&&"name"in e&&"message"in e}function uu(e,t,n){return e.message=t,e.originalMessage=n??e.originalMessage,e}function du(e){let t=e.error.message;return e.error&&"object"==typeof e.error&&"data"in e.error&&(t+=` ${e.error.data}`),t}const hu=new Map;function pu(e){let t=e.toString();try{new Function(`(${t})`)}catch(e){if(e.message.includes("Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive"))return t;let n="function ";t.startsWith("async ")&&(n=`async ${n}`,t=t.substring(6)),t=`${n}${t}`;try{new Function(`(${t})`)}catch{throw new Error("Passed function cannot be serialized!")}}return t}const fu=(e,t)=>{let n=pu(e);for(const[e,r]of Object.entries(t))n=n.replace(new RegExp(`PLACEHOLDER\\(\\s*(?:'${e}'|"${e}")\\s*\\)`,"g"),`(${r})`);return(e=>{let t=hu.get(e);return t||(t=new Function(`return ${e}`)(),hu.set(e,t),t)})(n)};var mu=function(e,t,n){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var r,s;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],n&&(s=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");s&&(r=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},gu=function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,"An error was suppressed during disposal."):n,t.hasError=!0}var r,s=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===s)return s=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var i=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(i).then(e,(function(t){return n(t),e()}))}else s|=1}catch(e){n(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,n){var r=new Error(n);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});async function*yu(e,t){const n={stack:[],error:void 0,hasError:!1};try{const r=mu(n,await e.evaluateHandle((async(e,t)=>{const n=[];for(;n.length {for(const e of i){const t={stack:[],error:void 0,hasError:!1};try{mu(t,e,!1)[fl]()}catch(e){t.error=e,t.hasError=!0}finally{gu(t)}}})),yield*i,0===s.size}catch(e){n.error=e,n.hasError=!0}finally{gu(n)}}async function*bu(e){const t={stack:[],error:void 0,hasError:!1};try{const n=mu(t,await e.evaluateHandle((e=>async function*(){yield*e}())),!1);yield*async function*(e){let t=20;for(;!(yield*yu(e,t));)t<<=1}(n)}catch(e){t.error=e,t.hasError=!0}finally{gu(t)}}class wu{static create=e=>new wu(e);#E;constructor(e){this.#E=e}async get(e){return await this.#E(e)}}var vu=function(e,t,n){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var r,s;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],n&&(s=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");s&&(r=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},_u=function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,"An error was suppressed during disposal."):n,t.hasError=!0}var r,s=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===s)return s=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var i=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(i).then(e,(function(t){return n(t),e()}))}else s|=1}catch(e){n(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,n){var r=new Error(n);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});class ku{static querySelectorAll;static querySelector;static get _querySelector(){if(this.querySelector)return this.querySelector;if(!this.querySelectorAll)throw new Error("Cannot create default `querySelector`.");return this.querySelector=fu((async(e,t,n)=>{const r=PLACEHOLDER("querySelectorAll")(e,t,n);for await(const e of r)return e;return null}),{querySelectorAll:pu(this.querySelectorAll)})}static get _querySelectorAll(){if(this.querySelectorAll)return this.querySelectorAll;if(!this.querySelector)throw new Error("Cannot create default `querySelectorAll`.");return this.querySelectorAll=fu((async function*(e,t,n){const r=PLACEHOLDER("querySelector"),s=await r(e,t,n);s&&(yield s)}),{querySelector:pu(this.querySelector)})}static async*queryAll(e,t){const n={stack:[],error:void 0,hasError:!1};try{const r=vu(n,await e.evaluateHandle(this._querySelectorAll,t,wu.create((e=>e.puppeteerUtil))),!1);yield*bu(r)}catch(e){n.error=e,n.hasError=!0}finally{_u(n)}}static async queryOne(e,t){const n={stack:[],error:void 0,hasError:!1};try{const r=vu(n,await e.evaluateHandle(this._querySelector,t,wu.create((e=>e.puppeteerUtil))),!1);return cu in r?r.move():null}catch(e){n.error=e,n.hasError=!0}finally{_u(n)}}static async waitFor(e,t,n){const r={stack:[],error:void 0,hasError:!1};try{let s;const i=vu(r,await(async()=>{if(cu in e)return s=e.frame,await s.isolatedRealm().adoptHandle(e);s=e})(),!1),{visible:a=!1,hidden:o=!1,timeout:c,signal:l}=n,u=a||o?"raf":n.polling;try{const e={stack:[],error:void 0,hasError:!1};try{l?.throwIfAborted();const n=vu(e,await s.isolatedRealm().waitForFunction((async(e,t,n,r,s)=>{const i=e.createFunction(t),a=await i(r??document,n,e);return e.checkVisibility(a,s)}),{polling:u,root:i,timeout:c,signal:l},wu.create((e=>e.puppeteerUtil)),pu(this._querySelector),t,i,!!a||!o&&void 0),!1);if(l?.aborted)throw l.reason;return cu in n?await s.mainRealm().transferHandle(n):null}catch(t){e.error=t,e.hasError=!0}finally{_u(e)}}catch(e){if(!lu(e))throw e;if("AbortError"===e.name)throw e;throw e.message=`Waiting for selector \`${t}\` failed: ${e.message}`,e}}catch(e){r.error=e,r.hasError=!0}finally{_u(r)}}}class Su{static async*map(e,t){for await(const n of e)yield await t(n)}static async*flatMap(e,t){for await(const n of e)yield*t(n)}static async collect(e){const t=[];for await(const n of e)t.push(n);return t}static async first(e){for await(const t of e)return t}}const Tu=/\[\s*(? \w+)\s*=\s*(? "|')(?\\.|.*?(?=\k ))\k\s*\]/g;class xu extends ku{static querySelector=async(e,t,{ariaQuerySelector:n})=>await n(e,t);static async*queryAll(e,t){const{name:n,role:r}=(e=>{if(e.length>1e4)throw new Error(`Selector ${e} is too long`);const t={},n=e.replace(Tu,((e,n,r,s)=>(Sl((e=>["name","role"].includes(e))(n),`Unknown aria attribute "${n}" in selector`),t[n]=s,"")));return n&&!t.name&&(t.name=n),t})(t);yield*e.queryAXTree(n,r)}static queryOne=async(e,t)=>await Su.first(this.queryAll(e,t))??null}class Eu extends ku{static querySelector=(e,t,{cssQuerySelector:n})=>n(e,t);static querySelectorAll=(e,t,{cssQuerySelectorAll:n})=>n(e,t)}const Cu=new class{#C=!1;#P=new Set;append(e){this.#I((()=>{this.#P.add(e)}))}pop(e){this.#I((()=>{this.#P.delete(e)}))}inject(e,t=!1){(this.#C||t)&&e(this.#E()),this.#C=!1}#I(e){e(),this.#C=!0}#E(){return`(() => {\n const module = {};\n "use strict";var g=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var l=(t,e)=>{for(var r in e)g(t,r,{get:e[r],enumerable:!0})},J=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of B(e))!Y.call(t,n)&&n!==r&&g(t,n,{get:()=>e[n],enumerable:!(o=X(e,n))||o.enumerable});return t};var z=t=>J(g({},"__esModule",{value:!0}),t);var pe={};l(pe,{default:()=>he});module.exports=z(pe);var N=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}},p=class extends N{};var c=class t{static create(e){return new t(e)}static async race(e){let r=new Set;try{let o=e.map(n=>n instanceof t?(n.#n&&r.add(n),n.valueOrThrow()):n);return await Promise.race(o)}finally{for(let o of r)o.reject(new Error("Timeout cleared"))}}#e=!1;#r=!1;#o;#t;#a=new Promise(e=>{this.#t=e});#n;#i;constructor(e){e&&e.timeout>0&&(this.#i=new p(e.message),this.#n=setTimeout(()=>{this.reject(this.#i)},e.timeout))}#l(e){clearTimeout(this.#n),this.#o=e,this.#t()}resolve(e){this.#r||this.#e||(this.#e=!0,this.#l(e))}reject(e){this.#r||this.#e||(this.#r=!0,this.#l(e))}resolved(){return this.#e}finished(){return this.#e||this.#r}value(){return this.#o}#s;valueOrThrow(){return this.#s||(this.#s=(async()=>{if(await this.#a,this.#r)throw this.#o;return this.#o})()),this.#s}};var L=new Map,F=t=>{let e=L.get(t);return e||(e=new Function(\`return \${t}\`)(),L.set(t,e),e)};var x={};l(x,{ariaQuerySelector:()=>G,ariaQuerySelectorAll:()=>b});var G=(t,e)=>globalThis.__ariaQuerySelector(t,e),b=async function*(t,e){yield*await globalThis.__ariaQuerySelectorAll(t,e)};var E={};l(E,{cssQuerySelector:()=>K,cssQuerySelectorAll:()=>Z});var K=(t,e)=>t.querySelector(e),Z=function(t,e){return t.querySelectorAll(e)};var A={};l(A,{customQuerySelectors:()=>P});var v=class{#e=new Map;register(e,r){if(!r.queryOne&&r.queryAll){let o=r.queryAll;r.queryOne=(n,i)=>{for(let s of o(n,i))return s;return null}}else if(r.queryOne&&!r.queryAll){let o=r.queryOne;r.queryAll=(n,i)=>{let s=o(n,i);return s?[s]:[]}}else if(!r.queryOne||!r.queryAll)throw new Error("At least one query method must be defined.");this.#e.set(e,{querySelector:r.queryOne,querySelectorAll:r.queryAll})}unregister(e){this.#e.delete(e)}get(e){return this.#e.get(e)}clear(){this.#e.clear()}},P=new v;var R={};l(R,{pierceQuerySelector:()=>ee,pierceQuerySelectorAll:()=>te});var ee=(t,e)=>{let r=null,o=n=>{let i=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT);do{let s=i.currentNode;s.shadowRoot&&o(s.shadowRoot),!(s instanceof ShadowRoot)&&s!==n&&!r&&s.matches(e)&&(r=s)}while(!r&&i.nextNode())};return t instanceof Document&&(t=t.documentElement),o(t),r},te=(t,e)=>{let r=[],o=n=>{let i=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT);do{let s=i.currentNode;s.shadowRoot&&o(s.shadowRoot),!(s instanceof ShadowRoot)&&s!==n&&s.matches(e)&&r.push(s)}while(i.nextNode())};return t instanceof Document&&(t=t.documentElement),o(t),r};var u=(t,e)=>{if(!t)throw new Error(e)};var y=class{#e;#r;#o;#t;constructor(e,r){this.#e=e,this.#r=r}async start(){let e=this.#t=c.create(),r=await this.#e();if(r){e.resolve(r);return}this.#o=new MutationObserver(async()=>{let o=await this.#e();o&&(e.resolve(o),await this.stop())}),this.#o.observe(this.#r,{childList:!0,subtree:!0,attributes:!0})}async stop(){u(this.#t,"Polling never started."),this.#t.finished()||this.#t.reject(new Error("Polling stopped")),this.#o&&(this.#o.disconnect(),this.#o=void 0)}result(){return u(this.#t,"Polling never started."),this.#t.valueOrThrow()}},w=class{#e;#r;constructor(e){this.#e=e}async start(){let e=this.#r=c.create(),r=await this.#e();if(r){e.resolve(r);return}let o=async()=>{if(e.finished())return;let n=await this.#e();if(!n){window.requestAnimationFrame(o);return}e.resolve(n),await this.stop()};window.requestAnimationFrame(o)}async stop(){u(this.#r,"Polling never started."),this.#r.finished()||this.#r.reject(new Error("Polling stopped"))}result(){return u(this.#r,"Polling never started."),this.#r.valueOrThrow()}},S=class{#e;#r;#o;#t;constructor(e,r){this.#e=e,this.#r=r}async start(){let e=this.#t=c.create(),r=await this.#e();if(r){e.resolve(r);return}this.#o=setInterval(async()=>{let o=await this.#e();o&&(e.resolve(o),await this.stop())},this.#r)}async stop(){u(this.#t,"Polling never started."),this.#t.finished()||this.#t.reject(new Error("Polling stopped")),this.#o&&(clearInterval(this.#o),this.#o=void 0)}result(){return u(this.#t,"Polling never started."),this.#t.valueOrThrow()}};var _={};l(_,{PCombinator:()=>H,pQuerySelector:()=>fe,pQuerySelectorAll:()=>$});var a=class{static async*map(e,r){for await(let o of e)yield await r(o)}static async*flatMap(e,r){for await(let o of e)yield*r(o)}static async collect(e){let r=[];for await(let o of e)r.push(o);return r}static async first(e){for await(let r of e)return r}};var C={};l(C,{textQuerySelectorAll:()=>m});var re=new Set(["checkbox","image","radio"]),oe=t=>t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLInputElement&&!re.has(t.type),ne=new Set(["SCRIPT","STYLE"]),f=t=>!ne.has(t.nodeName)&&!document.head?.contains(t),I=new WeakMap,j=t=>{for(;t;)I.delete(t),t instanceof ShadowRoot?t=t.host:t=t.parentNode},W=new WeakSet,se=new MutationObserver(t=>{for(let e of t)j(e.target)}),d=t=>{let e=I.get(t);if(e||(e={full:"",immediate:[]},!f(t)))return e;let r="";if(oe(t))e.full=t.value,e.immediate.push(t.value),t.addEventListener("input",o=>{j(o.target)},{once:!0,capture:!0});else{for(let o=t.firstChild;o;o=o.nextSibling){if(o.nodeType===Node.TEXT_NODE){e.full+=o.nodeValue??"",r+=o.nodeValue??"";continue}r&&e.immediate.push(r),r="",o.nodeType===Node.ELEMENT_NODE&&(e.full+=d(o).full)}r&&e.immediate.push(r),t instanceof Element&&t.shadowRoot&&(e.full+=d(t.shadowRoot).full),W.has(t)||(se.observe(t,{childList:!0,characterData:!0,subtree:!0}),W.add(t))}return I.set(t,e),e};var m=function*(t,e){let r=!1;for(let o of t.childNodes)if(o instanceof Element&&f(o)){let n;o.shadowRoot?n=m(o.shadowRoot,e):n=m(o,e);for(let i of n)yield i,r=!0}r||t instanceof Element&&f(t)&&d(t).full.includes(e)&&(yield t)};var k={};l(k,{checkVisibility:()=>le,pierce:()=>T,pierceAll:()=>O});var ie=["hidden","collapse"],le=(t,e)=>{if(!t)return e===!1;if(e===void 0)return t;let r=t.nodeType===Node.TEXT_NODE?t.parentElement:t,o=window.getComputedStyle(r),n=o&&!ie.includes(o.visibility)&&!ae(r);return e===n?t:!1};function ae(t){let e=t.getBoundingClientRect();return e.width===0||e.height===0}var ce=t=>"shadowRoot"in t&&t.shadowRoot instanceof ShadowRoot;function*T(t){ce(t)?yield t.shadowRoot:yield t}function*O(t){t=T(t).next().value,yield t;let e=[document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT)];for(let r of e){let o;for(;o=r.nextNode();)o.shadowRoot&&(yield o.shadowRoot,e.push(document.createTreeWalker(o.shadowRoot,NodeFilter.SHOW_ELEMENT)))}}var Q={};l(Q,{xpathQuerySelectorAll:()=>q});var q=function*(t,e,r=-1){let n=(t.ownerDocument||document).evaluate(e,t,null,XPathResult.ORDERED_NODE_ITERATOR_TYPE),i=[],s;for(;(s=n.iterateNext())&&(i.push(s),!(r&&i.length===r)););for(let h=0;h(r.Descendent=">>>",r.Child=">>>>",r))(H||{}),V=t=>"querySelectorAll"in t,M=class{#e;#r=[];#o=void 0;elements;constructor(e,r){this.elements=[e],this.#e=r,this.#t()}async run(){if(typeof this.#o=="string")switch(this.#o.trimStart()){case":scope":this.#t();break}for(;this.#o!==void 0;this.#t()){let e=this.#o;typeof e=="string"?e[0]&&ue.test(e[0])?this.elements=a.flatMap(this.elements,async function*(r){V(r)&&(yield*r.querySelectorAll(e))}):this.elements=a.flatMap(this.elements,async function*(r){if(!r.parentElement){if(!V(r))return;yield*r.querySelectorAll(e);return}let o=0;for(let n of r.parentElement.children)if(++o,n===r)break;yield*r.parentElement.querySelectorAll(\`:scope>:nth-child(\${o})\${e}\`)}):this.elements=a.flatMap(this.elements,async function*(r){switch(e.name){case"text":yield*m(r,e.value);break;case"xpath":yield*q(r,e.value);break;case"aria":yield*b(r,e.value);break;default:let o=P.get(e.name);if(!o)throw new Error(\`Unknown selector type: \${e.name}\`);yield*o.querySelectorAll(r,e.value)}})}}#t(){if(this.#r.length!==0){this.#o=this.#r.shift();return}if(this.#e.length===0){this.#o=void 0;return}let e=this.#e.shift();switch(e){case">>>>":{this.elements=a.flatMap(this.elements,T),this.#t();break}case">>>":{this.elements=a.flatMap(this.elements,O),this.#t();break}default:this.#r=e,this.#t();break}}},D=class{#e=new WeakMap;calculate(e,r=[]){if(e===null)return r;e instanceof ShadowRoot&&(e=e.host);let o=this.#e.get(e);if(o)return[...o,...r];let n=0;for(let s=e.previousSibling;s;s=s.previousSibling)++n;let i=this.calculate(e.parentNode,[n]);return this.#e.set(e,i),[...i,...r]}},U=(t,e)=>{if(t.length+e.length===0)return 0;let[r=-1,...o]=t,[n=-1,...i]=e;return r===n?U(o,i):r [o,r.calculate(o)]).sort(([,o],[,n])=>U(o,n)).map(([o])=>o)},$=function(t,e){let r=JSON.parse(e);if(r.some(o=>{let n=0;return o.some(i=>(typeof i=="string"?++n:n=0,n>1))}))throw new Error("Multiple deep combinators found in sequence.");return de(a.flatMap(r,o=>{let n=new M(t,o);return n.run(),n.elements}))},fe=async function(t,e){for await(let r of $(t,e))return r;return null};var me=Object.freeze({...x,...A,...R,..._,...C,...k,...Q,...E,Deferred:c,createFunction:F,createTextContent:d,IntervalPoller:S,isSuitableNodeForTextMatching:f,MutationPoller:y,RAFPoller:w}),he=me;\n\n ${[...this.#P].map((e=>`(${e})(module.exports.default);`)).join("")}\n return module.exports.default;\n })()`}};const Pu=new class{#a=new Map;get(e){const t=this.#a.get(e);return t?t[1]:void 0}register(e,t){Sl(!this.#a.has(e),`Cannot register over existing handler: ${e}`),Sl(/^[a-zA-Z]+$/.test(e),"Custom query handler names may only contain [a-zA-Z]"),Sl(t.queryAll||t.queryOne,"At least one query method must be implemented.");const n=class extends ku{static querySelectorAll=fu(((e,t,n)=>n.customQuerySelectors.get(PLACEHOLDER("name")).querySelectorAll(e,t)),{name:JSON.stringify(e)});static querySelector=fu(((e,t,n)=>n.customQuerySelectors.get(PLACEHOLDER("name")).querySelector(e,t)),{name:JSON.stringify(e)})},r=fu((e=>{e.customQuerySelectors.register(PLACEHOLDER("name"),{queryAll:PLACEHOLDER("queryAll"),queryOne:PLACEHOLDER("queryOne")})}),{name:JSON.stringify(e),queryAll:t.queryAll?pu(t.queryAll):String(void 0),queryOne:t.queryOne?pu(t.queryOne):String(void 0)}).toString();this.#a.set(e,[r,n]),Cu.append(r)}unregister(e){const t=this.#a.get(e);if(!t)throw new Error(`Cannot unregister unknown handler: ${e}`);Cu.pop(t[0]),this.#a.delete(e)}names(){return[...this.#a.keys()]}clear(){for(const[e]of this.#a)Cu.pop(e);this.#a.clear()}};class Iu extends ku{static querySelectorAll=(e,t,{pQuerySelectorAll:n})=>n(e,t);static querySelector=(e,t,{pQuerySelector:n})=>n(e,t)}var Au={attribute:/\[\s*(?:(? \*|[-\w\P{ASCII}]*)\|)?(? [-\w\P{ASCII}]+)\s*(?:(? \W?=)\s*(? .+?)\s*(\s(? [iIsS]))?\s*)?\]/gu,id:/#(? [-\w\P{ASCII}]+)/gu,class:/\.(? [-\w\P{ASCII}]+)/gu,comma:/\s*,\s*/g,combinator:/\s*[\s>+~]\s*/g,"pseudo-element":/::(? [-\w\P{ASCII}]+)(?:\((? ยถ*)\))?/gu,"pseudo-class":/:(? [-\w\P{ASCII}]+)(?:\((? ยถ*)\))?/gu,universal:/(?:(? \*|[-\w\P{ASCII}]*)\|)?\*/gu,type:/(?:(? \*|[-\w\P{ASCII}]*)\|)?(? [-\w\P{ASCII}]+)/gu},Ou=new Set(["combinator","comma"]),$u=e=>{switch(e){case"pseudo-element":case"pseudo-class":return new RegExp(Au[e].source.replace("(? ยถ*)","(? .*)"),"gu");default:return Au[e]}};function Mu(e,t){let n=0,r="";for(;t (n.push({value:e,offset:t}),"๎".repeat(e.length)))),e=e.replace(Ru,((e,t,r,s)=>(n.push({value:e,offset:s}),`${t}${"๎".repeat(r.length)}${t}`)));{let t,r=0;for(;(t=e.indexOf("(",r))>-1;){const s=Mu(e,t);n.push({value:s,offset:t}),e=`${e.substring(0,t)}(${"ยถ".repeat(s.length-2)})${e.substring(t+s.length)}`,r=t+s.length}}const r=function(e,t=Au){if(!e)return[];const n=[e];for(const[e,r]of Object.entries(t))for(let t=0;t e.content)).join("");switch(e.type){case"list":return e.list.map(Fu).join(",");case"relative":return e.combinator+Fu(e.right);case"complex":return Fu(e.left)+e.combinator+Fu(e.right);case"compound":return e.list.map(Fu).join("");default:return e.content}}Au.nesting=/&/g,Au.combinator=/\s*(>>>>?|[\s>+~])\s*/g;const Lu=/\\[\s\S]/g;const Du={aria:xu,pierce:class extends ku{static querySelector=(e,t,{pierceQuerySelector:n})=>n(e,t);static querySelectorAll=(e,t,{pierceQuerySelectorAll:n})=>n(e,t)},xpath:class extends ku{static querySelectorAll=(e,t,{xpathQuerySelectorAll:n})=>n(e,t);static querySelector=(e,t,{xpathQuerySelectorAll:n})=>{for(const r of n(e,t,1))return r;return null}},text:class extends ku{static querySelectorAll=(e,t,{textQuerySelectorAll:n})=>n(e,t)}},zu=["=","/"];function Uu(e){for(const t of[Pu.names().map((e=>[e,Pu.get(e)])),Object.entries(Du)])for(const[n,r]of t)for(const t of zu){const s=`${n}${t}`;if(e.startsWith(s))return{updatedSelector:e=e.slice(s.length),polling:"aria"===n?"raf":"mutation",QueryHandler:r}}try{const[t,n,r,s]=function(e){let t=!0,n=!1,r=!1;const s=ju(e);if(0===s.length)return[[],t,r,!1];let i=[],a=[i];const o=[a],c=[];for(const e of s){switch(e.type){case"combinator":switch(e.content){case">>>":t=!1,c.length&&(i.push(Fu(c)),c.splice(0)),i=[],a.push(">>>"),a.push(i);continue;case">>>>":t=!1,c.length&&(i.push(Fu(c)),c.splice(0)),i=[],a.push(">>>>"),a.push(i);continue}break;case"pseudo-element":if(!e.name.startsWith("-p-"))break;t=!1,c.length&&(i.push(Fu(c)),c.splice(0));const s=e.name.slice(3);"aria"===s&&(n=!0),i.push({name:s,value:(l=e.argument??"",l.length<=1?l:('"'!==l[0]&&"'"!==l[0]||!l.endsWith(l[0])||(l=l.slice(1,-1)),l.replace(Lu,(e=>e[1]))))});continue;case"pseudo-class":r=!0;break;case"comma":c.length&&(i.push(Fu(c)),c.splice(0)),i=[],a=[i],o.push(a);continue}c.push(e)}var l;return c.length&&i.push(Fu(c)),[o,t,r,n]}(e);return n?{updatedSelector:e,polling:r?"raf":"mutation",QueryHandler:Eu}:{updatedSelector:JSON.stringify(t),polling:s?"raf":"mutation",QueryHandler:Iu}}catch{return{updatedSelector:e,polling:"mutation",QueryHandler:Eu}}}var Bu=function(e,t,n){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var r,s;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],n&&(s=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");s&&(r=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},qu=function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,"An error was suppressed during disposal."):n,t.hasError=!0}var r,s=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===s)return s=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var i=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(i).then(e,(function(t){return n(t),e()}))}else s|=1}catch(e){n(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,n){var r=new Error(n);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});const Wu=new WeakSet;function Hu(e,t){let n=!1;if(e.prototype[fl]){const t=e.prototype[fl];e.prototype[fl]=function(){if(!Wu.has(this))return t.call(this);Wu.delete(this)},n=!0}if(e.prototype[ml]){const t=e.prototype[ml];e.prototype[ml]=function(){if(!Wu.has(this))return t.call(this);Wu.delete(this)},n=!0}return n&&(e.prototype.move=function(){return Wu.add(this),this}),e}function Ku(e=e=>`Attempted to use disposed ${e.constructor.name}.`){return(t,n)=>function(...n){if(this.disposed)throw new Error(e(this));return t.call(this,...n)}}function Gu(e,t){const n=new WeakMap;let r=-1;return function(...t){if(-1===r&&(r=t.length),r!==t.length)throw new Error("Memoized method was called with the wrong number of arguments");let s=!1,i=n;for(const e of t)i.has(e)||(s=!0,i.set(e,new WeakMap)),i=i.get(e);if(s)return e.call(this,...t)}}function Vu(e=function(){return this}){return(t,n)=>{const r=new WeakMap;return async function(...n){const s={stack:[],error:void 0,hasError:!1};try{const i=e.call(this);let a=r.get(i);a||(a=new su,r.set(i,a));Bu(s,await a.acquire(),!0);return await t.call(this,...n)}catch(e){s.error=e,s.hasError=!0}finally{const e=qu(s);e&&await e}}}}new WeakMap;var Yu=function(e,t,n){for(var r=arguments.length>2,s=0;s =0;p--){var f={};for(var m in r)f[m]="access"===m?{}:r[m];for(var m in r.access)f.access[m]=r.access[m];f.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");i.push(a(e||null))};var g=(0,n[p])("accessor"===c?{get:d.get,set:d.set}:d[l],f);if("accessor"===c){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(o=a(g.get))&&(d.get=o),(o=a(g.set))&&(d.set=o),(o=a(g.init))&&s.unshift(o)}else(o=a(g))&&("field"===c?s.unshift(o):d[l]=o)}u&&Object.defineProperty(u,r.name,d),h=!0},Zu=function(e,t,n){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var r,s;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],n&&(s=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");s&&(r=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},Xu=function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,"An error was suppressed during disposal."):n,t.hasError=!0}var r,s=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===s)return s=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var i=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(i).then(e,(function(t){return n(t),e()}))}else s|=1}catch(e){n(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,n){var r=new Error(n);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});let Qu=(()=>{let e,t,n,r,s=[Hu],i=[],a=[];(class{static{t=this}static{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ju(this,null,n,{kind:"method",name:"getProperty",static:!1,private:!1,access:{has:e=>"getProperty"in e,get:e=>e.getProperty},metadata:o},null,a),Ju(this,null,r,{kind:"method",name:"getProperties",static:!1,private:!1,access:{has:e=>"getProperties"in e,get:e=>e.getProperties},metadata:o},null,a),Ju(null,e={value:t},s,{kind:"class",name:t.name,metadata:o},null,i),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),Yu(t,i)}constructor(){Yu(this,a)}async evaluate(e,...t){return e=Ul(this.evaluate.name,e),await this.realm.evaluate(e,this,...t)}async evaluateHandle(e,...t){return e=Ul(this.evaluateHandle.name,e),await this.realm.evaluateHandle(e,this,...t)}async getProperty(e){return await this.evaluateHandle(((e,t)=>e[t]),e)}async getProperties(){const e=await this.evaluate((e=>{const t=[],n=Object.getOwnPropertyDescriptors(e);for(const e in n)n[e]?.enumerable&&t.push(e);return t})),t=new Map,n=await Promise.all(e.map((e=>this.getProperty(e))));for(const[r,s]of Object.entries(e)){const e={stack:[],error:void 0,hasError:!1};try{const i=Zu(e,n[r],!1);i&&t.set(s,i.move())}catch(t){e.error=t,e.hasError=!0}finally{Xu(e)}}return t}[(n=[Ku()],r=[Ku()],fl)](){this.dispose().catch(Fl)}[ml](){return this.dispose()}});return t})();var ed=function(e,t,n){for(var r=arguments.length>2,s=0;s =0;p--){var f={};for(var m in r)f[m]="access"===m?{}:r[m];for(var m in r.access)f.access[m]=r.access[m];f.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");i.push(a(e||null))};var g=(0,n[p])("accessor"===c?{get:d.get,set:d.set}:d[l],f);if("accessor"===c){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(o=a(g.get))&&(d.get=o),(o=a(g.set))&&(d.set=o),(o=a(g.init))&&s.unshift(o)}else(o=a(g))&&("field"===c?s.unshift(o):d[l]=o)}u&&Object.defineProperty(u,r.name,d),h=!0},nd=function(e,t,n){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var r,s;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],n&&(s=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");s&&(r=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},rd=function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,"An error was suppressed during disposal."):n,t.hasError=!0}var r,s=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===s)return s=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var i=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(i).then(e,(function(t){return n(t),e()}))}else s|=1}catch(e){n(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,n){var r=new Error(n);return r.name="SuppressedError",r.error=e,r.suppressed=t,r}),sd=function(e,t,n){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:n?"".concat(n," ",t):t})};function id(e,t){return async function(...t){if(this.realm===this.frame.isolatedRealm())return await e.call(this,...t);let n;this.isolatedHandle?n=this.isolatedHandle:this.isolatedHandle=n=await this.frame.isolatedRealm().adoptHandle(this);const r=await e.call(n,...t);return r===n?this:r instanceof Qu?await this.realm.transferHandle(r):(Array.isArray(r)&&await Promise.all(r.map((async(e,t,n)=>{e instanceof Qu&&(n[t]=await this.realm.transferHandle(e))}))),r instanceof Map&&await Promise.all([...r.entries()].map((async([e,t])=>{t instanceof Qu&&r.set(e,await this.realm.transferHandle(t))}))),r)}}let ad=(()=>{let e,t,n,r,s,i,a,o,c,l,u,d,h,p,f,m,g,y,b,w,v,_,k,S,T,x,E,C,P,I,A,O,$=Qu,M=[];return class R extends ${static{const R="function"==typeof Symbol&&Symbol.metadata?Object.create($[Symbol.metadata]??null):void 0;e=[Ku(),id],t=[Ku(),id],n=[Ku(),id],r=[Ku(),id],s=[Ku()],i=[id],o=[Ku(),id],c=[Ku(),id],l=[Ku(),id],u=[Ku(),id],d=[Ku(),id],h=[Ku(),id],p=[Ku(),id],f=[Ku(),id],m=[Ku(),id],g=[Ku(),id],y=[Ku(),id],b=[Ku(),id],w=[Ku(),id],v=[Ku(),id],_=[Ku(),id],k=[Ku(),id],S=[Ku(),id],T=[Ku(),id],x=[Ku(),id],E=[Ku(),id],C=[Ku(),id],P=[Ku(),id],I=[Ku(),id],A=[Ku(),id],O=[Ku(),id],td(this,null,e,{kind:"method",name:"getProperty",static:!1,private:!1,access:{has:e=>"getProperty"in e,get:e=>e.getProperty},metadata:R},null,M),td(this,null,t,{kind:"method",name:"getProperties",static:!1,private:!1,access:{has:e=>"getProperties"in e,get:e=>e.getProperties},metadata:R},null,M),td(this,null,n,{kind:"method",name:"jsonValue",static:!1,private:!1,access:{has:e=>"jsonValue"in e,get:e=>e.jsonValue},metadata:R},null,M),td(this,null,r,{kind:"method",name:"$",static:!1,private:!1,access:{has:e=>"$"in e,get:e=>e.$},metadata:R},null,M),td(this,null,s,{kind:"method",name:"$$",static:!1,private:!1,access:{has:e=>"$$"in e,get:e=>e.$$},metadata:R},null,M),td(this,a={value:sd((async function(e){return await this.#A(e)}),"#$$")},i,{kind:"method",name:"#$$",static:!1,private:!0,access:{has:e=>#O in e,get:e=>e.#O},metadata:R},null,M),td(this,null,o,{kind:"method",name:"waitForSelector",static:!1,private:!1,access:{has:e=>"waitForSelector"in e,get:e=>e.waitForSelector},metadata:R},null,M),td(this,null,c,{kind:"method",name:"isVisible",static:!1,private:!1,access:{has:e=>"isVisible"in e,get:e=>e.isVisible},metadata:R},null,M),td(this,null,l,{kind:"method",name:"isHidden",static:!1,private:!1,access:{has:e=>"isHidden"in e,get:e=>e.isHidden},metadata:R},null,M),td(this,null,u,{kind:"method",name:"toElement",static:!1,private:!1,access:{has:e=>"toElement"in e,get:e=>e.toElement},metadata:R},null,M),td(this,null,d,{kind:"method",name:"clickablePoint",static:!1,private:!1,access:{has:e=>"clickablePoint"in e,get:e=>e.clickablePoint},metadata:R},null,M),td(this,null,h,{kind:"method",name:"hover",static:!1,private:!1,access:{has:e=>"hover"in e,get:e=>e.hover},metadata:R},null,M),td(this,null,p,{kind:"method",name:"click",static:!1,private:!1,access:{has:e=>"click"in e,get:e=>e.click},metadata:R},null,M),td(this,null,f,{kind:"method",name:"drag",static:!1,private:!1,access:{has:e=>"drag"in e,get:e=>e.drag},metadata:R},null,M),td(this,null,m,{kind:"method",name:"dragEnter",static:!1,private:!1,access:{has:e=>"dragEnter"in e,get:e=>e.dragEnter},metadata:R},null,M),td(this,null,g,{kind:"method",name:"dragOver",static:!1,private:!1,access:{has:e=>"dragOver"in e,get:e=>e.dragOver},metadata:R},null,M),td(this,null,y,{kind:"method",name:"drop",static:!1,private:!1,access:{has:e=>"drop"in e,get:e=>e.drop},metadata:R},null,M),td(this,null,b,{kind:"method",name:"dragAndDrop",static:!1,private:!1,access:{has:e=>"dragAndDrop"in e,get:e=>e.dragAndDrop},metadata:R},null,M),td(this,null,w,{kind:"method",name:"select",static:!1,private:!1,access:{has:e=>"select"in e,get:e=>e.select},metadata:R},null,M),td(this,null,v,{kind:"method",name:"tap",static:!1,private:!1,access:{has:e=>"tap"in e,get:e=>e.tap},metadata:R},null,M),td(this,null,_,{kind:"method",name:"touchStart",static:!1,private:!1,access:{has:e=>"touchStart"in e,get:e=>e.touchStart},metadata:R},null,M),td(this,null,k,{kind:"method",name:"touchMove",static:!1,private:!1,access:{has:e=>"touchMove"in e,get:e=>e.touchMove},metadata:R},null,M),td(this,null,S,{kind:"method",name:"touchEnd",static:!1,private:!1,access:{has:e=>"touchEnd"in e,get:e=>e.touchEnd},metadata:R},null,M),td(this,null,T,{kind:"method",name:"focus",static:!1,private:!1,access:{has:e=>"focus"in e,get:e=>e.focus},metadata:R},null,M),td(this,null,x,{kind:"method",name:"type",static:!1,private:!1,access:{has:e=>"type"in e,get:e=>e.type},metadata:R},null,M),td(this,null,E,{kind:"method",name:"press",static:!1,private:!1,access:{has:e=>"press"in e,get:e=>e.press},metadata:R},null,M),td(this,null,C,{kind:"method",name:"boundingBox",static:!1,private:!1,access:{has:e=>"boundingBox"in e,get:e=>e.boundingBox},metadata:R},null,M),td(this,null,P,{kind:"method",name:"boxModel",static:!1,private:!1,access:{has:e=>"boxModel"in e,get:e=>e.boxModel},metadata:R},null,M),td(this,null,I,{kind:"method",name:"screenshot",static:!1,private:!1,access:{has:e=>"screenshot"in e,get:e=>e.screenshot},metadata:R},null,M),td(this,null,A,{kind:"method",name:"isIntersectingViewport",static:!1,private:!1,access:{has:e=>"isIntersectingViewport"in e,get:e=>e.isIntersectingViewport},metadata:R},null,M),td(this,null,O,{kind:"method",name:"scrollIntoView",static:!1,private:!1,access:{has:e=>"scrollIntoView"in e,get:e=>e.scrollIntoView},metadata:R},null,M),R&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:R})}isolatedHandle=ed(this,M);handle;constructor(e){super(),this.handle=e,this[cu]=!0}get id(){return this.handle.id}get disposed(){return this.handle.disposed}async getProperty(e){return await this.handle.getProperty(e)}async getProperties(){return await this.handle.getProperties()}async evaluate(e,...t){return e=Ul(this.evaluate.name,e),await this.handle.evaluate(e,...t)}async evaluateHandle(e,...t){return e=Ul(this.evaluateHandle.name,e),await this.handle.evaluateHandle(e,...t)}async jsonValue(){return await this.handle.jsonValue()}toString(){return this.handle.toString()}remoteObject(){return this.handle.remoteObject()}async dispose(){await Promise.all([this.handle.dispose(),this.isolatedHandle?.dispose()])}asElement(){return this}async $(e){const{updatedSelector:t,QueryHandler:n}=Uu(e);return await n.queryOne(this,t)}async $$(e,t){return!1===t?.isolate?await this.#A(e):await this.#O(e)}get#O(){return a.value}async#A(e){const{updatedSelector:t,QueryHandler:n}=Uu(e);return await Su.collect(n.queryAll(this,t))}async $eval(e,t,...n){const r={stack:[],error:void 0,hasError:!1};try{t=Ul(this.$eval.name,t);const s=nd(r,await this.$(e),!1);if(!s)throw new Error(`Error: failed to find element matching selector "${e}"`);return await s.evaluate(t,...n)}catch(e){r.error=e,r.hasError=!0}finally{rd(r)}}async $$eval(e,t,...n){const r={stack:[],error:void 0,hasError:!1};try{t=Ul(this.$$eval.name,t);const s=await this.$$(e),i=nd(r,await this.evaluateHandle(((e,...t)=>t),...s),!1),[a]=await Promise.all([i.evaluate(t,...n),...s.map((e=>e.dispose()))]);return a}catch(e){r.error=e,r.hasError=!0}finally{rd(r)}}async waitForSelector(e,t={}){const{updatedSelector:n,QueryHandler:r,polling:s}=Uu(e);return await r.waitFor(this,n,{polling:s,...t})}async#$(e){return await this.evaluate((async(e,t,n)=>Boolean(t.checkVisibility(e,n))),wu.create((e=>e.puppeteerUtil)),e)}async isVisible(){return await this.#$(!0)}async isHidden(){return await this.#$(!1)}async toElement(e){const t=await this.evaluate(((e,t)=>e.nodeName===t.toUpperCase()),e);if(!t)throw new Error(`Element is not a(n) \`${e}\` element`);return this}async clickablePoint(e){const t=await this.#M();if(!t)throw new Error("Node is either not clickable or not an Element");return void 0!==e?{x:t.x+e.x,y:t.y+e.y}:{x:t.x+t.width/2,y:t.y+t.height/2}}async hover(){await this.scrollIntoViewIfNeeded();const{x:e,y:t}=await this.clickablePoint();await this.frame.page().mouse.move(e,t)}async click(e={}){await this.scrollIntoViewIfNeeded();const{x:t,y:n}=await this.clickablePoint(e.offset);await this.frame.page().mouse.click(t,n,e)}async drag(e){await this.scrollIntoViewIfNeeded();const t=this.frame.page();if(t.isDragInterceptionEnabled()){const n=await this.clickablePoint();return e instanceof R&&(e=await e.clickablePoint()),await t.mouse.drag(n,e)}try{t._isDragging||(t._isDragging=!0,await this.hover(),await t.mouse.down()),e instanceof R?await e.hover():await t.mouse.move(e.x,e.y)}catch(e){throw t._isDragging=!1,e}}async dragEnter(e={items:[],dragOperationsMask:1}){const t=this.frame.page();await this.scrollIntoViewIfNeeded();const n=await this.clickablePoint();await t.mouse.dragEnter(n,e)}async dragOver(e={items:[],dragOperationsMask:1}){const t=this.frame.page();await this.scrollIntoViewIfNeeded();const n=await this.clickablePoint();await t.mouse.dragOver(n,e)}async drop(e={items:[],dragOperationsMask:1}){const t=this.frame.page();if("items"in e){await this.scrollIntoViewIfNeeded();const n=await this.clickablePoint();await t.mouse.drop(n,e)}else await e.drag(this),t._isDragging=!1,await t.mouse.up()}async dragAndDrop(e,t){const n=this.frame.page();Sl(n.isDragInterceptionEnabled(),"Drag Interception is not enabled!"),await this.scrollIntoViewIfNeeded();const r=await this.clickablePoint(),s=await e.clickablePoint();await n.mouse.dragAndDrop(r,s,t)}async select(...e){for(const t of e)Sl(Bl(t),'Values must be strings. Found value "'+t+'" of type "'+typeof t+'"');return await this.evaluate(((e,t)=>{const n=new Set(t);if(!(e instanceof HTMLSelectElement))throw new Error("Element is not a