diff --git a/packages/browseros/chromium_patches/chrome/browser/resources/settings/nxtscape_page/models_data.ts b/packages/browseros/chromium_patches/chrome/browser/resources/settings/nxtscape_page/models_data.ts index 7e11806d..184b3bae 100644 --- a/packages/browseros/chromium_patches/chrome/browser/resources/settings/nxtscape_page/models_data.ts +++ b/packages/browseros/chromium_patches/chrome/browser/resources/settings/nxtscape_page/models_data.ts @@ -8,6 +8,7 @@ index 0000000000000..36638c1910a09 +export interface ModelInfo { + model_id: string; + context_length: number; ++ requires_computer_use?: boolean; +} + +export interface ModelsData { @@ -66,6 +67,7 @@ index 0000000000000..36638c1910a09 + { model_id: 'gemini-2.5-pro-preview-05-06', context_length: 1048576 }, + { model_id: 'gemini-2.5-pro-preview-06-05', context_length: 1048576 }, + { model_id: 'gemini-2.5-pro', context_length: 1048576 }, ++ { model_id: 'gemini-2.5-computer-use-preview-10-2025', context_length: 1048576, requires_computer_use: true }, + { model_id: 'gemini-2.0-flash-exp', context_length: 1048576 }, + { model_id: 'gemini-2.0-flash', context_length: 1048576 }, + { model_id: 'gemini-2.0-flash-001', context_length: 1048576 }, diff --git a/packages/browseros/resources/files/ai_side_panel/BUILD.gn b/packages/browseros/resources/files/ai_side_panel/BUILD.gn new file mode 100644 index 00000000..713db11e --- /dev/null +++ b/packages/browseros/resources/files/ai_side_panel/BUILD.gn @@ -0,0 +1,27 @@ +# Copyright 2024 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//ui/webui/resources/tools/generate_grd.gni") + +generate_grd("build") { + grd_prefix = "ai_side_panel" + out_grd = "$target_gen_dir/resources.grd" + + input_files = [ + "manifest.json", + "background.js", + "content.js", + "sidepanel.html", + "sidepanel.js", + "options.html", + "options.js", + "Readability.js", + "buildDomTree.js", + "assets/icon16.png", + "assets/icon48.png", + "assets/icon128.png", + ] + + input_files_base_dir = rebase_path(".", "//") +} diff --git a/packages/browseros/resources/files/ai_side_panel/Readability.js b/packages/browseros/resources/files/ai_side_panel/Readability.js new file mode 100644 index 00000000..f961851d --- /dev/null +++ b/packages/browseros/resources/files/ai_side_panel/Readability.js @@ -0,0 +1 @@ +function Readability(e,t){if(t&&t.documentElement)e=t,t=arguments[2];else if(!e||!e.documentElement)throw new Error("First argument to Readability constructor should be a document object.");if(t=t||{},this._doc=e,this._docJSDOMParser=this._doc.firstChild.__JSDOMParser__,this._articleTitle=null,this._articleByline=null,this._articleDir=null,this._articleSiteName=null,this._attempts=[],this._metadata={},this._debug=!!t.debug,this._maxElemsToParse=t.maxElemsToParse||this.DEFAULT_MAX_ELEMS_TO_PARSE,this._nbTopCandidates=t.nbTopCandidates||this.DEFAULT_N_TOP_CANDIDATES,this._charThreshold=t.charThreshold||this.DEFAULT_CHAR_THRESHOLD,this._classesToPreserve=this.CLASSES_TO_PRESERVE.concat(t.classesToPreserve||[]),this._keepClasses=!!t.keepClasses,this._serializer=t.serializer||function(e){return e.innerHTML},this._disableJSONLD=!!t.disableJSONLD,this._allowedVideoRegex=t.allowedVideoRegex||this.REGEXPS.videos,this._linkDensityModifier=t.linkDensityModifier||0,this._flags=this.FLAG_STRIP_UNLIKELYS|this.FLAG_WEIGHT_CLASSES|this.FLAG_CLEAN_CONDITIONALLY,this._debug){let e=function(e){if(e.nodeType==e.TEXT_NODE)return`${e.nodeName} ("${e.textContent}")`;let t=Array.from(e.attributes||[],(function(e){return`${e.name}="${e.value}"`})).join(" ");return`<${e.localName} ${t}>`};this.log=function(){if("undefined"!=typeof console){Array.from(arguments,(t=>t&&t.nodeType==this.ELEMENT_NODE?e(t):t)).unshift("Reader: (Readability)")}else if("undefined"!=typeof dump){var t=Array.prototype.map.call(arguments,(function(t){return t&&t.nodeName?e(t):t})).join(" ");dump("Reader: (Readability) "+t+"\n")}}}else this.log=function(){}}Readability.prototype={FLAG_STRIP_UNLIKELYS:1,FLAG_WEIGHT_CLASSES:2,FLAG_CLEAN_CONDITIONALLY:4,ELEMENT_NODE:1,TEXT_NODE:3,DEFAULT_MAX_ELEMS_TO_PARSE:0,DEFAULT_N_TOP_CANDIDATES:5,DEFAULT_TAGS_TO_SCORE:"section,h2,h3,h4,h5,h6,p,td,pre".toUpperCase().split(","),DEFAULT_CHAR_THRESHOLD:500,REGEXPS:{unlikelyCandidates:/-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i,okMaybeItsACandidate:/and|article|body|column|content|main|mathjax|shadow/i,positive:/article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story/i,negative:/-ad-|hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|footer|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|widget/i,extraneous:/print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single|utility/i,byline:/byline|author|dateline|writtenby|p-author/i,replaceFonts:/<(\/?)font[^>]*>/gi,normalize:/\s{2,}/g,videos:/\/\/(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq|bilibili|live.bilibili)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)/i,shareElements:/(\b|_)(share|sharedaddy)(\b|_)/i,nextLink:/(next|weiter|continue|>([^\|]|$)|»([^\|]|$))/i,prevLink:/(prev|earl|old|new|<|«)/i,tokenize:/\W+/g,whitespace:/^\s*$/,hasContent:/\S$/,hashUrl:/^#.+/,srcsetUrl:/(\S+)(\s+[\d.]+[xw])?(\s*(?:,|$))/g,b64DataUrl:/^data:\s*([^\s;,]+)\s*;\s*base64\s*,/i,commas:/\u002C|\u060C|\uFE50|\uFE10|\uFE11|\u2E41|\u2E34|\u2E32|\uFF0C/g,jsonLdArticleTypes:/^Article|AdvertiserContentArticle|NewsArticle|AnalysisNewsArticle|AskPublicNewsArticle|BackgroundNewsArticle|OpinionNewsArticle|ReportageNewsArticle|ReviewNewsArticle|Report|SatiricalArticle|ScholarlyArticle|MedicalScholarlyArticle|SocialMediaPosting|BlogPosting|LiveBlogPosting|DiscussionForumPosting|TechArticle|APIReference$/,adWords:/^(ad(vertising|vertisement)?|pub(licité)?|werb(ung)?|广告|Реклама|Anuncio)$/iu,loadingWords:/^((loading|正在加载|Загрузка|chargement|cargando)(…|\.\.\.)?)$/iu},UNLIKELY_ROLES:["menu","menubar","complementary","navigation","alert","alertdialog","dialog"],DIV_TO_P_ELEMS:new Set(["BLOCKQUOTE","DL","DIV","IMG","OL","P","PRE","TABLE","UL"]),ALTER_TO_DIV_EXCEPTIONS:["DIV","ARTICLE","SECTION","P","OL","UL"],PRESENTATIONAL_ATTRIBUTES:["align","background","bgcolor","border","cellpadding","cellspacing","frame","hspace","rules","style","valign","vspace"],DEPRECATED_SIZE_ATTRIBUTE_ELEMS:["TABLE","TH","TD","HR","PRE"],PHRASING_ELEMS:["ABBR","AUDIO","B","BDO","BR","BUTTON","CITE","CODE","DATA","DATALIST","DFN","EM","EMBED","I","IMG","INPUT","KBD","LABEL","MARK","MATH","METER","NOSCRIPT","OBJECT","OUTPUT","PROGRESS","Q","RUBY","SAMP","SCRIPT","SELECT","SMALL","SPAN","STRONG","SUB","SUP","TEXTAREA","TIME","VAR","WBR"],CLASSES_TO_PRESERVE:["page"],HTML_ESCAPE_MAP:{lt:"<",gt:">",amp:"&",quot:'"',apos:"'"},_postProcessContent(e){this._fixRelativeUris(e),this._simplifyNestedElements(e),this._keepClasses||this._cleanClasses(e)},_removeNodes(e,t){if(this._docJSDOMParser&&e._isLiveNodeList)throw new Error("Do not pass live node lists to _removeNodes");for(var i=e.length-1;i>=0;i--){var a=e[i],r=a.parentNode;r&&(t&&!t.call(this,a,i,e)||r.removeChild(a))}},_replaceNodeTags(e,t){if(this._docJSDOMParser&&e._isLiveNodeList)throw new Error("Do not pass live node lists to _replaceNodeTags");for(const i of e)this._setNodeTag(i,t)},_forEachNode(e,t){Array.prototype.forEach.call(e,t,this)},_findNode(e,t){return Array.prototype.find.call(e,t,this)},_someNode(e,t){return Array.prototype.some.call(e,t,this)},_everyNode(e,t){return Array.prototype.every.call(e,t,this)},_getAllNodesWithTag:(e,t)=>e.querySelectorAll?e.querySelectorAll(t.join(",")):[].concat.apply([],t.map((function(t){var i=e.getElementsByTagName(t);return Array.isArray(i)?i:Array.from(i)}))),_cleanClasses(e){var t=this._classesToPreserve,i=(e.getAttribute("class")||"").split(/\s+/).filter((e=>t.includes(e))).join(" ");for(i?e.setAttribute("class",i):e.removeAttribute("class"),e=e.firstElementChild;e;e=e.nextElementSibling)this._cleanClasses(e)},_isUrl(e){try{return new URL(e),!0}catch{return!1}},_fixRelativeUris(e){var t=this._doc.baseURI,i=this._doc.documentURI;function a(e){if(t==i&&"#"==e.charAt(0))return e;try{return new URL(e,t).href}catch(e){}return e}var r=this._getAllNodesWithTag(e,["a"]);this._forEachNode(r,(function(e){var t=e.getAttribute("href");if(t)if(0===t.indexOf("javascript:"))if(1===e.childNodes.length&&e.childNodes[0].nodeType===this.TEXT_NODE){var i=this._doc.createTextNode(e.textContent);e.parentNode.replaceChild(i,e)}else{for(var r=this._doc.createElement("span");e.firstChild;)r.appendChild(e.firstChild);e.parentNode.replaceChild(r,e)}else e.setAttribute("href",a(t))}));var s=this._getAllNodesWithTag(e,["img","picture","figure","video","audio","source"]);this._forEachNode(s,(function(e){var t=e.getAttribute("src"),i=e.getAttribute("poster"),r=e.getAttribute("srcset");if(t&&e.setAttribute("src",a(t)),i&&e.setAttribute("poster",a(i)),r){var s=r.replace(this.REGEXPS.srcsetUrl,(function(e,t,i,r){return a(t)+(i||"")+r}));e.setAttribute("srcset",s)}}))},_simplifyNestedElements(e){for(var t=e;t;){if(t.parentNode&&["DIV","SECTION"].includes(t.tagName)&&(!t.id||!t.id.startsWith("readability"))){if(this._isElementWithoutContent(t)){t=this._removeAndGetNext(t);continue}if(this._hasSingleTagInsideElement(t,"DIV")||this._hasSingleTagInsideElement(t,"SECTION")){for(var i=t.children[0],a=0;a»/.source;if(new RegExp(`\\s[${s}]\\s`).test(t)){a=/\s[\\\/>»]\s/.test(t);let e=Array.from(i.matchAll(new RegExp(`\\s[${s}]\\s`,"gi")));r(t=i.substring(0,e.pop().index))<3&&(t=i.replace(new RegExp(`^[^${s}]*[${s}]`,"gi"),""))}else if(t.includes(": ")){var n=this._getAllNodesWithTag(e,["h1","h2"]),l=t.trim();this._someNode(n,(function(e){return e.textContent.trim()===l}))||(r(t=i.substring(i.lastIndexOf(":")+1))<3?t=i.substring(i.indexOf(":")+1):r(i.substr(0,i.indexOf(":")))>5&&(t=i))}else if(t.length>150||t.length<15){var o=e.getElementsByTagName("h1");1===o.length&&(t=this._getInnerText(o[0]))}var h=r(t=t.trim().replace(this.REGEXPS.normalize," "));return h<=4&&(!a||h!=r(i.replace(new RegExp(`\\s[${s}]\\s`,"g"),""))-1)&&(t=i),t},_prepDocument(){var e=this._doc;this._removeNodes(this._getAllNodesWithTag(e,["style"])),e.body&&this._replaceBrs(e.body),this._replaceNodeTags(this._getAllNodesWithTag(e,["font"]),"SPAN")},_nextNode(e){for(var t=e;t&&t.nodeType!=this.ELEMENT_NODE&&this.REGEXPS.whitespace.test(t.textContent);)t=t.nextSibling;return t},_replaceBrs(e){this._forEachNode(this._getAllNodesWithTag(e,["br"]),(function(e){for(var t=e.nextSibling,i=!1;(t=this._nextNode(t))&&"BR"==t.tagName;){i=!0;var a=t.nextSibling;t.remove(),t=a}if(i){var r=this._doc.createElement("p");for(e.parentNode.replaceChild(r,e),t=r.nextSibling;t;){if("BR"==t.tagName){var s=this._nextNode(t.nextSibling);if(s&&"BR"==s.tagName)break}if(!this._isPhrasingContent(t))break;var n=t.nextSibling;r.appendChild(t),t=n}for(;r.lastChild&&this._isWhitespace(r.lastChild);)r.lastChild.remove();"P"===r.parentNode.tagName&&this._setNodeTag(r.parentNode,"DIV")}}))},_setNodeTag(e,t){if(this.log("_setNodeTag",e,t),this._docJSDOMParser)return e.localName=t.toLowerCase(),e.tagName=t.toUpperCase(),e;for(var i=e.ownerDocument.createElement(t);e.firstChild;)i.appendChild(e.firstChild);e.parentNode.replaceChild(i,e),e.readability&&(i.readability=e.readability);for(var a=0;a!i.includes(e))).join(" ").length/a.join(" ").length:0},_isValidByline(e,t){var i=e.getAttribute("rel"),a=e.getAttribute("itemprop"),r=e.textContent.trim().length;return("author"===i||a&&a.includes("author")||this.REGEXPS.byline.test(t))&&!!r&&r<100},_getNodeAncestors(e,t){t=t||0;for(var i=0,a=[];e.parentNode&&(a.push(e.parentNode),!t||++i!==t);)e=e.parentNode;return a},_grabArticle(e){this.log("**** grabArticle ****");var t=this._doc,i=null!==e;if(!(e=e||this._doc.body))return this.log("No body found in document. Abort."),null;for(var a=e.innerHTML;;){this.log("Starting grabArticle loop");var r=this._flagIsActive(this.FLAG_STRIP_UNLIKELYS),s=[],n=this._doc.documentElement;let J=!0;for(;n;){"HTML"===n.tagName&&(this._articleLang=n.getAttribute("lang"));var l=n.className+" "+n.id;if(this._isProbablyVisible(n))if("true"!=n.getAttribute("aria-modal")||"dialog"!=n.getAttribute("role"))if(this._articleByline||this._metadata.byline||!this._isValidByline(n,l))if(J&&this._headerDuplicatesTitle(n))this.log("Removing header: ",n.textContent.trim(),this._articleTitle.trim()),J=!1,n=this._removeAndGetNext(n);else{if(r){if(this.REGEXPS.unlikelyCandidates.test(l)&&!this.REGEXPS.okMaybeItsACandidate.test(l)&&!this._hasAncestorTag(n,"table")&&!this._hasAncestorTag(n,"code")&&"BODY"!==n.tagName&&"A"!==n.tagName){this.log("Removing unlikely candidate - "+l),n=this._removeAndGetNext(n);continue}if(this.UNLIKELY_ROLES.includes(n.getAttribute("role"))){this.log("Removing content with role "+n.getAttribute("role")+" - "+l),n=this._removeAndGetNext(n);continue}}if("DIV"!==n.tagName&&"SECTION"!==n.tagName&&"HEADER"!==n.tagName&&"H1"!==n.tagName&&"H2"!==n.tagName&&"H3"!==n.tagName&&"H4"!==n.tagName&&"H5"!==n.tagName&&"H6"!==n.tagName||!this._isElementWithoutContent(n)){if(this.DEFAULT_TAGS_TO_SCORE.includes(n.tagName)&&s.push(n),"DIV"===n.tagName){for(var o=null,h=n.firstChild;h;){var d=h.nextSibling;if(this._isPhrasingContent(h))null!==o?o.appendChild(h):this._isWhitespace(h)||(o=t.createElement("p"),n.replaceChild(o,h),o.appendChild(h));else if(null!==o){for(;o.lastChild&&this._isWhitespace(o.lastChild);)o.lastChild.remove();o=null}h=d}if(this._hasSingleTagInsideElement(n,"P")&&this._getLinkDensity(n)<.25){var c=n.children[0];n.parentNode.replaceChild(c,n),n=c,s.push(n)}else this._hasChildBlockElement(n)||(n=this._setNodeTag(n,"P"),s.push(n))}n=this._getNextNode(n)}else n=this._removeAndGetNext(n)}else{for(var g=this._getNextNode(n,!0),_=this._getNextNode(n),m=null;_&&_!=g;){var u=_.getAttribute("itemprop");if(u&&u.includes("name")){m=_;break}_=this._getNextNode(_)}this._articleByline=(m??n).textContent.trim(),n=this._removeAndGetNext(n)}else n=this._removeAndGetNext(n);else this.log("Removing hidden node - "+l),n=this._removeAndGetNext(n)}var p=[];this._forEachNode(s,(function(e){if(e.parentNode&&void 0!==e.parentNode.tagName){var t=this._getInnerText(e);if(!(t.length<25)){var i=this._getNodeAncestors(e,5);if(0!==i.length){var a=0;a+=1,a+=t.split(this.REGEXPS.commas).length,a+=Math.min(Math.floor(t.length/100),3),this._forEachNode(i,(function(e,t){if(e.tagName&&e.parentNode&&void 0!==e.parentNode.tagName){if(void 0===e.readability&&(this._initializeNode(e),p.push(e)),0===t)var i=1;else i=1===t?2:3*t;e.readability.contentScore+=a/i}}))}}}}));for(var N=[],f=0,E=p.length;fA.readability.contentScore){N.splice(y,0,b),N.length>this._nbTopCandidates&&N.pop();break}}}var v,S=N[0]||null,C=!1;if(null===S||"BODY"===S.tagName){for(S=t.createElement("DIV"),C=!0;e.firstChild;)this.log("Moving child out:",e.firstChild),S.appendChild(e.firstChild);e.appendChild(S),this._initializeNode(S)}else if(S){for(var L=[],x=1;x=.75&&L.push(this._getNodeAncestors(N[x]));if(L.length>=3)for(v=S.parentNode;"BODY"!==v.tagName;){for(var D=0,I=0;I=3){S=v;break}v=v.parentNode}S.readability||this._initializeNode(S),v=S.parentNode;for(var R=S.readability.contentScore,P=R/3;"BODY"!==v.tagName;)if(v.readability){var w=v.readability.contentScore;if(wR){S=v;break}R=v.readability.contentScore,v=v.parentNode}else v=v.parentNode;for(v=S.parentNode;"BODY"!=v.tagName&&1==v.children.length;)v=(S=v).parentNode;S.readability||this._initializeNode(S)}var O=t.createElement("DIV");i&&(O.id="readability-content");for(var B=Math.max(10,.2*S.readability.contentScore),G=(v=S.parentNode).children,M=0,H=G.length;M=B)U=!0;else if("P"===k.nodeName){var $=this._getLinkDensity(k),F=this._getInnerText(k),X=F.length;(X>80&&$<.25||X<80&&X>0&&0===$&&-1!==F.search(/\.( |$)/))&&(U=!0)}}U&&(this.log("Appending node:",k),this.ALTER_TO_DIV_EXCEPTIONS.includes(k.nodeName)||(this.log("Altering sibling:",k,"to div."),k=this._setNodeTag(k,"DIV")),O.appendChild(k),G=v.children,M-=1,H-=1)}if(this._debug&&this.log("Article content pre-prep: "+O.innerHTML),this._prepArticle(O),this._debug&&this.log("Article content post-prep: "+O.innerHTML),C)S.id="readability-page-1",S.className="page";else{var j=t.createElement("DIV");for(j.id="readability-page-1",j.className="page";O.firstChild;)j.appendChild(O.firstChild);O.appendChild(j)}this._debug&&this.log("Article content after paging: "+O.innerHTML);var V=!0,Y=this._getInnerText(O,!0).length;if(Y1114111||a>=55296&&a<=57343)&&(a=65533),String.fromCodePoint(a)}))},_getJSONLD(e){var t,i=this._getAllNodesWithTag(e,["script"]);return this._forEachNode(i,(function(e){if(!t&&"application/ld+json"===e.getAttribute("type"))try{var i=e.textContent.replace(/^\s*\s*$/g,""),a=JSON.parse(i);if(Array.isArray(a)&&!(a=a.find((e=>e["@type"]&&e["@type"].match(this.REGEXPS.jsonLdArticleTypes)))))return;var r=/^https?\:\/\/schema\.org\/?$/;if(!("string"==typeof a["@context"]&&a["@context"].match(r)||"object"==typeof a["@context"]&&"string"==typeof a["@context"]["@vocab"]&&a["@context"]["@vocab"].match(r)))return;if(!a["@type"]&&Array.isArray(a["@graph"])&&(a=a["@graph"].find((e=>(e["@type"]||"").match(this.REGEXPS.jsonLdArticleTypes)))),!a||!a["@type"]||!a["@type"].match(this.REGEXPS.jsonLdArticleTypes))return;if(t={},"string"==typeof a.name&&"string"==typeof a.headline&&a.name!==a.headline){var s=this._getArticleTitle(),n=this._textSimilarity(a.name,s)>.75,l=this._textSimilarity(a.headline,s)>.75;t.title=l&&!n?a.headline:a.name}else"string"==typeof a.name?t.title=a.name.trim():"string"==typeof a.headline&&(t.title=a.headline.trim());a.author&&("string"==typeof a.author.name?t.byline=a.author.name.trim():Array.isArray(a.author)&&a.author[0]&&"string"==typeof a.author[0].name&&(t.byline=a.author.filter((function(e){return e&&"string"==typeof e.name})).map((function(e){return e.name.trim()})).join(", "))),"string"==typeof a.description&&(t.excerpt=a.description.trim()),a.publisher&&"string"==typeof a.publisher.name&&(t.siteName=a.publisher.name.trim()),"string"==typeof a.datePublished&&(t.datePublished=a.datePublished.trim())}catch(e){this.log(e.message)}})),t||{}},_getArticleMetadata(e){var t={},i={},a=this._doc.getElementsByTagName("meta"),r=/\s*(article|dc|dcterm|og|twitter)\s*:\s*(author|creator|description|published_time|title|site_name)\s*/gi,s=/^\s*(?:(dc|dcterm|og|twitter|parsely|weibo:(article|webpage))\s*[-\.:]\s*)?(author|creator|pub-date|description|title|site_name)\s*$/i;this._forEachNode(a,(function(e){var t=e.getAttribute("name"),a=e.getAttribute("property"),n=e.getAttribute("content");if(n){var l=null,o=null;a&&(l=a.match(r))&&(o=l[0].toLowerCase().replace(/\s/g,""),i[o]=n.trim()),!l&&t&&s.test(t)&&(o=t,n&&(o=o.toLowerCase().replace(/\s/g,"").replace(/\./g,":"),i[o]=n.trim()))}})),t.title=e.title||i["dc:title"]||i["dcterm:title"]||i["og:title"]||i["weibo:article:title"]||i["weibo:webpage:title"]||i.title||i["twitter:title"]||i["parsely-title"],t.title||(t.title=this._getArticleTitle());const n="string"!=typeof i["article:author"]||this._isUrl(i["article:author"])?void 0:i["article:author"];return t.byline=e.byline||i["dc:creator"]||i["dcterm:creator"]||i.author||i["parsely-author"]||n,t.excerpt=e.excerpt||i["dc:description"]||i["dcterm:description"]||i["og:description"]||i["weibo:article:description"]||i["weibo:webpage:description"]||i.description||i["twitter:description"],t.siteName=e.siteName||i["og:site_name"],t.publishedTime=e.datePublished||i["article:published_time"]||i["parsely-pub-date"]||null,t.title=this._unescapeHtmlEntities(t.title),t.byline=this._unescapeHtmlEntities(t.byline),t.excerpt=this._unescapeHtmlEntities(t.excerpt),t.siteName=this._unescapeHtmlEntities(t.siteName),t.publishedTime=this._unescapeHtmlEntities(t.publishedTime),t},_isSingleImage(e){for(;e;){if("IMG"===e.tagName)return!0;if(1!==e.children.length||""!==e.textContent.trim())return!1;e=e.children[0]}return!1},_unwrapNoscriptImages(e){var t=Array.from(e.getElementsByTagName("img"));this._forEachNode(t,(function(e){for(var t=0;t0&&r>i)return!1;if(e.parentNode.tagName===t&&(!a||a(e.parentNode)))return!0;e=e.parentNode,r++}return!1},_getRowAndColumnCount(e){for(var t=0,i=0,a=e.getElementsByTagName("tr"),r=0;r=10||s.columns>4?a._readabilityDataTable=!0:a._readabilityDataTable=s.rows*s.columns>10:a._readabilityDataTable=!1}}}else a._readabilityDataTable=!1;else a._readabilityDataTable=!1}},_fixLazyImages(e){this._forEachNode(this._getAllNodesWithTag(e,["img","picture","figure"]),(function(e){if(e.src&&this.REGEXPS.b64DataUrl.test(e.src)){var t=this.REGEXPS.b64DataUrl.exec(e.src);if("image/svg+xml"===t[1])return;for(var i=!1,a=0;aa+=this._getInnerText(e,!0).length)),a/i},_cleanConditionally(e,t){this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)&&this._removeNodes(this._getAllNodesWithTag(e,[t]),(function(e){var i=function(e){return e._readabilityDataTable},a="ul"===t||"ol"===t;if(!a){var r=0,s=this._getAllNodesWithTag(e,["ul","ol"]);this._forEachNode(s,(e=>r+=this._getInnerText(e).length)),a=r/this._getInnerText(e).length>.9}if("table"===t&&i(e))return!1;if(this._hasAncestorTag(e,"table",-1,i))return!1;if(this._hasAncestorTag(e,"code"))return!1;if([...e.getElementsByTagName("table")].some((e=>e._readabilityDataTable)))return!1;var n=this._getClassWeight(e);this.log("Cleaning Conditionally",e);if(n+0<0)return!0;if(this._getCharCount(e,",")<10){for(var l=e.getElementsByTagName("p").length,o=e.getElementsByTagName("img").length,h=e.getElementsByTagName("li").length-100,d=e.getElementsByTagName("input").length,c=this._getTextDensity(e,["h1","h2","h3","h4","h5","h6"]),g=0,_=this._getAllNodesWithTag(e,["object","embed","iframe"]),m=0;m<_.length;m++){for(var u=0;u<_[m].attributes.length;u++)if(this._allowedVideoRegex.test(_[m].attributes[u].value))return!1;if("object"===_[m].tagName&&this._allowedVideoRegex.test(_[m].innerHTML))return!1;g++}var p=this._getInnerText(e);if(this.REGEXPS.adWords.test(p)||this.REGEXPS.loadingWords.test(p))return!0;var N=p.length,f=this._getLinkDensity(e),E=["SPAN","LI","TD"].concat(Array.from(this.DIV_TO_P_ELEMS)),b=this._getTextDensity(e,E),T=this._hasAncestorTag(e,"figure");var y=(()=>{const e=[];return!T&&o>1&&l/o<.5&&e.push(`Bad p to img ratio (img=${o}, p=${l})`),!a&&h>l&&e.push(`Too many li's outside of a list. (li=${h} > p=${l})`),d>Math.floor(l/3)&&e.push(`Too many inputs per p. (input=${d}, p=${l})`),!a&&!T&&c<.9&&N<25&&(0===o||o>2)&&f>0&&e.push(`Suspiciously short. (headingDensity=${c}, img=${o}, linkDensity=${f})`),!a&&n<25&&f>.2+this._linkDensityModifier&&e.push(`Low weight and a little linky. (linkDensity=${f})`),n>=25&&f>.5+this._linkDensityModifier&&e.push(`High weight and mostly links. (linkDensity=${f})`),(1===g&&N<75||g>1)&&e.push(`Suspicious embed. (embedCount=${g}, contentLength=${N})`),0===o&&0===b&&e.push(`No useful content. (img=${o}, textDensity=${b})`),!!e.length&&(this.log("Checks failed",e),!0)})();if(a&&y){for(var A=0;A1)return y}let t=e.getElementsByTagName("li").length;if(o==t)return!1}return y}return!1}))},_cleanMatchedNodes(e,t){for(var i=this._getNextNode(e,!0),a=this._getNextNode(e);a&&a!=i;)a=t.call(this,a,a.className+" "+a.id)?this._removeAndGetNext(a):this._getNextNode(a)},_cleanHeaders(e){let t=this._getAllNodesWithTag(e,["h1","h2"]);this._removeNodes(t,(function(e){let t=this._getClassWeight(e)<0;return t&&this.log("Removing header with low class weight:",e),t}))},_headerDuplicatesTitle(e){if("H1"!=e.tagName&&"H2"!=e.tagName)return!1;var t=this._getInnerText(e,!1);return this.log("Evaluating similarity of header:",t,this._articleTitle),this._textSimilarity(this._articleTitle,t)>.75},_flagIsActive(e){return(this._flags&e)>0},_removeFlag(e){this._flags=this._flags&~e},_isProbablyVisible:e=>(!e.style||"none"!=e.style.display)&&(!e.style||"hidden"!=e.style.visibility)&&!e.hasAttribute("hidden")&&(!e.hasAttribute("aria-hidden")||"true"!=e.getAttribute("aria-hidden")||e.className&&e.className.includes&&e.className.includes("fallback-image")),parse(){if(this._maxElemsToParse>0){var e=this._doc.getElementsByTagName("*").length;if(e>this._maxElemsToParse)throw new Error("Aborting parsing document; "+e+" elements found")}this._unwrapNoscriptImages(this._doc);var t=this._disableJSONLD?{}:this._getJSONLD(this._doc);this._removeScripts(this._doc),this._prepDocument();var i=this._getArticleMetadata(t);this._metadata=i,this._articleTitle=i.title;var a=this._grabArticle();if(!a)return null;if(this.log("Grabbed: "+a.innerHTML),this._postProcessContent(a),!i.excerpt){var r=a.getElementsByTagName("p");r.length&&(i.excerpt=r[0].textContent.trim())}var s=a.textContent;return{title:this._articleTitle,byline:i.byline||this._articleByline,dir:this._articleDir,lang:this._articleLang,content:this._serializer(a),textContent:s,length:s.length,excerpt:i.excerpt,siteName:i.siteName||this._articleSiteName,publishedTime:i.publishedTime}}},"object"==typeof module&&(module.exports=Readability); \ No newline at end of file diff --git a/packages/browseros/resources/files/ai_side_panel/assets/icon128.png b/packages/browseros/resources/files/ai_side_panel/assets/icon128.png new file mode 100644 index 00000000..d2b1ab19 Binary files /dev/null and b/packages/browseros/resources/files/ai_side_panel/assets/icon128.png differ diff --git a/packages/browseros/resources/files/ai_side_panel/assets/icon16.png b/packages/browseros/resources/files/ai_side_panel/assets/icon16.png new file mode 100644 index 00000000..acb5d131 Binary files /dev/null and b/packages/browseros/resources/files/ai_side_panel/assets/icon16.png differ diff --git a/packages/browseros/resources/files/ai_side_panel/assets/icon48.png b/packages/browseros/resources/files/ai_side_panel/assets/icon48.png new file mode 100644 index 00000000..6d33537a Binary files /dev/null and b/packages/browseros/resources/files/ai_side_panel/assets/icon48.png differ diff --git a/packages/browseros/resources/files/ai_side_panel/background.js b/packages/browseros/resources/files/ai_side_panel/background.js new file mode 100644 index 00000000..ba09a05b --- /dev/null +++ b/packages/browseros/resources/files/ai_side_panel/background.js @@ -0,0 +1 @@ +(()=>{var e={144:(e,t,n)=>{"use strict";const r=n(3908);e.exports=(e,t,n=!1)=>{if(e instanceof r)return e;try{return new r(e,t)}catch(e){if(!n)return null;throw e}}},228:e=>{"use strict";var t=Object.prototype.hasOwnProperty,n="~";function r(){}function s(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function i(e,t,r,i,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new s(r,i||e,a),l=n?n+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),o.prototype.eventNames=function(){var e,r,s=[];if(0===this._eventsCount)return s;for(r in e=this._events)t.call(e,r)&&s.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,i=r.length,a=new Array(i);s{"use strict";const r=n(3908),s=n(8311);e.exports=(e,t,n)=>{let i=null,a=null,o=null;try{o=new s(t,n)}catch(e){return null}return e.forEach(e=>{o.test(e)&&(i&&1!==a.compare(e)||(i=e,a=new r(i,n)))}),i}},560:(e,t,n)=>{"use strict";const r=n(3908);e.exports=(e,t,n)=>new r(e,n).compare(new r(t,n))},909:(e,t,n)=>{"use strict";const r=n(3908);e.exports=(e,t,n)=>{const s=new r(e,n),i=new r(t,n);return s.compare(i)||s.compareBuild(i)}},1123:e=>{"use strict";const t=/^[0-9]+$/,n=(e,n)=>{const r=t.test(e),s=t.test(n);return r&&s&&(e=+e,n=+n),e===n?0:r&&!s?-1:s&&!r?1:en(t,e)}},1261:(e,t,n)=>{"use strict";const r=n(3908),s=n(8311),i=n(5580);e.exports=(e,t)=>{e=new s(e,t);let n=new r("0.0.0");if(e.test(n))return n;if(n=new r("0.0.0-0"),e.test(n))return n;n=null;for(let t=0;t{const t=new r(e.semver.version);switch(e.operator){case">":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":a&&!i(t,a)||(a=t);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${e.operator}`)}}),!a||n&&!i(n,a)||(n=a)}return n&&e.test(n)?n:null}},1763:(e,t,n)=>{"use strict";const r=n(560);e.exports=(e,t)=>r(e,t,!0)},1832:(e,t,n)=>{"use strict";const r=n(144);e.exports=(e,t)=>{const n=r(e,null,!0),s=r(t,null,!0),i=n.compare(s);if(0===i)return null;const a=i>0,o=a?n:s,l=a?s:n,c=!!o.prerelease.length;if(!!l.prerelease.length&&!c){if(!l.patch&&!l.minor)return"major";if(0===l.compareMain(o))return l.minor&&!l.patch?"minor":"patch"}const u=c?"pre":"";return n.major!==s.major?u+"major":n.minor!==s.minor?u+"minor":n.patch!==s.patch?u+"patch":"prerelease"}},2111:(e,t,n)=>{"use strict";const r=n(4641),s=n(3999),i=n(5580),a=n(4089),o=n(7059),l=n(5200);e.exports=(e,t,n,c)=>{switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof n&&(n=n.version),e===n;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof n&&(n=n.version),e!==n;case"":case"=":case"==":return r(e,n,c);case"!=":return s(e,n,c);case">":return i(e,n,c);case">=":return a(e,n,c);case"<":return o(e,n,c);case"<=":return l(e,n,c);default:throw new TypeError(`Invalid operator: ${t}`)}}},2525:(e,t,n)=>{"use strict";const r=n(7638),s=n(560);e.exports=(e,t,n)=>{const i=[];let a=null,o=null;const l=e.sort((e,t)=>s(e,t,n));for(const e of l){r(e,t,n)?(o=e,a||(a=e)):(o&&i.push([a,o]),o=null,a=null)}a&&i.push([a,null]);const c=[];for(const[e,t]of i)e===t?c.push(e):t||e!==l[0]?t?e===l[0]?c.push(`<=${t}`):c.push(`${e} - ${t}`):c.push(`>=${e}`):c.push("*");const u=c.join(" || "),d="string"==typeof t.raw?t.raw:String(t);return u.length{"use strict";const t=/[\p{Lu}]/u,n=/[\p{Ll}]/u,r=/^[\p{Lu}](?![\p{Lu}])/gu,s=/([\p{Alpha}\p{N}_]|$)/u,i=/[_.\- ]+/,a=new RegExp("^"+i.source),o=new RegExp(i.source+s.source,"gu"),l=new RegExp("\\d+"+s.source,"gu"),c=(e,s)=>{if("string"!=typeof e&&!Array.isArray(e))throw new TypeError("Expected the input to be `string | string[]`");if(s={pascalCase:!1,preserveConsecutiveUppercase:!1,...s},0===(e=Array.isArray(e)?e.map(e=>e.trim()).filter(e=>e.length).join("-"):e.trim()).length)return"";const i=!1===s.locale?e=>e.toLowerCase():e=>e.toLocaleLowerCase(s.locale),c=!1===s.locale?e=>e.toUpperCase():e=>e.toLocaleUpperCase(s.locale);if(1===e.length)return s.pascalCase?c(e):i(e);return e!==i(e)&&(e=((e,r,s)=>{let i=!1,a=!1,o=!1;for(let l=0;l(r.lastIndex=0,e.replace(r,e=>t(e))))(e,i):i(e),s.pascalCase&&(e=c(e.charAt(0))+e.slice(1)),((e,t)=>(o.lastIndex=0,l.lastIndex=0,e.replace(o,(e,n)=>t(n)).replace(l,e=>t(e))))(e,c)};e.exports=c,e.exports.default=c},2938:(e,t,n)=>{"use strict";const r=n(3908);e.exports=(e,t)=>new r(e,t).major},3007:(e,t,n)=>{"use strict";const r=n(3908);e.exports=(e,t,n,s,i)=>{"string"==typeof n&&(i=s,s=n,n=void 0);try{return new r(e instanceof r?e.version:e,n).inc(t,s,i).version}catch(e){return null}}},3290:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=n(228),s=n(6641),i=n(4774),a=()=>{},o=new s.TimeoutError;t.default=class extends r{constructor(e){var t,n,r,s;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=a,this._resolveIdle=a,!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:i.default},e)).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(n=null===(t=e.intervalCap)||void 0===t?void 0:t.toString())&&void 0!==n?n:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(s=null===(r=e.interval)||void 0===r?void 0:r.toString())&&void 0!==s?s:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount{this._onResumeInterval()},t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const t=this._queue.dequeue();return!!t&&(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0)}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise((n,r)=>{this._queue.enqueue(async()=>{this._pendingCount++,this._intervalCount++;try{const i=void 0===this._timeout&&void 0===t.timeout?e():s.default(Promise.resolve(e()),void 0===t.timeout?this._timeout:t.timeout,()=>{(void 0===t.throwOnTimeout?this._throwOnTimeout:t.throwOnTimeout)&&r(o)});n(await i)}catch(e){r(e)}this._next()},t),this._tryToStartAnother(),this.emit("add")})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise(e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise(e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}},3874:(e,t,n)=>{"use strict";const r=n(8311);e.exports=(e,t)=>{try{return new r(e,t).range||"*"}catch(e){return null}}},3904:(e,t,n)=>{"use strict";const r=Symbol("SemVer ANY");class s{static get ANY(){return r}constructor(e,t){if(t=i(t),e instanceof s){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),c("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===r?this.value="":this.value=this.operator+this.semver.version,c("comp",this)}parse(e){const t=this.options.loose?a[o.COMPARATORLOOSE]:a[o.COMPARATOR],n=e.match(t);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=void 0!==n[1]?n[1]:"","="===this.operator&&(this.operator=""),n[2]?this.semver=new u(n[2],this.options.loose):this.semver=r}toString(){return this.value}test(e){if(c("Comparator.test",e,this.options.loose),this.semver===r||e===r)return!0;if("string"==typeof e)try{e=new u(e,this.options)}catch(e){return!1}return l(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof s))throw new TypeError("a Comparator is required");return""===this.operator?""===this.value||new d(e.value,t).test(this.value):""===e.operator?""===e.value||new d(this.value,t).test(e.semver):(!(t=i(t)).includePrerelease||"<0.0.0-0"!==this.value&&"<0.0.0-0"!==e.value)&&(!(!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0")))&&(!(!this.operator.startsWith(">")||!e.operator.startsWith(">"))||(!(!this.operator.startsWith("<")||!e.operator.startsWith("<"))||(!(this.semver.version!==e.semver.version||!this.operator.includes("=")||!e.operator.includes("="))||(!!(l(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<"))||!!(l(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))))))}}e.exports=s;const i=n(8587),{safeRe:a,t:o}=n(9718),l=n(2111),c=n(7272),u=n(3908),d=n(8311)},3908:(e,t,n)=>{"use strict";const r=n(7272),{MAX_LENGTH:s,MAX_SAFE_INTEGER:i}=n(6874),{safeRe:a,t:o}=n(9718),l=n(8587),{compareIdentifiers:c}=n(1123);class u{constructor(e,t){if(t=l(t),e instanceof u){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if("string"!=typeof e)throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>s)throw new TypeError(`version is longer than ${s} characters`);r("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const n=e.trim().match(t.loose?a[o.LOOSE]:a[o.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>i||this.major<0)throw new TypeError("Invalid major version");if(this.minor>i||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>i||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t=0;)"number"==typeof this.prerelease[r]&&(this.prerelease[r]++,r=-2);if(-1===r){if(t===this.prerelease.join(".")&&!1===n)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let r=[t,e];!1===n&&(r=[t]),0===c(this.prerelease[0],t)?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}e.exports=u},3927:(e,t,n)=>{"use strict";const r=n(909);e.exports=(e,t)=>e.sort((e,n)=>r(e,n,t))},3961:e=>{function t(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}e.exports=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var n=this._timeouts.shift();if(void 0===n){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1)}var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n),this._options.unref&&this._timer.unref(),!0},t.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},t.prototype.try=function(e){this.attempt(e)},t.prototype.start=function(e){this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,n=0,r=0;r=n&&(t=s,n=a)}return t}},3999:(e,t,n)=>{"use strict";const r=n(560);e.exports=(e,t,n)=>0!==r(e,t,n)},4089:(e,t,n)=>{"use strict";const r=n(560);e.exports=(e,t,n)=>r(e,t,n)>=0},4110:(e,t,n)=>{"use strict";const r=n(144);e.exports=(e,t)=>{const n=r(e,t);return n&&n.prerelease.length?n.prerelease:null}},4116:(e,t,n)=>{"use strict";const r=n(5617),s=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class i extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const a=(e,t)=>new Promise((n,a)=>{t={onFailedAttempt:()=>{},retries:10,...t};const o=r.operation(t);o.attempt(async r=>{try{n(await e(r))}catch(e){if(!(e instanceof Error))return void a(new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));if(e instanceof i)o.stop(),a(e.originalError);else if(e instanceof TypeError&&(l=e.message,!s.includes(l)))o.stop(),a(e);else{((e,t,n)=>{const r=n.retries-(t-1);e.attemptNumber=t,e.retriesLeft=r})(e,r,t);try{await t.onFailedAttempt(e)}catch(e){return void a(e)}o.retry(e)||a(o.mainError())}}var l})});e.exports=a,e.exports.default=a,e.exports.AbortError=i},4277:(e,t,n)=>{"use strict";const r=n(909);e.exports=(e,t)=>e.sort((e,n)=>r(n,e,t))},4493:(e,t,n)=>{"use strict";const r=n(3908);e.exports=(e,t)=>new r(e,t).patch},4617:e=>{"use strict";e.exports=(e,t)=>(t=t||(()=>{}),e.then(e=>new Promise(e=>{e(t())}).then(()=>e),e=>new Promise(e=>{e(t())}).then(()=>{throw e})))},4641:(e,t,n)=>{"use strict";const r=n(560);e.exports=(e,t,n)=>0===r(e,t,n)},4774:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=n(9998);t.default=class{constructor(){this._queue=[]}enqueue(e,t){const n={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority)return void this._queue.push(n);const s=r.default(this._queue,n,(e,t)=>t.priority-e.priority);this._queue.splice(s,0,n)}dequeue(){const e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this._queue.length}}},5032:(e,t,n)=>{"use strict";const r=n(8311),s=n(3904),{ANY:i}=s,a=n(7638),o=n(560),l=[new s(">=0.0.0-0")],c=[new s(">=0.0.0")],u=(e,t,n)=>{if(e===t)return!0;if(1===e.length&&e[0].semver===i){if(1===t.length&&t[0].semver===i)return!0;e=n.includePrerelease?l:c}if(1===t.length&&t[0].semver===i){if(n.includePrerelease)return!0;t=c}const r=new Set;let s,u,p,f,m,g,_;for(const t of e)">"===t.operator||">="===t.operator?s=d(s,t,n):"<"===t.operator||"<="===t.operator?u=h(u,t,n):r.add(t.semver);if(r.size>1)return null;if(s&&u){if(p=o(s.semver,u.semver,n),p>0)return null;if(0===p&&(">="!==s.operator||"<="!==u.operator))return null}for(const e of r){if(s&&!a(e,String(s),n))return null;if(u&&!a(e,String(u),n))return null;for(const r of t)if(!a(e,String(r),n))return!1;return!0}let y=!(!u||n.includePrerelease||!u.semver.prerelease.length)&&u.semver,v=!(!s||n.includePrerelease||!s.semver.prerelease.length)&&s.semver;y&&1===y.prerelease.length&&"<"===u.operator&&0===y.prerelease[0]&&(y=!1);for(const e of t){if(_=_||">"===e.operator||">="===e.operator,g=g||"<"===e.operator||"<="===e.operator,s)if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),">"===e.operator||">="===e.operator){if(f=d(s,e,n),f===e&&f!==s)return!1}else if(">="===s.operator&&!a(s.semver,String(e),n))return!1;if(u)if(y&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===y.major&&e.semver.minor===y.minor&&e.semver.patch===y.patch&&(y=!1),"<"===e.operator||"<="===e.operator){if(m=h(u,e,n),m===e&&m!==u)return!1}else if("<="===u.operator&&!a(u.semver,String(e),n))return!1;if(!e.operator&&(u||s)&&0!==p)return!1}return!(s&&g&&!u&&0!==p)&&(!(u&&_&&!s&&0!==p)&&(!v&&!y))},d=(e,t,n)=>{if(!e)return t;const r=o(e.semver,t.semver,n);return r>0?e:r<0||">"===t.operator&&">="===e.operator?t:e},h=(e,t,n)=>{if(!e)return t;const r=o(e.semver,t.semver,n);return r<0?e:r>0||"<"===t.operator&&"<="===e.operator?t:e};e.exports=(e,t,n={})=>{if(e===t)return!0;e=new r(e,n),t=new r(t,n);let s=!1;e:for(const r of e.set){for(const e of t.set){const t=u(r,e,n);if(s=s||null!==t,t)continue e}if(s)return!1}return!0}},5200:(e,t,n)=>{"use strict";const r=n(560);e.exports=(e,t,n)=>r(e,t,n)<=0},5342:(e,t,n)=>{"use strict";const r=n(7075);e.exports=(e,t,n)=>r(e,t,"<",n)},5571:(e,t,n)=>{"use strict";const r=n(7075);e.exports=(e,t,n)=>r(e,t,">",n)},5580:(e,t,n)=>{"use strict";const r=n(560);e.exports=(e,t,n)=>r(e,t,n)>0},5617:(e,t,n)=>{e.exports=n(8303)},6170:(e,t,n)=>{"use strict";const r=n(3908),s=n(144),{safeRe:i,t:a}=n(9718);e.exports=(e,t)=>{if(e instanceof r)return e;if("number"==typeof e&&(e=String(e)),"string"!=typeof e)return null;let n=null;if((t=t||{}).rtl){const r=t.includePrerelease?i[a.COERCERTLFULL]:i[a.COERCERTL];let s;for(;(s=r.exec(e))&&(!n||n.index+n[0].length!==e.length);)n&&s.index+s[0].length===n.index+n[0].length||(n=s),r.lastIndex=s.index+s[1].length+s[2].length;r.lastIndex=-1}else n=e.match(t.includePrerelease?i[a.COERCEFULL]:i[a.COERCE]);if(null===n)return null;const o=n[2],l=n[3]||"0",c=n[4]||"0",u=t.includePrerelease&&n[5]?`-${n[5]}`:"",d=t.includePrerelease&&n[6]?`+${n[6]}`:"";return s(`${o}.${l}.${c}${u}${d}`,t)}},6254:(e,t,n)=>{"use strict";const r=n(3908);e.exports=(e,t)=>new r(e,t).minor},6641:(e,t,n)=>{"use strict";const r=n(4617);class s extends Error{constructor(e){super(e),this.name="TimeoutError"}}const i=(e,t,n)=>new Promise((i,a)=>{if("number"!=typeof t||t<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(t===1/0)return void i(e);const o=setTimeout(()=>{if("function"==typeof n){try{i(n())}catch(e){a(e)}return}const r=n instanceof Error?n:new s("string"==typeof n?n:`Promise timed out after ${t} milliseconds`);"function"==typeof e.cancel&&e.cancel(),a(r)},t);r(e.then(i,a),()=>{clearTimeout(o)})});e.exports=i,e.exports.default=i,e.exports.TimeoutError=s},6780:(e,t,n)=>{"use strict";const r=n(8311);e.exports=(e,t,n)=>(e=new r(e,n),t=new r(t,n),e.intersects(t,n))},6874:e=>{"use strict";const t=Number.MAX_SAFE_INTEGER||9007199254740991;e.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:t,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}},6953:(e,t,n)=>{"use strict";const r=n(144);e.exports=(e,t)=>{const n=r(e,t);return n?n.version:null}},7007:e=>{"use strict";var t,n="object"==typeof Reflect?Reflect:null,r=n&&"function"==typeof n.apply?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};t=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function i(){i.init.call(this)}e.exports=i,e.exports.once=function(e,t){return new Promise(function(n,r){function s(n){e.removeListener(t,i),r(n)}function i(){"function"==typeof e.removeListener&&e.removeListener("error",s),n([].slice.call(arguments))}m(e,t,i,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&m(e,"error",t,n)}(e,s,{once:!0})})},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var a=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function l(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function c(e,t,n,r){var s,i,a;if(o(n),void 0===(i=e._events)?(i=e._events=Object.create(null),e._eventsCount=0):(void 0!==i.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),i=e._events),a=i[t]),void 0===a)a=i[t]=n,++e._eventsCount;else if("function"==typeof a?a=i[t]=r?[n,a]:[a,n]:r?a.unshift(n):a.push(n),(s=l(e))>0&&a.length>s&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=a.length,console&&console.warn}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},s=u.bind(r);return s.listener=n,r.wrapFn=s,s}function h(e,t,n){var r=e._events;if(void 0===r)return[];var s=r[t];return void 0===s?[]:"function"==typeof s?n?[s.listener||s]:[s]:n?function(e){for(var t=new Array(e.length),n=0;n0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var l=i[e];if(void 0===l)return!1;if("function"==typeof l)r(l,this,t);else{var c=l.length,u=f(l,c);for(n=0;n=0;i--)if(n[i]===t||n[i].listener===t){a=n[i].listener,s=i;break}if(s<0)return this;0===s?n.shift():function(e,t){for(;t+1=0;r--)this.removeListener(e,t[r]);return this},i.prototype.listeners=function(e){return h(this,e,!0)},i.prototype.rawListeners=function(e){return h(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},i.prototype.listenerCount=p,i.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},7059:(e,t,n)=>{"use strict";const r=n(560);e.exports=(e,t,n)=>r(e,t,n)<0},7075:(e,t,n)=>{"use strict";const r=n(3908),s=n(3904),{ANY:i}=s,a=n(8311),o=n(7638),l=n(5580),c=n(7059),u=n(5200),d=n(4089);e.exports=(e,t,n,h)=>{let p,f,m,g,_;switch(e=new r(e,h),t=new a(t,h),n){case">":p=l,f=u,m=c,g=">",_=">=";break;case"<":p=c,f=d,m=l,g="<",_="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(o(e,t,h))return!1;for(let n=0;n{e.semver===i&&(e=new s(">=0.0.0")),a=a||e,o=o||e,p(e.semver,a.semver,h)?a=e:m(e.semver,o.semver,h)&&(o=e)}),a.operator===g||a.operator===_)return!1;if((!o.operator||o.operator===g)&&f(e,o.semver))return!1;if(o.operator===_&&m(e,o.semver))return!1}return!0}},7272:e=>{"use strict";const t="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>{}:()=>{};e.exports=t},7414:(e,t,n)=>{"use strict";const r=n(144);e.exports=(e,t)=>{const n=r(e.trim().replace(/^[=v]+/,""),t);return n?n.version:null}},7526:(e,t)=>{"use strict";t.byteLength=function(e){var t=o(e),n=t[0],r=t[1];return 3*(n+r)/4-r},t.toByteArray=function(e){var t,n,i=o(e),a=i[0],l=i[1],c=new s(function(e,t,n){return 3*(t+n)/4-n}(0,a,l)),u=0,d=l>0?a-4:a;for(n=0;n>16&255,c[u++]=t>>8&255,c[u++]=255&t;2===l&&(t=r[e.charCodeAt(n)]<<2|r[e.charCodeAt(n+1)]>>4,c[u++]=255&t);1===l&&(t=r[e.charCodeAt(n)]<<10|r[e.charCodeAt(n+1)]<<4|r[e.charCodeAt(n+2)]>>2,c[u++]=t>>8&255,c[u++]=255&t);return c},t.fromByteArray=function(e){for(var t,r=e.length,s=r%3,i=[],a=16383,o=0,l=r-s;ol?l:o+a));1===s?(t=e[r-1],i.push(n[t>>2]+n[t<<4&63]+"==")):2===s&&(t=(e[r-2]<<8)+e[r-1],i.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return i.join("")};for(var n=[],r=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)n[a]=i[a],r[i.charCodeAt(a)]=a;function o(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function l(e){return n[e>>18&63]+n[e>>12&63]+n[e>>6&63]+n[63&e]}function c(e,t,n){for(var r,s=[],i=t;i{"use strict";const r=n(8311);e.exports=(e,t)=>new r(e,t).set.map(e=>e.map(e=>e.value).join(" ").trim().split(" "))},7638:(e,t,n)=>{"use strict";const r=n(8311);e.exports=(e,t,n)=>{try{t=new r(t,n)}catch(e){return!1}return t.test(e)}},8303:(e,t,n)=>{var r=n(3961);t.operation=function(e){var n=t.timeouts(e);return new r(n,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})},t.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var r=[],s=0;s{"use strict";const r=/\s+/g;class s{constructor(e,t){if(t=a(t),e instanceof s)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new s(e.raw,t);if(e instanceof o)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(r," "),this.set=this.raw.split("||").map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const e=this.set[0];if(this.set=this.set.filter(e=>!_(e[0])),0===this.set.length)this.set=[e];else if(this.set.length>1)for(const e of this.set)if(1===e.length&&y(e[0])){this.set=[e];break}}this.formatted=void 0}get range(){if(void 0===this.formatted){this.formatted="";for(let e=0;e0&&(this.formatted+="||");const t=this.set[e];for(let e=0;e0&&(this.formatted+=" "),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){const t=((this.options.includePrerelease&&m)|(this.options.loose&&g))+":"+e,n=i.get(t);if(n)return n;const r=this.options.loose,s=r?u[d.HYPHENRANGELOOSE]:u[d.HYPHENRANGE];e=e.replace(s,P(this.options.includePrerelease)),l("hyphen replace",e),e=e.replace(u[d.COMPARATORTRIM],h),l("comparator trim",e),e=e.replace(u[d.TILDETRIM],p),l("tilde trim",e),e=e.replace(u[d.CARETTRIM],f),l("caret trim",e);let a=e.split(" ").map(e=>b(e,this.options)).join(" ").split(/\s+/).map(e=>A(e,this.options));r&&(a=a.filter(e=>(l("loose invalid filter",e,this.options),!!e.match(u[d.COMPARATORLOOSE])))),l("range list",a);const c=new Map,y=a.map(e=>new o(e,this.options));for(const e of y){if(_(e))return[e];c.set(e.value,e)}c.size>1&&c.has("")&&c.delete("");const v=[...c.values()];return i.set(t,v),v}intersects(e,t){if(!(e instanceof s))throw new TypeError("a Range is required");return this.set.some(n=>v(n,t)&&e.set.some(e=>v(e,t)&&n.every(n=>e.every(e=>n.intersects(e,t)))))}test(e){if(!e)return!1;if("string"==typeof e)try{e=new c(e,this.options)}catch(e){return!1}for(let t=0;t"<0.0.0-0"===e.value,y=e=>""===e.value,v=(e,t)=>{let n=!0;const r=e.slice();let s=r.pop();for(;n&&r.length;)n=r.every(e=>s.intersects(e,t)),s=r.pop();return n},b=(e,t)=>(l("comp",e,t),e=k(e,t),l("caret",e),e=E(e,t),l("tildes",e),e=O(e,t),l("xrange",e),e=I(e,t),l("stars",e),e),w=e=>!e||"x"===e.toLowerCase()||"*"===e,E=(e,t)=>e.trim().split(/\s+/).map(e=>S(e,t)).join(" "),S=(e,t)=>{const n=t.loose?u[d.TILDELOOSE]:u[d.TILDE];return e.replace(n,(t,n,r,s,i)=>{let a;return l("tilde",e,t,n,r,s,i),w(n)?a="":w(r)?a=`>=${n}.0.0 <${+n+1}.0.0-0`:w(s)?a=`>=${n}.${r}.0 <${n}.${+r+1}.0-0`:i?(l("replaceTilde pr",i),a=`>=${n}.${r}.${s}-${i} <${n}.${+r+1}.0-0`):a=`>=${n}.${r}.${s} <${n}.${+r+1}.0-0`,l("tilde return",a),a})},k=(e,t)=>e.trim().split(/\s+/).map(e=>x(e,t)).join(" "),x=(e,t)=>{l("caret",e,t);const n=t.loose?u[d.CARETLOOSE]:u[d.CARET],r=t.includePrerelease?"-0":"";return e.replace(n,(t,n,s,i,a)=>{let o;return l("caret",e,t,n,s,i,a),w(n)?o="":w(s)?o=`>=${n}.0.0${r} <${+n+1}.0.0-0`:w(i)?o="0"===n?`>=${n}.${s}.0${r} <${n}.${+s+1}.0-0`:`>=${n}.${s}.0${r} <${+n+1}.0.0-0`:a?(l("replaceCaret pr",a),o="0"===n?"0"===s?`>=${n}.${s}.${i}-${a} <${n}.${s}.${+i+1}-0`:`>=${n}.${s}.${i}-${a} <${n}.${+s+1}.0-0`:`>=${n}.${s}.${i}-${a} <${+n+1}.0.0-0`):(l("no pr"),o="0"===n?"0"===s?`>=${n}.${s}.${i}${r} <${n}.${s}.${+i+1}-0`:`>=${n}.${s}.${i}${r} <${n}.${+s+1}.0-0`:`>=${n}.${s}.${i} <${+n+1}.0.0-0`),l("caret return",o),o})},O=(e,t)=>(l("replaceXRanges",e,t),e.split(/\s+/).map(e=>T(e,t)).join(" ")),T=(e,t)=>{e=e.trim();const n=t.loose?u[d.XRANGELOOSE]:u[d.XRANGE];return e.replace(n,(n,r,s,i,a,o)=>{l("xRange",e,n,r,s,i,a,o);const c=w(s),u=c||w(i),d=u||w(a),h=d;return"="===r&&h&&(r=""),o=t.includePrerelease?"-0":"",c?n=">"===r||"<"===r?"<0.0.0-0":"*":r&&h?(u&&(i=0),a=0,">"===r?(r=">=",u?(s=+s+1,i=0,a=0):(i=+i+1,a=0)):"<="===r&&(r="<",u?s=+s+1:i=+i+1),"<"===r&&(o="-0"),n=`${r+s}.${i}.${a}${o}`):u?n=`>=${s}.0.0${o} <${+s+1}.0.0-0`:d&&(n=`>=${s}.${i}.0${o} <${s}.${+i+1}.0-0`),l("xRange return",n),n})},I=(e,t)=>(l("replaceStars",e,t),e.trim().replace(u[d.STAR],"")),A=(e,t)=>(l("replaceGTE0",e,t),e.trim().replace(u[t.includePrerelease?d.GTE0PRE:d.GTE0],"")),P=e=>(t,n,r,s,i,a,o,l,c,u,d,h)=>`${n=w(r)?"":w(s)?`>=${r}.0.0${e?"-0":""}`:w(i)?`>=${r}.${s}.0${e?"-0":""}`:a?`>=${n}`:`>=${n}${e?"-0":""}`} ${l=w(c)?"":w(u)?`<${+c+1}.0.0-0`:w(d)?`<${c}.${+u+1}.0-0`:h?`<=${c}.${u}.${d}-${h}`:e?`<${c}.${u}.${+d+1}-0`:`<=${l}`}`.trim(),C=(e,t,n)=>{for(let n=0;n0){const r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}},8587:e=>{"use strict";const t=Object.freeze({loose:!0}),n=Object.freeze({});e.exports=e=>e?"object"!=typeof e?t:e:n},8794:e=>{"use strict";e.exports=class{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);return void 0===t?void 0:(this.map.delete(e),this.map.set(e,t),t)}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&void 0!==t){if(this.map.size>=this.max){const e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}},9418:(e,t,n)=>{"use strict";e=n.nmd(e);const r=(e=0)=>t=>`[${38+e};5;${t}m`,s=(e=0)=>(t,n,r)=>`[${38+e};2;${t};${n};${r}m`;Object.defineProperty(e,"exports",{enumerable:!0,get:function(){const e=new Map,t={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(const[n,r]of Object.entries(t)){for(const[n,s]of Object.entries(r))t[n]={open:`[${s[0]}m`,close:`[${s[1]}m`},r[n]=t[n],e.set(s[0],s[1]);Object.defineProperty(t,n,{value:r,enumerable:!1})}return Object.defineProperty(t,"codes",{value:e,enumerable:!1}),t.color.close="",t.bgColor.close="",t.color.ansi256=r(),t.color.ansi16m=s(),t.bgColor.ansi256=r(10),t.bgColor.ansi16m=s(10),Object.defineProperties(t,{rgbToAnsi256:{value:(e,t,n)=>e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5),enumerable:!1},hexToRgb:{value:e=>{const t=/(?[a-f\d]{6}|[a-f\d]{3})/i.exec(e.toString(16));if(!t)return[0,0,0];let{colorString:n}=t.groups;3===n.length&&(n=n.split("").map(e=>e+e).join(""));const r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,255&r]},enumerable:!1},hexToAnsi256:{value:e=>t.rgbToAnsi256(...t.hexToRgb(e)),enumerable:!1}}),t}})},9478:e=>{"use strict";e.exports=function(e,t){if("string"!=typeof e)throw new TypeError("Expected a string");return t=void 0===t?"_":t,e.replace(/([a-z\d])([A-Z])/g,"$1"+t+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+t+"$2").toLowerCase()}},9589:(e,t,n)=>{"use strict";const r=n(9718),s=n(6874),i=n(3908),a=n(1123),o=n(144),l=n(6953),c=n(7414),u=n(3007),d=n(1832),h=n(2938),p=n(6254),f=n(4493),m=n(4110),g=n(560),_=n(9970),y=n(1763),v=n(909),b=n(3927),w=n(4277),E=n(5580),S=n(7059),k=n(4641),x=n(3999),O=n(4089),T=n(5200),I=n(2111),A=n(6170),P=n(3904),C=n(8311),$=n(7638),R=n(7631),N=n(9628),j=n(270),L=n(1261),M=n(3874),D=n(7075),U=n(5571),F=n(5342),B=n(6780),q=n(2525),z=n(5032);e.exports={parse:o,valid:l,clean:c,inc:u,diff:d,major:h,minor:p,patch:f,prerelease:m,compare:g,rcompare:_,compareLoose:y,compareBuild:v,sort:b,rsort:w,gt:E,lt:S,eq:k,neq:x,gte:O,lte:T,cmp:I,coerce:A,Comparator:P,Range:C,satisfies:$,toComparators:R,maxSatisfying:N,minSatisfying:j,minVersion:L,validRange:M,outside:D,gtr:U,ltr:F,intersects:B,simplifyRange:q,subset:z,SemVer:i,re:r.re,src:r.src,tokens:r.t,SEMVER_SPEC_VERSION:s.SEMVER_SPEC_VERSION,RELEASE_TYPES:s.RELEASE_TYPES,compareIdentifiers:a.compareIdentifiers,rcompareIdentifiers:a.rcompareIdentifiers}},9628:(e,t,n)=>{"use strict";const r=n(3908),s=n(8311);e.exports=(e,t,n)=>{let i=null,a=null,o=null;try{o=new s(t,n)}catch(e){return null}return e.forEach(e=>{o.test(e)&&(i&&-1!==a.compare(e)||(i=e,a=new r(i,n)))}),i}},9718:(e,t,n)=>{"use strict";const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:s,MAX_LENGTH:i}=n(6874),a=n(7272),o=(t=e.exports={}).re=[],l=t.safeRe=[],c=t.src=[],u=t.safeSrc=[],d=t.t={};let h=0;const p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",i],[p,s]],m=(e,t,n)=>{const r=(e=>{for(const[t,n]of f)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e})(t),s=h++;a(e,s,t),d[e]=s,c[s]=t,u[s]=r,o[s]=new RegExp(t,n?"g":void 0),l[s]=new RegExp(r,n?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\d*"),m("NUMERICIDENTIFIERLOOSE","\\d+"),m("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),m("MAINVERSION",`(${c[d.NUMERICIDENTIFIER]})\\.(${c[d.NUMERICIDENTIFIER]})\\.(${c[d.NUMERICIDENTIFIER]})`),m("MAINVERSIONLOOSE",`(${c[d.NUMERICIDENTIFIERLOOSE]})\\.(${c[d.NUMERICIDENTIFIERLOOSE]})\\.(${c[d.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASEIDENTIFIER",`(?:${c[d.NONNUMERICIDENTIFIER]}|${c[d.NUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${c[d.NONNUMERICIDENTIFIER]}|${c[d.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASE",`(?:-(${c[d.PRERELEASEIDENTIFIER]}(?:\\.${c[d.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${c[d.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[d.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${p}+`),m("BUILD",`(?:\\+(${c[d.BUILDIDENTIFIER]}(?:\\.${c[d.BUILDIDENTIFIER]})*))`),m("FULLPLAIN",`v?${c[d.MAINVERSION]}${c[d.PRERELEASE]}?${c[d.BUILD]}?`),m("FULL",`^${c[d.FULLPLAIN]}$`),m("LOOSEPLAIN",`[v=\\s]*${c[d.MAINVERSIONLOOSE]}${c[d.PRERELEASELOOSE]}?${c[d.BUILD]}?`),m("LOOSE",`^${c[d.LOOSEPLAIN]}$`),m("GTLT","((?:<|>)?=?)"),m("XRANGEIDENTIFIERLOOSE",`${c[d.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),m("XRANGEIDENTIFIER",`${c[d.NUMERICIDENTIFIER]}|x|X|\\*`),m("XRANGEPLAIN",`[v=\\s]*(${c[d.XRANGEIDENTIFIER]})(?:\\.(${c[d.XRANGEIDENTIFIER]})(?:\\.(${c[d.XRANGEIDENTIFIER]})(?:${c[d.PRERELEASE]})?${c[d.BUILD]}?)?)?`),m("XRANGEPLAINLOOSE",`[v=\\s]*(${c[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[d.XRANGEIDENTIFIERLOOSE]})(?:${c[d.PRERELEASELOOSE]})?${c[d.BUILD]}?)?)?`),m("XRANGE",`^${c[d.GTLT]}\\s*${c[d.XRANGEPLAIN]}$`),m("XRANGELOOSE",`^${c[d.GTLT]}\\s*${c[d.XRANGEPLAINLOOSE]}$`),m("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),m("COERCE",`${c[d.COERCEPLAIN]}(?:$|[^\\d])`),m("COERCEFULL",c[d.COERCEPLAIN]+`(?:${c[d.PRERELEASE]})?`+`(?:${c[d.BUILD]})?(?:$|[^\\d])`),m("COERCERTL",c[d.COERCE],!0),m("COERCERTLFULL",c[d.COERCEFULL],!0),m("LONETILDE","(?:~>?)"),m("TILDETRIM",`(\\s*)${c[d.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",m("TILDE",`^${c[d.LONETILDE]}${c[d.XRANGEPLAIN]}$`),m("TILDELOOSE",`^${c[d.LONETILDE]}${c[d.XRANGEPLAINLOOSE]}$`),m("LONECARET","(?:\\^)"),m("CARETTRIM",`(\\s*)${c[d.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",m("CARET",`^${c[d.LONECARET]}${c[d.XRANGEPLAIN]}$`),m("CARETLOOSE",`^${c[d.LONECARET]}${c[d.XRANGEPLAINLOOSE]}$`),m("COMPARATORLOOSE",`^${c[d.GTLT]}\\s*(${c[d.LOOSEPLAIN]})$|^$`),m("COMPARATOR",`^${c[d.GTLT]}\\s*(${c[d.FULLPLAIN]})$|^$`),m("COMPARATORTRIM",`(\\s*)${c[d.GTLT]}\\s*(${c[d.LOOSEPLAIN]}|${c[d.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",m("HYPHENRANGE",`^\\s*(${c[d.XRANGEPLAIN]})\\s+-\\s+(${c[d.XRANGEPLAIN]})\\s*$`),m("HYPHENRANGELOOSE",`^\\s*(${c[d.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[d.XRANGEPLAINLOOSE]})\\s*$`),m("STAR","(<|>)?=?\\s*\\*"),m("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),m("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")},9970:(e,t,n)=>{"use strict";const r=n(560);e.exports=(e,t,n)=>r(t,e,n)},9998:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,n){let r=0,s=e.length;for(;s>0;){const i=s/2|0;let a=r+i;n(e[a],t)<=0?(r=++a,s-=i+1):s=i}return r}}},t={};function n(r){var s=t[r];if(void 0!==s)return s.exports;var i=t[r]={id:r,loaded:!1,exports:{}};return e[r](i,i.exports,n),i.loaded=!0,i.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),(()=>{"use strict";var e,t,r={};n.r(r),n.d(r,{JsonPatchError:()=>nr,_areEquals:()=>hr,applyOperation:()=>or,applyPatch:()=>lr,applyReducer:()=>cr,deepClone:()=>rr,getValueByPointer:()=>ar,validate:()=>dr,validator:()=>ur}),function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},e.getValidEnumValues=t=>{const n=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),r={};for(const e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(const n of e)if(t(n))return n},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(e||(e={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(t||(t={}));const s=e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),i=e=>{switch(typeof e){case"undefined":return s.undefined;case"string":return s.string;case"number":return Number.isNaN(e)?s.nan:s.number;case"boolean":return s.boolean;case"function":return s.function;case"bigint":return s.bigint;case"symbol":return s.symbol;case"object":return Array.isArray(e)?s.array:null===e?s.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?s.promise:"undefined"!=typeof Map&&e instanceof Map?s.map:"undefined"!=typeof Set&&e instanceof Set?s.set:"undefined"!=typeof Date&&e instanceof Date?s.date:s.object;default:return s.unknown}},a=e.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class o extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(r);else if("invalid_return_type"===s.code)r(s.returnTypeError);else if("invalid_arguments"===s.code)r(s.argumentsError);else if(0===s.path.length)n._errors.push(t(s));else{let e=n,r=0;for(;re.message){const t={},n=[];for(const r of this.issues)if(r.path.length>0){const n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}o.create=e=>new o(e);const l=(t,n)=>{let r;switch(t.code){case a.invalid_type:r=t.received===s.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case a.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,e.jsonStringifyReplacer)}`;break;case a.unrecognized_keys:r=`Unrecognized key(s) in object: ${e.joinValues(t.keys,", ")}`;break;case a.invalid_union:r="Invalid input";break;case a.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${e.joinValues(t.options)}`;break;case a.invalid_enum_value:r=`Invalid enum value. Expected ${e.joinValues(t.options)}, received '${t.received}'`;break;case a.invalid_arguments:r="Invalid function arguments";break;case a.invalid_return_type:r="Invalid function return type";break;case a.invalid_date:r="Invalid date";break;case a.invalid_string:"object"==typeof t.validation?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,"number"==typeof t.validation.position&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:e.assertNever(t.validation):r="regex"!==t.validation?`Invalid ${t.validation}`:"Invalid";break;case a.too_small:r="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:"number"===t.type||"bigint"===t.type?`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:"date"===t.type?`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:"Invalid input";break;case a.too_big:r="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:"number"===t.type?`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"bigint"===t.type?`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"date"===t.type?`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:"Invalid input";break;case a.custom:r="Invalid input";break;case a.invalid_intersection_types:r="Intersection results could not be merged";break;case a.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case a.not_finite:r="Number must be finite";break;default:r=n.defaultError,e.assertNever(t)}return{message:r}};let c=l;function u(){return c}var d;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(d||(d={}));const h=e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,i=[...n,...s.path||[]],a={...s,path:i};if(void 0!==s.message)return{...s,path:i,message:s.message};let o="";const l=r.filter(e=>!!e).slice().reverse();for(const e of l)o=e(a,{data:t,defaultError:o}).message;return{...s,path:i,message:o}};function p(e,t){const n=u(),r=h({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===l?void 0:l].filter(e=>!!e)});e.common.issues.push(r)}class f{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const r of t){if("aborted"===r.status)return m;"dirty"===r.status&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const e of t){const t=await e.key,r=await e.value;n.push({key:t,value:r})}return f.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const r of t){const{key:t,value:s}=r;if("aborted"===t.status)return m;if("aborted"===s.status)return m;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!r.alwaysSet||(n[t.value]=s.value)}return{status:e.value,value:n}}}const m=Object.freeze({status:"aborted"}),g=e=>({status:"dirty",value:e}),_=e=>({status:"valid",value:e}),y=e=>"aborted"===e.status,v=e=>"dirty"===e.status,b=e=>"valid"===e.status,w=e=>"undefined"!=typeof Promise&&e instanceof Promise;class E{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const S=(e,t)=>{if(b(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new o(e.common.issues);return this._error=t,this._error}}};function k(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:s};return{errorMap:(t,s)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??s.defaultError}:void 0===s.data?{message:i??r??s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:i??n??s.defaultError}},description:s}}class x{get description(){return this._def.description}_getType(e){return i(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:i(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new f,ctx:{common:e.parent.common,data:e.data,parsedType:i(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(w(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)},r=this._parseSync({data:e,path:n.path,parent:n});return S(n,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return b(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>b(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)},r=this._parse({data:e,path:n.path,parent:n}),s=await(w(r)?r:Promise.resolve(r));return S(n,s)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,r)=>{const s=e(t),i=()=>r.addIssue({code:a.custom,...n(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(i(),!1)):!!s||(i(),!1)})}refinement(e,t){return this._refinement((n,r)=>!!e(n)||(r.addIssue("function"==typeof t?t(n,r):t),!1))}_refinement(e){return new Oe({schema:this,typeName:Le.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Te.create(this,this._def)}nullable(){return Ie.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return le.create(this)}promise(){return xe.create(this,this._def)}or(e){return de.create([this,e],this._def)}and(e){return me.create(this,e,this._def)}transform(e){return new Oe({...k(this._def),schema:this,typeName:Le.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ae({...k(this._def),innerType:this,defaultValue:t,typeName:Le.ZodDefault})}brand(){return new $e({typeName:Le.ZodBranded,type:this,...k(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Pe({...k(this._def),innerType:this,catchValue:t,typeName:Le.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Re.create(this,e)}readonly(){return Ne.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const O=/^c[^\s-]{8,}$/i,T=/^[0-9a-z]+$/,I=/^[0-9A-HJKMNP-TV-Z]{26}$/i,A=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,P=/^[a-z0-9_-]{21}$/i,C=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,$=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,R=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let N;const j=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,L=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,M=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,D=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,U=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,F=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,B="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",q=new RegExp(`^${B}$`);function z(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function H(e){return new RegExp(`^${z(e)}$`)}function W(e){let t=`${B}T${z(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function G(e,t){return!("v4"!==t&&t||!j.test(e))||!("v6"!==t&&t||!M.test(e))}function K(e,t){if(!C.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return"object"==typeof s&&null!==s&&((!("typ"in s)||"JWT"===s?.typ)&&(!!s.alg&&(!t||s.alg===t)))}catch{return!1}}function J(e,t){return!("v4"!==t&&t||!L.test(e))||!("v6"!==t&&t||!D.test(e))}class Z extends x{_parse(t){this._def.coerce&&(t.data=String(t.data));if(this._getType(t)!==s.string){const e=this._getOrReturnCtx(t);return p(e,{code:a.invalid_type,expected:s.string,received:e.parsedType}),m}const n=new f;let r;for(const s of this._def.checks)if("min"===s.kind)t.data.lengths.value&&(r=this._getOrReturnCtx(t,r),p(r,{code:a.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if("length"===s.kind){const e=t.data.length>s.value,i=t.data.lengthe.test(t),{validation:t,code:a.invalid_string,...d.errToObj(n)})}_addCheck(e){return new Z({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...d.errToObj(e)})}url(e){return this._addCheck({kind:"url",...d.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...d.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...d.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...d.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...d.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...d.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...d.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...d.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...d.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...d.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...d.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...d.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...d.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...d.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...d.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...d.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...d.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...d.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...d.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...d.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...d.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...d.errToObj(t)})}nonempty(e){return this.min(1,d.errToObj(e))}trim(){return new Z({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Z({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Z({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.valuer?n:r;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}Z.create=e=>new Z({checks:[],typeName:Le.ZodString,coerce:e?.coerce??!1,...k(e)});class Y extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){this._def.coerce&&(t.data=Number(t.data));if(this._getType(t)!==s.number){const e=this._getOrReturnCtx(t);return p(e,{code:a.invalid_type,expected:s.number,received:e.parsedType}),m}let n;const r=new f;for(const s of this._def.checks)if("int"===s.kind)e.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),p(n,{code:a.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty());else if("min"===s.kind){(s.inclusive?t.datas.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),p(n,{code:a.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==V(t.data,s.value)&&(n=this._getOrReturnCtx(t,n),p(n,{code:a.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),p(n,{code:a.not_finite,message:s.message}),r.dirty()):e.assertNever(s);return{status:r.value,value:t.data}}gte(e,t){return this.setLimit("min",e,!0,d.toString(t))}gt(e,t){return this.setLimit("min",e,!1,d.toString(t))}lte(e,t){return this.setLimit("max",e,!0,d.toString(t))}lt(e,t){return this.setLimit("max",e,!1,d.toString(t))}setLimit(e,t,n,r){return new Y({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:d.toString(r)}]})}_addCheck(e){return new Y({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:d.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:d.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:d.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:d.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:d.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:d.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:d.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:d.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:d.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value"int"===t.kind||"multipleOf"===t.kind&&e.isInteger(t.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if("finite"===n.kind||"int"===n.kind||"multipleOf"===n.kind)return!0;"min"===n.kind?(null===t||n.value>t)&&(t=n.value):"max"===n.kind&&(null===e||n.valuenew Y({checks:[],typeName:Le.ZodNumber,coerce:e?.coerce||!1,...k(e)});class X extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==s.bigint)return this._getInvalidInput(t);let n;const r=new f;for(const s of this._def.checks)if("min"===s.kind){(s.inclusive?t.datas.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),p(n,{code:a.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else"multipleOf"===s.kind?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),p(n,{code:a.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):e.assertNever(s);return{status:r.value,value:t.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return p(t,{code:a.invalid_type,expected:s.bigint,received:t.parsedType}),m}gte(e,t){return this.setLimit("min",e,!0,d.toString(t))}gt(e,t){return this.setLimit("min",e,!1,d.toString(t))}lte(e,t){return this.setLimit("max",e,!0,d.toString(t))}lt(e,t){return this.setLimit("max",e,!1,d.toString(t))}setLimit(e,t,n,r){return new X({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:d.toString(r)}]})}_addCheck(e){return new X({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:d.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:d.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:d.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:d.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:d.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.valuenew X({checks:[],typeName:Le.ZodBigInt,coerce:e?.coerce??!1,...k(e)});class Q extends x{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==s.boolean){const t=this._getOrReturnCtx(e);return p(t,{code:a.invalid_type,expected:s.boolean,received:t.parsedType}),m}return _(e.data)}}Q.create=e=>new Q({typeName:Le.ZodBoolean,coerce:e?.coerce||!1,...k(e)});class ee extends x{_parse(t){this._def.coerce&&(t.data=new Date(t.data));if(this._getType(t)!==s.date){const e=this._getOrReturnCtx(t);return p(e,{code:a.invalid_type,expected:s.date,received:e.parsedType}),m}if(Number.isNaN(t.data.getTime())){return p(this._getOrReturnCtx(t),{code:a.invalid_date}),m}const n=new f;let r;for(const s of this._def.checks)"min"===s.kind?t.data.getTime()s.value&&(r=this._getOrReturnCtx(t,r),p(r,{code:a.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):e.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(e){return new ee({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:d.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:d.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.valuenew ee({checks:[],coerce:e?.coerce||!1,typeName:Le.ZodDate,...k(e)});class te extends x{_parse(e){if(this._getType(e)!==s.symbol){const t=this._getOrReturnCtx(e);return p(t,{code:a.invalid_type,expected:s.symbol,received:t.parsedType}),m}return _(e.data)}}te.create=e=>new te({typeName:Le.ZodSymbol,...k(e)});class ne extends x{_parse(e){if(this._getType(e)!==s.undefined){const t=this._getOrReturnCtx(e);return p(t,{code:a.invalid_type,expected:s.undefined,received:t.parsedType}),m}return _(e.data)}}ne.create=e=>new ne({typeName:Le.ZodUndefined,...k(e)});class re extends x{_parse(e){if(this._getType(e)!==s.null){const t=this._getOrReturnCtx(e);return p(t,{code:a.invalid_type,expected:s.null,received:t.parsedType}),m}return _(e.data)}}re.create=e=>new re({typeName:Le.ZodNull,...k(e)});class se extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return _(e.data)}}se.create=e=>new se({typeName:Le.ZodAny,...k(e)});class ie extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _(e.data)}}ie.create=e=>new ie({typeName:Le.ZodUnknown,...k(e)});class ae extends x{_parse(e){const t=this._getOrReturnCtx(e);return p(t,{code:a.invalid_type,expected:s.never,received:t.parsedType}),m}}ae.create=e=>new ae({typeName:Le.ZodNever,...k(e)});class oe extends x{_parse(e){if(this._getType(e)!==s.undefined){const t=this._getOrReturnCtx(e);return p(t,{code:a.invalid_type,expected:s.void,received:t.parsedType}),m}return _(e.data)}}oe.create=e=>new oe({typeName:Le.ZodVoid,...k(e)});class le extends x{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==s.array)return p(t,{code:a.invalid_type,expected:s.array,received:t.parsedType}),m;if(null!==r.exactLength){const e=t.data.length>r.exactLength.value,s=t.data.lengthr.maxLength.value&&(p(t,{code:a.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new E(t,e,t.path,n)))).then(e=>f.mergeArray(n,e));const i=[...t.data].map((e,n)=>r.type._parseSync(new E(t,e,t.path,n)));return f.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new le({...this._def,minLength:{value:e,message:d.toString(t)}})}max(e,t){return new le({...this._def,maxLength:{value:e,message:d.toString(t)}})}length(e,t){return new le({...this._def,exactLength:{value:e,message:d.toString(t)}})}nonempty(e){return this.min(1,e)}}function ce(e){if(e instanceof ue){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Te.create(ce(r))}return new ue({...e._def,shape:()=>t})}return e instanceof le?new le({...e._def,type:ce(e.element)}):e instanceof Te?Te.create(ce(e.unwrap())):e instanceof Ie?Ie.create(ce(e.unwrap())):e instanceof ge?ge.create(e.items.map(e=>ce(e))):e}le.create=(e,t)=>new le({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Le.ZodArray,...k(t)});class ue extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const t=this._def.shape(),n=e.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(e){if(this._getType(e)!==s.object){const t=this._getOrReturnCtx(e);return p(t,{code:a.invalid_type,expected:s.object,received:t.parsedType}),m}const{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof ae&&"strip"===this._def.unknownKeys))for(const e in n.data)i.includes(e)||o.push(e);const l=[];for(const e of i){const t=r[e],s=n.data[e];l.push({key:{status:"valid",value:e},value:t._parse(new E(n,s,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof ae){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of o)l.push({key:{status:"valid",value:e},value:{status:"valid",value:n.data[e]}});else if("strict"===e)o.length>0&&(p(n,{code:a.unrecognized_keys,keys:o}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of o){const r=n.data[t];l.push({key:{status:"valid",value:t},value:e._parse(new E(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of l){const n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>f.mergeObjectSync(t,e)):f.mergeObjectSync(t,l)}get shape(){return this._def.shape()}strict(e){return d.errToObj,new ue({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,n)=>{const r=this._def.errorMap?.(t,n).message??n.defaultError;return"unrecognized_keys"===t.code?{message:d.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new ue({...this._def,unknownKeys:"strip"})}passthrough(){return new ue({...this._def,unknownKeys:"passthrough"})}extend(e){return new ue({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ue({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Le.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ue({...this._def,catchall:e})}pick(t){const n={};for(const r of e.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new ue({...this._def,shape:()=>n})}omit(t){const n={};for(const r of e.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new ue({...this._def,shape:()=>n})}deepPartial(){return ce(this)}partial(t){const n={};for(const r of e.objectKeys(this.shape)){const e=this.shape[r];t&&!t[r]?n[r]=e:n[r]=e.optional()}return new ue({...this._def,shape:()=>n})}required(t){const n={};for(const r of e.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Te;)e=e._def.innerType;n[r]=e}return new ue({...this._def,shape:()=>n})}keyof(){return Ee(e.objectKeys(this.shape))}}ue.create=(e,t)=>new ue({shape:()=>e,unknownKeys:"strip",catchall:ae.create(),typeName:Le.ZodObject,...k(t)}),ue.strictCreate=(e,t)=>new ue({shape:()=>e,unknownKeys:"strict",catchall:ae.create(),typeName:Le.ZodObject,...k(t)}),ue.lazycreate=(e,t)=>new ue({shape:e,unknownKeys:"strip",catchall:ae.create(),typeName:Le.ZodObject,...k(t)});class de extends x{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map(async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const n=e.map(e=>new o(e.ctx.common.issues));return p(t,{code:a.invalid_union,unionErrors:n}),m});{let e;const r=[];for(const s of n){const n={...t,common:{...t.common,issues:[]},parent:null},i=s._parseSync({data:t.data,path:t.path,parent:n});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=r.map(e=>new o(e));return p(t,{code:a.invalid_union,unionErrors:s}),m}}get options(){return this._def.options}}de.create=(e,t)=>new de({options:e,typeName:Le.ZodUnion,...k(t)});const he=t=>t instanceof be?he(t.schema):t instanceof Oe?he(t.innerType()):t instanceof we?[t.value]:t instanceof Se?t.options:t instanceof ke?e.objectValues(t.enum):t instanceof Ae?he(t._def.innerType):t instanceof ne?[void 0]:t instanceof re?[null]:t instanceof Te?[void 0,...he(t.unwrap())]:t instanceof Ie?[null,...he(t.unwrap())]:t instanceof $e||t instanceof Ne?he(t.unwrap()):t instanceof Pe?he(t._def.innerType):[];class pe extends x{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.object)return p(t,{code:a.invalid_type,expected:s.object,received:t.parsedType}),m;const n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:a.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),m)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const r=new Map;for(const n of t){const t=he(n.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const s of t){if(r.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);r.set(s,n)}}return new pe({typeName:Le.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...k(n)})}}function fe(t,n){const r=i(t),a=i(n);if(t===n)return{valid:!0,data:t};if(r===s.object&&a===s.object){const r=e.objectKeys(n),s=e.objectKeys(t).filter(e=>-1!==r.indexOf(e)),i={...t,...n};for(const e of s){const r=fe(t[e],n[e]);if(!r.valid)return{valid:!1};i[e]=r.data}return{valid:!0,data:i}}if(r===s.array&&a===s.array){if(t.length!==n.length)return{valid:!1};const e=[];for(let r=0;r{if(y(e)||y(r))return m;const s=fe(e.value,r.value);return s.valid?((v(e)||v(r))&&t.dirty(),{status:t.value,value:s.data}):(p(n,{code:a.invalid_intersection_types}),m)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}me.create=(e,t,n)=>new me({left:e,right:t,typeName:Le.ZodIntersection,...k(n)});class ge extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==s.array)return p(n,{code:a.invalid_type,expected:s.array,received:n.parsedType}),m;if(n.data.lengththis._def.items.length&&(p(n,{code:a.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...n.data].map((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new E(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>f.mergeArray(t,e)):f.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new ge({...this._def,rest:e})}}ge.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ge({items:e,typeName:Le.ZodTuple,rest:null,...k(t)})};class _e extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==s.object)return p(n,{code:a.invalid_type,expected:s.object,received:n.parsedType}),m;const r=[],i=this._def.keyType,o=this._def.valueType;for(const e in n.data)r.push({key:i._parse(new E(n,e,n.path,e)),value:o._parse(new E(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?f.mergeObjectAsync(t,r):f.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){return new _e(t instanceof x?{keyType:e,valueType:t,typeName:Le.ZodRecord,...k(n)}:{keyType:Z.create(),valueType:e,typeName:Le.ZodRecord,...k(t)})}}class ye extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==s.map)return p(n,{code:a.invalid_type,expected:s.map,received:n.parsedType}),m;const r=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([e,t],s)=>({key:r._parse(new E(n,e,n.path,[s,"key"])),value:i._parse(new E(n,t,n.path,[s,"value"]))}));if(n.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const n of o){const r=await n.key,s=await n.value;if("aborted"===r.status||"aborted"===s.status)return m;"dirty"!==r.status&&"dirty"!==s.status||t.dirty(),e.set(r.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const n of o){const r=n.key,s=n.value;if("aborted"===r.status||"aborted"===s.status)return m;"dirty"!==r.status&&"dirty"!==s.status||t.dirty(),e.set(r.value,s.value)}return{status:t.value,value:e}}}}ye.create=(e,t,n)=>new ye({valueType:t,keyType:e,typeName:Le.ZodMap,...k(n)});class ve extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==s.set)return p(n,{code:a.invalid_type,expected:s.set,received:n.parsedType}),m;const r=this._def;null!==r.minSize&&n.data.sizer.maxSize.value&&(p(n,{code:a.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const i=this._def.valueType;function o(e){const n=new Set;for(const r of e){if("aborted"===r.status)return m;"dirty"===r.status&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}const l=[...n.data.values()].map((e,t)=>i._parse(new E(n,e,n.path,t)));return n.common.async?Promise.all(l).then(e=>o(e)):o(l)}min(e,t){return new ve({...this._def,minSize:{value:e,message:d.toString(t)}})}max(e,t){return new ve({...this._def,maxSize:{value:e,message:d.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ve.create=(e,t)=>new ve({valueType:e,minSize:null,maxSize:null,typeName:Le.ZodSet,...k(t)});class be extends x{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}be.create=(e,t)=>new be({getter:e,typeName:Le.ZodLazy,...k(t)});class we extends x{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:a.invalid_literal,expected:this._def.value}),m}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Ee(e,t){return new Se({values:e,typeName:Le.ZodEnum,...k(t)})}we.create=(e,t)=>new we({value:e,typeName:Le.ZodLiteral,...k(t)});class Se extends x{_parse(t){if("string"!=typeof t.data){const n=this._getOrReturnCtx(t),r=this._def.values;return p(n,{expected:e.joinValues(r),received:n.parsedType,code:a.invalid_type}),m}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const e=this._getOrReturnCtx(t),n=this._def.values;return p(e,{received:e.data,code:a.invalid_enum_value,options:n}),m}return _(t.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Se.create(e,{...this._def,...t})}exclude(e,t=this._def){return Se.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Se.create=Ee;class ke extends x{_parse(t){const n=e.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==s.string&&r.parsedType!==s.number){const t=e.objectValues(n);return p(r,{expected:e.joinValues(t),received:r.parsedType,code:a.invalid_type}),m}if(this._cache||(this._cache=new Set(e.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const t=e.objectValues(n);return p(r,{received:r.data,code:a.invalid_enum_value,options:t}),m}return _(t.data)}get enum(){return this._def.values}}ke.create=(e,t)=>new ke({values:e,typeName:Le.ZodNativeEnum,...k(t)});class xe extends x{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.promise&&!1===t.common.async)return p(t,{code:a.invalid_type,expected:s.promise,received:t.parsedType}),m;const n=t.parsedType===s.promise?t.data:Promise.resolve(t.data);return _(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}xe.create=(e,t)=>new xe({type:e,typeName:Le.ZodPromise,...k(t)});class Oe extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Le.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,i={addIssue:e=>{p(r,e),e.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===s.type){const e=s.transform(r.data,i);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===n.value)return m;const t=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===t.status?m:"dirty"===t.status||"dirty"===n.value?g(t.value):t});{if("aborted"===n.value)return m;const t=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===t.status?m:"dirty"===t.status||"dirty"===n.value?g(t.value):t}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,i);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const t=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===t.status?m:("dirty"===t.status&&n.dirty(),e(t.value),{status:n.value,value:t.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(t=>"aborted"===t.status?m:("dirty"===t.status&&n.dirty(),e(t.value).then(()=>({status:n.value,value:t.value}))))}if("transform"===s.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!b(e))return m;const t=s.transform(e.value,i);if(t instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:t}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>b(e)?Promise.resolve(s.transform(e.value,i)).then(e=>({status:n.value,value:e})):m)}e.assertNever(s)}}Oe.create=(e,t,n)=>new Oe({schema:e,typeName:Le.ZodEffects,effect:t,...k(n)}),Oe.createWithPreprocess=(e,t,n)=>new Oe({schema:t,effect:{type:"preprocess",transform:e},typeName:Le.ZodEffects,...k(n)});class Te extends x{_parse(e){return this._getType(e)===s.undefined?_(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Te.create=(e,t)=>new Te({innerType:e,typeName:Le.ZodOptional,...k(t)});class Ie extends x{_parse(e){return this._getType(e)===s.null?_(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:Le.ZodNullable,...k(t)});class Ae extends x{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===s.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:Le.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...k(t)});class Pe extends x{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return w(r)?r.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new o(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===r.status?r.value:this._def.catchValue({get error(){return new o(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Pe.create=(e,t)=>new Pe({innerType:e,typeName:Le.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...k(t)});class Ce extends x{_parse(e){if(this._getType(e)!==s.nan){const t=this._getOrReturnCtx(e);return p(t,{code:a.invalid_type,expected:s.nan,received:t.parsedType}),m}return{status:"valid",value:e.data}}}Ce.create=e=>new Ce({typeName:Le.ZodNaN,...k(e)});Symbol("zod_brand");class $e extends x{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class Re extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?m:"dirty"===e.status?(t.dirty(),g(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})()}{const e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?m:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new Re({in:e,out:t,typeName:Le.ZodPipeline})}}class Ne extends x{_parse(e){const t=this._def.innerType._parse(e),n=e=>(b(e)&&(e.value=Object.freeze(e.value)),e);return w(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}function je(e,t){const n="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof n?{message:n}:n}Ne.create=(e,t)=>new Ne({innerType:e,typeName:Le.ZodReadonly,...k(t)});ue.lazycreate;var Le;!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Le||(Le={}));const Me=(e,t={message:`Input not instance of ${e.name}`})=>function(e,t={},n){return e?se.create().superRefine((r,s)=>{const i=e(r);if(i instanceof Promise)return i.then(e=>{if(!e){const e=je(t,r),i=e.fatal??n??!0;s.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=je(t,r),i=e.fatal??n??!0;s.addIssue({code:"custom",...e,fatal:i})}}):se.create()}(t=>t instanceof e,t),De=Z.create,Ue=Y.create,Fe=(Ce.create,X.create,Q.create),Be=(ee.create,te.create,ne.create,re.create,se.create),qe=ie.create,ze=(ae.create,oe.create,le.create),He=ue.create,We=(ue.strictCreate,de.create,pe.create),Ge=(me.create,ge.create,_e.create),Ke=(ye.create,ve.create,be.create,we.create),Je=Se.create,Ze=ke.create;xe.create,Oe.create,Te.create,Ie.create,Oe.createWithPreprocess,Re.create;var Ve;!function(e){e.NAVIGATE="NAVIGATE",e.CLICK="CLICK",e.EXTRACT="EXTRACT",e.LOG="LOG",e.CONTENT_READY="CONTENT_READY",e.EXECUTE_WORKFLOW="EXECUTE_WORKFLOW",e.WORKFLOW_STATUS="WORKFLOW_STATUS",e.CONNECTION_STATUS="CONNECTION_STATUS",e.EXECUTE_QUERY="EXECUTE_QUERY",e.HEARTBEAT="HEARTBEAT",e.HEARTBEAT_ACK="HEARTBEAT_ACK",e.AGENT_STREAM_UPDATE="AGENT_STREAM_UPDATE",e.CANCEL_TASK="CANCEL_TASK",e.CLOSE_PANEL="CLOSE_PANEL",e.RESET_CONVERSATION="RESET_CONVERSATION",e.GET_TABS="GET_TABS",e.GET_TAB_HISTORY="GET_TAB_HISTORY",e.INTENT_PREDICTION_UPDATED="INTENT_PREDICTION_UPDATED",e.INTENT_BUBBLES_SHOW="INTENT_BUBBLES_SHOW",e.INTENT_BUBBLE_CLICKED="INTENT_BUBBLE_CLICKED"}(Ve||(Ve={}));const Ye=Ze(Ve),Xe=He({type:Ye,payload:qe()});We("type",[Xe.extend({type:Ke(Ve.NAVIGATE),payload:He({url:De()})}),Xe.extend({type:Ke(Ve.CLICK),payload:He({selector:De()})}),Xe.extend({type:Ke(Ve.LOG),payload:He({source:De(),message:De(),level:Je(["info","error","warning"]),timestamp:De()})}),Xe.extend({type:Ke(Ve.CONTENT_READY),payload:He({url:De(),title:De()})}),Xe.extend({type:Ke(Ve.EXECUTE_WORKFLOW),payload:He({dsl:De()})}),Xe.extend({type:Ke(Ve.WORKFLOW_STATUS),payload:He({workflowId:De(),steps:ze(He({id:De(),status:De(),message:De().optional(),error:De().optional()})),output:qe().optional()})}),Xe.extend({type:Ke(Ve.CONNECTION_STATUS),payload:He({connected:Fe(),port:De().optional()})}),Xe.extend({type:Ke(Ve.EXECUTE_QUERY),payload:He({query:De(),tabIds:ze(Ue()).optional(),source:De().optional()})}),Xe.extend({type:Ke(Ve.HEARTBEAT),payload:He({timestamp:Ue()})}),Xe.extend({type:Ke(Ve.HEARTBEAT_ACK),payload:He({timestamp:Ue()})}),Xe.extend({type:Ke(Ve.AGENT_STREAM_UPDATE),payload:He({step:Ue(),action:De(),status:Je(["thinking","executing","completed","error","debug"]),details:He({content:De().optional(),toolName:De().optional(),toolArgs:Be().optional(),toolResult:De().optional(),error:De().optional(),messageType:De().optional(),messageId:De().optional(),segmentId:Ue().optional(),data:Be().optional(),timestamp:De().optional()})})}),Xe.extend({type:Ke(Ve.CANCEL_TASK),payload:He({reason:De().optional(),source:De().optional()})}),Xe.extend({type:Ke(Ve.CLOSE_PANEL),payload:He({reason:De().optional()})}),Xe.extend({type:Ke(Ve.RESET_CONVERSATION),payload:He({source:De().optional()})}),Xe.extend({type:Ke(Ve.GET_TABS),payload:He({currentWindowOnly:Fe().default(!0)})}),Xe.extend({type:Ke(Ve.GET_TAB_HISTORY),payload:He({tabId:Ue(),limit:Ue().optional().default(5)})}),Xe.extend({type:Ke(Ve.INTENT_PREDICTION_UPDATED),payload:He({tabId:Ue(),url:De(),intents:ze(De()),confidence:Ue().optional(),timestamp:Ue(),error:De().optional()})}),Xe.extend({type:Ke(Ve.INTENT_BUBBLES_SHOW),payload:He({intents:ze(De()),confidence:Ue().optional()})}),Xe.extend({type:Ke(Ve.INTENT_BUBBLE_CLICKED),payload:He({intent:De()})})]);var Qe;!function(e){e.OPTIONS_TO_BACKGROUND="options-to-background",e.SIDEPANEL_TO_BACKGROUND="sidepanel-to-background"}(Qe||(Qe={}));Ze(Qe),He({type:Ze(Ve),payload:qe(),id:De().optional()});He({DEV_MODE:Fe(),MOCK_LLM_SETTINGS:Fe(),VERSION:De(),LOG_LEVEL:Je(["info","error","warning","debug"]).default("info")});const et={DEV_MODE:!1,MOCK_LLM_SETTINGS:!1,VERSION:"0.1.0",LOG_LEVEL:"info"};function tt(){return et.DEV_MODE}function nt(){return et.MOCK_LLM_SETTINGS}const rt=Je(["info","error","warning"]);He({source:De(),message:De(),level:rt,timestamp:De()});class st{static initialize(e={}){this.debugMode=e.debugMode||!1}static registerPort(e,t){this.connectedPorts.set(e,t)}static unregisterPort(e){this.connectedPorts.delete(e)}static log(e,t,n="info"){if(!this.debugMode&&"info"===n)return;const r={source:e,message:t,level:n,timestamp:(new Date).toISOString()};let s=!1;if(tt()){const e=this.connectedPorts.get(Qe.OPTIONS_TO_BACKGROUND);if(e)try{void 0!==e.name?(e.postMessage({type:Ve.LOG,payload:r}),s=!0):this.unregisterPort(Qe.OPTIONS_TO_BACKGROUND)}catch(e){this.unregisterPort(Qe.OPTIONS_TO_BACKGROUND),"info"!==n||t.includes("heartbeat")}}!s&&"undefined"!=typeof chrome&&chrome.runtime&&chrome.runtime.sendMessage({type:Ve.LOG,payload:r}).catch(e=>{})}}st.connectedPorts=new Map,st.debugMode=!1;var it=n(7007);const at=Je(["segment.start","segment.chunk","segment.end","tool.start","tool.stream","tool.end","tool.result","system.message","system.thinking","system.error","system.cancel","task.result","debug.message"]),ot=He({id:De(),type:at,timestamp:Ue(),source:De().optional(),data:Ge(qe())});He({segmentId:Ue(),messageId:De()}),He({segmentId:Ue(),content:De(),messageId:De()}),He({segmentId:Ue(),finalContent:De(),messageId:De()}),He({toolName:De(),displayName:De(),icon:De(),description:De(),args:Ge(qe())}),He({toolName:De(),content:De()}),He({toolName:De(),displayName:De(),result:De(),rawResult:qe().optional(),success:Fe()}),He({toolName:De(),displayName:De(),content:De(),success:Fe(),isJson:Fe().optional()}),He({message:De(),level:Je(["info","warning","error"]).default("info")}),He({message:De(),category:De().optional()}),He({error:De(),code:De().optional(),fatal:Fe().default(!1)}),He({reason:De().optional(),userInitiated:Fe().default(!0)}),He({message:De(),data:qe().optional()}),He({success:Fe(),message:De()});class lt extends it.EventEmitter{constructor(e={}){super(),this.eventBuffer=[],this.eventCounter=0,this.bufferSize=e.bufferSize||100,this.debugMode=e.debugMode||!1,this.setMaxListeners(50)}emitStreamEvent(e){const t={...e,id:this.generateEventId(),timestamp:Date.now()};try{ot.parse(t)}catch(e){return st.log("StreamEventBus",`Invalid event: ${e}`,"error"),!1}return this.addToBuffer(t),this.debugMode&&st.log("StreamEventBus",`Emitting ${t.type} event`,"info"),super.emit(t.type,t),super.emit("*",t),!0}onStreamEvent(e,t){return Array.isArray(e)?e.forEach(e=>super.on(e,t)):super.on(e,t),this}onceStreamEvent(e,t){return super.once(e,t)}offStreamEvent(e,t){return Array.isArray(e)?e.forEach(e=>super.off(e,t)):super.off(e,t),this}onFiltered(e,t){const n=n=>{e(n)&&t(n)};return super.on("*",n),()=>super.off("*",n)}async waitFor(e,t,n){return new Promise((r,s)=>{const i=t?setTimeout(()=>{super.off(e,a),s(new Error(`Timeout waiting for event: ${e}`))},t):null,a=e=>{n&&!n(e)||(i&&clearTimeout(i),r(e))};super.once(e,a)})}replay(e,t){(t?this.eventBuffer.filter(t):this.eventBuffer).forEach(t=>{try{e(t)}catch(e){st.log("StreamEventBus",`Error replaying event: ${e}`,"error")}})}getBuffer(e){return e?this.eventBuffer.filter(e):[...this.eventBuffer]}clearBuffer(){this.eventBuffer=[]}getStats(){const e={};return this.eventBuffer.forEach(t=>{e[t.type]=(e[t.type]||0)+1}),e}emitSegmentStart(e,t,n){this.emitStreamEvent({type:"segment.start",source:n,data:{segmentId:e,messageId:t}})}emitSegmentChunk(e,t,n,r){this.emitStreamEvent({type:"segment.chunk",source:r,data:{segmentId:e,content:t,messageId:n}})}emitSegmentEnd(e,t,n,r){this.emitStreamEvent({type:"segment.end",source:r,data:{segmentId:e,finalContent:t,messageId:n}})}emitToolStart(e,t){this.emitStreamEvent({type:"tool.start",source:t,data:e})}emitToolStream(e,t,n){this.emitStreamEvent({type:"tool.stream",source:n,data:{toolName:e,content:t}})}emitToolEnd(e,t){this.emitStreamEvent({type:"tool.end",source:t,data:e})}emitToolResult(e,t){this.emitStreamEvent({type:"tool.result",source:t,data:e})}emitSystemMessage(e,t="info",n){this.emitStreamEvent({type:"system.message",source:n,data:{message:e,level:t}})}emitThinking(e,t,n){this.emitStreamEvent({type:"system.thinking",source:n,data:{message:e,category:t}})}emitError(e,t,n=!1,r){this.emitStreamEvent({type:"system.error",source:r,data:{error:e,code:t,fatal:n}})}emitCancel(e,t=!0,n){this.emitStreamEvent({type:"system.cancel",source:n,data:{reason:e,userInitiated:t}})}emitDebug(e,t,n){this.debugMode&&this.emitStreamEvent({type:"debug.message",source:n,data:{message:e,data:t}})}emitTaskResult(e,t,n){this.emitStreamEvent({type:"task.result",source:n,data:{success:e,message:t}})}emitSystemError(e,t,n){this.emitError(e,t?.name,!1,n)}generateEventId(){return`evt_${Date.now()}_${++this.eventCounter}`}addToBuffer(e){for(this.eventBuffer.push(e);this.eventBuffer.length>this.bufferSize;)this.eventBuffer.shift()}}var ct;!function(e){e.SystemMessage="SystemMessage",e.ThinkingMessage="ThinkingMessage",e.NewSegment="NewSegment",e.StreamingChunk="StreamingChunk",e.FinalizeSegment="FinalizeSegment",e.ToolStart="ToolStart",e.ToolStream="ToolStream",e.ToolEnd="ToolEnd",e.ToolResult="ToolResult",e.DebugMessage="DebugMessage",e.ErrorMessage="ErrorMessage",e.CancelMessage="CancelMessage",e.TaskResult="TaskResult"}(ct||(ct={}));class ut{constructor(e,t){this.messageIdMap=new Map,this.eventBus=e,this.sendToUI=t,this.setupEventListeners()}setupEventListeners(){this.eventBus.onStreamEvent("segment.start",this.handleSegmentStart.bind(this)),this.eventBus.onStreamEvent("segment.chunk",this.handleSegmentChunk.bind(this)),this.eventBus.onStreamEvent("segment.end",this.handleSegmentEnd.bind(this)),this.eventBus.onStreamEvent("tool.start",this.handleToolStart.bind(this)),this.eventBus.onStreamEvent("tool.stream",this.handleToolStream.bind(this)),this.eventBus.onStreamEvent("tool.end",this.handleToolEnd.bind(this)),this.eventBus.onStreamEvent("tool.result",this.handleToolResult.bind(this)),this.eventBus.onStreamEvent("system.message",this.handleSystemMessage.bind(this)),this.eventBus.onStreamEvent("system.thinking",this.handleSystemThinking.bind(this)),this.eventBus.onStreamEvent("system.error",this.handleSystemError.bind(this)),this.eventBus.onStreamEvent("system.cancel",this.handleSystemCancel.bind(this)),this.eventBus.onStreamEvent("task.result",this.handleTaskResult.bind(this)),this.eventBus.onStreamEvent("debug.message",this.handleDebugMessage.bind(this))}sendUIMessage(e){this.sendToUI(Ve.AGENT_STREAM_UPDATE,{step:Date.now(),action:e.messageType,status:"executing",details:e})}handleSegmentStart(e){const{segmentId:t,messageId:n}=e.data;this.messageIdMap.set(t,n),this.sendUIMessage({messageType:ct.NewSegment,messageId:n,segmentId:t})}handleSegmentChunk(e){const{segmentId:t,content:n,messageId:r}=e.data;this.sendUIMessage({messageType:ct.StreamingChunk,messageId:r,segmentId:t,content:n})}handleSegmentEnd(e){const{segmentId:t,finalContent:n,messageId:r}=e.data;this.sendUIMessage({messageType:ct.FinalizeSegment,messageId:r,segmentId:t,content:n})}handleToolStart(e){const{toolName:t,displayName:n,icon:r,description:s,args:i}=e.data;this.sendUIMessage({messageType:ct.ToolStart,toolName:n,toolArgs:{description:s,icon:r,args:i}})}handleToolStream(e){const{toolName:t,content:n}=e.data;this.sendUIMessage({messageType:ct.ToolStream,toolName:t,content:n})}handleToolEnd(e){const{toolName:t,displayName:n,result:r}=e.data;this.sendUIMessage({messageType:ct.ToolEnd,toolName:n,toolResult:r,content:r})}handleToolResult(e){const{toolName:t,displayName:n,content:r,success:s}=e.data;this.sendUIMessage({messageType:ct.ToolResult,toolName:n,content:r,success:s})}handleSystemMessage(e){const{message:t}=e.data;this.sendUIMessage({messageType:ct.SystemMessage,content:t})}handleSystemError(e){const{error:t}=e.data;this.sendUIMessage({messageType:ct.ErrorMessage,error:t,content:t})}handleSystemCancel(e){const{reason:t,userInitiated:n}=e.data;n&&this.sendUIMessage({messageType:ct.CancelMessage,content:t||"✋ Task paused. To continue this task, just type your next request OR use 🔄 to start a new task!"})}handleSystemThinking(e){const{message:t,category:n}=e.data;this.sendUIMessage({messageType:ct.ThinkingMessage,content:t,data:{category:n}})}handleDebugMessage(e){const{message:t,data:n}=e.data;this.sendUIMessage({messageType:ct.DebugMessage,content:t,data:n})}handleTaskResult(e){const{success:t,message:n}=e.data;this.sendUIMessage({messageType:ct.TaskResult,content:n,success:t})}destroy(){this.eventBus.removeAllListeners(),this.messageIdMap.clear()}replay(){this.eventBus.replay(e=>{this.eventBus.emitStreamEvent(e)})}}function dt(e,t){if(!t.ok){return`❌ Error in ${e}: ${t.error||"Unknown error occurred"}`}const n=t.output;if(!n)return"No output available.";switch(e){case"planner_tool":{if(!n.steps||!Array.isArray(n.steps))return"```json\n"+JSON.stringify(n,null,2)+"\n```";let e="#### 📋 Execution Plan\n\n";return n.steps.forEach((t,n)=>{e+=`**Step ${n+1}:** ${t.action}\n`,t.reasoning&&(e+=`*Reasoning:* ${t.reasoning}\n`),e+="\n"}),e.trim()}case"tab_operations_tool":{let e=n;if("string"==typeof n)try{e=JSON.parse(n)}catch{return n}if(!Array.isArray(e))return"```json\n"+JSON.stringify(e,null,2)+"\n```";if(0===e.length)return"#### 📑 No Open Tabs";let t=`#### 📑 Open Tabs (${e.length})\n\n`;return t+="| ID | Title | URL |\n| -- | ----- | --- |\n",e.forEach(e=>{const n=e.title||"Untitled",r=e.url||"",s=n.length>50?n.substring(0,47)+"...":n,i=r.length>60?r.substring(0,57)+"...":r;t+=`| ${e.id} | ${s} | ${i} |\n`}),t.trim()}case"validator_tool":{let e="#### ✅ Validation Result\n\n";return e+=`**Complete?** ${n.isComplete?"Yes ✓":"No ✗"}\n\n`,n.reasoning&&(e+=`**Reasoning:** ${n.reasoning}\n\n`),n.suggestions&&Array.isArray(n.suggestions)&&n.suggestions.length>0&&(e+="**Suggestions:**\n",n.suggestions.forEach(t=>e+=`- ${t}\n`)),e.trim()}case"navigation_tool":return`#### 🧭 Navigation\n\n**URL:** ${n.url||"Unknown URL"}\n**Status:** ${void 0!==n.success?n.success?"✓ Success":"✗ Failed":"Complete"}`;case"find_element_tool":{if(!n.elements||!Array.isArray(n.elements))return"```json\n"+JSON.stringify(n,null,2)+"\n```";if(0===n.elements.length)return"#### 🔍 No Elements Found";let e=`#### 🔍 Found ${n.elements.length} Element${n.elements.length>1?"s":""}\n\n`;return n.elements.forEach((t,n)=>{e+=`**Element ${n+1}:**\n`,t.selector&&(e+=`- Selector: \`${t.selector}\`\n`),t.text&&(e+=`- Text: "${t.text}"\n`),t.position&&(e+=`- Position: (${t.position.x}, ${t.position.y})\n`),e+="\n"}),e.trim()}case"classification_tool":return`#### 🏷️ Task Classification\n\n**Type:** ${n.is_simple_task?"Simple":"Complex"} Task`;case"interaction_tool":{let e="#### 🖱️ Interaction\n\n";return n.action&&(e+=`**Action:** ${n.action}\n`),n.element&&(e+=`**Element:** ${n.element}\n`),e+="**Status:** "+(n.success?"✓ Success":"✗ Failed"),e.trim()}case"scroll_tool":{let e="#### 📜 Scroll\n\n";return n.direction&&(e+=`**Direction:** ${n.direction}\n`),void 0!==n.amount&&(e+=`**Amount:** ${n.amount}px\n`),e+="**Status:** "+(n.success?"✓ Success":"✗ Failed"),e.trim()}case"search_tool":{if(!n.matches||!Array.isArray(n.matches))return"```json\n"+JSON.stringify(n,null,2)+"\n```";let e="#### 🔎 Search Results\n\n";return n.query&&(e+=`**Query:** "${n.query}"\n\n`),0===n.matches.length?e+="*No matches found*":(e+=`**Found ${n.matches.length} match${n.matches.length>1?"es":""}:**\n\n`,n.matches.forEach((t,n)=>{e+=`${n+1}. "${t.text}"\n`,t.selector&&(e+=` Selector: \`${t.selector}\`\n`)})),e.trim()}case"refresh_browser_state":case"refresh_state_tool":return"#### 🔄 Browser State Refreshed\n\nCurrent page state has been captured and updated.";case"group_tabs_tool":{if(!n.groups||!Array.isArray(n.groups))return"```json\n"+JSON.stringify(n,null,2)+"\n```";let e="#### 📁 Tab Groups\n\n";return n.groups.forEach(t=>{e+=`**${t.name||"Unnamed Group"}**\n`,t.tabs&&Array.isArray(t.tabs)&&t.tabs.forEach(t=>{e+=`- ${t.title||"Untitled"}\n`}),e+="\n"}),e.trim()}case"done_tool":{let e="#### 🎉 Task Complete\n\n";return n.message?e+=n.message:n.status?e+=`Status: ${n.status}`:e+="The task has been completed successfully.",e}case"todo_manager":return"string"==typeof n?n:"```json\n"+JSON.stringify(n,null,2)+"\n```";default:return"```json\n"+JSON.stringify(n,null,2)+"\n```"}}class ht{constructor(e){this.currentSegmentId=0,this.currentMessageId="",this.eventBus=e}startThinking(){return this.currentSegmentId++,this.currentMessageId=this._generateMessageId(),this.eventBus.emitSegmentStart(this.currentSegmentId,this.currentMessageId,"BrowserAgent"),this.currentMessageId}streamThoughtDuringThinking(e){this.currentMessageId&&this.eventBus.emitSegmentChunk(this.currentSegmentId,e,this.currentMessageId,"BrowserAgent")}finishThinking(e){this.currentMessageId&&this.eventBus.emitSegmentEnd(this.currentSegmentId,e,this.currentMessageId,"BrowserAgent")}executingTool(e,t){const n=this._getToolDisplayInfo(e,t);this.eventBus.emitToolStart({toolName:e,displayName:n.name,icon:n.icon,description:n.description,args:t||{}},"BrowserAgent")}toolEnd(e,t,n){const r=this._getToolDisplayInfo(e).name;this.eventBus.emitToolEnd({toolName:e,displayName:r,result:n||(t?"Completed":"Failed"),rawResult:{},success:t},"BrowserAgent")}emitToolResult(e,t){const n=this._getToolDisplayInfo(e).name;let r,s=!1;try{r=JSON.parse(t),s=r.ok||!1}catch{r={ok:!0,output:t},s=!0}const i=dt(e,r);this.eventBus.emitToolResult({toolName:e,displayName:n,content:i,success:s,isJson:!0},"BrowserAgent")}info(e){this.eventBus.emitSystemMessage(e,"info","BrowserAgent")}error(e,t=!1){this.eventBus.emitError(e,void 0,t,"BrowserAgent")}debug(e,t){this.eventBus.emitDebug(e,t,"BrowserAgent")}emitTaskResult(e,t){this.eventBus.emitTaskResult(e,t,"BrowserAgent")}_generateMessageId(){return`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}_getToolDisplayInfo(e,t){const n={classification_tool:{name:"Task Analysis",icon:"🔍",description:()=>"Analyzing task complexity"},planner_tool:{name:"Planning",icon:"📋",description:e=>`Creating ${e?.max_steps||3}-step plan`},navigation_tool:{name:"Navigation",icon:"🌐",description:e=>e?.url?`Navigating to ${e.url}`:"Navigating to page"},tab_operations_tool:{name:"Tab Operations",icon:"📑",description:e=>"list"===e?.action?"Listing tabs in current window":"list_all"===e?.action?"Listing all tabs":"new"===e?.action?"Creating new tab":"switch"===e?.action?"Switching tabs":"close"===e?.action?"Closing tabs":e?.action||"Managing tabs"},done_tool:{name:"Completion",icon:"✅",description:()=>"Marking task as complete"}}[e]||{name:e,icon:"🔧",description:()=>`Executing ${e}`};return{name:n.name,icon:n.icon,description:n.description?n.description(t):`Executing ${n.name}`}}}class pt{constructor(){}static getInstance(){return pt.instance||(pt.instance=new pt),pt.instance}async getInteractiveSnapshot(e,t){try{return st.log("BrowserOSAdapter",`Getting interactive snapshot for tab ${e} with options: ${JSON.stringify(t)}`,"info"),new Promise((n,r)=>{t?chrome.browserOS.getInteractiveSnapshot(e,t,e=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):(st.log("BrowserOSAdapter",`Retrieved snapshot with ${e.elements.length} elements`,"info"),n(e))}):chrome.browserOS.getInteractiveSnapshot(e,e=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):(st.log("BrowserOSAdapter",`Retrieved snapshot with ${e.elements.length} elements`,"info"),n(e))})})}catch(e){const t=e instanceof Error?e.message:String(e);throw st.log("BrowserOSAdapter",`Failed to get interactive snapshot: ${t}`,"error"),new Error(`Failed to get interactive snapshot: ${t}`)}}async click(e,t){try{return st.log("BrowserOSAdapter",`Clicking node ${t} in tab ${e}`,"info"),new Promise((n,r)=>{chrome.browserOS.click(e,t,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):n()})})}catch(e){const n=e instanceof Error?e.message:String(e);throw st.log("BrowserOSAdapter",`Failed to click node: ${n}`,"error"),new Error(`Failed to click node ${t}: ${n}`)}}async inputText(e,t,n){try{return st.log("BrowserOSAdapter",`Inputting text into node ${t} in tab ${e}`,"info"),new Promise((r,s)=>{chrome.browserOS.inputText(e,t,n,()=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):r()})})}catch(e){const n=e instanceof Error?e.message:String(e);throw st.log("BrowserOSAdapter",`Failed to input text: ${n}`,"error"),new Error(`Failed to input text into node ${t}: ${n}`)}}async clear(e,t){try{return st.log("BrowserOSAdapter",`Clearing node ${t} in tab ${e}`,"info"),new Promise((n,r)=>{chrome.browserOS.clear(e,t,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):n()})})}catch(e){const n=e instanceof Error?e.message:String(e);throw st.log("BrowserOSAdapter",`Failed to clear node: ${n}`,"error"),new Error(`Failed to clear node ${t}: ${n}`)}}async scrollToNode(e,t){try{return st.log("BrowserOSAdapter",`Scrolling to node ${t} in tab ${e}`,"info"),new Promise((n,r)=>{chrome.browserOS.scrollToNode(e,t,e=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):n(e)})})}catch(e){const n=e instanceof Error?e.message:String(e);throw st.log("BrowserOSAdapter",`Failed to scroll to node: ${n}`,"error"),new Error(`Failed to scroll to node ${t}: ${n}`)}}async sendKeys(e,t){try{return st.log("BrowserOSAdapter",`Sending keys "${t}" to tab ${e}`,"info"),new Promise((n,r)=>{chrome.browserOS.sendKeys(e,t,()=>{chrome.runtime.lastError?r(new Error(chrome.runtime.lastError.message)):n()})})}catch(e){const t=e instanceof Error?e.message:String(e);throw st.log("BrowserOSAdapter",`Failed to send keys: ${t}`,"error"),new Error(`Failed to send keys: ${t}`)}}async getPageLoadStatus(e){try{return st.log("BrowserOSAdapter",`Getting page load status for tab ${e}`,"info"),new Promise((t,n)=>{chrome.browserOS.getPageLoadStatus(e,e=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):t(e)})})}catch(e){const t=e instanceof Error?e.message:String(e);throw st.log("BrowserOSAdapter",`Failed to get page load status: ${t}`,"error"),new Error(`Failed to get page load status: ${t}`)}}async getAccessibilityTree(e){try{return st.log("BrowserOSAdapter",`Getting accessibility tree for tab ${e}`,"info"),new Promise((t,n)=>{chrome.browserOS.getAccessibilityTree(e,e=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):t(e)})})}catch(e){const t=e instanceof Error?e.message:String(e);throw st.log("BrowserOSAdapter",`Failed to get accessibility tree: ${t}`,"error"),new Error(`Failed to get accessibility tree: ${t}`)}}async captureScreenshot(e){try{return st.log("BrowserOSAdapter",`Capturing screenshot for tab ${e}`,"info"),new Promise((t,n)=>{chrome.browserOS.captureScreenshot(e,r=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):(st.log("BrowserOSAdapter",`Screenshot captured for tab ${e}`,"info"),t(r))})})}catch(e){const t=e instanceof Error?e.message:String(e);throw st.log("BrowserOSAdapter",`Failed to capture screenshot: ${t}`,"error"),new Error(`Failed to capture screenshot: ${t}`)}}async getSnapshot(e,t,n){try{return st.log("BrowserOSAdapter",`Getting ${t} snapshot for tab ${e} with options: ${JSON.stringify(n)}`,"info"),new Promise((r,s)=>{n?chrome.browserOS.getSnapshot(e,t,n,e=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):(st.log("BrowserOSAdapter",`Retrieved ${t} snapshot with ${e.sections.length} sections`,"info"),r(e))}):chrome.browserOS.getSnapshot(e,t,e=>{chrome.runtime.lastError?s(new Error(chrome.runtime.lastError.message)):(st.log("BrowserOSAdapter",`Retrieved ${t} snapshot with ${e.sections.length} sections`,"info"),r(e))})})}catch(e){const n=e instanceof Error?e.message:String(e);throw st.log("BrowserOSAdapter",`Failed to get ${t} snapshot: ${n}`,"error"),new Error(`Failed to get ${t} snapshot: ${n}`)}}async getTextSnapshot(e,t){return this.getSnapshot(e,"text",t)}async getLinksSnapshot(e,t){return this.getSnapshot(e,"links",t)}async invokeAPI(e,...t){try{if(st.log("BrowserOSAdapter",`Invoking BrowserOS API: ${e}`,"info"),!(e in chrome.browserOS))throw new Error(`Unknown BrowserOS API method: ${e}`);return await chrome.browserOS[e](...t)}catch(t){const n=t instanceof Error?t.message:String(t);throw st.log("BrowserOSAdapter",`Failed to invoke API ${e}: ${n}`,"error"),new Error(`Failed to invoke BrowserOS API ${e}: ${n}`)}}isAPIAvailable(e){return e in chrome.browserOS}getAvailableAPIs(){return Object.keys(chrome.browserOS).filter(e=>"function"==typeof chrome.browserOS[e])}}pt.instance=null;const ft=new Map,mt=[],gt=[];let _t=null;function yt(e){return null===_t&&(_t=e),Math.round(1e3*(e-_t))}function vt(e){if(et.DEV_MODE)try{const t=performance.now();ft.set(e,t),mt.push(e),performance.mark(`${e}-start`),gt.push({name:e,cat:"profile",ph:"B",ts:yt(t),pid:1,tid:1})}catch(e){}}function bt(e){if(et.DEV_MODE)try{const t=ft.get(e);if(void 0!==t){const t=performance.now();ft.delete(e);const n=mt.lastIndexOf(e);-1!==n&&mt.splice(n,1),performance.mark(`${e}-end`),performance.measure(e,`${e}-start`,`${e}-end`),gt.push({name:e,cat:"profile",ph:"E",ts:yt(t),pid:1,tid:1}),performance.clearMarks(`${e}-start`),performance.clearMarks(`${e}-end`)}}catch(e){}}async function wt(e,t){vt(e);try{return await t()}finally{bt(e)}}function Et(){if(!et.DEV_MODE)return[];try{return performance.getEntriesByType("measure")}catch(e){return[]}}function St(){}function kt(){if(!et.DEV_MODE)return{totalTime:0,totalCount:0,avgTime:0,topOperations:[],frequentOperations:[]};const e=Et();if(0===e.length)return{totalTime:0,totalCount:0,avgTime:0,topOperations:[],frequentOperations:[]};let t=0;const n={};e.forEach(e=>{t+=e.duration,n[e.name]||(n[e.name]={count:0,totalDuration:0,maxDuration:0}),n[e.name].count++,n[e.name].totalDuration+=e.duration,n[e.name].maxDuration=Math.max(n[e.name].maxDuration,e.duration)});const r=t/e.length,s=Object.entries(n).map(([e,t])=>({name:e,count:t.count,totalDuration:t.totalDuration,avgDuration:t.totalDuration/t.count,maxDuration:t.maxDuration})),i=[...s].sort((e,t)=>t.maxDuration-e.maxDuration).slice(0,5).map(e=>({name:e.name,duration:e.maxDuration,count:e.count,avgDuration:e.avgDuration})),a=[...s].sort((e,t)=>t.count-e.count).slice(0,5).map(e=>({name:e.name,count:e.count,totalDuration:e.totalDuration,avgDuration:e.avgDuration}));return{totalTime:t,totalCount:e.length,avgTime:r,topOperations:i,frequentOperations:a}}function xt(){}function Ot(){if(!et.DEV_MODE)return'{"traceEvents":[]}';const e={traceEvents:[{name:"process_name",ph:"M",ts:0,pid:1,tid:1,cat:"__metadata",args:{name:"Browser Extension"}},{name:"thread_name",ph:"M",ts:0,pid:1,tid:1,cat:"__metadata",args:{name:"Main Thread"}},...gt]};return JSON.stringify(e)}function Tt(){if(!et.DEV_MODE)return"[]";const e=[{name:"process_name",ph:"M",ts:0,pid:1,tid:1,cat:"__metadata",args:{name:"Browser Extension"}},{name:"thread_name",ph:"M",ts:0,pid:1,tid:1,cat:"__metadata",args:{name:"Main Thread"}},...gt];return JSON.stringify(e)}function It(){gt.length=0,mt.length=0,_t=null,ft.clear()}function At(){return gt.length}function Pt(){et.DEV_MODE&&(It(),vt("main"),vt("processData"),vt("fetchData"),bt("fetchData"),vt("parseData"),bt("parseData"),bt("processData"),vt("renderResults"),bt("renderResults"),bt("main"))}et.DEV_MODE&&(globalThis.__profileReport=St,globalThis.__profileMeasures=Et,globalThis.__profileStart=vt,globalThis.__profileEnd=bt,globalThis.__profileSummary=xt,globalThis.__profileGetSummary=kt,globalThis.__profileExportTrace=Ot,globalThis.__profileExportTraceLegacy=Tt,globalThis.__profileClearTrace=It,globalThis.__profileTraceCount=At,globalThis.__profileTestTrace=Pt,globalThis.profiler={start:vt,end:bt,report:St,measures:Et,summary:xt,getSummary:kt,exportTrace:Ot,exportTraceLegacy:Tt,clearTrace:It,traceCount:At,testTrace:Pt});const Ct=["type","placeholder","value","aria-label"];He({nodeId:Ue(),text:De(),tag:De()});function $t(e){switch(e){case"clickable":case"selectable":return"C";case"typeable":return"T";default:return"O"}}function Rt(e,t){return!e||e.length<=t?e:e.substring(0,t-3)+"..."}function Nt(e){if(!e.attributes)return"";const t=[];for(const n of Ct){const r=e.attributes[n];r&&t.push(`${n}=${r}`)}return t.length>0?`attr:"${t.join(" ")}"`:""}function jt(e){if(!e)return"";const t=e.split(" > ").filter(e=>e&&"root"!==e),n=t.slice(-3);return n.length>0?`path:"${n.join(">")}"`:""}const Lt=class{constructor(e,t,n){this._browserOS=pt.getInstance(),this._cachedSnapshot=null,this._nodeIdToNodeMap=new Map,this._cacheTimestamp=0,this._cacheExpiryMs=5e3,this._tabId=e,this._url=t,this._title=n,st.log("BrowserPage",`Page created for tab ${this._tabId}`)}get tabId(){return this._tabId}url(){return this._url}async title(){try{const e=await chrome.tabs.get(this._tabId);return this._title=e.title||"",this._title}catch{return this._title}}_invalidateCache(){this._cachedSnapshot=null,this._cacheTimestamp=0,this._nodeIdToNodeMap.clear(),st.log("BrowserPage",`Cache invalidated for tab ${this._tabId}`,"info")}_isCacheValid(){return null!==this._cachedSnapshot&&this._cacheTimestamp>0&&Date.now()-this._cacheTimestamp{if(this._isCacheValid())return st.log("BrowserPage",`Using cached snapshot for tab ${this._tabId}`,"info"),this._cachedSnapshot;try{st.log("BrowserPage",`Fetching fresh snapshot for tab ${this._tabId}`,"info");const e=await this._browserOS.getInteractiveSnapshot(this._tabId);this._cachedSnapshot=e,this._cacheTimestamp=Date.now(),this._nodeIdToNodeMap.clear();for(const t of e.elements)"clickable"!==t.type&&"typeable"!==t.type&&"selectable"!==t.type||this._nodeIdToNodeMap.set(t.nodeId,t);return e}catch(e){return st.log("BrowserPage",`Failed to get snapshot: ${e}`,"error"),this._invalidateCache(),null}})}async getElementsAsString(){return wt("BrowserPage.getElementsAsString",async()=>{const e=await this._getSnapshot();if(!e)return"No interactive elements found";const t=[];for(const n of e.elements){if("other"===n.type)continue;const e=[],r=parseInt(n.attributes?.depth||"0",10),s=" ".repeat(r);e.push(`${s}[${n.nodeId}]`),e.push(`<${$t(n.type)}>`);const i=n.attributes?.["html-tag"]||n.attributes?.role||"div";e.push(`<${i}>`),n.name&&e.push(`"${Rt(n.name,40)}"`),n.attributes?.context&&e.push(`ctx:"${Rt(n.attributes.context,60)}"`),n.attributes?.path&&e.push(jt(n.attributes.path));const a=Nt(n);a&&e.push(a),t.push(e.join(" "))}return t.join("\n")})}async getClickableElementsString(){const e=await this._getSnapshot();if(!e)return"";const t=[];for(const n of e.elements)if("clickable"===n.type||"selectable"===n.type){const e=[],r=parseInt(n.attributes?.depth||"0",10),s=" ".repeat(r);e.push(`${s}[${n.nodeId}]`),e.push("");const i=n.attributes?.["html-tag"]||n.attributes?.role||"div";e.push(`<${i}>`),n.name&&e.push(`"${Rt(n.name,40)}"`),n.attributes?.context&&e.push(`ctx:"${Rt(n.attributes.context,60)}"`),n.attributes?.path&&e.push(jt(n.attributes.path));const a=Nt(n);a&&e.push(a),t.push(e.join(" "))}return t.join("\n")}async getTypeableElementsString(){const e=await this._getSnapshot();if(!e)return"";const t=[];for(const n of e.elements)if("typeable"===n.type){const e=[],r=parseInt(n.attributes?.depth||"0",10),s=" ".repeat(r);e.push(`${s}[${n.nodeId}]`),e.push("");const i=n.attributes?.["html-tag"]||n.attributes?.role||"input";e.push(`<${i}>`);const a=n.name||n.attributes?.placeholder||"";a&&e.push(`"${Rt(a,40)}"`),n.attributes?.context&&e.push(`ctx:"${Rt(n.attributes.context,60)}"`),n.attributes?.path&&e.push(jt(n.attributes.path));const o=Nt(n);o&&e.push(o),t.push(e.join(" "))}return t.join("\n")}async getClickableElements(){const e=await this._getSnapshot();if(!e)return[];const t=[];for(const n of e.elements)"clickable"!==n.type&&"selectable"!==n.type||t.push({nodeId:n.nodeId,text:n.name||"",tag:n.attributes?.["html-tag"]||n.attributes?.role||""});return t}async getTypeableElements(){const e=await this._getSnapshot();if(!e)return[];const t=[];for(const n of e.elements)"typeable"===n.type&&t.push({nodeId:n.nodeId,text:n.name||"",tag:n.attributes?.["html-tag"]||n.attributes?.role||""});return t}async getElementByIndex(e){return this._cachedSnapshot||await this._getSnapshot(),this._nodeIdToNodeMap.get(e)||null}async getInteractiveElements(){return await this._getSnapshot(),new Map(this._nodeIdToNodeMap)}async getHierarchicalStructure(){const e=await this._getSnapshot();return e?.hierarchicalStructure||null}async clickElement(e){await wt(`BrowserPage.clickElement[${e}]`,async()=>{await this._browserOS.click(this._tabId,e),this._invalidateCache(),await this.waitForStability()})}async inputText(e,t){await wt(`BrowserPage.inputText[${e}]`,async()=>{await this._browserOS.clear(this._tabId,e),await this._browserOS.inputText(this._tabId,e,t),this._invalidateCache(),await this.waitForStability()})}async clearElement(e){await this._browserOS.clear(this._tabId,e),this._invalidateCache(),await this.waitForStability()}async scrollToElement(e){return await this._browserOS.scrollToNode(this._tabId,e)}async sendKeys(e){const t=["Enter","Delete","Backspace","Tab","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown"];if(!t.includes(e))throw new Error(`Unsupported key: "${e}". Supported keys are: ${t.join(", ")}`);await this._browserOS.sendKeys(this._tabId,e);["Enter","Delete","Backspace","Tab"].includes(e)&&this._invalidateCache(),await this.waitForStability()}async scrollDown(e){const t=e||1;for(let e=0;esetTimeout(e,50))}async scrollUp(e){const t=e||1;for(let e=0;esetTimeout(e,50))}async navigateTo(e){await wt("BrowserPage.navigateTo",async()=>{await chrome.tabs.update(this._tabId,{url:e}),this._invalidateCache(),await this.waitForStability(),this._url=e})}async refreshPage(){await chrome.tabs.reload(this._tabId),this._invalidateCache(),await this.waitForStability()}async goBack(){await chrome.tabs.goBack(this._tabId),this._invalidateCache(),await this.waitForStability()}async goForward(){await chrome.tabs.goForward(this._tabId),this._invalidateCache(),await this.waitForStability()}invalidateCache(){this._invalidateCache()}async waitForStability(){await wt("BrowserPage.waitForStability",async()=>{const e=3e4,t=Date.now();for(;Date.now()-tsetTimeout(e,100))}Date.now()-t>=e&&st.log("BrowserPage",`waitForStability timeout after 30000ms for tab ${this._tabId}`,"warning")})}async takeScreenshot(){try{const e=await this._browserOS.captureScreenshot(this._tabId);return e.split(",")[1]||e}catch(e){return st.log("BrowserPage",`Failed to take screenshot: ${e}`,"error"),null}}async close(){try{await chrome.tabs.remove(this._tabId)}catch(e){st.log("BrowserPage",`Error closing tab: ${e}`,"error")}}async getTextSnapshot(e){return await this._browserOS.getTextSnapshot(this._tabId,e)}async getLinksSnapshot(e){return await this._browserOS.getLinksSnapshot(this._tabId,e)}isFileUploader(e){return"input"===e.tagName&&"file"===e.attributes?.type}async getDropdownOptions(e){throw new Error("Not implemented")}async selectDropdownOption(e,t){throw new Error("Not implemented")}async getBrowserState(){return{tabId:this._tabId,url:this._url,title:this._title}}},Mt=(He({width:Ue().int().positive(),height:Ue().int().positive()}),He({maximumWaitPageLoadTime:Ue().default(5),waitBetweenActions:Ue().default(.1),homePageUrl:De().default("https://www.google.com"),useVision:Fe().default(!0)}).parse({})),Dt=He({id:Ue().int().positive(),url:De(),title:De()});He({tabId:Ue(),url:De(),title:De(),tabs:ze(Dt),clickableElements:ze(He({nodeId:Ue(),text:De(),tag:De()})),typeableElements:ze(He({nodeId:Ue(),text:De(),tag:De()})),clickableElementsString:De(),typeableElementsString:De(),hierarchicalStructure:De().nullable().optional(),screenshot:De().nullable().optional()});Error;class Ut{constructor(e={}){this._userSelectedTabIds=null,this._executionLockedTabId=null,this._pageCache=new Map,this._config={...Mt,...e}}getConfig(){return this._config}updateConfig(e){this._config={...this._config,...e}}async _getOrCreatePage(e){if(!e.id)throw new Error("Tab ID is not available");const t=this._pageCache.get(e.id);if(t)return t;const n=new Lt(e.id,e.url||"Unknown URL",e.title||"Unknown Title");return this._pageCache.set(e.id,n),st.log("BrowserContextV2",`Created page for tab ${e.id}`),n}async getCurrentPage(){return wt("BrowserContext.getCurrentPage",async()=>{const e=await this.getTargetTab();if(!e.id)throw new Error("Target tab has no ID");const t=await this._getOrCreatePage(e);return this._executionLockedTabId||this.lockExecutionToTab(e.id),t})}async switchTab(e){return wt(`BrowserContext.switchTab[${e}]`,async()=>{st.log("BrowserContextV2",`Switching to tab ${e}`),await chrome.tabs.update(e,{active:!0});const t=await chrome.tabs.get(e),n=await this._getOrCreatePage(t);return this._executionLockedTabId=e,n})}async getTabs(){const e=await chrome.tabs.query({}),t=[];for(const n of e)n.id&&n.url&&n.title&&t.push({id:n.id,url:n.url,title:n.title});return t}async navigateTo(e){const t=await this.getCurrentPage();await t.navigateTo(e)}async openTab(e){return wt("BrowserContext.openTab",async()=>{const t=await chrome.tabs.create({url:e,active:!0});if(!t.id)throw new Error("No tab ID available");await new Promise(e=>setTimeout(e,100));const n=await chrome.tabs.get(t.id),r=await this._getOrCreatePage(n);return this._executionLockedTabId=t.id,r})}async closeTab(e){this._pageCache.delete(e),await chrome.tabs.remove(e),this._executionLockedTabId===e&&(this._executionLockedTabId=null),this._userSelectedTabIds&&this._userSelectedTabIds.includes(e)&&(this._userSelectedTabIds=this._userSelectedTabIds.filter(t=>t!==e))}async getBrowserStateString(){return wt("BrowserContext.getBrowserStateString",async()=>{try{const e=await this.getBrowserState(),t=`{id: ${e.tabId}, url: ${e.url}, title: ${e.title}}`,n=e.tabs.filter(t=>t.id!==e.tabId).map(e=>`- {id: ${e.id}, url: ${e.url}, title: ${e.title}}`),r=(new Date).toISOString().slice(0,16).replace("T"," ");let s="";const i=[];e.clickableElementsString&&i.push("Clickable elements:\n"+e.clickableElementsString),e.typeableElementsString&&i.push("Input fields:\n"+e.typeableElementsString),s=i.join("\n\n")||"No interactive elements found";return`\nBROWSER STATE:\nCurrent tab: ${t}\nOther available tabs:\n ${n.join("\n ")}\nCurrent date and time: ${r}\n\nInteractive elements from the current page (numbers in [brackets] are nodeIds):\n${s}\n`}catch(e){st.log("BrowserContextV2",`Failed to get detailed browser state: ${e}`,"warning");const t=await this.getCurrentPage();return`BROWSER STATE:\nCurrent page: ${await t.url()} - ${await t.title()}`}})}async getPages(e){try{if(!e||0===e.length){return[await this.getCurrentPage()]}const t=[];for(const n of e)try{const e=await chrome.tabs.get(n),r=await this._getOrCreatePage(e);t.push(r)}catch(e){st.log("BrowserContextV2",`Failed to get page for tab ${n}: ${e}`,"warning")}if(0===t.length)throw new Error(`Failed to get any of the selected tabs (${e.join(", ")})`);return t}catch(e){return st.log("BrowserContextV2",`Error getting pages: ${e}`,"error"),[]}}async getAllTabIds(){try{const e=await chrome.tabs.query({currentWindow:!0});return new Set(e.map(e=>e.id).filter(e=>void 0!==e))}catch(e){return st.log("BrowserContextV2",`Failed to get tab IDs: ${e}`,"warning"),new Set}}async getTargetTab(){if(this._executionLockedTabId)try{const e=await chrome.tabs.get(this._executionLockedTabId);if(e)return e}catch(e){st.log("BrowserContextV2",`Execution-locked tab ${this._executionLockedTabId} no longer exists`,"warning"),this._executionLockedTabId=null}const[e]=await chrome.tabs.query({active:!0,currentWindow:!0});if(!e?.id)throw new Error("No active tab available");return e}lockExecutionToTab(e){this._executionLockedTabId=e,st.log("BrowserContextV2",`Execution locked to tab ${e}`)}async unlockExecution(){const e=this._executionLockedTabId;this._executionLockedTabId=null,st.log("BrowserContextV2","Execution unlocked"+(e?` (was locked to tab ${e})`:""))}async getCurrentWindow(){try{const e=await this.getTargetTab();if(e&&e.windowId){return await chrome.windows.get(e.windowId)}}catch(e){st.log("BrowserContextV2",`Failed to get window from target tab: ${e}`,"warning")}const e=await chrome.windows.getCurrent();if(e)return e;throw new Error("No window found")}async getBrowserState(){return wt("BrowserContext.getBrowserState",async()=>{try{const e=await this.getCurrentPage(),t=await this.getTabs(),n=await e.url(),r=await e.title(),s=e.tabId,i=await e.getClickableElementsString(),a=await e.getTypeableElementsString(),o=await e.getClickableElements(),l=await e.getTypeableElements(),c=await e.getHierarchicalStructure();let u=null;this._config.useVision&&(u=await e.takeScreenshot());return{tabId:s,url:n,title:r,tabs:t,clickableElements:o,typeableElements:l,clickableElementsString:i,typeableElementsString:a,hierarchicalStructure:c,screenshot:u}}catch(e){st.log("BrowserContextV2",`Failed to get state: ${e}`,"warning");return{tabId:0,url:"about:blank",title:"New Tab",tabs:[],clickableElements:[],typeableElements:[],clickableElementsString:"",typeableElementsString:"",hierarchicalStructure:null,screenshot:null}}})}async cleanup(){try{st.log("BrowserContextV2","Cleaning up browser context"),this._pageCache.clear(),this._executionLockedTabId=null,this._userSelectedTabIds=null,st.log("BrowserContextV2","Browser context cleaned up successfully")}catch(e){st.log("BrowserContextV2",`Error during cleanup: ${e}`,"error")}}}const Ft=Ut;function Bt(e,t=qt){const n=(e=e.trim()).indexOf("```");if(-1===n)return t(e);let r=e.substring(n+3);r.startsWith("json\n")?r=r.substring(5):r.startsWith("json")?r=r.substring(4):r.startsWith("\n")&&(r=r.substring(1));const s=r.indexOf("```");let i=r;return-1!==s&&(i=r.substring(0,s)),t(i.trim())}function qt(e){if(void 0===e)return null;try{return JSON.parse(e)}catch(e){}let t="";const n=[];let r=!1,s=!1;for(let i of e){if(r)'"'!==i||s?"\n"!==i||s?s="\\"===i&&!s:i="\\n":r=!1;else if('"'===i)r=!0,s=!1;else if("{"===i)n.push("}");else if("["===i)n.push("]");else if("}"===i||"]"===i){if(!n||n[n.length-1]!==i)return null;n.pop()}t+=i}r&&(t+='"');for(let e=n.length-1;e>=0;e-=1)t+=n[e];try{return JSON.parse(t)}catch(e){return null}}var zt=n(9478);n(2729);function Ht(e,t){return t?.[e]||zt(e)}function Wt(e,t,n){const r={};for(const s in e)Object.hasOwn(e,s)&&(r[t(s,n)]=e[s]);return r}function Gt(e){return Array.isArray(e)?[...e]:{...e}}function Kt(e,t){const n=Gt(e);for(const[e,r]of Object.entries(t)){const[t,...s]=e.split(".").reverse();let i=n;for(const e of s.reverse()){if(void 0===i[e])break;i[e]=Gt(i[e]),i=i[e]}void 0!==i[t]&&(i[t]={lc:1,type:"secret",id:[r]})}return n}function Jt(e){const t=Object.getPrototypeOf(e);return"function"==typeof e.lc_name&&("function"!=typeof t.lc_name||e.lc_name()!==t.lc_name())?e.lc_name():e.name}class Zt{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Jt(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),void 0!==this.lc_serializable_keys?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([e])=>this.lc_serializable_keys?.includes(e))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof Zt||"object"!=typeof this.lc_kwargs||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},t={},n=Object.keys(this.lc_kwargs).reduce((e,t)=>(e[t]=t in this?this[t]:this.lc_kwargs[t],e),{});for(let r=Object.getPrototypeOf(this);r;r=Object.getPrototypeOf(r))Object.assign(e,Reflect.get(r,"lc_aliases",this)),Object.assign(t,Reflect.get(r,"lc_secrets",this)),Object.assign(n,Reflect.get(r,"lc_attributes",this));return Object.keys(t).forEach(e=>{let t=this,r=n;const[s,...i]=e.split(".").reverse();for(const e of i.reverse()){if(!(e in t)||void 0===t[e])return;e in r&&void 0!==r[e]||("object"==typeof t[e]&&null!=t[e]?r[e]={}:Array.isArray(t[e])&&(r[e]=[])),t=t[e],r=r[e]}s in t&&void 0!==t[s]&&(r[s]=r[s]||t[s])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Wt(Object.keys(t).length?Kt(n,t):n,Ht,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}function Vt(e){return"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&"source_type"in e&&("url"===e.source_type||"base64"===e.source_type||"text"===e.source_type||"id"===e.source_type)}function Yt(e){return Vt(e)&&"url"===e.source_type&&"url"in e&&"string"==typeof e.url}function Xt(e){return Vt(e)&&"base64"===e.source_type&&"data"in e&&"string"==typeof e.data}function Qt(e){if(Vt(e)){if("url"===e.source_type)return{type:"image_url",image_url:{url:e.url}};if("base64"===e.source_type){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function en(e){const t=e.split(";")[0].split("/");if(2!==t.length)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const n=t[0].trim(),r=t[1].trim();if(""===n||""===r)throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const s={};for(const t of e.split(";").slice(1)){const n=t.split("=");if(2!==n.length)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const r=n[0].trim(),i=n[1].trim();if(""===r)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);s[r]=i}return{type:n,subtype:r,parameters:s}}function tn({dataUrl:e,asTypedArray:t=!1}){const n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let r;if(n){r=n[1].toLowerCase();const e=t?Uint8Array.from(atob(n[2]),e=>e.charCodeAt(0)):n[2];return{mime_type:r,data:e}}}function nn(e,t){if("text"===e.type){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if("image"===e.type){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if("audio"===e.type){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if("file"===e.type){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function rn(e,t){return"string"==typeof e?""===e?t:"string"==typeof t?e+t:Array.isArray(t)&&t.some(e=>Vt(e))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?on(e,t)??[...e,...t]:""===t?e:Array.isArray(e)&&e.some(e=>Vt(e))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}class sn extends Zt{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return"string"==typeof this.content?this.content:Array.isArray(this.content)?this.content.map(e=>"string"==typeof e?e:"text"===e.type?e.text:"").join(""):""}getType(){return this._getType()}constructor(e,t){"string"==typeof e&&(e={content:e,additional_kwargs:t,response_metadata:{}}),e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{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,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.content=e.content,this.additional_kwargs=e.additional_kwargs,this.response_metadata=e.response_metadata,this.id=e.id}toDict(){return{type:this._getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(null===e)return this;const t=(n=this._printableFields,r=Math.max(4,e),JSON.stringify(function e(t,n){if("object"!=typeof t||null==t)return t;if(n>=r)return Array.isArray(t)?"[Array]":"[Object]";if(Array.isArray(t))return t.map(t=>e(t,n+1));const s={};for(const r of Object.keys(t))s[r]=e(t[r],n+1);return s}(n,0),null,2));var n,r;return`${this.constructor.lc_name()} ${t}`}}function an(e,t){const n={...e};for(const[e,r]of Object.entries(t))if(null==n[e])n[e]=r;else{if(null==r)continue;if(typeof n[e]!=typeof r||Array.isArray(n[e])!==Array.isArray(r))throw new Error(`field[${e}] already exists in the message chunk, but with a different type.`);if("string"==typeof n[e]){if("type"===e)continue;n[e]+=r}else if("object"!=typeof n[e]||Array.isArray(n[e])){if(Array.isArray(n[e]))n[e]=on(n[e],r);else if(n[e]===r)continue}else n[e]=an(n[e],r)}return n}function on(e,t){if(void 0!==e||void 0!==t){if(void 0===e||void 0===t)return e||t;{const n=[...e];for(const e of t)if("object"==typeof e&&"index"in e&&"number"==typeof e.index){const t=n.findIndex(t=>t.index===e.index);-1!==t?n[t]=an(n[t],e):n.push(e)}else{if("object"==typeof e&&"text"in e&&""===e.text)continue;n.push(e)}return n}}}function ln(e,t){if(!e&&!t)throw new Error("Cannot merge two undefined objects.");if(e&&t){if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.\nLeft ${typeof e}\nRight ${typeof t}`);if("string"==typeof e&&"string"==typeof t)return e+t;if(Array.isArray(e)&&Array.isArray(t))return on(e,t);if("object"==typeof e&&"object"==typeof t)return an(e,t);if(e===t)return e;throw new Error(`Can not merge objects of different types.\nLeft ${e}\nRight ${t}`)}return e||t}class cn extends sn{}function un(e){return"function"==typeof e?._getType}function dn(e){return un(e)&&"function"==typeof e.concat}class hn extends sn{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(e,t,n){"string"==typeof e&&(e={content:e,name:n,tool_call_id:t}),super(e),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}_getType(){return"tool"}static isInstance(e){return"tool"===e._getType()}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}class pn extends cn{constructor(e){super(e),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}_getType(){return"tool"}concat(e){return new pn({content:rn(this.content,e.content),additional_kwargs:an(this.additional_kwargs,e.additional_kwargs),response_metadata:an(this.response_metadata,e.response_metadata),artifact:ln(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:(t=this.status,n=e.status,"error"===t||"error"===n?"error":"success")});var t,n}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}class fn extends sn{get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e,t){let n;if("string"==typeof e)n={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:t??{}};else{n=e;const t=n.additional_kwargs?.tool_calls,r=n.tool_calls;null!=t&&t.length>0&&(void 0===r||r.length);try{if(null!=t&&void 0===r){const[e,r]=function(e){const t=[],n=[];for(const r of e)if(r.function){const e=r.function.name;try{const n={name:e||"",args:JSON.parse(r.function.arguments)||{},id:r.id};t.push(n)}catch(t){n.push({name:e,args:r.function.arguments,id:r.id,error:"Malformed args."})}}return[t,n]}(t);n.tool_calls=e??[],n.invalid_tool_calls=r??[]}else n.tool_calls=n.tool_calls??[],n.invalid_tool_calls=n.invalid_tool_calls??[]}catch(e){n.tool_calls=[],n.invalid_tool_calls=[]}}super(n),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),"string"!=typeof n&&(this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=n.usage_metadata}static lc_name(){return"AIMessage"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}}function mn(e){return"ai"===e._getType()}function gn(e){return"ai"===e._getType()}class _n extends cn{constructor(e){let t;if("string"==typeof e)t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(void 0===e.tool_call_chunks)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0};else{const n=e.tool_call_chunks.reduce((e,t)=>t.id?(e[t.id]=e[t.id]??[],e[t.id].push(t),e):e,{}),r=[],s=[];for(const[e,t]of Object.entries(n)){let n={};const i=t[0]?.name??"",a=t.map(e=>e.args||"").join(""),o=a.length?a:"{}";try{if(n=qt(o),null===n||"object"!=typeof n||Array.isArray(n))throw new Error("Malformed tool call chunk args.");r.push({name:i,args:n,id:e,type:"tool_call"})}catch(t){s.push({name:i,args:o,id:e,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:r,invalid_tool_calls:s,usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0}}super(t),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){const t={content:rn(this.content,e.content),additional_kwargs:an(this.additional_kwargs,e.additional_kwargs),response_metadata:an(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(void 0!==this.tool_call_chunks||void 0!==e.tool_call_chunks){const n=on(this.tool_call_chunks,e.tool_call_chunks);void 0!==n&&n.length>0&&(t.tool_call_chunks=n)}if(void 0!==this.usage_metadata||void 0!==e.usage_metadata){const n={...(void 0!==this.usage_metadata?.input_token_details?.audio||void 0!==e.usage_metadata?.input_token_details?.audio)&&{audio:(this.usage_metadata?.input_token_details?.audio??0)+(e.usage_metadata?.input_token_details?.audio??0)},...(void 0!==this.usage_metadata?.input_token_details?.cache_read||void 0!==e.usage_metadata?.input_token_details?.cache_read)&&{cache_read:(this.usage_metadata?.input_token_details?.cache_read??0)+(e.usage_metadata?.input_token_details?.cache_read??0)},...(void 0!==this.usage_metadata?.input_token_details?.cache_creation||void 0!==e.usage_metadata?.input_token_details?.cache_creation)&&{cache_creation:(this.usage_metadata?.input_token_details?.cache_creation??0)+(e.usage_metadata?.input_token_details?.cache_creation??0)}},r={...(void 0!==this.usage_metadata?.output_token_details?.audio||void 0!==e.usage_metadata?.output_token_details?.audio)&&{audio:(this.usage_metadata?.output_token_details?.audio??0)+(e.usage_metadata?.output_token_details?.audio??0)},...(void 0!==this.usage_metadata?.output_token_details?.reasoning||void 0!==e.usage_metadata?.output_token_details?.reasoning)&&{reasoning:(this.usage_metadata?.output_token_details?.reasoning??0)+(e.usage_metadata?.output_token_details?.reasoning??0)}},s=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},i=e.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},a={input_tokens:s.input_tokens+i.input_tokens,output_tokens:s.output_tokens+i.output_tokens,total_tokens:s.total_tokens+i.total_tokens,...Object.keys(n).length>0&&{input_token_details:n},...Object.keys(r).length>0&&{output_token_details:r}};t.usage_metadata=a}return new _n(t)}}class yn extends sn{static lc_name(){return"ChatMessage"}static _chatMessageClass(){return yn}constructor(e,t){"string"==typeof e&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}static isInstance(e){return"generic"===e._getType()}get _printableFields(){return{...super._printableFields,role:this.role}}}class vn extends cn{static lc_name(){return"ChatMessageChunk"}constructor(e,t){"string"==typeof e&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}concat(e){return new vn({content:rn(this.content,e.content),additional_kwargs:an(this.additional_kwargs,e.additional_kwargs),response_metadata:an(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}get _printableFields(){return{...super._printableFields,role:this.role}}}class bn extends cn{static lc_name(){return"FunctionMessageChunk"}_getType(){return"function"}concat(e){return new bn({content:rn(this.content,e.content),additional_kwargs:an(this.additional_kwargs,e.additional_kwargs),response_metadata:an(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}}class wn extends sn{static lc_name(){return"HumanMessage"}_getType(){return"human"}constructor(e,t){super(e,t)}}class En extends cn{static lc_name(){return"HumanMessageChunk"}_getType(){return"human"}constructor(e,t){super(e,t)}concat(e){return new En({content:rn(this.content,e.content),additional_kwargs:an(this.additional_kwargs,e.additional_kwargs),response_metadata:an(this.response_metadata,e.response_metadata),id:this.id??e.id})}}class Sn extends sn{static lc_name(){return"SystemMessage"}_getType(){return"system"}constructor(e,t){super(e,t)}}class kn extends cn{static lc_name(){return"SystemMessageChunk"}_getType(){return"system"}constructor(e,t){super(e,t)}concat(e){return new kn({content:rn(this.content,e.content),additional_kwargs:an(this.additional_kwargs,e.additional_kwargs),response_metadata:an(this.response_metadata,e.response_metadata),id:this.id??e.id})}}function xn(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/\n`,e}function On(e){return!(!e||"object"!=typeof e||!("type"in e)||"tool_call"!==e.type)}class Tn extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}}function In(e){return On(e)?e:"string"==typeof e.id&&"function"===e.type&&"object"==typeof e.function&&null!==e.function&&"arguments"in e.function&&"string"==typeof e.function.arguments&&"name"in e.function&&"string"==typeof e.function.name?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function An(e){let t,n;if(function(e){return"object"==typeof e&&null!=e&&1===e.lc&&Array.isArray(e.id)&&null!=e.kwargs&&"object"==typeof e.kwargs}(e)){const r=e.id.at(-1);t="HumanMessage"===r||"HumanMessageChunk"===r?"user":"AIMessage"===r||"AIMessageChunk"===r?"assistant":"SystemMessage"===r||"SystemMessageChunk"===r?"system":"FunctionMessage"===r||"FunctionMessageChunk"===r?"function":"ToolMessage"===r||"ToolMessageChunk"===r?"tool":"unknown",n=e.kwargs}else{const{type:r,...s}=e;t=r,n=s}if("human"===t||"user"===t)return new wn(n);if("ai"===t||"assistant"===t){const{tool_calls:e,...t}=n;if(!Array.isArray(e))return new fn(n);const r=e.map(In);return new fn({...t,tool_calls:r})}if("system"===t)return new Sn(n);if("developer"===t)return new Sn({...n,additional_kwargs:{...n.additional_kwargs,__openai_role__:"developer"}});if("tool"===t&&"tool_call_id"in n)return new hn({...n,content:n.content,tool_call_id:n.tool_call_id,name:n.name});throw xn(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\n\nReceived: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}function Pn(e){if("string"==typeof e)return new wn(e);if(un(e))return e;if(Array.isArray(e)){const[t,n]=e;return An({type:t,content:n})}if(function(e){return"string"==typeof e.role}(e)){const{role:t,...n}=e;return An({...n,type:t})}return An(e)}function Cn(e,t="Human",n="AI"){const r=[];for(const s of e){let e;if("human"===s._getType())e=t;else if("ai"===s._getType())e=n;else if("system"===s._getType())e="System";else if("function"===s._getType())e="Function";else if("tool"===s._getType())e="Tool";else{if("generic"!==s._getType())throw new Error(`Got unsupported message type: ${s._getType()}`);e=s.role}const i=s.name?`${s.name}, `:"",a="string"==typeof s.content?s.content:JSON.stringify(s.content,null,2);r.push(`${e}: ${i}${a}`)}return r.join("\n")}function $n(e){const t=e._getType();if("human"===t)return new En({...e});if("ai"===t){let t={...e};return"tool_calls"in t&&(t={...t,tool_call_chunks:t.tool_calls?.map(e=>({...e,type:"tool_call_chunk",index:void 0,args:JSON.stringify(e.args)}))}),new _n({...t})}if("system"===t)return new kn({...e});if("function"===t)return new bn({...e});if(yn.isInstance(e))return new vn({...e});throw new Error("Unknown message type.")}var Rn=n(4116);const Nn={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};var jn,Ln=new Uint8Array(16);function Mn(){if(!jn&&!(jn="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 jn(Ln)}for(var Dn=[],Un=0;Un<256;++Un)Dn.push((Un+256).toString(16).slice(1));function Fn(e,t=0){return(Dn[e[t+0]]+Dn[e[t+1]]+Dn[e[t+2]]+Dn[e[t+3]]+"-"+Dn[e[t+4]]+Dn[e[t+5]]+"-"+Dn[e[t+6]]+Dn[e[t+7]]+"-"+Dn[e[t+8]]+Dn[e[t+9]]+"-"+Dn[e[t+10]]+Dn[e[t+11]]+Dn[e[t+12]]+Dn[e[t+13]]+Dn[e[t+14]]+Dn[e[t+15]]).toLowerCase()}const Bn=function(e,t,n){if(Nn.randomUUID&&!t&&!e)return Nn.randomUUID();var r=(e=e||{}).random||(e.rng||Mn)();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 Fn(r)};const qn=Symbol.for("ls:tracing_async_local_storage"),zn=new class{getStore(){}run(e,t){return t()}};const Hn=new class{getInstance(){return globalThis[qn]??zn}initializeGlobalInstance(e){void 0===globalThis[qn]&&(globalThis[qn]=e)}};Symbol.for("langsmith:traceable:root");function Wn(e){return"function"==typeof e&&"langsmith:traceable"in e}const Gn=Object.prototype.hasOwnProperty;function Kn(e,t){return Gn.call(e,t)}function Jn(e){if(Array.isArray(e)){const t=new Array(e.length);for(let e=0;e=48&&r<=57))return!1;t++}return!0}function Yn(e){return-1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function Xn(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Qn(e){if(void 0===e)return!0;if(e)if(Array.isArray(e)){for(let t=0,n=e.length;t0&&"constructor"==a[d-1]))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&void 0===o&&(void 0===u[l]?o=a.slice(0,d).join("/"):d==h-1&&(o=t.path),void 0!==o&&c(t,0,e,o)),d++,Array.isArray(u)){if("-"===l)l=u.length;else{if(n&&!Vn(l))throw new nr("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,t,e);Vn(l)&&(l=~~l)}if(d>=h){if(n&&"add"===t.op&&l>u.length)throw new nr("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,t,e);const r=ir[t.op].call(t,u,l,e);if(!1===r.test)throw new nr("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return r}}else if(d>=h){const n=sr[t.op].call(t,u,l,e);if(!1===n.test)throw new nr("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return n}if(u=u[l],n&&d0)throw new nr('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,n);if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new nr("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,n);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new nr("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,n);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&Qn(e.value))throw new nr("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,n);if(n)if("add"==e.op){var s=e.path.split("/").length,i=r.split("/").length;if(s!==i+1&&s!==i)throw new nr("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,n)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==r)throw new nr("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,n)}else if("move"===e.op||"copy"===e.op){var a=dr([{op:"_get",path:e.from,value:void 0}],n);if(a&&"OPERATION_PATH_UNRESOLVABLE"===a.name)throw new nr("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,n)}}function dr(e,t,n){try{if(!Array.isArray(e))throw new nr("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)lr(Zn(t),Zn(e),n||!0);else{n=n||ur;for(var r=0;r=0;l--){var c=e[d=a[l]];if(!Kn(t,d)||void 0===t[d]&&void 0!==c&&!1===Array.isArray(t))Array.isArray(e)===Array.isArray(t)?(s&&n.push({op:"test",path:r+"/"+Yn(d),value:Zn(c)}),n.push({op:"remove",path:r+"/"+Yn(d)}),o=!0):(s&&n.push({op:"test",path:r,value:e}),n.push({op:"replace",path:r,value:t}),!0);else{var u=t[d];"object"==typeof c&&null!=c&&"object"==typeof u&&null!=u&&Array.isArray(c)===Array.isArray(u)?pr(c,u,n,r+"/"+Yn(d),s):c!==u&&(s&&n.push({op:"test",path:r+"/"+Yn(d),value:Zn(c)}),n.push({op:"replace",path:r+"/"+Yn(d),value:Zn(u)}))}}if(o||i.length!=a.length)for(l=0;l>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=255&t,n[4]=(t=parseInt(e.slice(9,13),16))>>>8,n[5]=255&t,n[6]=(t=parseInt(e.slice(14,18),16))>>>8,n[7]=255&t,n[8]=(t=parseInt(e.slice(19,23),16))>>>8,n[9]=255&t,n[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=255&t,n};function Or(e,t,n,r){switch(e){case 0:return t&n^~t&r;case 1:case 3:return t^n^r;case 2:return t&n^t&r^n&r}}function Tr(e,t){return e<>>32-t}const Ir=function(e){var t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var r=unescape(encodeURIComponent(e));e=[];for(var s=0;s>>0;v=y,y=_,_=Tr(g,30)>>>0,g=m,m=E}n[0]=n[0]+m>>>0,n[1]=n[1]+g>>>0,n[2]=n[2]+_>>>0,n[3]=n[3]+y>>>0,n[4]=n[4]+v>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,255&n[0],n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,255&n[1],n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,255&n[2],n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,255&n[3],n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,255&n[4]]};var Ar=function(e,t,n){function r(e,r,s,i){var a;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],n=0;nfetch(...e),Mr=Symbol.for("ls:fetch_implementation"),Dr=e=>async(...t)=>{if(e||"true"===Zr("DEBUG")){const[e,n]=t}const n=await(globalThis[Mr]??Lr)(...t);return e||Zr("DEBUG"),n},Ur=()=>Zr("PROJECT")??Jr("LANGCHAIN_SESSION")??"default",Fr="0.3.46";let Br;const qr=()=>"undefined"!=typeof Deno,zr=()=>Br||(Br="undefined"!=typeof window&&void 0!==window.document?"browser":"undefined"==typeof process||void 0===process.versions||void 0===process.versions.node||qr()?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&navigator.userAgent.includes("jsdom")?"jsdom":qr()?"deno":"other":"node",Br);let Hr,Wr;function Gr(){if(void 0===Hr){const e=zr(),t=function(){if(void 0!==Wr)return Wr;const e=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],t={};for(const n of e){const e=Jr(n);void 0!==e&&(t[n]=e)}return Wr=t,t}();Hr={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:Fr,...t}}return Hr}function Kr(){try{return"undefined"!=typeof process&&process.env?Object.entries(process.env).reduce((e,[t,n])=>(e[t]=String(n),e),{}):void 0}catch(e){return}}function Jr(e){try{return"undefined"!=typeof process?process.env?.[e]:void 0}catch(e){return}}function Zr(e){return Jr(`LANGSMITH_${e}`)||Jr(`LANGCHAIN_${e}`)}class Vr{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){let n;if(this.hasWarned||"true"!==Jr("OTEL_ENABLED")||(this.hasWarned=!0),1===t.length&&"function"==typeof t[0]?n=t[0]:2===t.length&&"function"==typeof t[1]?n=t[1]:3===t.length&&"function"==typeof t[2]&&(n=t[2]),"function"==typeof n)return n()}}const Yr=Symbol.for("ls:otel_trace"),Xr=Symbol.for("ls:otel_context"),Qr=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),es=new class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Vr})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},ts=new class{active(){return{}}with(e,t){return t()}};const ns=new class{getTraceInstance(){return globalThis[Yr]??es}getContextInstance(){return globalThis[Xr]??ts}initializeGlobalInstances(e){void 0===globalThis[Yr]&&(globalThis[Yr]=e.trace),void 0===globalThis[Xr]&&(globalThis[Xr]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[Qr]=e}getDefaultOTLPTracerComponents(){return globalThis[Qr]??void 0}};function rs(){return ns.getTraceInstance()}const ss={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};class is{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(const n of e)try{if(!n.run)continue;if("post"===n.operation){const e=this.createSpanForRun(n,n.run,t.get(n.id));e&&!n.run.end_time&&this.spans.set(n.id,e)}else this.updateSpanForRun(n,n.run)}catch(e){}}createSpanForRun(e,t,n){const r=n&&rs().getSpan(n);if(r)try{return this.finishSpanSetup(r,t,e)}catch(e){return}}finishSpanSetup(e,t,n){return this.setSpanAttributes(e,t,n),t.error?(e.setStatus({code:2}),e.recordException(new Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){try{const n=this.spans.get(e.id);if(!n)return;this.setSpanAttributes(n,t,e),t.error?(n.setStatus({code:2}),n.recordException(new Error(t.error))):n.setStatus({code:1});const r=t.end_time;r&&(n.end(new Date(r)),this.spans.delete(e.id))}catch(e){}}extractModelName(e){if(e.extra?.metadata){const t=e.extra.metadata;if(t.ls_model_name)return t.ls_model_name;if(t.invocation_params){const e=t.invocation_params;if(e.model)return e.model;if(e.model_name)return e.model_name}}}setSpanAttributes(e,t,n){if("run_type"in t&&t.run_type){e.setAttribute("langsmith.span.kind",t.run_type);const n=(r=t.run_type||"chain",ss[r]||r);e.setAttribute("gen_ai.operation.name",n)}var r;"name"in t&&t.name&&e.setAttribute("langsmith.trace.name",t.name),"session_id"in t&&t.session_id&&e.setAttribute("langsmith.trace.session_id",t.session_id),"session_name"in t&&t.session_name&&e.setAttribute("langsmith.trace.session_name",t.session_name),this.setGenAiSystem(e,t);const s=this.extractModelName(t);s&&e.setAttribute(Cr,s),"prompt_tokens"in t&&"number"==typeof t.prompt_tokens&&e.setAttribute($r,t.prompt_tokens),"completion_tokens"in t&&"number"==typeof t.completion_tokens&&e.setAttribute(Rr,t.completion_tokens),"total_tokens"in t&&"number"==typeof t.total_tokens&&e.setAttribute(Nr,t.total_tokens),this.setInvocationParameters(e,t);const i=t.extra?.metadata||{};for(const[t,n]of Object.entries(i))null!=n&&e.setAttribute(`langsmith.metadata.${t}`,String(n));const a=t.tags;if(a&&Array.isArray(a)?e.setAttribute(jr,a.join(", ")):a&&e.setAttribute(jr,String(a)),"serialized"in t&&"object"==typeof t.serialized){const n=t.serialized;n.name&&e.setAttribute("gen_ai.serialized.name",String(n.name)),n.signature&&e.setAttribute("gen_ai.serialized.signature",String(n.signature)),n.doc&&e.setAttribute("gen_ai.serialized.doc",String(n.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,t){let n="langchain";const r=this.extractModelName(t);if(r){const e=r.toLowerCase();e.includes("anthropic")||e.startsWith("claude")?n="anthropic":e.includes("bedrock")?n="aws.bedrock":e.includes("azure")&&e.includes("openai")?n="az.ai.openai":e.includes("azure")&&e.includes("inference")?n="az.ai.inference":e.includes("cohere")?n="cohere":e.includes("deepseek")?n="deepseek":e.includes("gemini")?n="gemini":e.includes("groq")?n="groq":e.includes("watson")||e.includes("ibm")?n="ibm.watsonx.ai":e.includes("mistral")?n="mistral_ai":e.includes("gpt")||e.includes("openai")?n="openai":e.includes("perplexity")||e.includes("sonar")?n="perplexity":e.includes("vertex")?n="vertex_ai":(e.includes("xai")||e.includes("grok"))&&(n="xai")}e.setAttribute("gen_ai.system",n)}setInvocationParameters(e,t){if(!t.extra?.metadata?.invocation_params)return;const n=t.extra.metadata.invocation_params;void 0!==n.max_tokens&&e.setAttribute("gen_ai.request.max_tokens",n.max_tokens),void 0!==n.temperature&&e.setAttribute("gen_ai.request.temperature",n.temperature),void 0!==n.top_p&&e.setAttribute("gen_ai.request.top_p",n.top_p),void 0!==n.frequency_penalty&&e.setAttribute("gen_ai.request.frequency_penalty",n.frequency_penalty),void 0!==n.presence_penalty&&e.setAttribute("gen_ai.request.presence_penalty",n.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{const n=t.run.inputs;"object"==typeof n&&null!==n&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(Cr,n.model),void 0!==n.stream&&e.setAttribute("langsmith.request.streaming",n.stream),n.extra_headers&&e.setAttribute("langsmith.request.headers",JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute("gen_ai.request.extra_query",JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute("gen_ai.request.extra_body",JSON.stringify(n.extra_body))),e.setAttribute("gen_ai.prompt",JSON.stringify(n))}catch(e){}if(t.run.outputs)try{const n=t.run.outputs,r=this.getUnifiedRunTokens(n);if(r&&(e.setAttribute($r,r[0]),e.setAttribute(Rr,r[1]),e.setAttribute(Nr,r[0]+r[1])),n&&"object"==typeof n){if(n.model&&e.setAttribute("gen_ai.response.model",String(n.model)),n.id&&e.setAttribute("gen_ai.response.id",n.id),n.choices&&Array.isArray(n.choices)){const t=n.choices.map(e=>e.finish_reason).filter(e=>e).map(String);t.length>0&&e.setAttribute("gen_ai.response.finish_reasons",t.join(", "))}if(n.service_tier&&e.setAttribute("gen_ai.response.service_tier",n.service_tier),n.system_fingerprint&&e.setAttribute("gen_ai.response.system_fingerprint",n.system_fingerprint),n.usage_metadata&&"object"==typeof n.usage_metadata){const t=n.usage_metadata;t.input_token_details&&e.setAttribute("gen_ai.usage.input_token_details",JSON.stringify(t.input_token_details)),t.output_token_details&&e.setAttribute("gen_ai.usage.output_token_details",JSON.stringify(t.output_token_details))}}e.setAttribute("gen_ai.completion",JSON.stringify(n))}catch(e){}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;const n=Object.keys(e);for(const r of n){const n=e[r];if(n&&"object"==typeof n){if(t=this.extractUnifiedRunTokens(n.usage_metadata),t)return t;if(1===n.lc&&n.kwargs&&"object"==typeof n.kwargs&&(t=this.extractUnifiedRunTokens(n.kwargs.usage_metadata),t))return t}}const r=e.generations||[];if(!Array.isArray(r))return null;const s=Array.isArray(r[0])?r.flat():r;for(const e of s)if("object"==typeof e&&e.message&&"object"==typeof e.message&&e.message.kwargs&&"object"==typeof e.message.kwargs&&(t=this.extractUnifiedRunTokens(e.message.kwargs.usage_metadata),t))return t;return null}extractUnifiedRunTokens(e){return e&&"object"==typeof e?"number"!=typeof e.input_tokens||"number"!=typeof e.output_tokens?null:[e.input_tokens,e.output_tokens]:null}}var as=n(3290);const os=[400,401,403,404,405,406,407,408],ls=[409];class cs{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.debug=e.debug,this.queue=new as.default({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){const n=this.onFailedResponseHook;return this.queue.add(()=>Rn(()=>e(...t).catch(e=>{throw e instanceof Error?e:new Error(e)}),{async onFailedAttempt(e){if(e.message.startsWith("Cancel")||e.message.startsWith("TimeoutError")||e.message.startsWith("AbortError"))throw e;if("ECONNABORTED"===e?.code)throw e;const t=e?.response,r=t?.status;if(r){if(os.includes(+r))throw e;if(ls.includes(+r))return;n&&await n(t)}},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){return e.signal?Promise.race([this.call(t,...n),new Promise((t,n)=>{e.signal?.addEventListener("abort",()=>{n(new Error("AbortError"))})})]):this.call(t,...n)}fetch(...e){return this.call(()=>Dr(this.debug)(...e).then(e=>e.ok?e:Promise.reject(e)))}}function us(e){return"function"==typeof e?._getType}function ds(e){const t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}const hs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ps(e,t){if(!hs.test(e)){throw new Error(void 0!==t?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`)}return e}const fs={};function ms(e){fs[e]||(fs[e]=!0)}n(9589);function gs(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw new Error(`Invalid identifier format: ${e}`);const[t,n]=e.split(":"),r=n||"latest";if(t.includes("/")){const[n,s]=t.split("/",2);if(!n||!s)throw new Error(`Invalid identifier format: ${e}`);return[n,s,r]}if(!t)throw new Error(`Invalid identifier format: ${e}`);return["-",t,r]}class _s extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}async function ys(e,t,n){let r;if(e.ok)return void(n&&(r=await e.text()));r=await e.text();const s=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Server response: ${r}`;if(409===e.status)throw new _s(s);const i=new Error(s);throw i.status=e.status,i}const vs="ERR_CONFLICTING_ENDPOINTS";class bs extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:vs}),this.name="ConflictingEndpointsError"}}var ws="[...]",Es={result:"[Circular]"},Ss=[],ks=[];const xs=new TextEncoder;function Os(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Ts(e){return xs.encode(e)}function Is(e){if(e&&"object"==typeof e&&null!==e){if(e instanceof Map)return Object.fromEntries(e);if(e instanceof Set)return Array.from(e);if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(e instanceof Error)return{name:e.name,message:e.message}}else if("bigint"==typeof e)return e.toString();return e}function As(e,t,n,r,s){try{return Ts(JSON.stringify(e,(i=n,function(e,t){if(i){const n=i.call(this,e,t);if(void 0!==n)return n}return Is(t)}),r))}catch(t){if(!t.message?.includes("Converting circular structure to JSON"))return Ts("[Unserializable]");let i;Zr("SUPPRESS_CIRCULAR_JSON_WARNINGS"),void 0===s&&(s=Os()),Cs(e,"",0,[],void 0,0,s);try{i=0===ks.length?JSON.stringify(e,n,r):JSON.stringify(e,$s(n),r)}catch(e){return Ts("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Ss.length;){const e=Ss.pop();4===e.length?Object.defineProperty(e[0],e[1],e[3]):e[0][e[1]]=e[2]}}return Ts(i)}var i}function Ps(e,t,n,r){var s=Object.getOwnPropertyDescriptor(r,n);void 0!==s.get?s.configurable?(Object.defineProperty(r,n,{value:e}),Ss.push([r,n,t,s])):ks.push([t,n,e]):(r[n]=e,Ss.push([r,n,t]))}function Cs(e,t,n,r,s,i,a){var o;if(i+=1,"object"==typeof e&&null!==e){for(o=0;oa.depthLimit)return void Ps(ws,e,t,s);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void Ps(ws,e,t,s);if(r.push(e),Array.isArray(e))for(o=0;o0)for(var r=0;r{if(429===e?.status){const t=1e3*parseInt(e.headers.get("retry-after")??"30",10);if(t>0)return await new Promise(e=>setTimeout(e,t)),!0}return!1};function Ls(e){return"number"==typeof e?Number(e.toFixed(4)):e}class Ms{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let t;const n=new Promise(e=>{t=e}),r=As(e.item,e.item.id).length;return this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:n,size:r}),this.sizeBytes+=r,n}pop(e){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const t=[];let n=0;for(;n+(this.peek()?.size??0)0;){const e=this.items.shift();e&&(t.push(e),n+=e.size,this.sizeBytes-=e.size)}if(0===t.length&&this.items.length>0){const e=this.items.shift();t.push(e),n+=e.size,this.sizeBytes-=e.size}return[t.map(e=>({action:e.action,item:e.payload,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl})),()=>t.forEach(e=>e.itemPromiseResolve())]}}const Ds="https://api.smith.langchain.com";class Us{constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new Ms}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:"false"===Jr("LANGSMITH_TRACING_BACKGROUND")}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:"true"===Jr("LANGSMITH_DEBUG")});const t=Us.getDefaultClientConfig();if(this.tracingSampleRate=(e=>{const t=e?.toString()??Zr("TRACING_SAMPLING_RATE");if(void 0===t)return;const n=parseFloat(t);if(n<0||n>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${n}`);return n})(e.tracingSamplingRate),this.apiUrl=Ns(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=Ns(e.apiKey??t.apiKey),this.webUrl=Ns(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.timeout_ms=e.timeout_ms??9e4,this.caller=new cs({...e.callerOptions??{},debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.batchIngestCaller=new cs({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:js,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,"true"===Jr("OTEL_ENABLED")&&(this.langSmithToOTELTranslator=new is)}static getDefaultClientConfig(){const e=Zr("API_KEY");return{apiUrl:Zr("ENDPOINT")??Ds,apiKey:e,webUrl:void 0,hideInputs:"true"===Zr("HIDE_INPUTS"),hideOutputs:"true"===Zr("HIDE_OUTPUTS")}}getHostUrl(){return this.webUrl?this.webUrl:(e=>{const t=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return"localhost"===t||"127.0.0.1"===t||"::1"===t})(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const e={"User-Agent":`langsmith-js/${Fr}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),e}_getPlatformEndpointPath(e){return"/v1"!==this.apiUrl.slice(-3)&&"/v1/"!==this.apiUrl.slice(-4)?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return!1===this.hideInputs?e:!0===this.hideInputs?{}:"function"==typeof this.hideInputs?this.hideInputs(e):e}async processOutputs(e){return!1===this.hideOutputs?e:!0===this.hideOutputs?{}:"function"==typeof this.hideOutputs?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){const t={...e};return void 0!==t.inputs&&(t.inputs=await this.processInputs(t.inputs)),void 0!==t.outputs&&(t.outputs=await this.processOutputs(t.outputs)),t}async _getResponse(e,t){const n=t?.toString()??"",r=`${this.apiUrl}${e}?${n}`,s=await this.caller.call(Dr(this.debug),r,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ys(s,`Failed to fetch ${e}`),s}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,n){let r=Number(t.get("offset"))||0;const s=Number(t.get("limit"))||100;for(;;){t.set("offset",String(r)),t.set("limit",String(s));const i=`${this.apiUrl}${e}?${t}`,a=await this.caller.call(Dr(this.debug),i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(a,`Failed to fetch ${e}`);const o=n?n(await a.json()):await a.json();if(0===o.length)break;if(yield o,o.length0;){const[n,r]=this.autoBatchQueue.pop(e);if(!n.length){r();break}const s=n.reduce((e,t)=>{const n=t.apiUrl??this.apiUrl,r=t.apiKey??this.apiKey,s=t.apiKey===this.apiKey&&t.apiUrl===this.apiUrl?"default":`${n}|${r}`;return e[s]||(e[s]=[]),e[s].push(t),e},{}),i=[];for(const[e,t]of Object.entries(s)){const n=this._processBatch(t,{apiUrl:"default"===e?void 0:e.split("|")[0],apiKey:"default"===e?void 0:e.split("|")[1]});i.push(n)}const a=Promise.all(i).finally(r);t.push(a)}return Promise.all(t)}async _processBatch(e,t){if(e.length)try{if(void 0!==this.langSmithToOTELTranslator)this._sendBatchToOTELTranslator(e);else{const n={runCreates:e.filter(e=>"create"===e.action).map(e=>e.item),runUpdates:e.filter(e=>"update"===e.action).map(e=>e.item)},r=await this._ensureServerInfo();r?.batch_ingest_config?.use_multipart_endpoint?await this.multipartIngestRuns(n,t):await this.batchIngestRuns(n,t)}}catch(e){}}_sendBatchToOTELTranslator(e){if(void 0!==this.langSmithToOTELTranslator){const t=new Map,n=[];for(const r of e)r.item.id&&r.otelContext&&(t.set(r.item.id,r.otelContext),"create"===r.action?n.push({operation:"post",id:r.item.id,trace_id:r.item.trace_id??r.item.id,run:r.item}):n.push({operation:"patch",id:r.item.id,trace_id:r.item.trace_id??r.item.id,run:r.item}));this.langSmithToOTELTranslator.exportBatch(n,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,"create"===e.action&&(e.item=Rs(e.item));const t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;const n=await this._getBatchSizeLimitBytes();return this.autoBatchQueue.sizeBytes>n&&this.drainAutoBatchQueue(n),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue(n)},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){const e=await this.caller.call(Dr(this.debug),`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(2500),...this.fetchOptions});await ys(e,"get server info");const t=await e.json();return this.debug,t}async _ensureServerInfo(){return void 0===this._getServerInfoPromise&&(this._getServerInfoPromise=(async()=>{if(void 0===this._serverInfo)try{this._serverInfo=await this._getServerInfo()}catch(e){}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(void 0===this._serverInfo&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const e=await this._getBatchSizeLimitBytes();await this.drainAutoBatchQueue(e)}_cloneCurrentOTELContext(){const e=rs(),t=ns.getContextInstance();if(void 0!==this.langSmithToOTELTranslator){const n=e.getActiveSpan();if(n)return e.setSpan(t.active(),n)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;const n={...this.headers,"Content-Type":"application/json"},r=e.project_name;delete e.project_name;const s=await this.prepareRunCreateOrUpdateInputs({session_name:r,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&void 0!==s.trace_id&&void 0!==s.dotted_order){const e=this._cloneCurrentOTELContext();return void this.processRunOperation({action:"create",item:s,otelContext:e,apiKey:t?.apiKey,apiUrl:t?.apiUrl}).catch(console.error)}const i=Rs(s);void 0!==t?.apiKey&&(n["x-api-key"]=t.apiKey);const a=await this.caller.call(Dr(this.debug),`${t?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,body:As(i,i.id),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(a,"create run",!0)}async batchIngestRuns({runCreates:e,runUpdates:t},n){if(void 0===e&&void 0===t)return;let r=await Promise.all(e?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]),s=await Promise.all(t?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]);if(r.length>0&&s.length>0){const e=r.reduce((e,t)=>t.id?(e[t.id]=t,e):e,{}),t=[];for(const n of s)void 0!==n.id&&e[n.id]?e[n.id]={...e[n.id],...n}:t.push(n);r=Object.values(e),s=t}const i={post:r,patch:s};if(!i.post.length&&!i.patch.length)return;const a={post:[],patch:[]};for(const e of["post","patch"]){const t=e,n=i[t].reverse();let r=n.pop();for(;void 0!==r;)a[t].push(r),r=n.pop()}if(a.post.length>0||a.patch.length>0){a.post.map(e=>e.id).concat(a.patch.map(e=>e.id)).join(",");await this._postBatchIngestRuns(As(a),n)}}async _postBatchIngestRuns(e,t){const n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};void 0!==t?.apiKey&&(n["x-api-key"]=t.apiKey);const r=await this.batchIngestCaller.call(Dr(this.debug),`${t?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(r,"batch create run",!0)}async multipartIngestRuns({runCreates:e,runUpdates:t},n){if(void 0===e&&void 0===t)return;const r={};let s=[];for(const t of e??[]){const e=await this.prepareRunCreateOrUpdateInputs(t);void 0!==e.id&&void 0!==e.attachments&&(r[e.id]=e.attachments),delete e.attachments,s.push(e)}let i=[];for(const e of t??[])i.push(await this.prepareRunCreateOrUpdateInputs(e));if(void 0!==s.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(void 0!==i.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(s.length>0&&i.length>0){const e=s.reduce((e,t)=>t.id?(e[t.id]=t,e):e,{}),t=[];for(const n of i)void 0!==n.id&&e[n.id]?e[n.id]={...e[n.id],...n}:t.push(n);s=Object.values(e),i=t}if(0===s.length&&0===i.length)return;const a=[],o=[];for(const[e,t]of[["post",s],["patch",i]])for(const n of t){const{inputs:t,outputs:s,events:i,attachments:l,...c}=n,u={inputs:t,outputs:s,events:i},d=As(c,c.id);o.push({name:`${e}.${c.id}`,payload:new Blob([d],{type:`application/json; length=${d.length}`})});for(const[t,n]of Object.entries(u)){if(void 0===n)continue;const r=As(n,c.id);o.push({name:`${e}.${c.id}.${t}`,payload:new Blob([r],{type:`application/json; length=${r.length}`})})}if(void 0!==c.id){const e=r[c.id];if(e){delete r[c.id];for(const[t,n]of Object.entries(e)){let e,r;Array.isArray(n)?[e,r]=n:(e=n.mimeType,r=n.data),t.includes(".")||o.push({name:`attachment.${c.id}.${t}`,payload:new Blob([r],{type:`${e}; length=${r.byteLength}`})})}}}a.push(`trace=${c.trace_id},id=${c.id}`)}await this._sendMultipartRequest(o,a.join("; "),n)}async _createNodeFetchBody(e,t){const n=[];for(const r of e)n.push(new Blob([`--${t}\r\n`])),n.push(new Blob([`Content-Disposition: form-data; name="${r.name}"\r\n`,`Content-Type: ${r.payload.type}\r\n\r\n`])),n.push(r.payload),n.push(new Blob(["\r\n"]));n.push(new Blob([`--${t}--\r\n`]));const r=new Blob(n);return await r.arrayBuffer()}async _createMultipartStream(e,t){const n=new TextEncoder;return new ReadableStream({async start(r){const s=async e=>{"string"==typeof e?r.enqueue(n.encode(e)):r.enqueue(e)};for(const n of e){await s(`--${t}\r\n`),await s(`Content-Disposition: form-data; name="${n.name}"\r\n`),await s(`Content-Type: ${n.payload.type}\r\n\r\n`);const e=n.payload.stream().getReader();try{let t;for(;!(t=await e.read()).done;)r.enqueue(t.value)}finally{e.releaseLock()}await s("\r\n")}await s(`--${t}--\r\n`),r.close()}})}async _sendMultipartRequest(e,t,n){const r="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),s=(()=>{const e=globalThis[Mr];return!!e&&"function"==typeof e&&"Headers"in e&&"Request"in e&&"Response"in e})(),i=()=>this._createNodeFetchBody(e,r),a=()=>this._createMultipartStream(e,r),o=async e=>{const t={...this.headers,"Content-Type":`multipart/form-data; boundary=${r}`};return void 0!==n?.apiKey&&(t["x-api-key"]=n.apiKey),this.batchIngestCaller.call(Dr(this.debug),`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:t,body:e,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})};try{let e,t=!1;s||this.multipartStreamingDisabled?e=await o(await i()):(t=!0,e=await o(await a())),this.multipartStreamingDisabled&&!t||422!==e.status||(n?.apiUrl??this.apiUrl)===Ds||(this.multipartStreamingDisabled=!0,e=await o(await i())),await ys(e,"ingest multipart runs",!0)}catch(e){}}async updateRun(e,t,n){ps(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs));const r={...t,id:e};if(!this._filterForSampling([r],!0).length)return;if(this.autoBatchTracing&&void 0!==r.trace_id&&void 0!==r.dotted_order){const e=this._cloneCurrentOTELContext();return void 0!==t.end_time&&void 0===r.parent_run_id&&this.blockOnRootRunFinalization&&!this.manualFlushMode?void await this.processRunOperation({action:"update",item:r,otelContext:e,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error):void this.processRunOperation({action:"update",item:r,otelContext:e,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error)}const s={...this.headers,"Content-Type":"application/json"};void 0!==n?.apiKey&&(s["x-api-key"]=n.apiKey);const i=await this.caller.call(Dr(this.debug),`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:s,body:As(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(i,"update run",!0)}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){ps(e);let n=await this._get(`/runs/${e}`);return t&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:t,projectOpts:n}){if(void 0!==t){let e;if(t.session_id)e=t.session_id;else if(n?.projectName)e=(await this.readProject({projectName:n?.projectName})).id;else if(n?.projectId)e=n?.projectId;else{e=(await this.readProject({projectName:Zr("PROJECT")||"default"})).id}const r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/projects/p/${e}/r/${t.id}?poll=true`}if(void 0!==e){const t=await this.readRun(e);if(!t.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${t.app_path}`}throw new Error("Must provide either runId or run")}async _loadChildRuns(e){const t=await async function(e){const t=[];for await(const n of e)t.push(n);return t}(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},r={};t.sort((e,t)=>(e?.dotted_order??"").localeCompare(t?.dotted_order??""));for(const s of t){if(null===s.parent_run_id||void 0===s.parent_run_id)throw new Error(`Child run ${s.id} has no parent`);s.dotted_order?.startsWith(e.dotted_order??"")&&s.id!==e.id&&(s.parent_run_id in n||(n[s.parent_run_id]=[]),n[s.parent_run_id].push(s),r[s.id]=s)}e.child_runs=n[e.id]||[];for(const t in n)t!==e.id&&(r[t].child_runs=n[t]);return e}async*listRuns(e){const{projectId:t,projectName:n,parentRunId:r,traceId:s,referenceExampleId:i,startTime:a,executionOrder:o,isRoot:l,runType:c,error:u,id:d,query:h,filter:p,traceFilter:f,treeFilter:m,limit:g,select:_,order:y}=e;let v=[];if(t&&(v=Array.isArray(t)?t:[t]),n){const e=Array.isArray(n)?n:[n],t=await Promise.all(e.map(e=>this.readProject({projectName:e}).then(e=>e.id)));v.push(...t)}const b={session:v.length?v:null,run_type:c,reference_example:i,query:h,filter:p,trace_filter:f,tree_filter:m,execution_order:o,parent_run:r,start_time:a?a.toISOString():null,error:u,id:d,limit:g,trace:s,select:_||["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],is_root:l,order:y};let w=0;for await(const e of this._getCursorPaginatedList("/runs/query",b))if(g){if(w>=g)break;if(e.length+w>g){const t=e.slice(0,g-w);yield*t;break}w+=e.length,yield*e}else yield*e}async*listGroupRuns(e){const{projectId:t,projectName:n,groupBy:r,filter:s,startTime:i,endTime:a,limit:o,offset:l}=e,c={session_id:t||(await this.readProject({projectName:n})).id,group_by:r,filter:s,start_time:i?i.toISOString():null,end_time:a?a.toISOString():null,limit:Number(o)||100};let u=Number(l)||0;const d="/runs/group",h=`${this.apiUrl}${d}`;for(;;){const e={...c,offset:u},t=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t)),n=await this.caller.call(Dr(),h,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(n,`Failed to fetch ${d}`);const r=await n.json(),{groups:s,total:i}=r;if(0===s.length)break;for(const e of s)yield e;if(u+=s.length,u>=i)break}}async getRunStats({id:e,trace:t,parentRun:n,runType:r,projectNames:s,projectIds:i,referenceExampleIds:a,startTime:o,endTime:l,error:c,query:u,filter:d,traceFilter:h,treeFilter:p,isRoot:f,dataSourceType:m}){let g=i||[];s&&(g=[...i||[],...await Promise.all(s.map(e=>this.readProject({projectName:e}).then(e=>e.id)))]);const _={id:e,trace:t,parent_run:n,run_type:r,session:g,reference_example:a,start_time:o,end_time:l,error:c,query:u,filter:d,trace_filter:h,tree_filter:p,is_root:f,data_source_type:m},y=Object.fromEntries(Object.entries(_).filter(([e,t])=>void 0!==t)),v=await this.caller.call(Dr(this.debug),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(y),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v.json()}async shareRun(e,{shareId:t}={}){const n={run_id:e,share_token:t||Er()};ps(e);const r=await this.caller.call(Dr(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),s=await r.json();if(null===s||!("share_token"in s))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${s.share_token}/r`}async unshareRun(e){ps(e);const t=await this.caller.call(Dr(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(t,"unshare run",!0)}async readRunSharedLink(e){ps(e);const t=await this.caller.call(Dr(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await t.json();if(null!==n&&"share_token"in n)return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){const n=new URLSearchParams({share_token:e});if(void 0!==t)for(const e of t)n.append("id",e);ps(e);const r=await this.caller.call(Dr(this.debug),`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r.json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");if(!e){e=(await this.readDataset({datasetName:t})).id}ps(e);const n=await this.caller.call(Dr(this.debug),`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await n.json();return r.url=`${this.getHostUrl()}/public/${r.share_token}/d`,r}async shareDataset(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");if(!e){e=(await this.readDataset({datasetName:t})).id}const n={dataset_id:e};ps(e);const r=await this.caller.call(Dr(this.debug),`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),s=await r.json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async unshareDataset(e){ps(e);const t=await this.caller.call(Dr(this.debug),`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(t,"unshare dataset",!0)}async readSharedDataset(e){ps(e);const t=await this.caller.call(Dr(this.debug),`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await t.json()}async listSharedExamples(e,t){const n={};t?.exampleIds&&(n.id=t.exampleIds);const r=new URLSearchParams;Object.entries(n).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>r.append(e,t)):r.append(e,t)});const s=await this.caller.call(Dr(this.debug),`${this.apiUrl}/public/${e}/examples?${r.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),i=await s.json();if(!s.ok){if("detail"in i)throw new Error(`Failed to list shared examples.\nStatus: ${s.status}\nMessage: ${Array.isArray(i.detail)?i.detail.join("\n"):"Unspecified error"}`);throw new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`)}return i.map(e=>({...e,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:n=null,upsert:r=!1,projectExtra:s=null,referenceDatasetId:i=null}){const a=r?"?upsert=true":"",o=`${this.apiUrl}/sessions${a}`,l=s||{};n&&(l.metadata=n);const c={name:e,extra:l,description:t};null!==i&&(c.reference_dataset_id=i);const u=await this.caller.call(Dr(this.debug),o,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(u,"create project");return await u.json()}async updateProject(e,{name:t=null,description:n=null,metadata:r=null,projectExtra:s=null,endTime:i=null}){const a=`${this.apiUrl}/sessions/${e}`;let o=s;r&&(o={...o||{},metadata:r});const l={name:t,extra:o,description:n,end_time:i?new Date(i).toISOString():null},c=await this.caller.call(Dr(this.debug),a,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(c,"update project");return await c.json()}async hasProject({projectId:e,projectName:t}){let n="/sessions";const r=new URLSearchParams;if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");if(void 0!==e)ps(e),n+=`/${e}`;else{if(void 0===t)throw new Error("Must provide projectName or projectId");r.append("name",t)}const s=await this.caller.call(Dr(this.debug),`${this.apiUrl}${n}?${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{const e=await s.json();return!!s.ok&&(!Array.isArray(e)||e.length>0)}catch(e){return!1}}async readProject({projectId:e,projectName:t,includeStats:n}){let r="/sessions";const s=new URLSearchParams;if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");if(void 0!==e)ps(e),r+=`/${e}`;else{if(void 0===t)throw new Error("Must provide projectName or projectId");s.append("name",t)}void 0!==n&&s.append("include_stats",n.toString());const i=await this._get(r,s);let a;if(Array.isArray(i)){if(0===i.length)throw new Error(`Project[id=${e}, name=${t}] not found`);a=i[0]}else a=i;return a}async getProjectUrl({projectId:e,projectName:t}){if(void 0===e&&void 0===t)throw new Error("Must provide either projectName or projectId");const n=await this.readProject({projectId:e,projectName:t}),r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(void 0===e&&void 0===t)throw new Error("Must provide either datasetName or datasetId");const n=await this.readDataset({datasetId:e,datasetName:t}),r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/datasets/${n.id}`}async _getTenantId(){if(null!==this._tenantId)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:t,nameContains:n,referenceDatasetId:r,referenceDatasetName:s,referenceFree:i,metadata:a}={}){const o=new URLSearchParams;if(void 0!==e)for(const t of e)o.append("id",t);if(void 0!==t&&o.append("name",t),void 0!==n&&o.append("name_contains",n),void 0!==r)o.append("reference_dataset",r);else if(void 0!==s){const e=await this.readDataset({datasetName:s});o.append("reference_dataset",e.id)}void 0!==i&&o.append("reference_free",i.toString()),void 0!==a&&o.append("metadata",JSON.stringify(a));for await(const e of this._getPaginated("/sessions",o))yield*e}async deleteProject({projectId:e,projectName:t}){let n;if(void 0===e&&void 0===t)throw new Error("Must provide projectName or projectId");if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");n=void 0===e?(await this.readProject({projectName:t})).id:e,ps(n);const r=await this.caller.call(Dr(this.debug),`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(r,`delete session ${n} (${t})`,!0)}async uploadCsv({csvFile:e,fileName:t,inputKeys:n,outputKeys:r,description:s,dataType:i,name:a}){const o=`${this.apiUrl}/datasets/upload`,l=new FormData;l.append("file",e,t),n.forEach(e=>{l.append("input_keys",e)}),r.forEach(e=>{l.append("output_keys",e)}),s&&l.append("description",s),i&&l.append("data_type",i),a&&l.append("name",a);const c=await this.caller.call(Dr(this.debug),o,{method:"POST",headers:this.headers,body:l,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(c,"upload CSV");return await c.json()}async createDataset(e,{description:t,dataType:n,inputsSchema:r,outputsSchema:s,metadata:i}={}){const a={name:e,description:t,extra:i?{metadata:i}:void 0};n&&(a.data_type=n),r&&(a.inputs_schema_definition=r),s&&(a.outputs_schema_definition=s);const o=await this.caller.call(Dr(this.debug),`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(o,"create dataset");return await o.json()}async readDataset({datasetId:e,datasetName:t}){let n="/datasets";const r=new URLSearchParams({limit:"1"});if(e&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(e)ps(e),n+=`/${e}`;else{if(!t)throw new Error("Must provide datasetName or datasetId");r.append("name",t)}const s=await this._get(n,r);let i;if(Array.isArray(s)){if(0===s.length)throw new Error(`Dataset[id=${e}, name=${t}] not found`);i=s[0]}else i=s;return i}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(e){if(e instanceof Error&&e.message.toLocaleLowerCase().includes("not found"))return!1;throw e}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:n,toVersion:r}){let s=e;if(void 0===s&&void 0===t)throw new Error("Must provide either datasetName or datasetId");if(void 0!==s&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===s){s=(await this.readDataset({datasetName:t})).id}const i=new URLSearchParams({from_version:"string"==typeof n?n:n.toISOString(),to_version:"string"==typeof r?r:r.toISOString()});return await this._get(`/datasets/${s}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){if(void 0!==e);else{if(void 0===t)throw new Error("Must provide either datasetName or datasetId");e=(await this.readDataset({datasetName:t})).id}const n=await this._getResponse(`/datasets/${e}/openai_ft`);return(await n.text()).trim().split("\n").map(e=>JSON.parse(e))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:n,datasetName:r,datasetNameContains:s,metadata:i}={}){const a=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(void 0!==n)for(const e of n)a.append("id",e);void 0!==r&&a.append("name",r),void 0!==s&&a.append("name_contains",s),void 0!==i&&a.append("metadata",JSON.stringify(i));for await(const e of this._getPaginated("/datasets",a))yield*e}async updateDataset(e){const{datasetId:t,datasetName:n,...r}=e;if(!t&&!n)throw new Error("Must provide either datasetName or datasetId");const s=t??(await this.readDataset({datasetName:n})).id;ps(s);const i=await this.caller.call(Dr(this.debug),`${this.apiUrl}/datasets/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ys(i,"update dataset"),await i.json()}async updateDatasetTag(e){const{datasetId:t,datasetName:n,asOf:r,tag:s}=e;if(!t&&!n)throw new Error("Must provide either datasetName or datasetId");const i=t??(await this.readDataset({datasetName:n})).id;ps(i);const a=await this.caller.call(Dr(this.debug),`${this.apiUrl}/datasets/${i}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({as_of:"string"==typeof r?r:r.toISOString(),tag:s}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(a,"update dataset tags")}async deleteDataset({datasetId:e,datasetName:t}){let n="/datasets",r=e;if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==t){r=(await this.readDataset({datasetName:t})).id}if(void 0===r)throw new Error("Must provide datasetName or datasetId");ps(r),n+=`/${r}`;const s=await this.caller.call(Dr(this.debug),this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(s,`delete ${n}`),await s.json()}async indexDataset({datasetId:e,datasetName:t,tag:n}){let r=e;if(!r&&!t)throw new Error("Must provide either datasetName or datasetId");if(r&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(!r){r=(await this.readDataset({datasetName:t})).id}ps(r);const s={tag:n},i=await this.caller.call(Dr(this.debug),`${this.apiUrl}/datasets/${r}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(i,"index dataset"),await i.json()}async similarExamples(e,t,n,{filter:r}={}){const s={limit:n,inputs:e};void 0!==r&&(s.filter=r),ps(t);const i=await this.caller.call(Dr(this.debug),`${this.apiUrl}/datasets/${t}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(i,"fetch similar examples");return(await i.json()).examples}async createExample(e,t,n){if(Fs(e)&&(void 0!==t||void 0!==n))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let r=t?n?.datasetId:e.dataset_id;const s=t?n?.datasetName:e.dataset_name;if(void 0===r&&void 0===s)throw new Error("Must provide either datasetName or datasetId");if(void 0!==r&&void 0!==s)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===r){r=(await this.readDataset({datasetName:s})).id}const i=(t?n?.createdAt:e.created_at)||new Date;let a;a=Fs(e)?e:{inputs:e,outputs:t,created_at:i?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};const o=await this._uploadExamplesMultipart(r,[a]);return await this.readExample(o.example_ids?.[0]??Er())}async createExamples(e){if(Array.isArray(e)){if(0===e.length)return[];const t=e;let n=t[0].dataset_id;const r=t[0].dataset_name;if(void 0===n&&void 0===r)throw new Error("Must provide either datasetName or datasetId");if(void 0!==n&&void 0!==r)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===n){n=(await this.readDataset({datasetName:r})).id}const s=await this._uploadExamplesMultipart(n,t);return await Promise.all(s.example_ids.map(e=>this.readExample(e)))}const{inputs:t,outputs:n,metadata:r,splits:s,sourceRunIds:i,useSourceRunIOs:a,useSourceRunAttachments:o,attachments:l,exampleIds:c,datasetId:u,datasetName:d}=e;if(void 0===t)throw new Error("Must provide inputs when using legacy parameters");let h=u;const p=d;if(void 0===h&&void 0===p)throw new Error("Must provide either datasetName or datasetId");if(void 0!==h&&void 0!==p)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===h){const e=await this.readDataset({datasetName:p});h=e.id}const f=t.map((e,t)=>({dataset_id:h,inputs:e,outputs:n?.[t],metadata:r?.[t],split:s?.[t],id:c?.[t],attachments:l?.[t],source_run_id:i?.[t],use_source_run_io:a?.[t],use_source_run_attachments:o?.[t]})),m=await this._uploadExamplesMultipart(h,f);return await Promise.all(m.example_ids.map(e=>this.readExample(e)))}async createLLMExample(e,t,n){return this.createExample({input:e},{output:t},n)}async createChatExample(e,t,n){const r=e.map(e=>us(e)?ds(e):e),s=us(t)?ds(t):t;return this.createExample({input:r},{output:s},n)}async readExample(e){ps(e);const t=`/examples/${e}`,n=await this._get(t),{attachment_urls:r,...s}=n,i=s;return r&&(i.attachments=Object.entries(r).reduce((e,[t,n])=>(e[t.slice(11)]={presigned_url:n.presigned_url,mime_type:n.mime_type},e),{})),i}async*listExamples({datasetId:e,datasetName:t,exampleIds:n,asOf:r,splits:s,inlineS3Urls:i,metadata:a,limit:o,offset:l,filter:c,includeAttachments:u}={}){let d;if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)d=e;else{if(void 0===t)throw new Error("Must provide a datasetName or datasetId");d=(await this.readDataset({datasetName:t})).id}const h=new URLSearchParams({dataset:d}),p=r?"string"==typeof r?r:r?.toISOString():void 0;p&&h.append("as_of",p);const f=i??!0;if(h.append("inline_s3_urls",f.toString()),void 0!==n)for(const e of n)h.append("id",e);if(void 0!==s)for(const e of s)h.append("splits",e);if(void 0!==a){const e=JSON.stringify(a);h.append("metadata",e)}void 0!==o&&h.append("limit",o.toString()),void 0!==l&&h.append("offset",l.toString()),void 0!==c&&h.append("filter",c),!0===u&&["attachment_urls","outputs","metadata"].forEach(e=>h.append("select",e));let m=0;for await(const e of this._getPaginated("/examples",h)){for(const t of e){const{attachment_urls:e,...n}=t,r=n;e&&(r.attachments=Object.entries(e).reduce((e,[t,n])=>(e[t.slice(11)]={presigned_url:n.presigned_url,mime_type:n.mime_type||void 0},e),{})),yield r,m++}if(void 0!==o&&m>=o)break}}async deleteExample(e){ps(e);const t=`/examples/${e}`,n=await this.caller.call(Dr(this.debug),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(n,`delete ${t}`),await n.json()}async updateExample(e,t){let n,r,s;if(n=t?e:e.id,ps(n),r=t?{id:n,...t}:e,void 0!==r.dataset_id)s=r.dataset_id;else{s=(await this.readExample(n)).dataset_id}return this._updateExamplesMultipart(s,[r])}async updateExamples(e){let t;if(void 0===e[0].dataset_id){t=(await this.readExample(e[0].id)).dataset_id}else t=e[0].dataset_id;return this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:n,tag:r}){let s;if(e)s=e;else{s=(await this.readDataset({datasetName:t})).id}if(ps(s),n&&r||!n&&!r)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;void 0!==n&&i.append("as_of","string"==typeof n?n:n.toISOString()),void 0!==r&&i.append("tag",r);const a=await this.caller.call(Dr(this.debug),`${this.apiUrl}/datasets/${s}/version?${i.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ys(a,"read dataset version"),await a.json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:n}){let r;if(void 0===e&&void 0===t)throw new Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===e){r=(await this.readDataset({datasetName:t})).id}else r=e;ps(r);const s=new URLSearchParams,i=n?"string"==typeof n?n:n?.toISOString():void 0;i&&s.append("as_of",i);return await this._get(`/datasets/${r}/splits`,s)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:n,exampleIds:r,remove:s=!1}){let i;if(void 0===e&&void 0===t)throw new Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===e){i=(await this.readDataset({datasetName:t})).id}else i=e;ps(i);const a={split_name:n,examples:r.map(e=>(ps(e),e)),remove:s},o=await this.caller.call(Dr(this.debug),`${this.apiUrl}/datasets/${i}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(o,"update dataset splits",!0)}async evaluateRun(e,t,{sourceInfo:n,loadChildRuns:r,referenceExample:s}={loadChildRuns:!1}){let i;if(ms("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."),"string"==typeof e)i=await this.readRun(e,{loadChildRuns:r});else{if("object"!=typeof e||!("id"in e))throw new Error("Invalid run type: "+typeof e);i=e}null!==i.reference_example_id&&void 0!==i.reference_example_id&&(s=await this.readExample(i.reference_example_id));const a=await t.evaluateRun(i,s),[o,l]=await this._logEvaluationFeedback(a,i,n);return l[0]}async createFeedback(e,t,{score:n,value:r,correction:s,comment:i,sourceInfo:a,feedbackSourceType:o="api",sourceRunId:l,feedbackId:c,feedbackConfig:u,projectId:d,comparativeExperimentId:h}){if(!e&&!d)throw new Error("One of runId or projectId must be provided");if(e&&d)throw new Error("Only one of runId or projectId can be provided");const p={type:o??"api",metadata:a??{}};void 0===l||void 0===p?.metadata||p.metadata.__run||(p.metadata.__run={run_id:l}),void 0!==p?.metadata&&void 0!==p.metadata.__run?.run_id&&ps(p.metadata.__run.run_id);const f={id:c??Er(),run_id:e,key:t,score:Ls(n),value:r,correction:s,comment:i,feedback_source:p,comparative_experiment_id:h,feedbackConfig:u,session_id:d},m=`${this.apiUrl}/feedback`,g=await this.caller.call(Dr(this.debug),m,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(f),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ys(g,"create feedback",!0),f}async updateFeedback(e,{score:t,value:n,correction:r,comment:s}){const i={};null!=t&&(i.score=Ls(t)),null!=n&&(i.value=n),null!=r&&(i.correction=r),null!=s&&(i.comment=s),ps(e);const a=await this.caller.call(Dr(this.debug),`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(a,"update feedback",!0)}async readFeedback(e){ps(e);const t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){ps(e);const t=`/feedback/${e}`,n=await this.caller.call(Dr(this.debug),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(n,`delete ${t}`),await n.json()}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:n}={}){const r=new URLSearchParams;if(e&&r.append("run",e.join(",")),t)for(const e of t)r.append("key",e);if(n)for(const e of n)r.append("source",e);for await(const e of this._getPaginated("/feedback",r))yield*e}async createPresignedFeedbackToken(e,t,{expiration:n,feedbackConfig:r}={}){const s={run_id:e,feedback_key:t,feedback_config:r};n?"string"==typeof n?s.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(s.expires_in=n):s.expires_in={hours:3};const i=await this.caller.call(Dr(this.debug),`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await i.json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:n,createdAt:r,description:s,metadata:i,id:a}){if(0===t.length)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:t[0]})).reference_dataset_id),null==!n)throw new Error("A reference dataset is required");const o={id:a,name:e,experiment_ids:t,reference_dataset_id:n,description:s,created_at:(r??new Date)?.toISOString(),extra:{}};i&&(o.extra.metadata=i);const l=await this.caller.call(Dr(this.debug),`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await l.json()}async*listPresignedFeedbackTokens(e){ps(e);const t=new URLSearchParams({run_id:e});for await(const e of this._getPaginated("/feedback/tokens",t))yield*e}_selectEvalResults(e){let t;return t="results"in e?e.results:Array.isArray(e)?e:[e],t}async _logEvaluationFeedback(e,t,n){const r=this._selectEvalResults(e),s=[];for(const e of r){let r=n||{};e.evaluatorInfo&&(r={...e.evaluatorInfo,...r});let i=null;e.targetRunId?i=e.targetRunId:t&&(i=t.id),s.push(await this.createFeedback(i,e.key,{score:e.score,value:e.value,comment:e.comment,correction:e.correction,sourceInfo:r,sourceRunId:e.sourceRunId,feedbackConfig:e.feedbackConfig,feedbackSourceType:"model"}))}return[r,s]}async logEvaluationFeedback(e,t,n){const[r]=await this._logEvaluationFeedback(e,t,n);return r}async*listAnnotationQueues(e={}){const{queueIds:t,name:n,nameContains:r,limit:s}=e,i=new URLSearchParams;t&&t.forEach((e,t)=>{ps(e,`queueIds[${t}]`),i.append("ids",e)}),n&&i.append("name",n),r&&i.append("name_contains",r),i.append("limit",(void 0!==s?Math.min(s,100):100).toString());let a=0;for await(const e of this._getPaginated("/annotation-queues",i))if(yield*e,a++,void 0!==s&&a>=s)break}async createAnnotationQueue(e){const{name:t,description:n,queueId:r,rubricInstructions:s}=e,i={name:t,description:n,id:r||Er(),rubric_instructions:s},a=await this.caller.call(Dr(this.debug),`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(Object.fromEntries(Object.entries(i).filter(([e,t])=>void 0!==t))),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(a,"create annotation queue");return await a.json()}async readAnnotationQueue(e){const t=await this.caller.call(Dr(this.debug),`${this.apiUrl}/annotation-queues/${ps(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(t,"read annotation queue");return await t.json()}async updateAnnotationQueue(e,t){const{name:n,description:r,rubricInstructions:s}=t,i=await this.caller.call(Dr(this.debug),`${this.apiUrl}/annotation-queues/${ps(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({name:n,description:r,rubric_instructions:s}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(i,"update annotation queue")}async deleteAnnotationQueue(e){const t=await this.caller.call(Dr(this.debug),`${this.apiUrl}/annotation-queues/${ps(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(t,"delete annotation queue")}async addRunsToAnnotationQueue(e,t){const n=await this.caller.call(Dr(this.debug),`${this.apiUrl}/annotation-queues/${ps(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t.map((e,t)=>ps(e,`runIds[${t}]`).toString())),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(n,"add runs to annotation queue")}async getRunFromAnnotationQueue(e,t){const n=`/annotation-queues/${ps(e,"queueId")}/run`,r=await this.caller.call(Dr(this.debug),`${this.apiUrl}${n}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ys(r,"get run from annotation queue"),await r.json()}async deleteRunFromAnnotationQueue(e,t){const n=await this.caller.call(Dr(this.debug),`${this.apiUrl}/annotation-queues/${ps(e,"queueId")}/runs/${ps(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(n,"delete run from annotation queue")}async getSizeFromAnnotationQueue(e){const t=await this.caller.call(Dr(this.debug),`${this.apiUrl}/annotation-queues/${ps(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ys(t,"get size from annotation queue"),await t.json()}async _currentTenantIsOwner(e){const t=await this._getSettings();return"-"==e||t.tenant_handle===e}async _ownerConflictError(e,t){const n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.\n\n Current tenant: ${n.tenant_handle}\n\n Requested tenant: ${t}`)}async _getLatestCommitHash(e){const t=await this.caller.call(Dr(this.debug),`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await t.json();if(!t.ok){const e="string"==typeof n.detail?n.detail:JSON.stringify(n.detail),r=new Error(`Error ${t.status}: ${t.statusText}\n${e}`);throw r.statusCode=t.status,r}if(0!==n.commits.length)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){const[n,r,s]=gs(e),i=await this.caller.call(Dr(this.debug),`${this.apiUrl}/likes/${n}/${r}`,{method:"POST",body:JSON.stringify({like:t}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ys(i,(t?"like":"unlike")+" prompt"),await i.json()}async _getPromptUrl(e){const[t,n,r]=gs(e);if(await this._currentTenantIsOwner(t)){const e=await this._getSettings();return"latest"!==r?`${this.getHostUrl()}/prompts/${n}/${r.substring(0,8)}?organizationId=${e.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${e.id}`}return"latest"!==r?`${this.getHostUrl()}/hub/${t}/${n}/${r.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${n}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(const t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,e=>e.commits))yield*t}async*listPrompts(e){const t=new URLSearchParams;t.append("sort_field",e?.sortField??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!e?.isArchived).toString()),void 0!==e?.isPublic&&t.append("is_public",e.isPublic.toString()),e?.query&&t.append("query",e.query);for await(const e of this._getPaginated("/repos",t,e=>e.repos))yield*e}async getPrompt(e){const[t,n,r]=gs(e),s=await this.caller.call(Dr(this.debug),`${this.apiUrl}/repos/${t}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(404===s.status)return null;await ys(s,"get prompt");const i=await s.json();return i.repo?i.repo:null}async createPrompt(e,t){const n=await this._getSettings();if(t?.isPublic&&!n.tenant_handle)throw new Error("Cannot create a public prompt without first\n\n creating a LangChain Hub handle.\n You can add a handle by creating a public prompt at:\n\n https://smith.langchain.com/prompts");const[r,s,i]=gs(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("create a prompt",r);const a={repo_handle:s,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},o=await this.caller.call(Dr(this.debug),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(o,"create prompt");const{repo:l}=await o.json();return l}async createCommit(e,t,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,s,i]=gs(e),a="latest"!==n?.parentCommitHash&&n?.parentCommitHash?n?.parentCommitHash:await this._getLatestCommitHash(`${r}/${s}`),o={manifest:JSON.parse(JSON.stringify(t)),parent_commit:a},l=await this.caller.call(Dr(this.debug),`${this.apiUrl}/commits/${r}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(l,"create commit");const c=await l.json();return this._getPromptUrl(`${r}/${s}${c.commit_hash?`:${c.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){if(!await this._getMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const n=new FormData;for(const e of t){const t=e.id,r=As({...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}}),s=new Blob([r],{type:"application/json"});if(n.append(t,s),e.inputs){const r=As(e.inputs),s=new Blob([r],{type:"application/json"});n.append(`${t}.inputs`,s)}if(e.outputs){const r=As(e.outputs),s=new Blob([r],{type:"application/json"});n.append(`${t}.outputs`,s)}if(e.attachments)for(const[r,s]of Object.entries(e.attachments)){let e,i;Array.isArray(s)?[e,i]=s:(e=s.mimeType,i=s.data);const a=new Blob([i],{type:`${e}; length=${i.byteLength}`});n.append(`${t}.attachment.${r}`,a)}if(e.attachments_operations){const r=As(e.attachments_operations),s=new Blob([r],{type:"application/json"});n.append(`${t}.attachments_operations`,s)}}const r=e??t[0]?.dataset_id,s=await this.caller.call(Dr(this.debug),`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${r}/examples`)}`,{method:"PATCH",headers:this.headers,body:n});return await s.json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){if(!await this._getMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const n=new FormData;for(const e of t){const t=(e.id??Er()).toString(),r=As({created_at:e.created_at,...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split},...e.source_run_id&&{source_run_id:e.source_run_id},...e.use_source_run_io&&{use_source_run_io:e.use_source_run_io},...e.use_source_run_attachments&&{use_source_run_attachments:e.use_source_run_attachments}}),s=new Blob([r],{type:"application/json"});if(n.append(t,s),e.inputs){const r=As(e.inputs),s=new Blob([r],{type:"application/json"});n.append(`${t}.inputs`,s)}if(e.outputs){const r=As(e.outputs),s=new Blob([r],{type:"application/json"});n.append(`${t}.outputs`,s)}if(e.attachments)for(const[r,s]of Object.entries(e.attachments)){let e,i;Array.isArray(s)?[e,i]=s:(e=s.mimeType,i=s.data);const a=new Blob([i],{type:`${e}; length=${i.byteLength}`});n.append(`${t}.attachment.${r}`,a)}}const r=await this.caller.call(Dr(this.debug),`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,body:n});await ys(r,"upload examples");return await r.json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[n,r]=gs(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);const s={};if(void 0!==t?.description&&(s.description=t.description),void 0!==t?.readme&&(s.readme=t.readme),void 0!==t?.tags&&(s.tags=t.tags),void 0!==t?.isPublic&&(s.is_public=t.isPublic),void 0!==t?.isArchived&&(s.is_archived=t.isArchived),0===Object.keys(s).length)throw new Error("No valid update options provided");const i=await this.caller.call(Dr(this.debug),`${this.apiUrl}/repos/${n}/${r}`,{method:"PATCH",body:JSON.stringify(s),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ys(i,"update prompt"),i.json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[t,n,r]=gs(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);const s=await this.caller.call(Dr(this.debug),`${this.apiUrl}/repos/${t}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await s.json()}async pullPromptCommit(e,t){const[n,r,s]=gs(e),i=await this.caller.call(Dr(this.debug),`${this.apiUrl}/commits/${n}/${r}/${s}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await ys(i,"pull prompt commit");const a=await i.json();return{owner:n,repo:r,commit_hash:a.commit_hash,manifest:a.manifest,examples:a.examples}}async _pullPrompt(e,t){const n=await this.pullPromptCommit(e,{includeModel:t?.includeModel});return JSON.stringify(n.manifest)}async pushPrompt(e,t){if(await this.promptExists(e)?t&&Object.keys(t).some(e=>"object"!==e)&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),!t?.object)return await this._getPromptUrl(e);return await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash})}async clonePublicDataset(e,t={}){const{sourceApiUrl:n=this.apiUrl,datasetName:r}=t,[s,i]=this.parseTokenOrUrl(e,n),a=new Us({apiUrl:s,apiKey:"placeholder"}),o=await a.readSharedDataset(i),l=r||o.name;try{if(await this.hasDataset({datasetId:l}))return}catch(e){}const c=await a.listSharedExamples(i),u=await this.createDataset(l,{description:o.description,dataType:o.data_type||"kv",inputsSchema:o.inputs_schema_definition??void 0,outputsSchema:o.outputs_schema_definition??void 0});try{await this.createExamples({inputs:c.map(e=>e.inputs),outputs:c.flatMap(e=>e.outputs?[e.outputs]:[]),datasetId:u.id})}catch(e){throw e}}parseTokenOrUrl(e,t,n=2,r="dataset"){try{return ps(e),[t,e]}catch(e){}try{const s=new URL(e).pathname.split("/").filter(e=>""!==e);if(s.length>=n){return[t,s[s.length-n]]}throw new Error(`Invalid public ${r} URL: ${e}`)}catch(t){throw new Error(`Invalid public ${r} URL or token: ${e}`)}}async awaitPendingTraceBatches(){if(this.manualFlushMode)return Promise.resolve();await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),void 0!==this.langSmithToOTELTranslator&&await(ns.getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush())}}function Fs(e){return"dataset_id"in e||"dataset_name"in e}const Bs=Symbol.for("lc:context_variables");function qs(e,t,n=1){const r=n.toFixed(0).slice(0,3).padStart(3,"0"),s=`${new Date(e).toISOString().slice(0,-1)}${r}Z`;return{dottedOrder:(i=s,i.replace(/[-:.]/g,"")+t),microsecondPrecisionDatestring:s};var i}class zs{constructor(e,t,n,r){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=t,this.project_name=n,this.replicas=r}static fromHeader(e){const t=e.split(",");let n,r,s={},i=[];for(const e of t){const[t,a]=e.split("="),o=decodeURIComponent(a);"langsmith-metadata"===t?s=JSON.parse(o):"langsmith-tags"===t?i=o.split(","):"langsmith-project"===t?n=o:"langsmith-replicas"===t&&(r=JSON.parse(o))}return new zs(s,i,n,r)}toHeader(){const e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class Hs{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),function(e){return void 0!==e&&"function"==typeof e.createChild&&"function"==typeof e.postRun}(e))return void Object.assign(this,{...e});const t=Hs.getDefaultConfig(),{metadata:n,...r}=e,s=r.client??Hs.getSharedClient(),i={...n,...r?.extra?.metadata};if(r.extra={...r.extra,metadata:i},Object.assign(this,{...t,...r,client:s}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=function(e){if(e)return e.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e);return function(){const e=Jr("LANGSMITH_RUNS_ENDPOINTS");if(!e)return[];try{const t=JSON.parse(e);return function(e){if(Object.keys(e).length>0&&Zr("ENDPOINT"))throw new bs}(t),Object.entries(t).map(([e,t])=>({apiUrl:e.replace(/\/$/,""),apiKey:t}))}catch(e){if("object"==typeof(t=e)&&null!==t&&t.code===vs)throw e;return[]}var t}()}(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const{dottedOrder:e,microsecondPrecisionDatestring:t}=qs(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+e:this.dotted_order=e,this._serialized_start_time=t}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){return{id:Er(),run_type:"chain",project_name:Ur(),child_runs:[],api_url:Jr("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Jr("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return Hs.sharedClient||(Hs.sharedClient=new Us),Hs.sharedClient}createChild(e){const t=this.child_execution_order+1,n=new Hs({...e,parent_run:this,project_name:this.project_name,replicas:this.replicas,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t});Bs in this&&(n[Bs]=this[Bs]);const r=Symbol.for("lc:child_config"),s=e.extra?.[r]??this.extra[r];if(function(e){return void 0!==e&&"object"==typeof e.callbacks&&(Gs(e.callbacks?.handlers)||Gs(e.callbacks))}(s)){const e={...s},t=function(e){return"object"==typeof e&&null!=e&&Array.isArray(e.handlers)}(e.callbacks)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:n.id}),t.handlers?.find(Ws)?.updateFromRunTree?.(n),e.callbacks=t),n.extra[r]=e}const i=new Set;let a=this;for(;null!=a&&!i.has(a.id);)i.add(a.id),a.child_execution_order=Math.max(a.child_execution_order,t),a=a.parent_run;return this.child_runs.push(n),n}async end(e,t,n=Date.now(),r){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??n,r&&Object.keys(r).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...r}}:{metadata:r})}_convertToCreate(e,t,n=!0){const r=e.extra??{};if(void 0===r?.runtime?.library&&(r.runtime||(r.runtime={}),t))for(const[e,n]of Object.entries(t))r.runtime[e]||(r.runtime[e]=n);let s,i;return n?(i=e.parent_run?.id??e.parent_run_id,s=[]):(s=e.child_runs.map(e=>this._convertToCreate(e,t,n)),i=void 0),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:r,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:s,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_remapForProject(e,t,n=!0){const r=this._convertToCreate(this,t,n);if(e===this.project_name)return r;const s=t=>Pr(`${t}:${e}`,Pr.DNS),i=s(r.id),a=r.trace_id?s(r.trace_id):void 0,o=r.parent_run_id?s(r.parent_run_id):void 0;let l;if(r.dotted_order){const e=r.dotted_order.split(".").map(e=>{const t=e.slice(0,-36),n=e.slice(-36),r=parseInt(t.slice(0,4)),s=parseInt(t.slice(4,6))-1,i=parseInt(t.slice(6,8)),a=parseInt(t.slice(9,11)),o=parseInt(t.slice(11,13)),l=parseInt(t.slice(13,15)),c=parseInt(t.slice(15,21));return[new Date(r,s,i,a,o,l,c/1e3),n]}),t=[];for(let n=0;n0)for(const{projectName:e,apiKey:n,apiUrl:r}of this.replicas){const s=this._remapForProject(e??this.project_name,t,!0);await this.client.createRun(s,{apiKey:n,apiUrl:r})}else{const n=this._convertToCreate(this,t,e);await this.client.createRun(n)}if(!e){ms("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const e of this.child_runs)await e.postRun(!1)}}catch(e){}}async patchRun(){if(this.replicas&&this.replicas.length>0)for(const{projectName:e,apiKey:t,apiUrl:n,updates:r}of this.replicas){const s=this._remapForProject(e??this.project_name);await this.client.updateRun(s.id,{inputs:s.inputs,outputs:s.outputs,error:s.error,parent_run_id:s.parent_run_id,session_name:s.session_name,reference_example_id:s.reference_example_id,end_time:s.end_time,dotted_order:s.dotted_order,trace_id:s.trace_id,events:s.events,tags:s.tags,extra:s.extra,attachments:this.attachments,...r},{apiKey:t,apiUrl:n})}else try{const e={end_time:this.end_time,error:this.error,inputs:this.inputs,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};await this.client.updateRun(this.id,e)}catch(e){}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),"string"==typeof e?this.events.push({name:"event",time:(new Date).toISOString(),message:e}):this.events.push({...e,time:e.time??(new Date).toISOString()})}static fromRunnableConfig(e,t){const n=e?.callbacks;let r,s,i,a=(e=>void 0!==e?e:!!["TRACING_V2","TRACING"].find(e=>"true"===Zr(e)))();if(n){const e=n?.getParentRunId?.()??"",t=n?.handlers?.find(e=>"langchain_tracer"==e?.name);r=t?.getRun?.(e),s=t?.projectName,i=t?.client,a=a||!!t}if(!r)return new Hs({...t,client:i,tracingEnabled:a,project_name:s});return new Hs({name:r.name,id:r.id,trace_id:r.trace_id,dotted_order:r.dotted_order,client:i,tracingEnabled:a,project_name:s,tags:[...new Set((r?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...r?.extra?.metadata,...e?.metadata}}}).createChild(t)}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){const n="get"in e&&"function"==typeof e.get?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,r=n["langsmith-trace"];if(!r||"string"!=typeof r)return;const s=r.trim(),i=s.split(".").map(e=>{const[t,n]=e.split("Z");return{strTime:t,time:Date.parse(t+"Z"),uuid:n}}),a=i[0].uuid,o={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:i.at(-1)?.uuid,trace_id:a,dotted_order:s};if(n.baggage&&"string"==typeof n.baggage){const e=zs.fromHeader(n.baggage);o.metadata=e.metadata,o.tags=e.tags,o.project_name=e.project_name,o.replicas=e.replicas}return new Hs(o)}toHeaders(e){const t={"langsmith-trace":this.dotted_order,baggage:new zs(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[n,r]of Object.entries(t))e.set(n,r);return t}}function Ws(e){return"object"==typeof e&&null!=e&&"string"==typeof e.name&&"langchain_tracer"===e.name}function Gs(e){return Array.isArray(e)&&e.some(e=>Ws(e))}Object.defineProperty(Hs,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});const Ks=()=>"undefined"!=typeof Deno,Js=()=>{let e;return e="undefined"!=typeof window&&void 0!==window.document?"browser":"undefined"==typeof process||void 0===process.versions||void 0===process.versions.node||Ks()?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&navigator.userAgent.includes("jsdom")?"jsdom":Ks()?"deno":"other":"node",e};let Zs;function Vs(){if(void 0===Zs){const e=Js();Zs={library:"langchain-js",runtime:e}}return Zs}function Ys(e){try{return"undefined"!=typeof process?process.env?.[e]:Ks()?Deno?.env.get(e):void 0}catch(e){return}}class Xs{}function Qs(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}class ei extends Xs{get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Jt(this.constructor)]}constructor(e){super(),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ignoreLLM",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreChain",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreAgent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreRetriever",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"raiseError",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"awaitHandlers",{enumerable:!0,configurable:!0,writable:!0,value:"false"===Ys("LANGCHAIN_CALLBACKS_BACKGROUND")}),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return Zt.prototype.toJSON.call(this)}toJSONNotImplemented(){return Zt.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){return new class extends ei{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:Bn()}),Object.assign(this,e)}}}}const ti=e=>{const t=e;return void 0!==t&&"function"==typeof t.copy&&"string"==typeof t.name&&"boolean"==typeof t.awaitHandlers};function ni(e,t){if(e)return new Hs({...e,start_time:e._serialized_start_time??e.start_time,parent_run:ni(t),child_runs:e.child_runs.map(e=>ni(e)).filter(e=>void 0!==e),extra:{...e.extra,runtime:Vs()},tracingEnabled:!1})}function ri(e,t){return e&&!Array.isArray(e)&&"object"==typeof e?e:{[t]:e}}function si(e){return"function"==typeof e._addRunToRunMap}class ii extends ei{constructor(e){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"runTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"usesRunTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:!1})}copy(){return this}getRunById(e){if(void 0!==e)return this.usesRunTreeMap?(e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e})(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`\n\n${e.stack}`:""):"string"==typeof e?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const{dottedOrder:t,microsecondPrecisionDatestring:n}=qs(new Date(e.start_time).getTime(),e.id,e.execution_order),r={...e},s=this.getRunById(r.parent_run_id);if(void 0!==r.parent_run_id?s&&(this._addChildRun(s,r),s.child_execution_order=Math.max(s.child_execution_order,r.child_execution_order),r.trace_id=s.trace_id,void 0!==s.dotted_order&&(r.dotted_order=[s.dotted_order,t].join("."),r._serialized_start_time=n)):(r.trace_id=r.id,r.dotted_order=t,r._serialized_start_time=n),this.usesRunTreeMap){const e=ni(r,s);void 0!==e&&this.runTreeMap.set(r.id,e)}else this.runMap.set(r.id,r);return r}async _endTrace(e){const t=void 0!==e.parent_run_id&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await(this.onRunUpdate?.(e)),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){const t=void 0!==e&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,n,r,s,i,a,o){const l=this._getExecutionOrder(r),c=Date.now(),u=a?{...s,metadata:a}:s,d={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{prompts:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:u??{},tags:i||[]};return this._addRunToRunMap(d)}async handleLLMStart(e,t,n,r,s,i,a,o){const l=this.getRunById(n)??this._createRunForLLMStart(e,t,n,r,s,i,a,o);return await(this.onRunCreate?.(l)),await(this.onLLMStart?.(l)),l}_createRunForChatModelStart(e,t,n,r,s,i,a,o){const l=this._getExecutionOrder(r),c=Date.now(),u=a?{...s,metadata:a}:s,d={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{messages:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:u??{},tags:i||[]};return this._addRunToRunMap(d)}async handleChatModelStart(e,t,n,r,s,i,a,o){const l=this.getRunById(n)??this._createRunForChatModelStart(e,t,n,r,s,i,a,o);return await(this.onRunCreate?.(l)),await(this.onLLMStart?.(l)),l}async handleLLMEnd(e,t,n,r,s){const i=this.getRunById(t);if(!i||"llm"!==i?.run_type)throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.outputs=e,i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...s},await(this.onLLMEnd?.(i)),await this._endTrace(i),i}async handleLLMError(e,t,n,r,s){const i=this.getRunById(t);if(!i||"llm"!==i?.run_type)throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...s},await(this.onLLMError?.(i)),await this._endTrace(i),i}_createRunForChainStart(e,t,n,r,s,i,a,o){const l=this._getExecutionOrder(r),c=Date.now(),u={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:t,execution_order:l,child_execution_order:l,run_type:a??"chain",child_runs:[],extra:i?{metadata:i}:{},tags:s||[]};return this._addRunToRunMap(u)}async handleChainStart(e,t,n,r,s,i,a,o){const l=this.getRunById(n)??this._createRunForChainStart(e,t,n,r,s,i,a,o);return await(this.onRunCreate?.(l)),await(this.onChainStart?.(l)),l}async handleChainEnd(e,t,n,r,s){const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=ri(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),void 0!==s?.inputs&&(i.inputs=ri(s.inputs,"input")),await(this.onChainEnd?.(i)),await this._endTrace(i),i}async handleChainError(e,t,n,r,s){const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),void 0!==s?.inputs&&(i.inputs=ri(s.inputs,"input")),await(this.onChainError?.(i)),await this._endTrace(i),i}_createRunForToolStart(e,t,n,r,s,i,a){const o=this._getExecutionOrder(r),l=Date.now(),c={id:n,name:a??e.id[e.id.length-1],parent_run_id:r,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:s||[]};return this._addRunToRunMap(c)}async handleToolStart(e,t,n,r,s,i,a){const o=this.getRunById(n)??this._createRunForToolStart(e,t,n,r,s,i,a);return await(this.onRunCreate?.(o)),await(this.onToolStart?.(o)),o}async handleToolEnd(e,t){const n=this.getRunById(t);if(!n||"tool"!==n?.run_type)throw new Error("No tool run to end");return n.end_time=Date.now(),n.outputs={output:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await(this.onToolEnd?.(n)),await this._endTrace(n),n}async handleToolError(e,t){const n=this.getRunById(t);if(!n||"tool"!==n?.run_type)throw new Error("No tool run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await(this.onToolError?.(n)),await this._endTrace(n),n}async handleAgentAction(e,t){const n=this.getRunById(t);if(!n||"chain"!==n?.run_type)return;const r=n;r.actions=r.actions||[],r.actions.push(e),r.events.push({name:"agent_action",time:(new Date).toISOString(),kwargs:{action:e}}),await(this.onAgentAction?.(n))}async handleAgentEnd(e,t){const n=this.getRunById(t);n&&"chain"===n?.run_type&&(n.events.push({name:"agent_end",time:(new Date).toISOString(),kwargs:{action:e}}),await(this.onAgentEnd?.(n)))}_createRunForRetrieverStart(e,t,n,r,s,i,a){const o=this._getExecutionOrder(r),l=Date.now(),c={id:n,name:a??e.id[e.id.length-1],parent_run_id:r,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:s||[]};return this._addRunToRunMap(c)}async handleRetrieverStart(e,t,n,r,s,i,a){const o=this.getRunById(n)??this._createRunForRetrieverStart(e,t,n,r,s,i,a);return await(this.onRunCreate?.(o)),await(this.onRetrieverStart?.(o)),o}async handleRetrieverEnd(e,t){const n=this.getRunById(t);if(!n||"retriever"!==n?.run_type)throw new Error("No retriever run to end");return n.end_time=Date.now(),n.outputs={documents:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await(this.onRetrieverEnd?.(n)),await this._endTrace(n),n}async handleRetrieverError(e,t){const n=this.getRunById(t);if(!n||"retriever"!==n?.run_type)throw new Error("No retriever run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await(this.onRetrieverError?.(n)),await this._endTrace(n),n}async handleText(e,t){const n=this.getRunById(t);n&&"chain"===n?.run_type&&(n.events.push({name:"text",time:(new Date).toISOString(),kwargs:{text:e}}),await(this.onText?.(n)))}async handleLLMNewToken(e,t,n,r,s,i){const a=this.getRunById(n);if(!a||"llm"!==a?.run_type)throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return a.events.push({name:"new_token",time:(new Date).toISOString(),kwargs:{token:e,idx:t,chunk:i?.chunk}}),await(this.onLLMNewToken?.(a,e,{chunk:i?.chunk})),a}}var ai=n(9418);function oi(e,t){return`${e.open}${t}${e.close}`}const{color:li}=ai;class ci extends ii{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(e){return Promise.resolve()}getParents(e){const t=[];let n=e;for(;n.parent_run_id;){const e=this.runMap.get(n.parent_run_id);if(!e)break;t.push(e),n=e}return t}getBreadcrumbs(e){const t=[...this.getParents(e).reverse(),e].map((e,t,n)=>{const r=`${e.execution_order}:${e.run_type}:${e.name}`;return t===n.length-1?oi(ai.bold,r):r}).join(" > ");return oi(li.grey,t)}onChainStart(e){this.getBreadcrumbs(e)}onChainEnd(e){this.getBreadcrumbs(e)}onChainError(e){this.getBreadcrumbs(e)}onLLMStart(e){this.getBreadcrumbs(e),"prompts"in e.inputs?e.inputs.prompts.map(e=>e.trim()):e.inputs}onLLMEnd(e){this.getBreadcrumbs(e)}onLLMError(e){this.getBreadcrumbs(e)}onToolStart(e){this.getBreadcrumbs(e)}onToolEnd(e){this.getBreadcrumbs(e)}onToolError(e){this.getBreadcrumbs(e)}onRetrieverStart(e){this.getBreadcrumbs(e)}onRetrieverEnd(e){this.getBreadcrumbs(e)}onRetrieverError(e){this.getBreadcrumbs(e)}onAgentAction(e){this.getBreadcrumbs(e)}}let ui;const di=()=>{if(void 0===ui){const e="false"===Ys("LANGCHAIN_CALLBACKS_BACKGROUND")?{blockOnRootRunFinalization:!0}:{};ui=new Us(e)}return ui};class hi extends ii{constructor(e={}){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"usesRunTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:!0});const{exampleId:t,projectName:n,client:r,replicas:s}=e;this.projectName=n??Ur(),this.replicas=s,this.exampleId=t,this.client=r??di();const i=hi.getTraceableRunTree();i&&this.updateFromRunTree(i)}async persistRun(e){}async onRunCreate(e){const t=this.getRunTreeWithTracingConfig(e.id);await(t?.postRun())}async onRunUpdate(e){const t=this.getRunTreeWithTracingConfig(e.id);await(t?.patchRun())}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){let t=e;const n=new Set;for(;t.parent_run&&!n.has(t.id)&&(n.add(t.id),t.parent_run);)t=t.parent_run;n.clear();const r=[t];for(;r.length>0;){const e=r.shift();e&&!n.has(e.id)&&(n.add(e.id),this.runTreeMap.set(e.id,e),e.child_runs&&r.push(...e.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(e){const t=this.runTreeMap.get(e);if(t)return new Hs({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return function(e=!1){const t=Hn.getInstance().getStore();if(!e&&void 0===t)throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled.");return t}(!0)}catch{return}}}const pi=Symbol.for("ls:tracing_async_local_storage"),fi=Symbol.for("lc:context_variables"),mi=()=>globalThis[pi];let gi;function _i(){return void 0===gi&&(gi=new(0,as.default)({autoStart:!0,concurrency:1})),gi}async function yi(e,t){if(!0===t){const t=mi();void 0!==t?await t.run(void 0,async()=>e()):await e()}else gi=_i(),gi.add(async()=>{const t=mi();void 0!==t?await t.run(void 0,async()=>e()):await e()})}function vi(e){const t=mi();if(void 0===t)return;const n=t.getStore();return n?.[fi]?.[e]}const bi=Symbol("lc:configure_hooks"),wi=()=>vi(bi)||[];function Ei(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}class Si{setHandler(e){return this.setHandlers([e])}}class ki{constructor(e,t,n,r,s,i,a,o){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:o})}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>yi(async()=>{try{await(t.handleText?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleCustomEvent(e,t,n,r,s){await Promise.all(this.handlers.map(n=>yi(async()=>{try{await(n.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleCustomEvent: ${e}`),n.raiseError)throw e}},n.awaitHandlers)))}}class xi extends ki{getChild(e){const t=new Ai(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>yi(async()=>{if(!t.ignoreRetriever)try{await(t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw e}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>yi(async()=>{if(!t.ignoreRetriever)try{await(t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags))}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${n}`),t.raiseError)throw e}},t.awaitHandlers)))}}class Oi extends ki{async handleLLMNewToken(e,t,n,r,s,i){await Promise.all(this.handlers.map(n=>yi(async()=>{if(!n.ignoreLLM)try{await(n.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMNewToken: ${e}`),n.raiseError)throw e}},n.awaitHandlers)))}async handleLLMError(e,t,n,r,s){await Promise.all(this.handlers.map(t=>yi(async()=>{if(!t.ignoreLLM)try{await(t.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,s))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMEnd(e,t,n,r,s){await Promise.all(this.handlers.map(t=>yi(async()=>{if(!t.ignoreLLM)try{await(t.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,s))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}}class Ti extends ki{getChild(e){const t=new Ai(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,n,r,s){await Promise.all(this.handlers.map(t=>yi(async()=>{if(!t.ignoreChain)try{await(t.handleChainError?.(e,this.runId,this._parentRunId,this.tags,s))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleChainEnd(e,t,n,r,s){await Promise.all(this.handlers.map(t=>yi(async()=>{if(!t.ignoreChain)try{await(t.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,s))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>yi(async()=>{if(!t.ignoreAgent)try{await(t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>yi(async()=>{if(!t.ignoreAgent)try{await(t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}}class Ii extends ki{getChild(e){const t=new Ai(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>yi(async()=>{if(!t.ignoreAgent)try{await(t.handleToolError?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>yi(async()=>{if(!t.ignoreAgent)try{await(t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}}class Ai extends Si{constructor(e,t){super(),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"callback_manager"}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.handlers=t?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,n=void 0,r=void 0,s=void 0,i=void 0,a=void 0,o=void 0){return Promise.all(t.map(async(t,r)=>{const i=0===r&&n?n:Bn();return await Promise.all(this.handlers.map(n=>{if(!n.ignoreLLM)return si(n)&&n._createRunForLLMStart(e,[t],i,this._parentRunId,s,this.tags,this.metadata,o),yi(async()=>{try{await(n.handleLLMStart?.(e,[t],i,this._parentRunId,s,this.tags,this.metadata,o))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new Oi(i,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,n=void 0,r=void 0,s=void 0,i=void 0,a=void 0,o=void 0){return Promise.all(t.map(async(t,r)=>{const i=0===r&&n?n:Bn();return await Promise.all(this.handlers.map(n=>{if(!n.ignoreLLM)return si(n)&&n._createRunForChatModelStart(e,[t],i,this._parentRunId,s,this.tags,this.metadata,o),yi(async()=>{try{if(n.handleChatModelStart)await(n.handleChatModelStart?.(e,[t],i,this._parentRunId,s,this.tags,this.metadata,o));else if(n.handleLLMStart){const r=Cn(t);await(n.handleLLMStart?.(e,[r],i,this._parentRunId,s,this.tags,this.metadata,o))}}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new Oi(i,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,n=Bn(),r=void 0,s=void 0,i=void 0,a=void 0){return await Promise.all(this.handlers.map(s=>{if(!s.ignoreChain)return si(s)&&s._createRunForChainStart(e,t,n,this._parentRunId,this.tags,this.metadata,r,a),yi(async()=>{try{await(s.handleChainStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,r,a))}catch(e){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainStart: ${e}`),s.raiseError)throw e}},s.awaitHandlers)})),new Ti(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,n=Bn(),r=void 0,s=void 0,i=void 0,a=void 0){return await Promise.all(this.handlers.map(r=>{if(!r.ignoreAgent)return si(r)&&r._createRunForToolStart(e,t,n,this._parentRunId,this.tags,this.metadata,a),yi(async()=>{try{await(r.handleToolStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,a))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleToolStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new Ii(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,n=Bn(),r=void 0,s=void 0,i=void 0,a=void 0){return await Promise.all(this.handlers.map(r=>{if(!r.ignoreRetriever)return si(r)&&r._createRunForRetrieverStart(e,t,n,this._parentRunId,this.tags,this.metadata,a),yi(async()=>{try{await(r.handleRetrieverStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,a))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleRetrieverStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new xi(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,n,r,s){await Promise.all(this.handlers.map(r=>yi(async()=>{if(!r.ignoreCustomEvent)try{await(r.handleCustomEvent?.(e,t,n,this.tags,this.metadata))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleCustomEvent: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}addHandler(e,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(t=>t!==e),this.inheritableHandlers=this.inheritableHandlers.filter(t=>t!==e)}setHandlers(e,t=!0){this.handlers=[],this.inheritableHandlers=[];for(const n of e)this.addHandler(n,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(const t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(e=[],t=!0){const n=new Ai(this._parentRunId);for(const e of this.handlers){const t=this.inheritableHandlers.includes(e);n.addHandler(e,t)}for(const e of this.tags){const t=this.inheritableTags.includes(e);n.addTags([e],t)}for(const e of Object.keys(this.metadata)){const t=Object.keys(this.inheritableMetadata).includes(e);n.addMetadata({[e]:this.metadata[e]},t)}for(const r of e)n.handlers.filter(e=>"console_callback_handler"===e.name).some(e=>e.name===r.name)||n.addHandler(r,t);return n}static fromHandlers(e){const t=new this;return t.addHandler(new class extends ei{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:Bn()}),Object.assign(this,e)}}),t}static configure(e,t,n,r,s,i,a){return this._configureSync(e,t,n,r,s,i,a)}static _configureSync(e,t,n,r,s,i,a){let o;(e||t)&&(Array.isArray(e)||!e?(o=new Ai,o.setHandlers(e?.map(Pi)??[],!0)):o=e,o=o.copy(Array.isArray(t)?t.map(Pi):t?.handlers,!1));const l="true"===Ys("LANGCHAIN_VERBOSE")||a?.verbose,c=hi.getTraceableRunTree()?.tracingEnabled||(e=>void 0!==e?e:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>"true"===Ys(e)))(),u=c||(Ys("LANGCHAIN_TRACING")??!1);if(l||u){if(o||(o=new Ai),l&&!o.handlers.some(e=>e.name===ci.prototype.name)){const e=new ci;o.addHandler(e,!0)}if(u&&!o.handlers.some(e=>"langchain_tracer"===e.name)&&c){const e=new hi;o.addHandler(e,!0),o._parentRunId=hi.getTraceableRunTree()?.id??o._parentRunId}}for(const{contextVar:e,inheritable:t=!0,handlerClass:n,envVar:r}of wi()){const s=r&&"true"===Ys(r)&&n;let i;const a=void 0!==e?vi(e):void 0;a&&ti(a)?i=a:s&&(i=new n({})),void 0!==i&&(o||(o=new Ai),o.handlers.some(e=>e.name===i.name)||o.addHandler(i,t))}return(n||r)&&o&&(o.addTags(n??[]),o.addTags(r??[],!1)),(s||i)&&o&&(o.addMetadata(s??{}),o.addMetadata(i??{},!1)),o}}function Pi(e){return"name"in e?e:ei.fromMethods(e)}const Ci=new class{getStore(){}run(e,t){return t()}enterWith(e){}},$i=Symbol.for("lc:child_config");const Ri=new class{getInstance(){return mi()??Ci}getRunnableConfig(){const e=this.getInstance();return e.getStore()?.extra?.[$i]}runWithConfig(e,t,n){const r=Ai._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),s=this.getInstance(),i=s.getStore(),a=r?.getParentRunId(),o=r?.handlers?.find(e=>"langchain_tracer"===e?.name);let l;return o&&a?l=o.getRunTreeWithTracingConfig(a):n||(l=new Hs({name:"",tracingEnabled:!1})),l&&(l.extra={...l.extra,[$i]:e}),void 0!==i&&void 0!==i[fi]&&(void 0===l&&(l={}),l[fi]=i[fi]),s.run(l,t)}initializeGlobalInstance(e){void 0===mi()&&(e=>{globalThis[pi]=e})(e)}};async function Ni(e){return Ai._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function ji(...e){const t={};for(const n of e.filter(e=>!!e))for(const e of Object.keys(n))if("metadata"===e)t[e]={...t[e],...n[e]};else if("tags"===e){const r=t[e]??[];t[e]=[...new Set(r.concat(n[e]??[]))]}else if("configurable"===e)t[e]={...t[e],...n[e]};else if("timeout"===e)void 0===t.timeout?t.timeout=n.timeout:void 0!==n.timeout&&(t.timeout=Math.min(t.timeout,n.timeout));else if("signal"===e)void 0===t.signal?t.signal=n.signal:void 0!==n.signal&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,n.signal]):t.signal=n.signal);else if("callbacks"===e){const e=t.callbacks,r=n.callbacks;if(Array.isArray(r))if(e)if(Array.isArray(e))t.callbacks=e.concat(r);else{const n=e.copy();for(const e of r)n.addHandler(Pi(e),!0);t.callbacks=n}else t.callbacks=r;else if(r)if(e)if(Array.isArray(e)){const n=r.copy();for(const t of e)n.addHandler(Pi(t),!0);t.callbacks=n}else t.callbacks=new Ai(r._parentRunId,{handlers:e.handlers.concat(r.handlers),inheritableHandlers:e.inheritableHandlers.concat(r.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(r.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(r.inheritableTags))),metadata:{...e.metadata,...r.metadata}});else t.callbacks=r}else{const r=e;t[r]=n[r]??t[r]}return t}const Li=new Set(["string","number","boolean"]);function Mi(e){const t=Ri.getRunnableConfig();let n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){const{runId:e,runName:r,...s}=t;n=Object.entries(s).reduce((e,[t,n])=>(void 0!==n&&(e[t]=n),e),n)}if(e&&(n=Object.entries(e).reduce((e,[t,n])=>(void 0!==n&&(e[t]=n),e),n)),n?.configurable)for(const e of Object.keys(n.configurable))Li.has(typeof n.configurable[e])&&!n.metadata?.[e]&&(n.metadata||(n.metadata={}),n.metadata[e]=n.configurable[e]);if(void 0!==n.timeout){if(n.timeout<=0)throw new Error("Timeout must be a positive number");const e=AbortSignal.timeout(n.timeout);void 0!==n.signal?"any"in AbortSignal&&(n.signal=AbortSignal.any([n.signal,e])):n.signal=e,delete n.timeout}return n}function Di(e={},{callbacks:t,maxConcurrency:n,recursionLimit:r,runName:s,configurable:i,runId:a}={}){const o=Mi(e);return void 0!==t&&(delete o.runName,o.callbacks=t),void 0!==r&&(o.recursionLimit=r),void 0!==n&&(o.maxConcurrency=n),void 0!==s&&(o.runName=s),void 0!==i&&(o.configurable={...o.configurable,...i}),void 0!==a&&delete o.runId,o}function Ui(e){return e?{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal}:void 0}async function Fi(e,t){if(void 0===t)return e;let n;return Promise.race([e.catch(e=>{if(!t?.aborted)throw e}),new Promise((e,r)=>{n=()=>{r(new Error("Aborted"))},t.addEventListener("abort",n),t.aborted&&r(new Error("Aborted"))})]).finally(()=>t.removeEventListener("abort",n))}class Bi extends ReadableStream{constructor(){super(...arguments),Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const t=e.getReader();return new Bi({start:e=>function n(){return t.read().then(({done:t,value:r})=>{if(!t)return e.enqueue(r),n();e.close()})}(),cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new Bi({async pull(t){const{value:n,done:r}=await e.next();r&&t.close(),t.enqueue(n)},async cancel(t){await e.return(t)}})}}function qi(e,t=2){const n=Array.from({length:t},()=>[]);return n.map(async function*(t){for(;;)if(0===t.length){const t=await e.next();for(const e of n)e.push(t)}else{if(t[0].done)return;yield t.shift().value}})}function zi(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if("string"==typeof e&&"string"==typeof t)return e+t;if("number"==typeof e&&"number"==typeof t)return e+t;if("concat"in e&&"function"==typeof e.concat)return e.concat(t);if("object"==typeof e&&"object"==typeof t){const n={...e};for(const[e,r]of Object.entries(t))e in n&&!Array.isArray(n[e])?n[e]=zi(n[e],r):n[e]=r;return n}throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}class Hi{constructor(e){Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setup",{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,"signal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResultUsed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,n)=>{Ri.runWithConfig(Ui(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,n):this.firstResult.then(e=>t(void 0),n)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?Ri.runWithConfig(Ui(this.config),this.signal?async()=>Fi(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}}class Wi{constructor(e){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),n=lr({},t);return new Gi({ops:t,state:n[n.length-1].newDocument})}}class Gi extends Wi{constructor(e){super(e),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=e.state}concat(e){const t=this.ops.concat(e.ops),n=lr(this.state,e.ops);return new Gi({ops:t,state:n[n.length-1].newDocument})}static fromRunLogPatch(e){const t=lr({},e.ops);return new Gi({ops:e.ops,state:t[t.length-1].newDocument})}}const Ki=e=>"log_stream_tracer"===e.name;async function Ji(e,t){if("original"===t)throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:n}=e;return["retriever","llm","prompt"].includes(e.run_type)?n:1!==Object.keys(n).length||""!==n?.input?n.input:void 0}async function Zi(e,t){const{outputs:n}=e;return"original"===t||["retriever","llm","prompt"].includes(e.run_type)?n:void 0!==n&&1===Object.keys(n).length&&void 0!==n?.output?n.output:n}class Vi extends ii{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaFormat",{enumerable:!0,configurable:!0,writable:!0,value:"original"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keyMapByRunId",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"counterMapByRunName",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"log_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Bi.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=e.tags??[];let n=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(n=n||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(n=n||this.includeTypes.includes(e.run_type)),void 0!==this.includeTags&&(n=n||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(n=n&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(n=n&&!this.excludeTypes.includes(e.run_type)),void 0!==this.excludeTags&&(n=n&&t.every(e=>!this.excludeTags?.includes(e))),n}async*tapOutputIterable(e,t){for await(const n of t){if(e!==this.rootId){const t=this.keyMapByRunId[e];t&&await this.writer.write(new Wi({ops:[{op:"add",path:`/logs/${t}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){if(void 0===this.rootId&&(this.rootId=e.id,await this.writer.write(new Wi({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;void 0===this.counterMapByRunName[e.name]&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=1===t?e.name:`${e.name}:${t}`;const n={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};"streaming_events"===this._schemaFormat&&(n.inputs=await Ji(e,this._schemaFormat)),await this.writer.write(new Wi({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:n}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(void 0===t)return;const n=[];"streaming_events"===this._schemaFormat&&n.push({op:"replace",path:`/logs/${t}/inputs`,value:await Ji(e,this._schemaFormat)}),n.push({op:"add",path:`/logs/${t}/final_output`,value:await Zi(e,this._schemaFormat)}),void 0!==e.end_time&&n.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const r=new Wi({ops:n});await this.writer.write(r)}finally{if(e.id===this.rootId){const t=new Wi({ops:[{op:"replace",path:"/final_output",value:await Zi(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){const r=this.keyMapByRunId[e.id];if(void 0===r)return;let s;s=void 0!==e.inputs.messages?function(e){return void 0!==e&&void 0!==e.message}(n?.chunk)?n?.chunk:new _n({id:`run-${e.id}`,content:t}):t;const i=new Wi({ops:[{op:"add",path:`/logs/${r}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${r}/streamed_output/-`,value:s}]});await this.writer.write(i)}}const Yi="__run";class Xi{constructor(e){Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generationInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new Xi({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}class Qi extends Xi{constructor(e){super(e),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.message=e.message}concat(e){return new Qi({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}}function ea({name:e,serialized:t}){return void 0!==e?e:void 0!==t?.name?t.name:void 0!==t?.id&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}const ta=e=>"event_stream_tracer"===e.name;class na extends ii{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"runInfoMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"tappedPromises",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"event_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Bi.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.tags??[];let n=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(n=n||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(n=n||this.includeTypes.includes(e.runType)),void 0!==this.includeTags&&(n=n||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(n=n&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(n=n&&!this.excludeTypes.includes(e.runType)),void 0!==this.excludeTags&&(n=n&&t.every(e=>!this.excludeTags?.includes(e))),n}async*tapOutputIterable(e,t){const n=await t.next();if(n.done)return;const r=this.runInfoMap.get(e);if(void 0===r)return void(yield n.value);function s(e,t){return"llm"===e&&"string"==typeof t?new Xi({text:t}):t}let i=this.tappedPromises.get(e);if(void 0===i){let a;i=new Promise(e=>{a=e}),this.tappedPromises.set(e,i);try{const i={event:`on_${r.runType}_stream`,run_id:e,name:r.name,tags:r.tags,metadata:r.metadata,data:{}};await this.send({...i,data:{chunk:s(r.runType,n.value)}},r),yield n.value;for await(const e of t)"tool"!==r.runType&&"retriever"!==r.runType&&await this.send({...i,data:{chunk:s(r.runType,e)}},r),yield e}finally{a()}}else{yield n.value;for await(const e of t)yield e}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const n=this.tappedPromises.get(e.run_id);void 0!==n?n.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){const t=ea(e),n=void 0!==e.inputs.messages?"chat_model":"llm",r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:n,inputs:e.inputs};this.runInfoMap.set(e.id,r);const s=`on_${n}_start`;await this.send({event:s,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onLLMNewToken(e,t,n){const r=this.runInfoMap.get(e.id);let s,i;if(void 0===r)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(1!==this.runInfoMap.size){if("chat_model"===r.runType)i="on_chat_model_stream",s=void 0===n?.chunk?new _n({content:t,id:`run-${e.id}`}):n.chunk.message;else{if("llm"!==r.runType)throw new Error(`Unexpected run type ${r.runType}`);i="on_llm_stream",s=void 0===n?.chunk?new Xi({text:t}):n.chunk}await this.send({event:i,data:{chunk:s},run_id:e.id,name:r.name,tags:r.tags,metadata:r.metadata},r)}}async onLLMEnd(e){const t=this.runInfoMap.get(e.id);let n;if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const r=e.outputs?.generations;let s;if("chat_model"===t.runType){for(const e of r??[]){if(void 0!==s)break;s=e[0]?.message}n="on_chat_model_end"}else{if("llm"!==t.runType)throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);s={generations:r?.map(e=>e.map(e=>({text:e.text,generationInfo:e.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},n="on_llm_end"}await this.sendEndEvent({event:n,data:{output:s,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){const t=ea(e),n=e.run_type??"chain",r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let s={};""===e.inputs.input&&1===Object.keys(e.inputs).length?(s={},r.inputs={}):void 0!==e.inputs.input?(s.input=e.inputs.input,r.inputs=e.inputs.input):(s.input=e.inputs,r.inputs=e.inputs),this.runInfoMap.set(e.id,r),await this.send({event:`on_${n}_start`,data:s,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onChainEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const n=`on_${e.run_type}_end`,r=e.inputs??t.inputs??{},s={output:e.outputs?.output??e.outputs,input:r};r.input&&1===Object.keys(r).length&&(s.input=r.input,t.inputs=r.input),await this.sendEndEvent({event:n,data:s,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=ea(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,n),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},n)}async onToolEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const n=void 0===e.outputs?.output?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:n,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){const t=ea(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,n),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onRetrieverEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,n){const r=this.runInfoMap.get(n);if(void 0===r)throw new Error(`handleCustomEvent: Run ID ${n} not found in run map.`);await this.send({event:"on_custom_event",run_id:n,name:e,tags:r.tags,metadata:r.metadata,data:t},r)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}}const ra=[400,401,402,403,404,405,406,407,409],sa=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||"AbortError"===e.name)throw e;if("ECONNABORTED"===e?.code)throw e;const t=e?.response?.status??e?.status;if(t&&ra.includes(+t))throw e;if("insufficient_quota"===e?.error?.code){const t=new Error(e?.message);throw t.name="InsufficientQuotaError",t}};class ia{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??sa;const t=as.default;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>Rn(()=>e(...t).catch(e=>{throw e instanceof Error?e:new Error(e)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){return e.signal?Promise.race([this.call(t,...n),new Promise((t,n)=>{e.signal?.addEventListener("abort",()=>{n(new Error("AbortError"))})})]):this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}}class aa extends ii{constructor({config:e,onStart:t,onEnd:n,onError:r}){super({_awaitHandler:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RootListenersTracer"}),Object.defineProperty(this,"rootId",{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,"argOnStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.config=e,this.argOnStart=t,this.argOnEnd=n,this.argOnError=r}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}}function oa(e){return!!e&&e.lc_runnable}class la{constructor(e){Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let n=void 0===this.includeNames&&void 0===this.includeTypes&&void 0===this.includeTags;const r=e.tags??[];return void 0!==this.includeNames&&(n=n||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(n=n||this.includeTypes.includes(t)),void 0!==this.includeTags&&(n=n||r.some(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(n=n&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(n=n&&!this.excludeTypes.includes(t)),void 0!==this.excludeTags&&(n=n&&r.every(e=>!this.excludeTags?.includes(e))),n}}const ca=/^(?:[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 ua=function(e){return"string"==typeof e&&ca.test(e)};function da(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const ha=["*","_","`"];function pa(e,t,n){const{firstNode:r,lastNode:s,nodeColors:i,withStyles:a=!0,curveStyle:o="linear",wrapLabelNWords:l=9}=n??{};let c=a?`%%{init: {'flowchart': {'curve': '${o}'}}}%%\ngraph TD;\n`:"graph TD;\n";if(a){const t="default",n={[t]:"{0}({1})"};void 0!==r&&(n[r]="{0}([{1}]):::first"),void 0!==s&&(n[s]="{0}([{1}]):::last");for(const[r,s]of Object.entries(e)){const e=s.name.split(":").pop()??"";let i=ha.some(t=>e.startsWith(t)&&e.endsWith(t))?`

${e}

`:e;Object.keys(s.metadata??{}).length&&(i+=`
${Object.entries(s.metadata??{}).map(([e,t])=>`${e} = ${t}`).join("\n")}`);const a=(n[r]??n[t]).replace("{0}",da(r)).replace("{1}",i);c+=`\t${a}\n`}}const u={};for(const e of t){const t=e.source.split(":"),n=e.target.split(":"),r=t.filter((e,t)=>e===n[t]).join(":");u[r]||(u[r]=[]),u[r].push(e)}const d=new Set;function h(e,t){const n=1===e.length&&e[0].source===e[0].target;if(t&&!n){const e=t.split(":").pop();if(d.has(e))throw new Error(`Found duplicate subgraph '${e}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(e),c+=`\tsubgraph ${e}\n`}for(const t of e){const{source:e,target:n,data:r,conditional:s}=t;let i="";if(void 0!==r){let e=r;const t=e.split(" ");t.length>l&&(e=Array.from({length:Math.ceil(t.length/l)},(e,n)=>t.slice(n*l,(n+1)*l).join(" ")).join(" 
 ")),i=s?` -.  ${e}  .-> `:` --  ${e}  --\x3e `}else i=s?" -.-> ":" --\x3e ";c+=`\t${da(e)}${i}${da(n)};\n`}for(const e in u)e.startsWith(`${t}:`)&&e!==t&&h(u[e],e);t&&!n&&(c+="\tend\n")}h(u[""]??[],"");for(const e in u)e.includes(":")||""===e||h(u[e],e);return a&&(c+=function(e){let t="";for(const[n,r]of Object.entries(e))t+=`\tclassDef ${n} ${r};\n`;return t}(i??{})),c}Symbol("ZodOutput"),Symbol("ZodInput");class fa{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const n=t[0];if(this._map.set(e,n),n&&"object"==typeof n&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function ma(){return new fa}const ga=ma();function _a(e,t){return"bigint"==typeof t?t.toString():t}const ya=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};va=()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}};var va;new Set(["string","number","symbol"]),new Set(["string","number","bigint","boolean","symbol","undefined"]);function ba(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function wa(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,Number.MAX_VALUE,Number.MAX_VALUE;function Ea(e,t=0){for(let n=t;n{}),this.io=e?.io??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var n;const r=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i){i.count++;return t.schemaPath.includes(e)&&(i.cycle=t.path),i.schema}const a={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,a);const o=e._zod.toJSONSchema?.();if(o)a.schema=o;else{const n={...t,schemaPath:[...t.schemaPath,e],path:t.path},i=e._zod.parent;if(i)a.ref=i,this.process(i,n),this.seen.get(i).isParent=!0;else{const t=a.schema;switch(r.type){case"string":{const n=t;n.type="string";const{minimum:r,maximum:i,format:o,patterns:l,contentEncoding:c}=e._zod.bag;if("number"==typeof r&&(n.minLength=r),"number"==typeof i&&(n.maxLength=i),o&&(n.format=s[o]??o,""===n.format&&delete n.format),c&&(n.contentEncoding=c),l&&l.size>0){const e=[...l];1===e.length?n.pattern=e[0].source:e.length>1&&(a.schema.allOf=[...e.map(e=>({..."draft-7"===this.target?{type:"string"}:{},pattern:e.source}))])}break}case"number":{const n=t,{minimum:r,maximum:s,format:i,multipleOf:a,exclusiveMaximum:o,exclusiveMinimum:l}=e._zod.bag;"string"==typeof i&&i.includes("int")?n.type="integer":n.type="number","number"==typeof l&&(n.exclusiveMinimum=l),"number"==typeof r&&(n.minimum=r,"number"==typeof l&&(l>=r?delete n.minimum:delete n.exclusiveMinimum)),"number"==typeof o&&(n.exclusiveMaximum=o),"number"==typeof s&&(n.maximum=s,"number"==typeof o&&(o<=s?delete n.maximum:delete n.exclusiveMaximum)),"number"==typeof a&&(n.multipleOf=a);break}case"boolean":t.type="boolean";break;case"bigint":if("throw"===this.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema");break;case"symbol":if("throw"===this.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema");break;case"null":t.type="null";break;case"any":case"unknown":break;case"undefined":if("throw"===this.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema");break;case"void":if("throw"===this.unrepresentable)throw new Error("Void cannot be represented in JSON Schema");break;case"never":t.not={};break;case"date":if("throw"===this.unrepresentable)throw new Error("Date cannot be represented in JSON Schema");break;case"array":{const s=t,{minimum:i,maximum:a}=e._zod.bag;"number"==typeof i&&(s.minItems=i),"number"==typeof a&&(s.maxItems=a),s.type="array",s.items=this.process(r.element,{...n,path:[...n.path,"items"]});break}case"object":{const e=t;e.type="object",e.properties={};const s=r.shape;for(const t in s)e.properties[t]=this.process(s[t],{...n,path:[...n.path,"properties",t]});const i=new Set(Object.keys(s)),a=new Set([...i].filter(e=>{const t=r.shape[e]._zod;return"input"===this.io?void 0===t.optin:void 0===t.optout}));a.size>0&&(e.required=Array.from(a)),"never"===r.catchall?._zod.def.type?e.additionalProperties=!1:r.catchall?r.catchall&&(e.additionalProperties=this.process(r.catchall,{...n,path:[...n.path,"additionalProperties"]})):"output"===this.io&&(e.additionalProperties=!1);break}case"union":t.anyOf=r.options.map((e,t)=>this.process(e,{...n,path:[...n.path,"anyOf",t]}));break;case"intersection":{const e=t,s=this.process(r.left,{...n,path:[...n.path,"allOf",0]}),i=this.process(r.right,{...n,path:[...n.path,"allOf",1]}),a=e=>"allOf"in e&&1===Object.keys(e).length,o=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];e.allOf=o;break}case"tuple":{const s=t;s.type="array";const i=r.items.map((e,t)=>this.process(e,{...n,path:[...n.path,"prefixItems",t]}));if("draft-2020-12"===this.target?s.prefixItems=i:s.items=i,r.rest){const e=this.process(r.rest,{...n,path:[...n.path,"items"]});"draft-2020-12"===this.target?s.items=e:s.additionalItems=e}r.rest&&(s.items=this.process(r.rest,{...n,path:[...n.path,"items"]}));const{minimum:a,maximum:o}=e._zod.bag;"number"==typeof a&&(s.minItems=a),"number"==typeof o&&(s.maxItems=o);break}case"record":{const e=t;e.type="object",e.propertyNames=this.process(r.keyType,{...n,path:[...n.path,"propertyNames"]}),e.additionalProperties=this.process(r.valueType,{...n,path:[...n.path,"additionalProperties"]});break}case"map":if("throw"===this.unrepresentable)throw new Error("Map cannot be represented in JSON Schema");break;case"set":if("throw"===this.unrepresentable)throw new Error("Set cannot be represented in JSON Schema");break;case"enum":{const e=t,n=function(e){const t=Object.values(e).filter(e=>"number"==typeof e),n=Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t);return n}(r.entries);n.every(e=>"number"==typeof e)&&(e.type="number"),n.every(e=>"string"==typeof e)&&(e.type="string"),e.enum=n;break}case"literal":{const e=t,n=[];for(const e of r.values)if(void 0===e){if("throw"===this.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===this.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");n.push(Number(e))}else n.push(e);if(0===n.length);else if(1===n.length){const t=n[0];e.type=null===t?"null":typeof t,e.const=t}else n.every(e=>"number"==typeof e)&&(e.type="number"),n.every(e=>"string"==typeof e)&&(e.type="string"),n.every(e=>"boolean"==typeof e)&&(e.type="string"),n.every(e=>null===e)&&(e.type="null"),e.enum=n;break}case"file":{const n=t,r={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:i,mime:a}=e._zod.bag;void 0!==s&&(r.minLength=s),void 0!==i&&(r.maxLength=i),a?1===a.length?(r.contentMediaType=a[0],Object.assign(n,r)):n.anyOf=a.map(e=>({...r,contentMediaType:e})):Object.assign(n,r);break}case"transform":if("throw"===this.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema");break;case"nullable":{const e=this.process(r.innerType,n);t.anyOf=[e,{type:"null"}];break}case"nonoptional":case"promise":case"optional":this.process(r.innerType,n),a.ref=r.innerType;break;case"success":t.type="boolean";break;case"default":this.process(r.innerType,n),a.ref=r.innerType,t.default=JSON.parse(JSON.stringify(r.defaultValue));break;case"prefault":this.process(r.innerType,n),a.ref=r.innerType,"input"===this.io&&(t._prefault=JSON.parse(JSON.stringify(r.defaultValue)));break;case"catch":{let e;this.process(r.innerType,n),a.ref=r.innerType;try{e=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=e;break}case"nan":if("throw"===this.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema");break;case"template_literal":{const n=t,r=e._zod.pattern;if(!r)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=r.source;break}case"pipe":{const e="input"===this.io?"transform"===r.in._zod.def.type?r.out:r.in:r.out;this.process(e,n),a.ref=e;break}case"readonly":this.process(r.innerType,n),a.ref=r.innerType,t.readOnly=!0;break;case"lazy":{const t=e._zod.innerType;this.process(t,n),a.ref=t;break}case"custom":if("throw"===this.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")}}}const l=this.metadataRegistry.get(e);l&&Object.assign(a.schema,l),"input"===this.io&&Ta(e)&&(delete a.schema.examples,delete a.schema.default),"input"===this.io&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault;return this.seen.get(e).schema}emit(e,t){const n={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},r=this.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=e=>{const t="draft-2020-12"===this.target?"$defs":"definitions";if(n.external){const r=n.external.registry.get(e[0])?.id,s=n.external.uri??(e=>e);if(r)return{ref:s(r)};const i=e[1].defId??e[1].schema.id??"schema"+this.counter++;return e[1].defId=i,{defId:i,ref:`${s("__shared")}#/${t}/${i}`}}if(e[1]===r)return{ref:"#"};const s=`#/${t}/`,i=e[1].schema.id??"__schema"+this.counter++;return{defId:i,ref:s+i}},i=e=>{if(e[1].schema.$ref)return;const t=e[1],{ref:n,defId:r}=s(e);t.def={...t.schema},r&&(t.defId=r);const i=t.schema;for(const e in i)delete i[e];i.$ref=n};if("throw"===n.cycles)for(const e of this.seen.entries()){const t=e[1];if(t.cycle)throw new Error(`Cycle detected: #/${t.cycle?.join("/")}/\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const t of this.seen.entries()){const r=t[1];if(e===t[0]){i(t);continue}if(n.external){const r=n.external.registry.get(t[0])?.id;if(e!==t[0]&&r){i(t);continue}}const s=this.metadataRegistry.get(t[0])?.id;s?i(t):(r.cycle||r.count>1&&"ref"===n.reused)&&i(t)}const a=(e,t)=>{const n=this.seen.get(e),r=n.def??n.schema,s={...r};if(null===n.ref)return;const i=n.ref;if(n.ref=null,i){a(i,t);const e=this.seen.get(i).schema;e.$ref&&"draft-7"===t.target?(r.allOf=r.allOf??[],r.allOf.push(e)):(Object.assign(r,e),Object.assign(r,s))}n.isParent||this.override({zodSchema:e,jsonSchema:r,path:n.path??[]})};for(const e of[...this.seen.entries()].reverse())a(e[0],{target:this.target});const o={};if("draft-2020-12"===this.target?o.$schema="https://json-schema.org/draft/2020-12/schema":"draft-7"===this.target&&(o.$schema="http://json-schema.org/draft-07/schema#"),n.external?.uri){const t=n.external.registry.get(e)?.id;if(!t)throw new Error("Schema is missing an `id` property");o.$id=n.external.uri(t)}Object.assign(o,r.def);const l=n.external?.defs??{};for(const e of this.seen.entries()){const t=e[1];t.def&&t.defId&&(l[t.defId]=t.def)}n.external||Object.keys(l).length>0&&("draft-2020-12"===this.target?o.$defs=l:o.definitions=l);try{return JSON.parse(JSON.stringify(o))}catch(e){throw new Error("Error converting schema to JSON.")}}}function Oa(e,t){if(e instanceof fa){const n=new xa(t),r={};for(const t of e._idmap.entries()){const[e,r]=t;n.process(r)}const s={},i={registry:e,uri:t?.uri,defs:r};for(const r of e._idmap.entries()){const[e,a]=r;s[e]=n.emit(a,{...t,external:i})}if(Object.keys(r).length>0){const e="draft-2020-12"===n.target?"$defs":"definitions";s.__shared={[e]:r}}return{schemas:s}}const n=new xa(t);return n.process(e),n.emit(e,t)}function Ta(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;switch(r.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":case"custom":case"success":case"catch":return!1;case"array":return Ta(r.element,n);case"object":for(const e in r.shape)if(Ta(r.shape[e],n))return!0;return!1;case"union":for(const e of r.options)if(Ta(e,n))return!0;return!1;case"intersection":return Ta(r.left,n)||Ta(r.right,n);case"tuple":for(const e of r.items)if(Ta(e,n))return!0;return!(!r.rest||!Ta(r.rest,n));case"record":case"map":return Ta(r.keyType,n)||Ta(r.valueType,n);case"set":return Ta(r.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return Ta(r.innerType,n);case"lazy":return Ta(r.getter(),n);case"transform":return!0;case"pipe":return Ta(r.in,n)||Ta(r.out,n)}throw new Error(`Unknown schema type: ${r.type}`)}const Ia=Symbol("Let zodToJsonSchema decide on which parser to use"),Aa={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Pa=e=>{const t=(e=>"string"==typeof e?{...Aa,name:e}:{...Aa,...e})(e),n=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},Ca=(e,t)=>{let n=0;for(;nLa(e,t,n))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Ma(e,t)}}const Ma=(e,t)=>{const n={type:"integer",format:"unix-time"};if("openApi3"===t.target)return n;for(const r of e.checks)switch(r.kind){case"min":Na(n,"minimum",r.value,r.message,t);break;case"max":Na(n,"maximum",r.value,r.message,t)}return n};let Da;const Ua=/^[cC][^\s-]{8,}$/,Fa=/^[0-9a-z]+$/,Ba=/^[0-9A-HJKMNP-TV-Z]{26}$/,qa=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,za=()=>(void 0===Da&&(Da=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Da),Ha=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Wa=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ga=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ka=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ja=/^[a-zA-Z0-9_-]{21}$/,Za=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function Va(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":Na(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":Na(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Qa(n,"email",r.message,t);break;case"format:idn-email":Qa(n,"idn-email",r.message,t);break;case"pattern:zod":eo(n,qa,r.message,t)}break;case"url":Qa(n,"uri",r.message,t);break;case"uuid":Qa(n,"uuid",r.message,t);break;case"regex":eo(n,r.regex,r.message,t);break;case"cuid":eo(n,Ua,r.message,t);break;case"cuid2":eo(n,Fa,r.message,t);break;case"startsWith":eo(n,RegExp(`^${Ya(r.value,t)}`),r.message,t);break;case"endsWith":eo(n,RegExp(`${Ya(r.value,t)}$`),r.message,t);break;case"datetime":Qa(n,"date-time",r.message,t);break;case"date":Qa(n,"date",r.message,t);break;case"time":Qa(n,"time",r.message,t);break;case"duration":Qa(n,"duration",r.message,t);break;case"length":Na(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t),Na(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":eo(n,RegExp(Ya(r.value,t)),r.message,t);break;case"ip":"v6"!==r.version&&Qa(n,"ipv4",r.message,t),"v4"!==r.version&&Qa(n,"ipv6",r.message,t);break;case"base64url":eo(n,Ka,r.message,t);break;case"jwt":eo(n,Za,r.message,t);break;case"cidr":"v6"!==r.version&&eo(n,Ha,r.message,t),"v4"!==r.version&&eo(n,Wa,r.message,t);break;case"emoji":eo(n,za(),r.message,t);break;case"ulid":eo(n,Ba,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":Qa(n,"binary",r.message,t);break;case"contentEncoding:base64":Na(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":eo(n,Ga,r.message,t)}break;case"nanoid":eo(n,Ja,r.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:(()=>{})()}return n}function Ya(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let n=0;ne.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Na(e,"format",t,n,r)}function eo(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:to(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Na(e,"pattern",to(t,r),n,r)}function to(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const n=e.flags.includes("i"),r=e.flags.includes("m"),s=e.flags.includes("s"),i=n?e.source.toLowerCase():e.source;let a="",o=!1,l=!1,c=!1;for(let e=0;e({...n,[r]:lo(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??$a(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:lo(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return n;if(e.keyType?._def.typeName===Le.ZodString&&e.keyType._def.checks?.length){const{type:r,...s}=Va(e.keyType._def,t);return{...n,propertyNames:s}}if(e.keyType?._def.typeName===Le.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===Le.ZodBranded&&e.keyType._def.type._def.typeName===Le.ZodString&&e.keyType._def.type._def.checks?.length){const{type:r,...s}=ja(e.keyType._def,t);return{...n,propertyNames:s}}return n}const ro={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const so=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>lo(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function io(e,t){const n="openAi"===t.target,r={type:"object",properties:{}},s=[],i=e.shape();for(const e in i){let a=i[e];if(void 0===a||void 0===a._def)continue;let o=ao(a);o&&n&&("ZodOptional"===a._def.typeName&&(a=a._def.innerType),a.isNullable()||(a=a.nullable()),o=!1);const l=lo(a._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==l&&(r.properties[e]=l,o||s.push(e))}s.length&&(r.required=s);const a=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return lo(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==a&&(r.additionalProperties=a),r}function ao(e){try{return e.isOptional()}catch{return!0}}const oo=(e,t,n)=>{switch(t){case Le.ZodString:return Va(e,n);case Le.ZodNumber:return function(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",Ra(n,"type",r.message,t);break;case"min":"jsonSchema7"===t.target?r.inclusive?Na(n,"minimum",r.value,r.message,t):Na(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Na(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Na(n,"maximum",r.value,r.message,t):Na(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Na(n,"maximum",r.value,r.message,t));break;case"multipleOf":Na(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case Le.ZodObject:return io(e,n);case Le.ZodBigInt:return function(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":"jsonSchema7"===t.target?r.inclusive?Na(n,"minimum",r.value,r.message,t):Na(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Na(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Na(n,"maximum",r.value,r.message,t):Na(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Na(n,"maximum",r.value,r.message,t));break;case"multipleOf":Na(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case Le.ZodBoolean:return{type:"boolean"};case Le.ZodDate:return La(e,n);case Le.ZodUndefined:return function(e){return{not:$a(e)}}(n);case Le.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(n);case Le.ZodArray:return function(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==Le.ZodAny&&(n.items=lo(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Na(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Na(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Na(n,"minItems",e.exactLength.value,e.exactLength.message,t),Na(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}(e,n);case Le.ZodUnion:case Le.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return so(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in ro&&(!e._def.checks||!e._def.checks.length))){const e=n.reduce((e,t)=>{const n=ro[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){const e=n.reduce((e,t)=>{const n=typeof t._def.value;switch(n){case"string":case"number":case"boolean":return[...e,n];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===n.length){const t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return so(e,t)}(e,n);case Le.ZodIntersection:return function(e,t){const n=[lo(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),lo(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e);let r="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const s=[];return n.forEach(e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:n,...r}=e;t=r}else r=void 0;s.push(t)}else s.push(...e.allOf),void 0===e.unevaluatedProperties&&(r=void 0);var t}),s.length?{allOf:s,...r}:void 0}(e,n);case Le.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,n)=>lo(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:lo(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>lo(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,n);case Le.ZodRecord:return no(e,n);case Le.ZodLiteral:return function(e,t){const n=typeof e.value;return"bigint"!==n&&"number"!==n&&"boolean"!==n&&"string"!==n?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===n?"integer":n,enum:[e.value]}:{type:"bigint"===n?"integer":n,const:e.value}}(e,n);case Le.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case Le.ZodNativeEnum:return function(e){const t=e.values,n=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:1===r.length?"string"===r[0]?"string":"number":["string","number"],enum:n}}(e);case Le.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:ro[e.innerType._def.typeName],nullable:!0}:{type:[ro[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const n=lo(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const n=lo(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}(e,n);case Le.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return lo(e.innerType._def,t);const n=lo(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:$a(t)},n]}:$a(t)})(e,n);case Le.ZodMap:return function(e,t){return"record"===t.mapStrategy?no(e,t):{type:"array",maxItems:125,items:{type:"array",items:[lo(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||$a(t),lo(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||$a(t)],minItems:2,maxItems:2}}}(e,n);case Le.ZodSet:return function(e,t){const n={type:"array",uniqueItems:!0,items:lo(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Na(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Na(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}(e,n);case Le.ZodLazy:return()=>e.getter()._def;case Le.ZodPromise:return function(e,t){return lo(e.type._def,t)}(e,n);case Le.ZodNaN:case Le.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:$a({...e,currentPath:[...e.currentPath,"not"]})}}(n);case Le.ZodEffects:return function(e,t){return"input"===t.effectStrategy?lo(e.schema._def,t):$a(t)}(e,n);case Le.ZodAny:return $a(n);case Le.ZodUnknown:return function(e){return $a(e)}(n);case Le.ZodDefault:return function(e,t){return{...lo(e.innerType._def,t),default:e.defaultValue()}}(e,n);case Le.ZodBranded:return ja(e,n);case Le.ZodReadonly:case Le.ZodCatch:return((e,t)=>lo(e.innerType._def,t))(e,n);case Le.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return lo(e.in._def,t);if("output"===t.pipeStrategy)return lo(e.out._def,t);const n=lo(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[n,lo(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]})].filter(e=>void 0!==e)}})(e,n);case Le.ZodFunction:case Le.ZodVoid:case Le.ZodSymbol:default:return}};function lo(e,t,n=!1){const r=t.seen.get(e);if(t.override){const s=t.override?.(e,t,r,n);if(s!==Ia)return s}if(r&&!n){const e=co(r,t);if(void 0!==e)return e}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const i=oo(e,e.typeName,t),a="function"==typeof i?lo(i(),t):i;if(a&&uo(e,t,a),t.postProcess){const n=t.postProcess(a,e,t);return s.jsonSchema=a,n}return s.jsonSchema=a,a}const co=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Ca(t.currentPath,e.path)};case"none":case"seen":return e.path.lengtht.currentPath[n]===e)||"seen"===t.$refStrategy?$a(t):void 0}},uo=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n);function ho(e,t){const n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;const n=e.length;if(n!==t.length)return!1;for(let r=0;r1?t[i.href]=e:(i.hash="",""===r?n=i:yo(e,t,n))}}else if(!0!==e&&!1!==e)return t;const s=n.href+(r?"#"+r:"");if(void 0!==t[s])throw new Error(`Duplicate schema URI "${s}".`);if(t[s]=e,!0===e||!1===e)return t;if(void 0===e.__absolute_uri__&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:s}),e.$ref&&void 0===e.__absolute_ref__){const t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&void 0===e.__absolute_recursive_ref__){const t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){t[new URL("#"+e.$anchor,n.href).href]=e}for(let s in e){if(go[s])continue;const i=`${r}/${po(s)}`,a=e[s];if(Array.isArray(a)){if(fo[s]){const e=a.length;for(let r=0;re.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),uri:function(e){return To.test(e)&&Io.test(e)},"uri-reference":Eo(/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i),"uri-template":Eo(/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i),url:Eo(/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu),email:e=>{if('"'===e[0])return!1;const[t,n,...r]=e.split("@");return!(!t||!n||0!==r.length||t.length>64||n.length>253)&&("."!==t[0]&&!t.endsWith(".")&&!t.includes("..")&&(!(!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t))&&n.split(".").every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))))},hostname:Eo(/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i),ipv4:Eo(/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/),ipv6:Eo(/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i),regex:function(e){if(Ao.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(e){return!1}},uuid:Eo(/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i),"json-pointer":Eo(/^(?:\/(?:[^~/]|~0|~1)*)*$/),"json-pointer-uri-fragment":Eo(/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i),"relative-json-pointer":Eo(/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/)};function ko(e){const t=e.match(vo);if(!t)return!1;const n=+t[1],r=+t[2],s=+t[3];return r>=1&&r<=12&&s>=1&&s<=(2==r&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(n)?29:bo[r])}function xo(e,t){const n=t.match(wo);if(!n)return!1;const r=+n[1],s=+n[2],i=+n[3],a=!!n[5];return(r<=23&&s<=59&&i<=59||23==r&&59==s&&60==i)&&(!e||a)}const Oo=/t|\s/i;const To=/\/|:/,Io=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;const Ao=/[^\\]\\Z/;var Po;function Co(e,t,n="2019-09",r=yo(t),s=!0,i=null,a="#",o="#",l=Object.create(null)){if(!0===t)return{valid:!0,errors:[]};if(!1===t)return{valid:!1,errors:[{instanceLocation:a,keyword:"false",keywordLocation:a,error:"False boolean schema."}]};const c=typeof e;let u;switch(c){case"boolean":case"number":case"string":u=c;break;case"object":u=null===e?"null":Array.isArray(e)?"array":"object";break;default:throw new Error(`Instances of "${c}" type are not supported.`)}const{$ref:d,$recursiveRef:h,$recursiveAnchor:p,type:f,const:m,enum:g,required:_,not:y,anyOf:v,allOf:b,oneOf:w,if:E,then:S,else:k,format:x,properties:O,patternProperties:T,additionalProperties:I,unevaluatedProperties:A,minProperties:P,maxProperties:C,propertyNames:$,dependentRequired:R,dependentSchemas:N,dependencies:j,prefixItems:L,items:M,additionalItems:D,unevaluatedItems:U,contains:F,minContains:B,maxContains:q,minItems:z,maxItems:H,uniqueItems:W,minimum:G,maximum:K,exclusiveMinimum:J,exclusiveMaximum:Z,multipleOf:V,minLength:Y,maxLength:X,pattern:Q,__absolute_ref__:ee,__absolute_recursive_ref__:te}=t,ne=[];if(!0===p&&null===i&&(i=t),"#"===h){const c=null===i?r[te]:i,u=`${o}/$recursiveRef`,d=Co(e,null===i?t:i,n,r,s,c,a,u,l);d.valid||ne.push({instanceLocation:a,keyword:"$recursiveRef",keywordLocation:u,error:"A subschema had errors."},...d.errors)}if(void 0!==d){const t=r[ee||d];if(void 0===t){let e=`Unresolved $ref "${d}".`;throw ee&&ee!==d&&(e+=` Absolute URI "${ee}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join("\n- ")}`,new Error(e)}const c=`${o}/$ref`,u=Co(e,t,n,r,s,i,a,c,l);if(u.valid||ne.push({instanceLocation:a,keyword:"$ref",keywordLocation:c,error:"A subschema had errors."},...u.errors),"4"===n||"7"===n)return{valid:0===ne.length,errors:ne}}if(Array.isArray(f)){let t=f.length,n=!1;for(let r=0;rho(e,t))||ne.push({instanceLocation:a,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||ne.push({instanceLocation:a,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),void 0!==y){const t=`${o}/not`;Co(e,y,n,r,s,i,a,t).valid&&ne.push({instanceLocation:a,keyword:"not",keywordLocation:t,error:'Instance matched "not" schema.'})}let re=[];if(void 0!==v){const t=`${o}/anyOf`,c=ne.length;let u=!1;for(let o=0;o{const u=Object.create(l),d=Co(e,o,n,r,s,!0===p?i:null,a,`${t}/${c}`,u);return ne.push(...d.errors),d.valid&&re.push(u),d.valid}).length;1===u?ne.length=c:ne.splice(c,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if("object"!==u&&"array"!==u||Object.assign(l,...re),void 0!==E){const t=`${o}/if`;if(Co(e,E,n,r,s,i,a,t,l).valid){if(void 0!==S){const c=Co(e,S,n,r,s,i,a,`${o}/then`,l);c.valid||ne.push({instanceLocation:a,keyword:"if",keywordLocation:t,error:'Instance does not match "then" schema.'},...c.errors)}}else if(void 0!==k){const c=Co(e,k,n,r,s,i,a,`${o}/else`,l);c.valid||ne.push({instanceLocation:a,keyword:"if",keywordLocation:t,error:'Instance does not match "else" schema.'},...c.errors)}}if("object"===u){if(void 0!==_)for(const t of _)t in e||ne.push({instanceLocation:a,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${t}".`});const t=Object.keys(e);if(void 0!==P&&t.lengthC&&ne.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${C} properties.`}),void 0!==$){const t=`${o}/propertyNames`;for(const o in e){const e=`${a}/${po(o)}`,l=Co(o,$,n,r,s,i,e,t);l.valid||ne.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:t,error:`Property name "${o}" does not match schema.`},...l.errors)}}if(void 0!==R){const t=`${o}/dependantRequired`;for(const n in R)if(n in e){const r=R[n];for(const s of r)s in e||ne.push({instanceLocation:a,keyword:"dependentRequired",keywordLocation:t,error:`Instance has "${n}" but does not have "${s}".`})}}if(void 0!==N)for(const t in N){const c=`${o}/dependentSchemas`;if(t in e){const o=Co(e,N[t],n,r,s,i,a,`${c}/${po(t)}`,l);o.valid||ne.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:c,error:`Instance has "${t}" but does not match dependant schema.`},...o.errors)}}if(void 0!==j){const t=`${o}/dependencies`;for(const o in j)if(o in e){const l=j[o];if(Array.isArray(l))for(const n of l)n in e||ne.push({instanceLocation:a,keyword:"dependencies",keywordLocation:t,error:`Instance has "${o}" but does not have "${n}".`});else{const c=Co(e,l,n,r,s,i,a,`${t}/${po(o)}`);c.valid||ne.push({instanceLocation:a,keyword:"dependencies",keywordLocation:t,error:`Instance has "${o}" but does not match dependant schema.`},...c.errors)}}}const c=Object.create(null);let u=!1;if(void 0!==O){const t=`${o}/properties`;for(const o in O){if(!(o in e))continue;const d=`${a}/${po(o)}`,h=Co(e[o],O[o],n,r,s,i,d,`${t}/${po(o)}`);if(h.valid)l[o]=c[o]=!0;else if(u=s,ne.push({instanceLocation:a,keyword:"properties",keywordLocation:t,error:`Property "${o}" does not match schema.`},...h.errors),u)break}}if(!u&&void 0!==T){const t=`${o}/patternProperties`;for(const o in T){const d=new RegExp(o,"u"),h=T[o];for(const p in e){if(!d.test(p))continue;const f=`${a}/${po(p)}`,m=Co(e[p],h,n,r,s,i,f,`${t}/${po(o)}`);m.valid?l[p]=c[p]=!0:(u=s,ne.push({instanceLocation:a,keyword:"patternProperties",keywordLocation:t,error:`Property "${p}" matches pattern "${o}" but does not match associated schema.`},...m.errors))}}}if(u||void 0===I){if(!u&&void 0!==A){const t=`${o}/unevaluatedProperties`;for(const o in e)if(!l[o]){const c=`${a}/${po(o)}`,u=Co(e[o],A,n,r,s,i,c,t);u.valid?l[o]=!0:ne.push({instanceLocation:a,keyword:"unevaluatedProperties",keywordLocation:t,error:`Property "${o}" does not match unevaluated properties schema.`},...u.errors)}}}else{const t=`${o}/additionalProperties`;for(const o in e){if(c[o])continue;const d=`${a}/${po(o)}`,h=Co(e[o],I,n,r,s,i,d,t);h.valid?l[o]=!0:(u=s,ne.push({instanceLocation:a,keyword:"additionalProperties",keywordLocation:t,error:`Property "${o}" does not match additional properties schema.`},...h.errors))}}}else if("array"===u){void 0!==H&&e.length>H&&ne.push({instanceLocation:a,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${e.length} > ${H}).`}),void 0!==z&&e.length=(B||0)&&(ne.length=u),void 0===B&&void 0===q&&0===d?ne.splice(u,0,{instanceLocation:a,keyword:"contains",keywordLocation:c,error:"Array does not contain item matching schema."}):void 0!==B&&dq&&ne.push({instanceLocation:a,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${q} items matching schema. ${d} items were found.`})}if(!u&&void 0!==U){const u=`${o}/unevaluatedItems`;for(;c=K||e>K)&&ne.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${Z?"or equal to ":""} ${K}.`})):(void 0!==G&&eK&&ne.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${K}.`}),void 0!==J&&e<=J&&ne.push({instanceLocation:a,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${e} is less than ${J}.`}),void 0!==Z&&e>=Z&&ne.push({instanceLocation:a,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Z}.`})),void 0!==V){const t=e%V;Math.abs(0-t)>=1.1920929e-7&&Math.abs(V-t)>=1.1920929e-7&&ne.push({instanceLocation:a,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${e} is not a multiple of ${V}.`})}}else if("string"===u){const t=void 0===Y&&void 0===X?0:function(e){let t,n=0,r=e.length,s=0;for(;s=55296&&t<=56319&&sX&&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&&So[x]&&!So[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"}(Po||(Po={}));Object.freeze({status:"aborted"});function $o(e,t,n){function r(n,r){var s;Object.defineProperty(n,"_zod",{value:n._zod??{},enumerable:!1}),(s=n._zod).traits??(s.traits=new Set),n._zod.traits.add(e),t(n,r);for(const e in a.prototype)e in n||Object.defineProperty(n,e,{value:a.prototype[e].bind(n)});n._zod.constr=a,n._zod.def=r}const s=n?.Parent??Object;class i extends s{}function a(e){var t;const s=n?.Parent?new i:this;r(s,e),(t=s._zod).deferred??(t.deferred=[]);for(const e of s._zod.deferred)e();return s}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}Symbol("zod_brand");class Ro extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const No={};function jo(e){return e&&Object.assign(No,e),No}const Lo=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get:()=>JSON.stringify(t,_a,2),enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Mo=$o("$ZodError",Lo),Do=$o("$ZodError",Lo,{Parent:Error});const Uo=e=>(t,n,r,s)=>{const i=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Ro;if(a.issues.length){const t=new(s?.Err??e)(a.issues.map(e=>ka(e,i,jo())));throw ya(t,s?.callee),t}return a.value},Fo=Uo(Do),Bo=e=>async(t,n,r,s)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){const t=new(s?.Err??e)(a.issues.map(e=>ka(e,i,jo())));throw ya(t,s?.callee),t}return a.value},qo=Bo(Do),zo=e=>(t,n,r)=>{const s=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new Ro;return i.issues.length?{success:!1,error:new(e??Mo)(i.issues.map(e=>ka(e,s,jo())))}:{success:!0,data:i.value}},Ho=zo(Do),Wo=e=>async(t,n,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},s);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>ka(e,s,jo())))}:{success:!0,data:i.value}},Go=Wo(Do);function Ko(e,t){return new e({type:"never",...wa(t)})}const Jo={major:4,minor:0,patch:0},Zo=$o("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Jo;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const t of r)for(const n of t._zod.onattach)n(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,s=Ea(e);for(const i of t){if(i._zod.def.when){if(!i._zod.def.when(e))continue}else if(s)continue;const t=e.issues.length,a=i._zod.check(e);if(a instanceof Promise&&!1===n?.async)throw new Ro;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a;e.issues.length!==t&&(s||(s=Ea(e,t)))});else{if(e.issues.length===t)continue;s||(s=Ea(e,t))}}return r?r.then(()=>e):e};e._zod.run=(n,s)=>{const i=e._zod.parse(n,s);if(i instanceof Promise){if(!1===s.async)throw new Ro;return i.then(e=>t(e,r,s))}return t(i,r,s)}}e["~standard"]={validate:t=>{try{const n=Ho(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return Go(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}});const Vo=$o("$ZodNever",(e,t)=>{Zo.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Yo(e){if("object"!=typeof e||null===e)return!1;if(!("_zod"in e))return!1;const t=e._zod;return"object"==typeof t&&null!==t&&"def"in t}function Xo(e){if("object"!=typeof e||null===e)return!1;if(!("_def"in e)||"_zod"in e)return!1;const t=e._def;return"object"==typeof t&&null!=t&&"typeName"in t}function Qo(e){return!!e&&("object"==typeof e&&(!Array.isArray(e)&&!(!Yo(e)&&!Xo(e))))}async function el(e,t){if(Yo(e))try{return{success:!0,data:await qo(e,t)}}catch(e){return{success:!1,error:e}}if(Xo(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function tl(e,t){if(Yo(e))return Fo(e,t);if(Xo(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function nl(e){return Yo(e)?ga.get(e)?.description:Xo(e)||"description"in e&&"string"==typeof e.description?e.description:void 0}function rl(e){return!!Yo(e)&&("object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"object"===e._zod.def.type)}function sl(e){return!!Yo(e)&&("object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"array"===e._zod.def.type)}function il(e,t=!1){if(Xo(e))return e.strict();if(rl(e)){const n=e._zod.def.shape;if(t)for(const[r,s]of Object.entries(e._zod.def.shape)){if(rl(s)){const e=il(s,t);n[r]=e}else if(sl(s)){let e=s._zod.def.element;rl(e)&&(e=il(e,t)),n[r]=ba(s,{...s._zod.def,element:e})}else n[r]=s;const e=ga.get(s);e&&ga.add(n[r],e)}const r=ba(e,{...e._zod.def,shape:n,catchall:Ko(Vo)}),s=ga.get(e);return s&&ga.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function al(e,t=!1){if(Xo(e))return function(e){return Xo(e)&&"typeName"in e._def&&"ZodEffects"===e._def.typeName}(e)?al(e._def.schema,t):e;if(Yo(e)){let n=e;if(function(e){return Yo(e)&&"pipe"===e._zod.def.type}(e)&&(n=al(e._zod.def.in,t)),t)if(rl(n)){const e=n._zod.def.shape;for(const[r,s]of Object.entries(n._zod.def.shape))e[r]=al(s,t);n=ba(n,{...n._zod.def,shape:e})}else if(sl(n)){const e=al(n._zod.def.element,t);n=ba(n,{...n._zod.def,element:e})}const r=ga.get(e);return r&&ga.add(n,r),n}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function ol(e){if(Yo(e)){const t=al(e,!0);if(rl(t)){return Oa(il(t,!0))}return Oa(e)}return Xo(e)?((e,t)=>{const n=Pa(t);let r="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:lo(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??$a(n)}),{}):void 0;const s="string"==typeof t?t:"title"===t?.nameStrategy?void 0:t?.name,i=lo(e._def,void 0===s?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??$a(n),a="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==a&&(i.title=a),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===n.$refStrategy?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const o=void 0===s?r?{...i,[n.definitionPath]:r}:i:{$ref:[..."relative"===n.$refStrategy?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...r,[s]:i}};return"jsonSchema7"===n.target?o.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==n.target&&"openAi"!==n.target||(o.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===n.target&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type)),o})(e):e}function ll(e,t){if(void 0!==e&&!ua(e))return e;if(!oa(t))return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e,e}catch(e){return t.getName()}}function cl(e){return oa(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...ol(e.data.schema),title:e.data.name}}}class ul{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((t,n)=>{e[t.id]=ua(t.id)?n:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...cl(t)})),edges:this.edges.map(t=>{const n={source:e[t.source],target:e[t.target]};return void 0!==t.data&&(n.data=t.data),void 0!==t.conditional&&(n.conditional=t.conditional),n})}}addNode(e,t,n){if(void 0!==t&&void 0!==this.nodes[t])throw new Error(`Node with id ${t} already exists`);const r=t??Bn(),s={id:r,data:e,name:ll(t,e),metadata:n};return this.nodes[r]=s,s}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,n,r){if(void 0===this.nodes[e.id])throw new Error(`Source node ${e.id} not in graph`);if(void 0===this.nodes[t.id])throw new Error(`Target node ${t.id} not in graph`);const s={source:e.id,target:t.id,data:n,conditional:r};return this.edges.push(s),s}firstNode(){return dl(this)}lastNode(){return hl(this)}extend(e,t=""){let n=t;Object.values(e.nodes).map(e=>e.id).every(ua)&&(n="");const r=e=>n?`${n}:${e}`:e;Object.entries(e.nodes).forEach(([e,t])=>{this.nodes[r(e)]={...t,id:r(e)}});const s=e.edges.map(e=>({...e,source:r(e.source),target:r(e.target)}));this.edges=[...this.edges,...s];const i=e.firstNode(),a=e.lastNode();return[i?{id:r(i.id),data:i.data}:void 0,a?{id:r(a.id),data:a.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&dl(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&hl(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map(e=>[e.id,e.name])),t=new Map;Object.values(e).forEach(e=>{t.set(e,(t.get(e)||0)+1)});const n=n=>{const r=e[n];return ua(n)&&1===t.get(r)?r:n};return new ul({nodes:Object.fromEntries(Object.entries(this.nodes).map(([e,t])=>[n(e),{...t,id:n(e)}])),edges:this.edges.map(e=>({...e,source:n(e.source),target:n(e.target)}))})}drawMermaid(e){const{withStyles:t,curveStyle:n,nodeColors:r={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:s}=e??{},i=this.reid(),a=i.firstNode(),o=i.lastNode();return pa(i.nodes,i.edges,{firstNode:a?.id,lastNode:o?.id,withStyles:t,curveStyle:n,nodeColors:r,wrapLabelNWords:s})}async drawMermaidPng(e){return async function(e,t){let{backgroundColor:n="white"}=t??{};const r=btoa(e);void 0!==n&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));const s=`https://mermaid.ink/img/${r}?bgColor=${n}`,i=await fetch(s);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join("\n"));return await i.blob()}(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}}function dl(e,t=[]){const n=new Set(e.edges.filter(e=>!t.includes(e.source)).map(e=>e.target)),r=[];for(const s of Object.values(e.nodes))t.includes(s.id)||n.has(s.id)||r.push(s);return 1===r.length?r[0]:void 0}function hl(e,t=[]){const n=new Set(e.edges.filter(e=>!t.includes(e.target)).map(e=>e.source)),r=[];for(const s of Object.values(e.nodes))t.includes(s.id)||n.has(s.id)||r.push(s);return 1===r.length?r[0]:void 0}function pl(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.iterator]&&"function"==typeof e.next}function fl(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.asyncIterator]}function*ml(e,t){for(;;){const{value:n,done:r}=Ri.runWithConfig(Ui(e),t.next.bind(t),!0);if(r)break;yield n}}async function*gl(e,t){const n=t[Symbol.asyncIterator]();for(;;){const{value:r,done:s}=await Ri.runWithConfig(Ui(e),n.next.bind(t),!0);if(s)break;yield r}}function _l(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}class yl extends Zt{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}bind(e){return new vl({bound:this,kwargs:e,config:{}})}map(){return new bl({bound:this})}withRetry(e){return new wl({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new vl({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new Ol({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(Mi);if(t>1&&!Array.isArray(e)&&e.runId){const n=Object.fromEntries(Object.entries(e).filter(([e])=>"runId"!==e));return Array.from({length:t},(t,r)=>Mi(0===r?e:n))}return Array.from({length:t},()=>Mi(e))}async batch(e,t,n){const r=this._getOptionsList(t??{},e.length),s=r[0]?.maxConcurrency??n?.maxConcurrency,i=new ia({maxConcurrency:s,onFailedAttempt:e=>{throw e}}),a=e.map((e,t)=>i.call(async()=>{try{return await this.invoke(e,r[t])}catch(e){if(n?.returnExceptions)return e;throw e}}));return Promise.all(a)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const n=Mi(t),r=new Hi({generator:this._streamIterator(e,n),config:n});return await r.setup,Bi.fromAsyncGenerator(r)}_separateRunnableConfigFromCallOptions(e){let t;t=Mi(void 0===e?e:{callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[t,n]}async _callWithConfig(e,t,n){const r=Mi(n),s=await Ni(r),i=await(s?.handleChainStart(this.toJSON(),_l(t,"input"),r.runId,r?.runType,void 0,void 0,r?.runName??this.getName()));let a;delete r.runId;try{const s=e.call(this,t,r,i);a=await Fi(s,n?.signal)}catch(e){throw await(i?.handleChainError(e)),e}return await(i?.handleChainEnd(_l(a,"output"))),a}async _batchWithConfig(e,t,n,r){const s=this._getOptionsList(n??{},t.length),i=await Promise.all(s.map(Ni)),a=await Promise.all(i.map(async(e,n)=>{const r=await(e?.handleChainStart(this.toJSON(),_l(t[n],"input"),s[n].runId,s[n].runType,void 0,void 0,s[n].runName??this.getName()));return delete s[n].runId,r}));let o;try{const n=e.call(this,t,s,a,r);o=await Fi(n,s?.[0]?.signal)}catch(e){throw await Promise.all(a.map(t=>t?.handleChainError(e))),e}return await Promise.all(a.map(e=>e?.handleChainEnd(_l(o,"output")))),o}async*_transformStreamWithConfig(e,t,n){let r,s,i=!0,a=!0;const o=Mi(n),l=await Ni(o);let c;try{const u=await async function(e,t,n,r,...s){const i=new Hi({generator:t,startSetup:n,signal:r}),a=await i.setup;return{output:e(i,a,...s),setup:a}}(t.bind(this),async function*(){for await(const t of e){if(i)if(void 0===r)r=t;else try{r=zi(r,t)}catch{r=void 0,i=!1}yield t}}(),async()=>l?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName()),n?.signal,o);delete o.runId,c=u.setup;const d=c?.handlers.find(ta);let h=u.output;void 0!==d&&void 0!==c&&(h=d.tapOutputIterable(c.runId,h));const p=c?.handlers.find(Ki);void 0!==p&&void 0!==c&&(h=p.tapOutputIterable(c.runId,h));for await(const e of h)if(yield e,a)if(void 0===s)s=e;else try{s=zi(s,e)}catch{s=void 0,a=!1}}catch(e){throw await(c?.handleChainError(e,void 0,void 0,void 0,{inputs:_l(r,"input")})),e}await(c?.handleChainEnd(s??{},void 0,void 0,void 0,{inputs:_l(r,"input")}))}getGraph(e){const t=new ul,n=t.addNode({name:`${this.getName()}Input`,schema:Be()}),r=t.addNode(this),s=t.addNode({name:`${this.getName()}Output`,schema:Be()});return t.addEdge(n,r),t.addEdge(r,s),t}pipe(e){return new El({first:this,last:Tl(e)})}pick(e){return this.pipe(new Al(e))}assign(e){return this.pipe(new Il(new Sl({steps:e})))}async*transform(e,t){let n;for await(const t of e)n=void 0===n?t:zi(n,t);yield*this._streamIterator(n,Mi(t))}async*streamLog(e,t,n){const r=new Vi({...n,autoClose:!1,_schemaFormat:"original"}),s=Mi(t);yield*this._streamLog(e,r,s)}async*_streamLog(e,t,n){const{callbacks:r}=n;if(void 0===r)n.callbacks=[t];else if(Array.isArray(r))n.callbacks=r.concat([t]);else{const e=r.copy();e.addHandler(t,!0),n.callbacks=e}const s=this.stream(e,n);const i=async function(){try{const e=await s;for await(const n of e){const e=new Wi({ops:[{op:"add",path:"/streamed_output/-",value:n}]});await t.writer.write(e)}}finally{await t.writer.close()}}();try{for await(const e of t)yield e}finally{await i}}streamEvents(e,t,n){let r;if("v1"===t.version)r=this._streamEventsV1(e,t,n);else{if("v2"!==t.version)throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');r=this._streamEventsV2(e,t,n)}return"text/event-stream"===t.encoding?function(e){const t=new TextEncoder,n=new ReadableStream({async start(n){for await(const r of e)n.enqueue(t.encode(`event: data\ndata: ${JSON.stringify(r)}\n\n`));n.enqueue(t.encode("event: end\n\n")),n.close()}});return Bi.fromReadableStream(n)}(r):Bi.fromAsyncGenerator(r)}async*_streamEventsV2(e,t,n){const r=new na({...n,autoClose:!1}),s=Mi(t),i=s.runId??Bn();s.runId=i;const a=s.callbacks;if(void 0===a)s.callbacks=[r];else if(Array.isArray(a))s.callbacks=a.concat(r);else{const e=a.copy();e.addHandler(r,!0),s.callbacks=e}const o=new AbortController,l=this;const c=async function(){let n,a=null;try{t?.signal?"any"in AbortSignal?n=AbortSignal.any([o.signal,t.signal]):(n=t.signal,a=()=>{o.abort()},t.signal.addEventListener("abort",a,{once:!0})):n=o.signal;const c=await l.stream(e,{...s,signal:n}),u=r.tapOutputIterable(i,c);for await(const e of u)if(o.signal.aborted)break}finally{await r.finish(),n&&a&&n.removeEventListener("abort",a)}}();let u,d=!1;try{for await(const t of r)d?(t.run_id===u&&t.event.endsWith("_end")&&t.data?.input&&delete t.data.input,yield t):(t.data.input=e,d=!0,u=t.run_id,yield t)}finally{o.abort(),await c}}async*_streamEventsV1(e,t,n){let r,s=!1;const i=Mi(t),a=i.tags??[],o=i.metadata??{},l=i.runName??this.getName(),c=new Vi({...n,autoClose:!1,_schemaFormat:"streaming_events"}),u=new la({...n}),d=this._streamLog(e,c,i);for await(const t of d){if(r=r?r.concat(t):Gi.fromRunLogPatch(t),void 0===r.state)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!s){s=!0;const t={...r.state},n={run_id:t.id,event:`on_${t.type}_start`,name:l,tags:a,metadata:o,data:{input:e}};u.includeEvent(n,t.type)&&(yield n)}const n=t.ops.filter(e=>e.path.startsWith("/logs/")).map(e=>e.path.split("/")[2]),i=[...new Set(n)];for(const e of i){let t,n={};const s=r.state.logs[e];if(t=void 0===s.end_time?s.streamed_output.length>0?"stream":"start":"end","start"===t)void 0!==s.inputs&&(n.input=s.inputs);else if("end"===t)void 0!==s.inputs&&(n.input=s.inputs),n.output=s.final_output;else if("stream"===t){const e=s.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${s.name}"`);n={chunk:s.streamed_output[0]},s.streamed_output=[]}yield{event:`on_${s.type}_${t}`,name:s.name,run_id:s.id,tags:s.tags,metadata:s.metadata,data:n}}const{state:c}=r;if(c.streamed_output.length>0){const e=c.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${c.name}"`);const t={chunk:c.streamed_output[0]};c.streamed_output=[];const n={event:`on_${c.type}_stream`,run_id:c.id,tags:a,metadata:o,name:l,data:t};u.includeEvent(n,c.type)&&(yield n)}}const h=r?.state;if(void 0!==h){const e={event:`on_${h.type}_end`,name:l,run_id:h.id,tags:a,metadata:o,data:{output:h.final_output}};u.includeEvent(e,h.type)&&(yield e)}}static isRunnable(e){return oa(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new vl({bound:this,config:{},configFactories:[r=>({callbacks:[new aa({config:r,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return function(e,t){const n=t.name??e.getName(),r=t.description??nl(t.schema);if(function(e){if(!Qo(e))return!1;if(Xo(e))return"ZodString"===e._def.typeName;if(Yo(e))return"string"===e._zod.def.type;return!1}(t.schema))return new Pl({name:n,description:r,schema:He({input:De()}).transform(e=>e.input),bound:e});return new Pl({name:n,description:r,schema:t.schema,bound:e})}(this,e)}}class vl extends yl{static lc_name(){return"RunnableBinding"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"bound",{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,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configFactories",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){const t=ji(this.config,...e);return ji(t,...this.configFactories?await Promise.all(this.configFactories.map(async e=>await e(t))):[])}bind(e){return new this.constructor({bound:this.bound,kwargs:{...this.kwargs,...e},config:this.config})}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new wl({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(Mi(t),this.kwargs))}async batch(e,t,n){const r=Array.isArray(t)?await Promise.all(t.map(async e=>this._mergeConfig(Mi(e),this.kwargs))):await this._mergeConfig(Mi(t),this.kwargs);return this.bound.batch(e,r,n)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(Mi(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(Mi(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(Mi(t),this.kwargs))}streamEvents(e,t,n){const r=this;return Bi.fromAsyncGenerator(async function*(){yield*r.bound.streamEvents(e,{...await r._mergeConfig(Mi(t),r.kwargs),version:t.version},n)}())}static isRunnableBinding(e){return e.bound&&yl.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:n}){return new vl({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[r=>({callbacks:[new aa({config:r,onStart:e,onEnd:t,onError:n})]})]})}}class bl extends yl{static lc_name(){return"RunnableEach"}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound}bind(e){return new bl({bound:this.bound.bind(e)})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,n){return this.bound.batch(e,Di(t,{callbacks:n?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:n}){return new bl({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:n})})}}class wl extends vl{static lc_name(){return"RunnableRetry"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"maxAttemptNumber",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}}),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,n){const r=e>1?`retry:attempt:${e}`:void 0;return Di(t,{callbacks:n?.getChild(r)})}async _invoke(e,t,n){return Rn(r=>super.invoke(e,this._patchConfigForRetry(r,t,n)),{onFailedAttempt:t=>this.onFailedAttempt(t,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,n,r){const s={};try{await Rn(async i=>{const a=e.map((e,t)=>t).filter(e=>void 0===s[e.toString()]||s[e.toString()]instanceof Error),o=a.map(t=>e[t]),l=a.map(e=>this._patchConfigForRetry(i,t?.[e],n?.[e])),c=await super.batch(o,l,{...r,returnExceptions:!0});let u;for(let e=0;ethis.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(!0!==r?.returnExceptions)throw e}return Object.keys(s).sort((e,t)=>parseInt(e,10)-parseInt(t,10)).map(e=>s[parseInt(e,10)])}async batch(e,t,n){return this._batchWithConfig(this._batch.bind(this),e,t,n)}}class El extends yl{static lc_name(){return"RunnableSequence"}constructor(e){super(e),Object.defineProperty(this,"first",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"middle",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"last",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitSequenceTags",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){const n=Mi(t),r=await Ni(n),s=await(r?.handleChainStart(this.toJSON(),_l(e,"input"),n.runId,void 0,void 0,void 0,n?.runName));delete n.runId;let i,a=e;try{const e=[this.first,...this.middle];for(let r=0;r{const s=await(t?.handleChainStart(this.toJSON(),_l(e[n],"input"),r[n].runId,void 0,void 0,void 0,r[n].runName));return delete r[n].runId,s}));let a=e;try{for(let e=0;e{const s=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return Di(r[n],{callbacks:s})}),n);a=await Fi(t,r[0]?.signal)}}catch(e){throw await Promise.all(i.map(t=>t?.handleChainError(e))),e}return await Promise.all(i.map(e=>e?.handleChainEnd(_l(a,"output")))),a}async*_streamIterator(e,t){const n=await Ni(t),{runId:r,...s}=t??{},i=await(n?.handleChainStart(this.toJSON(),_l(e,"input"),r,void 0,void 0,void 0,s?.runName)),a=[this.first,...this.middle,this.last];let o,l=!0;try{let n=a[0].transform(async function*(){yield e}(),Di(s,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let e=1;e{const i=r.getGraph(e);0!==s&&i.trimFirstNode(),s!==this.steps.length-1&&i.trimLastNode(),t.extend(i);const a=i.firstNode();if(!a)throw new Error(`Runnable ${r} has no first node`);n&&t.addEdge(n,a),n=i.lastNode()}),t}pipe(e){return El.isRunnableSequence(e)?new El({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new El({first:this.first,middle:[...this.middle,this.last],last:Tl(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&yl.isRunnable(e)}static from([e,...t],n){let r={};return"string"==typeof n?r.name=n:void 0!==n&&(r=n),new El({...r,first:Tl(e),middle:t.slice(0,-1).map(Tl),last:Tl(t[t.length-1])})}}class Sl extends yl{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"steps",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.steps={};for(const[t,n]of Object.entries(e.steps))this.steps[t]=Tl(n)}static from(e){return new Sl({steps:e})}async invoke(e,t){const n=Mi(t),r=await Ni(n),s=await(r?.handleChainStart(this.toJSON(),{input:e},n.runId,void 0,void 0,void 0,n?.runName));delete n.runId;const i={};try{const r=Object.entries(this.steps).map(async([t,r])=>{i[t]=await r.invoke(e,Di(n,{callbacks:s?.getChild(`map:key:${t}`)}))});await Fi(Promise.all(r),t?.signal)}catch(e){throw await(s?.handleChainError(e)),e}return await(s?.handleChainEnd(i)),i}async*_transform(e,t,n){const r={...this.steps},s=qi(e,Object.keys(r).length),i=new Map(Object.entries(r).map(([e,r],i)=>{const a=r.transform(s[i],Di(n,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,a.next().then(t=>({key:e,gen:a,result:t}))]}));for(;i.size;){const e=Promise.race(i.values()),{key:t,result:r,gen:s}=await Fi(e,n?.signal);i.delete(t),r.done||(yield{[t]:r.value},i.set(t,s.next().then(e=>({key:t,gen:s,result:e}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const n=Mi(t),r=new Hi({generator:this.transform(async function*(){yield e}(),n),config:n});return await r.setup,Bi.fromAsyncGenerator(r)}}class kl extends yl{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!Wn(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){const[n]=this._getOptionsList(t??{},1),r=await Ni(n);return Fi(this.func(Di(n,{callbacks:r}),e),n?.signal)}async*_streamIterator(e,t){const[n]=this._getOptionsList(t??{},1),r=await this.invoke(e,t);if(fl(r))for await(const e of r)n?.signal?.throwIfAborted(),yield e;else if((e=>null!=e&&"object"==typeof e&&"next"in e&&"function"==typeof e.next)(r))for(;;){n?.signal?.throwIfAborted();const e=r.next();if(e.done)break;yield e.value}else yield r}static from(e){return new kl({func:e})}}class xl extends yl{static lc_name(){return"RunnableLambda"}constructor(e){if(Wn(e.func))return kl.from(e.func);super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),function(e){if(Wn(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}(e.func),this.func=e.func}static from(e){return new xl({func:e})}async _invoke(e,t,n){return new Promise((r,s)=>{const i=Di(t,{callbacks:n?.getChild(),recursionLimit:(t?.recursionLimit??25)-1});Ri.runWithConfig(Ui(i),async()=>{try{let n=await this.func(e,{...i});if(n&&yl.isRunnable(n)){if(0===t?.recursionLimit)throw new Error("Recursion limit reached.");n=await n.invoke(e,{...i,recursionLimit:(i.recursionLimit??25)-1})}else if(fl(n)){let e;for await(const r of gl(i,n))if(t?.signal?.throwIfAborted(),void 0===e)e=r;else try{e=zi(e,r)}catch(t){e=r}n=e}else if(pl(n)){let e;for(const r of ml(i,n))if(t?.signal?.throwIfAborted(),void 0===e)e=r;else try{e=zi(e,r)}catch(t){e=r}n=e}r(n)}catch(e){s(e)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,n){let r;for await(const t of e)if(void 0===r)r=t;else try{r=zi(r,t)}catch(e){r=t}const s=Di(n,{callbacks:t?.getChild(),recursionLimit:(n?.recursionLimit??25)-1}),i=await new Promise((e,t)=>{Ri.runWithConfig(Ui(s),async()=>{try{const t=await this.func(r,{...s,config:s});e(t)}catch(e){t(e)}})});if(i&&yl.isRunnable(i)){if(0===n?.recursionLimit)throw new Error("Recursion limit reached.");const e=await i.stream(r,s);for await(const t of e)yield t}else if(fl(i))for await(const e of gl(s,i))n?.signal?.throwIfAborted(),yield e;else if(pl(i))for(const e of ml(s,i))n?.signal?.throwIfAborted(),yield e;else yield i}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const n=Mi(t),r=new Hi({generator:this.transform(async function*(){yield e}(),n),config:n});return await r.setup,Bi.fromAsyncGenerator(r)}}class Ol extends yl{static lc_name(){return"RunnableWithFallbacks"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"runnable",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fallbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const n=Mi(t),r=await Ni(n),{runId:s,...i}=n,a=await(r?.handleChainStart(this.toJSON(),_l(e,"input"),s,void 0,void 0,void 0,i?.runName)),o=Di(i,{callbacks:a?.getChild()}),l=await Ri.runWithConfig(o,async()=>{let t;for(const r of this.runnables()){n?.signal?.throwIfAborted();try{const t=await r.invoke(e,o);return await(a?.handleChainEnd(_l(t,"output"))),t}catch(e){void 0===t&&(t=e)}}if(void 0===t)throw new Error("No error stored at end of fallback.");throw await(a?.handleChainError(t)),t});return l}async*_streamIterator(e,t){const n=Mi(t),r=await Ni(n),{runId:s,...i}=n,a=await(r?.handleChainStart(this.toJSON(),_l(e,"input"),s,void 0,void 0,void 0,i?.runName));let o,l,c;for(const t of this.runnables()){n?.signal?.throwIfAborted();const r=Di(i,{callbacks:a?.getChild()});try{l=gl(r,await t.stream(e,r));break}catch(e){void 0===o&&(o=e)}}if(void 0===l){const e=o??new Error("No error stored at end of fallback.");throw await(a?.handleChainError(e)),e}try{for await(const e of l){yield e;try{c=void 0===c?c:zi(c,e)}catch(e){c=void 0}}}catch(e){throw await(a?.handleChainError(e)),e}await(a?.handleChainEnd(_l(c,"output")))}async batch(e,t,n){if(n?.returnExceptions)throw new Error("Not implemented.");const r=this._getOptionsList(t??{},e.length),s=await Promise.all(r.map(e=>Ni(e))),i=await Promise.all(s.map(async(t,n)=>{const s=await(t?.handleChainStart(this.toJSON(),_l(e[n],"input"),r[n].runId,void 0,void 0,void 0,r[n].runName));return delete r[n].runId,s}));let a;for(const t of this.runnables()){r[0].signal?.throwIfAborted();try{const s=await t.batch(e,i.map((e,t)=>Di(r[t],{callbacks:e?.getChild()})),n);return await Promise.all(i.map((e,t)=>e?.handleChainEnd(_l(s[t],"output")))),s}catch(e){void 0===a&&(a=e)}}if(!a)throw new Error("No error stored at end of fallbacks.");throw await Promise.all(i.map(e=>e?.handleChainError(a))),a}}function Tl(e){if("function"==typeof e)return new xl({func:e});if(yl.isRunnable(e))return e;if(Array.isArray(e)||"object"!=typeof e)throw new Error("Expected a Runnable, function or object.\nInstead got an unsupported type.");{const t={};for(const[n,r]of Object.entries(e))t[n]=Tl(r);return new Sl({steps:t})}}class Il extends yl{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof Sl&&(e={mapper:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mapper=e.mapper}async invoke(e,t){const n=await this.mapper.invoke(e,t);return{...e,...n}}async*_transform(e,t,n){const r=this.mapper.getStepsKeys(),[s,i]=qi(e),a=this.mapper.transform(i,Di(n,{callbacks:t?.getChild()})),o=a.next();for await(const e of s){if("object"!=typeof e||Array.isArray(e))throw new Error("RunnableAssign can only be used with objects as input, got "+typeof e);const t=Object.fromEntries(Object.entries(e).filter(([e])=>!r.includes(e)));Object.keys(t).length>0&&(yield t)}yield(await o).value;for await(const e of a)yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const n=Mi(t),r=new Hi({generator:this.transform(async function*(){yield e}(),n),config:n});return await r.setup,Bi.fromAsyncGenerator(r)}}class Al extends yl{static lc_name(){return"RunnablePick"}constructor(e){("string"==typeof e||Array.isArray(e))&&(e={keys:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keys=e.keys}async _pick(e){if("string"==typeof this.keys)return e[this.keys];{const t=this.keys.map(t=>[t,e[t]]).filter(e=>void 0!==e[1]);return 0===t.length?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const e=await this._pick(t);void 0!==e&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const n=Mi(t),r=new Hi({generator:this.transform(async function*(){yield e}(),n),config:n});return await r.setup,Bi.fromAsyncGenerator(r)}}class Pl extends vl{constructor(e){super({bound:El.from([xl.from(async e=>{let t;if(On(e))try{t=await tl(this.schema,e.args)}catch(t){throw new Tn("Received tool input did not match expected schema",JSON.stringify(e.args))}else t=e;return t}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name}),config:e.config??{}}),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}static lc_name(){return"RunnableToolLike"}}var Cl;!function(e){e.SYSTEM="system",e.AI="ai",e.HUMAN="human",e.TOOL="tool",e.BROWSER_STATE="browser_state"}(Cl||(Cl={}));class $l extends fn{constructor(e){super(e),this.additional_kwargs={messageType:Cl.BROWSER_STATE}}}class Rl{constructor(e){this.messageManager=e}getAll(){return this.messageManager.getMessages()}getRecentBrowserState(){const e=this.messageManager.getMessages();for(let t=e.length-1;t>=0;t--)if(e[t]instanceof $l)return e[t].content;return null}}class Nl{constructor(e=8192){this.messages=[],this.maxTokens=e}add(e){this.messages.push(e),this._trimIfNeeded()}addHuman(e){this.add(new wn(e)),this._trimIfNeeded()}addAI(e){this.add(new fn(e)),this._trimIfNeeded()}addSystem(e,t){this.removeSystemMessages(),this.messages.splice(t??this.messages.length,0,new Sn(e)),this._trimIfNeeded()}addBrowserState(e){this.removeMessagesByType(Cl.BROWSER_STATE),this.add(new $l(e)),this._trimIfNeeded()}addTool(e,t){this.add(new hn(e,t)),this._trimIfNeeded()}addSystemReminder(e){this.add(new wn(`${e}`)),this._trimIfNeeded()}getMessages(){return[...this.messages]}_getMessageType(e){return e.additional_kwargs?.messageType===Cl.BROWSER_STATE?Cl.BROWSER_STATE:e instanceof wn?Cl.HUMAN:e instanceof fn?Cl.AI:e instanceof Sn?Cl.SYSTEM:e instanceof hn?Cl.TOOL:Cl.AI}removeMessagesByType(e){this.messages=this.messages.filter(t=>this._getMessageType(t)!==e)}getTokenCount(){if(0===this.messages.length)return 0;let e=0;for(const t of this.messages){if(e+=3,"string"==typeof t.content)e+=Math.ceil(t.content.length/4);else if(t.content){const n=JSON.stringify(t.content);e+=Math.ceil(n.length/4)}if(t instanceof fn&&t.tool_calls){const n=JSON.stringify(t.tool_calls);e+=Math.ceil(n.length/4)}t instanceof hn&&t.tool_call_id&&(e+=Math.ceil(t.tool_call_id.length/4))}return e}remaining(){return Math.max(0,this.maxTokens-this.getTokenCount())}clear(){this.messages=[]}removeLast(){return void 0!==this.messages.pop()}removeSystemMessages(){this.removeMessagesByType(Cl.SYSTEM)}fork(e=!0){const t=new Nl(this.maxTokens);return e&&(t.messages=[...this.messages]),t}_trimIfNeeded(){for(;this.getTokenCount()>this.maxTokens&&this.messages.length>1;){const e=this.messages.findIndex(e=>this._getMessageType(e)!==Cl.SYSTEM);-1!==e?this.messages.splice(e,1):this.messages.shift()}}}function jl(e,t,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,n):s?s.value=n:t.set(e,n),n}function Ll(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}let Ml=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return Ml=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^n()&15>>+e/4).toString(16))};function Dl(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const Ul=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class Fl extends Error{}class Bl extends Fl{constructor(e,t,n,r){super(`${Bl.makeMessage(e,t,n)}`),this.status=e,this.headers=r,this.requestID=r?.get("x-request-id"),this.error=t;const s=t;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,t,n){const r=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e||!r)return new zl({message:n,cause:Ul(t)});const s=t?.error;return 400===e?new Wl(e,s,n,r):401===e?new Gl(e,s,n,r):403===e?new Kl(e,s,n,r):404===e?new Jl(e,s,n,r):409===e?new Zl(e,s,n,r):422===e?new Vl(e,s,n,r):429===e?new Yl(e,s,n,r):e>=500?new Xl(e,s,n,r):new Bl(e,s,n,r)}}class ql extends Bl{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class zl extends Bl{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Hl extends zl{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Wl extends Bl{}class Gl extends Bl{}class Kl extends Bl{}class Jl extends Bl{}class Zl extends Bl{}class Vl extends Bl{}class Yl extends Bl{}class Xl extends Bl{}class Ql extends Fl{constructor(){super("Could not parse response content as the length limit was reached")}}class ec extends Fl{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class tc extends Error{constructor(e){super(e)}}const nc=/^[a-z][a-z0-9+.-]*:/i;let rc=e=>(rc=Array.isArray,rc(e)),sc=rc;function ic(e){return"object"!=typeof e?{}:e??{}}function ac(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}const oc=e=>new Promise(t=>setTimeout(t,e)),lc="5.10.1";const cc=()=>{const e="undefined"!=typeof Deno&&null!=Deno.build?"deno":"undefined"!=typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":lc,"X-Stainless-OS":dc(Deno.build.os),"X-Stainless-Arch":uc(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":lc,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":lc,"X-Stainless-OS":dc(globalThis.process.platform??"unknown"),"X-Stainless-Arch":uc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:n}of e){const e=n.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":lc,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":lc,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const uc=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",dc=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let hc;function pc(...e){const t=globalThis.ReadableStream;if(void 0===t)throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function fc(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return pc({start(){},async pull(e){const{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await(t.return?.())}})}function mc(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}const gc=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),_c="RFC3986",yc=e=>String(e),vc={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:yc},bc="RFC1738";let wc=(e,t)=>(wc=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),wc(e,t));const Ec=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();const Sc=1024;function kc(e,t){if(rc(e)){const n=[];for(let r=0;rString(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},Oc=function(e,t){Array.prototype.push.apply(e,rc(t)?t:[t])};let Tc;const Ic={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,n,r,s)=>{if(0===e.length)return e;let i=e;if("symbol"==typeof e?i=Symbol.prototype.toString.call(e):"string"!=typeof e&&(i=String(e)),"iso-8859-1"===n)return escape(i).replace(/%u[0-9a-f]{4}/gi,function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"});let a="";for(let e=0;e=Sc?i.slice(e,e+Sc):i,n=[];for(let e=0;e=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||s===bc&&(40===r||41===r)?n[n.length]=t.charAt(e):r<128?n[n.length]=Ec[r]:r<2048?n[n.length]=Ec[192|r>>6]+Ec[128|63&r]:r<55296||r>=57344?n[n.length]=Ec[224|r>>12]+Ec[128|r>>6&63]+Ec[128|63&r]:(e+=1,r=65536+((1023&r)<<10|1023&t.charCodeAt(e)),n[n.length]=Ec[240|r>>18]+Ec[128|r>>12&63]+Ec[128|r>>6&63]+Ec[128|63&r])}a+=n.join("")}return a},encodeValuesOnly:!1,format:_c,formatter:yc,indices:!1,serializeDate:e=>(Tc??(Tc=Function.prototype.call.bind(Date.prototype.toISOString)))(e),skipNulls:!1,strictNullHandling:!1};const Ac={};function Pc(e,t,n,r,s,i,a,o,l,c,u,d,h,p,f,m,g,_){let y=e,v=_,b=0,w=!1;for(;void 0!==(v=v.get(Ac))&&!w;){const t=v.get(e);if(b+=1,void 0!==t){if(t===b)throw new RangeError("Cyclic object value");w=!0}void 0===v.get(Ac)&&(b=0)}if("function"==typeof c?y=c(t,y):y instanceof Date?y=h?.(y):"comma"===n&&rc(y)&&(y=kc(y,function(e){return e instanceof Date?h?.(e):e})),null===y){if(i)return l&&!m?l(t,Ic.encoder,g,"key",p):t;y=""}if(function(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e||"symbol"==typeof e||"bigint"==typeof e}(y)||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(y)){if(l){const e=m?t:l(t,Ic.encoder,g,"key",p);return[f?.(e)+"="+f?.(l(y,Ic.encoder,g,"value",p))]}return[f?.(t)+"="+f?.(String(y))]}const E=[];if(void 0===y)return E;let S;if("comma"===n&&rc(y))m&&l&&(y=kc(y,l)),S=[{value:y.length>0?y.join(",")||null:void 0}];else if(rc(c))S=c;else{const e=Object.keys(y);S=u?e.sort(u):e}const k=o?String(t).replace(/\./g,"%2E"):String(t),x=r&&rc(y)&&1===y.length?k+"[]":k;if(s&&rc(y)&&0===y.length)return x+"[]";for(let t=0;t0?d+u:""}let $c,Rc;function Nc(e){let t;return($c??(t=new globalThis.TextEncoder,$c=t.encode.bind(t)))(e)}function jc(e){let t;return(Rc??(t=new globalThis.TextDecoder,Rc=t.decode.bind(t)))(e)}var Lc,Mc;class Dc{constructor(){Lc.set(this,void 0),Mc.set(this,void 0),jl(this,Lc,new Uint8Array,"f"),jl(this,Mc,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?Nc(e):e;jl(this,Lc,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}([Ll(this,Lc,"f"),t]),"f");const n=[];let r;for(;null!=(r=Uc(Ll(this,Lc,"f"),Ll(this,Mc,"f")));){if(r.carriage&&null==Ll(this,Mc,"f")){jl(this,Mc,r.index,"f");continue}if(null!=Ll(this,Mc,"f")&&(r.index!==Ll(this,Mc,"f")+1||r.carriage)){n.push(jc(Ll(this,Lc,"f").subarray(0,Ll(this,Mc,"f")-1))),jl(this,Lc,Ll(this,Lc,"f").subarray(Ll(this,Mc,"f")),"f"),jl(this,Mc,null,"f");continue}const e=null!==Ll(this,Mc,"f")?r.preceding-1:r.preceding,t=jc(Ll(this,Lc,"f").subarray(0,e));n.push(t),jl(this,Lc,Ll(this,Lc,"f").subarray(r.index),"f"),jl(this,Mc,null,"f")}return n}flush(){return Ll(this,Lc,"f").length?this.decode("\n"):[]}}function Uc(e,t){for(let n=t??0;n{var r,s;if(e)return r=Bc,s=e,Object.prototype.hasOwnProperty.call(r,s)?e:void Kc(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Bc))}`)};function zc(){}function Hc(e,t,n){return!t||Bc[e]>Bc[n]?zc:t[e].bind(t)}const Wc={error:zc,warn:zc,info:zc,debug:zc};let Gc=new WeakMap;function Kc(e){const t=e.logger,n=e.logLevel??"off";if(!t)return Wc;const r=Gc.get(t);if(r&&r[0]===n)return r[1];const s={error:Hc("error",t,n),warn:Hc("warn",t,n),info:Hc("info",t,n),debug:Hc("debug",t,n)};return Gc.set(t,[n,s]),s}const Jc=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var Zc,Vc,Yc;class Xc{constructor(e,t,n){this.iterator=e,Zc.set(this,void 0),this.controller=t,jl(this,Zc,n,"f")}static fromSSEResponse(e,t,n){let r=!1;const s=n?Kc(n):console;return new Xc(async function*(){if(r)throw new Fl("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let n=!1;try{for await(const r of async function*(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new Fl("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new Fl("Attempted to iterate over a response with no body")}const n=new Qc,r=new Dc,s=mc(e.body);for await(const e of async function*(e){let t=new Uint8Array;for await(const n of e){if(null==n)continue;const e=n instanceof ArrayBuffer?new Uint8Array(n):"string"==typeof n?Nc(n):n;let r,s=new Uint8Array(t.length+e.length);for(s.set(t),s.set(e,t.length),t=s;-1!==(r=Fc(t));)yield t.slice(0,r),t=t.slice(r)}t.length>0&&(yield t)}(s))for(const t of r.decode(e)){const e=n.decode(t);e&&(yield e)}for(const e of r.flush()){const t=n.decode(e);t&&(yield t)}}(e,t))if(!n)if(r.data.startsWith("[DONE]"))n=!0;else if(null===r.event||r.event.startsWith("response.")||r.event.startsWith("image_edit.")||r.event.startsWith("image_generation.")||r.event.startsWith("transcript.")){let t;try{t=JSON.parse(r.data)}catch(e){throw s.error("Could not parse message into JSON:",r.data),s.error("From chunk:",r.raw),e}if(t&&t.error)throw new Bl(void 0,t.error,void 0,e.headers);yield t}else{let e;try{e=JSON.parse(r.data)}catch(e){throw e}if("error"==r.event)throw new Bl(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}n=!0}catch(e){if(Dl(e))return;throw e}finally{n||t.abort()}},t,n)}static fromReadableStream(e,t,n){let r=!1;return new Xc(async function*(){if(r)throw new Fl("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let n=!1;try{for await(const t of async function*(){const t=new Dc,n=mc(e);for await(const e of n)for(const n of t.decode(e))yield n;for(const e of t.flush())yield e}())n||t&&(yield JSON.parse(t));n=!0}catch(e){if(Dl(e))return;throw e}finally{n||t.abort()}},t,n)}[(Zc=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),r=r=>({next:()=>{if(0===r.length){const r=n.next();e.push(r),t.push(r)}return r.shift()}});return[new Xc(()=>r(e),this.controller,Ll(this,Zc,"f")),new Xc(()=>r(t),this.controller,Ll(this,Zc,"f"))]}toReadableStream(){const e=this;let t;return pc({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:n,done:r}=await t.next();if(r)return e.close();const s=Nc(JSON.stringify(n)+"\n");e.enqueue(s)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class Qc{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,r]=function(e,t){const n=e.indexOf(t);if(-1!==n)return[e.substring(0,n),t,e.substring(n+t.length)];return[e,"",""]}(e,":");return r.startsWith(" ")&&(r=r.substring(1)),"event"===t?this.event=r:"data"===t&&this.data.push(r),null}}async function eu(e,t){const{response:n,requestLogID:r,retryOfRequestLogID:s,startTime:i}=t,a=await(async()=>{if(t.options.stream)return Kc(e).debug("response",n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e):Xc.fromSSEResponse(n,t.controller,e);if(204===n.status)return null;if(t.options.__binaryResponse)return n;const r=n.headers.get("content-type"),s=r?.split(";")[0]?.trim();if(s?.includes("application/json")||s?.endsWith("+json")){return tu(await n.json(),n)}return await n.text()})();return Kc(e).debug(`[${r}] response parsed`,Jc({retryOfRequestLogID:s,url:n.url,status:n.status,body:a,durationMs:Date.now()-i})),a}function tu(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}class nu extends Promise{constructor(e,t,n=eu){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,Vc.set(this,void 0),jl(this,Vc,e,"f")}_thenUnwrap(e){return new nu(Ll(this,Vc,"f"),this.responsePromise,async(t,n)=>tu(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(Ll(this,Vc,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Vc=new WeakMap;class ru{constructor(e,t,n,r){Yc.set(this,void 0),jl(this,Yc,e,"f"),this.options=r,this.response=t,this.body=n}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new Fl("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Ll(this,Yc,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Yc=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class su extends nu{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await eu(e,t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}class iu extends ru{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class au extends ru{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...ic(this.options.query),after:t}}:null}}const ou=()=>{if("undefined"==typeof File){const{process:e}=globalThis,t="string"==typeof e?.versions?.node&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function lu(e,t,n){return ou(),new File(e,t??"unknown_file",n)}function cu(e){return("object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}const uu=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],du=async(e,t)=>({...e,body:await pu(e.body,t)}),hu=new WeakMap;const pu=async(e,t)=>{if(!await function(e){const t="function"==typeof e?e:e.fetch,n=hu.get(t);if(n)return n;const r=(async()=>{try{const e="Response"in t?t.Response:(await t("data:,")).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return hu.set(t,r),r}(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>mu(n,e,t))),n},fu=e=>e instanceof Blob&&"name"in e,mu=async(e,t,n)=>{if(void 0!==n){if(null==n)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)e.append(t,String(n));else if(n instanceof Response)e.append(t,lu([await n.blob()],cu(n)));else if(uu(n))e.append(t,lu([await new Response(fc(n)).blob()],cu(n)));else if(fu(n))e.append(t,n,cu(n));else if(Array.isArray(n))await Promise.all(n.map(n=>mu(e,t+"[]",n)));else{if("object"!=typeof n)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`);await Promise.all(Object.entries(n).map(([n,r])=>mu(e,`${t}[${n}]`,r)))}}},gu=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function _u(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(gu(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!uu(e)){const t=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";const t=Object.getOwnPropertyNames(e);return`; props: [${t.map(e=>`"${e}"`).join(", ")}]`}(e)}`)}for await(const n of e)t.push(...await _u(n))}return t}class yu{constructor(e){this._client=e}}function vu(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const bu=Object.freeze(Object.create(null)),wu=(e=vu)=>function(t,...n){if(1===t.length)return t[0];let r=!1;const s=[],i=t.reduce((t,i,a)=>{/[?#]/.test(i)&&(r=!0);const o=n[a];let l=(r?encodeURIComponent:e)(""+o);return a!==n.length&&(null==o||"object"==typeof o&&o.toString===Object.getPrototypeOf(Object.getPrototypeOf(o.hasOwnProperty??bu)??bu)?.toString)&&(l=o+"",s.push({start:t.length+i.length,length:l.length,error:`Value of type ${Object.prototype.toString.call(o).slice(8,-1)} is not a valid path parameter`})),t+i+(a===n.length?"":l)},""),a=i.split(/[?#]/,1)[0],o=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let l;for(;null!==(l=o.exec(a));)s.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(s.sort((e,t)=>e.start-t.start),s.length>0){let e=0;const t=s.reduce((t,n)=>{const r=" ".repeat(n.start-e),s="^".repeat(n.length);return e=n.start+n.length,t+r+s},"");throw new Fl(`Path parameters result in path with invalid segments:\n${s.map(e=>e.error).join("\n")}\n${i}\n${t}`)}return i},Eu=wu(vu);class Su extends yu{list(e,t={},n){return this._client.getAPIList(Eu`/chat/completions/${e}/messages`,au,{query:t,...n})}}function ku(e){return"function"==typeof e.parse}const xu=e=>"assistant"===e?.role,Ou=e=>"tool"===e?.role;var Tu,Iu,Au,Pu,Cu,$u,Ru,Nu,ju,Lu,Mu,Du,Uu,Fu,Bu,qu,zu,Hu,Wu,Gu,Ku;class Ju{constructor(){Tu.add(this),this.controller=new AbortController,Iu.set(this,void 0),Au.set(this,()=>{}),Pu.set(this,()=>{}),Cu.set(this,void 0),$u.set(this,()=>{}),Ru.set(this,()=>{}),Nu.set(this,{}),ju.set(this,!1),Lu.set(this,!1),Mu.set(this,!1),Du.set(this,!1),jl(this,Iu,new Promise((e,t)=>{jl(this,Au,e,"f"),jl(this,Pu,t,"f")}),"f"),jl(this,Cu,new Promise((e,t)=>{jl(this,$u,e,"f"),jl(this,Ru,t,"f")}),"f"),Ll(this,Iu,"f").catch(()=>{}),Ll(this,Cu,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},Ll(this,Tu,"m",Uu).bind(this))},0)}_connected(){this.ended||(Ll(this,Au,"f").call(this),this._emit("connect"))}get ended(){return Ll(this,ju,"f")}get errored(){return Ll(this,Lu,"f")}get aborted(){return Ll(this,Mu,"f")}abort(){this.controller.abort()}on(e,t){return(Ll(this,Nu,"f")[e]||(Ll(this,Nu,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=Ll(this,Nu,"f")[e];if(!n)return this;const r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(Ll(this,Nu,"f")[e]||(Ll(this,Nu,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{jl(this,Du,!0,"f"),"error"!==e&&this.once("error",n),this.once(e,t)})}async done(){jl(this,Du,!0,"f"),await Ll(this,Cu,"f")}_emit(e,...t){if(Ll(this,ju,"f"))return;"end"===e&&(jl(this,ju,!0,"f"),Ll(this,$u,"f").call(this));const n=Ll(this,Nu,"f")[e];if(n&&(Ll(this,Nu,"f")[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return Ll(this,Du,"f")||n?.length||Promise.reject(e),Ll(this,Pu,"f").call(this,e),Ll(this,Ru,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];Ll(this,Du,"f")||n?.length||Promise.reject(e),Ll(this,Pu,"f").call(this,e),Ll(this,Ru,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function Zu(e){return"auto-parseable-response-format"===e?.$brand}function Vu(e){return"auto-parseable-tool"===e?.$brand}function Yu(e,t){const n=e.choices.map(e=>{if("length"===e.finish_reason)throw new Ql;if("content_filter"===e.finish_reason)throw new ec;return{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>function(e,t){const n=e.tools?.find(e=>e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Vu(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?Xu(t,e.message.content):null}}});return{...e,choices:n}}function Xu(e,t){if("json_schema"!==e.response_format?.type)return null;if("json_schema"===e.response_format?.type){if("$parseRaw"in e.response_format){return e.response_format.$parseRaw(t)}return JSON.parse(t)}return null}function Qu(e,t){if(!e)return!1;const n=e.tools?.find(e=>e.function?.name===t.function.name);return Vu(n)||n?.function.strict||!1}function ed(e){return!!Zu(e.response_format)||(e.tools?.some(e=>Vu(e)||"function"===e.type&&!0===e.function.strict)??!1)}Iu=new WeakMap,Au=new WeakMap,Pu=new WeakMap,Cu=new WeakMap,$u=new WeakMap,Ru=new WeakMap,Nu=new WeakMap,ju=new WeakMap,Lu=new WeakMap,Mu=new WeakMap,Du=new WeakMap,Tu=new WeakSet,Uu=function(e){if(jl(this,Lu,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new ql),e instanceof ql)return jl(this,Mu,!0,"f"),this._emit("abort",e);if(e instanceof Fl)return this._emit("error",e);if(e instanceof Error){const t=new Fl(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Fl(String(e)))};const td=10;class nd extends Ju{constructor(){super(...arguments),Fu.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t)if(this._emit("message",e),Ou(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(xu(e)&&e.tool_calls)for(const t of e.tool_calls)"function"===t.type&&this._emit("functionToolCall",t.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new Fl("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),Ll(this,Fu,"m",Bu).call(this)}async finalMessage(){return await this.done(),Ll(this,Fu,"m",qu).call(this)}async finalFunctionToolCall(){return await this.done(),Ll(this,Fu,"m",zu).call(this)}async finalFunctionToolCallResult(){return await this.done(),Ll(this,Fu,"m",Hu).call(this)}async totalUsage(){return await this.done(),Ll(this,Fu,"m",Wu).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=Ll(this,Fu,"m",qu).call(this);t&&this._emit("finalMessage",t);const n=Ll(this,Fu,"m",Bu).call(this);n&&this._emit("finalContent",n);const r=Ll(this,Fu,"m",zu).call(this);r&&this._emit("finalFunctionToolCall",r);const s=Ll(this,Fu,"m",Hu).call(this);null!=s&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(e=>e.usage)&&this._emit("totalUsage",Ll(this,Fu,"m",Wu).call(this))}async _createChatCompletion(e,t,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),Ll(this,Fu,"m",Gu).call(this,t);const s=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Yu(s,t))}async _runChatCompletion(e,t,n){for(const e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n){const r="tool",{tool_choice:s="auto",stream:i,...a}=t,o="string"!=typeof s&&s?.function?.name,{maxChatCompletions:l=td}=n||{},c=t.tools.map(e=>{if(Vu(e)){if(!e.$callback)throw new Fl("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),u={};for(const e of c)"function"===e.type&&(u[e.function.name||e.function.function.name]=e.function);const d="tools"in t?c.map(e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(const e of t.messages)this._addMessage(e,!1);for(let t=0;tJSON.stringify(e)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:t,content:e});continue}if(o&&o!==n){const e=`Invalid tool_call: ${JSON.stringify(n)}. ${JSON.stringify(o)} requested. Please try again`;this._addMessage({role:r,tool_call_id:t,content:e});continue}let a;try{a=ku(i)?await i.parse(s):s}catch(e){const n=e instanceof Error?e.message:String(e);this._addMessage({role:r,tool_call_id:t,content:n});continue}const l=await i.function(a,this),c=Ll(this,Fu,"m",Ku).call(this,l);if(this._addMessage({role:r,tool_call_id:t,content:c}),o)return}}}}Fu=new WeakSet,Bu=function(){return Ll(this,Fu,"m",qu).call(this).content??null},qu=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(xu(t)){return{...t,content:t.content??null,refusal:t.refusal??null}}}throw new Fl("stream ended without producing a ChatCompletionMessage with role=assistant")},zu=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(xu(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},Hu=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Ou(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some(e=>"assistant"===e.role&&e.tool_calls?.some(e=>"function"===e.type&&e.id===t.tool_call_id)))return t.content}},Wu=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Gu=function(e){if(null!=e.n&&e.n>1)throw new Fl("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Ku=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class rd extends nd{static runTools(e,t,n){const r=new rd,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,s)),r}_addMessage(e,t=!0){super._addMessage(e,t),xu(e)&&e.content&&this._emit("content",e.content)}}const sd=1,id=2,ad=4,od=8,ld=16,cd=32,ud=64,dd=128,hd=256,pd=511;class fd extends Error{}class md extends Error{}const gd=(e,t)=>{const n=e.length;let r=0;const s=e=>{throw new fd(`${e} at position ${r}`)},i=e=>{throw new md(`${e} at position ${r}`)},a=()=>(d(),r>=n&&s("Unexpected end of input"),'"'===e[r]?o():"{"===e[r]?l():"["===e[r]?c():"null"===e.substring(r,r+4)||ld&t&&n-r<4&&"null".startsWith(e.substring(r))?(r+=4,null):"true"===e.substring(r,r+4)||cd&t&&n-r<4&&"true".startsWith(e.substring(r))?(r+=4,!0):"false"===e.substring(r,r+5)||cd&t&&n-r<5&&"false".startsWith(e.substring(r))?(r+=5,!1):"Infinity"===e.substring(r,r+8)||dd&t&&n-r<8&&"Infinity".startsWith(e.substring(r))?(r+=8,1/0):"-Infinity"===e.substring(r,r+9)||hd&t&&1{const a=r;let o=!1;for(r++;r{r++,d();const i={};try{for(;"}"!==e[r];){if(d(),r>=n&&od&t)return i;const s=o();d(),r++;try{const e=a();Object.defineProperty(i,s,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(od&t)return i;throw e}d(),","===e[r]&&r++}}catch(e){if(od&t)return i;s("Expected '}' at end of object")}return r++,i},c=()=>{r++;const n=[];try{for(;"]"!==e[r];)n.push(a()),d(),","===e[r]&&r++}catch(e){if(ad&t)return n;s("Expected ']' at end of array")}return r++,n},u=()=>{if(0===r){"-"===e&&id&t&&s("Not sure what '-' is");try{return JSON.parse(e)}catch(n){if(id&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(e){}i(String(n))}}const a=r;for("-"===e[r]&&r++;e[r]&&!",]}".includes(e[r]);)r++;r!=n||id&t||s("Unterminated number literal");try{return JSON.parse(e.substring(a,r))}catch(n){"-"===e.substring(a,r)&&id&t&&s("Not sure what '-' is");try{return JSON.parse(e.substring(a,e.lastIndexOf("e")))}catch(e){i(String(e))}}},d=()=>{for(;rfunction(e,t=pd){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return gd(e.trim(),t)}(e,pd^id);var yd,vd,bd,wd,Ed,Sd,kd,xd,Od,Td,Id,Ad;class Pd extends nd{constructor(e){super(),yd.add(this),vd.set(this,void 0),bd.set(this,void 0),wd.set(this,void 0),jl(this,vd,e,"f"),jl(this,bd,[],"f")}get currentChatCompletionSnapshot(){return Ll(this,wd,"f")}static fromReadableStream(e){const t=new Pd(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const r=new Pd(t);return r._run(()=>r._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(e,t,n){super._createChatCompletion;const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),Ll(this,yd,"m",Ed).call(this);const s=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const e of s)Ll(this,yd,"m",kd).call(this,e);if(s.controller.signal?.aborted)throw new ql;return this._addChatCompletion(Ll(this,yd,"m",Td).call(this))}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Ll(this,yd,"m",Ed).call(this),this._connected();const r=Xc.fromReadableStream(e,this.controller);let s;for await(const e of r)s&&s!==e.id&&this._addChatCompletion(Ll(this,yd,"m",Td).call(this)),Ll(this,yd,"m",kd).call(this,e),s=e.id;if(r.controller.signal?.aborted)throw new ql;return this._addChatCompletion(Ll(this,yd,"m",Td).call(this))}[(vd=new WeakMap,bd=new WeakMap,wd=new WeakMap,yd=new WeakSet,Ed=function(){this.ended||jl(this,wd,void 0,"f")},Sd=function(e){let t=Ll(this,bd,"f")[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},Ll(this,bd,"f")[e.index]=t,t)},kd=function(e){if(this.ended)return;const t=Ll(this,yd,"m",Ad).call(this,e);this._emit("chunk",e,t);for(const n of e.choices){const e=t.choices[n.index];null!=n.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",n.delta.content,e.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=n.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:e.message.refusal}),null!=n.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=n.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const r=Ll(this,yd,"m",Sd).call(this,e);e.finish_reason&&(Ll(this,yd,"m",Od).call(this,e),null!=r.current_tool_call_index&&Ll(this,yd,"m",xd).call(this,e,r.current_tool_call_index));for(const t of n.delta.tool_calls??[])r.current_tool_call_index!==t.index&&(Ll(this,yd,"m",Od).call(this,e),null!=r.current_tool_call_index&&Ll(this,yd,"m",xd).call(this,e,r.current_tool_call_index)),r.current_tool_call_index=t.index;for(const t of n.delta.tool_calls??[]){const n=e.message.tool_calls?.[t.index];n?.type&&("function"===n?.type?this._emit("tool_calls.function.arguments.delta",{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??""}):Rd(n?.type))}}},xd=function(e,t){if(Ll(this,yd,"m",Sd).call(this,e).done_tool_calls.has(t))return;const n=e.message.tool_calls?.[t];if(!n)throw new Error("no tool call snapshot");if(!n.type)throw new Error("tool call snapshot missing `type`");if("function"===n.type){const e=Ll(this,vd,"f")?.tools?.find(e=>"function"===e.type&&e.function.name===n.function.name);this._emit("tool_calls.function.arguments.done",{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:Vu(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},Od=function(e){const t=Ll(this,yd,"m",Sd).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const n=Ll(this,yd,"m",Id).call(this);this._emit("content.done",{content:e.message.content,parsed:n?n.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},Td=function(){if(this.ended)throw new Fl("stream has ended, this shouldn't happen");const e=Ll(this,wd,"f");if(!e)throw new Fl("request ended without sending any chunks");return jl(this,wd,void 0,"f"),jl(this,bd,[],"f"),function(e,t){const{id:n,choices:r,created:s,model:i,system_fingerprint:a,...o}=e,l={...o,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:s,...i})=>{if(!n)throw new Fl(`missing finish_reason for choice ${r}`);const{content:a=null,function_call:o,tool_calls:l,...c}=t,u=t.role;if(!u)throw new Fl(`missing role for choice ${r}`);if(o){const{arguments:e,name:l}=o;if(null==e)throw new Fl(`missing function_call.arguments for choice ${r}`);if(!l)throw new Fl(`missing function_call.name for choice ${r}`);return{...i,message:{content:a,function_call:{arguments:e,name:l},role:u,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:s}}return l?{...i,index:r,finish_reason:n,logprobs:s,message:{...c,role:u,content:a,refusal:t.refusal??null,tool_calls:l.map((t,n)=>{const{function:s,type:i,id:a,...o}=t,{arguments:l,name:c,...u}=s||{};if(null==a)throw new Fl(`missing choices[${r}].tool_calls[${n}].id\n${Cd(e)}`);if(null==i)throw new Fl(`missing choices[${r}].tool_calls[${n}].type\n${Cd(e)}`);if(null==c)throw new Fl(`missing choices[${r}].tool_calls[${n}].function.name\n${Cd(e)}`);if(null==l)throw new Fl(`missing choices[${r}].tool_calls[${n}].function.arguments\n${Cd(e)}`);return{...o,id:a,type:i,function:{...u,name:c,arguments:l}}})}}:{...i,message:{...c,content:a,role:u,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:s}}),created:s,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return function(e,t){return t&&ed(t)?Yu(e,t):{...e,choices:e.choices.map(e=>({...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}}(l,t)}(e,Ll(this,vd,"f"))},Id=function(){const e=Ll(this,vd,"f")?.response_format;return Zu(e)?e:null},Ad=function(e){var t,n,r,s;let i=Ll(this,wd,"f");const{choices:a,...o}=e;i?Object.assign(i,o):i=jl(this,wd,{...o,choices:[]},"f");for(const{delta:a,finish_reason:o,index:l,logprobs:c=null,...u}of e.choices){let e=i.choices[l];if(e||(e=i.choices[l]={finish_reason:o,index:l,message:{},logprobs:c,...u}),c)if(e.logprobs){const{content:r,refusal:s,...i}=c;$d(i),Object.assign(e.logprobs,i),r&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...r)),s&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...s))}else e.logprobs=Object.assign({},c);if(o&&(e.finish_reason=o,Ll(this,vd,"f")&&ed(Ll(this,vd,"f")))){if("length"===o)throw new Ql;if("content_filter"===o)throw new ec}if(Object.assign(e,u),!a)continue;const{content:d,refusal:h,function_call:p,role:f,tool_calls:m,...g}=a;if($d(g),Object.assign(e.message,g),h&&(e.message.refusal=(e.message.refusal||"")+h),f&&(e.message.role=f),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((r=e.message.function_call).arguments??(r.arguments=""),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),d&&(e.message.content=(e.message.content||"")+d,!e.message.refusal&&Ll(this,yd,"m",Id).call(this)&&(e.message.parsed=_d(e.message.content))),m){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:n,type:r,function:i,...a}of m){const o=(s=e.message.tool_calls)[t]??(s[t]={});Object.assign(o,a),n&&(o.id=n),r&&(o.type=r),i&&(o.function??(o.function={name:i.name??"",arguments:""})),i?.name&&(o.function.name=i.name),i?.arguments&&(o.function.arguments+=i.arguments,Qu(Ll(this,vd,"f"),o)&&(o.function.parsed_arguments=_d(o.function.arguments)))}}}return i},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",n=>{const r=t.shift();r?r.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Xc(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Cd(e){return JSON.stringify(e)}function $d(e){}function Rd(e){}class Nd extends Pd{static fromReadableStream(e){const t=new Nd(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,n){const r=new Nd(t),s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,s)),r}}class jd extends yu{constructor(){super(...arguments),this.messages=new Su(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(Eu`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(Eu`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/chat/completions",au,{query:e,...t})}delete(e,t){return this._client.delete(Eu`/chat/completions/${e}`,t)}parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new Fl(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new Fl(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(t=>Yu(t,e))}runTools(e,t){return e.stream?Nd.runTools(this._client,e,t):rd.runTools(this._client,e,t)}stream(e,t){return Pd.createChatCompletion(this._client,e,t)}}jd.Messages=Su;class Ld extends yu{constructor(){super(...arguments),this.completions=new jd(this._client)}}Ld.Completions=jd;const Md=Symbol("brand.privateNullableHeaders");function*Dd(e){if(!e)return;if(Md in e){const{values:t,nulls:n}=e;yield*t.entries();for(const e of n)yield[e,null];return}let t,n=!1;e instanceof Headers?t=e.entries():sc(e)?t=e:(n=!0,t=Object.entries(e??{}));for(let e of t){const t=e[0];if("string"!=typeof t)throw new TypeError("expected header name to be a string");const r=sc(e[1])?e[1]:[e[1]];let s=!1;for(const e of r)void 0!==e&&(n&&!s&&(s=!0,yield[t,null]),yield[t,e])}}const Ud=e=>{const t=new Headers,n=new Set;for(const r of e){const e=new Set;for(const[s,i]of Dd(r)){const r=s.toLowerCase();e.has(r)||(t.delete(s),e.add(r)),null===i?(t.delete(s),n.add(r)):(t.append(s,i),n.delete(r))}}return{[Md]:!0,values:t,nulls:n}};class Fd extends yu{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:Ud([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class Bd extends yu{create(e,t){return this._client.post("/audio/transcriptions",du({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class qd extends yu{create(e,t){return this._client.post("/audio/translations",du({body:e,...t,__metadata:{model:e.model}},this._client))}}class zd extends yu{constructor(){super(...arguments),this.transcriptions=new Bd(this._client),this.translations=new qd(this._client),this.speech=new Fd(this._client)}}zd.Transcriptions=Bd,zd.Translations=qd,zd.Speech=Fd;class Hd extends yu{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(Eu`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",au,{query:e,...t})}cancel(e,t){return this._client.post(Eu`/batches/${e}/cancel`,t)}}class Wd extends yu{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:Ud([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(Eu`/assistants/${e}`,{...t,headers:Ud([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(Eu`/assistants/${e}`,{body:t,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",au,{query:e,...t,headers:Ud([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(Eu`/assistants/${e}`,{...t,headers:Ud([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Gd extends yu{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:Ud([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Kd extends yu{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:Ud([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Jd extends yu{constructor(){super(...arguments),this.sessions=new Gd(this._client),this.transcriptionSessions=new Kd(this._client)}}Jd.Sessions=Gd,Jd.TranscriptionSessions=Kd;class Zd extends yu{create(e,t,n){return this._client.post(Eu`/threads/${e}/messages`,{body:t,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){const{thread_id:r}=t;return this._client.get(Eu`/threads/${r}/messages/${e}`,{...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){const{thread_id:r,...s}=t;return this._client.post(Eu`/threads/${r}/messages/${e}`,{body:s,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(Eu`/threads/${e}/messages`,au,{query:t,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){const{thread_id:r}=t;return this._client.delete(Eu`/threads/${r}/messages/${e}`,{...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}class Vd extends yu{retrieve(e,t,n){const{thread_id:r,run_id:s,...i}=t;return this._client.get(Eu`/threads/${r}/runs/${s}/steps/${e}`,{query:i,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t,n){const{thread_id:r,...s}=t;return this._client.getAPIList(Eu`/threads/${r}/runs/${e}/steps`,au,{query:s,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}const Yd=e=>void 0!==globalThis.process?globalThis.process.env?.[e]?.trim()??void 0:void 0!==globalThis.Deno?globalThis.Deno.env?.get?.(e)?.trim():void 0;var Xd,Qd,eh,th,nh,rh,sh,ih,ah,oh,lh,ch,uh,dh,hh,ph,fh,mh,gh,_h,yh,vh,bh,wh,Eh,Sh,kh,xh,Oh,Th,Ih;class Ah extends Ju{constructor(){super(...arguments),Xd.add(this),eh.set(this,[]),th.set(this,{}),nh.set(this,{}),rh.set(this,void 0),sh.set(this,void 0),ih.set(this,void 0),ah.set(this,void 0),oh.set(this,void 0),lh.set(this,void 0),ch.set(this,void 0),uh.set(this,void 0),dh.set(this,void 0)}[(eh=new WeakMap,th=new WeakMap,nh=new WeakMap,rh=new WeakMap,sh=new WeakMap,ih=new WeakMap,ah=new WeakMap,oh=new WeakMap,lh=new WeakMap,ch=new WeakMap,uh=new WeakMap,dh=new WeakMap,Xd=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",n=>{const r=t.shift();r?r.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new Qd;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const r=Xc.fromReadableStream(e,this.controller);for await(const e of r)Ll(this,Xd,"m",hh).call(this,e);if(r.controller.signal?.aborted)throw new ql;return this._addRun(Ll(this,Xd,"m",ph).call(this))}toReadableStream(){return new Xc(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){const s=new Qd;return s._run(()=>s._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,t,n,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},a=await e.submitToolOutputs(t,i,{...r,signal:this.controller.signal});this._connected();for await(const e of a)Ll(this,Xd,"m",hh).call(this,e);if(a.controller.signal?.aborted)throw new ql;return this._addRun(Ll(this,Xd,"m",ph).call(this))}static createThreadAssistantStream(e,t,n){const r=new Qd;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,t,n,r){const s=new Qd;return s._run(()=>s._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return Ll(this,ch,"f")}currentRun(){return Ll(this,uh,"f")}currentMessageSnapshot(){return Ll(this,rh,"f")}currentRunStepSnapshot(){return Ll(this,dh,"f")}async finalRunSteps(){return await this.done(),Object.values(Ll(this,th,"f"))}async finalMessages(){return await this.done(),Object.values(Ll(this,nh,"f"))}async finalRun(){if(await this.done(),!Ll(this,sh,"f"))throw Error("Final run was not received.");return Ll(this,sh,"f")}async _createThreadAssistantStream(e,t,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const s={...t,stream:!0},i=await e.createAndRun(s,{...n,signal:this.controller.signal});this._connected();for await(const e of i)Ll(this,Xd,"m",hh).call(this,e);if(i.controller.signal?.aborted)throw new ql;return this._addRun(Ll(this,Xd,"m",ph).call(this))}async _createAssistantStream(e,t,n,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},a=await e.create(t,i,{...r,signal:this.controller.signal});this._connected();for await(const e of a)Ll(this,Xd,"m",hh).call(this,e);if(a.controller.signal?.aborted)throw new ql;return this._addRun(Ll(this,Xd,"m",ph).call(this))}static accumulateDelta(e,t){for(const[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(null!=t)if("index"!==n&&"type"!==n){if("string"==typeof t&&"string"==typeof r)t+=r;else if("number"==typeof t&&"number"==typeof r)t+=r;else{if(!ac(t)||!ac(r)){if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>"string"==typeof e||"number"==typeof e)){t.push(...r);continue}for(const e of r){if(!ac(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const n=e.index;if(null==n)throw new Error("Expected array delta entry to have an `index` property");if("number"!=typeof n)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);const r=t[n];null==r?t.push(e):t[n]=this.accumulateDelta(r,e)}continue}throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`)}t=this.accumulateDelta(t,r)}e[n]=t}else e[n]=r;else e[n]=r}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}}Qd=Ah,hh=function(e){if(!this.ended)switch(jl(this,ch,e,"f"),Ll(this,Xd,"m",gh).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":Ll(this,Xd,"m",bh).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Ll(this,Xd,"m",mh).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":Ll(this,Xd,"m",fh).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},ph=function(){if(this.ended)throw new Fl("stream has ended, this shouldn't happen");if(!Ll(this,sh,"f"))throw Error("Final run has not been received");return Ll(this,sh,"f")},fh=function(e){const[t,n]=Ll(this,Xd,"m",yh).call(this,e,Ll(this,rh,"f"));jl(this,rh,t,"f"),Ll(this,nh,"f")[t.id]=t;for(const e of n){const n=t.content[e.index];"text"==n?.type&&this._emit("textCreated",n.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const n of e.data.delta.content){if("text"==n.type&&n.text){let e=n.text,r=t.content[n.index];if(!r||"text"!=r.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,r.text)}if(n.index!=Ll(this,ih,"f")){if(Ll(this,ah,"f"))switch(Ll(this,ah,"f").type){case"text":this._emit("textDone",Ll(this,ah,"f").text,Ll(this,rh,"f"));break;case"image_file":this._emit("imageFileDone",Ll(this,ah,"f").image_file,Ll(this,rh,"f"))}jl(this,ih,n.index,"f")}jl(this,ah,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==Ll(this,ih,"f")){const t=e.data.content[Ll(this,ih,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,Ll(this,rh,"f"));break;case"text":this._emit("textDone",t.text,Ll(this,rh,"f"))}}Ll(this,rh,"f")&&this._emit("messageDone",e.data),jl(this,rh,void 0,"f")}},mh=function(e){const t=Ll(this,Xd,"m",_h).call(this,e);switch(jl(this,dh,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const n=e.data.delta;if(n.step_details&&"tool_calls"==n.step_details.type&&n.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of n.step_details.tool_calls)e.index==Ll(this,oh,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(Ll(this,lh,"f")&&this._emit("toolCallDone",Ll(this,lh,"f")),jl(this,oh,e.index,"f"),jl(this,lh,t.step_details.tool_calls[e.index],"f"),Ll(this,lh,"f")&&this._emit("toolCallCreated",Ll(this,lh,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":jl(this,dh,void 0,"f");"tool_calls"==e.data.step_details.type&&Ll(this,lh,"f")&&(this._emit("toolCallDone",Ll(this,lh,"f")),jl(this,lh,void 0,"f")),this._emit("runStepDone",e.data,t)}},gh=function(e){Ll(this,eh,"f").push(e),this._emit("event",e)},_h=function(e){switch(e.event){case"thread.run.step.created":return Ll(this,th,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=Ll(this,th,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){const r=Qd.accumulateDelta(t,n.delta);Ll(this,th,"f")[e.data.id]=r}return Ll(this,th,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":Ll(this,th,"f")[e.data.id]=e.data}if(Ll(this,th,"f")[e.data.id])return Ll(this,th,"f")[e.data.id];throw new Error("No snapshot available")},yh=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let r=e.data;if(r.delta.content)for(const e of r.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=Ll(this,Xd,"m",vh).call(this,e,n)}else t.content[e.index]=e,n.push(e);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},vh=function(e,t){return Qd.accumulateDelta(t,e)},bh=function(e){switch(jl(this,uh,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.cancelling":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":jl(this,sh,e.data,"f"),Ll(this,lh,"f")&&(this._emit("toolCallDone",Ll(this,lh,"f")),jl(this,lh,void 0,"f"))}};class Ph extends yu{constructor(){super(...arguments),this.steps=new Vd(this._client)}create(e,t,n){const{include:r,...s}=t;return this._client.post(Eu`/threads/${e}/runs`,{query:{include:r},body:s,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}retrieve(e,t,n){const{thread_id:r}=t;return this._client.get(Eu`/threads/${r}/runs/${e}`,{...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){const{thread_id:r,...s}=t;return this._client.post(Eu`/threads/${r}/runs/${e}`,{body:s,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(Eu`/threads/${e}/runs`,au,{query:t,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){const{thread_id:r}=t;return this._client.post(Eu`/threads/${r}/runs/${e}/cancel`,{...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){const r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return Ah.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){const r=Ud([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:s,response:i}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=i.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await oc(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,t,n){return Ah.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){const{thread_id:r,...s}=t;return this._client.post(Eu`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:s,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,n){const r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return Ah.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}}Ph.Steps=Vd;class Ch extends yu{constructor(){super(...arguments),this.runs=new Ph(this._client),this.messages=new Zd(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:Ud([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(Eu`/threads/${e}`,{...t,headers:Ud([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(Eu`/threads/${e}`,{body:t,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t){return this._client.delete(Eu`/threads/${e}`,{...t,headers:Ud([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:Ud([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return Ah.createThreadAssistantStream(e,this._client.beta.threads,t)}}Ch.Runs=Ph,Ch.Messages=Zd;class $h extends yu{constructor(){super(...arguments),this.realtime=new Jd(this._client),this.assistants=new Wd(this._client),this.threads=new Ch(this._client)}}$h.Realtime=Jd,$h.Assistants=Wd,$h.Threads=Ch;class Rh extends yu{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Nh extends yu{retrieve(e,t,n){const{container_id:r}=t;return this._client.get(Eu`/containers/${r}/files/${e}/content`,{...n,headers:Ud([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}}class jh extends yu{constructor(){super(...arguments),this.content=new Nh(this._client)}create(e,t,n){return this._client.post(Eu`/containers/${e}/files`,du({body:t,...n},this._client))}retrieve(e,t,n){const{container_id:r}=t;return this._client.get(Eu`/containers/${r}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(Eu`/containers/${e}/files`,au,{query:t,...n})}delete(e,t,n){const{container_id:r}=t;return this._client.delete(Eu`/containers/${r}/files/${e}`,{...n,headers:Ud([{Accept:"*/*"},n?.headers])})}}jh.Content=Nh;class Lh extends yu{constructor(){super(...arguments),this.files=new jh(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(Eu`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",au,{query:e,...t})}delete(e,t){return this._client.delete(Eu`/containers/${e}`,{...t,headers:Ud([{Accept:"*/*"},t?.headers])})}}Lh.Files=jh;class Mh extends yu{create(e,t){const n=!!e.encoding_format;let r=n?e.encoding_format:"base64";n&&Kc(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const s=this._client.post("/embeddings",{body:{...e,encoding_format:r},...t});return n?s:(Kc(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{const t=e.embedding;e.embedding=(e=>{if("undefined"!=typeof Buffer){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{const t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;en)throw new Hl({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}}class qh extends yu{}class zh extends yu{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}}class Hh extends yu{constructor(){super(...arguments),this.graders=new zh(this._client)}}Hh.Graders=zh;class Wh extends yu{create(e,t,n){return this._client.getAPIList(Eu`/fine_tuning/checkpoints/${e}/permissions`,iu,{body:t,method:"post",...n})}retrieve(e,t={},n){return this._client.get(Eu`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}delete(e,t,n){const{fine_tuned_model_checkpoint:r}=t;return this._client.delete(Eu`/fine_tuning/checkpoints/${r}/permissions/${e}`,n)}}class Gh extends yu{constructor(){super(...arguments),this.permissions=new Wh(this._client)}}Gh.Permissions=Wh;class Kh extends yu{list(e,t={},n){return this._client.getAPIList(Eu`/fine_tuning/jobs/${e}/checkpoints`,au,{query:t,...n})}}class Jh extends yu{constructor(){super(...arguments),this.checkpoints=new Kh(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(Eu`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",au,{query:e,...t})}cancel(e,t){return this._client.post(Eu`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(Eu`/fine_tuning/jobs/${e}/events`,au,{query:t,...n})}pause(e,t){return this._client.post(Eu`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(Eu`/fine_tuning/jobs/${e}/resume`,t)}}Jh.Checkpoints=Kh;class Zh extends yu{constructor(){super(...arguments),this.methods=new qh(this._client),this.jobs=new Jh(this._client),this.checkpoints=new Gh(this._client),this.alpha=new Hh(this._client)}}Zh.Methods=qh,Zh.Jobs=Jh,Zh.Checkpoints=Gh,Zh.Alpha=Hh;class Vh extends yu{}class Yh extends yu{constructor(){super(...arguments),this.graderModels=new Vh(this._client)}}Yh.GraderModels=Vh;class Xh extends yu{createVariation(e,t){return this._client.post("/images/variations",du({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",du({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class Qh extends yu{retrieve(e,t){return this._client.get(Eu`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",iu,e)}delete(e,t){return this._client.delete(Eu`/models/${e}`,t)}}class ep extends yu{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function tp(e,t){return t&&function(e){if(Zu(e.text?.format))return!0;return!1}(t)?np(e,t):{...e,output_parsed:null,output:e.output.map(e=>"function_call"===e.type?{...e,parsed_arguments:null}:"message"===e.type?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}}function np(e,t){const n=e.output.map(e=>{if("function_call"===e.type)return{...e,parsed_arguments:ap(t,e)};if("message"===e.type){const n=e.content.map(e=>"output_text"===e.type?{...e,parsed:rp(t,e.text)}:e);return{...e,content:n}}return e}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,"output_text")||op(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(const e of r.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),r}function rp(e,t){if("json_schema"!==e.text?.format?.type)return null;if("$parseRaw"in e.text?.format){const n=e.text?.format;return n.$parseRaw(t)}return JSON.parse(t)}function sp(e){return"auto-parseable-tool"===e?.$brand}function ip(e,t){return e.find(e=>"function"===e.type&&e.name===t)}function ap(e,t){const n=ip(e.tools??[],t.name);return{...t,...t,parsed_arguments:sp(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function op(e){const t=[];for(const n of e.output)if("message"===n.type)for(const e of n.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}class lp extends Ju{constructor(e){super(),wh.add(this),Eh.set(this,void 0),Sh.set(this,void 0),kh.set(this,void 0),jl(this,Eh,e,"f")}static createResponse(e,t,n){const r=new lp(t);return r._run(()=>r._createOrRetrieveResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createOrRetrieveResponse(e,t,n){const r=n?.signal;let s;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),Ll(this,wh,"m",xh).call(this);let i=null;"response_id"in t?(s=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):s=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const e of s)Ll(this,wh,"m",Oh).call(this,e,i);if(s.controller.signal?.aborted)throw new ql;return Ll(this,wh,"m",Th).call(this)}[(Eh=new WeakMap,Sh=new WeakMap,kh=new WeakMap,wh=new WeakSet,xh=function(){this.ended||jl(this,Sh,void 0,"f")},Oh=function(e,t){if(this.ended)return;const n=(e,n)=>{(null==t||n.sequence_number>t)&&this._emit(e,n)},r=Ll(this,wh,"m",Ih).call(this,e);switch(n("event",e),e.type){case"response.output_text.delta":{const t=r.output[e.output_index];if(!t)throw new Fl(`missing output at index ${e.output_index}`);if("message"===t.type){const r=t.content[e.content_index];if(!r)throw new Fl(`missing content at index ${e.content_index}`);if("output_text"!==r.type)throw new Fl(`expected content to be 'output_text', got ${r.type}`);n("response.output_text.delta",{...e,snapshot:r.text})}break}case"response.function_call_arguments.delta":{const t=r.output[e.output_index];if(!t)throw new Fl(`missing output at index ${e.output_index}`);"function_call"===t.type&&n("response.function_call_arguments.delta",{...e,snapshot:t.arguments});break}default:n(e.type,e)}},Th=function(){if(this.ended)throw new Fl("stream has ended, this shouldn't happen");const e=Ll(this,Sh,"f");if(!e)throw new Fl("request ended without sending any events");jl(this,Sh,void 0,"f");const t=function(e,t){return tp(e,t)}(e,Ll(this,Eh,"f"));return jl(this,kh,t,"f"),t},Ih=function(e){let t=Ll(this,Sh,"f");if(!t){if("response.created"!==e.type)throw new Fl(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=jl(this,Sh,e.response,"f"),t}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{const n=t.output[e.output_index];if(!n)throw new Fl(`missing output at index ${e.output_index}`);"message"===n.type&&n.content.push(e.part);break}case"response.output_text.delta":{const n=t.output[e.output_index];if(!n)throw new Fl(`missing output at index ${e.output_index}`);if("message"===n.type){const t=n.content[e.content_index];if(!t)throw new Fl(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new Fl(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{const n=t.output[e.output_index];if(!n)throw new Fl(`missing output at index ${e.output_index}`);"function_call"===n.type&&(n.arguments+=e.delta);break}case"response.completed":jl(this,Sh,e.response,"f")}return t},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",n=>{const r=t.shift();r?r.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=Ll(this,kh,"f");if(!e)throw new Fl("stream ended without producing a ChatCompletion");return e}}class cp extends yu{list(e,t={},n){return this._client.getAPIList(Eu`/responses/${e}/input_items`,au,{query:t,...n})}}class up extends yu{constructor(){super(...arguments),this.inputItems=new cp(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&op(e),e))}retrieve(e,t={},n){return this._client.get(Eu`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&op(e),e))}delete(e,t){return this._client.delete(Eu`/responses/${e}`,{...t,headers:Ud([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>np(t,e))}stream(e,t){return lp.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(Eu`/responses/${e}/cancel`,t)}}up.InputItems=cp;class dp extends yu{create(e,t,n){return this._client.post(Eu`/uploads/${e}/parts`,du({body:t,...n},this._client))}}class hp extends yu{constructor(){super(...arguments),this.parts=new dp(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(Eu`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(Eu`/uploads/${e}/complete`,{body:t,...n})}}hp.Parts=dp;class pp extends yu{create(e,t,n){return this._client.post(Eu`/vector_stores/${e}/file_batches`,{body:t,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){const{vector_store_id:r}=t;return this._client.get(Eu`/vector_stores/${r}/file_batches/${e}`,{...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){const{vector_store_id:r}=t;return this._client.post(Eu`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){const r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){const{vector_store_id:r,...s}=t;return this._client.getAPIList(Eu`/vector_stores/${r}/file_batches/${e}/files`,au,{query:s,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async poll(e,t,n){const r=Ud([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:s,response:i}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(s.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=i.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await oc(e);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(null==t||0==t.length)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const s=r?.maxConcurrency??5,i=Math.min(s,t.length),a=this._client,o=t.values(),l=[...n];const c=Array(i).fill(o).map(async function(e){for(let t of e){const e=await a.files.create({file:t,purpose:"assistants"},r);l.push(e.id)}});return await(async e=>{const t=await Promise.allSettled(e),n=t.filter(e=>"rejected"===e.status);if(n.length){for(const e of n);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const r=[];for(const e of t)"fulfilled"===e.status&&r.push(e.value);return r})(c),await this.createAndPoll(e,{file_ids:l})}}class fp extends yu{create(e,t,n){return this._client.post(Eu`/vector_stores/${e}/files`,{body:t,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){const{vector_store_id:r}=t;return this._client.get(Eu`/vector_stores/${r}/files/${e}`,{...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){const{vector_store_id:r,...s}=t;return this._client.post(Eu`/vector_stores/${r}/files/${e}`,{body:s,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(Eu`/vector_stores/${e}/files`,au,{query:t,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){const{vector_store_id:r}=t;return this._client.delete(Eu`/vector_stores/${r}/files/${e}`,{...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){const r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){const r=Ud([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){const s=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),i=s.data;switch(i.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=s.response.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await oc(e);break;case"failed":case"completed":return i}}}async upload(e,t,n){const r=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){const r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){const{vector_store_id:r}=t;return this._client.getAPIList(Eu`/vector_stores/${r}/files/${e}/content`,iu,{...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}class mp extends yu{constructor(){super(...arguments),this.files=new fp(this._client),this.fileBatches=new pp(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:Ud([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(Eu`/vector_stores/${e}`,{...t,headers:Ud([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(Eu`/vector_stores/${e}`,{body:t,...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",au,{query:e,...t,headers:Ud([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(Eu`/vector_stores/${e}`,{...t,headers:Ud([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,n){return this._client.getAPIList(Eu`/vector_stores/${e}/search`,iu,{body:t,method:"post",...n,headers:Ud([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}var gp,_p,yp,vp,bp,wp,Ep;mp.Files=fp,mp.FileBatches=pp;class Sp extends yu{constructor(){super(...arguments),gp.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,r=300){if("undefined"==typeof crypto||"function"!=typeof crypto.subtle.importKey||"function"!=typeof crypto.subtle.verify)throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");Ll(this,gp,"m",_p).call(this,n);const s=Ud([t]).values,i=Ll(this,gp,"m",yp).call(this,s,"webhook-signature"),a=Ll(this,gp,"m",yp).call(this,s,"webhook-timestamp"),o=Ll(this,gp,"m",yp).call(this,s,"webhook-id"),l=parseInt(a,10);if(isNaN(l))throw new tc("Invalid webhook timestamp format");const c=Math.floor(Date.now()/1e3);if(c-l>r)throw new tc("Webhook timestamp is too old");if(l>c+r)throw new tc("Webhook timestamp is too new");const u=i.split(" ").map(e=>e.startsWith("v1,")?e.substring(3):e),d=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),h=o?`${o}.${a}.${e}`:`${a}.${e}`,p=await crypto.subtle.importKey("raw",d,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const e of u)try{const t=Buffer.from(e,"base64");if(await crypto.subtle.verify("HMAC",p,t,(new TextEncoder).encode(h)))return}catch{continue}throw new tc("The given webhook signature does not match the expected signature")}}gp=new WeakSet,_p=function(e){if("string"!=typeof e||0===e.length)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},yp=function(e,t){if(!e)throw new Error("Headers are required");const n=e.get(t);if(null==n)throw new Error(`Missing required header: ${t}`);return n};class kp{constructor({baseURL:e=Yd("OPENAI_BASE_URL"),apiKey:t=Yd("OPENAI_API_KEY"),organization:n=Yd("OPENAI_ORG_ID")??null,project:r=Yd("OPENAI_PROJECT_ID")??null,webhookSecret:s=Yd("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(vp.add(this),wp.set(this,void 0),this.completions=new Rh(this),this.chat=new Ld(this),this.embeddings=new Mh(this),this.files=new Bh(this),this.images=new Xh(this),this.audio=new zd(this),this.moderations=new ep(this),this.models=new Qh(this),this.fineTuning=new Zh(this),this.graders=new Yh(this),this.vectorStores=new mp(this),this.webhooks=new Sp(this),this.beta=new $h(this),this.batches=new Hd(this),this.uploads=new hp(this),this.responses=new up(this),this.evals=new Fh(this),this.containers=new Lh(this),void 0===t)throw new Fl("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const a={apiKey:t,organization:n,project:r,webhookSecret:s,...i,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new Fl("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");this.baseURL=a.baseURL,this.timeout=a.timeout??bp.DEFAULT_TIMEOUT,this.logger=a.logger??console;const o="warn";this.logLevel=o,this.logLevel=qc(a.logLevel,"ClientOptions.logLevel",this)??qc(Yd("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??o,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??function(){if("undefined"!=typeof fetch)return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),jl(this,wp,gc,"f"),this._options=a,this.apiKey=t,this.organization=n,this.project=r,this.webhookSecret=s}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return Ud([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Cc(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${lc}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ml()}`}makeStatusError(e,t,n,r){return Bl.generate(e,t,n,r)}buildURL(e,t,n){const r=!Ll(this,vp,"m",Ep).call(this)&&n||this.baseURL,s=(e=>nc.test(e))(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return function(e){if(!e)return!0;for(const t in e)return!1;return!0}(i)||(t={...i,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(s.search=this.stringifyQuery(t)),s.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new nu(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){const r=await e,s=r.maxRetries??this.maxRetries;null==t&&(t=s),await this.prepareOptions(r);const{req:i,url:a,timeout:o}=await this.buildRequest(r,{retryCount:s-t});await this.prepareRequest(i,{url:a,options:r});const l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=void 0===n?"":`, retryOf: ${n}`,u=Date.now();if(Kc(this).debug(`[${l}] sending request`,Jc({retryOfRequestLogID:n,method:r.method,url:a,options:r,headers:i.headers})),r.signal?.aborted)throw new ql;const d=new AbortController,h=await this.fetchWithTimeout(a,i,o,d).catch(Ul),p=Date.now();if(h instanceof Error){const e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new ql;const s=Dl(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return Kc(this).info(`[${l}] connection ${s?"timed out":"failed"} - ${e}`),Kc(this).debug(`[${l}] connection ${s?"timed out":"failed"} (${e})`,Jc({retryOfRequestLogID:n,url:a,durationMs:p-u,message:h.message})),this.retryRequest(r,t,n??l);if(Kc(this).info(`[${l}] connection ${s?"timed out":"failed"} - error; no more retries left`),Kc(this).debug(`[${l}] connection ${s?"timed out":"failed"} (error; no more retries left)`,Jc({retryOfRequestLogID:n,url:a,durationMs:p-u,message:h.message})),s)throw new Hl;throw new zl({cause:h})}const f=`[${l}${c}${[...h.headers.entries()].filter(([e])=>"x-request-id"===e).map(([e,t])=>", "+e+": "+JSON.stringify(t)).join("")}] ${i.method} ${a} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${p-u}ms`;if(!h.ok){const e=await this.shouldRetry(h);if(t&&e){const e=`retrying, ${t} attempts remaining`;return await async function(e){if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await(e[Symbol.asyncIterator]().return?.());const t=e.getReader(),n=t.cancel();t.releaseLock(),await n}(h.body),Kc(this).info(`${f} - ${e}`),Kc(this).debug(`[${l}] response error (${e})`,Jc({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),this.retryRequest(r,t,n??l,h.headers)}const s=e?"error; no more retries left":"error; not retryable";Kc(this).info(`${f} - ${s}`);const i=await h.text().catch(e=>Ul(e).message),a=(e=>{try{return JSON.parse(e)}catch(e){return}})(i),o=a?void 0:i;Kc(this).debug(`[${l}] response error (${s})`,Jc({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,message:o,durationMs:Date.now()-u}));throw this.makeStatusError(h.status,a,o,h.headers)}return Kc(this).info(f),Kc(this).debug(`[${l}] response start`,Jc({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),{response:h,options:r,controller:d,requestLogID:l,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){const n=this.makeRequest(t,null,void 0);return new su(this,n,e)}async fetchWithTimeout(e,t,n,r){const{signal:s,method:i,...a}=t||{};s&&s.addEventListener("abort",()=>r.abort());const o=setTimeout(()=>r.abort(),n),l=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||"object"==typeof a.body&&null!==a.body&&Symbol.asyncIterator in a.body,c={signal:r.signal,...l?{duplex:"half"}:{},method:"GET",...a};i&&(c.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,c)}finally{clearTimeout(o)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,n,r){let s;const i=r?.get("retry-after-ms");if(i){const e=parseFloat(i);Number.isNaN(e)||(s=e)}const a=r?.get("retry-after");if(a&&!s){const e=parseFloat(a);s=Number.isNaN(e)?Date.parse(a)-Date.now():1e3*e}if(!(s&&0<=s&&s<6e4)){const n=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,n)}return await oc(s),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){const n=t-e;return Math.min(.5*Math.pow(2,n),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){const n={...e},{method:r,path:s,query:i,defaultBaseURL:a}=n,o=this.buildURL(s,i,a);"timeout"in n&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new Fl(`${e} must be an integer`);if(t<0)throw new Fl(`${e} must be a positive integer`)})("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:l,body:c}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:l,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&c instanceof globalThis.ReadableStream&&{duplex:"half"},...c&&{body:c},...this.fetchOptions??{},...n.fetchOptions??{}},url:o,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let s={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);const i=Ud([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...hc??(hc=cc()),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=Ud([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&n.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:"object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)?{bodyHeaders:void 0,body:fc(e)}:Ll(this,wp,"f").call(this,{body:e,headers:n})}}bp=kp,wp=new WeakMap,vp=new WeakSet,Ep=function(){return"https://api.openai.com/v1"!==this.baseURL},kp.OpenAI=bp,kp.DEFAULT_TIMEOUT=6e5,kp.OpenAIError=Fl,kp.APIError=Bl,kp.APIConnectionError=zl,kp.APIConnectionTimeoutError=Hl,kp.APIUserAbortError=ql,kp.NotFoundError=Jl,kp.ConflictError=Zl,kp.RateLimitError=Yl,kp.BadRequestError=Wl,kp.AuthenticationError=Gl,kp.InternalServerError=Xl,kp.PermissionDeniedError=Kl,kp.UnprocessableEntityError=Vl,kp.InvalidWebhookSignatureError=tc,kp.toFile=async function(e,t,n){if(ou(),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&gu(e))(e=await e))return e instanceof File?e:lu([await e.arrayBuffer()],e.name);if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const r=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),lu(await _u(r),t,n)}const r=await _u(e);if(t||(t=cu(e)),!n?.type){const e=r.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(n={...n,type:e})}return lu(r,t,n)},kp.Completions=Rh,kp.Chat=Ld,kp.Embeddings=Mh,kp.Files=Bh,kp.Images=Xh,kp.Audio=zd,kp.Moderations=ep,kp.Models=Qh,kp.FineTuning=Zh,kp.Graders=Yh,kp.VectorStores=mp,kp.Webhooks=Sp,kp.Beta=$h,kp.Batches=Hd,kp.Uploads=hp,kp.Responses=up,kp.Evals=Fh,kp.Containers=Lh;new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);var xp="object"==typeof window?window:{},Op="0123456789abcdef".split(""),Tp=[-2147483648,8388608,32768,128],Ip=[24,16,8,0],Ap=[];function Pp(e){e?(Ap[0]=Ap[16]=Ap[1]=Ap[2]=Ap[3]=Ap[4]=Ap[5]=Ap[6]=Ap[7]=Ap[8]=Ap[9]=Ap[10]=Ap[11]=Ap[12]=Ap[13]=Ap[14]=Ap[15]=0,this.blocks=Ap):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.h0=1732584193,this.h1=4023233417,this.h2=2562383102,this.h3=271733878,this.h4=3285377520,this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}Pp.prototype.update=function(e){if(!this.finalized){var t="string"!=typeof e;t&&e.constructor===xp.ArrayBuffer&&(e=new Uint8Array(e));for(var n,r,s=0,i=e.length||0,a=this.blocks;s>2]|=e[s]<>2]|=n<>2]|=(192|n>>6)<>2]|=(128|63&n)<=57344?(a[r>>2]|=(224|n>>12)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=(240|n>>18)<>2]|=(128|n>>12&63)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<=64?(this.block=a[16],this.start=r-64,this.hash(),this.hashed=!0):this.start=r}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this}},Pp.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>2]|=Tp[3&t],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},Pp.prototype.hash=function(){var e,t,n=this.h0,r=this.h1,s=this.h2,i=this.h3,a=this.h4,o=this.blocks;for(e=16;e<80;++e)t=o[e-3]^o[e-8]^o[e-14]^o[e-16],o[e]=t<<1|t>>>31;for(e=0;e<20;e+=5)n=(t=(r=(t=(s=(t=(i=(t=(a=(t=n<<5|n>>>27)+(r&s|~r&i)+a+1518500249+o[e]|0)<<5|a>>>27)+(n&(r=r<<30|r>>>2)|~n&s)+i+1518500249+o[e+1]|0)<<5|i>>>27)+(a&(n=n<<30|n>>>2)|~a&r)+s+1518500249+o[e+2]|0)<<5|s>>>27)+(i&(a=a<<30|a>>>2)|~i&n)+r+1518500249+o[e+3]|0)<<5|r>>>27)+(s&(i=i<<30|i>>>2)|~s&a)+n+1518500249+o[e+4]|0,s=s<<30|s>>>2;for(;e<40;e+=5)n=(t=(r=(t=(s=(t=(i=(t=(a=(t=n<<5|n>>>27)+(r^s^i)+a+1859775393+o[e]|0)<<5|a>>>27)+(n^(r=r<<30|r>>>2)^s)+i+1859775393+o[e+1]|0)<<5|i>>>27)+(a^(n=n<<30|n>>>2)^r)+s+1859775393+o[e+2]|0)<<5|s>>>27)+(i^(a=a<<30|a>>>2)^n)+r+1859775393+o[e+3]|0)<<5|r>>>27)+(s^(i=i<<30|i>>>2)^a)+n+1859775393+o[e+4]|0,s=s<<30|s>>>2;for(;e<60;e+=5)n=(t=(r=(t=(s=(t=(i=(t=(a=(t=n<<5|n>>>27)+(r&s|r&i|s&i)+a-1894007588+o[e]|0)<<5|a>>>27)+(n&(r=r<<30|r>>>2)|n&s|r&s)+i-1894007588+o[e+1]|0)<<5|i>>>27)+(a&(n=n<<30|n>>>2)|a&r|n&r)+s-1894007588+o[e+2]|0)<<5|s>>>27)+(i&(a=a<<30|a>>>2)|i&n|a&n)+r-1894007588+o[e+3]|0)<<5|r>>>27)+(s&(i=i<<30|i>>>2)|s&a|i&a)+n-1894007588+o[e+4]|0,s=s<<30|s>>>2;for(;e<80;e+=5)n=(t=(r=(t=(s=(t=(i=(t=(a=(t=n<<5|n>>>27)+(r^s^i)+a-899497514+o[e]|0)<<5|a>>>27)+(n^(r=r<<30|r>>>2)^s)+i-899497514+o[e+1]|0)<<5|i>>>27)+(a^(n=n<<30|n>>>2)^r)+s-899497514+o[e+2]|0)<<5|s>>>27)+(i^(a=a<<30|a>>>2)^n)+r-899497514+o[e+3]|0)<<5|r>>>27)+(s^(i=i<<30|i>>>2)^a)+n-899497514+o[e+4]|0,s=s<<30|s>>>2;this.h0=this.h0+n|0,this.h1=this.h1+r|0,this.h2=this.h2+s|0,this.h3=this.h3+i|0,this.h4=this.h4+a|0},Pp.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,s=this.h4;return Op[e>>28&15]+Op[e>>24&15]+Op[e>>20&15]+Op[e>>16&15]+Op[e>>12&15]+Op[e>>8&15]+Op[e>>4&15]+Op[15&e]+Op[t>>28&15]+Op[t>>24&15]+Op[t>>20&15]+Op[t>>16&15]+Op[t>>12&15]+Op[t>>8&15]+Op[t>>4&15]+Op[15&t]+Op[n>>28&15]+Op[n>>24&15]+Op[n>>20&15]+Op[n>>16&15]+Op[n>>12&15]+Op[n>>8&15]+Op[n>>4&15]+Op[15&n]+Op[r>>28&15]+Op[r>>24&15]+Op[r>>20&15]+Op[r>>16&15]+Op[r>>12&15]+Op[r>>8&15]+Op[r>>4&15]+Op[15&r]+Op[s>>28&15]+Op[s>>24&15]+Op[s>>20&15]+Op[s>>16&15]+Op[s>>12&15]+Op[s>>8&15]+Op[s>>4&15]+Op[15&s]},Pp.prototype.toString=Pp.prototype.hex,Pp.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,s=this.h4;return[e>>24&255,e>>16&255,e>>8&255,255&e,t>>24&255,t>>16&255,t>>8&255,255&t,n>>24&255,n>>16&255,n>>8&255,255&n,r>>24&255,r>>16&255,r>>8&255,255&r,s>>24&255,s>>16&255,s>>8&255,255&s]},Pp.prototype.array=Pp.prototype.digest,Pp.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(20),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),e};let Cp=!1;var $p="0123456789abcdef".split(""),Rp=[-2147483648,8388608,32768,128],Np=[24,16,8,0],jp=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Lp=[];function Mp(e,t){t?(Lp[0]=Lp[16]=Lp[1]=Lp[2]=Lp[3]=Lp[4]=Lp[5]=Lp[6]=Lp[7]=Lp[8]=Lp[9]=Lp[10]=Lp[11]=Lp[12]=Lp[13]=Lp[14]=Lp[15]=0,this.blocks=Lp):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}Mp.prototype.update=function(e){if(!this.finalized){var t,n=typeof e;if("string"!==n){if("object"!==n)throw new Error(ERROR);if(null===e)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!(Array.isArray(e)||ARRAY_BUFFER&&ArrayBuffer.isView(e)))throw new Error(ERROR);t=!0}for(var r,s,i=0,a=e.length,o=this.blocks;i>>2]|=e[i]<>>2]|=r<>>2]|=(192|r>>>6)<>>2]|=(128|63&r)<=57344?(o[s>>>2]|=(224|r>>>12)<>>2]|=(128|r>>>6&63)<>>2]|=(128|63&r)<>>2]|=(240|r>>>18)<>>2]|=(128|r>>>12&63)<>>2]|=(128|r>>>6&63)<>>2]|=(128|63&r)<=64?(this.block=o[16],this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this}},Mp.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=Rp[3&t],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},Mp.prototype.hash=function(){var e,t,n,r,s,i,a,o,l,c=this.h0,u=this.h1,d=this.h2,h=this.h3,p=this.h4,f=this.h5,m=this.h6,g=this.h7,_=this.blocks;for(e=16;e<64;++e)t=((s=_[e-15])>>>7|s<<25)^(s>>>18|s<<14)^s>>>3,n=((s=_[e-2])>>>17|s<<15)^(s>>>19|s<<13)^s>>>10,_[e]=_[e-16]+t+_[e-7]+n|0;for(l=u&d,e=0;e<64;e+=4)this.first?(this.is224?(i=300032,g=(s=_[0]-1413257819)-150054599|0,h=s+24177077|0):(i=704751109,g=(s=_[0]-210244248)-1521486534|0,h=s+143694565|0),this.first=!1):(t=(c>>>2|c<<30)^(c>>>13|c<<19)^(c>>>22|c<<10),r=(i=c&u)^c&d^l,g=h+(s=g+(n=(p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7))+(p&f^~p&m)+jp[e]+_[e])|0,h=s+(t+r)|0),t=(h>>>2|h<<30)^(h>>>13|h<<19)^(h>>>22|h<<10),r=(a=h&c)^h&u^i,m=d+(s=f+(n=(g>>>6|g<<26)^(g>>>11|g<<21)^(g>>>25|g<<7))+(m&g^~m&p)+jp[e+1]+_[e+1])|0,t=((d=s+(t+r)|0)>>>2|d<<30)^(d>>>13|d<<19)^(d>>>22|d<<10),r=(o=d&h)^d&c^a,f=u+(s=p+(n=(m>>>6|m<<26)^(m>>>11|m<<21)^(m>>>25|m<<7))+(f&m^~f&g)+jp[e+2]+_[e+2])|0,t=((u=s+(t+r)|0)>>>2|u<<30)^(u>>>13|u<<19)^(u>>>22|u<<10),r=(l=u&d)^u&h^o,p=c+(s=p+(n=(f>>>6|f<<26)^(f>>>11|f<<21)^(f>>>25|f<<7))+(f&m^~f&g)+jp[e+3]+_[e+3])|0,c=s+(t+r)|0,this.chromeBugWorkAround=!0;this.h0=this.h0+c|0,this.h1=this.h1+u|0,this.h2=this.h2+d|0,this.h3=this.h3+h|0,this.h4=this.h4+p|0,this.h5=this.h5+f|0,this.h6=this.h6+m|0,this.h7=this.h7+g|0},Mp.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,s=this.h4,i=this.h5,a=this.h6,o=this.h7,l=$p[e>>>28&15]+$p[e>>>24&15]+$p[e>>>20&15]+$p[e>>>16&15]+$p[e>>>12&15]+$p[e>>>8&15]+$p[e>>>4&15]+$p[15&e]+$p[t>>>28&15]+$p[t>>>24&15]+$p[t>>>20&15]+$p[t>>>16&15]+$p[t>>>12&15]+$p[t>>>8&15]+$p[t>>>4&15]+$p[15&t]+$p[n>>>28&15]+$p[n>>>24&15]+$p[n>>>20&15]+$p[n>>>16&15]+$p[n>>>12&15]+$p[n>>>8&15]+$p[n>>>4&15]+$p[15&n]+$p[r>>>28&15]+$p[r>>>24&15]+$p[r>>>20&15]+$p[r>>>16&15]+$p[r>>>12&15]+$p[r>>>8&15]+$p[r>>>4&15]+$p[15&r]+$p[s>>>28&15]+$p[s>>>24&15]+$p[s>>>20&15]+$p[s>>>16&15]+$p[s>>>12&15]+$p[s>>>8&15]+$p[s>>>4&15]+$p[15&s]+$p[i>>>28&15]+$p[i>>>24&15]+$p[i>>>20&15]+$p[i>>>16&15]+$p[i>>>12&15]+$p[i>>>8&15]+$p[i>>>4&15]+$p[15&i]+$p[a>>>28&15]+$p[a>>>24&15]+$p[a>>>20&15]+$p[a>>>16&15]+$p[a>>>12&15]+$p[a>>>8&15]+$p[a>>>4&15]+$p[15&a];return this.is224||(l+=$p[o>>>28&15]+$p[o>>>24&15]+$p[o>>>20&15]+$p[o>>>16&15]+$p[o>>>12&15]+$p[o>>>8&15]+$p[o>>>4&15]+$p[15&o]),l},Mp.prototype.toString=Mp.prototype.hex,Mp.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,s=this.h4,i=this.h5,a=this.h6,o=this.h7,l=[e>>>24&255,e>>>16&255,e>>>8&255,255&e,t>>>24&255,t>>>16&255,t>>>8&255,255&t,n>>>24&255,n>>>16&255,n>>>8&255,255&n,r>>>24&255,r>>>16&255,r>>>8&255,255&r,s>>>24&255,s>>>16&255,s>>>8&255,255&s,i>>>24&255,i>>>16&255,i>>>8&255,255&i,a>>>24&255,a>>>16&255,a>>>8&255,255&a];return this.is224||l.push(o>>>24&255,o>>>16&255,o>>>8&255,255&o),l},Mp.prototype.array=Mp.prototype.digest,Mp.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};const Dp=(...e)=>{return t=e.join("_"),Cp||(Cp=!0),new Pp(!0).update(t).hex();var t};class Up{constructor(){Object.defineProperty(this,"keyEncoder",{enumerable:!0,configurable:!0,writable:!0,value:Dp})}makeDefaultKeyEncoder(e){this.keyEncoder=e}}const Fp=new Map;class Bp extends Up{constructor(e){super(),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cache=e??new Map}lookup(e,t){return Promise.resolve(this.cache.get(this.keyEncoder(e,t))??null)}async update(e,t,n){this.cache.set(this.keyEncoder(e,t),n)}static global(){return new Bp(Fp)}}class qp extends Zt{}class zp extends qp{static lc_name(){return"StringPromptValue"}constructor(e){super({value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=e}toString(){return this.value}toChatMessages(){return[new wn(this.value)]}}class Hp extends qp{static lc_name(){return"ChatPromptValue"}constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.messages=e.messages}toString(){return Cn(this.messages)}toChatMessages(){return this.messages}}var Wp=n(7526),Gp=Object.defineProperty;function Kp(e,t){return 1===e.length?[t.get(e.join(","))]:function(e,t){let n=Array.from({length:e.length},(e,t)=>({start:t,end:t+1}));for(;n.length>1;){let r=null;for(let s=0;st.get(e.slice(n.start,n.end).join(","))).filter(e=>null!=e)}var Jp,Zp,Vp=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,t){this.patStr=e.pat_str;const n=e.bpe_ranks.split("\n").filter(Boolean).reduce((e,t)=>{const[n,r,...s]=t.split(" "),i=Number.parseInt(r,10);return s.forEach((t,n)=>e[t]=i+n),e},{});for(const[e,t]of Object.entries(n)){const n=Wp.toByteArray(e);this.rankMap.set(n.join(","),t),this.textMap.set(t,n)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((e,[t,n])=>(e[n]=this.textEncoder.encode(t),e),{})}encode(e,t=[],n="all"){const r=new RegExp(this.patStr,"ug"),s=Vp.specialTokenRegex(Object.keys(this.specialTokens)),i=[],a=new Set("all"===t?Object.keys(this.specialTokens):t),o=new Set("all"===n?Object.keys(this.specialTokens).filter(e=>!a.has(e)):n);if(o.size>0){const t=Vp.specialTokenRegex([...o]),n=e.match(t);if(null!=n)throw new Error(`The text contains a special token that is not allowed: ${n[0]}`)}let l=0;for(;;){let t=null,n=l;for(;s.lastIndex=n,t=s.exec(e),null!=t&&!a.has(t[0]);)n=t.index+1;const o=t?.index??e.length;for(const t of e.substring(l,o).matchAll(r)){const e=this.textEncoder.encode(t[0]),n=this.rankMap.get(e.join(","));null==n?i.push(...Kp(e,this.rankMap)):i.push(n)}if(null==t)break;let c=this.specialTokens[t[0]];i.push(c),l=t.index+t[0].length}return i}decode(e){const t=[];let n=0;for(let r=0;rnew RegExp(e.map(e=>function(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}(e)).join("|"),"g"),((e,t,n)=>{t in e?Gp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n})(Yp,"symbol"!=typeof(Jp="specialTokenRegex")?Jp+"":Jp,Zp);const Xp={},Qp=new ia({});async function ef(e){return async function(e){return e in Xp||(Xp[e]=Qp.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(e=>e.json()).then(e=>new Yp(e)).catch(t=>{throw delete Xp[e],t})),await Xp[e]}(function(e){switch(e){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":return"o200k_base";default:throw new Error("Unknown model")}}(e))}const tf=e=>e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e;function nf(e){return!("object"!=typeof e||!e)&&!!("type"in e&&"function"===e.type&&"function"in e&&"object"==typeof e.function&&e.function&&"name"in e.function&&"parameters"in e.function)}class rf extends yl{get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),Object.defineProperty(this,"verbose",{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,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verbose=e.verbose??!1,this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}}class sf extends rf{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}constructor({callbacks:e,callbackManager:t,...n}){const{cache:r,...s}=n;super({callbacks:e??t,...s}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_encoding",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cache="object"==typeof r?r:r?Bp.global():void 0,this.caller=new ia(n??{})}async getNumTokens(e){let t;t="string"==typeof e?e:e.map(e=>"string"==typeof e?e:"text"===e.type&&"text"in e?e.text:"").join("");let n=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await ef("modelName"in this?tf(this.modelName):"gpt2")}catch(e){}if(this._encoding)try{n=this._encoding.encode(t).length}catch(e){}return n}static _convertInputToPromptValue(e){return"string"==typeof e?new zp(e):Array.isArray(e)?new Hp(e.map(Pn)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){const n={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()},r=Object.entries(n).filter(([e,t])=>void 0!==t),s=r.map(([e,t])=>`${e}:${JSON.stringify(t)}`).sort().join(",");return s}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}}class af extends yl{static lc_name(){return"RunnablePassthrough"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e&&(this.func=e.func)}async invoke(e,t){const n=Mi(t);return this.func&&await this.func(e,n),this._callWithConfig(e=>Promise.resolve(e),e,n)}async*transform(e,t){const n=Mi(t);let r,s=!0;for await(const t of this._transformStreamWithConfig(e,e=>e,n))if(yield t,s)if(void 0===r)r=t;else try{r=zi(r,t)}catch{r=void 0,s=!1}this.func&&void 0!==r&&await this.func(r,n)}static assign(e){return new Il(new Sl({steps:e}))}}function of(e){const t=[];for(const n of e){let e=n;if(Array.isArray(n.content))for(let t=0;tt?.handleLLMError(e))),e}await Promise.all((l??[]).map(e=>e?.handleLLMEnd({generations:[[c]],llmOutput:u})))}}getLsParams(e){const t=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:e.stop,ls_provider:t}}async _generateUncached(e,t,n,r){const s=e.map(e=>e.map(Pn));let i;if(void 0!==r&&r.length===s.length)i=r;else{const e={...n.metadata,...this.getLsParams(t)},r=await Ai.configure(n.callbacks,this.callbacks,n.tags,this.tags,e,this.metadata,{verbose:this.verbose}),a={options:t,invocation_params:this?.invocationParams(t),batch_size:1};i=await(r?.handleChatModelStart(this.toJSON(),s.map(of),n.runId,void 0,a,void 0,void 0,n.runName))}const a=[],o=[];if(!!i?.[0].handlers.find(Qs)&&!this.disableStreaming&&1===s.length&&this._streamResponseChunks!==lf.prototype._streamResponseChunks)try{const e=await this._streamResponseChunks(s[0],t,i?.[0]);let n,r;for await(const t of e){if(null==t.message.id){const e=i?.at(0)?.runId;null!=e&&t.message._updateId(`run-${e}`)}n=void 0===n?t:zi(n,t),gn(t.message)&&void 0!==t.message.usage_metadata&&(r={tokenUsage:{promptTokens:t.message.usage_metadata.input_tokens,completionTokens:t.message.usage_metadata.output_tokens,totalTokens:t.message.usage_metadata.total_tokens}})}if(void 0===n)throw new Error("Received empty response from chat model call.");a.push([n]),await(i?.[0].handleLLMEnd({generations:a,llmOutput:r}))}catch(e){throw await(i?.[0].handleLLMError(e)),e}else{const e=await Promise.allSettled(s.map((e,n)=>this._generate(e,{...t,promptIndex:n},i?.[n])));await Promise.all(e.map(async(e,t)=>{if("fulfilled"===e.status){const n=e.value;for(const e of n.generations){if(null==e.message.id){const t=i?.at(0)?.runId;null!=t&&e.message._updateId(`run-${t}`)}e.message.response_metadata={...e.generationInfo,...e.message.response_metadata}}return 1===n.generations.length&&(n.generations[0].message.response_metadata={...n.llmOutput,...n.generations[0].message.response_metadata}),a[t]=n.generations,o[t]=n.llmOutput,i?.[t]?.handleLLMEnd({generations:[n.generations],llmOutput:n.llmOutput})}return await(i?.[t]?.handleLLMError(e.reason)),Promise.reject(e.reason)}))}const l={generations:a,llmOutput:o.length?this._combineLLMOutput?.(...o):void 0};return Object.defineProperty(l,Yi,{value:i?{runIds:i?.map(e=>e.runId)}:void 0,configurable:!0}),l}async _generateCached({messages:e,cache:t,llmStringKey:n,parsedOptions:r,handledOptions:s}){const i=e.map(e=>e.map(Pn)),a={...s.metadata,...this.getLsParams(r)},o=await Ai.configure(s.callbacks,this.callbacks,s.tags,this.tags,a,this.metadata,{verbose:this.verbose}),l={options:r,invocation_params:this?.invocationParams(r),batch_size:1},c=await(o?.handleChatModelStart(this.toJSON(),i.map(of),s.runId,void 0,l,void 0,void 0,s.runName)),u=[],d=(await Promise.allSettled(i.map(async(e,r)=>{const s=lf._convertInputToPromptValue(e).toString(),i=await t.lookup(s,n);return null==i&&u.push(r),i}))).map((e,t)=>({result:e,runManager:c?.[t]})).filter(({result:e})=>"fulfilled"===e.status&&null!=e.value||"rejected"===e.status),h=[];await Promise.all(d.map(async({result:e,runManager:t},n)=>{if("fulfilled"===e.status){const r=e.value;return h[n]=r.map(e=>("message"in e&&un(e.message)&&mn(e.message)&&(e.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0}),e.generationInfo={...e.generationInfo,tokenUsage:{}},e)),r.length&&await(t?.handleLLMNewToken(r[0].text)),t?.handleLLMEnd({generations:[r]},void 0,void 0,void 0,{cached:!0})}return await(t?.handleLLMError(e.reason,void 0,void 0,void 0,{cached:!0})),Promise.reject(e.reason)}));const p={generations:h,missingPromptIndices:u,startedRunManagers:c};return Object.defineProperty(p,Yi,{value:c?{runIds:c?.map(e=>e.runId)}:void 0,configurable:!0}),p}async generate(e,t,n){let r;r=Array.isArray(t)?{stop:t}:t;const s=e.map(e=>e.map(Pn)),[i,a]=this._separateRunnableConfigFromCallOptionsCompat(r);if(i.callbacks=i.callbacks??n,!this.cache)return this._generateUncached(s,a,i);const{cache:o}=this,l=this._getSerializedCacheKeyParametersForCall(a),{generations:c,missingPromptIndices:u,startedRunManagers:d}=await this._generateCached({messages:s,cache:o,llmStringKey:l,parsedOptions:a,handledOptions:i});let h={};if(u.length>0){const e=await this._generateUncached(u.map(e=>s[e]),a,i,void 0!==d?u.map(e=>d?.[e]):void 0);await Promise.all(e.generations.map(async(e,t)=>{const n=u[t];c[n]=e;const r=lf._convertInputToPromptValue(s[n]).toString();return o.update(r,l,e)})),h=e.llmOutput??{}}return{generations:c,llmOutput:h}}invocationParams(e){return{}}_modelType(){return"base_chat_model"}serialize(){return{...this.invocationParams(),_type:this._llmType(),_model:this._modelType()}}async generatePrompt(e,t,n){const r=e.map(e=>e.toChatMessages());return this.generate(r,t,n)}async call(e,t,n){return(await this.generate([e.map(Pn)],t,n)).generations[0][0].message}async callPrompt(e,t,n){const r=e.toChatMessages();return this.call(r,t,n)}async predictMessages(e,t,n){return this.call(e,t,n)}async predict(e,t,n){const r=new wn(e),s=await this.call([r],t,n);if("string"!=typeof s.content)throw new Error("Cannot use predict when output is not a string.");return s.content}withStructuredOutput(e,t){if("function"!=typeof this.bindTools)throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(t?.strict)throw new Error('"strict" mode is not supported for this model by default.');const n=e,r=t?.name,s=nl(n)??"A function available to call.",i=t?.method,a=t?.includeRaw;if("jsonMode"===i)throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let o,l=r??"extract";Qo(n)?o=[{type:"function",function:{name:l,description:s,parameters:ol(n)}}]:("name"in n&&(l=n.name),o=[{type:"function",function:{name:l,description:s,parameters:n}}]);const c=this.bindTools(o),u=xl.from(e=>{if(!e.tool_calls||0===e.tool_calls.length)throw new Error("No tool calls found in the response.");const t=e.tool_calls.find(e=>e.name===l);if(!t)throw new Error(`No tool call found with name ${l}.`);return t.args});if(!a)return c.pipe(u).withConfig({runName:"StructuredOutput"});const d=af.assign({parsed:(e,t)=>u.invoke(e.raw,t)}),h=af.assign({parsed:()=>null}),p=d.withFallbacks({fallbacks:[h]});return El.from([{raw:c},p]).withConfig({runName:"StructuredOutputRunnable"})}}class cf extends yl{parseResultWithPrompt(e,t,n){return this.parseResult(e,n)}_baseMessageToString(e){return"string"==typeof e.content?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return"string"==typeof e?this._callWithConfig(async(e,t)=>this.parseResult([{text:e}],t?.callbacks),e,{...t,runType:"parser"}):this._callWithConfig(async(e,t)=>this.parseResult([{message:e,text:this._baseMessageToString(e)}],t?.callbacks),e,{...t,runType:"parser"})}}class uf extends cf{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,n){return this.parse(e,n)}_type(){throw new Error("_type not implemented")}}class df extends Error{constructor(e,t,n,r=!1){if(super(e),Object.defineProperty(this,"llmOutput",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"observation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sendToLLM",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.llmOutput=t,this.observation=n,this.sendToLLM=r,r&&(void 0===n||void 0===t))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");xn(this,"OUTPUT_PARSING_FAILURE")}}class hf extends uf{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 pf extends hf{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(dn(r)){if("string"!=typeof r.content)throw new Error("Cannot handle non-string message output.");e=new Qi({message:r,text:r.content})}else if(un(r)){if("string"!=typeof r.content)throw new Error("Cannot handle non-string message output.");e=new Qi({message:$n(r),text:r.content})}else e=new Xi({text:r});n=void 0===n?e:n.concat(e);const s=await this.parsePartialResult([n]);null==s||ho(s,t)||(this.diff?yield this._diff(t,s):yield s,t=s)}}getFormatInstructions(){return""}}class ff extends uf{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(He(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,De().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(ol(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 tl(this.schema,JSON.parse(t))}catch(t){throw new df(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}}class mf extends pf{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?fr(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Bt(e[0].text)}async parse(e){return Bt(e,JSON.parse)}getFormatInstructions(){return""}}function gf(e,t){if(void 0===e.function)return;let n;if(t?.partial)try{n=qt(e.function.arguments??"{}")}catch(e){return}else try{n=JSON.parse(e.function.arguments)}catch(t){throw new df([`Function "${e.function.name}" arguments:`,"",e.function.arguments,"","are not valid JSON.",`Error: ${t.message}`].join("\n"))}const r={name:e.function.name,args:n,type:"tool_call"};return t?.returnId&&(r.id=e.id),r}function _f(e){if(void 0===e.id)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}}function yf(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:"invalid_tool_call"}}class vf extends pf{static lc_name(){return"JsonOutputToolsParser"}constructor(e){super(e),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.returnId=e?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){const n=e[0].message;let r;if(mn(n)&&n.tool_calls?.length)r=n.tool_calls.map(e=>{const{id:t,...n}=e;return this.returnId?{id:t,...n}:n});else if(void 0!==n.additional_kwargs.tool_calls){r=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(e=>gf(e,{returnId:this.returnId,partial:t}))}if(!r)return[];const s=[];for(const e of r)if(void 0!==e){const t={type:e.name,args:e.args,id:e.id};s.push(t)}return s}}class bf extends vf{static lc_name(){return"JsonOutputKeyToolsParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(void 0===this.zodSchema)return e;const t=await el(this.zodSchema,e);if(t.success)return t.data;throw new df(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){const t=(await super.parsePartialResult(e)).filter(e=>e.type===this.keyName);let n=t;if(t.length)return this.returnId||(n=t.map(e=>e.args)),this.returnSingle?n[0]:n}async parseResult(e){const t=(await super.parsePartialResult(e,!1)).filter(e=>e.type===this.keyName);let n=t;if(!t.length)return;if(this.returnId||(n=t.map(e=>e.args)),this.returnSingle)return this._validateResult(n[0]);const r=await Promise.all(n.map(e=>this._validateResult(e)));return r}}const wf=Symbol("Let zodToJsonSchema decide on which parser to use"),Ef={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Sf=e=>"_def"in e?e._def:e;const kf=e=>{const t=(e=>"string"==typeof e?{...Ef,basePath:["#"],definitions:{},name:e}:{...Ef,basePath:["#"],definitions:{},...e})(e),n=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[Sf(n),{def:Sf(n),path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function xf(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Of(e,t,n,r,s){e[t]=n,xf(e,t,r,s)}function Tf(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Tf(e,t,n))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return If(e,t)}}const If=(e,t)=>{const n={type:"integer",format:"unix-time"};if("openApi3"===t.target)return n;for(const r of e.checks)switch(r.kind){case"min":Of(n,"minimum",r.value,r.message,t);break;case"max":Of(n,"maximum",r.value,r.message,t)}return n};let Af;const Pf=/^[cC][^\s-]{8,}$/,Cf=/^[0-9a-z]+$/,$f=/^[0-9A-HJKMNP-TV-Z]{26}$/,Rf=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,Nf=()=>(void 0===Af&&(Af=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Af),jf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Lf=/^[a-zA-Z0-9_-]{21}$/;function Mf(e,t){const n={type:"string"};function r(e){return"escape"===t.patternStrategy?Df(e):e}if(e.checks)for(const s of e.checks)switch(s.kind){case"min":Of(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,s.value):s.value,s.message,t);break;case"max":Of(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,s.value):s.value,s.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Uf(n,"email",s.message,t);break;case"format:idn-email":Uf(n,"idn-email",s.message,t);break;case"pattern:zod":Ff(n,Rf,s.message,t)}break;case"url":Uf(n,"uri",s.message,t);break;case"uuid":Uf(n,"uuid",s.message,t);break;case"regex":Ff(n,s.regex,s.message,t);break;case"cuid":Ff(n,Pf,s.message,t);break;case"cuid2":Ff(n,Cf,s.message,t);break;case"startsWith":Ff(n,RegExp(`^${r(s.value)}`),s.message,t);break;case"endsWith":Ff(n,RegExp(`${r(s.value)}$`),s.message,t);break;case"datetime":Uf(n,"date-time",s.message,t);break;case"date":Uf(n,"date",s.message,t);break;case"time":Uf(n,"time",s.message,t);break;case"duration":Uf(n,"duration",s.message,t);break;case"length":Of(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,s.value):s.value,s.message,t),Of(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,s.value):s.value,s.message,t);break;case"includes":Ff(n,RegExp(r(s.value)),s.message,t);break;case"ip":"v6"!==s.version&&Uf(n,"ipv4",s.message,t),"v4"!==s.version&&Uf(n,"ipv6",s.message,t);break;case"emoji":Ff(n,Nf,s.message,t);break;case"ulid":Ff(n,$f,s.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":Uf(n,"binary",s.message,t);break;case"contentEncoding:base64":Of(n,"contentEncoding","base64",s.message,t);break;case"pattern:zod":Ff(n,jf,s.message,t)}break;case"nanoid":Ff(n,Lf,s.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:(()=>{})()}return n}const Df=e=>Array.from(e).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Uf=(e,t,n,r)=>{e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Of(e,"format",t,n,r)},Ff=(e,t,n,r)=>{e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:Bf(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Of(e,"pattern",Bf(t,r),n,r)},Bf=(e,t)=>{const n="function"==typeof e?e():e;if(!t.applyRegexFlags||!n.flags)return n.source;const r=n.flags.includes("i"),s=n.flags.includes("m"),i=n.flags.includes("s"),a=r?n.source.toLowerCase():n.source;let o="",l=!1,c=!1,u=!1;for(let e=0;e({...n,[r]:Gf(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??{}}),{}),additionalProperties:!1};const n={type:"object",additionalProperties:Gf(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if("openApi3"===t.target)return n;if(e.keyType?._def.typeName===Le.ZodString&&e.keyType._def.checks?.length){const r=Object.entries(Mf(e.keyType._def,t)).reduce((e,[t,n])=>"type"===t?e:{...e,[t]:n},{});return{...n,propertyNames:r}}return e.keyType?._def.typeName===Le.ZodEnum?{...n,propertyNames:{enum:e.keyType._def.values}}:n}const zf={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const Hf=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Gf(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Wf(e,t){return"strict"===t.removeAdditionalStrategy?"ZodNever"===e.catchall._def.typeName?"strict"!==e.unknownKeys:Gf(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0:"ZodNever"===e.catchall._def.typeName?"passthrough"===e.unknownKeys:Gf(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0}function Gf(e,t,n=!1){const r=t.seen.get(e);if(t.override){const s=t.override?.(e,t,r,n);if(s!==wf)return s}if(r&&!n){const e=Kf(r,t);if(void 0!==e)return"$ref"in e&&t.seenRefs.add(e.$ref),e}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const i=Zf(e,e.typeName,t,n);return i&&Vf(e,t,i),s.jsonSchema=i,i}const Kf=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"extract-to-root":const n=e.path.slice(t.basePath.length+1).join("_");return n!==t.name&&"duplicate-ref"===t.nameStrategy&&(t.definitions[n]=e.def),{$ref:[...t.basePath,t.definitionPath,n].join("/")};case"relative":return{$ref:Jf(t.currentPath,e.path)};case"none":case"seen":return e.path.lengtht.currentPath[n]===e)||"seen"===t.$refStrategy?{}:void 0}},Jf=(e,t)=>{let n=0;for(;n{switch(t){case Le.ZodString:return Mf(e,n);case Le.ZodNumber:return function(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",xf(n,"type",r.message,t);break;case"min":"jsonSchema7"===t.target?r.inclusive?Of(n,"minimum",r.value,r.message,t):Of(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Of(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Of(n,"maximum",r.value,r.message,t):Of(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Of(n,"maximum",r.value,r.message,t));break;case"multipleOf":Of(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case Le.ZodObject:return function(e,t){const n={type:"object",...Object.entries(e.shape()).reduce((e,[n,r])=>{if(void 0===r||void 0===r._def)return e;const s=[...t.currentPath,"properties",n],i=Gf(r._def,{...t,currentPath:s,propertyPath:s});if(void 0===i)return e;if(t.openaiStrictMode&&r.isOptional()&&!r.isNullable()&&void 0===r._def?.defaultValue)throw new Error(`Zod field at \`${s.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...e.properties,[n]:i},required:r.isOptional()&&!t.openaiStrictMode?e.required:[...e.required,n]}},{properties:{},required:[]}),additionalProperties:Wf(e,t)};return n.required.length||delete n.required,n}(e,n);case Le.ZodBigInt:return function(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":"jsonSchema7"===t.target?r.inclusive?Of(n,"minimum",r.value,r.message,t):Of(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Of(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Of(n,"maximum",r.value,r.message,t):Of(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Of(n,"maximum",r.value,r.message,t));break;case"multipleOf":Of(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case Le.ZodBoolean:return{type:"boolean"};case Le.ZodDate:return Tf(e,n);case Le.ZodUndefined:return{not:{}};case Le.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(n);case Le.ZodArray:return function(e,t){const n={type:"array"};return e.type?._def?.typeName!==Le.ZodAny&&(n.items=Gf(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Of(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Of(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Of(n,"minItems",e.exactLength.value,e.exactLength.message,t),Of(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}(e,n);case Le.ZodUnion:case Le.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return Hf(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in zf&&(!e._def.checks||!e._def.checks.length))){const e=n.reduce((e,t)=>{const n=zf[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){const e=n.reduce((e,t)=>{const n=typeof t._def.value;switch(n){case"string":case"number":case"boolean":return[...e,n];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===n.length){const t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Hf(e,t)}(e,n);case Le.ZodIntersection:return function(e,t){const n=[Gf(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Gf(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e);let r="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const s=[];return n.forEach(e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:n,...r}=e;t=r}else r=void 0;s.push(t)}else s.push(...e.allOf),void 0===e.unevaluatedProperties&&(r=void 0);var t}),s.length?{allOf:s,...r}:void 0}(e,n);case Le.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,n)=>Gf(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:Gf(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Gf(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,n);case Le.ZodRecord:return qf(e,n);case Le.ZodLiteral:return function(e,t){const n=typeof e.value;return"bigint"!==n&&"number"!==n&&"boolean"!==n&&"string"!==n?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===n?"integer":n,enum:[e.value]}:{type:"bigint"===n?"integer":n,const:e.value}}(e,n);case Le.ZodEnum:return function(e){return{type:"string",enum:[...e.values]}}(e);case Le.ZodNativeEnum:return function(e){const t=e.values,n=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]),r=n.map(e=>t[e]),s=Array.from(new Set(r.map(e=>typeof e)));return{type:1===s.length?"string"===s[0]?"string":"number":["string","number"],enum:r}}(e);case Le.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target||"property"===t.nullableStrategy?{type:zf[e.innerType._def.typeName],nullable:!0}:{type:[zf[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const n=Gf(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const n=Gf(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}(e,n);case Le.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Gf(e.innerType._def,t);const n=Gf(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}})(e,n);case Le.ZodMap:return function(e,t){return"record"===t.mapStrategy?qf(e,t):{type:"array",maxItems:125,items:{type:"array",items:[Gf(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},Gf(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}(e,n);case Le.ZodSet:return function(e,t){const n={type:"array",uniqueItems:!0,items:Gf(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Of(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Of(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}(e,n);case Le.ZodLazy:return Gf(e.getter()._def,n);case Le.ZodPromise:return function(e,t){return Gf(e.type._def,t)}(e,n);case Le.ZodNaN:case Le.ZodNever:return{not:{}};case Le.ZodEffects:return function(e,t,n){return"input"===t.effectStrategy?Gf(e.schema._def,t,n):{}}(e,n,r);case Le.ZodAny:case Le.ZodUnknown:return{};case Le.ZodDefault:return function(e,t){return{...Gf(e.innerType._def,t),default:e.defaultValue()}}(e,n);case Le.ZodBranded:return function(e,t){return Gf(e.type._def,t)}(e,n);case Le.ZodReadonly:case Le.ZodCatch:return((e,t)=>Gf(e.innerType._def,t))(e,n);case Le.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return Gf(e.in._def,t);if("output"===t.pipeStrategy)return Gf(e.out._def,t);const n=Gf(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[n,Gf(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]})].filter(e=>void 0!==e)}})(e,n);case Le.ZodFunction:case Le.ZodVoid:case Le.ZodSymbol:default:return}},Vf=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n);function Yf(e,t){return((e,t)=>{const n=kf(t),r="string"==typeof t?t:"title"===t?.nameStrategy?void 0:t?.name,s=Gf(e._def,void 0===r?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??{},i="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==i&&(s.title=i);const a=(()=>{if(function(e){if(!e)return!0;for(const t in e)return!1;return!0}(n.definitions))return;const e={},t=new Set;for(let r=0;r<500;r++){const r=Object.entries(n.definitions).filter(([e])=>!t.has(e));if(0===r.length)break;for(const[s,i]of r)e[s]=Gf(Sf(i),{...n,currentPath:[...n.basePath,n.definitionPath,s]},!0)??{},t.add(s)}return e})(),o=void 0===r?a?{...s,[n.definitionPath]:a}:s:"duplicate-ref"===n.nameStrategy?{...s,...a||n.seenRefs.size?{[n.definitionPath]:{...a,...n.seenRefs.size?{[r]:s}:void 0}}:void 0}:{$ref:[..."relative"===n.$refStrategy?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...a,[r]:s}};return"jsonSchema7"===n.target?o.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"===n.target&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o})(e,{openaiStrictMode:!0,name:t.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Xf(e,t,n){return function(e,t){const n={...e};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}({type:"json_schema",json_schema:{...n,name:t,strict:!0,schema:Yf(e,{name:t})}},t=>e.parse(JSON.parse(t)))}function Qf(e){const{azureOpenAIApiDeploymentName:t,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:r,azureOpenAIBasePath:s,baseURL:i,azureADTokenProvider:a,azureOpenAIEndpoint:o}=e;if((r||a)&&s&&t)return`${s}/${t}`;if((r||a)&&o&&t)return`${o}/openai/deployments/${t}`;if(r||a){if(!n)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!t)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${n}.openai.azure.com/openai/deployments/${t}`}return i}function em(e){return function(e){return!!e&&"object"==typeof e&&"name"in e&&"schema"in e&&(Qo(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))}(e)||function(e){return void 0!==e&&yl.isRunnable(e)&&"lc_name"in e.constructor&&"function"==typeof e.constructor.lc_name&&"RunnableToolLike"===e.constructor.lc_name()}(e)||function(e){return void 0!==e&&Array.isArray(e.lc_namespace)}(e)}function tm(e,t){const n="number"==typeof t?void 0:t;return{name:e.name,description:e.description,parameters:ol(e.schema),...void 0!==n?.strict?{strict:n.strict}:{}}}function nm(e,t){const n="number"==typeof t?void 0:t;let r;return r=em(e)?{type:"function",function:tm(e)}:e,void 0!==n?.strict&&(r.function.strict=n.strict),r}function rm(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/\n`,e}function sm(e){let t;return e.constructor.name===Hl.name?(t=new Error(e.message),t.name="TimeoutError"):e.constructor.name===ql.name?(t=new Error(e.message),t.name="AbortError"):t=400===e.status&&e.message.includes("tool_calls")?rm(e,"INVALID_TOOL_RESULTS"):401===e.status?rm(e,"MODEL_AUTHENTICATION"):429===e.status?rm(e,"MODEL_RATE_LIMIT"):404===e.status?rm(e,"MODEL_NOT_FOUND"):e,t}function im(e){return e?"any"===e||"required"===e?"required":"auto"===e?"auto":"none"===e?"none":"string"==typeof e?{type:"function",function:{name:e}}:e:void 0}function am(e,t){const n=[];for(const[r,s]of Object.entries(e.properties??{}))s.description&&t<2&&n.push(`// ${s.description}`),e.required?.includes(r)?n.push(`${r}: ${om(s,t)},`):n.push(`${r}?: ${om(s,t)},`);return n.map(e=>" ".repeat(t)+e).join("\n")}function om(e,t){if(void 0!==(n=e).anyOf&&Array.isArray(n.anyOf))return e.anyOf.map(e=>om(e,t)).join(" | ");var n;switch(e.type){case"string":return e.enum?e.enum.map(e=>`"${e}"`).join(" | "):"string";case"number":case"integer":return e.enum?e.enum.map(e=>`${e}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",am(e,t+2),"}"].join("\n");case"array":return e.items?`${om(e.items,t)}[]`:"any[]";default:return""}}function lm(e){const t=e._getType();switch(t){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!yn.isInstance(e))throw new Error("Invalid generic chat message");return function(e){return"system"!==e.role&&"developer"!==e.role&&"assistant"!==e.role&&"user"!==e.role&&"function"!==e.role&&e.role,e.role}(e);default:throw new Error(`Unknown message type: ${t}`)}}const cm={providerName:"ChatOpenAI",fromStandardTextBlock:e=>({type:"text",text:e.text}),fromStandardImageBlock(e){if("url"===e.source_type)return{type:"image_url",image_url:{url:e.url,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};if("base64"===e.source_type){return{type:"image_url",image_url:{url:`data:${e.mime_type??""};base64,${e.data}`,...e.metadata?.detail?{detail:e.metadata.detail}:{}}}}throw new Error(`Image content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(e){if("url"===e.source_type){const t=tn({dataUrl:e.url});if(!t)throw new Error(`URL audio blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);const n=t.mime_type||e.mime_type||"";let r;try{r=en(n)}catch{throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if("audio"!==r.type||"wav"!==r.subtype&&"mp3"!==r.subtype)throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:r.subtype,data:t.data}}}if("base64"===e.source_type){let t;try{t=en(e.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if("audio"!==t.type||"wav"!==t.subtype&&"mp3"!==t.subtype)throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:t.subtype,data:e.data}}}throw new Error(`Audio content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(e){if("url"===e.source_type){if(!tn({dataUrl:e.url}))throw new Error(`URL file blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:e.url,...e.metadata?.filename||e.metadata?.name?{filename:e.metadata?.filename||e.metadata?.name}:{}}}}if("base64"===e.source_type)return{type:"file",file:{file_data:`data:${e.mime_type??""};base64,${e.data}`,...e.metadata?.filename||e.metadata?.name||e.metadata?.title?{filename:e.metadata?.filename||e.metadata?.name||e.metadata?.title}:{}}};if("id"===e.source_type)return{type:"file",file:{file_id:e.id}};throw new Error(`File content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)}};function um(e,t){return e.flatMap(e=>{let n=lm(e);"system"===n&&ym(t)&&(n="developer");const r="string"==typeof e.content?e.content:e.content.map(e=>Vt(e)?nn(e,cm):e),s={role:n,content:r};if(null!=e.name&&(s.name=e.name),null!=e.additional_kwargs.function_call&&(s.function_call=e.additional_kwargs.function_call,s.content=""),mn(e)&&e.tool_calls?.length?(s.tool_calls=e.tool_calls.map(_f),s.content=""):(null!=e.additional_kwargs.tool_calls&&(s.tool_calls=e.additional_kwargs.tool_calls),null!=e.tool_call_id&&(s.tool_call_id=e.tool_call_id)),e.additional_kwargs.audio&&"object"==typeof e.additional_kwargs.audio&&"id"in e.additional_kwargs.audio){return[s,{role:"assistant",audio:{id:e.additional_kwargs.audio.id}}]}return s})}const dm="__openai_function_call_ids__";function hm(e,t,n){return e.flatMap(e=>{const r=e.additional_kwargs;let s=lm(e);if("system"===s&&ym(t)&&(s="developer"),"function"===s)throw new Error("Function messages are not supported in Responses API");if("tool"===s){const t=e;if("computer_call_output"===r?.type){const e=(()=>{if("string"==typeof t.content)return{type:"computer_screenshot",image_url:t.content};if(Array.isArray(t.content)){const e=t.content.find(e=>"computer_screenshot"===e.type);if(e)return e;const n=t.content.find(e=>"image_url"===e.type);if(n)return{type:"computer_screenshot",image_url:"string"==typeof n.image_url?n.image_url:n.image_url.url}}throw new Error("Invalid computer call output")})();return{type:"computer_call_output",output:e,call_id:t.tool_call_id}}return{type:"function_call_output",call_id:t.tool_call_id,id:t.id?.startsWith("fc_")?t.id:void 0,output:"string"!=typeof t.content?JSON.stringify(t.content):t.content}}if("assistant"===s){if(!n&&null!=e.response_metadata.output&&Array.isArray(e.response_metadata.output)&&e.response_metadata.output.length>0&&e.response_metadata.output.every(e=>"type"in e))return e.response_metadata.output;const t=[];if(r?.reasoning&&!n){const e=function(e){const t=(e.summary.length>1?e.summary.reduce((e,t)=>{const n=e.at(-1);return n.index===t.index?n.text+=t.text:e.push(t),e},[{...e.summary[0]}]):e.summary).map(e=>Object.fromEntries(Object.entries(e).filter(([e])=>"index"!==e)));return{...e,summary:t}}(r.reasoning);t.push(e)}let{content:s}=e;r?.refusal&&("string"==typeof s&&(s=[{type:"output_text",text:s,annotations:[]}]),s=[...s,{type:"refusal",refusal:r.refusal}]),t.push({type:"message",role:"assistant",...e.id&&!n&&e.id.startsWith("msg_")?{id:e.id}:{},content:"string"==typeof s?s:s.flatMap(e=>"text"===e.type?{type:"output_text",text:e.text,annotations:e.annotations??[]}:"output_text"===e.type||"refusal"===e.type?e:[])});const i=r?.[dm];mn(e)&&e.tool_calls?.length?t.push(...e.tool_calls.map(e=>({type:"function_call",name:e.name,arguments:JSON.stringify(e.args),call_id:e.id,...n?{id:i?.[e.id]}:{}}))):r?.tool_calls&&t.push(...r.tool_calls.map(e=>({type:"function_call",name:e.function.name,call_id:e.id,arguments:e.function.arguments,...n?{id:i?.[e.id]}:{}})));const a=e.response_metadata.output?.length?e.response_metadata.output:r.tool_outputs,o=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(null!=a){const e=a,n=e?.filter(e=>o.includes(e.type));n.length>0&&t.push(...n)}return t}if("user"===s||"system"===s||"developer"===s){if("string"==typeof e.content)return{type:"message",role:s,content:e.content};const t=[],n=e.content.flatMap(e=>("mcp_approval_response"===e.type&&t.push({type:"mcp_approval_response",approval_request_id:e.approval_request_id,approve:e.approve}),Vt(e)?nn(e,cm):"text"===e.type?{type:"input_text",text:e.text}:"image_url"===e.type?{type:"input_image",image_url:"string"==typeof e.image_url?e.image_url:e.image_url.url,detail:"string"==typeof e.image_url?"auto":e.image_url.detail}:"input_text"===e.type||"input_image"===e.type||"input_file"===e.type?e:[]));return n.length>0&&t.push({type:"message",role:s,content:n}),t}return[]})}function pm(e){if(e.error){const t=new Error(e.error.message);throw t.name=e.error.code,t}let t;const n=[],r=[],s=[],i={model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},a={};for(const i of e.output)if("message"===i.type)t=i.id,n.push(...i.content.flatMap(e=>"output_text"===e.type?("parsed"in e&&null!=e.parsed&&(a.parsed=e.parsed),{type:"text",text:e.text,annotations:e.annotations}):"refusal"===e.type?(a.refusal=e.refusal,[]):e));else if("function_call"===i.type){const e={function:{name:i.name,arguments:i.arguments},id:i.call_id};try{r.push(gf(e,{returnId:!0}))}catch(t){let n;"object"==typeof t&&null!=t&&"message"in t&&"string"==typeof t.message&&(n=t.message),s.push(yf(e,n))}a[dm]??={},i.id&&(a[dm][i.call_id]=i.id)}else"reasoning"===i.type?a.reasoning=i:(a.tool_outputs??=[],a.tool_outputs.push(i));return new fn({id:t,content:n,tool_calls:r,invalid_tool_calls:s,usage_metadata:e.usage,additional_kwargs:a,response_metadata:i})}function fm(e){const t=[];let n,r={};const s=[],i={},a={};let o;if("response.output_text.delta"===e.type)t.push({type:"text",text:e.delta,index:e.content_index});else if("response.output_text_annotation.added"===e.type)t.push({type:"text",text:"",annotations:[e.annotation],index:e.content_index});else if("response.output_item.added"===e.type&&"message"===e.item.type)o=e.item.id;else if("response.output_item.added"===e.type&&"function_call"===e.item.type)s.push({type:"tool_call_chunk",name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),a[dm]={[e.item.call_id]:e.item.id};else if("response.output_item.done"===e.type&&["web_search_call","file_search_call","computer_call","code_interpreter_call","mcp_call","mcp_list_tools","mcp_approval_request","image_generation_call"].includes(e.item.type))a.tool_outputs=[e.item];else if("response.created"===e.type)i.id=e.response.id,i.model_name=e.response.model,i.model=e.response.model;else if("response.completed"===e.type){const t=pm(e.response);n=e.response.usage,"json_schema"===e.response.text?.format?.type&&(a.parsed??=JSON.parse(t.text));for(const[t,n]of Object.entries(e.response))"id"!==t&&(i[t]=n)}else if("response.function_call_arguments.delta"===e.type)s.push({type:"tool_call_chunk",args:e.delta,index:e.output_index});else if("response.web_search_call.completed"===e.type||"response.file_search_call.completed"===e.type)r={tool_outputs:{id:e.item_id,type:e.type.replace("response.","").replace(".completed",""),status:"completed"}};else if("response.refusal.done"===e.type)a.refusal=e.refusal;else if("response.output_item.added"===e.type&&"item"in e&&"reasoning"===e.item.type){const t=e.item.summary?e.item.summary.map((e,t)=>({...e,index:t})):void 0;a.reasoning={id:e.item.id,type:e.item.type,...t?{summary:t}:{}}}else if("response.reasoning_summary_part.added"===e.type)a.reasoning={type:"reasoning",summary:[{...e.part,index:e.summary_index}]};else{if("response.reasoning_summary_text.delta"!==e.type)return e.type,null;a.reasoning={type:"reasoning",summary:[{text:e.delta,type:"summary_text",index:e.summary_index}]}}return new Qi({text:t.map(e=>e.text).join(""),message:new _n({id:o,content:t,tool_call_chunks:s,usage_metadata:n,additional_kwargs:a,response_metadata:i}),generationInfo:r})}function mm(e){return"type"in e&&"function"!==e.type}function gm(e,t){const n=[];for(const r of e)mm(r)?("image_generation"===r.type&&t?.stream&&(r.partial_images=1),n.push(r)):nf(r)&&n.push({type:"function",name:r.function.name,parameters:r.function.parameters,description:r.function.description,strict:t?.strict??null});return n}function _m(e,t){return nf(e)?void 0!==t?.strict?{...e,function:{...e.function,strict:t.strict}}:e:function(e,t){let n;return n=em(e)?nm(e):e,void 0!==t?.strict&&(n.function.strict=t.strict),n}(e,t)}function ym(e){return e&&/^o\d/.test(e)}class vm extends lf{static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning_effort","service_tier"]}get lc_secrets(){return{openAIApiKey:"OPENAI_API_KEY",apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{modelName:"model",openAIApiKey:"openai_api_key",apiKey:"openai_api_key"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","reasoningEffort","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","modelName","model","modelKwargs","stop","stopSequences","timeout","openAIApiKey","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","useResponsesApi","zdrEnabled","reasoning"]}constructor(e){super(e??{}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"frequencyPenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"presencePenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logitBias",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"gpt-3.5-turbo"}),Object.defineProperty(this,"modelKwargs",{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,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topLogprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"openAIApiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"organization",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"__includeRawResponse",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"clientConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"supportsStrictToolCalling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"audio",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modalities",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reasoningEffort",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reasoning",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"useResponsesApi",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zdrEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"service_tier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.openAIApiKey=e?.apiKey??e?.openAIApiKey??e?.configuration?.apiKey??Ys("OPENAI_API_KEY"),this.apiKey=this.openAIApiKey,this.organization=e?.configuration?.organization??Ys("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelName=this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoningEffort=e?.reasoningEffort??e?.reasoning?.effort,this.reasoning=e?.reasoning??(e?.reasoningEffort?{effort:e.reasoningEffort}:void 0),this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.useResponsesApi=e?.useResponsesApi??this.useResponsesApi,this.disableStreaming=e?.disableStreaming??this.disableStreaming,this.streaming=e?.streaming??!1,this.disableStreaming&&(this.streaming=!1),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},void 0!==e?.supportsStrictToolCalling&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),void 0!==e?.service_tier&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1}getLsParams(e){const t=this.invocationParams(e);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}bindTools(e,t){let n;return void 0!==t?.strict?n=t.strict:void 0!==this.supportsStrictToolCalling&&(n=this.supportsStrictToolCalling),this.withConfig({tools:e.map(e=>mm(e)?e:_m(e,{strict:n})),...t})}createResponseFormat(e){return e&&"json_schema"===e.type&&e.json_schema.schema&&Qo(e.json_schema.schema)?function(e,t,n){if(Xo(e))return Xf(e,t,n);if(Yo(e))return function(e,t){const n={...e};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}({type:"json_schema",json_schema:{...n,name:t,strict:!0,schema:Oa(e,{cycles:"ref",reused:"ref",override(e){e.jsonSchema.title=t}})}},t=>Fo(e,JSON.parse(t)));throw new Error("Unsupported schema response format")}(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}getReasoningParams(e){if(!ym(this.model))return;let t;return void 0!==this.reasoningEffort&&(t={effort:this.reasoningEffort}),void 0!==this.reasoning&&(t={...t,...this.reasoning}),void 0!==e?.reasoning_effort&&(t={...t,effort:e.reasoning_effort}),void 0!==e?.reasoning&&(t={...t,...e.reasoning}),t}invocationParams(e,t){let n;if(void 0!==e?.strict?n=e.strict:void 0!==this.supportsStrictToolCalling&&(n=this.supportsStrictToolCalling),this._useResponseApi(e)){const t={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?gm(e.tools,{stream:this.streaming,strict:n}):void 0,tool_choice:(r=e?.tool_choice,null!=r&&"object"==typeof r&&"type"in r&&"function"!==r.type?e?.tool_choice:(()=>{const t=im(e?.tool_choice);return"object"==typeof t&&"type"in t?{type:"function",name:t.function.name}:void 0})()),text:(()=>{if(e?.text)return e.text;const t=this.createResponseFormat(e?.response_format);return"json_schema"===t?.type?null!=t.json_schema.schema?{format:{type:"json_schema",schema:t.json_schema.schema,description:t.json_schema.description,name:t.json_schema.name,strict:t.json_schema.strict}}:void 0:{format:t}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:-1===this.maxTokens?void 0:this.maxTokens,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},s=this.getReasoningParams(e);return void 0!==s&&(t.reasoning=s),t}var r;let s={};void 0!==e?.stream_options?s={stream_options:e.stream_options}:this.streamUsage&&(this.streaming||t?.streaming)&&(s={stream_options:{include_usage:!0}});const i={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map(e=>_m(e,{strict:n})):void 0,tool_choice:im(e?.tool_choice),response_format:this.createResponseFormat(e?.response_format),seed:e?.seed,...s,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs};void 0!==e?.prediction&&(i.prediction=e.prediction),void 0!==this.service_tier&&(i.service_tier=this.service_tier),void 0!==e?.service_tier&&(i.service_tier=e.service_tier);const a=this.getReasoningParams(e);return void 0!==a&&void 0!==a.effort&&(i.reasoning_effort=a.effort),ym(i.model)?i.max_completion_tokens=-1===this.maxTokens?void 0:this.maxTokens:i.max_tokens=-1===this.maxTokens?void 0:this.maxTokens,i}_convertOpenAIChatCompletionMessageToBaseMessage(e,t){const n=e.tool_calls;if("assistant"===e.role){const r=[],s=[];for(const e of n??[])try{r.push(gf(e,{returnId:!0}))}catch(t){s.push(yf(e,t.message))}const i={function_call:e.function_call,tool_calls:n};void 0!==this.__includeRawResponse&&(i.__raw_response=t);const a={model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};return e.audio&&(i.audio=e.audio),new fn({content:e.content||"",tool_calls:r,invalid_tool_calls:s,additional_kwargs:i,response_metadata:a,id:t.id})}return new yn(e.content||"",e.role??"unknown")}_convertOpenAIDeltaToBaseMessageChunk(e,t,n){const r=e.role??n,s=e.content??"";let i;i=e.function_call?{function_call:e.function_call}:e.tool_calls?{tool_calls:e.tool_calls}:{},this.__includeRawResponse&&(i.__raw_response=t),e.audio&&(i.audio={...e.audio,index:t.choices[0].index});const a={usage:{...t.usage}};if("user"===r)return new En({content:s,response_metadata:a});if("assistant"===r){const n=[];if(Array.isArray(e.tool_calls))for(const t of e.tool_calls)n.push({name:t.function?.name,args:t.function?.arguments,id:t.id,index:t.index,type:"tool_call_chunk"});return new _n({content:s,tool_call_chunks:n,additional_kwargs:i,id:t.id,response_metadata:a})}return"system"===r?new kn({content:s,response_metadata:a}):"developer"===r?new kn({content:s,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):"function"===r?new bn({content:s,additional_kwargs:i,name:e.name,response_metadata:a}):"tool"===r?new pn({content:s,additional_kwargs:i,tool_call_id:e.tool_call_id,response_metadata:a}):new vn({content:s,role:r,response_metadata:a})}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}async*_streamResponseChunks(e,t,n){if(this._useResponseApi(t)){const n=await this.responseApiWithRetry({...this.invocationParams(t,{streaming:!0}),input:hm(e,this.model,this.zdrEnabled),stream:!0},t);for await(const e of n){const t=fm(e);null!=t&&(yield t)}return}const r=um(e,this.model),s={...this.invocationParams(t,{streaming:!0}),messages:r,stream:!0};let i;const a=await this.completionWithRetry(s,t);let o;for await(const e of a){const r=e?.choices?.[0];if(e.usage&&(o=e.usage),!r)continue;const{delta:s}=r;if(!s)continue;const a=this._convertOpenAIDeltaToBaseMessageChunk(s,e,i);i=s.role??i;const l={prompt:t.promptIndex??0,completion:r.index??0};if("string"!=typeof a.content)continue;const c={...l};null!=r.finish_reason&&(c.finish_reason=r.finish_reason,c.system_fingerprint=e.system_fingerprint,c.model_name=e.model,c.service_tier=e.service_tier),this.logprobs&&(c.logprobs=r.logprobs);const u=new Qi({message:a,text:a.content,generationInfo:c});yield u,await(n?.handleLLMNewToken(u.text??"",l,void 0,void 0,void 0,{chunk:u}))}if(o){const e={...null!==o.prompt_tokens_details?.audio_tokens&&{audio:o.prompt_tokens_details?.audio_tokens},...null!==o.prompt_tokens_details?.cached_tokens&&{cache_read:o.prompt_tokens_details?.cached_tokens}},t={...null!==o.completion_tokens_details?.audio_tokens&&{audio:o.completion_tokens_details?.audio_tokens},...null!==o.completion_tokens_details?.reasoning_tokens&&{reasoning:o.completion_tokens_details?.reasoning_tokens}},n=new Qi({message:new _n({content:"",response_metadata:{usage:{...o}},usage_metadata:{input_tokens:o.prompt_tokens,output_tokens:o.completion_tokens,total_tokens:o.total_tokens,...Object.keys(e).length>0&&{input_token_details:e},...Object.keys(t).length>0&&{output_token_details:t}}}),text:""});yield n}if(t.signal?.aborted)throw new Error("AbortError")}identifyingParams(){return this._identifyingParams()}async _responseApiGenerate(e,t,n){const r=this.invocationParams(t);if(r.stream){const r=this._streamResponseChunks(e,t,n);let s;for await(const e of r)e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},s=s?.concat(e)??e;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}const s=hm(e,this.model,this.zdrEnabled),i=await this.responseApiWithRetry({input:s,...r},{signal:t?.signal,...t?.options});return{generations:[{text:i.output_text,message:pm(i)}],llmOutput:{id:i.id,estimatedTokenUsage:i.usage?{promptTokens:i.usage.input_tokens,completionTokens:i.usage.output_tokens,totalTokens:i.usage.total_tokens}:void 0}}}_useResponseApi(e){const t=e?.tools?.some(mm),n=null!=e?.previous_response_id||null!=e?.text||null!=e?.truncation||null!=e?.include||null!=e?.reasoning?.summary||null!=this.reasoning?.summary;return this.useResponsesApi||t||n}async _generate(e,t,n){if(this._useResponseApi(t))return this._responseApiGenerate(e,t,n);const r={},s=this.invocationParams(t),i=um(e,this.model);if(s.stream){const s=this._streamResponseChunks(e,t,n),i={};for await(const e of s){e.message.response_metadata={...e.generationInfo,...e.message.response_metadata};const t=e.generationInfo?.completion??0;void 0===i[t]?i[t]=e:i[t]=i[t].concat(e)}const a=Object.entries(i).sort(([e],[t])=>parseInt(e,10)-parseInt(t,10)).map(([e,t])=>t),{functions:o,function_call:l}=this.invocationParams(t),c=await this.getEstimatedTokenCountFromPrompt(e,o,l),u=await this.getNumTokensFromGenerations(a);return r.input_tokens=c,r.output_tokens=u,r.total_tokens=c+u,{generations:a,llmOutput:{estimatedTokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}{let e;e=t.response_format&&"json_schema"===t.response_format.type?await this.betaParsedCompletionWithRetry({...s,stream:!1,messages:i},{signal:t?.signal,...t?.options}):await this.completionWithRetry({...s,stream:!1,messages:i},{signal:t?.signal,...t?.options});const{completion_tokens:n,prompt_tokens:a,total_tokens:o,prompt_tokens_details:l,completion_tokens_details:c}=e?.usage??{};n&&(r.output_tokens=(r.output_tokens??0)+n),a&&(r.input_tokens=(r.input_tokens??0)+a),o&&(r.total_tokens=(r.total_tokens??0)+o),null===l?.audio_tokens&&null===l?.cached_tokens||(r.input_token_details={...null!==l?.audio_tokens&&{audio:l?.audio_tokens},...null!==l?.cached_tokens&&{cache_read:l?.cached_tokens}}),null===c?.audio_tokens&&null===c?.reasoning_tokens||(r.output_token_details={...null!==c?.audio_tokens&&{audio:c?.audio_tokens},...null!==c?.reasoning_tokens&&{reasoning:c?.reasoning_tokens}});const u=[];for(const t of e?.choices??[]){const n={text:t.message?.content??"",message:this._convertOpenAIChatCompletionMessageToBaseMessage(t.message??{role:"assistant"},e)};n.generationInfo={...t.finish_reason?{finish_reason:t.finish_reason}:{},...t.logprobs?{logprobs:t.logprobs}:{}},mn(n.message)&&(n.message.usage_metadata=r),n.message=new fn(Object.fromEntries(Object.entries(n.message).filter(([e])=>!e.startsWith("lc_")))),u.push(n)}return{generations:u,llmOutput:{tokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}}async getEstimatedTokenCountFromPrompt(e,t,n){let r=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&"auto"!==n){const e=function(e){const t=["namespace functions {",""];for(const n of e)n.description&&t.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(t.push(`type ${n.name} = (_: {`),t.push(am(n.parameters,0)),t.push("}) => any;")):t.push(`type ${n.name} = () => any;`),t.push("");return t.push("} // namespace functions"),t.join("\n")}(t);r+=await this.getNumTokens(e),r+=9}return t&&e.find(e=>"system"===e._getType())&&(r-=4),"none"===n?r+=1:"object"==typeof n&&(r+=await this.getNumTokens(n.name)+4),r}async getNumTokensFromGenerations(e){return(await Promise.all(e.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,t)=>e+t,0)}async getNumTokensFromMessages(e){let t=0,n=0,r=0;"gpt-3.5-turbo-0301"===this.model?(n=4,r=-1):(n=3,r=1);const s=await Promise.all(e.map(async e=>{const s=await this.getNumTokens(e.content),i=await this.getNumTokens(lm(e)),a=void 0!==e.name?r+await this.getNumTokens(e.name):0;let o=s+n+i+a;const l=e;if("function"===l._getType()&&(o-=2),l.additional_kwargs?.function_call&&(o+=3),l?.additional_kwargs.function_call?.name&&(o+=await this.getNumTokens(l.additional_kwargs.function_call?.name)),l.additional_kwargs.function_call?.arguments)try{o+=await this.getNumTokens(JSON.stringify(JSON.parse(l.additional_kwargs.function_call?.arguments)))}catch(e){o+=await this.getNumTokens(l.additional_kwargs.function_call?.arguments)}return t+=o,o}));return t+=3,{totalCount:t,countPerMessage:s}}async completionWithRetry(e,t){const n=this._getClientOptions(t);return this.caller.call(async()=>{try{return await this.client.chat.completions.create(e,n)}catch(e){throw sm(e)}})}async responseApiWithRetry(e,t){return this.caller.call(async()=>{const n=this._getClientOptions(t);try{return"json_schema"!==e.text?.format?.type||e.stream?await this.client.responses.create(e,n):await this.client.responses.parse(e,n)}catch(e){throw sm(e)}})}async betaParsedCompletionWithRetry(e,t){const n=this._getClientOptions(t);return this.caller.call(async()=>{try{return await this.client.chat.completions.parse(e,n)}catch(e){throw sm(e)}})}_getClientOptions(e){if(!this.client){const e=Qf({baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,this.client=new kp(t)}return{...this.clientConfig,...e}}_llmType(){return"openai"}_combineLLMOutput(...e){return e.reduce((e,t)=>(t&&t.tokenUsage&&(e.tokenUsage.completionTokens+=t.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=t.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=t.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}withStructuredOutput(e,t){let n,r,s,i,a,o;if(!function(e){return void 0!==e&&"object"==typeof e.schema}(e)?(n=e,r=t?.name,s=t?.method,i=t?.includeRaw):(n=e.schema,r=e.name,s=e.method,i=e.includeRaw),void 0!==t?.strict&&"jsonMode"===s)throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");if(this.model.startsWith("gpt-3")||this.model.startsWith("gpt-4-")||"gpt-4"===this.model||void 0===s&&(s="jsonSchema"),"jsonMode"===s){let e;Qo(n)?(o=ff.fromZodSchema(n),e=ol(n)):o=new mf,a=this.withConfig({response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"jsonMode"},schema:e}})}else if("jsonSchema"===s)if(a=this.withConfig({response_format:{type:"json_schema",json_schema:{name:r??"extract",description:nl(n),schema:n,strict:t?.strict}},ls_structured_output_format:{kwargs:{method:"jsonSchema"},schema:ol(n)}}),Qo(n)){const e=ff.fromZodSchema(n);o=xl.from(t=>"parsed"in t.additional_kwargs?t.additional_kwargs.parsed:e)}else o=new mf;else{let e=r??"extract";if(Qo(n)){const r=ol(n);a=this.withConfig({tools:[{type:"function",function:{name:e,description:r.description,parameters:r}}],tool_choice:{type:"function",function:{name:e}},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:r},...void 0!==t?.strict?{strict:t.strict}:{}}),o=new bf({returnSingle:!0,keyName:e,zodSchema:n})}else{let r;"string"==typeof n.name&&"object"==typeof n.parameters&&null!=n.parameters?(r=n,e=n.name):(e=n.title??e,r={name:e,description:n.description??"",parameters:n}),a=this.withConfig({tools:[{type:"function",function:r}],tool_choice:{type:"function",function:{name:e}},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:ol(n)},...void 0!==t?.strict?{strict:t.strict}:{}}),o=new bf({returnSingle:!0,keyName:e})}}if(!i)return a.pipe(o);const l=af.assign({parsed:(e,t)=>o.invoke(e.raw,t)}),c=af.assign({parsed:()=>null}),u=l.withFallbacks({fallbacks:[c]});return El.from([{raw:a},u])}}class bm extends rf{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"}),Object.defineProperty(this,"defaultConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig}async invoke(e,t){let n,r=Mi(ji(this.defaultConfig,t));return On(e)?(n=e.args,r={...r,toolCall:e}):n=e,this.call(n,r)}async call(e,t,n){const r=On(e)?e.args:e;let s;if(Qo(this.schema))try{s=await tl(this.schema,r)}catch(t){let n="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(n=`${n}\nDetails: ${t.message}`),new Tn(n,JSON.stringify(e))}else{const t=Co(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 Tn(n,JSON.stringify(e))}s=r}const i=Ei(t),a=Ai.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 l,c,u,d;delete i.runId;try{l=await this._call(s,o,i)}catch(e){throw await(o?.handleToolError(e)),e}if("content_and_artifact"===this.responseFormat){if(!Array.isArray(l)||2!==l.length)throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(l)}`);[c,u]=l}else c=l;On(e)&&(d=e.id),!d&&function(e){return!!(e&&"object"==typeof e&&"toolCall"in e&&null!=e.toolCall&&"object"==typeof e.toolCall&&"id"in e.toolCall&&"string"==typeof e.toolCall.id)}(i)&&(d=i.toolCall.id);const h=function(e){const{content:t,artifact:n,toolCallId:r}=e;return r&&!function(e){return null!=e&&"object"==typeof e&&"lc_direct_tool_output"in e&&!0===e.lc_direct_tool_output}(t)?"string"==typeof t||Array.isArray(t)&&t.every(e=>"object"==typeof e)?new hn({content:t,artifact:n,tool_call_id:r,name:e.name}):new hn({content:Sm(t),artifact:n,tool_call_id:r,name:e.name}):t}({content:c,artifact:u,toolCallId:d,name:this.name});return await(o?.handleToolEnd(h)),h}}class wm extends bm{constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:He({input:De().optional()}).transform(e=>e.input)})}call(e,t){const n="string"==typeof e||null==e?{input:e}:e;return super.call(n,t)}}class Em extends bm{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=Ei(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)}}function Sm(e){try{return JSON.stringify(e,null,2)??""}catch(t){return`${e}`}}function km(e,t,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,n):s?s.value=n:t.set(e,n),n}function xm(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}Object.defineProperty(class extends wm{static lc_name(){return"DallEAPIWrapper"}constructor(e){void 0!==e?.responseFormat&&["url","b64_json"].includes(e.responseFormat)&&(e.dallEResponseFormat=e.responseFormat,e.responseFormat="content"),super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description."}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"dall-e-3"}),Object.defineProperty(this,"style",{enumerable:!0,configurable:!0,writable:!0,value:"vivid"}),Object.defineProperty(this,"quality",{enumerable:!0,configurable:!0,writable:!0,value:"standard"}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:"1024x1024"}),Object.defineProperty(this,"dallEResponseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"url"}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const t={apiKey:e?.apiKey??e?.openAIApiKey??Ys("OPENAI_API_KEY"),organization:e?.organization??Ys("OPENAI_ORGANIZATION"),dangerouslyAllowBrowser:!0,baseURL:e?.baseUrl};this.client=new kp(t),this.model=e?.model??e?.modelName??this.model,this.style=e?.style??this.style,this.quality=e?.quality??this.quality,this.n=e?.n??this.n,this.size=e?.size??this.size,this.dallEResponseFormat=e?.dallEResponseFormat??this.dallEResponseFormat,this.user=e?.user}processMultipleGeneratedUrls(e){return"url"===this.dallEResponseFormat?e.flatMap(e=>e.data?.flatMap(e=>e.url?{type:"image_url",image_url:e.url}:[]).filter(e=>void 0!==e&&"image_url"===e.type&&"string"==typeof e.image_url&&void 0!==e.image_url)??[]):e.flatMap(e=>e.data?.flatMap(e=>e.b64_json?{type:"image_url",image_url:{url:e.b64_json}}:[]).filter(e=>void 0!==e&&"image_url"===e.type&&"object"==typeof e.image_url&&"url"in e.image_url&&"string"==typeof e.image_url.url&&void 0!==e.image_url.url)??[])}async _call(e){const t={model:this.model,prompt:e,n:1,size:this.size,response_format:this.dallEResponseFormat,style:this.style,quality:this.quality,user:this.user};if(this.n>1){const e=await Promise.all(Array.from({length:this.n}).map(()=>this.client.images.generate(t)));return this.processMultipleGeneratedUrls(e)}const n=await this.client.images.generate(t);let r="";return"url"===this.dallEResponseFormat?[r]=n.data?.map(e=>e.url).filter(e=>"undefined"!==e)??[]:[r]=n.data?.map(e=>e.b64_json).filter(e=>"undefined"!==e)??[],r}},"toolName",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"});let Om=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return Om=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^n()&15>>+e/4).toString(16))};function Tm(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const Im=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class Am extends Error{}class Pm extends Am{constructor(e,t,n,r){super(`${Pm.makeMessage(e,t,n)}`),this.status=e,this.headers=r,this.requestID=r?.get("request-id"),this.error=t}static makeMessage(e,t,n){const r=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e||!r)return new $m({message:n,cause:Im(t)});const s=t;return 400===e?new Nm(e,s,n,r):401===e?new jm(e,s,n,r):403===e?new Lm(e,s,n,r):404===e?new Mm(e,s,n,r):409===e?new Dm(e,s,n,r):422===e?new Um(e,s,n,r):429===e?new Fm(e,s,n,r):e>=500?new Bm(e,s,n,r):new Pm(e,s,n,r)}}class Cm extends Pm{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class $m extends Pm{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Rm extends $m{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Nm extends Pm{}class jm extends Pm{}class Lm extends Pm{}class Mm extends Pm{}class Dm extends Pm{}class Um extends Pm{}class Fm extends Pm{}class Bm extends Pm{}const qm=/^[a-z][a-z0-9+.-]*:/i;let zm=e=>(zm=Array.isArray,zm(e)),Hm=zm;function Wm(e){return"object"!=typeof e?{}:e??{}}const Gm=e=>{try{return JSON.parse(e)}catch(e){return}},Km="0.56.0";const Jm=()=>{const e="undefined"!=typeof Deno&&null!=Deno.build?"deno":"undefined"!=typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Km,"X-Stainless-OS":Vm(Deno.build.os),"X-Stainless-Arch":Zm(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Km,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Km,"X-Stainless-OS":Vm(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Zm(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:n}of e){const e=n.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Km,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Km,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const Zm=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",Vm=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let Ym;function Xm(...e){const t=globalThis.ReadableStream;if(void 0===t)throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Qm(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Xm({start(){},async pull(e){const{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await(t.return?.())}})}function eg(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}const tg=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});let ng,rg;function sg(e){let t;return(ng??(t=new globalThis.TextEncoder,ng=t.encode.bind(t)))(e)}function ig(e){let t;return(rg??(t=new globalThis.TextDecoder,rg=t.decode.bind(t)))(e)}var ag,og;class lg{constructor(){ag.set(this,void 0),og.set(this,void 0),km(this,ag,new Uint8Array,"f"),km(this,og,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?sg(e):e;km(this,ag,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}([xm(this,ag,"f"),t]),"f");const n=[];let r;for(;null!=(r=cg(xm(this,ag,"f"),xm(this,og,"f")));){if(r.carriage&&null==xm(this,og,"f")){km(this,og,r.index,"f");continue}if(null!=xm(this,og,"f")&&(r.index!==xm(this,og,"f")+1||r.carriage)){n.push(ig(xm(this,ag,"f").subarray(0,xm(this,og,"f")-1))),km(this,ag,xm(this,ag,"f").subarray(xm(this,og,"f")),"f"),km(this,og,null,"f");continue}const e=null!==xm(this,og,"f")?r.preceding-1:r.preceding,t=ig(xm(this,ag,"f").subarray(0,e));n.push(t),km(this,ag,xm(this,ag,"f").subarray(r.index),"f"),km(this,og,null,"f")}return n}flush(){return xm(this,ag,"f").length?this.decode("\n"):[]}}function cg(e,t){for(let n=t??0;n{if(e)return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(dg,e)?e:void _g(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(dg))}`)};function pg(){}function fg(e,t,n){return!t||dg[e]>dg[n]?pg:t[e].bind(t)}const mg={error:pg,warn:pg,info:pg,debug:pg};let gg=new WeakMap;function _g(e){const t=e.logger,n=e.logLevel??"off";if(!t)return mg;const r=gg.get(t);if(r&&r[0]===n)return r[1];const s={error:fg("error",t,n),warn:fg("warn",t,n),info:fg("info",t,n),debug:fg("debug",t,n)};return gg.set(t,[n,s]),s}const yg=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"x-api-key"===e.toLowerCase()||"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var vg,bg,wg;class Eg{constructor(e,t,n){this.iterator=e,vg.set(this,void 0),this.controller=t,km(this,vg,n,"f")}static fromSSEResponse(e,t,n){let r=!1;const s=n?_g(n):console;return new Eg(async function*(){if(r)throw new Am("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let n=!1;try{for await(const n of async function*(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new Am("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new Am("Attempted to iterate over a response with no body")}const n=new Sg,r=new lg,s=eg(e.body);for await(const e of async function*(e){let t=new Uint8Array;for await(const n of e){if(null==n)continue;const e=n instanceof ArrayBuffer?new Uint8Array(n):"string"==typeof n?sg(n):n;let r,s=new Uint8Array(t.length+e.length);for(s.set(t),s.set(e,t.length),t=s;-1!==(r=ug(t));)yield t.slice(0,r),t=t.slice(r)}t.length>0&&(yield t)}(s))for(const t of r.decode(e)){const e=n.decode(t);e&&(yield e)}for(const e of r.flush()){const t=n.decode(e);t&&(yield t)}}(e,t)){if("completion"===n.event)try{yield JSON.parse(n.data)}catch(e){throw s.error("Could not parse message into JSON:",n.data),s.error("From chunk:",n.raw),e}if("message_start"===n.event||"message_delta"===n.event||"message_stop"===n.event||"content_block_start"===n.event||"content_block_delta"===n.event||"content_block_stop"===n.event)try{yield JSON.parse(n.data)}catch(e){throw s.error("Could not parse message into JSON:",n.data),s.error("From chunk:",n.raw),e}if("ping"!==n.event&&"error"===n.event)throw new Pm(void 0,Gm(n.data)??n.data,void 0,e.headers)}n=!0}catch(e){if(Tm(e))return;throw e}finally{n||t.abort()}},t,n)}static fromReadableStream(e,t,n){let r=!1;return new Eg(async function*(){if(r)throw new Am("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let n=!1;try{for await(const t of async function*(){const t=new lg,n=eg(e);for await(const e of n)for(const n of t.decode(e))yield n;for(const e of t.flush())yield e}())n||t&&(yield JSON.parse(t));n=!0}catch(e){if(Tm(e))return;throw e}finally{n||t.abort()}},t,n)}[(vg=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),r=r=>({next:()=>{if(0===r.length){const r=n.next();e.push(r),t.push(r)}return r.shift()}});return[new Eg(()=>r(e),this.controller,xm(this,vg,"f")),new Eg(()=>r(t),this.controller,xm(this,vg,"f"))]}toReadableStream(){const e=this;let t;return Xm({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:n,done:r}=await t.next();if(r)return e.close();const s=sg(JSON.stringify(n)+"\n");e.enqueue(s)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class Sg{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,r]=function(e,t){const n=e.indexOf(t);if(-1!==n)return[e.substring(0,n),t,e.substring(n+t.length)];return[e,"",""]}(e,":");return r.startsWith(" ")&&(r=r.substring(1)),"event"===t?this.event=r:"data"===t&&this.data.push(r),null}}async function kg(e,t){const{response:n,requestLogID:r,retryOfRequestLogID:s,startTime:i}=t,a=await(async()=>{if(t.options.stream)return _g(e).debug("response",n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e):Eg.fromSSEResponse(n,t.controller,e);if(204===n.status)return null;if(t.options.__binaryResponse)return n;const r=n.headers.get("content-type"),s=r?.split(";")[0]?.trim();if(s?.includes("application/json")||s?.endsWith("+json")){return xg(await n.json(),n)}return await n.text()})();return _g(e).debug(`[${r}] response parsed`,yg({retryOfRequestLogID:s,url:n.url,status:n.status,body:a,durationMs:Date.now()-i})),a}function xg(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("request-id"),enumerable:!1})}class Og extends Promise{constructor(e,t,n=kg){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,bg.set(this,void 0),km(this,bg,e,"f")}_thenUnwrap(e){return new Og(xm(this,bg,"f"),this.responsePromise,async(t,n)=>xg(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(xm(this,bg,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}bg=new WeakMap;class Tg{constructor(e,t,n,r){wg.set(this,void 0),km(this,wg,e,"f"),this.options=r,this.response=t,this.body=n}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new Am("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await xm(this,wg,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(wg=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Ig extends Og{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await kg(e,t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}class Ag extends Tg{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){const e=this.first_id;return e?{...this.options,query:{...Wm(this.options.query),before_id:e}}:null}const e=this.last_id;return e?{...this.options,query:{...Wm(this.options.query),after_id:e}}:null}}const Pg=()=>{if("undefined"==typeof File){const{process:e}=globalThis,t="string"==typeof e?.versions?.node&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Cg(e,t,n){return Pg(),new File(e,t??"unknown_file",n)}function $g(e){return("object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}const Rg=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],Ng=new WeakMap;const jg=async(e,t)=>{if(!await function(e){const t="function"==typeof e?e:e.fetch,n=Ng.get(t);if(n)return n;const r=(async()=>{try{const e="Response"in t?t.Response:(await t("data:,")).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return Ng.set(t,r),r}(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>Mg(n,e,t))),n},Lg=e=>e instanceof Blob&&"name"in e,Mg=async(e,t,n)=>{if(void 0!==n){if(null==n)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)e.append(t,String(n));else if(n instanceof Response){let r={};const s=n.headers.get("Content-Type");s&&(r={type:s}),e.append(t,Cg([await n.blob()],$g(n),r))}else if(Rg(n))e.append(t,Cg([await new Response(Qm(n)).blob()],$g(n)));else if(Lg(n))e.append(t,Cg([n],$g(n),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(n=>Mg(e,t+"[]",n)));else{if("object"!=typeof n)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`);await Promise.all(Object.entries(n).map(([n,r])=>Mg(e,`${t}[${n}]`,r)))}}},Dg=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function Ug(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Dg(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!Rg(e)){const t=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";const t=Object.getOwnPropertyNames(e);return`; props: [${t.map(e=>`"${e}"`).join(", ")}]`}(e)}`)}for await(const n of e)t.push(...await Ug(n))}return t}class Fg{constructor(e){this._client=e}}const Bg=Symbol.for("brand.privateNullableHeaders");function*qg(e){if(!e)return;if(Bg in e){const{values:t,nulls:n}=e;yield*t.entries();for(const e of n)yield[e,null];return}let t,n=!1;e instanceof Headers?t=e.entries():Hm(e)?t=e:(n=!0,t=Object.entries(e??{}));for(let e of t){const t=e[0];if("string"!=typeof t)throw new TypeError("expected header name to be a string");const r=Hm(e[1])?e[1]:[e[1]];let s=!1;for(const e of r)void 0!==e&&(n&&!s&&(s=!0,yield[t,null]),yield[t,e])}}const zg=e=>{const t=new Headers,n=new Set;for(const r of e){const e=new Set;for(const[s,i]of qg(r)){const r=s.toLowerCase();e.has(r)||(t.delete(s),e.add(r)),null===i?(t.delete(s),n.add(r)):(t.append(s,i),n.delete(r))}}return{[Bg]:!0,values:t,nulls:n}};function Hg(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Wg=Object.freeze(Object.create(null)),Gg=(e=Hg)=>function(t,...n){if(1===t.length)return t[0];let r=!1;const s=[],i=t.reduce((t,i,a)=>{/[?#]/.test(i)&&(r=!0);const o=n[a];let l=(r?encodeURIComponent:e)(""+o);return a!==n.length&&(null==o||"object"==typeof o&&o.toString===Object.getPrototypeOf(Object.getPrototypeOf(o.hasOwnProperty??Wg)??Wg)?.toString)&&(l=o+"",s.push({start:t.length+i.length,length:l.length,error:`Value of type ${Object.prototype.toString.call(o).slice(8,-1)} is not a valid path parameter`})),t+i+(a===n.length?"":l)},""),a=i.split(/[?#]/,1)[0],o=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let l;for(;null!==(l=o.exec(a));)s.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(s.sort((e,t)=>e.start-t.start),s.length>0){let e=0;const t=s.reduce((t,n)=>{const r=" ".repeat(n.start-e),s="^".repeat(n.length);return e=n.start+n.length,t+r+s},"");throw new Am(`Path parameters result in path with invalid segments:\n${s.map(e=>e.error).join("\n")}\n${i}\n${t}`)}return i},Kg=Gg(Hg);class Jg extends Fg{list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/files",Ag,{query:r,...t,headers:zg([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},n){const{betas:r}=t??{};return this._client.delete(Kg`/v1/files/${e}`,{...n,headers:zg([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,t={},n){const{betas:r}=t??{};return this._client.get(Kg`/v1/files/${e}/content`,{...n,headers:zg([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){const{betas:r}=t??{};return this._client.get(Kg`/v1/files/${e}`,{...n,headers:zg([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}upload(e,t){const{betas:n,...r}=e;return this._client.post("/v1/files",(async(e,t)=>({...e,body:await jg(e.body,t)}))({body:r,...t,headers:zg([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},t?.headers])},this._client))}}class Zg extends Fg{retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Kg`/v1/models/${e}?beta=true`,{...n,headers:zg([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/models?beta=true",Ag,{query:r,...t,headers:zg([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}}class Vg{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new lg;for await(const t of this.iterator)for(const n of e.decode(t))yield JSON.parse(n);for(const t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new Am("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new Am("Attempted to iterate over a response with no body")}return new Vg(eg(e.body),t)}}class Yg extends Fg{create(e,t){const{betas:n,...r}=e;return this._client.post("/v1/messages/batches?beta=true",{body:r,...t,headers:zg([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Kg`/v1/messages/batches/${e}?beta=true`,{...n,headers:zg([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Ag,{query:r,...t,headers:zg([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},n){const{betas:r}=t??{};return this._client.delete(Kg`/v1/messages/batches/${e}?beta=true`,{...n,headers:zg([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,t={},n){const{betas:r}=t??{};return this._client.post(Kg`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:zg([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}async results(e,t={},n){const r=await this.retrieve(e);if(!r.results_url)throw new Am(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);const{betas:s}=t??{};return this._client.get(r.results_url,{...n,headers:zg([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>Vg.fromResponse(t.response,t.controller))}}const Xg=e=>{if(0===e.length)return e;let t=e[e.length-1];switch(t.type){case"separator":return e=e.slice(0,e.length-1),Xg(e);case"number":let n=t.value[t.value.length-1];if("."===n||"-"===n)return e=e.slice(0,e.length-1),Xg(e);case"string":let r=e[e.length-2];if("delimiter"===r?.type)return e=e.slice(0,e.length-1),Xg(e);if("brace"===r?.type&&"{"===r.value)return e=e.slice(0,e.length-1),Xg(e);break;case"delimiter":return e=e.slice(0,e.length-1),Xg(e)}return e},Qg=e=>JSON.parse((e=>{let t="";return e.map(e=>{"string"===e.type?t+='"'+e.value+'"':t+=e.value}),t})((e=>{let t=[];return e.map(e=>{"brace"===e.type&&("{"===e.value?t.push("}"):t.splice(t.lastIndexOf("}"),1)),"paren"===e.type&&("["===e.value?t.push("]"):t.splice(t.lastIndexOf("]"),1))}),t.length>0&&t.reverse().map(t=>{"}"===t?e.push({type:"brace",value:"}"}):"]"===t&&e.push({type:"paren",value:"]"})}),e})(Xg((e=>{let t=0,n=[];for(;t{}),s_.set(this,()=>{}),i_.set(this,void 0),a_.set(this,()=>{}),o_.set(this,()=>{}),l_.set(this,{}),c_.set(this,!1),u_.set(this,!1),d_.set(this,!1),h_.set(this,!1),p_.set(this,void 0),f_.set(this,void 0),__.set(this,e=>{if(km(this,u_,!0,"f"),Tm(e)&&(e=new Cm),e instanceof Cm)return km(this,d_,!0,"f"),this._emit("abort",e);if(e instanceof Am)return this._emit("error",e);if(e instanceof Error){const t=new Am(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Am(String(e)))}),km(this,n_,new Promise((e,t)=>{km(this,r_,e,"f"),km(this,s_,t,"f")}),"f"),km(this,i_,new Promise((e,t)=>{km(this,a_,e,"f"),km(this,o_,t,"f")}),"f"),xm(this,n_,"f").catch(()=>{}),xm(this,i_,"f").catch(()=>{})}get response(){return xm(this,p_,"f")}get request_id(){return xm(this,f_,"f")}async withResponse(){const e=await xm(this,n_,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new k_;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){const r=new k_;for(const e of t.messages)r._addMessageParam(e);return r._run(()=>r._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},xm(this,__,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){const r=n?.signal;let s;r&&(r.aborted&&this.controller.abort(),s=this.controller.abort.bind(this.controller),r.addEventListener("abort",s));try{xm(this,e_,"m",y_).call(this);const{response:r,data:s}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(const e of s)xm(this,e_,"m",v_).call(this,e);if(s.controller.signal?.aborted)throw new Cm;xm(this,e_,"m",b_).call(this)}finally{r&&s&&r.removeEventListener("abort",s)}}_connected(e){this.ended||(km(this,p_,e,"f"),km(this,f_,e?.headers.get("request-id"),"f"),xm(this,r_,"f").call(this,e),this._emit("connect"))}get ended(){return xm(this,c_,"f")}get errored(){return xm(this,u_,"f")}get aborted(){return xm(this,d_,"f")}abort(){this.controller.abort()}on(e,t){return(xm(this,l_,"f")[e]||(xm(this,l_,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=xm(this,l_,"f")[e];if(!n)return this;const r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(xm(this,l_,"f")[e]||(xm(this,l_,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{km(this,h_,!0,"f"),"error"!==e&&this.once("error",n),this.once(e,t)})}async done(){km(this,h_,!0,"f"),await xm(this,i_,"f")}get currentMessage(){return xm(this,t_,"f")}async finalMessage(){return await this.done(),xm(this,e_,"m",m_).call(this)}async finalText(){return await this.done(),xm(this,e_,"m",g_).call(this)}_emit(e,...t){if(xm(this,c_,"f"))return;"end"===e&&(km(this,c_,!0,"f"),xm(this,a_,"f").call(this));const n=xm(this,l_,"f")[e];if(n&&(xm(this,l_,"f")[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return xm(this,h_,"f")||n?.length||Promise.reject(e),xm(this,s_,"f").call(this,e),xm(this,o_,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];xm(this,h_,"f")||n?.length||Promise.reject(e),xm(this,s_,"f").call(this,e),xm(this,o_,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",xm(this,e_,"m",m_).call(this))}async _fromReadableStream(e,t){const n=t?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{xm(this,e_,"m",y_).call(this),this._connected(null);const t=Eg.fromReadableStream(e,this.controller);for await(const e of t)xm(this,e_,"m",v_).call(this,e);if(t.controller.signal?.aborted)throw new Cm;xm(this,e_,"m",b_).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(t_=new WeakMap,n_=new WeakMap,r_=new WeakMap,s_=new WeakMap,i_=new WeakMap,a_=new WeakMap,o_=new WeakMap,l_=new WeakMap,c_=new WeakMap,u_=new WeakMap,d_=new WeakMap,h_=new WeakMap,p_=new WeakMap,f_=new WeakMap,__=new WeakMap,e_=new WeakSet,m_=function(){if(0===this.receivedMessages.length)throw new Am("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},g_=function(){if(0===this.receivedMessages.length)throw new Am("stream ended without producing a Message with role=assistant");const e=this.receivedMessages.at(-1).content.filter(e=>"text"===e.type).map(e=>e.text);if(0===e.length)throw new Am("stream ended without producing a content block with type=text");return e.join(" ")},y_=function(){this.ended||km(this,t_,void 0,"f")},v_=function(e){if(this.ended)return;const t=xm(this,e_,"m",w_).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{const n=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===n.type&&this._emit("text",e.delta.text,n.text||"");break;case"citations_delta":"text"===n.type&&this._emit("citation",e.delta.citation,n.citations??[]);break;case"input_json_delta":S_(n)&&n.input&&this._emit("inputJson",e.delta.partial_json,n.input);break;case"thinking_delta":"thinking"===n.type&&this._emit("thinking",e.delta.thinking,n.thinking);break;case"signature_delta":"thinking"===n.type&&this._emit("signature",n.signature);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(t,!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":km(this,t_,t,"f")}},b_=function(){if(this.ended)throw new Am("stream has ended, this shouldn't happen");const e=xm(this,t_,"f");if(!e)throw new Am("request ended without sending any chunks");return km(this,t_,void 0,"f"),e},w_=function(e){let t=xm(this,t_,"f");if("message_start"===e.type){if(t)throw new Am(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new Am(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.container=e.delta.container,t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,null!=e.usage.input_tokens&&(t.usage.input_tokens=e.usage.input_tokens),null!=e.usage.cache_creation_input_tokens&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),null!=e.usage.cache_read_input_tokens&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),null!=e.usage.server_tool_use&&(t.usage.server_tool_use=e.usage.server_tool_use),t;case"content_block_start":return t.content.push(e.content_block),t;case"content_block_delta":{const n=t.content.at(e.index);switch(e.delta.type){case"text_delta":"text"===n?.type&&(t.content[e.index]={...n,text:(n.text||"")+e.delta.text});break;case"citations_delta":"text"===n?.type&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case"input_json_delta":if(n&&S_(n)){let r=n[E_]||"";r+=e.delta.partial_json;const s={...n};if(Object.defineProperty(s,E_,{value:r,enumerable:!1,writable:!0}),r)try{s.input=Qg(r)}catch(e){const t=new Am(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${e}. JSON: ${r}`);xm(this,__,"f").call(this,t)}t.content[e.index]=s}break;case"thinking_delta":"thinking"===n?.type&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case"signature_delta":"thinking"===n?.type&&(t.content[e.index]={...n,signature:e.delta.signature});break;default:e.delta}return t}}},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("streamEvent",n=>{const r=t.shift();r?r.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Eg(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}const x_={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192};class O_ extends Fg{constructor(){super(...arguments),this.batches=new Yg(this._client)}create(e,t){const{betas:n,...r}=e;r.model;let s=this._client._options.timeout;if(!r.stream&&null==s){const e=x_[r.model]??void 0;s=this._client.calculateNonstreamingTimeout(r.max_tokens,e)}return this._client.post("/v1/messages?beta=true",{body:r,timeout:s??6e5,...t,headers:zg([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}stream(e,t){return k_.createMessage(this,e,t)}countTokens(e,t){const{betas:n,...r}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:r,...t,headers:zg([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},t?.headers])})}}O_.Batches=Yg;class T_ extends Fg{constructor(){super(...arguments),this.models=new Zg(this._client),this.messages=new O_(this._client),this.files=new Jg(this._client)}}T_.Models=Zg,T_.Messages=O_,T_.Files=Jg;class I_ extends Fg{create(e,t){const{betas:n,...r}=e;return this._client.post("/v1/complete",{body:r,timeout:this._client._options.timeout??6e5,...t,headers:zg([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}}var A_,P_,C_,$_,R_,N_,j_,L_,M_,D_,U_,F_,B_,q_,z_,H_,W_,G_,K_,J_,Z_,V_;const Y_="__json_buf";function X_(e){return"tool_use"===e.type||"server_tool_use"===e.type}class Q_{constructor(){A_.add(this),this.messages=[],this.receivedMessages=[],P_.set(this,void 0),this.controller=new AbortController,C_.set(this,void 0),$_.set(this,()=>{}),R_.set(this,()=>{}),N_.set(this,void 0),j_.set(this,()=>{}),L_.set(this,()=>{}),M_.set(this,{}),D_.set(this,!1),U_.set(this,!1),F_.set(this,!1),B_.set(this,!1),q_.set(this,void 0),z_.set(this,void 0),G_.set(this,e=>{if(km(this,U_,!0,"f"),Tm(e)&&(e=new Cm),e instanceof Cm)return km(this,F_,!0,"f"),this._emit("abort",e);if(e instanceof Am)return this._emit("error",e);if(e instanceof Error){const t=new Am(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Am(String(e)))}),km(this,C_,new Promise((e,t)=>{km(this,$_,e,"f"),km(this,R_,t,"f")}),"f"),km(this,N_,new Promise((e,t)=>{km(this,j_,e,"f"),km(this,L_,t,"f")}),"f"),xm(this,C_,"f").catch(()=>{}),xm(this,N_,"f").catch(()=>{})}get response(){return xm(this,q_,"f")}get request_id(){return xm(this,z_,"f")}async withResponse(){const e=await xm(this,C_,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new Q_;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){const r=new Q_;for(const e of t.messages)r._addMessageParam(e);return r._run(()=>r._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},xm(this,G_,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){const r=n?.signal;let s;r&&(r.aborted&&this.controller.abort(),s=this.controller.abort.bind(this.controller),r.addEventListener("abort",s));try{xm(this,A_,"m",K_).call(this);const{response:r,data:s}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(const e of s)xm(this,A_,"m",J_).call(this,e);if(s.controller.signal?.aborted)throw new Cm;xm(this,A_,"m",Z_).call(this)}finally{r&&s&&r.removeEventListener("abort",s)}}_connected(e){this.ended||(km(this,q_,e,"f"),km(this,z_,e?.headers.get("request-id"),"f"),xm(this,$_,"f").call(this,e),this._emit("connect"))}get ended(){return xm(this,D_,"f")}get errored(){return xm(this,U_,"f")}get aborted(){return xm(this,F_,"f")}abort(){this.controller.abort()}on(e,t){return(xm(this,M_,"f")[e]||(xm(this,M_,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=xm(this,M_,"f")[e];if(!n)return this;const r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(xm(this,M_,"f")[e]||(xm(this,M_,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{km(this,B_,!0,"f"),"error"!==e&&this.once("error",n),this.once(e,t)})}async done(){km(this,B_,!0,"f"),await xm(this,N_,"f")}get currentMessage(){return xm(this,P_,"f")}async finalMessage(){return await this.done(),xm(this,A_,"m",H_).call(this)}async finalText(){return await this.done(),xm(this,A_,"m",W_).call(this)}_emit(e,...t){if(xm(this,D_,"f"))return;"end"===e&&(km(this,D_,!0,"f"),xm(this,j_,"f").call(this));const n=xm(this,M_,"f")[e];if(n&&(xm(this,M_,"f")[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return xm(this,B_,"f")||n?.length||Promise.reject(e),xm(this,R_,"f").call(this,e),xm(this,L_,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];xm(this,B_,"f")||n?.length||Promise.reject(e),xm(this,R_,"f").call(this,e),xm(this,L_,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",xm(this,A_,"m",H_).call(this))}async _fromReadableStream(e,t){const n=t?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{xm(this,A_,"m",K_).call(this),this._connected(null);const t=Eg.fromReadableStream(e,this.controller);for await(const e of t)xm(this,A_,"m",J_).call(this,e);if(t.controller.signal?.aborted)throw new Cm;xm(this,A_,"m",Z_).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(P_=new WeakMap,C_=new WeakMap,$_=new WeakMap,R_=new WeakMap,N_=new WeakMap,j_=new WeakMap,L_=new WeakMap,M_=new WeakMap,D_=new WeakMap,U_=new WeakMap,F_=new WeakMap,B_=new WeakMap,q_=new WeakMap,z_=new WeakMap,G_=new WeakMap,A_=new WeakSet,H_=function(){if(0===this.receivedMessages.length)throw new Am("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},W_=function(){if(0===this.receivedMessages.length)throw new Am("stream ended without producing a Message with role=assistant");const e=this.receivedMessages.at(-1).content.filter(e=>"text"===e.type).map(e=>e.text);if(0===e.length)throw new Am("stream ended without producing a content block with type=text");return e.join(" ")},K_=function(){this.ended||km(this,P_,void 0,"f")},J_=function(e){if(this.ended)return;const t=xm(this,A_,"m",V_).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{const n=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===n.type&&this._emit("text",e.delta.text,n.text||"");break;case"citations_delta":"text"===n.type&&this._emit("citation",e.delta.citation,n.citations??[]);break;case"input_json_delta":X_(n)&&n.input&&this._emit("inputJson",e.delta.partial_json,n.input);break;case"thinking_delta":"thinking"===n.type&&this._emit("thinking",e.delta.thinking,n.thinking);break;case"signature_delta":"thinking"===n.type&&this._emit("signature",n.signature);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(t,!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":km(this,P_,t,"f")}},Z_=function(){if(this.ended)throw new Am("stream has ended, this shouldn't happen");const e=xm(this,P_,"f");if(!e)throw new Am("request ended without sending any chunks");return km(this,P_,void 0,"f"),e},V_=function(e){let t=xm(this,P_,"f");if("message_start"===e.type){if(t)throw new Am(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new Am(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,null!=e.usage.input_tokens&&(t.usage.input_tokens=e.usage.input_tokens),null!=e.usage.cache_creation_input_tokens&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),null!=e.usage.cache_read_input_tokens&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),null!=e.usage.server_tool_use&&(t.usage.server_tool_use=e.usage.server_tool_use),t;case"content_block_start":return t.content.push({...e.content_block}),t;case"content_block_delta":{const n=t.content.at(e.index);switch(e.delta.type){case"text_delta":"text"===n?.type&&(t.content[e.index]={...n,text:(n.text||"")+e.delta.text});break;case"citations_delta":"text"===n?.type&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case"input_json_delta":if(n&&X_(n)){let r=n[Y_]||"";r+=e.delta.partial_json;const s={...n};Object.defineProperty(s,Y_,{value:r,enumerable:!1,writable:!0}),r&&(s.input=Qg(r)),t.content[e.index]=s}break;case"thinking_delta":"thinking"===n?.type&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case"signature_delta":"thinking"===n?.type&&(t.content[e.index]={...n,signature:e.delta.signature});break;default:e.delta}return t}}},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("streamEvent",n=>{const r=t.shift();r?r.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Eg(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class ey extends Fg{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(Kg`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",Ag,{query:e,...t})}delete(e,t){return this._client.delete(Kg`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(Kg`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){const n=await this.retrieve(e);if(!n.results_url)throw new Am(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:zg([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>Vg.fromResponse(t.response,t.controller))}}class ty extends Fg{constructor(){super(...arguments),this.batches=new ey(this._client)}create(e,t){e.model;let n=this._client._options.timeout;if(!e.stream&&null==n){const t=x_[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,t)}return this._client.post("/v1/messages",{body:e,timeout:n??6e5,...t,stream:e.stream??!1})}stream(e,t){return Q_.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}ty.Batches=ey;class ny extends Fg{retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Kg`/v1/models/${e}`,{...n,headers:zg([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/models",Ag,{query:r,...t,headers:zg([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}}const ry=e=>void 0!==globalThis.process?globalThis.process.env?.[e]?.trim()??void 0:void 0!==globalThis.Deno?globalThis.Deno.env?.get?.(e)?.trim():void 0;var sy,iy,ay,oy;class ly{constructor({baseURL:e=ry("ANTHROPIC_BASE_URL"),apiKey:t=ry("ANTHROPIC_API_KEY")??null,authToken:n=ry("ANTHROPIC_AUTH_TOKEN")??null,...r}={}){sy.add(this),ay.set(this,void 0);const s={apiKey:t,authToken:n,...r,baseURL:e||"https://api.anthropic.com"};if(!s.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new Am("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");this.baseURL=s.baseURL,this.timeout=s.timeout??iy.DEFAULT_TIMEOUT,this.logger=s.logger??console;const i="warn";this.logLevel=i,this.logLevel=hg(s.logLevel,"ClientOptions.logLevel",this)??hg(ry("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??i,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??function(){if("undefined"!=typeof fetch)return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),km(this,ay,tg,"f"),this._options=s,this.apiKey=t,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(this.apiKey&&e.get("x-api-key")||t.has("x-api-key")||this.authToken&&e.get("authorization")||t.has("authorization")))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders(e){return zg([this.apiKeyAuth(e),this.bearerAuth(e)])}apiKeyAuth(e){if(null!=this.apiKey)return zg([{"X-Api-Key":this.apiKey}])}bearerAuth(e){if(null!=this.authToken)return zg([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new Am(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Km}`}defaultIdempotencyKey(){return`stainless-node-retry-${Om()}`}makeStatusError(e,t,n,r){return Pm.generate(e,t,n,r)}buildURL(e,t,n){const r=!xm(this,sy,"m",oy).call(this)&&n||this.baseURL,s=(e=>qm.test(e))(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return function(e){if(!e)return!0;for(const t in e)return!1;return!0}(i)||(t={...i,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(s.search=this.stringifyQuery(t)),s.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new Am("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 6e5}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Og(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){const r=await e,s=r.maxRetries??this.maxRetries;null==t&&(t=s),await this.prepareOptions(r);const{req:i,url:a,timeout:o}=this.buildRequest(r,{retryCount:s-t});await this.prepareRequest(i,{url:a,options:r});const l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=void 0===n?"":`, retryOf: ${n}`,u=Date.now();if(_g(this).debug(`[${l}] sending request`,yg({retryOfRequestLogID:n,method:r.method,url:a,options:r,headers:i.headers})),r.signal?.aborted)throw new Cm;const d=new AbortController,h=await this.fetchWithTimeout(a,i,o,d).catch(Im),p=Date.now();if(h instanceof Error){const e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new Cm;const s=Tm(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return _g(this).info(`[${l}] connection ${s?"timed out":"failed"} - ${e}`),_g(this).debug(`[${l}] connection ${s?"timed out":"failed"} (${e})`,yg({retryOfRequestLogID:n,url:a,durationMs:p-u,message:h.message})),this.retryRequest(r,t,n??l);if(_g(this).info(`[${l}] connection ${s?"timed out":"failed"} - error; no more retries left`),_g(this).debug(`[${l}] connection ${s?"timed out":"failed"} (error; no more retries left)`,yg({retryOfRequestLogID:n,url:a,durationMs:p-u,message:h.message})),s)throw new Rm;throw new $m({cause:h})}const f=[...h.headers.entries()].filter(([e])=>"request-id"===e).map(([e,t])=>", "+e+": "+JSON.stringify(t)).join(""),m=`[${l}${c}${f}] ${i.method} ${a} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${p-u}ms`;if(!h.ok){const e=this.shouldRetry(h);if(t&&e){const e=`retrying, ${t} attempts remaining`;return await async function(e){if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await(e[Symbol.asyncIterator]().return?.());const t=e.getReader(),n=t.cancel();t.releaseLock(),await n}(h.body),_g(this).info(`${m} - ${e}`),_g(this).debug(`[${l}] response error (${e})`,yg({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),this.retryRequest(r,t,n??l,h.headers)}const s=e?"error; no more retries left":"error; not retryable";_g(this).info(`${m} - ${s}`);const i=await h.text().catch(e=>Im(e).message),a=Gm(i),o=a?void 0:i;_g(this).debug(`[${l}] response error (${s})`,yg({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,message:o,durationMs:Date.now()-u}));throw this.makeStatusError(h.status,a,o,h.headers)}return _g(this).info(m),_g(this).debug(`[${l}] response start`,yg({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),{response:h,options:r,controller:d,requestLogID:l,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){const n=this.makeRequest(t,null,void 0);return new Ig(this,n,e)}async fetchWithTimeout(e,t,n,r){const{signal:s,method:i,...a}=t||{};s&&s.addEventListener("abort",()=>r.abort());const o=setTimeout(()=>r.abort(),n),l=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||"object"==typeof a.body&&null!==a.body&&Symbol.asyncIterator in a.body,c={signal:r.signal,...l?{duplex:"half"}:{},method:"GET",...a};i&&(c.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,c)}finally{clearTimeout(o)}}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,n,r){let s;const i=r?.get("retry-after-ms");if(i){const e=parseFloat(i);Number.isNaN(e)||(s=e)}const a=r?.get("retry-after");if(a&&!s){const e=parseFloat(a);s=Number.isNaN(e)?Date.parse(a)-Date.now():1e3*e}if(!(s&&0<=s&&s<6e4)){const n=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,n)}return await(e=>new Promise(t=>setTimeout(t,e)))(s),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){const n=t-e;return Math.min(.5*Math.pow(2,n),8)*(1-.25*Math.random())*1e3}calculateNonstreamingTimeout(e,t){const n=6e5;if(36e5*e/128e3>n||null!=t&&e>t)throw new Am("Streaming is strongly recommended for operations that may token longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return n}buildRequest(e,{retryCount:t=0}={}){const n={...e},{method:r,path:s,query:i,defaultBaseURL:a}=n,o=this.buildURL(s,i,a);"timeout"in n&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new Am(`${e} must be an integer`);if(t<0)throw new Am(`${e} must be a positive integer`)})("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:l,body:c}=this.buildBody({options:n});return{req:{method:r,headers:this.buildHeaders({options:e,method:r,bodyHeaders:l,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&c instanceof globalThis.ReadableStream&&{duplex:"half"},...c&&{body:c},...this.fetchOptions??{},...n.fetchOptions??{}},url:o,timeout:n.timeout}}buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let s={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);const i=zg([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Ym??(Ym=Jm()),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=zg([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&n.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:"object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)?{bodyHeaders:void 0,body:Qm(e)}:xm(this,ay,"f").call(this,{body:e,headers:n})}}iy=ly,ay=new WeakMap,sy=new WeakSet,oy=function(){return"https://api.anthropic.com"!==this.baseURL},ly.Anthropic=iy,ly.HUMAN_PROMPT="\n\nHuman:",ly.AI_PROMPT="\n\nAssistant:",ly.DEFAULT_TIMEOUT=6e5,ly.AnthropicError=Am,ly.APIError=Pm,ly.APIConnectionError=$m,ly.APIConnectionTimeoutError=Rm,ly.APIUserAbortError=Cm,ly.NotFoundError=Mm,ly.ConflictError=Dm,ly.RateLimitError=Fm,ly.BadRequestError=Nm,ly.AuthenticationError=jm,ly.InternalServerError=Bm,ly.PermissionDeniedError=Lm,ly.UnprocessableEntityError=Um,ly.toFile=async function(e,t,n){if(Pg(),e=await e,t||(t=$g(e)),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&Dg(e))(e))return e instanceof File&&null==t&&null==n?e:Cg([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...n});if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const r=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Cg(await Ug(r),t,n)}const r=await Ug(e);if(!n?.type){const e=r.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(n={...n,type:e})}return Cg(r,t,n)};class cy extends ly{constructor(){super(...arguments),this.completions=new I_(this),this.messages=new ty(this),this.models=new ny(this),this.beta=new T_(this)}}cy.Completions=I_,cy.Messages=ty,cy.Models=ny,cy.Beta=T_;const{HUMAN_PROMPT:uy,AI_PROMPT:dy}=cy;class hy extends cf{static lc_name(){return"AnthropicToolsOutputParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","anthropic","output_parsers"]}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){let t=e;if("string"==typeof e)try{t=JSON.parse(e)}catch(t){throw new df(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.message)}`,e)}else t=e;if(void 0===this.zodSchema)return t;const n=await el(this.zodSchema,t);if(n.success)return n.data;throw new df(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(e){const t=e.flatMap(e=>{const{message:t}=e;if(!Array.isArray(t.content))return[];return py(t.content)[0]});if(void 0===t[0])throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[n]=t;return await this._validateResult(n.args)}}function py(e){const t=[];for(const n of e)("tool_use"===n.type||"server_tool_use"===n.type&&"web_search"===n.name)&&t.push({name:n.name,args:n.input,id:n.id,type:"tool_call"});return t}function fy(e){const t=tn({dataUrl:e});if(t)return{type:"base64",media_type:t.mime_type,data:t.data};let n;try{n=new URL(e)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(e)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join("\n\n"))}if("http:"===n.protocol||"https:"===n.protocol)return{type:"url",url:e};throw new Error([`Invalid image URL protocol: ${JSON.stringify(n.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join("\n\n"))}function my(e){if(void 0===e.id)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:e.id,name:e.name,input:e.args}}const gy={providerName:"anthropic",fromStandardTextBlock:e=>({type:"text",text:e.text,..."citations"in(e.metadata??{})?{citations:e.metadata.citations}:{},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}),fromStandardImageBlock(e){if("url"===e.source_type){const t=tn({dataUrl:e.url,asTypedArray:!1});return t?{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:e.url,media_type:e.mime_type??""},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}}if("base64"===e.source_type)return{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type??""},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${e.source_type}`)},fromStandardFileBlock(e){const t=(e.mime_type??"").split(";")[0];if("url"===e.source_type){if("application/pdf"===t||""===t)return{type:"document",source:{type:"url",url:e.url,media_type:e.mime_type??""},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},..."citations"in(e.metadata??{})?{citations:e.metadata.citations}:{},..."context"in(e.metadata??{})?{context:e.metadata.context}:{},..."title"in(e.metadata??{})?{title:e.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${e.mime_type}`)}if("text"===e.source_type){if("text/plain"===t||""===t)return{type:"document",source:{type:"text",data:e.text,media_type:e.mime_type??""},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},..."citations"in(e.metadata??{})?{citations:e.metadata.citations}:{},..."context"in(e.metadata??{})?{context:e.metadata.context}:{},..."title"in(e.metadata??{})?{title:e.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${e.mime_type}`)}if("base64"===e.source_type){if("application/pdf"===t||""===t)return{type:"document",source:{type:"base64",data:e.data,media_type:"application/pdf"},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},..."citations"in(e.metadata??{})?{citations:e.metadata.citations}:{},..."context"in(e.metadata??{})?{context:e.metadata.context}:{},..."title"in(e.metadata??{})?{title:e.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(t))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:e.data,media_type:t}}]},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},..."citations"in(e.metadata??{})?{citations:e.metadata.citations}:{},..."context"in(e.metadata??{})?{context:e.metadata.context}:{},..."title"in(e.metadata??{})?{title:e.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${e.mime_type}`)}throw new Error(`Unsupported file source type: ${e.source_type}`)}};function _y(e){const t=["tool_use","tool_result","input_json_delta","server_tool_use","web_search_tool_result","web_search_result"],n=["text","text_delta"];if("string"==typeof e)return e;{const r=e.map(e=>{if(Vt(e))return nn(e,gy);const r="cache_control"in e?e.cache_control:void 0;if("image_url"===e.type){let t;return t="string"==typeof e.image_url?fy(e.image_url):fy(e.image_url.url),{type:"image",source:t,...r?{cache_control:r}:{}}}if(null!=(s=e)&&"object"==typeof s&&"type"in s&&"image"===s.type&&"source"in s&&"object"==typeof s.source&&null!=s.source&&"type"in s.source&&("base64"===s.source.type?"media_type"in s.source&&"string"==typeof s.source.media_type&&"data"in s.source&&"string"==typeof s.source.data:"url"===s.source.type&&"url"in s.source&&"string"==typeof s.source.url))return e;if("document"===e.type)return{...e,...r?{cache_control:r}:{}};if("thinking"===e.type){return{type:"thinking",thinking:e.thinking,signature:e.signature,...r?{cache_control:r}:{}}}if("redacted_thinking"===e.type){return{type:"redacted_thinking",data:e.data,...r?{cache_control:r}:{}}}if("search_result"===e.type){return{type:"search_result",title:e.title,source:e.source,..."cache_control"in e&&e.cache_control?{cache_control:e.cache_control}:{},..."citations"in e&&e.citations?{citations:e.citations}:{},content:e.content}}if(n.find(t=>t===e.type)&&"text"in e)return{type:"text",text:e.text,...r?{cache_control:r}:{},..."citations"in e&&e.citations?{citations:e.citations}:{}};if(t.find(t=>t===e.type)){const t={...e};if("index"in t&&delete t.index,"input_json_delta"===t.type&&(t.type="tool_use"),"input"in t&&"string"==typeof t.input)try{t.input=JSON.parse(t.input)}catch{t.input={}}return{...t,...r?{cache_control:r}:{}}}throw new Error("Unsupported message content format");var s});return r}}function yy(e){const t=function(e){const t=[];for(const n of e)if("tool"===n._getType())if("string"==typeof n.content){const e=t[t.length-1];"human"===e?._getType()&&Array.isArray(e.content)&&"type"in e.content[0]&&"tool_result"===e.content[0].type?e.content.push({type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}):t.push(new wn({content:[{type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}]}))}else t.push(new wn({content:[{type:"tool_result",...null!=n.content?{content:_y(n.content)}:{},tool_use_id:n.tool_call_id}]}));else t.push(n);return t}(e);let n;t.length>0&&"system"===t[0]._getType()&&(n=e[0].content);return{messages:vy((void 0!==n?t.slice(1):t).map(e=>{let t;if("human"===e._getType())t="user";else if("ai"===e._getType())t="assistant";else{if("tool"!==e._getType())throw"system"===e._getType()?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${e._getType()}" is not supported.`);t="user"}if(mn(e)&&e.tool_calls?.length){if("string"==typeof e.content)return""===e.content?{role:t,content:e.tool_calls.map(my)}:{role:t,content:[{type:"text",text:e.content},...e.tool_calls.map(my)]};{const{content:n}=e;e.tool_calls.every(e=>n.find(t=>("tool_use"===t.type||"input_json_delta"===t.type||"server_tool_use"===t.type)&&t.id===e.id));return{role:t,content:_y(e.content)}}}return{role:t,content:_y(e.content)}})),system:n}}function vy(e){if(!e||e.length<=1)return e;const t=[];let n=e[0];const r=e=>"string"==typeof e?[{type:"text",text:e}]:e,s=e=>"user"===e.role&&("string"!=typeof e.content&&(Array.isArray(e.content)&&e.content.every(e=>"tool_result"===e.type)));for(let i=1;i=1&&"input"in e.content[0]?"string"==typeof e.content[0].input?e.content[0].input:JSON.stringify(e.content[0].input):Array.isArray(e.content)&&e.content.length>=1&&"text"in e.content[0]?e.content[0].text:void 0}class ky extends lf{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}constructor(e){if(super(e??{}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"anthropicApiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"topK",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:2048}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"claude-2.1"}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"claude-2.1"}),Object.defineProperty(this,"invocationKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"clientOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thinking",{enumerable:!0,configurable:!0,writable:!0,value:{type:"disabled"}}),Object.defineProperty(this,"batchClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamingClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"createClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.anthropicApiKey=e?.apiKey??e?.anthropicApiKey??Ys("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!e?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=e?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=e?.anthropicApiUrl,this.modelName=e?.model??e?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=e?.invocationKwargs??{},this.temperature=e?.temperature??this.temperature,this.topK=e?.topK??this.topK,this.topP=e?.topP??this.topP,this.maxTokens=e?.maxTokensToSample??e?.maxTokens??this.maxTokens,this.stopSequences=e?.stopSequences??this.stopSequences,this.streaming=e?.streaming??!1,this.streamUsage=e?.streamUsage??this.streamUsage,this.thinking=e?.thinking??this.thinking,this.createClient=e?.createClient??(e=>new cy(e))}getLsParams(e){const t=this.invocationParams(e);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(e&&e.length)return e.map(e=>{if(function(e){return"object"==typeof e&&null!==e&&"type"in e&&"name"in e&&"string"==typeof e.type&&"string"==typeof e.name&&["web_search"].includes(e.name)}(e))return e;if(function(e){return"input_schema"in e}(e))return e;if(nf(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if(em(e))return{name:e.name,description:e.description,input_schema:Qo(e.schema)?ol(e.schema):e.schema};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)})}bindTools(e,t){return this.withConfig({tools:this.formatStructuredToolToAnthropic(e),...t})}invocationParams(e){const t=(n=e?.tool_choice,n?"any"===n?{type:"any"}:"auto"===n?{type:"auto"}:"string"==typeof n?{type:"tool",name:n}:n:void 0);var n;if("enabled"===this.thinking.type){if(-1!==this.topK)throw new Error("topK is not supported when thinking is enabled");if(-1!==this.topP)throw new Error("topP is not supported when thinking is enabled");if(1!==this.temperature)throw new Error("temperature is not supported when thinking is enabled");return{model:this.model,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e?.tools),tool_choice:t,thinking:this.thinking,...this.invocationKwargs}}return{model:this.model,temperature:this.temperature,top_k:this.topK,top_p:this.topP,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e?.tools),tool_choice:t,thinking:this.thinking,...this.invocationKwargs}}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(e,t,n){const r={...this.invocationParams(t),...yy(e),stream:!0},s=!function(e){return!!(e.tools&&e.tools.length>0)}(r)&&!function(e){for(const t of e.messages??[])if("string"!=typeof t.content)for(const e of t.content??[])if("object"==typeof e&&null!=e&&"document"===e.type&&"object"==typeof e.citations&&e.citations.enabled)return!0;return!1}(r)&&!function(e){return!(!e.thinking||"enabled"!==e.thinking.type)}(r),i=await this.createStreamWithRetry(r,{headers:t.headers});for await(const e of i){if(t.signal?.aborted)throw i.controller.abort(),new Error("AbortError: User aborted the request.");const r=this.streamUsage??t.streamUsage,a=by(e,{streamUsage:r,coerceContentToString:s});if(!a)continue;const{chunk:o}=a,l=Sy(o),c=new Qi({message:new _n({content:o.content,additional_kwargs:o.additional_kwargs,tool_call_chunks:o.tool_call_chunks,usage_metadata:r?o.usage_metadata:void 0,response_metadata:o.response_metadata,id:o.id}),text:l??""});yield c,await(n?.handleLLMNewToken(l??"",void 0,void 0,void 0,void 0,{chunk:c}))}}async _generateNonStreaming(e,t,n){const r=await this.completionWithRetry({...t,stream:!1,...yy(e)},n),{content:s,...i}=r,a=function(e,t){const n=t.usage,r=null!=n?{input_tokens:n.input_tokens??0,output_tokens:n.output_tokens??0,total_tokens:(n.input_tokens??0)+(n.output_tokens??0),input_token_details:{cache_creation:n.cache_creation_input_tokens,cache_read:n.cache_read_input_tokens}}:void 0;if(1===e.length&&"text"===e[0].type)return[{text:e[0].text,message:new fn({content:e[0].text,additional_kwargs:t,usage_metadata:r,response_metadata:t,id:t.id})}];{const n=py(e);return[{text:"",message:new fn({content:e,additional_kwargs:t,tool_calls:n,usage_metadata:r,response_metadata:t,id:t.id})}]}}(s,i),{role:o,type:l,...c}=i;return{generations:a,llmOutput:c}}async _generate(e,t,n){if(this.stopSequences&&t.stop)throw new Error('"stopSequence" parameter found in input and default params');const r=this.invocationParams(t);if(r.stream){let r;const s=this._streamResponseChunks(e,t,n);for await(const e of s)r=void 0===r?e:r.concat(e);if(void 0===r)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:r.text,message:r.message}]}}return this._generateNonStreaming(e,r,{signal:t.signal,headers:t.headers})}async createStreamWithRetry(e,t){if(!this.streamingClient){const e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}return this.caller.call(async()=>{try{return await this.streamingClient.messages.create({...e,...this.invocationKwargs,stream:!0},t)}catch(e){throw Ey(e)}})}async completionWithRetry(e,t){if(!this.batchClient){const e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}return this.caller.callWithOptions({signal:t.signal??void 0},async()=>{try{return await this.batchClient.messages.create({...e,...this.invocationKwargs},t)}catch(e){throw Ey(e)}})}_llmType(){return"anthropic"}withStructuredOutput(e,t){const n=e,r=t?.name,s=t?.method,i=t?.includeRaw;if("jsonMode"===s)throw new Error('Anthropic only supports "functionCalling" as a method.');let a,o,l,c=r??"extract";if(Qo(n)){const e=ol(n);o=[{name:c,description:e.description??"A function available to call.",input_schema:e}],a=new hy({returnSingle:!0,keyName:c,zodSchema:n})}else{let e;"string"==typeof n.name&&"string"==typeof n.description&&"object"==typeof n.input_schema&&null!=n.input_schema?(e=n,c=n.name):e={name:c,description:n.description??"",input_schema:n},o=[e],a=new hy({returnSingle:!0,keyName:c})}if("enabled"===this.thinking?.type){const e="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";l=this.withConfig({tools:o,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:ol(n)}});const t=t=>{if(!t.tool_calls||0===t.tool_calls.length)throw new Error(e);return t};l=l.pipe(t)}else l=this.withConfig({tools:o,tool_choice:{type:"tool",name:c},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:ol(n)}});if(!i)return l.pipe(a).withConfig({runName:"ChatAnthropicStructuredOutput"});const u=af.assign({parsed:(e,t)=>a.invoke(e.raw,t)}),d=af.assign({parsed:()=>null}),h=u.withFallbacks({fallbacks:[d]});return El.from([{raw:l},h]).withConfig({runName:"StructuredOutputRunnable"})}}class xy extends ky{}var Oy="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||void 0!==n.g&&n.g||{},Ty="URLSearchParams"in Oy,Iy="Symbol"in Oy&&"iterator"in Symbol,Ay="FileReader"in Oy&&"Blob"in Oy&&function(){try{return new Blob,!0}catch(e){return!1}}(),Py="FormData"in Oy,Cy="ArrayBuffer"in Oy;if(Cy)var $y=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Ry=ArrayBuffer.isView||function(e){return e&&$y.indexOf(Object.prototype.toString.call(e))>-1};function Ny(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||""===e)throw new TypeError('Invalid character in header field name: "'+e+'"');return e.toLowerCase()}function jy(e){return"string"!=typeof e&&(e=String(e)),e}function Ly(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return Iy&&(t[Symbol.iterator]=function(){return t}),t}function My(e){this.map={},e instanceof My?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){if(2!=e.length)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function Dy(e){if(!e._noBody)return e.bodyUsed?Promise.reject(new TypeError("Already read")):void(e.bodyUsed=!0)}function Uy(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function Fy(e){var t=new FileReader,n=Uy(t);return t.readAsArrayBuffer(e),n}function By(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function qy(){return this.bodyUsed=!1,this._initBody=function(e){this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:Ay&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:Py&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:Ty&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():Cy&&Ay&&function(e){return e&&DataView.prototype.isPrototypeOf(e)}(e)?(this._bodyArrayBuffer=By(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):Cy&&(ArrayBuffer.prototype.isPrototypeOf(e)||Ry(e))?this._bodyArrayBuffer=By(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):Ty&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},Ay&&(this.blob=function(){var e=Dy(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var e=Dy(this);return e||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}if(Ay)return this.blob().then(Fy);throw new Error("could not read as ArrayBuffer")},this.text=function(){var e,t,n,r,s,i=Dy(this);if(i)return i;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,n=Uy(t),r=/charset=([A-Za-z0-9_-]+)/.exec(e.type),s=r?r[1]:"utf-8",t.readAsText(e,s),n;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),n=new Array(t.length),r=0;r-1?r:n),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if("AbortController"in Oy)return(new AbortController).signal}(),this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&s)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(s),!("GET"!==this.method&&"HEAD"!==this.method||"no-store"!==t.cache&&"no-cache"!==t.cache)){var i=/([?&])_=[^&]*/;if(i.test(this.url))this.url=this.url.replace(i,"$1_="+(new Date).getTime());else{this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}}function Wy(e){var t=new FormData;return e.trim().split("&").forEach(function(e){if(e){var n=e.split("="),r=n.shift().replace(/\+/g," "),s=n.join("=").replace(/\+/g," ");t.append(decodeURIComponent(r),decodeURIComponent(s))}}),t}function Gy(e,t){if(!(this instanceof Gy))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=void 0===t.statusText?"":""+t.statusText,this.headers=new My(t.headers),this.url=t.url||"",this._initBody(e)}Hy.prototype.clone=function(){return new Hy(this,{body:this._bodyInit})},qy.call(Hy.prototype),qy.call(Gy.prototype),Gy.prototype.clone=function(){return new Gy(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new My(this.headers),url:this.url})},Gy.error=function(){var e=new Gy(null,{status:200,statusText:""});return e.ok=!1,e.status=0,e.type="error",e};var Ky=[301,302,303,307,308];Gy.redirect=function(e,t){if(-1===Ky.indexOf(t))throw new RangeError("Invalid status code");return new Gy(null,{status:t,headers:{location:e}})};var Jy=Oy.DOMException;try{new Jy}catch(e){(Jy=function(e,t){this.message=e,this.name=t;var n=Error(e);this.stack=n.stack}).prototype=Object.create(Error.prototype),Jy.prototype.constructor=Jy}function Zy(e,t){return new Promise(function(n,r){var s=new Hy(e,t);if(s.signal&&s.signal.aborted)return r(new Jy("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}if(i.onload=function(){var e,t,r={statusText:i.statusText,headers:(e=i.getAllResponseHeaders()||"",t=new My,e.replace(/\r?\n[\t ]+/g," ").split("\r").map(function(e){return 0===e.indexOf("\n")?e.substr(1,e.length):e}).forEach(function(e){var n=e.split(":"),r=n.shift().trim();if(r){var s=n.join(":").trim();try{t.append(r,s)}catch(e){}}}),t)};0===s.url.indexOf("file://")&&(i.status<200||i.status>599)?r.status=200:r.status=i.status,r.url="responseURL"in i?i.responseURL:r.headers.get("X-Request-URL");var a="response"in i?i.response:i.responseText;setTimeout(function(){n(new Gy(a,r))},0)},i.onerror=function(){setTimeout(function(){r(new TypeError("Network request failed"))},0)},i.ontimeout=function(){setTimeout(function(){r(new TypeError("Network request timed out"))},0)},i.onabort=function(){setTimeout(function(){r(new Jy("Aborted","AbortError"))},0)},i.open(s.method,function(e){try{return""===e&&Oy.location.href?Oy.location.href:e}catch(t){return e}}(s.url),!0),"include"===s.credentials?i.withCredentials=!0:"omit"===s.credentials&&(i.withCredentials=!1),"responseType"in i&&(Ay?i.responseType="blob":Cy&&(i.responseType="arraybuffer")),t&&"object"==typeof t.headers&&!(t.headers instanceof My||Oy.Headers&&t.headers instanceof Oy.Headers)){var o=[];Object.getOwnPropertyNames(t.headers).forEach(function(e){o.push(Ny(e)),i.setRequestHeader(e,jy(t.headers[e]))}),s.headers.forEach(function(e,t){-1===o.indexOf(t)&&i.setRequestHeader(t,e)})}else s.headers.forEach(function(e,t){i.setRequestHeader(t,e)});s.signal&&(s.signal.addEventListener("abort",a),i.onreadystatechange=function(){4===i.readyState&&s.signal.removeEventListener("abort",a)}),i.send(void 0===s._bodyInit?null:s._bodyInit)})}Zy.polyfill=!0,Oy.fetch||(Oy.fetch=Zy,Oy.Headers=My,Oy.Request=Hy,Oy.Response=Gy);const Vy="11434",Yy=`http://127.0.0.1:${Vy}`;var Xy=Object.defineProperty,Qy=(e,t,n)=>(((e,t,n)=>{t in e?Xy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n})(e,"symbol"!=typeof t?t+"":t,n),n);class ev extends Error{constructor(e,t){super(e),this.error=e,this.status_code=t,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,ev)}}class tv{constructor(e,t,n){Qy(this,"abortController"),Qy(this,"itr"),Qy(this,"doneCallback"),this.abortController=e,this.itr=t,this.doneCallback=n}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(const e of this.itr){if("error"in e)throw new Error(e.error);if(yield e,e.done||"success"===e.status)return void this.doneCallback()}throw new Error("Did not receive done or success response in stream.")}}const nv=async e=>{if(e.ok)return;let t=`Error ${e.status}: ${e.statusText}`,n=null;if(e.headers.get("content-type")?.includes("application/json"))try{n=await e.json(),t=n.error||t}catch(e){}else try{t=await e.text()||t}catch(e){}throw new ev(t,e.status)};function rv(){if("undefined"!=typeof window&&window.navigator){const e=navigator;return"userAgentData"in e&&e.userAgentData?.platform?`${e.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`:navigator.platform?`${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:`unknown Browser/${navigator.userAgent};`}return"undefined"!=typeof process?`${process.arch} ${process.platform} Node.js/${process.version}`:""}const sv=async(e,t,n={})=>{const r={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/0.5.16 (${rv()})`};n.headers=function(e){if(e instanceof Headers){const t={};return e.forEach((e,n)=>{t[n]=e}),t}return Array.isArray(e)?Object.fromEntries(e):e||{}}(n.headers);const s=Object.fromEntries(Object.entries(n.headers).filter(([e])=>!Object.keys(r).some(t=>t.toLowerCase()===e.toLowerCase())));return n.headers={...r,...s},e(t,n)},iv=async(e,t,n)=>{const r=await sv(e,t,{headers:n?.headers});return await nv(r),r},av=async(e,t,n,r)=>{const s=null===(i=n)||"object"!=typeof i||Array.isArray(i)?n:JSON.stringify(n);var i;const a=await sv(e,t,{method:"POST",body:s,signal:r?.signal,headers:r?.headers});return await nv(a),a};var ov=Object.defineProperty,lv=(e,t,n)=>(((e,t,n)=>{t in e?ov(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n})(e,"symbol"!=typeof t?t+"":t,n),n);let cv=class{constructor(e){lv(this,"config"),lv(this,"fetch"),lv(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=(e=>{if(!e)return Yy;let t=e.includes("://");e.startsWith(":")&&(e=`http://127.0.0.1${e}`,t=!0),t||(e=`http://${e}`);const n=new URL(e);let r=n.port;r||(r=t?"https:"===n.protocol?"443":"80":Vy);let s="";n.username&&(s=n.username,n.password&&(s+=`:${n.password}`),s+="@");let i=`${n.protocol}//${s}${n.hostname}:${r}${n.pathname}`;return i.endsWith("/")&&(i=i.slice(0,-1)),i})(e?.host??Yy)),this.fetch=e?.fetch??fetch}abort(){for(const e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,t){t.stream=t.stream??!1;const n=`${this.config.host}/api/${e}`;if(t.stream){const e=new AbortController,r=await av(this.fetch,n,t,{signal:e.signal,headers:this.config.headers});if(!r.body)throw new Error("Missing body");const s=async function*(e){const t=new TextDecoder("utf-8");let n="";const r=e.getReader();for(;;){const{done:e,value:s}=await r.read();if(e)break;n+=t.decode(s);const i=n.split("\n");n=i.pop()??"";for(const e of i)try{yield JSON.parse(e)}catch(e){}}for(const e of n.split("\n").filter(e=>""!==e))try{yield JSON.parse(e)}catch(e){}}(r.body),i=new tv(e,s,()=>{const e=this.ongoingStreamedRequests.indexOf(i);e>-1&&this.ongoingStreamedRequests.splice(e,1)});return this.ongoingStreamedRequests.push(i),i}const r=await av(this.fetch,n,t,{headers:this.config.headers});return await r.json()}async encodeImage(e){if("string"!=typeof e){const t=new Uint8Array(e);let n="";const r=t.byteLength;for(let e=0;e{const s=await sv(e,t,{method:"DELETE",body:JSON.stringify(n),headers:r?.headers});return await nv(s),s})(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await av(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){const e=await iv(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers});return await e.json()}async show(e){const t=await av(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers});return await t.json()}async embed(e){const t=await av(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers});return await t.json()}async embeddings(e){const t=await av(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers});return await t.json()}async ps(){const e=await iv(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers});return await e.json()}};new cv;const uv={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};var dv,hv=new Uint8Array(16);function pv(){if(!dv&&!(dv="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 dv(hv)}for(var fv=[],mv=0;mv<256;++mv)fv.push((mv+256).toString(16).slice(1));function gv(e,t=0){return(fv[e[t+0]]+fv[e[t+1]]+fv[e[t+2]]+fv[e[t+3]]+"-"+fv[e[t+4]]+fv[e[t+5]]+"-"+fv[e[t+6]]+fv[e[t+7]]+"-"+fv[e[t+8]]+fv[e[t+9]]+"-"+fv[e[t+10]]+fv[e[t+11]]+fv[e[t+12]]+fv[e[t+13]]+fv[e[t+14]]+fv[e[t+15]]).toLowerCase()}const _v=function(e,t,n){if(uv.randomUUID&&!t&&!e)return uv.randomUUID();var r=(e=e||{}).random||(e.rng||pv)();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 gv(r)};function yv(e,t){return new _n({content:e.content??"",tool_call_chunks:e.tool_calls?.map(e=>({name:e.function.name,args:JSON.stringify(e.function.arguments),type:"tool_call_chunk",index:0,id:_v()})),response_metadata:t?.responseMetadata,usage_metadata:t?.usageMetadata})}function vv(e){const t=e.match(/^data:.*?;base64,(.*)$/);return t?t[1]:""}function bv(e){return e.flatMap(e=>{if(["human","generic"].includes(e._getType()))return"string"==typeof(t=e).content?[{role:"user",content:t.content}]:t.content.map(e=>{if("text"===e.type)return{role:"user",content:e.text};if("image_url"===e.type){if("string"==typeof e.image_url)return{role:"user",content:"",images:[vv(e.image_url)]};if(e.image_url.url&&"string"==typeof e.image_url.url)return{role:"user",content:"",images:[vv(e.image_url.url)]}}throw new Error(`Unsupported content type: ${e.type}`)});if("ai"===e._getType())return function(e){if("string"==typeof e.content)return[{role:"assistant",content:e.content}];const t=e.content.filter(e=>"text"===e.type&&"string"==typeof e.text),n=t.map(e=>({role:"assistant",content:e.text}));let r;if(e.content.find(e=>"tool_use"===e.type)&&e.tool_calls?.length){const t=e.tool_calls?.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:e.args}}));t&&(r={role:"assistant",tool_calls:t,content:""})}else if(e.content.find(e=>"tool_use"===e.type)&&!e.tool_calls?.length)throw new Error("'tool_use' content type is not supported without tool calls.");return[...n,...r?[r]:[]]}(e);if("system"===e._getType())return function(e){if("string"==typeof e.content)return[{role:"system",content:e.content}];if(e.content.every(e=>"text"===e.type&&"string"==typeof e.text))return e.content.map(e=>({role:"system",content:e.text}));throw new Error(`Unsupported content type(s): ${e.content.map(e=>e.type).join(", ")}`)}(e);if("tool"===e._getType())return function(e){if("string"!=typeof e.content)throw new Error("Non string tool message content is not supported");return[{role:"tool",content:e.content}]}(e);throw new Error(`Unsupported message type: ${e._getType()}`);var t})}class wv extends lf{static lc_name(){return"ChatOllama"}constructor(e){super(e??{}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"llama3"}),Object.defineProperty(this,"numa",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numCtx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numBatch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numGpu",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mainGpu",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lowVram",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"f16Kv",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logitsAll",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"vocabOnly",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"useMmap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"useMlock",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"embeddingOnly",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numThread",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numKeep",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"seed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numPredict",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topK",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tfsZ",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"typicalP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"repeatLastN",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"repeatPenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"presencePenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"frequencyPenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mirostat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mirostatTau",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mirostatEta",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"penalizeNewline",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"format",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keepAlive",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkOrPullModel",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"baseUrl",{enumerable:!0,configurable:!0,writable:!0,value:"http://127.0.0.1:11434"}),this.client=new cv({fetch:e?.fetch,host:e?.baseUrl,headers:e?.headers}),this.baseUrl=e?.baseUrl??this.baseUrl,this.model=e?.model??this.model,this.numa=e?.numa,this.numCtx=e?.numCtx,this.numBatch=e?.numBatch,this.numGpu=e?.numGpu,this.mainGpu=e?.mainGpu,this.lowVram=e?.lowVram,this.f16Kv=e?.f16Kv,this.logitsAll=e?.logitsAll,this.vocabOnly=e?.vocabOnly,this.useMmap=e?.useMmap,this.useMlock=e?.useMlock,this.embeddingOnly=e?.embeddingOnly,this.numThread=e?.numThread,this.numKeep=e?.numKeep,this.seed=e?.seed,this.numPredict=e?.numPredict,this.topK=e?.topK,this.topP=e?.topP,this.tfsZ=e?.tfsZ,this.typicalP=e?.typicalP,this.repeatLastN=e?.repeatLastN,this.temperature=e?.temperature,this.repeatPenalty=e?.repeatPenalty,this.presencePenalty=e?.presencePenalty,this.frequencyPenalty=e?.frequencyPenalty,this.mirostat=e?.mirostat,this.mirostatTau=e?.mirostatTau,this.mirostatEta=e?.mirostatEta,this.penalizeNewline=e?.penalizeNewline,this.streaming=e?.streaming,this.format=e?.format,this.keepAlive=e?.keepAlive,this.checkOrPullModel=e?.checkOrPullModel??this.checkOrPullModel}_llmType(){return"ollama"}async pull(e,t){const{stream:n,insecure:r,logProgress:s}={stream:!0,...t};if(n)for await(const t of await this.client.pull({model:e,insecure:r,stream:n}));else{await this.client.pull({model:e,insecure:r})}}bindTools(e,t){return this.withConfig({tools:e.map(e=>nm(e)),...t})}getLsParams(e){const t=this.invocationParams(e);return{ls_provider:"ollama",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.options?.temperature??void 0,ls_max_tokens:t.options?.num_predict??void 0,ls_stop:e.stop}}invocationParams(e){if(e?.tool_choice)throw new Error("Tool choice is not supported for ChatOllama.");return{model:this.model,format:e?.format??this.format,keep_alive:this.keepAlive,options:{numa:this.numa,num_ctx:this.numCtx,num_batch:this.numBatch,num_gpu:this.numGpu,main_gpu:this.mainGpu,low_vram:this.lowVram,f16_kv:this.f16Kv,logits_all:this.logitsAll,vocab_only:this.vocabOnly,use_mmap:this.useMmap,use_mlock:this.useMlock,embedding_only:this.embeddingOnly,num_thread:this.numThread,num_keep:this.numKeep,seed:this.seed,num_predict:this.numPredict,top_k:this.topK,top_p:this.topP,tfs_z:this.tfsZ,typical_p:this.typicalP,repeat_last_n:this.repeatLastN,temperature:this.temperature,repeat_penalty:this.repeatPenalty,presence_penalty:this.presencePenalty,frequency_penalty:this.frequencyPenalty,mirostat:this.mirostat,mirostat_tau:this.mirostatTau,mirostat_eta:this.mirostatEta,penalize_newline:this.penalizeNewline,stop:e?.stop},tools:e?.tools?.length?e.tools.map(e=>nm(e)):void 0}}async checkModelExistsOnMachine(e){const{models:t}=await this.client.list();return!!t.find(t=>t.name===e||t.name===`${e}:latest`)}async _generate(e,t,n){let r;this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));for await(const s of this._streamResponseChunks(e,t,n))r=r?zi(r,s.message):s.message;const s=new fn({id:r?.id,content:r?.content??"",tool_calls:r?.tool_calls,response_metadata:r?.response_metadata,usage_metadata:r?.usage_metadata});return{generations:[{text:"string"==typeof s.content?s.content:"",message:s}]}}async*_streamResponseChunks(e,t,n){this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));const r=this.invocationParams(t),s=bv(e),i={input_tokens:0,output_tokens:0,total_tokens:0},a=await this.client.chat({...r,messages:s,stream:!0});let o;for await(const e of a){t.signal?.aborted&&this.client.abort();const{message:r,...s}=e;i.input_tokens+=s.prompt_eval_count??0,i.output_tokens+=s.eval_count??0,i.total_tokens=i.input_tokens+i.output_tokens,o=s,yield new Qi({text:r.content??"",message:yv(r)}),await(n?.handleLLMNewToken(r.content??""))}yield new Qi({text:"",message:new _n({content:"",response_metadata:o,usage_metadata:i})})}withStructuredOutput(e,t){if(void 0===t?.method||"jsonSchema"===t?.method){const n=Qo(e),r=n?ol(e):e,s=this.bindTools([{type:"function",function:{name:"extract",description:r.description,parameters:r}}]).withConfig({format:"json",ls_structured_output_format:{kwargs:{method:"jsonSchema"},schema:ol(e)}}),i=n?ff.fromZodSchema(e):new mf;if(!t?.includeRaw)return s.pipe(i);const a=af.assign({parsed:(e,t)=>i.invoke(e.raw,t)}),o=af.assign({parsed:()=>null}),l=a.withFallbacks({fallbacks:[o]});return El.from([{raw:s},l])}return super.withStructuredOutput(e,t)}}var Ev,Sv,kv;!function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"}(Ev||(Ev={})),function(e){e.LANGUAGE_UNSPECIFIED="language_unspecified",e.PYTHON="python"}(Sv||(Sv={})),function(e){e.OUTCOME_UNSPECIFIED="outcome_unspecified",e.OUTCOME_OK="outcome_ok",e.OUTCOME_FAILED="outcome_failed",e.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"}(kv||(kv={}));const xv=["user","model","function","system"];var Ov,Tv,Iv,Av,Pv,Cv,$v,Rv;!function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"}(Ov||(Ov={})),function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"}(Tv||(Tv={})),function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"}(Iv||(Iv={})),function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER"}(Av||(Av={})),function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.OTHER="OTHER"}(Pv||(Pv={})),function(e){e.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",e.RETRIEVAL_QUERY="RETRIEVAL_QUERY",e.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",e.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",e.CLASSIFICATION="CLASSIFICATION",e.CLUSTERING="CLUSTERING"}(Cv||(Cv={})),function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"}($v||($v={})),function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"}(Rv||(Rv={}));class Nv extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}}class jv extends Nv{constructor(e,t){super(e),this.response=t}}class Lv extends Nv{constructor(e,t,n,r){super(e),this.status=t,this.statusText=n,this.errorDetails=r}}class Mv extends Nv{}class Dv extends Nv{}var Uv;!function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens",e.EMBED_CONTENT="embedContent",e.BATCH_EMBED_CONTENTS="batchEmbedContents"}(Uv||(Uv={}));class Fv{constructor(e,t,n,r,s){this.model=e,this.task=t,this.apiKey=n,this.stream=r,this.requestOptions=s}toString(){var e,t;const n=(null===(e=this.requestOptions)||void 0===e?void 0:e.apiVersion)||"v1beta";let r=`${(null===(t=this.requestOptions)||void 0===t?void 0:t.baseUrl)||"https://generativelanguage.googleapis.com"}/${n}/${this.model}:${this.task}`;return this.stream&&(r+="?alt=sse"),r}}async function Bv(e){var t;const n=new Headers;n.append("Content-Type","application/json"),n.append("x-goog-api-client",function(e){const t=[];return(null==e?void 0:e.apiClient)&&t.push(e.apiClient),t.push("genai-js/0.24.1"),t.join(" ")}(e.requestOptions)),n.append("x-goog-api-key",e.apiKey);let r=null===(t=e.requestOptions)||void 0===t?void 0:t.customHeaders;if(r){if(!(r instanceof Headers))try{r=new Headers(r)}catch(e){throw new Mv(`unable to convert customHeaders value ${JSON.stringify(r)} to Headers: ${e.message}`)}for(const[e,t]of r.entries()){if("x-goog-api-key"===e)throw new Mv(`Cannot set reserved header name ${e}`);if("x-goog-api-client"===e)throw new Mv(`Header name ${e} can only be set using the apiClient field`);n.append(e,t)}}return n}async function qv(e,t,n,r,s,i={},a=fetch){const{url:o,fetchOptions:l}=await async function(e,t,n,r,s,i){const a=new Fv(e,t,n,r,i);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},zv(i)),{method:"POST",headers:await Bv(a),body:s})}}(e,t,n,r,s,i);return async function(e,t,n=fetch){let r;try{r=await n(e,t)}catch(t){!function(e,t){let n=e;"AbortError"===n.name?(n=new Dv(`Request aborted when fetching ${t.toString()}: ${e.message}`),n.stack=e.stack):e instanceof Lv||e instanceof Mv||(n=new Nv(`Error fetching from ${t.toString()}: ${e.message}`),n.stack=e.stack);throw n}(t,e)}r.ok||await async function(e,t){let n,r="";try{const t=await e.json();r=t.error.message,t.error.details&&(r+=` ${JSON.stringify(t.error.details)}`,n=t.error.details)}catch(e){}throw new Lv(`Error fetching from ${t.toString()}: [${e.status} ${e.statusText}] ${r}`,e.status,e.statusText,n)}(r,e);return r}(o,l,a)}function zv(e){const t={};if(void 0!==(null==e?void 0:e.signal)||(null==e?void 0:e.timeout)>=0){const n=new AbortController;(null==e?void 0:e.timeout)>=0&&setTimeout(()=>n.abort(),e.timeout),(null==e?void 0:e.signal)&&e.signal.addEventListener("abort",()=>{n.abort()}),t.signal=n.signal}return t}function Hv(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length,Kv(e.candidates[0]))throw new jv(`${Jv(e)}`,e);return function(e){var t,n,r,s;const i=[];if(null===(n=null===(t=e.candidates)||void 0===t?void 0:t[0].content)||void 0===n?void 0:n.parts)for(const t of null===(s=null===(r=e.candidates)||void 0===r?void 0:r[0].content)||void 0===s?void 0:s.parts)t.text&&i.push(t.text),t.executableCode&&i.push("\n```"+t.executableCode.language+"\n"+t.executableCode.code+"\n```\n"),t.codeExecutionResult&&i.push("\n```\n"+t.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}(e)}if(e.promptFeedback)throw new jv(`Text not available. ${Jv(e)}`,e);return""},e.functionCall=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length,Kv(e.candidates[0]))throw new jv(`${Jv(e)}`,e);return Wv(e)[0]}if(e.promptFeedback)throw new jv(`Function call not available. ${Jv(e)}`,e)},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length,Kv(e.candidates[0]))throw new jv(`${Jv(e)}`,e);return Wv(e)}if(e.promptFeedback)throw new jv(`Function call not available. ${Jv(e)}`,e)},e}function Wv(e){var t,n,r,s;const i=[];if(null===(n=null===(t=e.candidates)||void 0===t?void 0:t[0].content)||void 0===n?void 0:n.parts)for(const t of null===(s=null===(r=e.candidates)||void 0===r?void 0:r[0].content)||void 0===s?void 0:s.parts)t.functionCall&&i.push(t.functionCall);return i.length>0?i:void 0}const Gv=[Pv.RECITATION,Pv.SAFETY,Pv.LANGUAGE];function Kv(e){return!!e.finishReason&&Gv.includes(e.finishReason)}function Jv(e){var t,n,r;let s="";if(e.candidates&&0!==e.candidates.length||!e.promptFeedback){if(null===(r=e.candidates)||void 0===r?void 0:r[0]){const t=e.candidates[0];Kv(t)&&(s+=`Candidate was blocked due to ${t.finishReason}`,t.finishMessage&&(s+=`: ${t.finishMessage}`))}}else s+="Response was blocked",(null===(t=e.promptFeedback)||void 0===t?void 0:t.blockReason)&&(s+=` due to ${e.promptFeedback.blockReason}`),(null===(n=e.promptFeedback)||void 0===n?void 0:n.blockReasonMessage)&&(s+=`: ${e.promptFeedback.blockReasonMessage}`);return s}function Zv(e){return this instanceof Zv?(this.v=e,this):new Zv(e)}function Vv(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,s=n.apply(e,t||[]),i=[];return r={},a("next"),a("throw"),a("return"),r[Symbol.asyncIterator]=function(){return this},r;function a(e){s[e]&&(r[e]=function(t){return new Promise(function(n,r){i.push([e,t,n,r])>1||o(e,t)})})}function o(e,t){try{!function(e){e.value instanceof Zv?Promise.resolve(e.value.v).then(l,c):u(i[0][2],e)}(s[e](t))}catch(e){u(i[0][3],e)}}function l(e){o("next",e)}function c(e){o("throw",e)}function u(e,t){e(t),i.shift(),i.length&&o(i[0][0],i[0][1])}}"function"==typeof SuppressedError&&SuppressedError;const Yv=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function Xv(e){const t=function(e){const t=e.getReader(),n=new ReadableStream({start(e){let n="";return r();function r(){return t.read().then(({value:t,done:s})=>{if(s)return n.trim()?void e.error(new Nv("Failed to parse stream")):void e.close();n+=t;let i,a=n.match(Yv);for(;a;){try{i=JSON.parse(a[1])}catch(t){return void e.error(new Nv(`Error parsing JSON response: "${a[1]}"`))}e.enqueue(i),n=n.substring(a[0].length),a=n.match(Yv)}return r()}).catch(e=>{let t=e;throw t.stack=e.stack,t="AbortError"===t.name?new Dv("Request aborted when reading from the stream"):new Nv("Error reading from the stream"),t})}}});return n}(e.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0}))),[n,r]=t.tee();return{stream:eb(n),response:Qv(r)}}async function Qv(e){const t=[],n=e.getReader();for(;;){const{done:e,value:r}=await n.read();if(e)return Hv(tb(t));t.push(r)}}function eb(e){return Vv(this,arguments,function*(){const t=e.getReader();for(;;){const{value:e,done:n}=yield Zv(t.read());if(n)break;yield yield Zv(Hv(e))}})}function tb(e){const t=e[e.length-1],n={promptFeedback:null==t?void 0:t.promptFeedback};for(const t of e){if(t.candidates){let e=0;for(const r of t.candidates)if(n.candidates||(n.candidates=[]),n.candidates[e]||(n.candidates[e]={index:e}),n.candidates[e].citationMetadata=r.citationMetadata,n.candidates[e].groundingMetadata=r.groundingMetadata,n.candidates[e].finishReason=r.finishReason,n.candidates[e].finishMessage=r.finishMessage,n.candidates[e].safetyRatings=r.safetyRatings,r.content&&r.content.parts){n.candidates[e].content||(n.candidates[e].content={role:r.content.role||"user",parts:[]});const t={};for(const s of r.content.parts)s.text&&(t.text=s.text),s.functionCall&&(t.functionCall=s.functionCall),s.executableCode&&(t.executableCode=s.executableCode),s.codeExecutionResult&&(t.codeExecutionResult=s.codeExecutionResult),0===Object.keys(t).length&&(t.text=""),n.candidates[e].content.parts.push(t)}e++}t.usageMetadata&&(n.usageMetadata=t.usageMetadata)}return n}async function nb(e,t,n,r){return Xv(await qv(t,Uv.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),r))}async function rb(e,t,n,r){const s=await qv(t,Uv.GENERATE_CONTENT,e,!1,JSON.stringify(n),r);return{response:Hv(await s.json())}}function sb(e){if(null!=e)return"string"==typeof e?{role:"system",parts:[{text:e}]}:e.text?{role:"system",parts:[e]}:e.parts?e.role?e:{role:"system",parts:e.parts}:void 0}function ib(e){let t=[];if("string"==typeof e)t=[{text:e}];else for(const n of e)"string"==typeof n?t.push({text:n}):t.push(n);return function(e){const t={role:"user",parts:[]},n={role:"function",parts:[]};let r=!1,s=!1;for(const i of e)"functionResponse"in i?(n.parts.push(i),s=!0):(t.parts.push(i),r=!0);if(r&&s)throw new Nv("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!r&&!s)throw new Nv("No content is provided for sending chat message.");if(r)return t;return n}(t)}function ab(e){let t;if(e.contents)t=e;else{t={contents:[ib(e)]}}return e.systemInstruction&&(t.systemInstruction=sb(e.systemInstruction)),t}const ob=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],lb={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function cb(e){var t;if(void 0===e.candidates||0===e.candidates.length)return!1;const n=null===(t=e.candidates[0])||void 0===t?void 0:t.content;if(void 0===n)return!1;if(void 0===n.parts||0===n.parts.length)return!1;for(const e of n.parts){if(void 0===e||0===Object.keys(e).length)return!1;if(void 0!==e.text&&""===e.text)return!1}return!0}const ub="SILENT_ERROR";class db{constructor(e,t,n,r={}){this.model=t,this.params=n,this._requestOptions=r,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,(null==n?void 0:n.history)&&(!function(e){let t=!1;for(const n of e){const{role:e,parts:r}=n;if(!t&&"user"!==e)throw new Nv(`First content should be with role 'user', got ${e}`);if(!xv.includes(e))throw new Nv(`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(xv)}`);if(!Array.isArray(r))throw new Nv("Content should have 'parts' property with an array of Parts");if(0===r.length)throw new Nv("Each Content should have at least one part");const s={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(const e of r)for(const t of ob)t in e&&(s[t]+=1);const i=lb[e];for(const t of ob)if(!i.includes(t)&&s[t]>0)throw new Nv(`Content with role '${e}' can't contain '${t}' part`);t=!0}}(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,t={}){var n,r,s,i,a,o;await this._sendPromise;const l=ib(e),c={safetySettings:null===(n=this.params)||void 0===n?void 0:n.safetySettings,generationConfig:null===(r=this.params)||void 0===r?void 0:r.generationConfig,tools:null===(s=this.params)||void 0===s?void 0:s.tools,toolConfig:null===(i=this.params)||void 0===i?void 0:i.toolConfig,systemInstruction:null===(a=this.params)||void 0===a?void 0:a.systemInstruction,cachedContent:null===(o=this.params)||void 0===o?void 0:o.cachedContent,contents:[...this._history,l]},u=Object.assign(Object.assign({},this._requestOptions),t);let d;return this._sendPromise=this._sendPromise.then(()=>rb(this._apiKey,this.model,c,u)).then(e=>{var t;if(cb(e.response)){this._history.push(l);const n=Object.assign({parts:[],role:"model"},null===(t=e.response.candidates)||void 0===t?void 0:t[0].content);this._history.push(n)}else{Jv(e.response)}d=e}).catch(e=>{throw this._sendPromise=Promise.resolve(),e}),await this._sendPromise,d}async sendMessageStream(e,t={}){var n,r,s,i,a,o;await this._sendPromise;const l=ib(e),c={safetySettings:null===(n=this.params)||void 0===n?void 0:n.safetySettings,generationConfig:null===(r=this.params)||void 0===r?void 0:r.generationConfig,tools:null===(s=this.params)||void 0===s?void 0:s.tools,toolConfig:null===(i=this.params)||void 0===i?void 0:i.toolConfig,systemInstruction:null===(a=this.params)||void 0===a?void 0:a.systemInstruction,cachedContent:null===(o=this.params)||void 0===o?void 0:o.cachedContent,contents:[...this._history,l]},u=Object.assign(Object.assign({},this._requestOptions),t),d=nb(this._apiKey,this.model,c,u);return this._sendPromise=this._sendPromise.then(()=>d).catch(e=>{throw new Error(ub)}).then(e=>e.response).then(e=>{if(cb(e)){this._history.push(l);const t=Object.assign({},e.candidates[0].content);t.role||(t.role="model"),this._history.push(t)}else{Jv(e)}}).catch(e=>{e.message}),d}}class hb{constructor(e,t,n={}){this.apiKey=e,this._requestOptions=n,t.model.includes("/")?this.model=t.model:this.model=`models/${t.model}`,this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=sb(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(e,t={}){var n;const r=ab(e),s=Object.assign(Object.assign({},this._requestOptions),t);return rb(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:null===(n=this.cachedContent)||void 0===n?void 0:n.name},r),s)}async generateContentStream(e,t={}){var n;const r=ab(e),s=Object.assign(Object.assign({},this._requestOptions),t);return nb(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:null===(n=this.cachedContent)||void 0===n?void 0:n.name},r),s)}startChat(e){var t;return new db(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:null===(t=this.cachedContent)||void 0===t?void 0:t.name},e),this._requestOptions)}async countTokens(e,t={}){const n=function(e,t){var n;let r={model:null==t?void 0:t.model,generationConfig:null==t?void 0:t.generationConfig,safetySettings:null==t?void 0:t.safetySettings,tools:null==t?void 0:t.tools,toolConfig:null==t?void 0:t.toolConfig,systemInstruction:null==t?void 0:t.systemInstruction,cachedContent:null===(n=null==t?void 0:t.cachedContent)||void 0===n?void 0:n.name,contents:[]};const s=null!=e.generateContentRequest;if(e.contents){if(s)throw new Mv("CountTokensRequest must have one of contents or generateContentRequest, not both.");r.contents=e.contents}else if(s)r=Object.assign(Object.assign({},r),e.generateContentRequest);else{const t=ib(e);r.contents=[t]}return{generateContentRequest:r}}(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),r=Object.assign(Object.assign({},this._requestOptions),t);return async function(e,t,n,r){return(await qv(t,Uv.COUNT_TOKENS,e,!1,JSON.stringify(n),r)).json()}(this.apiKey,this.model,n,r)}async embedContent(e,t={}){const n=function(e){if("string"==typeof e||Array.isArray(e))return{content:ib(e)};return e}(e),r=Object.assign(Object.assign({},this._requestOptions),t);return async function(e,t,n,r){return(await qv(t,Uv.EMBED_CONTENT,e,!1,JSON.stringify(n),r)).json()}(this.apiKey,this.model,n,r)}async batchEmbedContents(e,t={}){const n=Object.assign(Object.assign({},this._requestOptions),t);return async function(e,t,n,r){const s=n.requests.map(e=>Object.assign(Object.assign({},e),{model:t}));return(await qv(t,Uv.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:s}),r)).json()}(this.apiKey,this.model,e,n)}}class pb{constructor(e){this.apiKey=e}getGenerativeModel(e,t){if(!e.model)throw new Nv("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new hb(this.apiKey,e,t)}getGenerativeModelFromCachedContent(e,t,n){if(!e.name)throw new Mv("Cached content must contain a `name` field.");if(!e.model)throw new Mv("Cached content must contain a `model` field.");const r=["model","systemInstruction"];for(const n of r)if((null==t?void 0:t[n])&&e[n]&&(null==t?void 0:t[n])!==e[n]){if("model"===n){if((t.model.startsWith("models/")?t.model.replace("models/",""):t.model)===(e.model.startsWith("models/")?e.model.replace("models/",""):e.model))continue}throw new Mv(`Different value for "${n}" specified in modelParams (${t[n]}) and cachedContent (${e[n]})`)}const s=Object.assign(Object.assign({},t),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new hb(this.apiKey,s,n)}}function fb(e){if("object"==typeof e&&null!==e){const t={...e};"additionalProperties"in t&&delete t.additionalProperties,"$schema"in t&&delete t.$schema,"strict"in t&&delete t.strict;for(const e in t)e in t&&(Array.isArray(t[e])?t[e]=t[e].map(fb):"object"==typeof t[e]&&null!==t[e]&&(t[e]=fb(t[e])));return t}return e}function mb(e){const t=fb(Qo(e)?ol(e):e),{$schema:n,...r}=t;return r}function gb(e){const t=fb(e),{$schema:n,...r}=t;return r}const _b={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let yb;const vb=new Uint8Array(16);const bb=[];for(let e=0;e<256;++e)bb.push((e+256).toString(16).slice(1));function wb(e,t=0){return(bb[e[t+0]]+bb[e[t+1]]+bb[e[t+2]]+bb[e[t+3]]+"-"+bb[e[t+4]]+bb[e[t+5]]+"-"+bb[e[t+6]]+bb[e[t+7]]+"-"+bb[e[t+8]]+bb[e[t+9]]+"-"+bb[e[t+10]]+bb[e[t+11]]+bb[e[t+12]]+bb[e[t+13]]+bb[e[t+14]]+bb[e[t+15]]).toLowerCase()}const Eb=function(e,t,n){if(_b.randomUUID&&!t&&!e)return _b.randomUUID();const r=(e=e||{}).random??e.rng?.()??function(){if(!yb){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");yb=crypto.getRandomValues.bind(crypto)}return yb(vb)}();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){if((n=n||0)<0||n+16>t.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return wb(r)};function Sb(e,t){if(Vt(e))return nn(e,function(e){return{providerName:"Google Gemini",fromStandardTextBlock:e=>({text:e.text}),fromStandardImageBlock(t){if(!e)throw new Error("This model does not support images");if("url"===t.source_type){const e=tn({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if("base64"===t.source_type)return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw new Error("This model does not support audio");if("url"===t.source_type){const e=tn({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if("base64"===t.source_type)return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw new Error("This model does not support files");if("text"===t.source_type)return{text:t.text};if("url"===t.source_type){const e=tn({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if("base64"===t.source_type)return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)}}}(t));if("text"===e.type)return{text:e.text};if("executableCode"===e.type)return{executableCode:e.executableCode};if("codeExecutionResult"===e.type)return{codeExecutionResult:e.codeExecutionResult};if("image_url"===e.type){if(!t)throw new Error("This model does not support images");let n;if("string"==typeof e.image_url)n=e.image_url;else{if("object"!=typeof e.image_url||!("url"in e.image_url))throw new Error("Please provide image as base64 encoded data URL");n=e.image_url.url}const[r,s]=n.split(",");if(!r.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[i,a]=r.replace(/^data:/,"").split(";");if("base64"!==a)throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:s,mimeType:i}}}if("media"===e.type)return function(e){if("mimeType"in e&&"data"in e)return{inlineData:{mimeType:e.mimeType,data:e.data}};if("mimeType"in e&&"fileUri"in e)return{fileData:{mimeType:e.mimeType,fileUri:e.fileUri}};throw new Error("Invalid media content")}(e);if("tool_use"===e.type)return{functionCall:{name:e.name,args:e.input}};if(e.type?.includes("/")&&2===e.type.split("/").length&&"data"in e&&"string"==typeof e.data)return{inlineData:{mimeType:e.type,data:e.data}};if(!("functionCall"in e))throw"type"in e?new Error(`Unknown content type ${e.type}`):new Error(`Unknown content ${JSON.stringify(e)}`)}function kb(e,t,n){if(function(e){return"tool"===e._getType()}(e)){const r=e.name??function(e,t){return t.map(e=>mn(e)?e.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}(e,n);if(void 0===r)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${e.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const s=Array.isArray(e.content)?e.content.map(e=>Sb(e,t)).filter(e=>void 0!==e):e.content;return"error"===e.status?[{functionResponse:{name:r,response:{error:{details:s}}}}]:[{functionResponse:{name:r,response:{result:s}}}]}let r=[];const s=[];return"string"==typeof e.content&&e.content&&s.push({text:e.content}),Array.isArray(e.content)&&s.push(...e.content.map(e=>Sb(e,t)).filter(e=>void 0!==e)),mn(e)&&e.tool_calls?.length&&(r=e.tool_calls.map(e=>({functionCall:{name:e.name,args:e.args}}))),[...s,...r]}function xb(e,t,n=!1){return e.reduce((r,s,i)=>{if(!un(s))throw new Error("Unsupported message input");const a=function(e){const t=e._getType();return yn.isInstance(e)?e.role:"tool"===t?t:e.name??t}(s);if("system"===a&&0!==i)throw new Error("System message should be the first one");const o=function(e){switch(e){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${e}`)}}(a),l=r.content[r.content.length];if(!r.mergeWithPreviousContent&&l&&l.role===o)throw new Error("Google Generative AI requires alternate messages between authors");const c=kb(s,t,e.slice(0,i));if(r.mergeWithPreviousContent){const e=r.content[r.content.length-1];if(!e)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return e.parts.push(...c),{mergeWithPreviousContent:!1,content:r.content}}let u=o;("function"===u||"system"===u&&!n)&&(u="user");const d={role:u,parts:c};return{mergeWithPreviousContent:"system"===a&&!n,content:[...r.content,d]}},{content:[],mergeWithPreviousContent:!1}).content}function Ob(e,t){if(!e.candidates||0===e.candidates.length)return null;const n=e.functionCalls(),[r]=e.candidates,{content:s,...i}=r;let a;a=Array.isArray(s?.parts)&&s.parts.every(e=>"text"in e)?s.parts.map(e=>e.text).join(""):Array.isArray(s?.parts)?s.parts.map(e=>"text"in e?{type:"text",text:e.text}:"executableCode"in e?{type:"executableCode",executableCode:e.executableCode}:"codeExecutionResult"in e?{type:"codeExecutionResult",codeExecutionResult:e.codeExecutionResult}:e):[];let o="";if(a&&"string"==typeof a)o=a;else if(Array.isArray(a)){const e=a.find(e=>"text"in e);o=e?.text??""}const l=[];return n&&l.push(...n.map(e=>({...e,args:JSON.stringify(e.args),index:t.index,type:"tool_call_chunk",id:"id"in e&&"string"==typeof e.id?e.id:Eb()}))),new Qi({text:o,message:new _n({content:a||"",name:s?s.role:void 0,tool_call_chunks:l,additional_kwargs:{},usage_metadata:t.usageMetadata}),generationInfo:i})}class Tb extends cf{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","google_genai","output_parsers"]}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(void 0===this.zodSchema)return e;const t=await el(this.zodSchema,e);if(t.success)return t.data;throw new df(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){const t=e.flatMap(e=>{const{message:t}=e;return"tool_calls"in t&&Array.isArray(t.tool_calls)?t.tool_calls:[]});if(void 0===t[0])throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[n]=t;return await this._validateResult(n.args)}}function Ib(e,t){const n=function(e){let t=[];const n=[];e.forEach(e=>{if(em(e)){const[n]=function(e){return e.every(e=>"functionDeclarations"in e&&Array.isArray(e.functionDeclarations))?e:[{functionDeclarations:e.map(e=>{if(em(e)){const t=mb(e.schema);return"object"===t.type&&"properties"in t&&0===Object.keys(t.properties).length?{name:e.name,description:e.description}:{name:e.name,description:e.description,parameters:t}}return nf(e)?{name:e.function.name,description:e.function.description??"A function available to call.",parameters:gb(e.function.parameters)}:e})}]}([e]);n.functionDeclarations&&t.push(...n.functionDeclarations)}else if(nf(e)){const{functionDeclarations:n}=function(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:fb(e.function.parameters)}]}}(e);if(!n)throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool");t.push(...n)}else n.push(e)});const r=n.find(e=>"functionDeclarations"in e);if(r)return n.map(e=>{if(t?.length>0&&"functionDeclarations"in e){const n={functionDeclarations:[...e.functionDeclarations||[],...t]};return t=[],n}return e});return[...n,...t.length>0?[{functionDeclarations:t}]:[]]}(e),r=function(e,t){if(!e.length||!t)return;const{toolChoice:n,allowedFunctionNames:r}=t,s={any:$v.ANY,auto:$v.AUTO,none:$v.NONE};if(n&&["any","auto","none"].includes(n))return{functionCallingConfig:{mode:s[n]??"MODE_UNSPECIFIED",allowedFunctionNames:r}};if("string"==typeof n||r)return{functionCallingConfig:{mode:$v.ANY,allowedFunctionNames:[...r??[],...n&&"string"==typeof n?[n]:[]]}};return}(n,t);return{tools:n,toolConfig:r}}class Ab extends lf{static lc_name(){return"ChatGoogleGenerativeAI"}get lc_secrets(){return{apiKey:"GOOGLE_API_KEY"}}get lc_aliases(){return{apiKey:"google_api_key"}}get _isMultimodalModel(){return this.model.includes("vision")||this.model.startsWith("gemini-1.5")||this.model.startsWith("gemini-2")}constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","chat_models","google_genai"]}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxOutputTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topK",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"safetySettings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"json",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"convertSystemMessageToHumanContent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.model=e.model.replace(/^models\//,""),this.maxOutputTokens=e.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw new Error("`maxOutputTokens` must be a positive integer");if(this.temperature=e.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw new Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=e.topP??this.topP,this.topP&&this.topP<0)throw new Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw new Error("`topP` must be below 1.");if(this.topK=e.topK??this.topK,this.topK&&this.topK<0)throw new Error("`topK` must be a positive integer");if(this.stopSequences=e.stopSequences??this.stopSequences,this.apiKey=e.apiKey??Ys("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=e.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0){const e=new Set(this.safetySettings.map(e=>e.category));if(e.size!==this.safetySettings.length)throw new Error("The categories in `safetySettings` array must be unique")}this.streaming=e.streaming??this.streaming,this.json=e.json,this.client=new pb(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:"application/json"}:{}}},{apiVersion:e.apiVersion,baseUrl:e.baseUrl}),this.streamUsage=e.streamUsage??this.streamUsage}useCachedContent(e,t,n){this.apiKey&&(this.client=new pb(this.apiKey).getGenerativeModelFromCachedContent(e,t,n))}get useSystemInstruction(){return"boolean"==typeof this.convertSystemMessageToHumanContent?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return"gemini-1.0-pro-001"!==this.model&&(!this.model.startsWith("gemini-pro-vision")&&(!this.model.startsWith("gemini-1.0-pro-vision")&&"gemini-pro"!==this.model))}getLsParams(e){return{ls_provider:"google_genai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:e.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(e,t){return this.withConfig({tools:Ib(e)?.tools,...t})}invocationParams(e){const t=e?.tools?.length?Ib(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return e?.responseSchema?(this.client.generationConfig.responseSchema=e.responseSchema,this.client.generationConfig.responseMimeType="application/json"):(this.client.generationConfig.responseSchema=void 0,this.client.generationConfig.responseMimeType=this.json?"application/json":void 0),{...t?.tools?{tools:t.tools}:{},...t?.toolConfig?{toolConfig:t.toolConfig}:{}}}async _generate(e,t,n){const r=xb(e,this._isMultimodalModel,this.useSystemInstruction);let s=r;if("system"===r[0].role){const[e]=r;this.client.systemInstruction=e,s=r.slice(1)}const i=this.invocationParams(t);if(this.streaming){const r={},s=this._streamResponseChunks(e,t,n),i={};for await(const e of s){const t=e.generationInfo?.completion??0;void 0===i[t]?i[t]=e:i[t]=i[t].concat(e)}const a=Object.entries(i).sort(([e],[t])=>parseInt(e,10)-parseInt(t,10)).map(([e,t])=>t);return{generations:a,llmOutput:{estimatedTokenUsage:r}}}const a=await this.completionWithRetry({...i,contents:s});let o;if("usageMetadata"in a.response){const e=a.response.usageMetadata;o={input_tokens:e.promptTokenCount??0,output_tokens:e.candidatesTokenCount??0,total_tokens:e.totalTokenCount??0}}const l=function(e,t){if(!e.candidates||0===e.candidates.length||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};const n=e.functionCalls(),[r]=e.candidates,{content:s,...i}=r;let a;a=Array.isArray(s?.parts)&&1===s.parts.length&&s.parts[0].text?s.parts[0].text:Array.isArray(s?.parts)&&s.parts.length>0?s.parts.map(e=>"text"in e?{type:"text",text:e.text}:"executableCode"in e?{type:"executableCode",executableCode:e.executableCode}:"codeExecutionResult"in e?{type:"codeExecutionResult",codeExecutionResult:e.codeExecutionResult}:e):[];let o="";if("string"==typeof a)o=a;else if(Array.isArray(a)&&a.length>0){const e=a.find(e=>"text"in e);o=e?.text??o}return{generations:[{text:o,message:new fn({content:a??"",tool_calls:n?.map(e=>({...e,type:"tool_call",id:"id"in e&&"string"==typeof e.id?e.id:Eb()})),additional_kwargs:{...i},usage_metadata:t?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:t?.usageMetadata?.input_tokens,completionTokens:t?.usageMetadata?.output_tokens,totalTokens:t?.usageMetadata?.total_tokens}}}}(a.response,{usageMetadata:o});return l.generations?.length>0&&await(n?.handleLLMNewToken(l.generations[0]?.text??"")),l}async*_streamResponseChunks(e,t,n){const r=xb(e,this._isMultimodalModel,this.useSystemInstruction);let s=r;if("system"===r[0].role){const[e]=r;this.client.systemInstruction=e,s=r.slice(1)}const i={...this.invocationParams(t),contents:s},a=await this.caller.callWithOptions({signal:t?.signal},async()=>{const{stream:e}=await this.client.generateContentStream(i);return e});let o,l=0;for await(const e of a){if("usageMetadata"in e&&!1!==this.streamUsage&&!1!==t.streamUsage){const t=e.usageMetadata;if(o){const e=(t.candidatesTokenCount??0)-o.output_tokens;o={input_tokens:0,output_tokens:e,total_tokens:e}}else o={input_tokens:t.promptTokenCount??0,output_tokens:t.candidatesTokenCount??0,total_tokens:t.totalTokenCount??0}}const r=Ob(e,{usageMetadata:o,index:l});l+=1,r&&(yield r,await(n?.handleLLMNewToken(r.text??"")))}}async completionWithRetry(e,t){return this.caller.callWithOptions({signal:t?.signal},async()=>{try{return await this.client.generateContent(e)}catch(e){throw e.message?.includes("400 Bad Request")&&(e.status=400),e}})}withStructuredOutput(e,t){const n=e,r=t?.name,s=t?.method,i=t?.includeRaw;if("jsonMode"===s)throw new Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let a,o;if("functionCalling"===s){let e,t=r??"extract";if(Qo(n)){const r=mb(n);e=[{functionDeclarations:[{name:t,description:r.description??"A function available to call.",parameters:r}]}],o=new Tb({returnSingle:!0,keyName:t,zodSchema:n})}else{let r;"string"==typeof n.name&&"object"==typeof n.parameters&&null!=n.parameters?(r=n,r.parameters=fb(n.parameters),t=n.name):r={name:t,description:n.description??"",parameters:fb(n)},e=[{functionDeclarations:[r]}],o=new Tb({returnSingle:!0,keyName:t})}a=this.bindTools(e).withConfig({allowedFunctionNames:[t]})}else{const e=mb(n);a=this.withConfig({responseSchema:e}),o=new mf}if(!i)return a.pipe(o).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});const l=af.assign({parsed:(e,t)=>o.invoke(e.raw,t)}),c=af.assign({parsed:()=>null}),u=l.withFallbacks({fallbacks:[c]});return El.from([{raw:a},u]).withConfig({runName:"StructuredOutputRunnable"})}}const Pb=Je(["nxtscape","openai","anthropic","gemini","ollama"]),Cb=He({model:De().optional()}),$b=He({apiKey:De().optional(),model:De().optional(),baseUrl:De().optional()}),Rb=He({apiKey:De().optional(),model:De().optional(),baseUrl:De().optional()}),Nb=He({apiKey:De().optional(),model:De().optional(),baseUrl:De().optional()}),jb=He({apiKey:De().optional(),baseUrl:De().optional(),model:De().optional()}),Lb=He({defaultProvider:Pb,nxtscape:Cb,openai:$b,anthropic:Rb,gemini:Nb,ollama:jb}),Mb=(He({provider:Je(["openai","anthropic","gemini","ollama"]),model:De(),apiKey:De().optional(),baseUrl:De().url().optional(),useProxy:Fe(),temperature:Ue().min(0).max(2).optional()}),{DEFAULT_PROVIDER:"nxtscape.default_provider",NXTSCAPE_MODEL:"nxtscape.nxtscape_model",OPENAI_API_KEY:"nxtscape.openai_api_key",OPENAI_MODEL:"nxtscape.openai_model",OPENAI_BASE_URL:"nxtscape.openai_base_url",ANTHROPIC_API_KEY:"nxtscape.anthropic_api_key",ANTHROPIC_MODEL:"nxtscape.anthropic_model",ANTHROPIC_BASE_URL:"nxtscape.anthropic_base_url",GEMINI_API_KEY:"nxtscape.gemini_api_key",GEMINI_MODEL:"nxtscape.gemini_model",GEMINI_BASE_URL:"nxtscape.gemini_base_url",OLLAMA_API_KEY:"nxtscape.ollama_api_key",OLLAMA_BASE_URL:"nxtscape.ollama_base_url",OLLAMA_MODEL:"nxtscape.ollama_model"}),Db={"nxtscape.default_provider":"nxtscape","nxtscape.nxtscape_model":"gpt-4o-mini","nxtscape.openai_api_key":"TBD","nxtscape.openai_model":"gpt-4o","nxtscape.openai_base_url":void 0,"nxtscape.anthropic_api_key":"TBD","nxtscape.anthropic_model":"claude-3-5-sonnet-latest","nxtscape.anthropic_base_url":void 0,"nxtscape.gemini_api_key":"TBD","nxtscape.gemini_model":"gemini-2.0-flash","nxtscape.gemini_base_url":void 0,"nxtscape.ollama_base_url":"http://localhost:11434","nxtscape.ollama_model":"qwen3:4b","nxtscape.ollama_api_key":void 0};class Ub{static setMockPreferences(e){nt()?(Object.assign(Db,e),st.log("LLMSettingsReader",`Mock preferences updated: ${JSON.stringify(e)}`)):st.log("LLMSettingsReader","setMockPreferences is only available in development mode","warning")}static async read(){try{st.log("LLMSettingsReader","Reading LLM settings from Chrome preferences");const e=await this.getPreferences(),t={defaultProvider:this.getProviderType(e[Mb.DEFAULT_PROVIDER]),nxtscape:{model:e[Mb.NXTSCAPE_MODEL]},openai:{apiKey:e[Mb.OPENAI_API_KEY],model:e[Mb.OPENAI_MODEL],baseUrl:e[Mb.OPENAI_BASE_URL]},anthropic:{apiKey:e[Mb.ANTHROPIC_API_KEY],model:e[Mb.ANTHROPIC_MODEL],baseUrl:e[Mb.ANTHROPIC_BASE_URL]},gemini:{apiKey:e[Mb.GEMINI_API_KEY],model:e[Mb.GEMINI_MODEL],baseUrl:e[Mb.GEMINI_BASE_URL]},ollama:{apiKey:e[Mb.OLLAMA_API_KEY],baseUrl:e[Mb.OLLAMA_BASE_URL],model:e[Mb.OLLAMA_MODEL]}},n=Lb.parse(t);return st.log("LLMSettingsReader",`Settings loaded successfully. Provider: ${n.defaultProvider}`),n}catch(e){const t=e instanceof Error?e.message:String(e);return st.log("LLMSettingsReader",`Failed to read settings: ${t}`,"error"),{defaultProvider:"nxtscape",nxtscape:{},openai:{},anthropic:{},gemini:{},ollama:{}}}}static async getPreferences(){if("undefined"==typeof chrome||!chrome.settingsPrivate||!chrome.settingsPrivate.getPref)return nt()?(st.log("LLMSettingsReader","Chrome settingsPrivate API not available, using mock values for development","warning"),st.log("LLMSettingsReader",`Mock provider: ${Db["nxtscape.default_provider"]}`),Db):(st.log("LLMSettingsReader","Chrome settingsPrivate API not available, using defaults","warning"),{});const e=Object.entries(Mb).map(([e,t])=>new Promise(e=>{chrome.settingsPrivate.getPref(t,n=>{if(chrome.runtime.lastError)st.log("LLMSettingsReader",`Failed to read preference ${t}: ${chrome.runtime.lastError.message}`,"warning"),e([t,void 0]);else{const r=n?.value;e([t,r])}})})),t=await Promise.all(e);return Object.fromEntries(t)}static getProviderType(e){return e&&["nxtscape","openai","anthropic","gemini","ollama"].includes(e)?e:"nxtscape"}static async readPreference(e){return"undefined"!=typeof chrome&&chrome.settingsPrivate&&chrome.settingsPrivate.getPref?new Promise(t=>{chrome.settingsPrivate.getPref(e,n=>{if(chrome.runtime.lastError)st.log("LLMSettingsReader",`Failed to read preference ${e}: ${chrome.runtime.lastError.message}`,"warning"),t(void 0);else{const e=n?.value;t(e)}})}):nt()?(st.log("LLMSettingsReader",`Chrome settingsPrivate API not available, using mock value for ${e}`,"warning"),Db[e]):void st.log("LLMSettingsReader","Chrome settingsPrivate API not available","warning")}}const Fb=.7,Bb=!0,qb=new Map;He({provider:Je(["openai","anthropic","ollama","nxtscape","gemini"]),model:De(),temperature:Ue().default(Fb),maxTokens:Ue().optional(),streaming:Fe().default(Bb),apiKey:De().optional(),baseURL:De().optional()});class zb{constructor(){this.settings=null}static getInstance(){return zb.instance||(zb.instance=new zb),zb.instance}async getLLM(e){this.settings=await Ub.read();const t=this._createConfigFromSettings(this.settings,e),n=this._getCacheKey(t);if(qb.has(n))return qb.get(n);const r=this._createLLM(t);return qb.set(n,r),r}createLLMFromConfig(e){const t=this._getCacheKey(e);if(qb.has(t))return qb.get(t);const n=this._createLLM(e);return qb.set(t,n),n}clearCache(){qb.clear(),this.settings=null}_createConfigFromSettings(e,t){const n=e.defaultProvider;switch(n){case"nxtscape":return{provider:"nxtscape",model:e.nxtscape?.model||"claude-3-5-sonnet",temperature:t?.temperature??Fb,maxTokens:t?.maxTokens,streaming:Bb,apiKey:"sk-xmIa7rAyujEDHPLRyYpwzQ",baseURL:"http://llm.nxtscape.ai"};case"openai":return{provider:"openai",model:e.openai?.model||"gpt-4o",temperature:t?.temperature??Fb,maxTokens:t?.maxTokens,streaming:Bb,apiKey:e.openai?.apiKey||process.env.OPENAI_API_KEY,baseURL:e.openai?.baseUrl};case"anthropic":return{provider:"anthropic",model:e.anthropic?.model||"claude-4-sonnet",temperature:t?.temperature??Fb,maxTokens:t?.maxTokens,streaming:Bb,apiKey:e.anthropic?.apiKey||process.env.ANTHROPIC_API_KEY,baseURL:e.anthropic?.baseUrl};case"ollama":return{provider:"ollama",model:e.ollama?.model||"qwen3:4b",temperature:t?.temperature??Fb,maxTokens:t?.maxTokens,streaming:Bb,baseURL:e.ollama?.baseUrl||"http://localhost:11434"};case"gemini":return{provider:"gemini",model:e.gemini?.model||"gemini-2.0-flash",temperature:t?.temperature??Fb,maxTokens:t?.maxTokens,streaming:Bb,apiKey:e.gemini?.apiKey||process.env.GOOGLE_API_KEY};default:throw new Error(`Unsupported provider: ${n}`)}}_createLLM(e){const t={modelName:e.model,temperature:e.temperature,maxTokens:e.maxTokens,streaming:e.streaming};switch(e.provider){case"nxtscape":return new vm({...t,openAIApiKey:e.apiKey,configuration:{baseURL:e.baseURL,apiKey:e.apiKey,dangerouslyAllowBrowser:!0}});case"openai":return new vm({...t,openAIApiKey:e.apiKey,configuration:e.baseURL?{baseURL:e.baseURL,dangerouslyAllowBrowser:!0}:{dangerouslyAllowBrowser:!0}});case"anthropic":return new xy({...t,anthropicApiKey:e.apiKey,anthropicApiUrl:e.baseURL});case"ollama":return new wv({model:e.model,temperature:e.temperature,maxRetries:2,baseUrl:e.baseURL});case"gemini":return new Ab({model:e.model,temperature:e.temperature,maxOutputTokens:e.maxTokens,apiKey:e.apiKey,convertSystemMessageToHumanContent:!0});default:throw new Error(`Unsupported provider: ${e.provider}`)}}_getCacheKey(e){return`${e.provider}-${e.model}-${e.temperature}-${e.maxTokens||"default"}`}}const Hb=zb.getInstance();He({id:Ue().int().positive(),content:De(),status:Je(["todo","doing","done","skipped"])});class Wb{constructor(){this.todos=[]}getAll(){return[...this.todos]}addMultiple(e){const t=this.todos.length+1,n=e.map((e,n)=>({id:t+n,content:e,status:"todo"}));this.todos.push(...n),this.todos.length>Wb.MAX_TODOS&&(this.todos=this.todos.slice(0,Wb.MAX_TODOS))}completeMultiple(e){e.forEach(e=>{const t=this.todos.find(t=>t.id===e);t&&(t.status="done")})}skip(e){this.todos=this.todos.filter(t=>t.id!==e),this._reindex()}replaceAll(e){this.todos=[],this.addMultiple(e)}markDoing(e){const t=this.todos.find(e=>"doing"===e.status);if(t&&t.id!==e)throw new Error(`Cannot mark TODO ${e} as doing - TODO ${t.id} is already in progress`);const n=this.todos.find(t=>t.id===e);n&&(n.status="doing")}getNextTodo(){const e=this.getCurrentDoing();if(e)return e;const t=this.getPending();if(0===t.length)return null;const n=t[0];return this.markDoing(n.id),n}getCurrentDoing(){return this.todos.find(e=>"doing"===e.status)||null}getPending(){return this.todos.filter(e=>"todo"===e.status)}isAllDoneOrSkipped(){return this.todos.every(e=>"done"===e.status||"skipped"===e.status)}isCompleted(e){const t=this.todos.find(t=>t.id===e);return!!t&&("done"===t.status||"skipped"===t.status)}getXml(){if(0===this.todos.length)return"";return`\n${this.todos.map(e=>`${this._escapeXml(e.content)}`).join("\n")}\n`}getJson(){return[...this.todos]}reset(){this.todos=[]}_reindex(){this.todos.forEach((e,t)=>{e.id=t+1})}_escapeXml(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}}Wb.MAX_TODOS=30;const Gb=He({browserContext:Me(Ft),messageManager:Me(Nl),abortController:Me(AbortController),debugMode:Fe().default(!1),eventBus:Me(lt).optional(),eventProcessor:Me(ht).optional(),todoStore:Me(Wb).optional()});class Kb{constructor(e){this.eventBus=null,this.eventProcessor=null,this.selectedTabIds=null,this.userInitiatedCancel=!1,this._isExecuting=!1,this._lockedTabId=null,this._currentTask=null;const t=Gb.parse(e);this.abortController=t.abortController,this.browserContext=t.browserContext,this.messageManager=t.messageManager,this.debugMode=t.debugMode||!1,this.eventBus=t.eventBus||null,this.eventProcessor=t.eventProcessor||null,this.todoStore=t.todoStore||new Wb,this.userInitiatedCancel=!1}setSelectedTabIds(e){this.selectedTabIds=e}getSelectedTabIds(){return this.selectedTabIds}setEventBus(e){this.eventBus=e}getEventBus(){if(!this.eventBus)throw new Error("EventBus not set. Call setEventBus first.");return this.eventBus}setEventProcessor(e){this.eventProcessor=e}getEventProcessor(){if(!this.eventProcessor)throw new Error("EventProcessor not set. Call setEventProcessor first.");return this.eventProcessor}cancelExecution(e=!1){this.userInitiatedCancel=e,this.abortController.abort()}isUserCancellation(){return this.userInitiatedCancel&&this.abortController.signal.aborted}resetAbortController(){this.userInitiatedCancel=!1,this.abortController=new AbortController}startExecution(e){this._isExecuting=!0,this._lockedTabId=e}endExecution(){this._isExecuting=!1}isExecuting(){return this._isExecuting}getLockedTabId(){return this._lockedTabId}reset(){this._isExecuting=!1,this._lockedTabId=null,this.userInitiatedCancel=!1,this._currentTask=null,this.todoStore.reset()}async getLLM(e){return async function(e){return Hb.getLLM(e)}(e)}setCurrentTask(e){this._currentTask=e}getCurrentTask(){return this._currentTask}}class Jb{constructor(e){this.tools=new Map,this.executionContext=e}register(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getDescriptions(){const e=this.getAll();if(0===e.length)return"No tools available.";const t=e.map(e=>`- ${e.name}: ${e.description}`).join("\n");return`Available tools:\n${t}`}}const Zb=5;He({ok:Fe(),output:De()});function Vb(e){return{ok:!0,output:e}}function Yb(e){return{ok:!1,output:e}}const Xb=He({task:De(),max_steps:Ue().default(Zb)}),Qb=He({steps:ze(He({action:De(),reasoning:De()}))});function ew(e){return new Em({name:"planner_tool",description:`Generate up to ${Zb} steps for the task`,schema:Xb,func:async t=>{try{const n=await e.getLLM(),r=new Rl(e.messageManager).getAll().map(e=>`${e._getType()}: ${e.content}`).join("\n"),s=await e.browserContext.getBrowserStateString(),i=`You are a helpful assistant that excels at analyzing tasks and breaking them down into actionable steps.\n\n# RESPONSIBILITIES:\n1. Analyze the current state and conversation history to understand what has been accomplished\n2. Evaluate progress towards the ultimate goal\n3. Identify potential challenges or roadblocks\n4. Generate specific, actionable next steps (maximum ${Zb} steps)\n5. Provide clear reasoning for your suggested approach\n\n# PLANNING GUIDELINES:\n- Keep plans SHORT and FOCUSED: Maximum of ${Zb} steps at a time. \n- You need NOT generate ${Zb} steps if the task is simple, even 1 or 2 step plan is fine.\n- Focus on WHAT to achieve, not HOW to do it\n- Each step should be a logical business action or goal\n- Order steps logically with dependencies in mind\n- Think in terms of user objectives, not technical implementations\n- If you know specific sites/URLs, mention them (e.g., "Navigate to Amazon")\n- Let the browser agent handle the technical details of each step\n\n# STEP FORMAT:\nEach step should describe WHAT to achieve, not HOW:\n- "Navigate to Amazon" (not "Click on address bar and type amazon.com")\n- "Search for toothpaste" (not "Click search box, type toothpaste, press enter")\n- "Select a suitable product" (not "Click on the first result with 4+ stars")\n- "Add product to cart" (not "Find and click the Add to Cart button")\n- "Proceed to checkout" (not "Click on cart icon then checkout button")\n\n# OUTPUT FORMAT:\nYou must return a JSON object with the following structure:\n{\n "steps": [\n {\n "action": "High-level description of what to do",\n "reasoning": "Why this step is necessary"\n }\n ]\n}\n\n# REMEMBER:\n- Maximum ${Zb} steps focusing on business objectives. You can generate 1 or 2 step plan as well, if the objective is simple.\n- Keep steps high-level and goal-oriented\n- Consider what has already been accomplished\n- The user can see the page - they often refer to visible elements`,a=function(e,t,n,r){return`PLANNING REQUEST:\n- Generate upto ${t} next steps to accomplish the task. You can generate a plan for fewer steps as well, if the task can achieved in fewer steps.\n- Task: ${e}\n- DO NOT repeat completed actions, BUILD on current progress.\n\nBelow is the conversation history and browser state. Use this to provide a plan with ${t} actionable steps or fewer steps if the task is simple.\n\n--------------------------------\nConversation history:\n--------------------------------\n${n}\n\n--------------------------------\nBrowser state:\n--------------------------------\n${r}\n`}(t.task,t.max_steps,r,s),o=n.withStructuredOutput(Qb),l=await o.invoke([new Sn(i),new wn(a)]);return JSON.stringify({ok:!0,output:l})}catch(e){const t=e instanceof Error?e.message:String(e);return JSON.stringify(Yb(`Planning failed: ${t}`))}}})}const tw=He({action:Je(["list","add_multiple","complete_multiple","skip","replace_all"]),todos:ze(He({content:De()})).optional(),ids:ze(Ue().int()).optional()});const nw=He({summary:De().optional()});const rw="https://",sw=He({action:Je(["navigate","back","forward","refresh"]),url:De().optional()});class iw{constructor(e){this.executionContext=e}async execute(e){switch(e.action){case"navigate":return this._navigateToUrl(e.url);case"back":return this._goBack();case"forward":return this._goForward();case"refresh":return this._refresh()}}async _navigateToUrl(e){if(!e)return Yb("URL is required for navigate action");try{const t=this._normalizeUrl(e),n=await this.executionContext.browserContext.getCurrentPage();await n.navigateTo(t);const[r,s]=await Promise.all([n.url(),n.title()]);return Vb(`Navigated to ${r} - ${s}`)}catch(t){const n=t instanceof Error?t.message:String(t);return n.includes("not allowed")?Yb(`URL not allowed: ${e}. This URL is restricted by security policy.`):Yb(`Navigation failed: ${n}`)}}async _goBack(){try{const e=await this.executionContext.browserContext.getCurrentPage();await e.goBack();const[t,n]=await Promise.all([e.url(),e.title()]);return Vb(`Went back to ${t} - ${n}`)}catch(e){const t=e instanceof Error?e.message:String(e);return t.includes("Cannot navigate back")||t.includes("no previous page")?Yb("Cannot go back - no previous page in history"):Yb(`Failed to go back: ${t}`)}}async _goForward(){try{const e=await this.executionContext.browserContext.getCurrentPage();await e.goForward();const[t,n]=await Promise.all([e.url(),e.title()]);return Vb(`Went forward to ${t} - ${n}`)}catch(e){const t=e instanceof Error?e.message:String(e);return t.includes("Cannot navigate forward")||t.includes("no next page")?Yb("Cannot go forward - no next page in history"):Yb(`Failed to go forward: ${t}`)}}async _refresh(){try{const e=await this.executionContext.browserContext.getCurrentPage();await e.refreshPage();const[t,n]=await Promise.all([e.url(),e.title()]);return Vb(`Refreshed ${t} - ${n}`)}catch(e){return Yb(`Failed to refresh: ${e instanceof Error?e.message:String(e)}`)}}_normalizeUrl(e){if(e.startsWith("http://")||e.startsWith(rw))return e;return e.includes(".")&&!e.includes(" ")?rw+e:"https://www.google.com/search?q="+encodeURIComponent(e)}}const aw=He({elementDescription:De(),intent:De().optional()}),ow=He({found:Fe().describe("Whether a matching element was found"),index:Ue().nullable().describe("The index number of the best matching element (null if not found)"),confidence:Je(["high","medium","low"]).nullable().describe("Confidence level in the match (null if not found)"),reasoning:De().describe("Brief explanation of the decision")});class lw{constructor(e){this.executionContext=e}async execute(e){try{const t=await this.executionContext.browserContext.getBrowserState();if(!t.clickableElements.length&&!t.typeableElements.length)return Yb("No interactive elements found on the current page");const n=this.executionContext.getCurrentTask(),r=await this._findElementWithLLM(e.elementDescription,t.clickableElementsString+"\n"+t.typeableElementsString,n);if(!r.found||null===r.index)return Yb(r.reasoning||`No element found matching "${e.elementDescription}"`);const s=t.clickableElements.find(e=>e.nodeId===r.index),i=t.typeableElements.find(e=>e.nodeId===r.index);return s||i?Vb(JSON.stringify(r)):Yb(`Invalid index ${r.index} returned - element not found`)}catch(e){return Yb(`Failed to find element: ${e instanceof Error?e.message:String(e)}`)}}async _findElementWithLLM(e,t,n){const r=(await this.executionContext.getLLM()).withStructuredOutput(ow);let s=`Find the element matching this description: "${e}"`;n&&(s=`User's goal: ${n}\n\n${s}`),s+=`\n\nInteractive elements on the page:\n${t}`;return await r.invoke([new Sn('You are an expert at finding elements on web pages.\n\nWhen the user\'s overall goal is provided, use it to better understand which element they\'re looking for.\n\nYour task is to find the element that best matches the user\'s description.\n\n**ELEMENT FORMAT:**\nElements are shown with nodeId in square brackets followed by element details:\n\nClickable elements ():\n[88] "Add to Cart" ctx:"One-time purchase: $17.97..." path:"rootWebArea>genericContainer>button"\n[23] "Hello, sign in Account & Lists" ctx:"Hello, sign in..." path:"genericContainer>link"\n[2]