sliccy 1.22.1 → 1.22.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-tzzI-w2Q.js","assets/stream-lEC9OYG2.js","assets/index-CTwqCjQD.js","assets/___vite-browser-external_commonjs-proxy-BaP7fEvT.js","assets/__vite-browser-external-D7Ct-6yo.js","assets/index-Cj6gFnz_.js","assets/sql-wasm-CgIJhlRQ.js","assets/index-DzGPKzGT.js","assets/xterm-DOrYoP_4.css"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DaQtug-G.js","assets/stream-lEC9OYG2.js","assets/index-DT33yILt.js","assets/___vite-browser-external_commonjs-proxy-HEKiI6EW.js","assets/__vite-browser-external-D7Ct-6yo.js","assets/index-CqKk1FTy.js","assets/sql-wasm-r2NFfZ6X.js","assets/index-B73vno6G.js","assets/xterm-DOrYoP_4.css"])))=>i.map(i=>d[i]);
2
2
  (function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const a of r)if(a.type==="childList")for(const l of a.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&i(l)}).observe(document,{childList:!0,subtree:!0});function n(r){const a={};return r.integrity&&(a.integrity=r.integrity),r.referrerPolicy&&(a.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?a.credentials="include":r.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(r){if(r.ep)return;r.ep=!0;const a=n(r);fetch(r.href,a)}})();const qCe="modulepreload",BCe=function(e){return"/"+e},XD={},fn=function(t,n,i){let r=Promise.resolve();if(n&&n.length>0){let l=function(s){return Promise.all(s.map(u=>Promise.resolve(u).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),o=c?.nonce||c?.getAttribute("nonce");r=l(n.map(s=>{if(s=BCe(s),s in XD)return;XD[s]=!0;const u=s.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${s}"]${d}`))return;const p=document.createElement("link");if(p.rel=u?"stylesheet":qCe,u||(p.as="script"),p.crossOrigin="",p.href=s,o&&p.setAttribute("nonce",o),document.head.appendChild(p),u)return new Promise((f,h)=>{p.addEventListener("load",f),p.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${s}`)))})}))}function a(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&a(c.reason);return t().catch(a)})};function pP(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Gy=pP();function Vie(e){Gy=e}var yy={exec:()=>null};function nr(e,t=""){let n=typeof e=="string"?e:e.source,i={replace:(r,a)=>{let l=typeof a=="string"?a:a.source;return l=l.replace(wa.caret,"$1"),n=n.replace(r,l),i},getRegex:()=>new RegExp(n,t)};return i}var WCe=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),wa={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},zCe=/^(?:[ \t]*(?:\n|$))+/,GCe=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,HCe=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,d2=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,VCe=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,fP=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Jie=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Kie=nr(Jie).replace(/bull/g,fP).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),JCe=nr(Jie).replace(/bull/g,fP).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),hP=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,KCe=/^[^\n]+/,mP=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ZCe=nr(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",mP).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),XCe=nr(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,fP).getRegex(),K3="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",gP=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,QCe=nr("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",gP).replace("tag",K3).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Zie=nr(hP).replace("hr",d2).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",K3).getRegex(),YCe=nr(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Zie).getRegex(),yP={blockquote:YCe,code:GCe,def:ZCe,fences:HCe,heading:VCe,hr:d2,html:QCe,lheading:Kie,list:XCe,newline:zCe,paragraph:Zie,table:yy,text:KCe},QD=nr("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",d2).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",K3).getRegex(),eTe={...yP,lheading:JCe,table:QD,paragraph:nr(hP).replace("hr",d2).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",QD).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",K3).getRegex()},tTe={...yP,html:nr(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",gP).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:yy,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:nr(hP).replace("hr",d2).replace("heading",` *#{1,6} *[^
3
3
  ]`).replace("lheading",Kie).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},nTe=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,rTe=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Xie=/^( {2,}|\\)\n(?!\s*$)/,iTe=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Z3=/[\p{P}\p{S}]/u,vP=/[\s\p{P}\p{S}]/u,Qie=/[^\s\p{P}\p{S}]/u,aTe=nr(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,vP).getRegex(),Yie=/(?!~)[\p{P}\p{S}]/u,sTe=/(?!~)[\s\p{P}\p{S}]/u,oTe=/(?:[^\s\p{P}\p{S}]|~)/u,eae=/(?![*_])[\p{P}\p{S}]/u,lTe=/(?![*_])[\s\p{P}\p{S}]/u,cTe=/(?:[^\s\p{P}\p{S}]|[*_])/u,uTe=nr(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",WCe?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),tae=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,dTe=nr(tae,"u").replace(/punct/g,Z3).getRegex(),pTe=nr(tae,"u").replace(/punct/g,Yie).getRegex(),nae="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",fTe=nr(nae,"gu").replace(/notPunctSpace/g,Qie).replace(/punctSpace/g,vP).replace(/punct/g,Z3).getRegex(),hTe=nr(nae,"gu").replace(/notPunctSpace/g,oTe).replace(/punctSpace/g,sTe).replace(/punct/g,Yie).getRegex(),mTe=nr("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Qie).replace(/punctSpace/g,vP).replace(/punct/g,Z3).getRegex(),gTe=nr(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,eae).getRegex(),yTe="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",vTe=nr(yTe,"gu").replace(/notPunctSpace/g,cTe).replace(/punctSpace/g,lTe).replace(/punct/g,eae).getRegex(),bTe=nr(/\\(punct)/,"gu").replace(/punct/g,Z3).getRegex(),wTe=nr(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),_Te=nr(gP).replace("(?:-->|$)","-->").getRegex(),xTe=nr("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",_Te).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ST=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,STe=nr(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",ST).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),rae=nr(/^!?\[(label)\]\[(ref)\]/).replace("label",ST).replace("ref",mP).getRegex(),iae=nr(/^!?\[(ref)\](?:\[\])?/).replace("ref",mP).getRegex(),CTe=nr("reflink|nolink(?!\\()","g").replace("reflink",rae).replace("nolink",iae).getRegex(),YD=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,bP={_backpedal:yy,anyPunctuation:bTe,autolink:wTe,blockSkip:uTe,br:Xie,code:rTe,del:yy,delLDelim:yy,delRDelim:yy,emStrongLDelim:dTe,emStrongRDelimAst:fTe,emStrongRDelimUnd:mTe,escape:nTe,link:STe,nolink:iae,punctuation:aTe,reflink:rae,reflinkSearch:CTe,tag:xTe,text:iTe,url:yy},TTe={...bP,link:nr(/^!?\[(label)\]\((.*?)\)/).replace("label",ST).getRegex(),reflink:nr(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ST).getRegex()},rR={...bP,emStrongRDelimAst:hTe,emStrongLDelim:pTe,delLDelim:gTe,delRDelim:vTe,url:nr(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",YD).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:nr(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",YD).getRegex()},ETe={...rR,br:nr(Xie).replace("{2,}","*").getRegex(),text:nr(rR.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ox={normal:yP,gfm:eTe,pedantic:tTe},T0={normal:bP,gfm:rR,breaks:ETe,pedantic:TTe},kTe={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},ej=e=>kTe[e];function vc(e,t){if(t){if(wa.escapeTest.test(e))return e.replace(wa.escapeReplace,ej)}else if(wa.escapeTestNoEncode.test(e))return e.replace(wa.escapeReplaceNoEncode,ej);return e}function tj(e){try{e=encodeURI(e).replace(wa.percentDecode,"%")}catch{return null}return e}function nj(e,t){let n=e.replace(wa.findPipe,(a,l,c)=>{let o=!1,s=l;for(;--s>=0&&c[s]==="\\";)o=!o;return o?"|":" |"}),i=n.split(wa.splitPipe),r=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),t)if(i.length>t)i.splice(t);else for(;i.length<t;)i.push("");for(;r<i.length;r++)i[r]=i[r].trim().replace(wa.slashPipe,"|");return i}function E0(e,t,n){let i=e.length;if(i===0)return"";let r=0;for(;r<i&&e.charAt(i-r-1)===t;)r++;return e.slice(0,i-r)}function ATe(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let i=0;i<e.length;i++)if(e[i]==="\\")i++;else if(e[i]===t[0])n++;else if(e[i]===t[1]&&(n--,n<0))return i;return n>0?-2:-1}function RTe(e,t=0){let n=t,i="";for(let r of e)if(r===" "){let a=4-n%4;i+=" ".repeat(a),n+=a}else i+=r,n++;return i}function rj(e,t,n,i,r){let a=t.href,l=t.title||null,c=e[1].replace(r.other.outputLinkReplace,"$1");i.state.inLink=!0;let o={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:a,title:l,text:c,tokens:i.inlineTokens(c)};return i.state.inLink=!1,o}function OTe(e,t,n){let i=e.match(n.other.indentCodeCompensation);if(i===null)return t;let r=i[1];return t.split(`
4
4
  `).map(a=>{let l=a.match(n.other.beginningSpace);if(l===null)return a;let[c]=l;return c.length>=r.length?a.slice(r.length):a}).join(`
@@ -511,7 +511,7 @@ ${l}`),i.push({type:"error",reason:r.stopReason,error:r}),i.end()}})(),i},Vle=(e
511
511
  If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body`);return r.stream()};return Object.assign(e,{transformToByteArray:n,transformToString:async r=>{const a=await n();if(r==="base64")return Fy(a);if(r==="hex")return qa(a);if(r===void 0||r==="utf8"||r==="utf-8")return Kb(a);if(typeof TextDecoder=="function")return new TextDecoder(r).decode(a);throw new Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(t)throw new Error(sF);if(t=!0,oF(e))return i(e);if(iF(e))return e;throw new Error(`Cannot transform payload to web stream, got ${e}`)}})},oF=e=>typeof Blob=="function"&&e instanceof Blob,Jw=async(e=new Uint8Array,t)=>{if(e instanceof Uint8Array)return Ry.mutate(e);if(!e)return Ry.mutate(new Uint8Array);const n=t.streamCollector(e);return Ry.mutate(await n)};function lF(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}const W6=e=>typeof e=="function"?e():e,Yle=(e,t,n,i,r)=>({name:t,namespace:e,traits:n,input:i,output:r}),C8e=e=>(t,n)=>async i=>{const{response:r}=await t(i),{operationSchema:a}=Jb(n),[,l,c,o,s,u]=a??[];try{const d=await e.protocol.deserializeResponse(Yle(l,c,o,s,u),{...e,...n},r);return{response:r,output:d}}catch(d){if(Object.defineProperty(d,"$response",{value:r,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in d)){const p="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{d.message+=`
512
512
  `+p}catch{!n.logger||n.logger?.constructor?.name==="NoOpLogger"?console.warn(p):n.logger?.warn?.(p)}typeof d.$responseBodyText<"u"&&d.$response&&(d.$response.body=d.$responseBodyText);try{if(jy.isInstance(r)){const{headers:f={}}=r,h=Object.entries(f);d.$metadata={httpStatusCode:r.statusCode,requestId:z6(/^x-[\w-]+-request-?id$/,h),extendedRequestId:z6(/^x-[\w-]+-id-2$/,h),cfId:z6(/^x-[\w-]+-cf-id$/,h)}}}catch{}}throw d}},z6=(e,t)=>(t.find(([n])=>n.match(e))||[void 0,void 0])[1],T8e=e=>(t,n)=>async i=>{const{operationSchema:r}=Jb(n),[,a,l,c,o,s]=r??[],u=n.endpointV2?.url&&e.urlParser?async()=>e.urlParser(n.endpointV2.url):e.endpoint,d=await e.protocol.serializeRequest(Yle(a,l,c,o,s),i.input,{...e,...n,endpoint:u});return t({...i,request:d})},E8e={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},k8e={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function A8e(e){return{applyToStack:t=>{t.add(T8e(e),k8e),t.add(C8e(e),E8e),e.protocol.setSerdeContext(e)}}}function pb(e){if(typeof e=="object")return e;e=e|0;const t={};let n=0;for(const i of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])(e>>n++&1)===1&&(t[i]=1);return t}const cF={it:Symbol.for("@smithy/nor-struct-it")};class Mr{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=Mr.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(t,n){this.ref=t,this.memberName=n;const i=[];let r=t,a=t;for(this._isMemberSchema=!1;G6(r);)i.push(r[1]),r=r[0],a=W6(r),this._isMemberSchema=!0;if(i.length>0){this.memberTraits={};for(let l=i.length-1;l>=0;--l){const c=i[l];Object.assign(this.memberTraits,pb(c))}}else this.memberTraits=0;if(a instanceof Mr){const l=this.memberTraits;Object.assign(this,a),this.memberTraits=Object.assign({},l,a.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=n??a.memberName;return}if(this.schema=W6(a),R8e(this.schema)?(this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3]):(this.name=this.memberName??String(a),this.traits=0),this._isMemberSchema&&!n)throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](t){const n=this.prototype.isPrototypeOf(t);return!n&&typeof t=="object"&&t!==null?t.symbol===this.symbol:n}static of(t){const n=W6(t);if(n instanceof Mr)return n;if(G6(n)){const[i,r]=n;if(i instanceof Mr)return Object.assign(i.getMergedTraits(),pb(r)),i;throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(t,null,2)}.`)}return new Mr(n)}getSchema(){const t=this.schema;return Array.isArray(t)&&t[0]===0?t[4]:t}getName(t=!1){const{name:n}=this;return!t&&n&&n.includes("#")?n.split("#")[1]:n||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){const t=this.getSchema();return typeof t=="number"?t>=64&&t<128:t[0]===1}isMapSchema(){const t=this.getSchema();return typeof t=="number"?t>=128&&t<=255:t[0]===2}isStructSchema(){const t=this.getSchema();if(typeof t!="object")return!1;const n=t[0];return n===3||n===-3||n===4}isUnionSchema(){const t=this.getSchema();return typeof t!="object"?!1:t[0]===4}isBlobSchema(){const t=this.getSchema();return t===21||t===42}isTimestampSchema(){const t=this.getSchema();return typeof t=="number"&&t>=4&&t<=7}isUnitSchema(){return this.getSchema()==="unit"}isDocumentSchema(){return this.getSchema()===15}isStringSchema(){return this.getSchema()===0}isBooleanSchema(){return this.getSchema()===2}isNumericSchema(){return this.getSchema()===1}isBigIntegerSchema(){return this.getSchema()===17}isBigDecimalSchema(){return this.getSchema()===19}isStreaming(){const{streaming:t}=this.getMergedTraits();return!!t||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return pb(this.memberTraits)}getOwnTraits(){return pb(this.traits)}getKeySchema(){const[t,n]=[this.isDocumentSchema(),this.isMapSchema()];if(!t&&!n)throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);const i=this.getSchema(),r=t?15:i[4]??0;return Y0([r,0],"key")}getValueSchema(){const t=this.getSchema(),[n,i,r]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],a=typeof t=="number"?63&t:t&&typeof t=="object"&&(i||r)?t[3+t[0]]:n?15:void 0;if(a!=null)return Y0([a,0],i?"value":"member");throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(t){const n=this.getSchema();if(this.isStructSchema()&&n[4].includes(t)){const i=n[4].indexOf(t),r=n[5][i];return Y0(G6(r)?r:[r,0],t)}if(this.isDocumentSchema())return Y0([15,0],t);throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no no member=${t}.`)}getMemberSchemas(){const t={};try{for(const[n,i]of this.structIterator())t[n]=i}catch{}return t}getEventStreamMember(){if(this.isStructSchema()){for(const[t,n]of this.structIterator())if(n.isStreaming()&&n.isStructSchema())return t}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw new Error("@smithy/core/schema - cannot iterate non-struct schema.");const t=this.getSchema(),n=t[4].length;let i=t[cF.it];if(i&&n===i.length){yield*i;return}i=Array(n);for(let r=0;r<n;++r){const a=t[4][r],l=Y0([t[5][r],0],a);yield i[r]=[a,l]}t[cF.it]=i}}function Y0(e,t){if(e instanceof Mr)return Object.assign(e,{memberName:t,_isMemberSchema:!0});const n=Mr;return new n(e,t)}const G6=e=>Array.isArray(e)&&e.length===2,R8e=e=>Array.isArray(e)&&e.length>=5;class Ua{namespace;schemas;exceptions;static registries=new Map;constructor(t,n=new Map,i=new Map){this.namespace=t,this.schemas=n,this.exceptions=i}static for(t){return Ua.registries.has(t)||Ua.registries.set(t,new Ua(t)),Ua.registries.get(t)}copyFrom(t){const{schemas:n,exceptions:i}=this;for(const[r,a]of t.schemas)n.has(r)||n.set(r,a);for(const[r,a]of t.exceptions)i.has(r)||i.set(r,a)}register(t,n){const i=this.normalizeShapeId(t);for(const r of[this,Ua.for(i.split("#")[0])])r.schemas.set(i,n)}getSchema(t){const n=this.normalizeShapeId(t);if(!this.schemas.has(n))throw new Error(`@smithy/core/schema - schema not found for ${n}`);return this.schemas.get(n)}registerError(t,n){const i=t,r=i[1];for(const a of[this,Ua.for(r)])a.schemas.set(r+"#"+i[2],i),a.exceptions.set(i,n)}getErrorCtor(t){const n=t;return this.exceptions.has(n)?this.exceptions.get(n):Ua.for(n[1]).exceptions.get(n)}getBaseException(){for(const t of this.exceptions.keys())if(Array.isArray(t)){const[,n,i]=t,r=n+"#"+i;if(r.startsWith("smithy.ts.sdk.synthetic.")&&r.endsWith("ServiceException"))return t}}find(t){return[...this.schemas.values()].find(t)}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(t){return t.includes("#")?t:this.namespace+"#"+t}}const nO=e=>{if(e!=null){if(typeof e=="string"){const t=parseFloat(e);if(!Number.isNaN(t))return String(t)!==String(e)&&L8e.warn(j8e(`Expected number but observed string: ${e}`)),t}if(typeof e=="number")return e;throw new TypeError(`Expected number, got ${typeof e}: ${e}`)}},O8e=Math.ceil(2**127*(2-2**-23)),uF=e=>{const t=nO(e);if(t!==void 0&&!Number.isNaN(t)&&t!==1/0&&t!==-1/0&&Math.abs(t)>O8e)throw new TypeError(`Expected 32-bit float, got ${e}`);return t},I8e=e=>{if(e!=null){if(Number.isInteger(e)&&!Number.isNaN(e))return e;throw new TypeError(`Expected integer, got ${typeof e}: ${e}`)}},dF=e=>ece(e,16),pF=e=>ece(e,8),ece=(e,t)=>{const n=I8e(e);if(n!==void 0&&P8e(n,t)!==n)throw new TypeError(`Expected ${t}-bit integer, got ${e}`);return n},P8e=(e,t)=>{switch(t){case 32:return Int32Array.of(e)[0];case 16:return Int16Array.of(e)[0];case 8:return Int8Array.of(e)[0]}},M8e=e=>nO(typeof e=="string"?vE(e):e),N8e=e=>uF(typeof e=="string"?vE(e):e),$8e=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,vE=e=>{const t=e.match($8e);if(t===null||t[0].length!==e.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(e)},JT=e=>dF(typeof e=="string"?vE(e):e),D8e=e=>pF(typeof e=="string"?vE(e):e),j8e=e=>String(new TypeError(e).stack||e).split(`
513
513
  `).slice(0,5).filter(t=>!t.includes("stackTraceWarning")).join(`
514
- `),L8e={warn:console.warn},U8e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],y8=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function tce(e){const t=e.getUTCFullYear(),n=e.getUTCMonth(),i=e.getUTCDay(),r=e.getUTCDate(),a=e.getUTCHours(),l=e.getUTCMinutes(),c=e.getUTCSeconds(),o=r<10?`0${r}`:`${r}`,s=a<10?`0${a}`:`${a}`,u=l<10?`0${l}`:`${l}`,d=c<10?`0${c}`:`${c}`;return`${U8e[i]}, ${o} ${y8[n]} ${t} ${s}:${u}:${d} GMT`}const F8e=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),q8e=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");const t=F8e.exec(e);if(!t)throw new TypeError("Invalid RFC-3339 date-time value");const[n,i,r,a,l,c,o,s,u]=t,d=JT(U_(i)),p=og(r,"month",1,12),f=og(a,"day",1,31),h=$C(d,p,f,{hours:l,minutes:c,seconds:o,fractionalMilliseconds:s});return u.toUpperCase()!="Z"&&h.setTime(h.getTime()-e7e(u)),h},B8e=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),W8e=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),z8e=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),G8e=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let t=B8e.exec(e);if(t){const[n,i,r,a,l,c,o,s]=t;return $C(JT(U_(a)),H6(r),og(i,"day",1,31),{hours:l,minutes:c,seconds:o,fractionalMilliseconds:s})}if(t=W8e.exec(e),t){const[n,i,r,a,l,c,o,s]=t;return K8e($C(V8e(a),H6(r),og(i,"day",1,31),{hours:l,minutes:c,seconds:o,fractionalMilliseconds:s}))}if(t=z8e.exec(e),t){const[n,i,r,a,l,c,o,s]=t;return $C(JT(U_(s)),H6(i),og(r.trimLeft(),"day",1,31),{hours:a,minutes:l,seconds:c,fractionalMilliseconds:o})}throw new TypeError("Invalid RFC-7231 date-time value")},H8e=e=>{if(e==null)return;let t;if(typeof e=="number")t=e;else if(typeof e=="string")t=M8e(e);else if(typeof e=="object"&&e.tag===1)t=e.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(t)||t===1/0||t===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(t*1e3))},$C=(e,t,n,i)=>{const r=t-1;return X8e(e,r,n),new Date(Date.UTC(e,r,n,og(i.hours,"hour",0,23),og(i.minutes,"minute",0,59),og(i.seconds,"seconds",0,60),Y8e(i.fractionalMilliseconds)))},V8e=e=>{const t=new Date().getUTCFullYear(),n=Math.floor(t/100)*100+JT(U_(e));return n<t?n+100:n},J8e=50*365*24*60*60*1e3,K8e=e=>e.getTime()-new Date().getTime()>J8e?new Date(Date.UTC(e.getUTCFullYear()-100,e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())):e,H6=e=>{const t=y8.indexOf(e);if(t<0)throw new TypeError(`Invalid month: ${e}`);return t+1},Z8e=[31,28,31,30,31,30,31,31,30,31,30,31],X8e=(e,t,n)=>{let i=Z8e[t];if(t===1&&Q8e(e)&&(i=29),n>i)throw new TypeError(`Invalid day for ${y8[t]} in ${e}: ${n}`)},Q8e=e=>e%4===0&&(e%100!==0||e%400===0),og=(e,t,n,i)=>{const r=D8e(U_(e));if(r<n||r>i)throw new TypeError(`${t} must be between ${n} and ${i}, inclusive`);return r},Y8e=e=>e==null?0:N8e("0."+e)*1e3,e7e=e=>{const t=e[0];let n=1;if(t=="+")n=1;else if(t=="-")n=-1;else throw new TypeError(`Offset direction, ${t}, must be "+" or "-"`);const i=Number(e.substring(1,3)),r=Number(e.substring(4,6));return n*(i*60+r)*60*1e3},U_=e=>{let t=0;for(;t<e.length-1&&e.charAt(t)==="0";)t++;return t===0?e:e.slice(t)},fF=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Yi=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0")),v8=()=>{if(fF)return fF();const e=new Uint8Array(16);return crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128,Yi[e[0]]+Yi[e[1]]+Yi[e[2]]+Yi[e[3]]+"-"+Yi[e[4]]+Yi[e[5]]+"-"+Yi[e[6]]+Yi[e[7]]+"-"+Yi[e[8]]+Yi[e[9]]+"-"+Yi[e[10]]+Yi[e[11]]+Yi[e[12]]+Yi[e[13]]+Yi[e[14]]+Yi[e[15]]},Ic=function(t){return Object.assign(new String(t),{deserializeJSON(){return JSON.parse(String(t))},toString(){return String(t)},toJSON(){return String(t)}})};Ic.from=e=>e&&typeof e=="object"&&(e instanceof Ic||"deserializeJSON"in e)?e:typeof e=="string"||Object.getPrototypeOf(e)===String.prototype?Ic(String(e)):Ic(JSON.stringify(e));Ic.fromObject=Ic.from;function t7e(e){return(e.includes(",")||e.includes('"'))&&(e=`"${e.replace(/"/g,'\\"')}"`),e}const b8="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",w8="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",_8="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",nce="(\\d?\\d)",rce="(\\d{4})",n7e=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),r7e=new RegExp(`^${b8}, ${nce} ${w8} ${rce} ${_8} GMT$`),i7e=new RegExp(`^${b8}, ${nce}-${w8}-(\\d\\d) ${_8} GMT$`),a7e=new RegExp(`^${b8} ${w8} ( [1-9]|\\d\\d) ${_8} ${rce}$`),s7e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],o7e=e=>{if(e==null)return;let t=NaN;if(typeof e=="number")t=e;else if(typeof e=="string"){if(!/^-?\d*\.?\d+$/.test(e))throw new TypeError("parseEpochTimestamp - numeric string invalid.");t=Number.parseFloat(e)}else typeof e=="object"&&e.tag===1&&(t=e.value);if(isNaN(t)||Math.abs(t)===1/0)throw new TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(t*1e3))},l7e=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC3339 timestamps must be strings");const t=n7e.exec(e);if(!t)throw new TypeError(`Invalid RFC3339 timestamp format ${e}`);const[,n,i,r,a,l,c,,o,s]=t;mm(i,1,12),mm(r,1,31),mm(a,0,23),mm(l,0,59),mm(c,0,60);const u=new Date(Date.UTC(Number(n),Number(i)-1,Number(r),Number(a),Number(l),Number(c),Number(o)?Math.round(parseFloat(`0.${o}`)*1e3):0));if(u.setUTCFullYear(Number(n)),s.toUpperCase()!="Z"){const[,d,p,f]=/([+-])(\d\d):(\d\d)/.exec(s)||[void 0,"+",0,0],h=d==="-"?1:-1;u.setTime(u.getTime()+h*(Number(p)*60*60*1e3+Number(f)*60*1e3))}return u},c7e=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC7231 timestamps must be strings.");let t,n,i,r,a,l,c,o;if((o=r7e.exec(e))?[,t,n,i,r,a,l,c]=o:(o=i7e.exec(e))?([,t,n,i,r,a,l,c]=o,i=(Number(i)+1900).toString()):(o=a7e.exec(e))&&([,n,t,r,a,l,c,i]=o),i&&l){const s=Date.UTC(Number(i),s7e.indexOf(n),Number(t),Number(r),Number(a),Number(l),c?Math.round(parseFloat(`0.${c}`)*1e3):0);mm(t,1,31),mm(r,0,23),mm(a,0,59),mm(l,0,60);const u=new Date(s);return u.setUTCFullYear(Number(i)),u}throw new TypeError(`Invalid RFC7231 date-time value ${e}.`)};function mm(e,t,n){const i=Number(e);if(i<t||i>n)throw new Error(`Value ${i} out of range [${t}, ${n}]`)}function u7e(e,t,n){if(!Number.isInteger(n))throw new Error("Invalid number of delimiters ("+n+") for splitEvery.");const i=e.split(t),r=[];let a="";for(let l=0;l<i.length;l++)a===""?a=i[l]:a+=t+i[l],(l+1)%n===0&&(r.push(a),a="");return a!==""&&r.push(a),r}const ice=e=>{const t=e.length,n=[];let i=!1,r,a=0;for(let l=0;l<t;++l){const c=e[l];switch(c){case'"':r!=="\\"&&(i=!i);break;case",":i||(n.push(e.slice(a,l)),a=l+1);break}r=c}return n.push(e.slice(a)),n.map(l=>{l=l.trim();const c=l.length;return c<2?l:(l[0]==='"'&&l[c-1]==='"'&&(l=l.slice(1,c-1)),l.replace(/\\"/g,'"'))})},hF=/^-?\d*(\.\d+)?$/;class Co{string;type;constructor(t,n){if(this.string=t,this.type=n,!hF.test(t))throw new Error('@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".')}toString(){return this.string}static[Symbol.hasInstance](t){if(!t||typeof t!="object")return!1;const n=t;return Co.prototype.isPrototypeOf(t)||n.type==="bigDecimal"&&hF.test(n.string)}}class bE{serdeContext;setSerdeContext(t){this.serdeContext=t}}class d7e extends bE{options;compositeErrorRegistry;constructor(t){super(),this.options=t,this.compositeErrorRegistry=Ua.for(t.defaultNamespace);for(const n of t.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(n)}getRequestType(){return Ea}getResponseType(){return jy}setSerdeContext(t){this.serdeContext=t,this.serializer.setSerdeContext(t),this.deserializer.setSerdeContext(t),this.getPayloadCodec()&&this.getPayloadCodec().setSerdeContext(t)}updateServiceEndpoint(t,n){if("url"in n){t.protocol=n.url.protocol,t.hostname=n.url.hostname,t.port=n.url.port?Number(n.url.port):void 0,t.path=n.url.pathname,t.fragment=n.url.hash||void 0,t.username=n.url.username||void 0,t.password=n.url.password||void 0,t.query||(t.query={});for(const[i,r]of n.url.searchParams.entries())t.query[i]=r;return t}else return t.protocol=n.protocol,t.hostname=n.hostname,t.port=n.port?Number(n.port):void 0,t.path=n.path,t.query={...n.query},t}setHostPrefix(t,n,i){if(this.serdeContext?.disableHostPrefix)return;const r=Mr.of(n.input),a=pb(n.traits??{});if(a.endpoint){let l=a.endpoint?.[0];if(typeof l=="string"){const c=[...r.structIterator()].filter(([,o])=>o.getMergedTraits().hostLabel);for(const[o]of c){const s=i[o];if(typeof s!="string")throw new Error(`@smithy/core/schema - ${o} in input must be a string as hostLabel.`);l=l.replace(`{${o}}`,s)}t.hostname=l+t.hostname}}}deserializeMetadata(t){return{httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:t,requestSchema:n,initialRequest:i}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:t,requestSchema:n,initialRequest:i})}async deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:i}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:i})}async loadEventStreamCapability(){const{EventStreamSerde:t}=await fn(async()=>{const{EventStreamSerde:n}=await import("./index-BnDoetcE.js");return{EventStreamSerde:n}},[]);return new t({marshaller:this.getEventStreamMarshaller(),serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}getDefaultContentType(){throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(t,n,i,r,a){return[]}getEventStreamMarshaller(){const t=this.serdeContext;if(!t.eventStreamMarshaller)throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return t.eventStreamMarshaller}}class p7e extends d7e{async serializeRequest(t,n,i){const r={...n??{}},a=this.serializer,l={},c={},o=await i.endpoint(),s=Mr.of(t?.input),u=[],d=[];let p=!1,f;const h=new Ea({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:l,headers:c,body:void 0});if(o){this.updateServiceEndpoint(h,o),this.setHostPrefix(h,t,r);const m=pb(t.traits);if(m.http){h.method=m.http[0];const[g,y]=m.http[1].split("?");h.path=="/"?h.path=g:h.path+=g;const v=new URLSearchParams(y??"");Object.assign(l,Object.fromEntries(v))}}for(const[m,g]of s.structIterator()){const y=g.getMergedTraits()??{},v=r[m];if(v==null&&!g.isIdempotencyToken()){if(y.httpLabel&&(h.path.includes(`{${m}+}`)||h.path.includes(`{${m}}`)))throw new Error(`No value provided for input HTTP label: ${m}.`);continue}if(y.httpPayload)g.isStreaming()?g.isStructSchema()?r[m]&&(f=await this.serializeEventStream({eventStream:r[m],requestSchema:s})):f=v:(a.write(g,v),f=a.flush()),delete r[m];else if(y.httpLabel){a.write(g,v);const b=a.flush();h.path.includes(`{${m}+}`)?h.path=h.path.replace(`{${m}+}`,b.split("/").map(lF).join("/")):h.path.includes(`{${m}}`)&&(h.path=h.path.replace(`{${m}}`,lF(b))),delete r[m]}else if(y.httpHeader)a.write(g,v),c[y.httpHeader.toLowerCase()]=String(a.flush()),delete r[m];else if(typeof y.httpPrefixHeaders=="string"){for(const[b,w]of Object.entries(v)){const x=y.httpPrefixHeaders+b;a.write([g.getValueSchema(),{httpHeader:x}],w),c[x.toLowerCase()]=a.flush()}delete r[m]}else y.httpQuery||y.httpQueryParams?(this.serializeQuery(g,v,l),delete r[m]):(p=!0,u.push(m),d.push(g))}if(p&&r){const[m,g]=(s.getName(!0)??"#Unknown").split("#"),y=s.getSchema()[6],v=[3,m,g,s.getMergedTraits(),u,d,void 0];y?v[6]=y:v.pop(),a.write(v,r),f=a.flush()}return h.headers=c,h.query=l,h.body=f,h}serializeQuery(t,n,i){const r=this.serializer,a=t.getMergedTraits();if(a.httpQueryParams){for(const[l,c]of Object.entries(n))if(!(l in i)){const o=t.getValueSchema();Object.assign(o.getMergedTraits(),{...a,httpQuery:l,httpQueryParams:void 0}),this.serializeQuery(o,c,i)}return}if(t.isListSchema()){const l=!!t.getMergedTraits().sparse,c=[];for(const o of n){r.write([t.getValueSchema(),a],o);const s=r.flush();(l||s!==void 0)&&c.push(s)}i[a.httpQuery]=c}else r.write([t,a],n),i[a.httpQuery]=r.flush()}async deserializeResponse(t,n,i){const r=this.deserializer,a=Mr.of(t.output),l={};if(i.statusCode>=300){const o=await Jw(i.body,n);throw o.byteLength>0&&Object.assign(l,await r.read(15,o)),await this.handleError(t,n,i,l,this.deserializeMetadata(i)),new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(const o in i.headers){const s=i.headers[o];delete i.headers[o],i.headers[o.toLowerCase()]=s}const c=await this.deserializeHttpMessage(a,n,i,l);if(c.length){const o=await Jw(i.body,n);if(o.byteLength>0){const s=await r.read(a,o);for(const u of c)s[u]!=null&&(l[u]=s[u])}}else c.discardResponseBody&&await Jw(i.body,n);return l.$metadata=this.deserializeMetadata(i),l}async deserializeHttpMessage(t,n,i,r,a){let l;r instanceof Set?l=a:l=r;let c=!0;const o=this.deserializer,s=Mr.of(t),u=[];for(const[d,p]of s.structIterator()){const f=p.getMemberTraits();if(f.httpPayload){if(c=!1,p.isStreaming())p.isStructSchema()?l[d]=await this.deserializeEventStream({response:i,responseSchema:s}):l[d]=S8e(i.body);else if(i.body){const m=await Jw(i.body,n);m.byteLength>0&&(l[d]=await o.read(p,m))}}else if(f.httpHeader){const h=String(f.httpHeader).toLowerCase(),m=i.headers[h];if(m!=null)if(p.isListSchema()){const g=p.getValueSchema();g.getMergedTraits().httpHeader=h;let y;g.isTimestampSchema()&&g.getSchema()===4?y=u7e(m,",",2):y=ice(m);const v=[];for(const b of y)v.push(await o.read(g,b.trim()));l[d]=v}else l[d]=await o.read(p,m)}else if(f.httpPrefixHeaders!==void 0){l[d]={};for(const[h,m]of Object.entries(i.headers))if(h.startsWith(f.httpPrefixHeaders)){const g=p.getValueSchema();g.getMergedTraits().httpHeader=h,l[d][h.slice(f.httpPrefixHeaders.length)]=await o.read(g,m)}}else f.httpResponseCode?l[d]=i.statusCode:u.push(d)}return u.discardResponseBody=c,u}}function wE(e,t){if(t.timestampFormat.useTrait&&e.isTimestampSchema()&&(e.getSchema()===5||e.getSchema()===6||e.getSchema()===7))return e.getSchema();const{httpLabel:n,httpPrefixHeaders:i,httpHeader:r,httpQuery:a}=e.getMergedTraits();return(t.httpBindings?typeof i=="string"||r?6:a||n?5:void 0:void 0)??t.timestampFormat.default}class f7e extends bE{settings;constructor(t){super(),this.settings=t}read(t,n){const i=Mr.of(t);if(i.isListSchema())return ice(n).map(r=>this.read(i.getValueSchema(),r));if(i.isBlobSchema())return(this.serdeContext?.base64Decoder??Ly)(n);if(i.isTimestampSchema())switch(wE(i,this.settings)){case 5:return l7e(n);case 6:return c7e(n);case 7:return o7e(n);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",n),new Date(n)}if(i.isStringSchema()){const r=i.getMergedTraits().mediaType;let a=n;if(r)return i.getMergedTraits().httpHeader&&(a=this.base64ToUtf8(a)),(r==="application/json"||r.endsWith("+json"))&&(a=Ic.from(a)),a}return i.isNumericSchema()?Number(n):i.isBigIntegerSchema()?BigInt(n):i.isBigDecimalSchema()?new Co(n,"bigDecimal"):i.isBooleanSchema()?String(n).toLowerCase()==="true":n}base64ToUtf8(t){return(this.serdeContext?.utf8Encoder??Kb)((this.serdeContext?.base64Decoder??Ly)(t))}}class h7e extends bE{codecDeserializer;stringDeserializer;constructor(t,n){super(),this.codecDeserializer=t,this.stringDeserializer=new f7e(n)}setSerdeContext(t){this.stringDeserializer.setSerdeContext(t),this.codecDeserializer.setSerdeContext(t),this.serdeContext=t}read(t,n){const i=Mr.of(t),r=i.getMergedTraits(),a=this.serdeContext?.utf8Encoder??Kb;if(r.httpHeader||r.httpResponseCode)return this.stringDeserializer.read(i,a(n));if(r.httpPayload){if(i.isBlobSchema()){const l=this.serdeContext?.utf8Decoder??Uy;return typeof n=="string"?l(n):n}else if(i.isStringSchema())return"byteLength"in n?a(n):n}return this.codecDeserializer.read(i,n)}}class m7e extends bE{settings;stringBuffer="";constructor(t){super(),this.settings=t}write(t,n){const i=Mr.of(t);switch(typeof n){case"object":if(n===null){this.stringBuffer="null";return}if(i.isTimestampSchema()){if(!(n instanceof Date))throw new Error(`@smithy/core/protocols - received non-Date value ${n} when schema expected Date in ${i.getName(!0)}`);switch(wE(i,this.settings)){case 5:this.stringBuffer=n.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=tce(n);break;case 7:this.stringBuffer=String(n.getTime()/1e3);break;default:console.warn("Missing timestamp format, using epoch seconds",n),this.stringBuffer=String(n.getTime()/1e3)}return}if(i.isBlobSchema()&&"byteLength"in n){this.stringBuffer=(this.serdeContext?.base64Encoder??Fy)(n);return}if(i.isListSchema()&&Array.isArray(n)){let l="";for(const c of n){this.write([i.getValueSchema(),i.getMergedTraits()],c);const o=this.flush(),s=i.getValueSchema().isTimestampSchema()?o:t7e(o);l!==""&&(l+=", "),l+=s}this.stringBuffer=l;return}this.stringBuffer=JSON.stringify(n,null,2);break;case"string":const r=i.getMergedTraits().mediaType;let a=n;if(r&&((r==="application/json"||r.endsWith("+json"))&&(a=Ic.from(a)),i.getMergedTraits().httpHeader)){this.stringBuffer=(this.serdeContext?.base64Encoder??Fy)(a.toString());return}this.stringBuffer=n;break;default:i.isIdempotencyToken()?this.stringBuffer=v8():this.stringBuffer=String(n)}}flush(){const t=this.stringBuffer;return this.stringBuffer="",t}}class g7e{codecSerializer;stringSerializer;buffer;constructor(t,n,i=new m7e(n)){this.codecSerializer=t,this.stringSerializer=i}setSerdeContext(t){this.codecSerializer.setSerdeContext(t),this.stringSerializer.setSerdeContext(t)}write(t,n){const i=Mr.of(t),r=i.getMergedTraits();if(r.httpHeader||r.httpLabel||r.httpQuery){this.stringSerializer.write(i,n),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(i,n)}flush(){if(this.buffer!==void 0){const t=this.buffer;return this.buffer=void 0,t}return this.codecSerializer.flush()}}function y7e(e,t,n){e.__smithy_context?e.__smithy_context.features||(e.__smithy_context.features={}):e.__smithy_context={features:{}},e.__smithy_context.features[t]=n}class v7e{authSchemes=new Map;constructor(t){for(const[n,i]of Object.entries(t))i!==void 0&&this.authSchemes.set(n,i)}getIdentityProvider(t){return this.authSchemes.get(t)}}class b7e{async sign(t,n,i){const r=Ea.clone(t);if(!n.token)throw new Error("request could not be signed with `token` since the `token` is not defined");return r.headers.Authorization=`Bearer ${n.token}`,r}}const w7e=e=>function(n){return x8(n)&&n.expiration.getTime()-Date.now()<e},_7e=3e5,ace=w7e(_7e),x8=e=>e.expiration!==void 0,sce=(e,t,n)=>{if(e===void 0)return;const i=typeof e!="function"?async()=>Promise.resolve(e):e;let r,a,l,c=!1;const o=async s=>{a||(a=i(s));try{r=await a,l=!0,c=!1}finally{a=void 0}return r};return t===void 0?async s=>((!l||s?.forceRefresh)&&(r=await o(s)),r):async s=>((!l||s?.forceRefresh)&&(r=await o(s)),c?r:n(r)?(t(r)&&await o(s),r):(c=!0,r))},x7e=void 0;function S7e(e){return e===void 0?!0:typeof e=="string"&&e.length<=50}function C7e(e){const t=b_(e.userAgentAppId??x7e),{customUserAgent:n}=e;return Object.assign(e,{customUserAgent:typeof n=="string"?[[n]]:n,userAgentAppId:async()=>{const i=await t();if(!S7e(i)){const r=e.logger?.constructor?.name==="NoOpLogger"||!e.logger?console:e.logger;typeof i!="string"?r?.warn("userAgentAppId must be a string or undefined."):i.length>50&&r?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return i}})}class T7e{capacity;data=new Map;parameters=[];constructor({size:t,params:n}){this.capacity=t??50,n&&(this.parameters=n)}get(t,n){const i=this.hash(t);if(i===!1)return n();if(!this.data.has(i)){if(this.data.size>this.capacity+10){const r=this.data.keys();let a=0;for(;;){const{value:l,done:c}=r.next();if(this.data.delete(l),c||++a>10)break}}this.data.set(i,n())}return this.data.get(i)}size(){return this.data.size}hash(t){let n="";const{parameters:i}=this;if(i.length===0)return!1;for(const r of i){const a=String(t[r]??"");if(a.includes("|;"))return!1;n+=a+"|;"}return n}}const E7e=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),oce=e=>E7e.test(e)||e.startsWith("[")&&e.endsWith("]"),k7e=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),_E=(e,t=!1)=>{if(!t)return k7e.test(e);const n=e.split(".");for(const i of n)if(!_E(i))return!1;return!0},KT={},F_="endpoints";function pg(e){return typeof e!="object"||e==null?e:"ref"in e?`$${pg(e.ref)}`:"fn"in e?`${e.fn}(${(e.argv||[]).map(pg).join(", ")})`:JSON.stringify(e,null,2)}class hs extends Error{constructor(t){super(t),this.name="EndpointError"}}const A7e=(e,t)=>e===t,R7e=e=>{const t=e.split("."),n=[];for(const i of t){const r=i.indexOf("[");if(r!==-1){if(i.indexOf("]")!==i.length-1)throw new hs(`Path: '${e}' does not end with ']'`);const a=i.slice(r+1,-1);if(Number.isNaN(parseInt(a)))throw new hs(`Invalid array index: '${a}' in path: '${e}'`);r!==0&&n.push(i.slice(0,r)),n.push(a)}else n.push(i)}return n},lce=(e,t)=>R7e(t).reduce((n,i)=>{if(typeof n!="object")throw new hs(`Index '${i}' in '${t}' not found in '${JSON.stringify(e)}'`);return Array.isArray(n)?n[parseInt(i)]:n[i]},e),O7e=e=>e!=null,I7e=e=>!e,V6={[$_.HTTP]:80,[$_.HTTPS]:443},P7e=e=>{const t=(()=>{try{if(e instanceof URL)return e;if(typeof e=="object"&&"hostname"in e){const{hostname:p,port:f,protocol:h="",path:m="",query:g={}}=e,y=new URL(`${h}//${p}${f?`:${f}`:""}${m}`);return y.search=Object.entries(g).map(([v,b])=>`${v}=${b}`).join("&"),y}return new URL(e)}catch{return null}})();if(!t)return console.error(`Unable to parse ${JSON.stringify(e)} as a whatwg URL.`),null;const n=t.href,{host:i,hostname:r,pathname:a,protocol:l,search:c}=t;if(c)return null;const o=l.slice(0,-1);if(!Object.values($_).includes(o))return null;const s=oce(r),u=n.includes(`${i}:${V6[o]}`)||typeof e=="string"&&e.includes(`${i}:${V6[o]}`),d=`${i}${u?`:${V6[o]}`:""}`;return{scheme:o,authority:d,path:a,normalizedPath:a.endsWith("/")?a:`${a}/`,isIp:s}},M7e=(e,t)=>e===t,N7e=(e,t,n,i)=>t>=n||e.length<n||/[^\u0000-\u007f]/.test(e)?null:i?e.substring(e.length-n,e.length-t):e.substring(t,n),$7e=e=>encodeURIComponent(e).replace(/[!*'()]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),D7e={booleanEquals:A7e,getAttr:lce,isSet:O7e,isValidHostLabel:_E,not:I7e,parseURL:P7e,stringEquals:M7e,substring:N7e,uriEncode:$7e},cce=(e,t)=>{const n=[],i={...t.endpointParams,...t.referenceRecord};let r=0;for(;r<e.length;){const a=e.indexOf("{",r);if(a===-1){n.push(e.slice(r));break}n.push(e.slice(r,a));const l=e.indexOf("}",a);if(l===-1){n.push(e.slice(a));break}e[a+1]==="{"&&e[l+1]==="}"&&(n.push(e.slice(a+1,l)),r=l+2);const c=e.substring(a+1,l);if(c.includes("#")){const[o,s]=c.split("#");n.push(lce(i[o],s))}else n.push(i[c]);r=l+1}return n.join("")},j7e=({ref:e},t)=>({...t.endpointParams,...t.referenceRecord})[e],xE=(e,t,n)=>{if(typeof e=="string")return cce(e,n);if(e.fn)return dce.callFunction(e,n);if(e.ref)return j7e(e,n);throw new hs(`'${t}': ${String(e)} is not a string, function or reference.`)},uce=({fn:e,argv:t},n)=>{const i=t.map(a=>["boolean","number"].includes(typeof a)?a:dce.evaluateExpression(a,"arg",n)),r=e.split(".");return r[0]in KT&&r[1]!=null?KT[r[0]][r[1]](...i):D7e[e](...i)},dce={evaluateExpression:xE,callFunction:uce},L7e=({assign:e,...t},n)=>{if(e&&e in n.referenceRecord)throw new hs(`'${e}' is already defined in Reference Record.`);const i=uce(t,n);return n.logger?.debug?.(`${F_} evaluateCondition: ${pg(t)} = ${pg(i)}`),{result:i===""?!0:!!i,...e!=null&&{toAssign:{name:e,value:i}}}},S8=(e=[],t)=>{const n={};for(const i of e){const{result:r,toAssign:a}=L7e(i,{...t,referenceRecord:{...t.referenceRecord,...n}});if(!r)return{result:r};a&&(n[a.name]=a.value,t.logger?.debug?.(`${F_} assign: ${a.name} := ${pg(a.value)}`))}return{result:!0,referenceRecord:n}},U7e=(e,t)=>Object.entries(e).reduce((n,[i,r])=>({...n,[i]:r.map(a=>{const l=xE(a,"Header value entry",t);if(typeof l!="string")throw new hs(`Header '${i}' value '${l}' is not a string`);return l})}),{}),pce=(e,t)=>Object.entries(e).reduce((n,[i,r])=>({...n,[i]:hce.getEndpointProperty(r,t)}),{}),fce=(e,t)=>{if(Array.isArray(e))return e.map(n=>fce(n,t));switch(typeof e){case"string":return cce(e,t);case"object":if(e===null)throw new hs(`Unexpected endpoint property: ${e}`);return hce.getEndpointProperties(e,t);case"boolean":return e;default:throw new hs(`Unexpected endpoint property type: ${typeof e}`)}},hce={getEndpointProperty:fce,getEndpointProperties:pce},F7e=(e,t)=>{const n=xE(e,"Endpoint URL",t);if(typeof n=="string")try{return new URL(n)}catch(i){throw console.error(`Failed to construct URL with ${n}`,i),i}throw new hs(`Endpoint URL must be a string, got ${typeof n}`)},q7e=(e,t)=>{const{conditions:n,endpoint:i}=e,{result:r,referenceRecord:a}=S8(n,t);if(!r)return;const l={...t,referenceRecord:{...t.referenceRecord,...a}},{url:c,properties:o,headers:s}=i;return t.logger?.debug?.(`${F_} Resolving endpoint from template: ${pg(i)}`),{...s!=null&&{headers:U7e(s,l)},...o!=null&&{properties:pce(o,l)},url:F7e(c,l)}},B7e=(e,t)=>{const{conditions:n,error:i}=e,{result:r,referenceRecord:a}=S8(n,t);if(r)throw new hs(xE(i,"Error",{...t,referenceRecord:{...t.referenceRecord,...a}}))},mce=(e,t)=>{for(const n of e)if(n.type==="endpoint"){const i=q7e(n,t);if(i)return i}else if(n.type==="error")B7e(n,t);else if(n.type==="tree"){const i=gce.evaluateTreeRule(n,t);if(i)return i}else throw new hs(`Unknown endpoint rule: ${n}`);throw new hs("Rules evaluation failed")},W7e=(e,t)=>{const{conditions:n,rules:i}=e,{result:r,referenceRecord:a}=S8(n,t);if(r)return gce.evaluateRules(i,{...t,referenceRecord:{...t.referenceRecord,...a}})},gce={evaluateRules:mce,evaluateTreeRule:W7e},z7e=(e,t)=>{const{endpointParams:n,logger:i}=t,{parameters:r,rules:a}=e;t.logger?.debug?.(`${F_} Initial EndpointParams: ${pg(n)}`);const l=Object.entries(r).filter(([,s])=>s.default!=null).map(([s,u])=>[s,u.default]);if(l.length>0)for(const[s,u]of l)n[s]=n[s]??u;const c=Object.entries(r).filter(([,s])=>s.required).map(([s])=>s);for(const s of c)if(n[s]==null)throw new hs(`Missing required parameter: '${s}'`);const o=mce(a,{endpointParams:n,logger:i,referenceRecord:{}});return t.logger?.debug?.(`${F_} Resolved endpoint: ${pg(o)}`),o},yce=(e,t=!1)=>{if(t){for(const n of e.split("."))if(!yce(n))return!1;return!0}return!(!_E(e)||e.length<3||e.length>63||e!==e.toLowerCase()||oce(e))},mF=":",G7e="/",H7e=e=>{const t=e.split(mF);if(t.length<6)return null;const[n,i,r,a,l,...c]=t;if(n!=="arn"||i===""||r===""||c.join(mF)==="")return null;const o=c.map(s=>s.split(G7e)).flat();return{partition:i,service:r,region:a,accountId:l,resourceId:o}},V7e=[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-east-2":{description:"Asia Pacific (Taipei)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"ap-southeast-6":{description:"Asia Pacific (New Zealand)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"aws global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"mx-central-1":{description:"Mexico (Central)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"aws-cn global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"api.amazonwebservices.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"AWS European Sovereign Cloud (Germany)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"api.aws.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"aws-iso global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"api.aws.scloud",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"aws-iso-b global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"},"us-isob-west-1":{description:"US ISOB West"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"api.cloud-aws.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"aws-iso-e global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"api.aws.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"aws-iso-f global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"aws-us-gov global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}}],J7e={partitions:V7e};let K7e=J7e;const Z7e=e=>{const{partitions:t}=K7e;for(const i of t){const{regions:r,outputs:a}=i;for(const[l,c]of Object.entries(r))if(l===e)return{...a,...c}}for(const i of t){const{regionRegex:r,outputs:a}=i;if(new RegExp(r).test(e))return{...a}}const n=t.find(i=>i.id==="aws");if(!n)throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...n.outputs}},vce={isVirtualHostableS3Bucket:yce,parseArn:H7e,partition:Z7e};KT.aws=vce;function X7e(e){const t={};if(e=e.replace(/^\?/,""),e)for(const n of e.split("&")){let[i,r=null]=n.split("=");i=decodeURIComponent(i),r&&(r=decodeURIComponent(r)),i in t?Array.isArray(t[i])?t[i].push(r):t[i]=[t[i],r]:t[i]=r}return t}const ZT=e=>{if(typeof e=="string")return ZT(new URL(e));const{hostname:t,pathname:n,port:i,protocol:r,search:a}=e;let l;return a&&(l=X7e(a)),{hostname:t,port:i?parseInt(i):void 0,protocol:r,path:n,query:l}};function Q7e(e,t,n){return e.$source||(e.$source={}),e.$source[t]=n,e}function Bo(e,t,n){e.__aws_sdk_context?e.__aws_sdk_context.features||(e.__aws_sdk_context.features={}):e.__aws_sdk_context={features:{}},e.__aws_sdk_context.features[t]=n}const gF=e=>jy.isInstance(e)?e.headers?.date??e.headers?.Date:void 0,bce=e=>new Date(Date.now()+e),Y7e=(e,t)=>Math.abs(bce(t).getTime()-e)>=3e5,yF=(e,t)=>{const n=Date.parse(e);return Y7e(n,t)?n-Date.now():t},__=(e,t)=>{if(!t)throw new Error(`Property \`${e}\` is not resolved for AWS SDK SigV4Auth`);return t},eMe=async e=>{const t=__("context",e.context),n=__("config",e.config),i=t.endpointV2?.properties?.authSchemes?.[0],a=await __("signer",n.signer)(i),l=e?.signingRegion,c=e?.signingRegionSet,o=e?.signingName;return{config:n,signer:a,signingRegion:l,signingRegionSet:c,signingName:o}};class tMe{async sign(t,n,i){if(!Ea.isInstance(t))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const r=await eMe(i),{config:a,signer:l}=r;let{signingRegion:c,signingName:o}=r;const s=i.context;if(s?.authSchemes?.length??!1){const[d,p]=s.authSchemes;d?.name==="sigv4a"&&p?.name==="sigv4"&&(c=p?.signingRegion??c,o=p?.signingName??o)}return await l.sign(t,{signingDate:bce(a.systemClockOffset),signingRegion:c,signingService:o})}errorHandler(t){return n=>{const i=n.ServerTime??gF(n.$response);if(i){const r=__("config",t.config),a=r.systemClockOffset;r.systemClockOffset=yF(i,r.systemClockOffset),r.systemClockOffset!==a&&n.$metadata&&(n.$metadata.clockSkewCorrected=!0)}throw n}}successHandler(t,n){const i=gF(t);if(i){const r=__("config",n.config);r.systemClockOffset=yF(i,r.systemClockOffset)}}}const nMe=(e,t,n)=>{let i,r,a,l=!1;const c=async()=>{r||(r=e());try{i=await r,a=!0,l=!1}finally{r=void 0}return i};return async o=>((!a||o?.forceRefresh)&&(i=await c()),i)},rMe="X-Amz-Algorithm",iMe="X-Amz-Credential",wce="X-Amz-Date",aMe="X-Amz-SignedHeaders",sMe="X-Amz-Expires",_ce="X-Amz-Signature",xce="X-Amz-Security-Token",Sce="authorization",Cce=wce.toLowerCase(),oMe="date",lMe=[Sce,Cce,oMe],cMe=_ce.toLowerCase(),rO="x-amz-content-sha256",uMe=xce.toLowerCase(),dMe={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},pMe=/^proxy-/,fMe=/^sec-/,J6="AWS4-HMAC-SHA256",hMe="AWS4-HMAC-SHA256-PAYLOAD",mMe="UNSIGNED-PAYLOAD",gMe=50,Tce="aws4_request",yMe=3600*24*7,Ux={},K6=[],Z6=(e,t,n)=>`${e}/${t}/${n}/${Tce}`,vMe=async(e,t,n,i,r)=>{const a=await vF(e,t.secretAccessKey,t.accessKeyId),l=`${n}:${i}:${r}:${qa(a)}:${t.sessionToken}`;if(l in Ux)return Ux[l];for(K6.push(l);K6.length>gMe;)delete Ux[K6.shift()];let c=`AWS4${t.secretAccessKey}`;for(const o of[n,i,r,Tce])c=await vF(e,c,o);return Ux[l]=c},vF=(e,t,n)=>{const i=new e(t);return i.update(j_(n)),i.digest()},bF=({headers:e},t,n)=>{const i={};for(const r of Object.keys(e).sort()){if(e[r]==null)continue;const a=r.toLowerCase();(a in dMe||t?.has(a)||pMe.test(a)||fMe.test(a))&&(!n||n&&!n.has(a))||(i[a]=e[r].trim().replace(/\s+/g," "))}return i},bMe=e=>typeof ArrayBuffer=="function"&&e instanceof ArrayBuffer||Object.prototype.toString.call(e)==="[object ArrayBuffer]",X6=async({headers:e,body:t},n)=>{for(const i of Object.keys(e))if(i.toLowerCase()===rO)return e[i];if(t==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if(typeof t=="string"||ArrayBuffer.isView(t)||bMe(t)){const i=new n;return i.update(j_(t)),qa(await i.digest())}return mMe};class wMe{format(t){const n=[];for(const a of Object.keys(t)){const l=Uy(a);n.push(Uint8Array.from([l.byteLength]),l,this.formatHeaderValue(t[a]))}const i=new Uint8Array(n.reduce((a,l)=>a+l.byteLength,0));let r=0;for(const a of n)i.set(a,r),r+=a.byteLength;return i}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?0:1]);case"byte":return Uint8Array.from([2,t.value]);case"short":const n=new DataView(new ArrayBuffer(3));return n.setUint8(0,3),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":const i=new DataView(new ArrayBuffer(5));return i.setUint8(0,4),i.setInt32(1,t.value,!1),new Uint8Array(i.buffer);case"long":const r=new Uint8Array(9);return r[0]=5,r.set(t.value.bytes,1),r;case"binary":const a=new DataView(new ArrayBuffer(3+t.value.byteLength));a.setUint8(0,6),a.setUint16(1,t.value.byteLength,!1);const l=new Uint8Array(a.buffer);return l.set(t.value,3),l;case"string":const c=Uy(t.value),o=new DataView(new ArrayBuffer(3+c.byteLength));o.setUint8(0,7),o.setUint16(1,c.byteLength,!1);const s=new Uint8Array(o.buffer);return s.set(c,3),s;case"timestamp":const u=new Uint8Array(9);return u[0]=8,u.set(xMe.fromNumber(t.value.valueOf()).bytes,1),u;case"uuid":if(!_Me.test(t.value))throw new Error(`Invalid UUID received: ${t.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(g8(t.value.replace(/\-/g,"")),1),d}}}var wF;(function(e){e[e.boolTrue=0]="boolTrue",e[e.boolFalse=1]="boolFalse",e[e.byte=2]="byte",e[e.short=3]="short",e[e.integer=4]="integer",e[e.long=5]="long",e[e.byteArray=6]="byteArray",e[e.string=7]="string",e[e.timestamp=8]="timestamp",e[e.uuid=9]="uuid"})(wF||(wF={}));const _Me=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;let xMe=class Ece{bytes;constructor(t){if(this.bytes=t,t.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(t){if(t>9223372036854776e3||t<-9223372036854776e3)throw new Error(`${t} is too large (or, if negative, too small) to represent as an Int64`);const n=new Uint8Array(8);for(let i=7,r=Math.abs(Math.round(t));i>-1&&r>0;i--,r/=256)n[i]=r;return t<0&&_F(n),new Ece(n)}valueOf(){const t=this.bytes.slice(0),n=t[0]&128;return n&&_F(t),parseInt(qa(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}};function _F(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,e[t]===0);t--);}const SMe=(e,t)=>{e=e.toLowerCase();for(const n of Object.keys(t))if(e===n.toLowerCase())return!0;return!1},CMe=(e,t={})=>{const{headers:n,query:i={}}=Ea.clone(e);for(const r of Object.keys(n)){const a=r.toLowerCase();(a.slice(0,6)==="x-amz-"&&!t.unhoistableHeaders?.has(a)||t.hoistableHeaders?.has(a))&&(i[r]=n[r],delete n[r])}return{...e,headers:n,query:i}},xF=e=>{e=Ea.clone(e);for(const t of Object.keys(e.headers))lMe.indexOf(t.toLowerCase())>-1&&delete e.headers[t];return e},TMe=({query:e={}})=>{const t=[],n={};for(const i of Object.keys(e)){if(i.toLowerCase()===cMe)continue;const r=Oy(i);t.push(r);const a=e[i];typeof a=="string"?n[r]=`${r}=${Oy(a)}`:Array.isArray(a)&&(n[r]=a.slice(0).reduce((l,c)=>l.concat([`${r}=${Oy(c)}`]),[]).sort().join("&"))}return t.sort().map(i=>n[i]).filter(i=>i).join("&")},EMe=e=>kMe(e).toISOString().replace(/\.\d{3}Z$/,"Z"),kMe=e=>typeof e=="number"?new Date(e*1e3):typeof e=="string"?Number(e)?new Date(Number(e)*1e3):new Date(e):e;class AMe{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:t,credentials:n,region:i,service:r,sha256:a,uriEscapePath:l=!0}){this.service=r,this.sha256=a,this.uriEscapePath=l,this.applyChecksum=typeof t=="boolean"?t:!0,this.regionProvider=ym(i),this.credentialProvider=ym(n)}createCanonicalRequest(t,n,i){const r=Object.keys(n).sort();return`${t.method}
514
+ `),L8e={warn:console.warn},U8e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],y8=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function tce(e){const t=e.getUTCFullYear(),n=e.getUTCMonth(),i=e.getUTCDay(),r=e.getUTCDate(),a=e.getUTCHours(),l=e.getUTCMinutes(),c=e.getUTCSeconds(),o=r<10?`0${r}`:`${r}`,s=a<10?`0${a}`:`${a}`,u=l<10?`0${l}`:`${l}`,d=c<10?`0${c}`:`${c}`;return`${U8e[i]}, ${o} ${y8[n]} ${t} ${s}:${u}:${d} GMT`}const F8e=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),q8e=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");const t=F8e.exec(e);if(!t)throw new TypeError("Invalid RFC-3339 date-time value");const[n,i,r,a,l,c,o,s,u]=t,d=JT(U_(i)),p=og(r,"month",1,12),f=og(a,"day",1,31),h=$C(d,p,f,{hours:l,minutes:c,seconds:o,fractionalMilliseconds:s});return u.toUpperCase()!="Z"&&h.setTime(h.getTime()-e7e(u)),h},B8e=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),W8e=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),z8e=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),G8e=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let t=B8e.exec(e);if(t){const[n,i,r,a,l,c,o,s]=t;return $C(JT(U_(a)),H6(r),og(i,"day",1,31),{hours:l,minutes:c,seconds:o,fractionalMilliseconds:s})}if(t=W8e.exec(e),t){const[n,i,r,a,l,c,o,s]=t;return K8e($C(V8e(a),H6(r),og(i,"day",1,31),{hours:l,minutes:c,seconds:o,fractionalMilliseconds:s}))}if(t=z8e.exec(e),t){const[n,i,r,a,l,c,o,s]=t;return $C(JT(U_(s)),H6(i),og(r.trimLeft(),"day",1,31),{hours:a,minutes:l,seconds:c,fractionalMilliseconds:o})}throw new TypeError("Invalid RFC-7231 date-time value")},H8e=e=>{if(e==null)return;let t;if(typeof e=="number")t=e;else if(typeof e=="string")t=M8e(e);else if(typeof e=="object"&&e.tag===1)t=e.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(t)||t===1/0||t===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(t*1e3))},$C=(e,t,n,i)=>{const r=t-1;return X8e(e,r,n),new Date(Date.UTC(e,r,n,og(i.hours,"hour",0,23),og(i.minutes,"minute",0,59),og(i.seconds,"seconds",0,60),Y8e(i.fractionalMilliseconds)))},V8e=e=>{const t=new Date().getUTCFullYear(),n=Math.floor(t/100)*100+JT(U_(e));return n<t?n+100:n},J8e=50*365*24*60*60*1e3,K8e=e=>e.getTime()-new Date().getTime()>J8e?new Date(Date.UTC(e.getUTCFullYear()-100,e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())):e,H6=e=>{const t=y8.indexOf(e);if(t<0)throw new TypeError(`Invalid month: ${e}`);return t+1},Z8e=[31,28,31,30,31,30,31,31,30,31,30,31],X8e=(e,t,n)=>{let i=Z8e[t];if(t===1&&Q8e(e)&&(i=29),n>i)throw new TypeError(`Invalid day for ${y8[t]} in ${e}: ${n}`)},Q8e=e=>e%4===0&&(e%100!==0||e%400===0),og=(e,t,n,i)=>{const r=D8e(U_(e));if(r<n||r>i)throw new TypeError(`${t} must be between ${n} and ${i}, inclusive`);return r},Y8e=e=>e==null?0:N8e("0."+e)*1e3,e7e=e=>{const t=e[0];let n=1;if(t=="+")n=1;else if(t=="-")n=-1;else throw new TypeError(`Offset direction, ${t}, must be "+" or "-"`);const i=Number(e.substring(1,3)),r=Number(e.substring(4,6));return n*(i*60+r)*60*1e3},U_=e=>{let t=0;for(;t<e.length-1&&e.charAt(t)==="0";)t++;return t===0?e:e.slice(t)},fF=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Yi=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0")),v8=()=>{if(fF)return fF();const e=new Uint8Array(16);return crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128,Yi[e[0]]+Yi[e[1]]+Yi[e[2]]+Yi[e[3]]+"-"+Yi[e[4]]+Yi[e[5]]+"-"+Yi[e[6]]+Yi[e[7]]+"-"+Yi[e[8]]+Yi[e[9]]+"-"+Yi[e[10]]+Yi[e[11]]+Yi[e[12]]+Yi[e[13]]+Yi[e[14]]+Yi[e[15]]},Ic=function(t){return Object.assign(new String(t),{deserializeJSON(){return JSON.parse(String(t))},toString(){return String(t)},toJSON(){return String(t)}})};Ic.from=e=>e&&typeof e=="object"&&(e instanceof Ic||"deserializeJSON"in e)?e:typeof e=="string"||Object.getPrototypeOf(e)===String.prototype?Ic(String(e)):Ic(JSON.stringify(e));Ic.fromObject=Ic.from;function t7e(e){return(e.includes(",")||e.includes('"'))&&(e=`"${e.replace(/"/g,'\\"')}"`),e}const b8="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",w8="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",_8="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",nce="(\\d?\\d)",rce="(\\d{4})",n7e=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),r7e=new RegExp(`^${b8}, ${nce} ${w8} ${rce} ${_8} GMT$`),i7e=new RegExp(`^${b8}, ${nce}-${w8}-(\\d\\d) ${_8} GMT$`),a7e=new RegExp(`^${b8} ${w8} ( [1-9]|\\d\\d) ${_8} ${rce}$`),s7e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],o7e=e=>{if(e==null)return;let t=NaN;if(typeof e=="number")t=e;else if(typeof e=="string"){if(!/^-?\d*\.?\d+$/.test(e))throw new TypeError("parseEpochTimestamp - numeric string invalid.");t=Number.parseFloat(e)}else typeof e=="object"&&e.tag===1&&(t=e.value);if(isNaN(t)||Math.abs(t)===1/0)throw new TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(t*1e3))},l7e=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC3339 timestamps must be strings");const t=n7e.exec(e);if(!t)throw new TypeError(`Invalid RFC3339 timestamp format ${e}`);const[,n,i,r,a,l,c,,o,s]=t;mm(i,1,12),mm(r,1,31),mm(a,0,23),mm(l,0,59),mm(c,0,60);const u=new Date(Date.UTC(Number(n),Number(i)-1,Number(r),Number(a),Number(l),Number(c),Number(o)?Math.round(parseFloat(`0.${o}`)*1e3):0));if(u.setUTCFullYear(Number(n)),s.toUpperCase()!="Z"){const[,d,p,f]=/([+-])(\d\d):(\d\d)/.exec(s)||[void 0,"+",0,0],h=d==="-"?1:-1;u.setTime(u.getTime()+h*(Number(p)*60*60*1e3+Number(f)*60*1e3))}return u},c7e=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC7231 timestamps must be strings.");let t,n,i,r,a,l,c,o;if((o=r7e.exec(e))?[,t,n,i,r,a,l,c]=o:(o=i7e.exec(e))?([,t,n,i,r,a,l,c]=o,i=(Number(i)+1900).toString()):(o=a7e.exec(e))&&([,n,t,r,a,l,c,i]=o),i&&l){const s=Date.UTC(Number(i),s7e.indexOf(n),Number(t),Number(r),Number(a),Number(l),c?Math.round(parseFloat(`0.${c}`)*1e3):0);mm(t,1,31),mm(r,0,23),mm(a,0,59),mm(l,0,60);const u=new Date(s);return u.setUTCFullYear(Number(i)),u}throw new TypeError(`Invalid RFC7231 date-time value ${e}.`)};function mm(e,t,n){const i=Number(e);if(i<t||i>n)throw new Error(`Value ${i} out of range [${t}, ${n}]`)}function u7e(e,t,n){if(!Number.isInteger(n))throw new Error("Invalid number of delimiters ("+n+") for splitEvery.");const i=e.split(t),r=[];let a="";for(let l=0;l<i.length;l++)a===""?a=i[l]:a+=t+i[l],(l+1)%n===0&&(r.push(a),a="");return a!==""&&r.push(a),r}const ice=e=>{const t=e.length,n=[];let i=!1,r,a=0;for(let l=0;l<t;++l){const c=e[l];switch(c){case'"':r!=="\\"&&(i=!i);break;case",":i||(n.push(e.slice(a,l)),a=l+1);break}r=c}return n.push(e.slice(a)),n.map(l=>{l=l.trim();const c=l.length;return c<2?l:(l[0]==='"'&&l[c-1]==='"'&&(l=l.slice(1,c-1)),l.replace(/\\"/g,'"'))})},hF=/^-?\d*(\.\d+)?$/;class Co{string;type;constructor(t,n){if(this.string=t,this.type=n,!hF.test(t))throw new Error('@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".')}toString(){return this.string}static[Symbol.hasInstance](t){if(!t||typeof t!="object")return!1;const n=t;return Co.prototype.isPrototypeOf(t)||n.type==="bigDecimal"&&hF.test(n.string)}}class bE{serdeContext;setSerdeContext(t){this.serdeContext=t}}class d7e extends bE{options;compositeErrorRegistry;constructor(t){super(),this.options=t,this.compositeErrorRegistry=Ua.for(t.defaultNamespace);for(const n of t.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(n)}getRequestType(){return Ea}getResponseType(){return jy}setSerdeContext(t){this.serdeContext=t,this.serializer.setSerdeContext(t),this.deserializer.setSerdeContext(t),this.getPayloadCodec()&&this.getPayloadCodec().setSerdeContext(t)}updateServiceEndpoint(t,n){if("url"in n){t.protocol=n.url.protocol,t.hostname=n.url.hostname,t.port=n.url.port?Number(n.url.port):void 0,t.path=n.url.pathname,t.fragment=n.url.hash||void 0,t.username=n.url.username||void 0,t.password=n.url.password||void 0,t.query||(t.query={});for(const[i,r]of n.url.searchParams.entries())t.query[i]=r;return t}else return t.protocol=n.protocol,t.hostname=n.hostname,t.port=n.port?Number(n.port):void 0,t.path=n.path,t.query={...n.query},t}setHostPrefix(t,n,i){if(this.serdeContext?.disableHostPrefix)return;const r=Mr.of(n.input),a=pb(n.traits??{});if(a.endpoint){let l=a.endpoint?.[0];if(typeof l=="string"){const c=[...r.structIterator()].filter(([,o])=>o.getMergedTraits().hostLabel);for(const[o]of c){const s=i[o];if(typeof s!="string")throw new Error(`@smithy/core/schema - ${o} in input must be a string as hostLabel.`);l=l.replace(`{${o}}`,s)}t.hostname=l+t.hostname}}}deserializeMetadata(t){return{httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:t,requestSchema:n,initialRequest:i}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:t,requestSchema:n,initialRequest:i})}async deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:i}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:i})}async loadEventStreamCapability(){const{EventStreamSerde:t}=await fn(async()=>{const{EventStreamSerde:n}=await import("./index-BSBZClnJ.js");return{EventStreamSerde:n}},[]);return new t({marshaller:this.getEventStreamMarshaller(),serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}getDefaultContentType(){throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(t,n,i,r,a){return[]}getEventStreamMarshaller(){const t=this.serdeContext;if(!t.eventStreamMarshaller)throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return t.eventStreamMarshaller}}class p7e extends d7e{async serializeRequest(t,n,i){const r={...n??{}},a=this.serializer,l={},c={},o=await i.endpoint(),s=Mr.of(t?.input),u=[],d=[];let p=!1,f;const h=new Ea({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:l,headers:c,body:void 0});if(o){this.updateServiceEndpoint(h,o),this.setHostPrefix(h,t,r);const m=pb(t.traits);if(m.http){h.method=m.http[0];const[g,y]=m.http[1].split("?");h.path=="/"?h.path=g:h.path+=g;const v=new URLSearchParams(y??"");Object.assign(l,Object.fromEntries(v))}}for(const[m,g]of s.structIterator()){const y=g.getMergedTraits()??{},v=r[m];if(v==null&&!g.isIdempotencyToken()){if(y.httpLabel&&(h.path.includes(`{${m}+}`)||h.path.includes(`{${m}}`)))throw new Error(`No value provided for input HTTP label: ${m}.`);continue}if(y.httpPayload)g.isStreaming()?g.isStructSchema()?r[m]&&(f=await this.serializeEventStream({eventStream:r[m],requestSchema:s})):f=v:(a.write(g,v),f=a.flush()),delete r[m];else if(y.httpLabel){a.write(g,v);const b=a.flush();h.path.includes(`{${m}+}`)?h.path=h.path.replace(`{${m}+}`,b.split("/").map(lF).join("/")):h.path.includes(`{${m}}`)&&(h.path=h.path.replace(`{${m}}`,lF(b))),delete r[m]}else if(y.httpHeader)a.write(g,v),c[y.httpHeader.toLowerCase()]=String(a.flush()),delete r[m];else if(typeof y.httpPrefixHeaders=="string"){for(const[b,w]of Object.entries(v)){const x=y.httpPrefixHeaders+b;a.write([g.getValueSchema(),{httpHeader:x}],w),c[x.toLowerCase()]=a.flush()}delete r[m]}else y.httpQuery||y.httpQueryParams?(this.serializeQuery(g,v,l),delete r[m]):(p=!0,u.push(m),d.push(g))}if(p&&r){const[m,g]=(s.getName(!0)??"#Unknown").split("#"),y=s.getSchema()[6],v=[3,m,g,s.getMergedTraits(),u,d,void 0];y?v[6]=y:v.pop(),a.write(v,r),f=a.flush()}return h.headers=c,h.query=l,h.body=f,h}serializeQuery(t,n,i){const r=this.serializer,a=t.getMergedTraits();if(a.httpQueryParams){for(const[l,c]of Object.entries(n))if(!(l in i)){const o=t.getValueSchema();Object.assign(o.getMergedTraits(),{...a,httpQuery:l,httpQueryParams:void 0}),this.serializeQuery(o,c,i)}return}if(t.isListSchema()){const l=!!t.getMergedTraits().sparse,c=[];for(const o of n){r.write([t.getValueSchema(),a],o);const s=r.flush();(l||s!==void 0)&&c.push(s)}i[a.httpQuery]=c}else r.write([t,a],n),i[a.httpQuery]=r.flush()}async deserializeResponse(t,n,i){const r=this.deserializer,a=Mr.of(t.output),l={};if(i.statusCode>=300){const o=await Jw(i.body,n);throw o.byteLength>0&&Object.assign(l,await r.read(15,o)),await this.handleError(t,n,i,l,this.deserializeMetadata(i)),new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(const o in i.headers){const s=i.headers[o];delete i.headers[o],i.headers[o.toLowerCase()]=s}const c=await this.deserializeHttpMessage(a,n,i,l);if(c.length){const o=await Jw(i.body,n);if(o.byteLength>0){const s=await r.read(a,o);for(const u of c)s[u]!=null&&(l[u]=s[u])}}else c.discardResponseBody&&await Jw(i.body,n);return l.$metadata=this.deserializeMetadata(i),l}async deserializeHttpMessage(t,n,i,r,a){let l;r instanceof Set?l=a:l=r;let c=!0;const o=this.deserializer,s=Mr.of(t),u=[];for(const[d,p]of s.structIterator()){const f=p.getMemberTraits();if(f.httpPayload){if(c=!1,p.isStreaming())p.isStructSchema()?l[d]=await this.deserializeEventStream({response:i,responseSchema:s}):l[d]=S8e(i.body);else if(i.body){const m=await Jw(i.body,n);m.byteLength>0&&(l[d]=await o.read(p,m))}}else if(f.httpHeader){const h=String(f.httpHeader).toLowerCase(),m=i.headers[h];if(m!=null)if(p.isListSchema()){const g=p.getValueSchema();g.getMergedTraits().httpHeader=h;let y;g.isTimestampSchema()&&g.getSchema()===4?y=u7e(m,",",2):y=ice(m);const v=[];for(const b of y)v.push(await o.read(g,b.trim()));l[d]=v}else l[d]=await o.read(p,m)}else if(f.httpPrefixHeaders!==void 0){l[d]={};for(const[h,m]of Object.entries(i.headers))if(h.startsWith(f.httpPrefixHeaders)){const g=p.getValueSchema();g.getMergedTraits().httpHeader=h,l[d][h.slice(f.httpPrefixHeaders.length)]=await o.read(g,m)}}else f.httpResponseCode?l[d]=i.statusCode:u.push(d)}return u.discardResponseBody=c,u}}function wE(e,t){if(t.timestampFormat.useTrait&&e.isTimestampSchema()&&(e.getSchema()===5||e.getSchema()===6||e.getSchema()===7))return e.getSchema();const{httpLabel:n,httpPrefixHeaders:i,httpHeader:r,httpQuery:a}=e.getMergedTraits();return(t.httpBindings?typeof i=="string"||r?6:a||n?5:void 0:void 0)??t.timestampFormat.default}class f7e extends bE{settings;constructor(t){super(),this.settings=t}read(t,n){const i=Mr.of(t);if(i.isListSchema())return ice(n).map(r=>this.read(i.getValueSchema(),r));if(i.isBlobSchema())return(this.serdeContext?.base64Decoder??Ly)(n);if(i.isTimestampSchema())switch(wE(i,this.settings)){case 5:return l7e(n);case 6:return c7e(n);case 7:return o7e(n);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",n),new Date(n)}if(i.isStringSchema()){const r=i.getMergedTraits().mediaType;let a=n;if(r)return i.getMergedTraits().httpHeader&&(a=this.base64ToUtf8(a)),(r==="application/json"||r.endsWith("+json"))&&(a=Ic.from(a)),a}return i.isNumericSchema()?Number(n):i.isBigIntegerSchema()?BigInt(n):i.isBigDecimalSchema()?new Co(n,"bigDecimal"):i.isBooleanSchema()?String(n).toLowerCase()==="true":n}base64ToUtf8(t){return(this.serdeContext?.utf8Encoder??Kb)((this.serdeContext?.base64Decoder??Ly)(t))}}class h7e extends bE{codecDeserializer;stringDeserializer;constructor(t,n){super(),this.codecDeserializer=t,this.stringDeserializer=new f7e(n)}setSerdeContext(t){this.stringDeserializer.setSerdeContext(t),this.codecDeserializer.setSerdeContext(t),this.serdeContext=t}read(t,n){const i=Mr.of(t),r=i.getMergedTraits(),a=this.serdeContext?.utf8Encoder??Kb;if(r.httpHeader||r.httpResponseCode)return this.stringDeserializer.read(i,a(n));if(r.httpPayload){if(i.isBlobSchema()){const l=this.serdeContext?.utf8Decoder??Uy;return typeof n=="string"?l(n):n}else if(i.isStringSchema())return"byteLength"in n?a(n):n}return this.codecDeserializer.read(i,n)}}class m7e extends bE{settings;stringBuffer="";constructor(t){super(),this.settings=t}write(t,n){const i=Mr.of(t);switch(typeof n){case"object":if(n===null){this.stringBuffer="null";return}if(i.isTimestampSchema()){if(!(n instanceof Date))throw new Error(`@smithy/core/protocols - received non-Date value ${n} when schema expected Date in ${i.getName(!0)}`);switch(wE(i,this.settings)){case 5:this.stringBuffer=n.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=tce(n);break;case 7:this.stringBuffer=String(n.getTime()/1e3);break;default:console.warn("Missing timestamp format, using epoch seconds",n),this.stringBuffer=String(n.getTime()/1e3)}return}if(i.isBlobSchema()&&"byteLength"in n){this.stringBuffer=(this.serdeContext?.base64Encoder??Fy)(n);return}if(i.isListSchema()&&Array.isArray(n)){let l="";for(const c of n){this.write([i.getValueSchema(),i.getMergedTraits()],c);const o=this.flush(),s=i.getValueSchema().isTimestampSchema()?o:t7e(o);l!==""&&(l+=", "),l+=s}this.stringBuffer=l;return}this.stringBuffer=JSON.stringify(n,null,2);break;case"string":const r=i.getMergedTraits().mediaType;let a=n;if(r&&((r==="application/json"||r.endsWith("+json"))&&(a=Ic.from(a)),i.getMergedTraits().httpHeader)){this.stringBuffer=(this.serdeContext?.base64Encoder??Fy)(a.toString());return}this.stringBuffer=n;break;default:i.isIdempotencyToken()?this.stringBuffer=v8():this.stringBuffer=String(n)}}flush(){const t=this.stringBuffer;return this.stringBuffer="",t}}class g7e{codecSerializer;stringSerializer;buffer;constructor(t,n,i=new m7e(n)){this.codecSerializer=t,this.stringSerializer=i}setSerdeContext(t){this.codecSerializer.setSerdeContext(t),this.stringSerializer.setSerdeContext(t)}write(t,n){const i=Mr.of(t),r=i.getMergedTraits();if(r.httpHeader||r.httpLabel||r.httpQuery){this.stringSerializer.write(i,n),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(i,n)}flush(){if(this.buffer!==void 0){const t=this.buffer;return this.buffer=void 0,t}return this.codecSerializer.flush()}}function y7e(e,t,n){e.__smithy_context?e.__smithy_context.features||(e.__smithy_context.features={}):e.__smithy_context={features:{}},e.__smithy_context.features[t]=n}class v7e{authSchemes=new Map;constructor(t){for(const[n,i]of Object.entries(t))i!==void 0&&this.authSchemes.set(n,i)}getIdentityProvider(t){return this.authSchemes.get(t)}}class b7e{async sign(t,n,i){const r=Ea.clone(t);if(!n.token)throw new Error("request could not be signed with `token` since the `token` is not defined");return r.headers.Authorization=`Bearer ${n.token}`,r}}const w7e=e=>function(n){return x8(n)&&n.expiration.getTime()-Date.now()<e},_7e=3e5,ace=w7e(_7e),x8=e=>e.expiration!==void 0,sce=(e,t,n)=>{if(e===void 0)return;const i=typeof e!="function"?async()=>Promise.resolve(e):e;let r,a,l,c=!1;const o=async s=>{a||(a=i(s));try{r=await a,l=!0,c=!1}finally{a=void 0}return r};return t===void 0?async s=>((!l||s?.forceRefresh)&&(r=await o(s)),r):async s=>((!l||s?.forceRefresh)&&(r=await o(s)),c?r:n(r)?(t(r)&&await o(s),r):(c=!0,r))},x7e=void 0;function S7e(e){return e===void 0?!0:typeof e=="string"&&e.length<=50}function C7e(e){const t=b_(e.userAgentAppId??x7e),{customUserAgent:n}=e;return Object.assign(e,{customUserAgent:typeof n=="string"?[[n]]:n,userAgentAppId:async()=>{const i=await t();if(!S7e(i)){const r=e.logger?.constructor?.name==="NoOpLogger"||!e.logger?console:e.logger;typeof i!="string"?r?.warn("userAgentAppId must be a string or undefined."):i.length>50&&r?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return i}})}class T7e{capacity;data=new Map;parameters=[];constructor({size:t,params:n}){this.capacity=t??50,n&&(this.parameters=n)}get(t,n){const i=this.hash(t);if(i===!1)return n();if(!this.data.has(i)){if(this.data.size>this.capacity+10){const r=this.data.keys();let a=0;for(;;){const{value:l,done:c}=r.next();if(this.data.delete(l),c||++a>10)break}}this.data.set(i,n())}return this.data.get(i)}size(){return this.data.size}hash(t){let n="";const{parameters:i}=this;if(i.length===0)return!1;for(const r of i){const a=String(t[r]??"");if(a.includes("|;"))return!1;n+=a+"|;"}return n}}const E7e=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),oce=e=>E7e.test(e)||e.startsWith("[")&&e.endsWith("]"),k7e=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),_E=(e,t=!1)=>{if(!t)return k7e.test(e);const n=e.split(".");for(const i of n)if(!_E(i))return!1;return!0},KT={},F_="endpoints";function pg(e){return typeof e!="object"||e==null?e:"ref"in e?`$${pg(e.ref)}`:"fn"in e?`${e.fn}(${(e.argv||[]).map(pg).join(", ")})`:JSON.stringify(e,null,2)}class hs extends Error{constructor(t){super(t),this.name="EndpointError"}}const A7e=(e,t)=>e===t,R7e=e=>{const t=e.split("."),n=[];for(const i of t){const r=i.indexOf("[");if(r!==-1){if(i.indexOf("]")!==i.length-1)throw new hs(`Path: '${e}' does not end with ']'`);const a=i.slice(r+1,-1);if(Number.isNaN(parseInt(a)))throw new hs(`Invalid array index: '${a}' in path: '${e}'`);r!==0&&n.push(i.slice(0,r)),n.push(a)}else n.push(i)}return n},lce=(e,t)=>R7e(t).reduce((n,i)=>{if(typeof n!="object")throw new hs(`Index '${i}' in '${t}' not found in '${JSON.stringify(e)}'`);return Array.isArray(n)?n[parseInt(i)]:n[i]},e),O7e=e=>e!=null,I7e=e=>!e,V6={[$_.HTTP]:80,[$_.HTTPS]:443},P7e=e=>{const t=(()=>{try{if(e instanceof URL)return e;if(typeof e=="object"&&"hostname"in e){const{hostname:p,port:f,protocol:h="",path:m="",query:g={}}=e,y=new URL(`${h}//${p}${f?`:${f}`:""}${m}`);return y.search=Object.entries(g).map(([v,b])=>`${v}=${b}`).join("&"),y}return new URL(e)}catch{return null}})();if(!t)return console.error(`Unable to parse ${JSON.stringify(e)} as a whatwg URL.`),null;const n=t.href,{host:i,hostname:r,pathname:a,protocol:l,search:c}=t;if(c)return null;const o=l.slice(0,-1);if(!Object.values($_).includes(o))return null;const s=oce(r),u=n.includes(`${i}:${V6[o]}`)||typeof e=="string"&&e.includes(`${i}:${V6[o]}`),d=`${i}${u?`:${V6[o]}`:""}`;return{scheme:o,authority:d,path:a,normalizedPath:a.endsWith("/")?a:`${a}/`,isIp:s}},M7e=(e,t)=>e===t,N7e=(e,t,n,i)=>t>=n||e.length<n||/[^\u0000-\u007f]/.test(e)?null:i?e.substring(e.length-n,e.length-t):e.substring(t,n),$7e=e=>encodeURIComponent(e).replace(/[!*'()]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),D7e={booleanEquals:A7e,getAttr:lce,isSet:O7e,isValidHostLabel:_E,not:I7e,parseURL:P7e,stringEquals:M7e,substring:N7e,uriEncode:$7e},cce=(e,t)=>{const n=[],i={...t.endpointParams,...t.referenceRecord};let r=0;for(;r<e.length;){const a=e.indexOf("{",r);if(a===-1){n.push(e.slice(r));break}n.push(e.slice(r,a));const l=e.indexOf("}",a);if(l===-1){n.push(e.slice(a));break}e[a+1]==="{"&&e[l+1]==="}"&&(n.push(e.slice(a+1,l)),r=l+2);const c=e.substring(a+1,l);if(c.includes("#")){const[o,s]=c.split("#");n.push(lce(i[o],s))}else n.push(i[c]);r=l+1}return n.join("")},j7e=({ref:e},t)=>({...t.endpointParams,...t.referenceRecord})[e],xE=(e,t,n)=>{if(typeof e=="string")return cce(e,n);if(e.fn)return dce.callFunction(e,n);if(e.ref)return j7e(e,n);throw new hs(`'${t}': ${String(e)} is not a string, function or reference.`)},uce=({fn:e,argv:t},n)=>{const i=t.map(a=>["boolean","number"].includes(typeof a)?a:dce.evaluateExpression(a,"arg",n)),r=e.split(".");return r[0]in KT&&r[1]!=null?KT[r[0]][r[1]](...i):D7e[e](...i)},dce={evaluateExpression:xE,callFunction:uce},L7e=({assign:e,...t},n)=>{if(e&&e in n.referenceRecord)throw new hs(`'${e}' is already defined in Reference Record.`);const i=uce(t,n);return n.logger?.debug?.(`${F_} evaluateCondition: ${pg(t)} = ${pg(i)}`),{result:i===""?!0:!!i,...e!=null&&{toAssign:{name:e,value:i}}}},S8=(e=[],t)=>{const n={};for(const i of e){const{result:r,toAssign:a}=L7e(i,{...t,referenceRecord:{...t.referenceRecord,...n}});if(!r)return{result:r};a&&(n[a.name]=a.value,t.logger?.debug?.(`${F_} assign: ${a.name} := ${pg(a.value)}`))}return{result:!0,referenceRecord:n}},U7e=(e,t)=>Object.entries(e).reduce((n,[i,r])=>({...n,[i]:r.map(a=>{const l=xE(a,"Header value entry",t);if(typeof l!="string")throw new hs(`Header '${i}' value '${l}' is not a string`);return l})}),{}),pce=(e,t)=>Object.entries(e).reduce((n,[i,r])=>({...n,[i]:hce.getEndpointProperty(r,t)}),{}),fce=(e,t)=>{if(Array.isArray(e))return e.map(n=>fce(n,t));switch(typeof e){case"string":return cce(e,t);case"object":if(e===null)throw new hs(`Unexpected endpoint property: ${e}`);return hce.getEndpointProperties(e,t);case"boolean":return e;default:throw new hs(`Unexpected endpoint property type: ${typeof e}`)}},hce={getEndpointProperty:fce,getEndpointProperties:pce},F7e=(e,t)=>{const n=xE(e,"Endpoint URL",t);if(typeof n=="string")try{return new URL(n)}catch(i){throw console.error(`Failed to construct URL with ${n}`,i),i}throw new hs(`Endpoint URL must be a string, got ${typeof n}`)},q7e=(e,t)=>{const{conditions:n,endpoint:i}=e,{result:r,referenceRecord:a}=S8(n,t);if(!r)return;const l={...t,referenceRecord:{...t.referenceRecord,...a}},{url:c,properties:o,headers:s}=i;return t.logger?.debug?.(`${F_} Resolving endpoint from template: ${pg(i)}`),{...s!=null&&{headers:U7e(s,l)},...o!=null&&{properties:pce(o,l)},url:F7e(c,l)}},B7e=(e,t)=>{const{conditions:n,error:i}=e,{result:r,referenceRecord:a}=S8(n,t);if(r)throw new hs(xE(i,"Error",{...t,referenceRecord:{...t.referenceRecord,...a}}))},mce=(e,t)=>{for(const n of e)if(n.type==="endpoint"){const i=q7e(n,t);if(i)return i}else if(n.type==="error")B7e(n,t);else if(n.type==="tree"){const i=gce.evaluateTreeRule(n,t);if(i)return i}else throw new hs(`Unknown endpoint rule: ${n}`);throw new hs("Rules evaluation failed")},W7e=(e,t)=>{const{conditions:n,rules:i}=e,{result:r,referenceRecord:a}=S8(n,t);if(r)return gce.evaluateRules(i,{...t,referenceRecord:{...t.referenceRecord,...a}})},gce={evaluateRules:mce,evaluateTreeRule:W7e},z7e=(e,t)=>{const{endpointParams:n,logger:i}=t,{parameters:r,rules:a}=e;t.logger?.debug?.(`${F_} Initial EndpointParams: ${pg(n)}`);const l=Object.entries(r).filter(([,s])=>s.default!=null).map(([s,u])=>[s,u.default]);if(l.length>0)for(const[s,u]of l)n[s]=n[s]??u;const c=Object.entries(r).filter(([,s])=>s.required).map(([s])=>s);for(const s of c)if(n[s]==null)throw new hs(`Missing required parameter: '${s}'`);const o=mce(a,{endpointParams:n,logger:i,referenceRecord:{}});return t.logger?.debug?.(`${F_} Resolved endpoint: ${pg(o)}`),o},yce=(e,t=!1)=>{if(t){for(const n of e.split("."))if(!yce(n))return!1;return!0}return!(!_E(e)||e.length<3||e.length>63||e!==e.toLowerCase()||oce(e))},mF=":",G7e="/",H7e=e=>{const t=e.split(mF);if(t.length<6)return null;const[n,i,r,a,l,...c]=t;if(n!=="arn"||i===""||r===""||c.join(mF)==="")return null;const o=c.map(s=>s.split(G7e)).flat();return{partition:i,service:r,region:a,accountId:l,resourceId:o}},V7e=[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-east-2":{description:"Asia Pacific (Taipei)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"ap-southeast-6":{description:"Asia Pacific (New Zealand)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"aws global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"mx-central-1":{description:"Mexico (Central)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"aws-cn global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"api.amazonwebservices.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"AWS European Sovereign Cloud (Germany)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"api.aws.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"aws-iso global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"api.aws.scloud",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"aws-iso-b global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"},"us-isob-west-1":{description:"US ISOB West"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"api.cloud-aws.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"aws-iso-e global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"api.aws.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"aws-iso-f global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"aws-us-gov global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}}],J7e={partitions:V7e};let K7e=J7e;const Z7e=e=>{const{partitions:t}=K7e;for(const i of t){const{regions:r,outputs:a}=i;for(const[l,c]of Object.entries(r))if(l===e)return{...a,...c}}for(const i of t){const{regionRegex:r,outputs:a}=i;if(new RegExp(r).test(e))return{...a}}const n=t.find(i=>i.id==="aws");if(!n)throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...n.outputs}},vce={isVirtualHostableS3Bucket:yce,parseArn:H7e,partition:Z7e};KT.aws=vce;function X7e(e){const t={};if(e=e.replace(/^\?/,""),e)for(const n of e.split("&")){let[i,r=null]=n.split("=");i=decodeURIComponent(i),r&&(r=decodeURIComponent(r)),i in t?Array.isArray(t[i])?t[i].push(r):t[i]=[t[i],r]:t[i]=r}return t}const ZT=e=>{if(typeof e=="string")return ZT(new URL(e));const{hostname:t,pathname:n,port:i,protocol:r,search:a}=e;let l;return a&&(l=X7e(a)),{hostname:t,port:i?parseInt(i):void 0,protocol:r,path:n,query:l}};function Q7e(e,t,n){return e.$source||(e.$source={}),e.$source[t]=n,e}function Bo(e,t,n){e.__aws_sdk_context?e.__aws_sdk_context.features||(e.__aws_sdk_context.features={}):e.__aws_sdk_context={features:{}},e.__aws_sdk_context.features[t]=n}const gF=e=>jy.isInstance(e)?e.headers?.date??e.headers?.Date:void 0,bce=e=>new Date(Date.now()+e),Y7e=(e,t)=>Math.abs(bce(t).getTime()-e)>=3e5,yF=(e,t)=>{const n=Date.parse(e);return Y7e(n,t)?n-Date.now():t},__=(e,t)=>{if(!t)throw new Error(`Property \`${e}\` is not resolved for AWS SDK SigV4Auth`);return t},eMe=async e=>{const t=__("context",e.context),n=__("config",e.config),i=t.endpointV2?.properties?.authSchemes?.[0],a=await __("signer",n.signer)(i),l=e?.signingRegion,c=e?.signingRegionSet,o=e?.signingName;return{config:n,signer:a,signingRegion:l,signingRegionSet:c,signingName:o}};class tMe{async sign(t,n,i){if(!Ea.isInstance(t))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const r=await eMe(i),{config:a,signer:l}=r;let{signingRegion:c,signingName:o}=r;const s=i.context;if(s?.authSchemes?.length??!1){const[d,p]=s.authSchemes;d?.name==="sigv4a"&&p?.name==="sigv4"&&(c=p?.signingRegion??c,o=p?.signingName??o)}return await l.sign(t,{signingDate:bce(a.systemClockOffset),signingRegion:c,signingService:o})}errorHandler(t){return n=>{const i=n.ServerTime??gF(n.$response);if(i){const r=__("config",t.config),a=r.systemClockOffset;r.systemClockOffset=yF(i,r.systemClockOffset),r.systemClockOffset!==a&&n.$metadata&&(n.$metadata.clockSkewCorrected=!0)}throw n}}successHandler(t,n){const i=gF(t);if(i){const r=__("config",n.config);r.systemClockOffset=yF(i,r.systemClockOffset)}}}const nMe=(e,t,n)=>{let i,r,a,l=!1;const c=async()=>{r||(r=e());try{i=await r,a=!0,l=!1}finally{r=void 0}return i};return async o=>((!a||o?.forceRefresh)&&(i=await c()),i)},rMe="X-Amz-Algorithm",iMe="X-Amz-Credential",wce="X-Amz-Date",aMe="X-Amz-SignedHeaders",sMe="X-Amz-Expires",_ce="X-Amz-Signature",xce="X-Amz-Security-Token",Sce="authorization",Cce=wce.toLowerCase(),oMe="date",lMe=[Sce,Cce,oMe],cMe=_ce.toLowerCase(),rO="x-amz-content-sha256",uMe=xce.toLowerCase(),dMe={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},pMe=/^proxy-/,fMe=/^sec-/,J6="AWS4-HMAC-SHA256",hMe="AWS4-HMAC-SHA256-PAYLOAD",mMe="UNSIGNED-PAYLOAD",gMe=50,Tce="aws4_request",yMe=3600*24*7,Ux={},K6=[],Z6=(e,t,n)=>`${e}/${t}/${n}/${Tce}`,vMe=async(e,t,n,i,r)=>{const a=await vF(e,t.secretAccessKey,t.accessKeyId),l=`${n}:${i}:${r}:${qa(a)}:${t.sessionToken}`;if(l in Ux)return Ux[l];for(K6.push(l);K6.length>gMe;)delete Ux[K6.shift()];let c=`AWS4${t.secretAccessKey}`;for(const o of[n,i,r,Tce])c=await vF(e,c,o);return Ux[l]=c},vF=(e,t,n)=>{const i=new e(t);return i.update(j_(n)),i.digest()},bF=({headers:e},t,n)=>{const i={};for(const r of Object.keys(e).sort()){if(e[r]==null)continue;const a=r.toLowerCase();(a in dMe||t?.has(a)||pMe.test(a)||fMe.test(a))&&(!n||n&&!n.has(a))||(i[a]=e[r].trim().replace(/\s+/g," "))}return i},bMe=e=>typeof ArrayBuffer=="function"&&e instanceof ArrayBuffer||Object.prototype.toString.call(e)==="[object ArrayBuffer]",X6=async({headers:e,body:t},n)=>{for(const i of Object.keys(e))if(i.toLowerCase()===rO)return e[i];if(t==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if(typeof t=="string"||ArrayBuffer.isView(t)||bMe(t)){const i=new n;return i.update(j_(t)),qa(await i.digest())}return mMe};class wMe{format(t){const n=[];for(const a of Object.keys(t)){const l=Uy(a);n.push(Uint8Array.from([l.byteLength]),l,this.formatHeaderValue(t[a]))}const i=new Uint8Array(n.reduce((a,l)=>a+l.byteLength,0));let r=0;for(const a of n)i.set(a,r),r+=a.byteLength;return i}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?0:1]);case"byte":return Uint8Array.from([2,t.value]);case"short":const n=new DataView(new ArrayBuffer(3));return n.setUint8(0,3),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":const i=new DataView(new ArrayBuffer(5));return i.setUint8(0,4),i.setInt32(1,t.value,!1),new Uint8Array(i.buffer);case"long":const r=new Uint8Array(9);return r[0]=5,r.set(t.value.bytes,1),r;case"binary":const a=new DataView(new ArrayBuffer(3+t.value.byteLength));a.setUint8(0,6),a.setUint16(1,t.value.byteLength,!1);const l=new Uint8Array(a.buffer);return l.set(t.value,3),l;case"string":const c=Uy(t.value),o=new DataView(new ArrayBuffer(3+c.byteLength));o.setUint8(0,7),o.setUint16(1,c.byteLength,!1);const s=new Uint8Array(o.buffer);return s.set(c,3),s;case"timestamp":const u=new Uint8Array(9);return u[0]=8,u.set(xMe.fromNumber(t.value.valueOf()).bytes,1),u;case"uuid":if(!_Me.test(t.value))throw new Error(`Invalid UUID received: ${t.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(g8(t.value.replace(/\-/g,"")),1),d}}}var wF;(function(e){e[e.boolTrue=0]="boolTrue",e[e.boolFalse=1]="boolFalse",e[e.byte=2]="byte",e[e.short=3]="short",e[e.integer=4]="integer",e[e.long=5]="long",e[e.byteArray=6]="byteArray",e[e.string=7]="string",e[e.timestamp=8]="timestamp",e[e.uuid=9]="uuid"})(wF||(wF={}));const _Me=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;let xMe=class Ece{bytes;constructor(t){if(this.bytes=t,t.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(t){if(t>9223372036854776e3||t<-9223372036854776e3)throw new Error(`${t} is too large (or, if negative, too small) to represent as an Int64`);const n=new Uint8Array(8);for(let i=7,r=Math.abs(Math.round(t));i>-1&&r>0;i--,r/=256)n[i]=r;return t<0&&_F(n),new Ece(n)}valueOf(){const t=this.bytes.slice(0),n=t[0]&128;return n&&_F(t),parseInt(qa(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}};function _F(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,e[t]===0);t--);}const SMe=(e,t)=>{e=e.toLowerCase();for(const n of Object.keys(t))if(e===n.toLowerCase())return!0;return!1},CMe=(e,t={})=>{const{headers:n,query:i={}}=Ea.clone(e);for(const r of Object.keys(n)){const a=r.toLowerCase();(a.slice(0,6)==="x-amz-"&&!t.unhoistableHeaders?.has(a)||t.hoistableHeaders?.has(a))&&(i[r]=n[r],delete n[r])}return{...e,headers:n,query:i}},xF=e=>{e=Ea.clone(e);for(const t of Object.keys(e.headers))lMe.indexOf(t.toLowerCase())>-1&&delete e.headers[t];return e},TMe=({query:e={}})=>{const t=[],n={};for(const i of Object.keys(e)){if(i.toLowerCase()===cMe)continue;const r=Oy(i);t.push(r);const a=e[i];typeof a=="string"?n[r]=`${r}=${Oy(a)}`:Array.isArray(a)&&(n[r]=a.slice(0).reduce((l,c)=>l.concat([`${r}=${Oy(c)}`]),[]).sort().join("&"))}return t.sort().map(i=>n[i]).filter(i=>i).join("&")},EMe=e=>kMe(e).toISOString().replace(/\.\d{3}Z$/,"Z"),kMe=e=>typeof e=="number"?new Date(e*1e3):typeof e=="string"?Number(e)?new Date(Number(e)*1e3):new Date(e):e;class AMe{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:t,credentials:n,region:i,service:r,sha256:a,uriEscapePath:l=!0}){this.service=r,this.sha256=a,this.uriEscapePath=l,this.applyChecksum=typeof t=="boolean"?t:!0,this.regionProvider=ym(i),this.credentialProvider=ym(n)}createCanonicalRequest(t,n,i){const r=Object.keys(n).sort();return`${t.method}
515
515
  ${this.getCanonicalPath(t)}
516
516
  ${TMe(t)}
517
517
  ${r.map(a=>`${a}:${n[a]}`).join(`
@@ -522,13 +522,13 @@ ${i}`}async createStringToSign(t,n,i,r){const a=new this.sha256;a.update(j_(i));
522
522
  ${t}
523
523
  ${n}
524
524
  ${qa(l)}`}getCanonicalPath({path:t}){if(this.uriEscapePath){const n=[];for(const a of t.split("/"))a?.length!==0&&a!=="."&&(a===".."?n.pop():n.push(a));const i=`${t?.startsWith("/")?"/":""}${n.join("/")}${n.length>0&&t?.endsWith("/")?"/":""}`;return Oy(i).replace(/%2F/g,"/")}return t}validateResolvedCredentials(t){if(typeof t!="object"||typeof t.accessKeyId!="string"||typeof t.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}formatDate(t){const n=EMe(t).replace(/[\-:]/g,"");return{longDate:n,shortDate:n.slice(0,8)}}getCanonicalHeaderList(t){return Object.keys(t).sort().join(";")}}class SF extends AMe{headerFormatter=new wMe;constructor({applyChecksum:t,credentials:n,region:i,service:r,sha256:a,uriEscapePath:l=!0}){super({applyChecksum:t,credentials:n,region:i,service:r,sha256:a,uriEscapePath:l})}async presign(t,n={}){const{signingDate:i=new Date,expiresIn:r=3600,unsignableHeaders:a,unhoistableHeaders:l,signableHeaders:c,hoistableHeaders:o,signingRegion:s,signingService:u}=n,d=await this.credentialProvider();this.validateResolvedCredentials(d);const p=s??await this.regionProvider(),{longDate:f,shortDate:h}=this.formatDate(i);if(r>yMe)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");const m=Z6(h,p,u??this.service),g=CMe(xF(t),{unhoistableHeaders:l,hoistableHeaders:o});d.sessionToken&&(g.query[xce]=d.sessionToken),g.query[rMe]=J6,g.query[iMe]=`${d.accessKeyId}/${m}`,g.query[wce]=f,g.query[sMe]=r.toString(10);const y=bF(g,a,c);return g.query[aMe]=this.getCanonicalHeaderList(y),g.query[_ce]=await this.getSignature(f,m,this.getSigningKey(d,p,h,u),this.createCanonicalRequest(g,y,await X6(t,this.sha256))),g}async sign(t,n){return typeof t=="string"?this.signString(t,n):t.headers&&t.payload?this.signEvent(t,n):t.message?this.signMessage(t,n):this.signRequest(t,n)}async signEvent({headers:t,payload:n},{signingDate:i=new Date,priorSignature:r,signingRegion:a,signingService:l}){const c=a??await this.regionProvider(),{shortDate:o,longDate:s}=this.formatDate(i),u=Z6(o,c,l??this.service),d=await X6({headers:{},body:n},this.sha256),p=new this.sha256;p.update(t);const f=qa(await p.digest()),h=[hMe,s,u,r,f,d].join(`
525
- `);return this.signString(h,{signingDate:i,signingRegion:c,signingService:l})}async signMessage(t,{signingDate:n=new Date,signingRegion:i,signingService:r}){return this.signEvent({headers:this.headerFormatter.format(t.message.headers),payload:t.message.body},{signingDate:n,signingRegion:i,signingService:r,priorSignature:t.priorSignature}).then(l=>({message:t.message,signature:l}))}async signString(t,{signingDate:n=new Date,signingRegion:i,signingService:r}={}){const a=await this.credentialProvider();this.validateResolvedCredentials(a);const l=i??await this.regionProvider(),{shortDate:c}=this.formatDate(n),o=new this.sha256(await this.getSigningKey(a,l,c,r));return o.update(j_(t)),qa(await o.digest())}async signRequest(t,{signingDate:n=new Date,signableHeaders:i,unsignableHeaders:r,signingRegion:a,signingService:l}={}){const c=await this.credentialProvider();this.validateResolvedCredentials(c);const o=a??await this.regionProvider(),s=xF(t),{longDate:u,shortDate:d}=this.formatDate(n),p=Z6(d,o,l??this.service);s.headers[Cce]=u,c.sessionToken&&(s.headers[uMe]=c.sessionToken);const f=await X6(s,this.sha256);!SMe(rO,s.headers)&&this.applyChecksum&&(s.headers[rO]=f);const h=bF(s,r,i),m=await this.getSignature(u,p,this.getSigningKey(c,o,d,l),this.createCanonicalRequest(s,h,f));return s.headers[Sce]=`${J6} Credential=${c.accessKeyId}/${p}, SignedHeaders=${this.getCanonicalHeaderList(h)}, Signature=${m}`,s}async getSignature(t,n,i,r){const a=await this.createStringToSign(t,n,r,J6),l=new this.sha256(await i);return l.update(j_(a)),qa(await l.digest())}getSigningKey(t,n,i,r){return vMe(this.sha256,t,i,n,r||this.service)}}const RMe=e=>{let t=e.credentials,n=!!e.credentials,i;Object.defineProperty(e,"credentials",{set(s){s&&s!==t&&s!==i&&(n=!0),t=s;const u=OMe(e,{credentials:t,credentialDefaultProvider:e.credentialDefaultProvider}),d=IMe(e,u);if(n&&!d.attributed){const p=typeof t=="object"&&t!==null;i=async f=>{const m=await d(f);return p&&(!m.$source||Object.keys(m.$source).length===0)?Q7e(m,"CREDENTIALS_CODE","e"):m},i.memoized=d.memoized,i.configBound=d.configBound,i.attributed=!0}else i=d},get(){return i},enumerable:!0,configurable:!0}),e.credentials=t;const{signingEscapePath:r=!0,systemClockOffset:a=e.systemClockOffset||0,sha256:l}=e;let c;return e.signer?c=b_(e.signer):e.regionInfoProvider?c=()=>b_(e.region)().then(async s=>[await e.regionInfoProvider(s,{useFipsEndpoint:await e.useFipsEndpoint(),useDualstackEndpoint:await e.useDualstackEndpoint()})||{},s]).then(([s,u])=>{const{signingRegion:d,signingService:p}=s;e.signingRegion=e.signingRegion||d||u,e.signingName=e.signingName||p||e.serviceId;const f={...e,credentials:e.credentials,region:e.signingRegion,service:e.signingName,sha256:l,uriEscapePath:r},h=e.signerConstructor||SF;return new h(f)}):c=async s=>{s=Object.assign({},{name:"sigv4",signingName:e.signingName||e.defaultSigningName,signingRegion:await b_(e.region)(),properties:{}},s);const u=s.signingRegion,d=s.signingName;e.signingRegion=e.signingRegion||u,e.signingName=e.signingName||d||e.serviceId;const p={...e,credentials:e.credentials,region:e.signingRegion,service:e.signingName,sha256:l,uriEscapePath:r},f=e.signerConstructor||SF;return new f(p)},Object.assign(e,{systemClockOffset:a,signingEscapePath:r,signer:c})};function OMe(e,{credentials:t,credentialDefaultProvider:n}){let i;return t?t?.memoized?i=t:i=sce(t,ace,x8):n?i=b_(n(Object.assign({},e,{parentClientConfig:e}))):i=async()=>{throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")},i.memoized=!0,i}function IMe(e,t){if(t.configBound)return t;const n=async i=>t({...i,callerClientConfig:e});return n.memoized=t.memoized,n.configBound=!0,n}const CF=typeof TextEncoder=="function"?new TextEncoder:null,PMe=e=>{if(typeof e=="string"){if(CF)return CF.encode(e).byteLength;let t=e.length;for(let n=t-1;n>=0;n--){const i=e.charCodeAt(n);i>127&&i<=2047?t++:i>2047&&i<=65535&&(t+=2),i>=56320&&i<=57343&&n--}return t}else{if(typeof e.byteLength=="number")return e.byteLength;if(typeof e.size=="number")return e.size}throw new Error(`Body Length computation failed for ${e}`)},Dg=(e,t)=>{const n=[];if(e&&n.push(e),t)for(const i of t)n.push(i);return n},qm=(e,t)=>`${e||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`,XT=()=>{let e=[],t=[],n=!1;const i=new Set,r=d=>d.sort((p,f)=>TF[f.step]-TF[p.step]||EF[f.priority||"normal"]-EF[p.priority||"normal"]),a=d=>{let p=!1;const f=h=>{const m=Dg(h.name,h.aliases);if(m.includes(d)){p=!0;for(const g of m)i.delete(g);return!1}return!0};return e=e.filter(f),t=t.filter(f),p},l=d=>{let p=!1;const f=h=>{if(h.middleware===d){p=!0;for(const m of Dg(h.name,h.aliases))i.delete(m);return!1}return!0};return e=e.filter(f),t=t.filter(f),p},c=d=>(e.forEach(p=>{d.add(p.middleware,{...p})}),t.forEach(p=>{d.addRelativeTo(p.middleware,{...p})}),d.identifyOnResolve?.(u.identifyOnResolve()),d),o=d=>{const p=[];return d.before.forEach(f=>{f.before.length===0&&f.after.length===0?p.push(f):p.push(...o(f))}),p.push(d),d.after.reverse().forEach(f=>{f.before.length===0&&f.after.length===0?p.push(f):p.push(...o(f))}),p},s=(d=!1)=>{const p=[],f=[],h={};return e.forEach(g=>{const y={...g,before:[],after:[]};for(const v of Dg(y.name,y.aliases))h[v]=y;p.push(y)}),t.forEach(g=>{const y={...g,before:[],after:[]};for(const v of Dg(y.name,y.aliases))h[v]=y;f.push(y)}),f.forEach(g=>{if(g.toMiddleware){const y=h[g.toMiddleware];if(y===void 0){if(d)return;throw new Error(`${g.toMiddleware} is not found when adding ${qm(g.name,g.aliases)} middleware ${g.relation} ${g.toMiddleware}`)}g.relation==="after"&&y.after.push(g),g.relation==="before"&&y.before.push(g)}}),r(p).map(o).reduce((g,y)=>(g.push(...y),g),[])},u={add:(d,p={})=>{const{name:f,override:h,aliases:m}=p,g={step:"initialize",priority:"normal",middleware:d,...p},y=Dg(f,m);if(y.length>0){if(y.some(v=>i.has(v))){if(!h)throw new Error(`Duplicate middleware name '${qm(f,m)}'`);for(const v of y){const b=e.findIndex(x=>x.name===v||x.aliases?.some(C=>C===v));if(b===-1)continue;const w=e[b];if(w.step!==g.step||g.priority!==w.priority)throw new Error(`"${qm(w.name,w.aliases)}" middleware with ${w.priority} priority in ${w.step} step cannot be overridden by "${qm(f,m)}" middleware with ${g.priority} priority in ${g.step} step.`);e.splice(b,1)}}for(const v of y)i.add(v)}e.push(g)},addRelativeTo:(d,p)=>{const{name:f,override:h,aliases:m}=p,g={middleware:d,...p},y=Dg(f,m);if(y.length>0){if(y.some(v=>i.has(v))){if(!h)throw new Error(`Duplicate middleware name '${qm(f,m)}'`);for(const v of y){const b=t.findIndex(x=>x.name===v||x.aliases?.some(C=>C===v));if(b===-1)continue;const w=t[b];if(w.toMiddleware!==g.toMiddleware||w.relation!==g.relation)throw new Error(`"${qm(w.name,w.aliases)}" middleware ${w.relation} "${w.toMiddleware}" middleware cannot be overridden by "${qm(f,m)}" middleware ${g.relation} "${g.toMiddleware}" middleware.`);t.splice(b,1)}}for(const v of y)i.add(v)}t.push(g)},clone:()=>c(XT()),use:d=>{d.applyToStack(u)},remove:d=>typeof d=="string"?a(d):l(d),removeByTag:d=>{let p=!1;const f=h=>{const{tags:m,name:g,aliases:y}=h;if(m&&m.includes(d)){const v=Dg(g,y);for(const b of v)i.delete(b);return p=!0,!1}return!0};return e=e.filter(f),t=t.filter(f),p},concat:d=>{const p=c(XT());return p.use(d),p.identifyOnResolve(n||p.identifyOnResolve()||(d.identifyOnResolve?.()??!1)),p},applyToStack:c,identify:()=>s(!0).map(d=>{const p=d.step??d.relation+" "+d.toMiddleware;return qm(d.name,d.aliases)+" - "+p}),identifyOnResolve(d){return typeof d=="boolean"&&(n=d),n},resolve:(d,p)=>{for(const f of s().map(h=>h.middleware).reverse())d=f(d,p);return n&&console.log(u.identify()),d}};return u},TF={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},EF={high:3,normal:2,low:1};class MMe{config;middlewareStack=XT();initConfig;handlers;constructor(t){this.config=t;const{protocol:n,protocolSettings:i}=t;i&&typeof n=="function"&&(t.protocol=new n(i))}send(t,n,i){const r=typeof n!="function"?n:void 0,a=typeof n=="function"?n:i,l=r===void 0&&this.config.cacheMiddleware===!0;let c;if(l){this.handlers||(this.handlers=new WeakMap);const o=this.handlers;o.has(t.constructor)?c=o.get(t.constructor):(c=t.resolveMiddleware(this.middlewareStack,this.config,r),o.set(t.constructor,c))}else delete this.handlers,c=t.resolveMiddleware(this.middlewareStack,this.config,r);if(a)c(t).then(o=>a(null,o.output),o=>a(o)).catch(()=>{});else return c(t).then(o=>o.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}const Q6="***SensitiveInformation***";function iO(e,t){if(t==null)return t;const n=Mr.of(e);if(n.getMergedTraits().sensitive)return Q6;if(n.isListSchema()){if(!!n.getValueSchema().getMergedTraits().sensitive)return Q6}else if(n.isMapSchema()){if(!!n.getKeySchema().getMergedTraits().sensitive||!!n.getValueSchema().getMergedTraits().sensitive)return Q6}else if(n.isStructSchema()&&typeof t=="object"){const i=t,r={};for(const[a,l]of n.structIterator())i[a]!=null&&(r[a]=iO(l,i[a]));return r}return t}class kce{middlewareStack=XT();schema;static classBuilder(){return new NMe}resolveMiddlewareWithContext(t,n,i,{middlewareFn:r,clientName:a,commandName:l,inputFilterSensitiveLog:c,outputFilterSensitiveLog:o,smithyContext:s,additionalContext:u,CommandCtor:d}){for(const g of r.bind(this)(d,t,n,i))this.middlewareStack.use(g);const p=t.concat(this.middlewareStack),{logger:f}=n,h={logger:f,clientName:a,commandName:l,inputFilterSensitiveLog:c,outputFilterSensitiveLog:o,[eO]:{commandInstance:this,...s},...u},{requestHandler:m}=n;return p.resolve(g=>m.handle(g.request,i||{}),h)}}class NMe{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(t){this._init=t}ep(t){return this._ep=t,this}m(t){return this._middlewareFn=t,this}s(t,n,i={}){return this._smithyContext={service:t,operation:n,...i},this}c(t={}){return this._additionalContext=t,this}n(t,n){return this._clientName=t,this._commandName=n,this}f(t=i=>i,n=i=>i){return this._inputFilterSensitiveLog=t,this._outputFilterSensitiveLog=n,this}ser(t){return this._serializer=t,this}de(t){return this._deserializer=t,this}sc(t){return this._operationSchema=t,this._smithyContext.operationSchema=t,this}build(){const t=this;let n;return n=class extends kce{input;static getEndpointParameterInstructions(){return t._ep}constructor(...[i]){super(),this.input=i??{},t._init(this),this.schema=t._operationSchema}resolveMiddleware(i,r,a){const l=t._operationSchema,c=l?.[4]??l?.input,o=l?.[5]??l?.output;return this.resolveMiddlewareWithContext(i,r,a,{CommandCtor:n,middlewareFn:t._middlewareFn,clientName:t._clientName,commandName:t._commandName,inputFilterSensitiveLog:t._inputFilterSensitiveLog??(l?iO.bind(null,c):s=>s),outputFilterSensitiveLog:t._outputFilterSensitiveLog??(l?iO.bind(null,o):s=>s),smithyContext:t._smithyContext,additionalContext:t._additionalContext})}serialize=t._serializer;deserialize=t._deserializer}}}class fb extends Error{$fault;$response;$retryable;$metadata;constructor(t){super(t.message),Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=t.name,this.$fault=t.$fault,this.$metadata=t.$metadata}static isInstance(t){if(!t)return!1;const n=t;return fb.prototype.isPrototypeOf(n)||!!n.$fault&&!!n.$metadata&&(n.$fault==="client"||n.$fault==="server")}static[Symbol.hasInstance](t){if(!t)return!1;const n=t;return this===fb?fb.isInstance(t):fb.isInstance(t)?n.name&&this.name?this.prototype.isPrototypeOf(t)||n.name===this.name:this.prototype.isPrototypeOf(t):!1}}const kF=(e,t={})=>{Object.entries(t).filter(([,i])=>i!==void 0).forEach(([i,r])=>{(e[i]==null||e[i]==="")&&(e[i]=r)});const n=e.message||e.Message||"UnknownError";return e.message=n,delete e.Message,e},$Me=e=>{switch(e){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}},Ace=Object.values(D_),DMe=e=>{const t=[];for(const n in D_){const i=D_[n];e[i]!==void 0&&t.push({algorithmId:()=>i,checksumConstructor:()=>e[i]})}for(const[n,i]of Object.entries(e.checksumAlgorithms??{}))t.push({algorithmId:()=>n,checksumConstructor:()=>i});return{addChecksumAlgorithm(n){e.checksumAlgorithms=e.checksumAlgorithms??{};const i=n.algorithmId(),r=n.checksumConstructor();Ace.includes(i)?e.checksumAlgorithms[i.toUpperCase()]=r:e.checksumAlgorithms[i]=r,t.push(n)},checksumAlgorithms(){return t}}},jMe=e=>{const t={};return e.checksumAlgorithms().forEach(n=>{const i=n.algorithmId();Ace.includes(i)&&(t[i]=n.checksumConstructor())}),t},LMe=e=>({setRetryStrategy(t){e.retryStrategy=t},retryStrategy(){return e.retryStrategy}}),UMe=e=>{const t={};return t.retryStrategy=e.retryStrategy(),t},FMe=e=>Object.assign(DMe(e),LMe(e)),qMe=e=>Object.assign(jMe(e),UMe(e));class Rce{trace(){}debug(){}info(){}warn(){}error(){}}class BMe{queryCompat;constructor(t=!1){this.queryCompat=t}resolveRestContentType(t,n){const i=n.getMemberSchemas(),r=Object.values(i).find(a=>!!a.getMergedTraits().httpPayload);if(r){const a=r.getMergedTraits().mediaType;return a||(r.isStringSchema()?"text/plain":r.isBlobSchema()?"application/octet-stream":t)}else if(!n.isUnitSchema()&&Object.values(i).find(l=>{const{httpQuery:c,httpQueryParams:o,httpHeader:s,httpLabel:u,httpPrefixHeaders:d}=l.getMergedTraits();return!c&&!o&&!s&&!u&&d===void 0}))return t}async getErrorSchemaOrThrowBaseException(t,n,i,r,a,l){let c=n,o=t;t.includes("#")&&([c,o]=t.split("#"));const s={$metadata:a,$fault:i.statusCode<500?"client":"server"},u=Ua.for(c);try{return{errorSchema:l?.(u,o)??u.getSchema(t),errorMetadata:s}}catch{r.message=r.message??r.Message??"UnknownError";const p=Ua.for("smithy.ts.sdk.synthetic."+c),f=p.getBaseException();if(f){const h=p.getErrorCtor(f)??Error;throw this.decorateServiceException(Object.assign(new h({name:o}),s),r)}throw this.decorateServiceException(Object.assign(new Error(o),s),r)}}decorateServiceException(t,n={}){if(this.queryCompat){const i=t.Message??n.Message,r=kF(t,n);i&&(r.message=i),r.Error={...r.Error,Type:r.Error?.Type,Code:r.Error?.Code,Message:r.Error?.message??r.Error?.Message??i};const a=r.$metadata.requestId;return a&&(r.RequestId=a),r}return kF(t,n)}setQueryCompatError(t,n){const i=n.headers?.["x-amzn-query-error"];if(t!==void 0&&i!=null){const[r,a]=i.split(";"),l=Object.entries(t),c={Code:r,Type:a};Object.assign(t,c);for(const[o,s]of l)c[o==="message"?"Message":o]=s;delete c.__type,t.Error=c}}queryCompatOutput(t,n){t.Error&&(n.Error=t.Error),t.Type&&(n.Type=t.Type),t.Code&&(n.Code=t.Code)}findQueryCompatibleError(t,n){try{return t.getSchema(n)}catch{return t.find(r=>Mr.of(r).getMergedTraits().awsQueryError?.[0]===n)}}}class C8{serdeContext;setSerdeContext(t){this.serdeContext=t}}class WMe{from;to;keys;constructor(t,n){this.from=t,this.to=n,this.keys=new Set(Object.keys(this.from).filter(i=>i!=="__type"))}mark(t){this.keys.delete(t)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){const t=this.keys.values().next().value,n=this.from[t];this.to.$unknown=[t,n]}}}function zMe(e,t,n){if(n?.source){const i=n.source;if(typeof t=="number"&&(t>Number.MAX_SAFE_INTEGER||t<Number.MIN_SAFE_INTEGER||i!==String(t)))return i.includes(".")?new Co(i,"bigDecimal"):BigInt(i)}return t}const GMe=(e,t)=>Jw(e,t).then(n=>(t?.utf8Encoder??Kb)(n)),HMe=(e,t)=>GMe(e,t).then(n=>{if(n.length)try{return JSON.parse(n)}catch(i){throw i?.name==="SyntaxError"&&Object.defineProperty(i,"$responseBodyText",{value:n}),i}return{}}),VMe=(e,t)=>{const n=(a,l)=>Object.keys(a).find(c=>c.toLowerCase()===l.toLowerCase()),i=a=>{let l=a;return typeof l=="number"&&(l=l.toString()),l.indexOf(",")>=0&&(l=l.split(",")[0]),l.indexOf(":")>=0&&(l=l.split(":")[0]),l.indexOf("#")>=0&&(l=l.split("#")[1]),l},r=n(e.headers,"x-amzn-errortype");if(r!==void 0)return i(e.headers[r]);if(t&&typeof t=="object"){const a=n(t,"code");if(a&&t[a]!==void 0)return i(t[a]);if(t.__type!==void 0)return i(t.__type)}};class JMe extends C8{settings;constructor(t){super(),this.settings=t}async read(t,n){return this._read(t,typeof n=="string"?JSON.parse(n,zMe):await HMe(n,this.serdeContext))}readObject(t,n){return this._read(t,n)}_read(t,n){const i=n!==null&&typeof n=="object",r=Mr.of(t);if(i){if(r.isStructSchema()){const l=n,c=r.isUnionSchema(),o={};let s;const{jsonName:u}=this.settings;u&&(s={});let d;c&&(d=new WMe(l,o));for(const[p,f]of r.structIterator()){let h=p;u&&(h=f.getMergedTraits().jsonName??h,s[h]=p),c&&d.mark(h),l[h]!=null&&(o[p]=this._read(f,l[h]))}if(c)d.writeUnknown();else if(typeof l.__type=="string")for(const[p,f]of Object.entries(l)){const h=u?s[p]??p:p;h in o||(o[h]=f)}return o}if(Array.isArray(n)&&r.isListSchema()){const l=r.getValueSchema(),c=[],o=!!r.getMergedTraits().sparse;for(const s of n)(o||s!=null)&&c.push(this._read(l,s));return c}if(r.isMapSchema()){const l=r.getValueSchema(),c={},o=!!r.getMergedTraits().sparse;for(const[s,u]of Object.entries(n))(o||u!=null)&&(c[s]=this._read(l,u));return c}}if(r.isBlobSchema()&&typeof n=="string")return Ly(n);const a=r.getMergedTraits().mediaType;if(r.isStringSchema()&&typeof n=="string"&&a)return a==="application/json"||a.endsWith("+json")?Ic.from(n):n;if(r.isTimestampSchema()&&n!=null)switch(wE(r,this.settings)){case 5:return q8e(n);case 6:return G8e(n);case 7:return H8e(n);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",n),new Date(n)}if(r.isBigIntegerSchema()&&(typeof n=="number"||typeof n=="string"))return BigInt(n);if(r.isBigDecimalSchema()&&n!=null){if(n instanceof Co)return n;const l=n;return l.type==="bigDecimal"&&"string"in l?new Co(l.string,l.type):new Co(String(n),"bigDecimal")}if(r.isNumericSchema()&&typeof n=="string"){switch(n){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return n}if(r.isDocumentSchema())if(i){const l=Array.isArray(n)?[]:{};for(const[c,o]of Object.entries(n))o instanceof Co?l[c]=o:l[c]=this._read(r,o);return l}else return structuredClone(n);return n}}const AF="Ν";class KMe{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw new Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(t,n)=>{if(n instanceof Co){const i=`${AF+"nv"+this.counter++}_`+n.string;return this.values.set(`"${i}"`,n.string),i}if(typeof n=="bigint"){const i=n.toString(),r=`${AF+"b"+this.counter++}_`+i;return this.values.set(`"${r}"`,i),r}return n}}replaceInJson(t){if(this.stage===0)throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return t;for(const[n,i]of this.values)t=t.replace(n,i);return t}}class ZMe extends C8{settings;buffer;useReplacer=!1;rootSchema;constructor(t){super(),this.settings=t}write(t,n){this.rootSchema=Mr.of(t),this.buffer=this._write(this.rootSchema,n)}writeDiscriminatedDocument(t,n){this.write(t,n),typeof this.buffer=="object"&&(this.buffer.__type=Mr.of(t).getName(!0))}flush(){const{rootSchema:t,useReplacer:n}=this;if(this.rootSchema=void 0,this.useReplacer=!1,t?.isStructSchema()||t?.isDocumentSchema()){if(!n)return JSON.stringify(this.buffer);const i=new KMe;return i.replaceInJson(JSON.stringify(this.buffer,i.createReplacer(),0))}return this.buffer}_write(t,n,i){const r=n!==null&&typeof n=="object",a=Mr.of(t);if(r){if(a.isStructSchema()){const l=n,c={},{jsonName:o}=this.settings;let s;o&&(s={});for(const[u,d]of a.structIterator()){const p=this._write(d,l[u],a);if(p!==void 0){let f=u;o&&(f=d.getMergedTraits().jsonName??u,s[u]=f),c[f]=p}}if(a.isUnionSchema()&&Object.keys(c).length===0){const{$unknown:u}=l;if(Array.isArray(u)){const[d,p]=u;c[d]=this._write(15,p)}}else if(typeof l.__type=="string")for(const[u,d]of Object.entries(l)){const p=o?s[u]??u:u;p in c||(c[p]=this._write(15,d))}return c}if(Array.isArray(n)&&a.isListSchema()){const l=a.getValueSchema(),c=[],o=!!a.getMergedTraits().sparse;for(const s of n)(o||s!=null)&&c.push(this._write(l,s));return c}if(a.isMapSchema()){const l=a.getValueSchema(),c={},o=!!a.getMergedTraits().sparse;for(const[s,u]of Object.entries(n))(o||u!=null)&&(c[s]=this._write(l,u));return c}if(n instanceof Uint8Array&&(a.isBlobSchema()||a.isDocumentSchema()))return a===this.rootSchema?n:(this.serdeContext?.base64Encoder??Fy)(n);if(n instanceof Date&&(a.isTimestampSchema()||a.isDocumentSchema()))switch(wE(a,this.settings)){case 5:return n.toISOString().replace(".000Z","Z");case 6:return tce(n);case 7:return n.getTime()/1e3;default:return console.warn("Missing timestamp format, using epoch seconds",n),n.getTime()/1e3}n instanceof Co&&(this.useReplacer=!0)}if(!(n===null&&i?.isStructSchema())){if(a.isStringSchema()){if(typeof n>"u"&&a.isIdempotencyToken())return v8();const l=a.getMergedTraits().mediaType;return n!=null&&l&&(l==="application/json"||l.endsWith("+json"))?Ic.from(n):n}if(typeof n=="number"&&a.isNumericSchema())return Math.abs(n)===1/0||isNaN(n)?String(n):n;if(typeof n=="string"&&a.isBlobSchema())return a===this.rootSchema?n:(this.serdeContext?.base64Encoder??Fy)(n);if(typeof n=="bigint"&&(this.useReplacer=!0),a.isDocumentSchema())if(r){const l=Array.isArray(n)?[]:{};for(const[c,o]of Object.entries(n))o instanceof Co?(this.useReplacer=!0,l[c]=o):l[c]=this._write(a,o);return l}else return structuredClone(n);return n}}}class XMe extends C8{settings;constructor(t){super(),this.settings=t}createSerializer(){const t=new ZMe(this.settings);return t.setSerdeContext(this.serdeContext),t}createDeserializer(){const t=new JMe(this.settings);return t.setSerdeContext(this.serdeContext),t}}class QMe extends p7e{serializer;deserializer;codec;mixin=new BMe;constructor({defaultNamespace:t}){super({defaultNamespace:t});const n={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=new XMe(n),this.serializer=new g7e(this.codec.createSerializer(),n),this.deserializer=new h7e(this.codec.createDeserializer(),n)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(t){this.codec.setSerdeContext(t),super.setSerdeContext(t)}async serializeRequest(t,n,i){const r=await super.serializeRequest(t,n,i),a=Mr.of(t.input);if(!r.headers["content-type"]){const l=this.mixin.resolveRestContentType(this.getDefaultContentType(),a);l&&(r.headers["content-type"]=l)}return r.body==null&&r.headers["content-type"]===this.getDefaultContentType()&&(r.body="{}"),r}async deserializeResponse(t,n,i){const r=await super.deserializeResponse(t,n,i),a=Mr.of(t.output);for(const[l,c]of a.structIterator())c.getMemberTraits().httpPayload&&!(l in r)&&(r[l]=null);return r}async handleError(t,n,i,r,a){const l=VMe(i,r)??"Unknown",{errorSchema:c,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(l,this.options.defaultNamespace,i,r,a),s=Mr.of(c),u=r.message??r.Message??"Unknown",d=Ua.for(c[1]).getErrorCtor(c)??Error,p=new d(u);await this.deserializeHttpMessage(c,n,i,r);const f={};for(const[h,m]of s.structIterator()){const g=m.getMergedTraits().jsonName??h;f[h]=this.codec.createDeserializer().readObject(m,r[g])}throw this.mixin.decorateServiceException(Object.assign(p,o,{$fault:s.getMergedTraits().error,message:u},f),r)}getDefaultContentType(){return"application/json"}}const YMe=/\d{12}\.ddb/;async function eNe(e,t,n){if(n.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor"&&Bo(e,"PROTOCOL_RPC_V2_CBOR","M"),typeof t.retryStrategy=="function"){const a=await t.retryStrategy();typeof a.acquireInitialRetryToken=="function"?a.constructor?.name?.includes("Adaptive")?Bo(e,"RETRY_MODE_ADAPTIVE","F"):Bo(e,"RETRY_MODE_STANDARD","E"):Bo(e,"RETRY_MODE_LEGACY","D")}if(typeof t.accountIdEndpointMode=="function"){const a=e.endpointV2;switch(String(a?.url?.hostname).match(YMe)&&Bo(e,"ACCOUNT_ID_ENDPOINT","O"),await t.accountIdEndpointMode?.()){case"disabled":Bo(e,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":Bo(e,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":Bo(e,"ACCOUNT_ID_MODE_REQUIRED","R");break}}const r=e.__smithy_context?.selectedHttpAuthScheme?.identity;if(r?.$source){const a=r;a.accountId&&Bo(e,"RESOLVED_ACCOUNT_ID","T");for(const[l,c]of Object.entries(a.$source??{}))Bo(e,l,c)}}const RF="user-agent",Y6="x-amz-user-agent",OF=" ",eA="/",tNe=/[^!$%&'*+\-.^_`|~\w]/g,nNe=/[^!$%&'*+\-.^_`|~\w#]/g,IF="-",rNe=1024;function iNe(e){let t="";for(const n in e){const i=e[n];if(t.length+i.length+1<=rNe){t.length?t+=","+i:t+=i;continue}break}return t}const aNe=e=>(t,n)=>async i=>{const{request:r}=i;if(!Ea.isInstance(r))return t(i);const{headers:a}=r,l=n?.userAgent?.map(Fx)||[],c=(await e.defaultUserAgentProvider()).map(Fx);await eNe(n,e,i);const o=n;c.push(`m/${iNe(Object.assign({},n.__smithy_context?.features,o.__aws_sdk_context?.features))}`);const s=e?.customUserAgent?.map(Fx)||[],u=await e.userAgentAppId();u&&c.push(Fx(["app",`${u}`]));const d=[].concat([...c,...l,...s]).join(OF),p=[...c.filter(f=>f.startsWith("aws-sdk-")),...s].join(OF);return e.runtime!=="browser"?(p&&(a[Y6]=a[Y6]?`${a[RF]} ${p}`:p),a[RF]=d):a[Y6]=d,t({...i,request:r})},Fx=e=>{const t=e[0].split(eA).map(l=>l.replace(tNe,IF)).join(eA),n=e[1]?.replace(nNe,IF),i=t.indexOf(eA),r=t.substring(0,i);let a=t.substring(i+1);return r==="api"&&(a=a.toLowerCase()),[r,a,n].filter(l=>l&&l.length>0).reduce((l,c,o)=>{switch(o){case 0:return c;case 1:return`${l}/${c}`;default:return`${l}#${c}`}},"")},sNe={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},oNe=e=>({applyToStack:t=>{t.add(aNe(e),sNe)}});function lNe(e){const{port:t,query:n}=e;let{protocol:i,path:r,hostname:a}=e;i&&i.slice(-1)!==":"&&(i+=":"),t&&(a+=`:${t}`),r&&r.charAt(0)!=="/"&&(r=`/${r}`);let l=n?Zle(n):"";l&&l[0]!=="?"&&(l=`?${l}`);let c="";if(e.username!=null||e.password!=null){const s=e.username??"",u=e.password??"";c=`${s}:${u}@`}let o="";return e.fragment&&(o=`#${e.fragment}`),`${i}//${c}${a}${r}${l}${o}`}var aO=function(e,t){return aO=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(n[r]=i[r])},aO(e,t)};function Oce(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");aO(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var QT=function(){return QT=Object.assign||function(t){for(var n,i=1,r=arguments.length;i<r;i++){n=arguments[i];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},QT.apply(this,arguments)};function Ice(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]]);return n}function Pce(e,t,n,i){var r=arguments.length,a=r<3?t:i===null?i=Object.getOwnPropertyDescriptor(t,n):i,l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(e,t,n,i);else for(var c=e.length-1;c>=0;c--)(l=e[c])&&(a=(r<3?l(a):r>3?l(t,n,a):l(t,n))||a);return r>3&&a&&Object.defineProperty(t,n,a),a}function Mce(e,t){return function(n,i){t(n,i,e)}}function Nce(e,t,n,i,r,a){function l(y){if(y!==void 0&&typeof y!="function")throw new TypeError("Function expected");return y}for(var c=i.kind,o=c==="getter"?"get":c==="setter"?"set":"value",s=!t&&e?i.static?e:e.prototype:null,u=t||(s?Object.getOwnPropertyDescriptor(s,i.name):{}),d,p=!1,f=n.length-1;f>=0;f--){var h={};for(var m in i)h[m]=m==="access"?{}:i[m];for(var m in i.access)h.access[m]=i.access[m];h.addInitializer=function(y){if(p)throw new TypeError("Cannot add initializers after decoration has completed");a.push(l(y||null))};var g=(0,n[f])(c==="accessor"?{get:u.get,set:u.set}:u[o],h);if(c==="accessor"){if(g===void 0)continue;if(g===null||typeof g!="object")throw new TypeError("Object expected");(d=l(g.get))&&(u.get=d),(d=l(g.set))&&(u.set=d),(d=l(g.init))&&r.unshift(d)}else(d=l(g))&&(c==="field"?r.unshift(d):u[o]=d)}s&&Object.defineProperty(s,i.name,u),p=!0}function $ce(e,t,n){for(var i=arguments.length>2,r=0;r<t.length;r++)n=i?t[r].call(e,n):t[r].call(e);return i?n:void 0}function Dce(e){return typeof e=="symbol"?e:"".concat(e)}function jce(e,t,n){return typeof t=="symbol"&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:n?"".concat(n," ",t):t})}function Lce(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}function T8(e,t,n,i){function r(a){return a instanceof n?a:new n(function(l){l(a)})}return new(n||(n=Promise))(function(a,l){function c(u){try{s(i.next(u))}catch(d){l(d)}}function o(u){try{s(i.throw(u))}catch(d){l(d)}}function s(u){u.done?a(u.value):r(u.value).then(c,o)}s((i=i.apply(e,t||[])).next())})}function E8(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,r,a,l=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return l.next=c(0),l.throw=c(1),l.return=c(2),typeof Symbol=="function"&&(l[Symbol.iterator]=function(){return this}),l;function c(s){return function(u){return o([s,u])}}function o(s){if(i)throw new TypeError("Generator is already executing.");for(;l&&(l=0,s[0]&&(n=0)),n;)try{if(i=1,r&&(a=s[0]&2?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return n.label++,{value:s[1],done:!1};case 5:n.label++,r=s[1],s=[0];continue;case 7:s=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>0&&a[a.length-1])&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){n.label=s[1];break}if(s[0]===6&&n.label<a[1]){n.label=a[1],a=s;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(s);break}a[2]&&n.ops.pop(),n.trys.pop();continue}s=t.call(e,n)}catch(u){s=[6,u],r=0}finally{i=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}var SE=Object.create?(function(e,t,n,i){i===void 0&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}):(function(e,t,n,i){i===void 0&&(i=n),e[i]=t[n]});function Uce(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&SE(t,e,n)}function q_(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function k8(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,a=[],l;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(c){l={error:c}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(l)throw l.error}}return a}function Fce(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(k8(arguments[t]));return e}function qce(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var i=Array(e),r=0,t=0;t<n;t++)for(var a=arguments[t],l=0,c=a.length;l<c;l++,r++)i[r]=a[l];return i}function Bce(e,t,n){if(n||arguments.length===2)for(var i=0,r=t.length,a;i<r;i++)(a||!(i in t))&&(a||(a=Array.prototype.slice.call(t,0,i)),a[i]=t[i]);return e.concat(a||Array.prototype.slice.call(t))}function Ob(e){return this instanceof Ob?(this.v=e,this):new Ob(e)}function Wce(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(e,t||[]),r,a=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",l),r[Symbol.asyncIterator]=function(){return this},r;function l(f){return function(h){return Promise.resolve(h).then(f,d)}}function c(f,h){i[f]&&(r[f]=function(m){return new Promise(function(g,y){a.push([f,m,g,y])>1||o(f,m)})},h&&(r[f]=h(r[f])))}function o(f,h){try{s(i[f](h))}catch(m){p(a[0][3],m)}}function s(f){f.value instanceof Ob?Promise.resolve(f.value.v).then(u,d):p(a[0][2],f)}function u(f){o("next",f)}function d(f){o("throw",f)}function p(f,h){f(h),a.shift(),a.length&&o(a[0][0],a[0][1])}}function zce(e){var t,n;return t={},i("next"),i("throw",function(r){throw r}),i("return"),t[Symbol.iterator]=function(){return this},t;function i(r,a){t[r]=e[r]?function(l){return(n=!n)?{value:Ob(e[r](l)),done:!1}:a?a(l):l}:a}}function Gce(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof q_=="function"?q_(e):e[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(a){n[a]=e[a]&&function(l){return new Promise(function(c,o){l=e[a](l),r(c,o,l.done,l.value)})}}function r(a,l,c,o){Promise.resolve(o).then(function(s){a({value:s,done:c})},l)}}function Hce(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}var cNe=Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t},sO=function(e){return sO=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},sO(e)};function Vce(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=sO(e),i=0;i<n.length;i++)n[i]!=="default"&&SE(t,e,n[i]);return cNe(t,e),t}function Jce(e){return e&&e.__esModule?e:{default:e}}function Kce(e,t,n,i){if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?i:n==="a"?i.call(e):i?i.value:t.get(e)}function Zce(e,t,n,i,r){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?r.call(e,n):r?r.value=n:t.set(e,n),n}function Xce(e,t){if(t===null||typeof t!="object"&&typeof t!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof e=="function"?t===e:e.has(t)}function Qce(e,t,n){if(t!=null){if(typeof t!="object"&&typeof t!="function")throw new TypeError("Object expected.");var i,r;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=t[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=t[Symbol.dispose],n&&(r=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");r&&(i=function(){try{r.call(this)}catch(a){return Promise.reject(a)}}),e.stack.push({value:t,dispose:i,async:n})}else n&&e.stack.push({async:!0});return t}var uNe=typeof SuppressedError=="function"?SuppressedError:function(e,t,n){var i=new Error(n);return i.name="SuppressedError",i.error=e,i.suppressed=t,i};function Yce(e){function t(a){e.error=e.hasError?new uNe(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function r(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(r);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(r,function(l){return t(l),r()})}else i|=1}catch(l){t(l)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return r()}function eue(e,t){return typeof e=="string"&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(n,i,r,a,l){return i?t?".jsx":".js":r&&(!a||!l)?n:r+a+"."+l.toLowerCase()+"js"}):e}const dNe={__extends:Oce,__assign:QT,__rest:Ice,__decorate:Pce,__param:Mce,__esDecorate:Nce,__runInitializers:$ce,__propKey:Dce,__setFunctionName:jce,__metadata:Lce,__awaiter:T8,__generator:E8,__createBinding:SE,__exportStar:Uce,__values:q_,__read:k8,__spread:Fce,__spreadArrays:qce,__spreadArray:Bce,__await:Ob,__asyncGenerator:Wce,__asyncDelegator:zce,__asyncValues:Gce,__makeTemplateObject:Hce,__importStar:Vce,__importDefault:Jce,__classPrivateFieldGet:Kce,__classPrivateFieldSet:Zce,__classPrivateFieldIn:Xce,__addDisposableResource:Qce,__disposeResources:Yce,__rewriteRelativeImportExtension:eue},I3t=Object.freeze(Object.defineProperty({__proto__:null,__addDisposableResource:Qce,get __assign(){return QT},__asyncDelegator:zce,__asyncGenerator:Wce,__asyncValues:Gce,__await:Ob,__awaiter:T8,__classPrivateFieldGet:Kce,__classPrivateFieldIn:Xce,__classPrivateFieldSet:Zce,__createBinding:SE,__decorate:Pce,__disposeResources:Yce,__esDecorate:Nce,__exportStar:Uce,__extends:Oce,__generator:E8,__importDefault:Jce,__importStar:Vce,__makeTemplateObject:Hce,__metadata:Lce,__param:Mce,__propKey:Dce,__read:k8,__rest:Ice,__rewriteRelativeImportExtension:eue,__runInitializers:$ce,__setFunctionName:jce,__spread:Fce,__spreadArray:Bce,__spreadArrays:qce,__values:q_,default:dNe},Symbol.toStringTag,{value:"Module"})),pNe=e=>new TextEncoder().encode(e);var fNe=typeof Buffer<"u"&&Buffer.from?function(e){return Buffer.from(e,"utf8")}:pNe;function B_(e){return e instanceof Uint8Array?e:typeof e=="string"?fNe(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}function oO(e){return typeof e=="string"?e.length===0:e.byteLength===0}function hNe(e){if(!Uint32Array.from){for(var t=new Uint32Array(e.length),n=0;n<e.length;)t[n]=e[n],n+=1;return t}return Uint32Array.from(e)}var tue=(function(){function e(){this.checksum=4294967295}return e.prototype.update=function(t){var n,i;try{for(var r=q_(t),a=r.next();!a.done;a=r.next()){var l=a.value;this.checksum=this.checksum>>>8^gNe[(this.checksum^l)&255]}}catch(c){n={error:c}}finally{try{a&&!a.done&&(i=r.return)&&i.call(r)}finally{if(n)throw n.error}}return this},e.prototype.digest=function(){return(this.checksum^4294967295)>>>0},e})(),mNe=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117],gNe=hNe(mNe);class x_{bytes;constructor(t){if(this.bytes=t,t.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(t){if(t>9223372036854776e3||t<-9223372036854776e3)throw new Error(`${t} is too large (or, if negative, too small) to represent as an Int64`);const n=new Uint8Array(8);for(let i=7,r=Math.abs(Math.round(t));i>-1&&r>0;i--,r/=256)n[i]=r;return t<0&&PF(n),new x_(n)}valueOf(){const t=this.bytes.slice(0),n=t[0]&128;return n&&PF(t),parseInt(qa(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function PF(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,e[t]===0);t--);}class yNe{toUtf8;fromUtf8;constructor(t,n){this.toUtf8=t,this.fromUtf8=n}format(t){const n=[];for(const a of Object.keys(t)){const l=this.fromUtf8(a);n.push(Uint8Array.from([l.byteLength]),l,this.formatHeaderValue(t[a]))}const i=new Uint8Array(n.reduce((a,l)=>a+l.byteLength,0));let r=0;for(const a of n)i.set(a,r),r+=a.byteLength;return i}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?0:1]);case"byte":return Uint8Array.from([2,t.value]);case"short":const n=new DataView(new ArrayBuffer(3));return n.setUint8(0,3),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":const i=new DataView(new ArrayBuffer(5));return i.setUint8(0,4),i.setInt32(1,t.value,!1),new Uint8Array(i.buffer);case"long":const r=new Uint8Array(9);return r[0]=5,r.set(t.value.bytes,1),r;case"binary":const a=new DataView(new ArrayBuffer(3+t.value.byteLength));a.setUint8(0,6),a.setUint16(1,t.value.byteLength,!1);const l=new Uint8Array(a.buffer);return l.set(t.value,3),l;case"string":const c=this.fromUtf8(t.value),o=new DataView(new ArrayBuffer(3+c.byteLength));o.setUint8(0,7),o.setUint16(1,c.byteLength,!1);const s=new Uint8Array(o.buffer);return s.set(c,3),s;case"timestamp":const u=new Uint8Array(9);return u[0]=8,u.set(x_.fromNumber(t.value.valueOf()).bytes,1),u;case"uuid":if(!ENe.test(t.value))throw new Error(`Invalid UUID received: ${t.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(g8(t.value.replace(/\-/g,"")),1),d}}parse(t){const n={};let i=0;for(;i<t.byteLength;){const r=t.getUint8(i++),a=this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+i,r));switch(i+=r,t.getUint8(i++)){case 0:n[a]={type:NF,value:!0};break;case 1:n[a]={type:NF,value:!1};break;case 2:n[a]={type:vNe,value:t.getInt8(i++)};break;case 3:n[a]={type:bNe,value:t.getInt16(i,!1)},i+=2;break;case 4:n[a]={type:wNe,value:t.getInt32(i,!1)},i+=4;break;case 5:n[a]={type:_Ne,value:new x_(new Uint8Array(t.buffer,t.byteOffset+i,8))},i+=8;break;case 6:const l=t.getUint16(i,!1);i+=2,n[a]={type:xNe,value:new Uint8Array(t.buffer,t.byteOffset+i,l)},i+=l;break;case 7:const c=t.getUint16(i,!1);i+=2,n[a]={type:SNe,value:this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+i,c))},i+=c;break;case 8:n[a]={type:CNe,value:new Date(new x_(new Uint8Array(t.buffer,t.byteOffset+i,8)).valueOf())},i+=8;break;case 9:const o=new Uint8Array(t.buffer,t.byteOffset+i,16);i+=16,n[a]={type:TNe,value:`${qa(o.subarray(0,4))}-${qa(o.subarray(4,6))}-${qa(o.subarray(6,8))}-${qa(o.subarray(8,10))}-${qa(o.subarray(10))}`};break;default:throw new Error("Unrecognized header type tag")}}return n}}var MF;(function(e){e[e.boolTrue=0]="boolTrue",e[e.boolFalse=1]="boolFalse",e[e.byte=2]="byte",e[e.short=3]="short",e[e.integer=4]="integer",e[e.long=5]="long",e[e.byteArray=6]="byteArray",e[e.string=7]="string",e[e.timestamp=8]="timestamp",e[e.uuid=9]="uuid"})(MF||(MF={}));const NF="boolean",vNe="byte",bNe="short",wNe="integer",_Ne="long",xNe="binary",SNe="string",CNe="timestamp",TNe="uuid",ENe=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,nue=4,Xm=nue*2,ay=4,kNe=Xm+ay*2;function ANe({byteLength:e,byteOffset:t,buffer:n}){if(e<kNe)throw new Error("Provided message too short to accommodate event stream message overhead");const i=new DataView(n,t,e),r=i.getUint32(0,!1);if(e!==r)throw new Error("Reported message length does not match received message length");const a=i.getUint32(nue,!1),l=i.getUint32(Xm,!1),c=i.getUint32(e-ay,!1),o=new tue().update(new Uint8Array(n,t,Xm));if(l!==o.digest())throw new Error(`The prelude checksum specified in the message (${l}) does not match the calculated CRC32 checksum (${o.digest()})`);if(o.update(new Uint8Array(n,t+Xm,e-(Xm+ay))),c!==o.digest())throw new Error(`The message checksum (${o.digest()}) did not match the expected value of ${c}`);return{headers:new DataView(n,t+Xm+ay,a),body:new Uint8Array(n,t+Xm+ay+a,r-a-(Xm+ay+ay))}}class rue{headerMarshaller;messageBuffer;isEndOfStream;constructor(t,n){this.headerMarshaller=new yNe(t,n),this.messageBuffer=[],this.isEndOfStream=!1}feed(t){this.messageBuffer.push(this.decode(t))}endOfStream(){this.isEndOfStream=!0}getMessage(){const t=this.messageBuffer.pop(),n=this.isEndOfStream;return{getMessage(){return t},isEndOfStream(){return n}}}getAvailableMessages(){const t=this.messageBuffer;this.messageBuffer=[];const n=this.isEndOfStream;return{getMessages(){return t},isEndOfStream(){return n}}}encode({headers:t,body:n}){const i=this.headerMarshaller.format(t),r=i.byteLength+n.byteLength+16,a=new Uint8Array(r),l=new DataView(a.buffer,a.byteOffset,a.byteLength),c=new tue;return l.setUint32(0,r,!1),l.setUint32(4,i.byteLength,!1),l.setUint32(8,c.update(a.subarray(0,8)).digest(),!1),a.set(i,12),a.set(n,i.byteLength+12),l.setUint32(r-4,c.update(a.subarray(8,r-4)).digest(),!1),a}decode(t){const{headers:n,body:i}=ANe(t);return{headers:this.headerMarshaller.parse(n),body:i}}formatHeaders(t){return this.headerMarshaller.format(t)}}class RNe{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const t of this.options.inputStream)yield this.options.decoder.decode(t)}}class ONe{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const t of this.options.messageStream)yield this.options.encoder.encode(t);this.options.includeEndFrame&&(yield new Uint8Array(0))}}class INe{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const t of this.options.messageStream){const n=await this.options.deserializer(t);n!==void 0&&(yield n)}}}class PNe{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const t of this.options.inputStream)yield this.options.serializer(t)}}function MNe(e){let t=0,n=0,i=null,r=null;const a=c=>{if(typeof c!="number")throw new Error("Attempted to allocate an event message where size was not a number: "+c);t=c,n=4,i=new Uint8Array(c),new DataView(i.buffer).setUint32(0,c,!1)},l=async function*(){const c=e[Symbol.asyncIterator]();for(;;){const{value:o,done:s}=await c.next();if(s){if(t)if(t===n)yield i;else throw new Error("Truncated event message received.");else return;return}const u=o.length;let d=0;for(;d<u;){if(!i){const f=u-d;r||(r=new Uint8Array(4));const h=Math.min(4-n,f);if(r.set(o.slice(d,d+h),n),n+=h,d+=h,n<4)break;a(new DataView(r.buffer).getUint32(0,!1)),r=null}const p=Math.min(t-n,u-d);i.set(o.slice(d,d+p),n),n+=p,d+=p,t&&t===n&&(yield i,i=null,t=0,n=0)}}};return{[Symbol.asyncIterator]:l}}function NNe(e,t){return async function(n){const{value:i}=n.headers[":message-type"];if(i==="error"){const r=new Error(n.headers[":error-message"].value||"UnknownError");throw r.name=n.headers[":error-code"].value,r}else if(i==="exception"){const r=n.headers[":exception-type"].value,a={[r]:n},l=await e(a);if(l.$unknown){const c=new Error(t(n.body));throw c.name=r,c}throw l[r]}else if(i==="event"){const r={[n.headers[":event-type"].value]:n},a=await e(r);return a.$unknown?void 0:a}else throw Error(`Unrecognizable event type: ${n.headers[":event-type"].value}`)}}let $Ne=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:t,utf8Decoder:n}){this.eventStreamCodec=new rue(t,n),this.utfEncoder=t}deserialize(t,n){const i=MNe(t);return new INe({messageStream:new RNe({inputStream:i,decoder:this.eventStreamCodec}),deserializer:NNe(n,this.utfEncoder)})}serialize(t,n){return new ONe({messageStream:new PNe({inputStream:t,serializer:n}),encoder:this.eventStreamCodec,includeEndFrame:!0})}};const iue=e=>({[Symbol.asyncIterator]:async function*(){const t=e.getReader();try{for(;;){const{done:n,value:i}=await t.read();if(n)return;yield i}}finally{t.releaseLock()}}}),aue=e=>{const t=e[Symbol.asyncIterator]();return new ReadableStream({async pull(n){const{done:i,value:r}=await t.next();if(i)return n.close();n.enqueue(r)}})};class DNe{universalMarshaller;constructor({utf8Encoder:t,utf8Decoder:n}){this.universalMarshaller=new $Ne({utf8Decoder:n,utf8Encoder:t})}deserialize(t,n){const i=jNe(t)?iue(t):t;return this.universalMarshaller.deserialize(i,n)}serialize(t,n){const i=this.universalMarshaller.serialize(t,n);return typeof ReadableStream=="function"?aue(i):i}}const jNe=e=>typeof ReadableStream=="function"&&e instanceof ReadableStream,LNe=e=>new DNe(e),sue=e=>e.protocol==="ws:"||e.protocol==="wss:",UNe=3e3;class A8{metadata={handlerProtocol:"websocket/h1.1"};config={};configPromise;httpHandler;sockets={};static create(t,n=new L_){return typeof t?.handle=="function"?t:new A8(t,n)}constructor(t,n=new L_){this.httpHandler=n;const i=r=>(this.config={...r??{}},this.config);typeof t=="function"?(this.config={},this.configPromise=t().then(r=>i(r))):this.configPromise=Promise.resolve(i(t))}destroy(){for(const[t,n]of Object.entries(this.sockets)){for(const i of n)i.close(1e3,"Socket closed through destroy() call");delete this.sockets[t]}}async handle(t){this.config=await this.configPromise;const{logger:n}=this.config;if(!sue(t))return n?.debug?.(`@aws-sdk - ws fetching ${t.protocol}${t.hostname}${t.path}`),this.httpHandler.handle(t);const i=lNe(t);n?.debug?.(`@aws-sdk - ws connecting ${i.split("?")[0]}`);const r=new WebSocket(i);this.sockets[i]||(this.sockets[i]=[]),this.sockets[i].push(r),r.binaryType="arraybuffer";const{connectionTimeout:a=UNe}=this.config;await this.waitForReady(r,a);const{body:l}=t,c=FNe(l),o=this.connect(r,c),s=qNe(o);return{response:new jy({statusCode:200,body:s})}}updateHttpClientConfig(t,n){this.configPromise=this.configPromise.then(i=>(i[t]=n,i))}httpHandlerConfigs(){return this.config??{}}removeNotUsableSockets(t){this.sockets[t]=(this.sockets[t]??[]).filter(n=>![WebSocket.CLOSING,WebSocket.CLOSED].includes(n.readyState))}waitForReady(t,n){return new Promise((i,r)=>{const a=setTimeout(()=>{this.removeNotUsableSockets(t.url),r({$metadata:{httpStatusCode:500,websocketSynthetic500Error:!0}})},n);t.onopen=()=>{clearTimeout(a),i()}})}connect(t,n){const i=[];let r=null,a=null;const l=s=>{r?(s.error?a(s.error):r({done:s.done,value:s.value}),r=null,a=null):i.push(s)};t.onmessage=s=>{const{data:u}=s;l(typeof u=="string"?{done:!1,value:Ly(u)}:{done:!1,value:new Uint8Array(u)})},t.onerror=s=>{t.close(),l({done:!0,error:s})},t.onclose=()=>{this.removeNotUsableSockets(t.url),l({done:!0})};const c={[Symbol.asyncIterator]:()=>({async next(){if(i.length>0){const s=i.shift();if(s.error)throw s.error;return{done:s.done,value:s.value}}return new Promise((s,u)=>{r=s,a=u})}})};return(async()=>{try{for await(const s of n){if(t.readyState>=WebSocket.CLOSING)break;t.send(s)}}catch(s){l({done:!0,error:s})}finally{t.close(1e3)}})(),c}}const FNe=e=>e[Symbol.asyncIterator]?e:BNe(e)?iue(e):{[Symbol.asyncIterator]:async function*(){yield e}},qNe=e=>typeof ReadableStream=="function"?aue(e):e,BNe=e=>typeof ReadableStream=="function"&&e instanceof ReadableStream;class WNe{signer;constructor(t){this.signer=t.signer}presign(t,n={}){return this.signer.presign(t,n)}async sign(t,n){return Ea.isInstance(t)&&sue(t)?{...await this.signer.presign({...t,body:""},{...n,expiresIn:60,unsignableHeaders:new Set(Object.keys(t.headers).filter(r=>r!=="host"))}),body:t.body}:this.signer.sign(t,n)}signMessage(t,n){return this.signer.signMessage(t,n)}}const zNe=e=>{const{signer:t}=e;return Object.assign(e,{signer:async n=>{const i=await t(n);if(GNe(i))return new WNe({signer:i});throw new Error("Expected WebsocketSignatureV4 signer, please check the client constructor.")}})},GNe=e=>!!e;class HNe extends TransformStream{constructor(t,n,i,r){let a=t;super({start(){},async transform(l,c){try{const o=new Date(Date.now()+await r()),s={":date":{type:"timestamp",value:o}},u=await n.sign({message:{body:l,headers:s},priorSignature:a},{signingDate:o});a=u.signature;const d=i.encode({headers:{...s,":chunk-signature":{type:"binary",value:g8(u.signature)}},body:l});c.enqueue(d)}catch(o){c.error(o)}}})}}class VNe{messageSigner;eventStreamCodec;systemClockOffsetProvider;constructor(t){this.messageSigner=t.messageSigner,this.eventStreamCodec=new rue(t.utf8Encoder,t.utf8Decoder),this.systemClockOffsetProvider=async()=>t.systemClockOffset??0}async handle(t,n,i={}){const r=n.request,{body:a,headers:l,query:c}=r;if(!(a instanceof ReadableStream))throw new Error("Eventstream payload must be a ReadableStream.");const o=new TransformStream;r.body=o.readable;let u=((l?.authorization??"").match(/Signature=(\w+)$/)??[])[1]??(c&&c["X-Amz-Signature"])??"";i.__staticSignature&&(u="");const d=new HNe(u,await this.messageSigner(),this.eventStreamCodec,this.systemClockOffsetProvider);a.pipeThrough(d).pipeThrough(o);let p;try{p=await t(n)}catch(f){const h=a.cancel?.();throw h instanceof Promise&&h.catch(()=>{}),f}return p}}const JNe=e=>new VNe(e),KNe=!1,ZNe=!1,$F=new Set,XNe=(e,t=_E)=>{if(!$F.has(e)&&!t(e))if(e==="*")console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.');else throw new Error(`Region not accepted: region="${e}" is not a valid hostname component.`);else $F.add(e)},oue=e=>typeof e=="string"&&(e.startsWith("fips-")||e.endsWith("-fips")),QNe=e=>oue(e)?["fips-aws-global","aws-fips"].includes(e)?"us-east-1":e.replace(/fips-(dkr-|prod-)?|-fips/,""):e,YNe=e=>{const{region:t,useFipsEndpoint:n}=e;if(!t)throw new Error("Region is missing");return Object.assign(e,{region:async()=>{const i=typeof t=="function"?await t():t,r=QNe(i);return XNe(r),r},useFipsEndpoint:async()=>{const i=typeof t=="string"?t:await t();return oue(i)?!0:typeof n!="function"?Promise.resolve(!!n):n()}})},e$e=e=>Object.assign(e,{eventStreamMarshaller:e.eventStreamSerdeProvider(e)}),DF="content-length";function t$e(e){return t=>async n=>{const i=n.request;if(Ea.isInstance(i)){const{body:r,headers:a}=i;if(r&&Object.keys(a).map(l=>l.toLowerCase()).indexOf(DF)===-1)try{const l=e(r);i.headers={...i.headers,[DF]:String(l)}}catch{}}return t({...n,request:i})}}const n$e={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},r$e=e=>({applyToStack:t=>{t.add(t$e(e.bodyLengthChecker),n$e)}}),i$e=async e=>{const t=e?.Bucket||"";if(typeof e.Bucket=="string"&&(e.Bucket=t.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),c$e(t)){if(e.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!l$e(t)||t.indexOf(".")!==-1&&!String(e.Endpoint).startsWith("http:")||t.toLowerCase()!==t||t.length<3)&&(e.ForcePathStyle=!0);return e.DisableMultiRegionAccessPoints&&(e.disableMultiRegionAccessPoints=!0,e.DisableMRAP=!0),e},a$e=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,s$e=/(\d+\.){3}\d+/,o$e=/\.\./,l$e=e=>a$e.test(e)&&!s$e.test(e)&&!o$e.test(e),c$e=e=>{const[t,n,i,,,r]=e.split(":"),a=t==="arn"&&e.split(":").length>=6,l=!!(a&&n&&i&&r);if(a&&!l)throw new Error(`Invalid ARN: ${e} was an invalid ARN.`);return l},u$e=(e,t,n,i=!1)=>{const r=async()=>{let a;return i?a=n.clientContextParams?.[e]??n[e]??n[t]:a=n[e]??n[t],typeof a=="function"?a():a};return e==="credentialScope"||t==="CredentialScope"?async()=>{const a=typeof n.credentials=="function"?await n.credentials():n.credentials;return a?.credentialScope??a?.CredentialScope}:e==="accountId"||t==="AccountId"?async()=>{const a=typeof n.credentials=="function"?await n.credentials():n.credentials;return a?.accountId??a?.AccountId}:e==="endpoint"||t==="endpoint"?async()=>{if(n.isCustomEndpoint===!1)return;const a=await r();if(a&&typeof a=="object"){if("url"in a)return a.url.href;if("hostname"in a){const{protocol:l,hostname:c,port:o,path:s}=a;return`${l}//${c}${o?":"+o:""}${s}`}}return a}:r},lue=async e=>{},cue=e=>typeof e=="object"?"url"in e?ZT(e.url):e:ZT(e),d$e=async(e,t,n,i)=>{if(!n.isCustomEndpoint){let l;n.serviceConfiguredEndpoint?l=await n.serviceConfiguredEndpoint():l=await lue(n.serviceId),l&&(n.endpoint=()=>Promise.resolve(cue(l)),n.isCustomEndpoint=!0)}const r=await p$e(e,t,n);if(typeof n.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");return n.endpointProvider(r,i)},p$e=async(e,t,n)=>{const i={},r=t?.getEndpointParameterInstructions?.()||{};for(const[a,l]of Object.entries(r))switch(l.type){case"staticContextParams":i[a]=l.value;break;case"contextParams":i[a]=e[l.name];break;case"clientContextParams":case"builtInParams":i[a]=await u$e(l.name,a,n,l.type!=="builtInParams")();break;case"operationContextParams":i[a]=l.get(e);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(l))}return Object.keys(r).length===0&&Object.assign(i,n),String(n.serviceId).toLowerCase()==="s3"&&await i$e(i),i},f$e=({config:e,instructions:t})=>(n,i)=>async r=>{e.isCustomEndpoint&&y7e(i,"ENDPOINT_OVERRIDE","N");const a=await d$e(r.input,{getEndpointParameterInstructions(){return t}},{...e},i);i.endpointV2=a,i.authSchemes=a.properties?.authSchemes;const l=i.authSchemes?.[0];if(l){i.signing_region=l.signingRegion,i.signing_service=l.signingName;const o=Jb(i)?.selectedHttpAuthScheme?.httpAuthOption;o&&(o.signingProperties=Object.assign(o.signingProperties||{},{signing_region:l.signingRegion,signingRegion:l.signingRegion,signing_service:l.signingName,signingName:l.signingName,signingRegionSet:l.signingRegionSet},l.properties))}return n({...r})},h$e={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:u8e.name},m$e=(e,t)=>({applyToStack:n=>{n.addRelativeTo(f$e({config:e,instructions:t}),h$e)}}),g$e=e=>{const t=e.tls??!0,{endpoint:n,useDualstackEndpoint:i,useFipsEndpoint:r}=e,a=n!=null?async()=>cue(await ym(n)()):void 0,c=Object.assign(e,{endpoint:a,tls:t,isCustomEndpoint:!!n,useDualstackEndpoint:ym(i??!1),useFipsEndpoint:ym(r??!1)});let o;return c.serviceConfiguredEndpoint=async()=>(e.serviceId&&!o&&(o=lue(e.serviceId)),o),c};var Ib;(function(e){e.STANDARD="standard",e.ADAPTIVE="adaptive"})(Ib||(Ib={}));const YT=3,y$e=Ib.STANDARD,v$e=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],b$e=["TimeoutError","RequestTimeout","RequestTimeoutException"],w$e=[500,502,503,504],_$e=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],x$e=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND"],S$e=e=>e?.$retryable!==void 0,C$e=e=>e.$metadata?.clockSkewCorrected,T$e=e=>{const t=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);return e&&e instanceof TypeError?t.has(e.message):!1},uue=e=>e.$metadata?.httpStatusCode===429||v$e.includes(e.name)||e.$retryable?.throttling==!0,R8=(e,t=0)=>S$e(e)||C$e(e)||b$e.includes(e.name)||_$e.includes(e?.code||"")||x$e.includes(e?.code||"")||w$e.includes(e.$metadata?.httpStatusCode||0)||T$e(e)||e.cause!==void 0&&t<=10&&R8(e.cause,t+1),E$e=e=>{if(e.$metadata?.httpStatusCode!==void 0){const t=e.$metadata.httpStatusCode;return 500<=t&&t<=599&&!R8(e)}return!1};class O8{static setTimeoutFn=setTimeout;beta;minCapacity;minFillRate;scaleConstant;smooth;currentCapacity=0;enabled=!1;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(t){this.beta=t?.beta??.7,this.minCapacity=t?.minCapacity??1,this.minFillRate=t?.minFillRate??.5,this.scaleConstant=t?.scaleConstant??.4,this.smooth=t?.smooth??.8;const n=this.getCurrentTimeInSeconds();this.lastThrottleTime=n,this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}getCurrentTimeInSeconds(){return Date.now()/1e3}async getSendToken(){return this.acquireTokenBucket(1)}async acquireTokenBucket(t){if(this.enabled){if(this.refillTokenBucket(),t>this.currentCapacity){const n=(t-this.currentCapacity)/this.fillRate*1e3;await new Promise(i=>O8.setTimeoutFn(i,n))}this.currentCapacity=this.currentCapacity-t}}refillTokenBucket(){const t=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=t;return}const n=(t-this.lastTimestamp)*this.fillRate;this.currentCapacity=Math.min(this.maxCapacity,this.currentCapacity+n),this.lastTimestamp=t}updateClientSendingRate(t){let n;if(this.updateMeasuredRate(),uue(t)){const r=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=r,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),n=this.cubicThrottle(r),this.enableTokenBucket()}else this.calculateTimeWindow(),n=this.cubicSuccess(this.getCurrentTimeInSeconds());const i=Math.min(n,2*this.measuredTxRate);this.updateTokenBucketRate(i)}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(t){return this.getPrecise(t*this.beta)}cubicSuccess(t){return this.getPrecise(this.scaleConstant*Math.pow(t-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(t){this.refillTokenBucket(),this.fillRate=Math.max(t,this.minFillRate),this.maxCapacity=Math.max(t,this.minCapacity),this.currentCapacity=Math.min(this.currentCapacity,this.maxCapacity)}updateMeasuredRate(){const t=this.getCurrentTimeInSeconds(),n=Math.floor(t*2)/2;if(this.requestCount++,n>this.lastTxRateBucket){const i=this.requestCount/(n-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(i*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=n}}getPrecise(t){return parseFloat(t.toFixed(8))}}const lO=100,due=20*1e3,k$e=500,jF=500,A$e=5,R$e=10,O$e=1,I$e="amz-sdk-invocation-id",P$e="amz-sdk-request",M$e=()=>{let e=lO;return{computeNextBackoffDelay:i=>Math.floor(Math.min(due,Math.random()*2**i*e)),setDelayBase:i=>{e=i}}},LF=({retryDelay:e,retryCount:t,retryCost:n})=>({getRetryCount:()=>t,getRetryDelay:()=>Math.min(due,e),getRetryCost:()=>n});class pue{maxAttempts;mode=Ib.STANDARD;capacity=jF;retryBackoffStrategy=M$e();maxAttemptsProvider;constructor(t){this.maxAttempts=t,this.maxAttemptsProvider=typeof t=="function"?t:async()=>t}async acquireInitialRetryToken(t){return LF({retryDelay:lO,retryCount:0})}async refreshRetryTokenForRetry(t,n){const i=await this.getMaxAttempts();if(this.shouldRetry(t,n,i)){const r=n.errorType;this.retryBackoffStrategy.setDelayBase(r==="THROTTLING"?k$e:lO);const a=this.retryBackoffStrategy.computeNextBackoffDelay(t.getRetryCount()),l=n.retryAfterHint?Math.max(n.retryAfterHint.getTime()-Date.now()||0,a):a,c=this.getCapacityCost(r);return this.capacity-=c,LF({retryDelay:l,retryCount:t.getRetryCount()+1,retryCost:c})}throw new Error("No retry token available")}recordSuccess(t){this.capacity=Math.max(jF,this.capacity+(t.getRetryCost()??O$e))}getCapacity(){return this.capacity}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch{return console.warn(`Max attempts provider could not resolve. Using default of ${YT}`),YT}}shouldRetry(t,n,i){return t.getRetryCount()+1<i&&this.capacity>=this.getCapacityCost(n.errorType)&&this.isRetryableError(n.errorType)}getCapacityCost(t){return t==="TRANSIENT"?R$e:A$e}isRetryableError(t){return t==="THROTTLING"||t==="TRANSIENT"}}class N$e{maxAttemptsProvider;rateLimiter;standardRetryStrategy;mode=Ib.ADAPTIVE;constructor(t,n){this.maxAttemptsProvider=t;const{rateLimiter:i}=n??{};this.rateLimiter=i??new O8,this.standardRetryStrategy=new pue(t)}async acquireInitialRetryToken(t){return await this.rateLimiter.getSendToken(),this.standardRetryStrategy.acquireInitialRetryToken(t)}async refreshRetryTokenForRetry(t,n){return this.rateLimiter.updateClientSendingRate(n),this.standardRetryStrategy.refreshRetryTokenForRetry(t,n)}recordSuccess(t){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(t)}}const $$e=e=>e instanceof Error?e:e instanceof Object?Object.assign(new Error,e):typeof e=="string"?new Error(e):new Error(`AWS SDK error wrapper for ${e}`),D$e=e=>{const{retryStrategy:t,retryMode:n,maxAttempts:i}=e,r=ym(i??YT);return Object.assign(e,{maxAttempts:r,retryStrategy:async()=>t||(await ym(n)()===Ib.ADAPTIVE?new N$e(r):new pue(r))})},j$e=e=>e?.body instanceof ReadableStream,L$e=e=>(t,n)=>async i=>{let r=await e.retryStrategy();const a=await e.maxAttempts();if(U$e(r)){r=r;let l=await r.acquireInitialRetryToken(n.partition_id),c=new Error,o=0,s=0;const{request:u}=i,d=Ea.isInstance(u);for(d&&(u.headers[I$e]=v8());;)try{d&&(u.headers[P$e]=`attempt=${o+1}; max=${a}`);const{response:p,output:f}=await t(i);return r.recordSuccess(l),f.$metadata.attempts=o+1,f.$metadata.totalRetryDelay=s,{response:p,output:f}}catch(p){const f=F$e(p);if(c=$$e(p),d&&j$e(u))throw(n.logger instanceof Rce?console:n.logger)?.warn("An error was encountered in a non-retryable streaming request."),c;try{l=await r.refreshRetryTokenForRetry(l,f)}catch{throw c.$metadata||(c.$metadata={}),c.$metadata.attempts=o+1,c.$metadata.totalRetryDelay=s,c}o=l.getRetryCount();const h=l.getRetryDelay();s+=h,await new Promise(m=>setTimeout(m,h))}}else return r=r,r?.mode&&(n.userAgent=[...n.userAgent||[],["cfg/retry-mode",r.mode]]),r.retry(t,i)},U$e=e=>typeof e.acquireInitialRetryToken<"u"&&typeof e.refreshRetryTokenForRetry<"u"&&typeof e.recordSuccess<"u",F$e=e=>{const t={error:e,errorType:q$e(e)},n=z$e(e.$response);return n&&(t.retryAfterHint=n),t},q$e=e=>uue(e)?"THROTTLING":R8(e)?"TRANSIENT":E$e(e)?"SERVER_ERROR":"CLIENT_ERROR",B$e={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0},W$e=e=>({applyToStack:t=>{t.add(L$e(e),B$e)}}),z$e=e=>{if(!jy.isInstance(e))return;const t=Object.keys(e.headers).find(a=>a.toLowerCase()==="retry-after");if(!t)return;const n=e.headers[t],i=Number(n);return Number.isNaN(i)?new Date(n):new Date(i*1e3)},G$e=async(e,t,n)=>({operation:Jb(t).operation,region:await ym(e.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function H$e(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"bedrock",region:e.region},propertiesExtractor:(t,n)=>({signingProperties:{config:t,context:n}})}}function V$e(e){return{schemeId:"smithy.api#httpBearerAuth",propertiesExtractor:({profile:t,filepath:n,configFilepath:i,ignoreCache:r},a)=>({identityProperties:{profile:t,filepath:n,configFilepath:i,ignoreCache:r}})}}const J$e=e=>{const t=[];switch(e.operation){default:t.push(H$e(e)),t.push(V$e())}return t},K$e=e=>{const t=sce(e.token,ace,x8),n=RMe(e);return Object.assign(n,{authSchemePreference:ym(e.authSchemePreference??[]),token:t})},Z$e=e=>Object.assign(e,{useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,defaultSigningName:"bedrock"}),X$e={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},Q$e="3.1000.0",Y$e={version:Q$e};var fue={name:"SHA-256"},UF={name:"HMAC",hash:fue},eDe=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85]);const tDe={};function DC(){return typeof window<"u"?window:typeof self<"u"?self:tDe}var nDe=(function(){function e(t){this.toHash=new Uint8Array(0),this.secret=t,this.reset()}return e.prototype.update=function(t){if(!oO(t)){var n=B_(t),i=new Uint8Array(this.toHash.byteLength+n.byteLength);i.set(this.toHash,0),i.set(n,this.toHash.byteLength),this.toHash=i}},e.prototype.digest=function(){var t=this;return this.key?this.key.then(function(n){return DC().crypto.subtle.sign(UF,n,t.toHash).then(function(i){return new Uint8Array(i)})}):oO(this.toHash)?Promise.resolve(eDe):Promise.resolve().then(function(){return DC().crypto.subtle.digest(fue,t.toHash)}).then(function(n){return Promise.resolve(new Uint8Array(n))})},e.prototype.reset=function(){var t=this;this.toHash=new Uint8Array(0),this.secret&&this.secret!==void 0&&(this.key=new Promise(function(n,i){DC().crypto.subtle.importKey("raw",B_(t.secret),UF,!1,["sign"]).then(n,i)}),this.key.catch(function(){}))},e})(),Ms=64,rDe=32,iDe=new Uint32Array([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]),aDe=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],sDe=Math.pow(2,53)-1,jC=(function(){function e(){this.state=Int32Array.from(aDe),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return e.prototype.update=function(t){if(this.finished)throw new Error("Attempted to update an already finished hash.");var n=0,i=t.byteLength;if(this.bytesHashed+=i,this.bytesHashed*8>sDe)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;i>0;)this.buffer[this.bufferLength++]=t[n++],i--,this.bufferLength===Ms&&(this.hashBuffer(),this.bufferLength=0)},e.prototype.digest=function(){if(!this.finished){var t=this.bytesHashed*8,n=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),i=this.bufferLength;if(n.setUint8(this.bufferLength++,128),i%Ms>=Ms-8){for(var r=this.bufferLength;r<Ms;r++)n.setUint8(r,0);this.hashBuffer(),this.bufferLength=0}for(var r=this.bufferLength;r<Ms-8;r++)n.setUint8(r,0);n.setUint32(Ms-8,Math.floor(t/4294967296),!0),n.setUint32(Ms-4,t),this.hashBuffer(),this.finished=!0}for(var a=new Uint8Array(rDe),r=0;r<8;r++)a[r*4]=this.state[r]>>>24&255,a[r*4+1]=this.state[r]>>>16&255,a[r*4+2]=this.state[r]>>>8&255,a[r*4+3]=this.state[r]>>>0&255;return a},e.prototype.hashBuffer=function(){for(var t=this,n=t.buffer,i=t.state,r=i[0],a=i[1],l=i[2],c=i[3],o=i[4],s=i[5],u=i[6],d=i[7],p=0;p<Ms;p++){if(p<16)this.temp[p]=(n[p*4]&255)<<24|(n[p*4+1]&255)<<16|(n[p*4+2]&255)<<8|n[p*4+3]&255;else{var f=this.temp[p-2],h=(f>>>17|f<<15)^(f>>>19|f<<13)^f>>>10;f=this.temp[p-15];var m=(f>>>7|f<<25)^(f>>>18|f<<14)^f>>>3;this.temp[p]=(h+this.temp[p-7]|0)+(m+this.temp[p-16]|0)}var g=(((o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7))+(o&s^~o&u)|0)+(d+(iDe[p]+this.temp[p]|0)|0)|0,y=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&a^r&l^a&l)|0;d=u,u=s,s=o,o=c+g|0,c=l,l=a,a=r,r=g+y|0}i[0]+=r,i[1]+=a,i[2]+=l,i[3]+=c,i[4]+=o,i[5]+=s,i[6]+=u,i[7]+=d},e})(),oDe=(function(){function e(t){this.secret=t,this.hash=new jC,this.reset()}return e.prototype.update=function(t){if(!(oO(t)||this.error))try{this.hash.update(B_(t))}catch(n){this.error=n}},e.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},e.prototype.digest=function(){return T8(this,void 0,void 0,function(){return E8(this,function(t){return[2,this.digestSync()]})})},e.prototype.reset=function(){if(this.hash=new jC,this.secret){this.outer=new jC;var t=lDe(this.secret),n=new Uint8Array(Ms);n.set(t);for(var i=0;i<Ms;i++)t[i]^=54,n[i]^=92;this.hash.update(t),this.outer.update(n);for(var i=0;i<t.byteLength;i++)t[i]=0}},e})();function lDe(e){var t=B_(e);if(t.byteLength>Ms){var n=new jC;n.update(t),t=n.digest()}var i=new Uint8Array(Ms);return i.set(t),i}var cDe=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function uDe(e){if(dDe(e)&&typeof e.crypto.subtle=="object"){var t=e.crypto.subtle;return pDe(t)}return!1}function dDe(e){if(typeof e=="object"&&typeof e.crypto=="object"){var t=e.crypto.getRandomValues;return typeof t=="function"}return!1}function pDe(e){return e&&cDe.every(function(t){return typeof e[t]=="function"})}var fDe=(function(){function e(t){uDe(DC())?this.hash=new nDe(t):this.hash=new oDe(t)}return e.prototype.update=function(t,n){this.hash.update(B_(t))},e.prototype.digest=function(){return this.hash.digest()},e.prototype.reset=function(){this.hash.reset()},e})();const hDe=({serviceId:e,clientVersion:t})=>async n=>{const i=typeof window<"u"?window.navigator:void 0,r=i?.userAgent??"",a=i?.userAgentData?.platform??FF.os(r)??"other",l=void 0,c=i?.userAgentData?.brands??[],o=c[c.length-1],s=o?.brand??FF.browser(r)??"unknown",u=o?.version??"unknown",d=[["aws-sdk-js",t],["ua","2.1"],[`os/${a}`,l],["lang/js"],["md/browser",`${s}_${u}`]];e&&d.push([`api/${e}`,t]);const p=await n?.userAgentAppId?.();return p&&d.push([`app/${p}`]),d},FF={os(e){if(/iPhone|iPad|iPod/.test(e))return"iOS";if(/Macintosh|Mac OS X/.test(e))return"macOS";if(/Windows NT/.test(e))return"Windows";if(/Android/.test(e))return"Android";if(/Linux/.test(e))return"Linux"},browser(e){if(/EdgiOS|EdgA|Edg\//.test(e))return"Microsoft Edge";if(/Firefox\//.test(e))return"Firefox";if(/Chrome\//.test(e))return"Chrome";if(/Safari\//.test(e))return"Safari"}},mDe=e=>()=>Promise.reject(e),gDe=["in-region","cross-region","mobile","standard","legacy"],yDe=({defaultsMode:e}={})=>nMe(async()=>{const t=typeof e=="function"?await e():e;switch(t?.toLowerCase()){case"auto":return Promise.resolve(vDe()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(t?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${gDe.join(", ")}, got ${t}`)}}),vDe=()=>{const e=window?.navigator;if(e?.connection){const{effectiveType:t,rtt:n,downlink:i}=e?.connection;if(typeof t=="string"&&t!=="4g"||Number(n)>100||Number(i)<10)return!0}return e?.userAgentData?.mobile||typeof e?.maxTouchPoints=="number"&&e?.maxTouchPoints>1},hue="required",Tc="fn",Ec="argv",Zb="ref",qF=!0,BF="isSet",W_="booleanEquals",Av="error",e1="endpoint",sa="tree",I8="PartitionResult",WF={[hue]:!1,type:"string"},zF={[hue]:!0,default:!1,type:"boolean"},GF={[Zb]:"Endpoint"},mue={[Tc]:W_,[Ec]:[{[Zb]:"UseFIPS"},!0]},gue={[Tc]:W_,[Ec]:[{[Zb]:"UseDualStack"},!0]},Wo={},HF={[Tc]:"getAttr",[Ec]:[{[Zb]:I8},"supportsFIPS"]},VF={[Tc]:W_,[Ec]:[!0,{[Tc]:"getAttr",[Ec]:[{[Zb]:I8},"supportsDualStack"]}]},JF=[mue],KF=[gue],ZF=[{[Zb]:"Region"}],bDe={parameters:{Region:WF,UseDualStack:zF,UseFIPS:zF,Endpoint:WF},rules:[{conditions:[{[Tc]:BF,[Ec]:[GF]}],rules:[{conditions:JF,error:"Invalid Configuration: FIPS and custom endpoint are not supported",type:Av},{rules:[{conditions:KF,error:"Invalid Configuration: Dualstack and custom endpoint are not supported",type:Av},{endpoint:{url:GF,properties:Wo,headers:Wo},type:e1}],type:sa}],type:sa},{rules:[{conditions:[{[Tc]:BF,[Ec]:ZF}],rules:[{conditions:[{[Tc]:"aws.partition",[Ec]:ZF,assign:I8}],rules:[{conditions:[mue,gue],rules:[{conditions:[{[Tc]:W_,[Ec]:[qF,HF]},VF],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:Wo,headers:Wo},type:e1}],type:sa}],type:sa},{error:"FIPS and DualStack are enabled, but this partition does not support one or both",type:Av}],type:sa},{conditions:JF,rules:[{conditions:[{[Tc]:W_,[Ec]:[HF,qF]}],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime-fips.{Region}.{PartitionResult#dnsSuffix}",properties:Wo,headers:Wo},type:e1}],type:sa}],type:sa},{error:"FIPS is enabled but this partition does not support FIPS",type:Av}],type:sa},{conditions:KF,rules:[{conditions:[VF],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:Wo,headers:Wo},type:e1}],type:sa}],type:sa},{error:"DualStack is enabled but this partition does not support DualStack",type:Av}],type:sa},{rules:[{endpoint:{url:"https://bedrock-runtime.{Region}.{PartitionResult#dnsSuffix}",properties:Wo,headers:Wo},type:e1}],type:sa}],type:sa}],type:sa},{error:"Invalid Configuration: Missing Region",type:Av}],type:sa}]},wDe=bDe,_De=new T7e({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),xDe=(e,t={})=>_De.get(e,()=>z7e(wDe,{endpointParams:e,logger:t.logger}));KT.aws=vce;class ka extends fb{constructor(t){super(t),Object.setPrototypeOf(this,ka.prototype)}}class P8 extends ka{name="AccessDeniedException";$fault="client";constructor(t){super({name:"AccessDeniedException",$fault:"client",...t}),Object.setPrototypeOf(this,P8.prototype)}}class M8 extends ka{name="InternalServerException";$fault="server";constructor(t){super({name:"InternalServerException",$fault:"server",...t}),Object.setPrototypeOf(this,M8.prototype)}}class N8 extends ka{name="ThrottlingException";$fault="client";constructor(t){super({name:"ThrottlingException",$fault:"client",...t}),Object.setPrototypeOf(this,N8.prototype)}}class $8 extends ka{name="ValidationException";$fault="client";constructor(t){super({name:"ValidationException",$fault:"client",...t}),Object.setPrototypeOf(this,$8.prototype)}}class D8 extends ka{name="ConflictException";$fault="client";constructor(t){super({name:"ConflictException",$fault:"client",...t}),Object.setPrototypeOf(this,D8.prototype)}}class j8 extends ka{name="ResourceNotFoundException";$fault="client";constructor(t){super({name:"ResourceNotFoundException",$fault:"client",...t}),Object.setPrototypeOf(this,j8.prototype)}}class L8 extends ka{name="ServiceQuotaExceededException";$fault="client";constructor(t){super({name:"ServiceQuotaExceededException",$fault:"client",...t}),Object.setPrototypeOf(this,L8.prototype)}}class U8 extends ka{name="ServiceUnavailableException";$fault="server";constructor(t){super({name:"ServiceUnavailableException",$fault:"server",...t}),Object.setPrototypeOf(this,U8.prototype)}}class F8 extends ka{name="ModelErrorException";$fault="client";originalStatusCode;resourceName;constructor(t){super({name:"ModelErrorException",$fault:"client",...t}),Object.setPrototypeOf(this,F8.prototype),this.originalStatusCode=t.originalStatusCode,this.resourceName=t.resourceName}}class q8 extends ka{name="ModelNotReadyException";$fault="client";$retryable={};constructor(t){super({name:"ModelNotReadyException",$fault:"client",...t}),Object.setPrototypeOf(this,q8.prototype)}}class B8 extends ka{name="ModelTimeoutException";$fault="client";constructor(t){super({name:"ModelTimeoutException",$fault:"client",...t}),Object.setPrototypeOf(this,B8.prototype)}}class W8 extends ka{name="ModelStreamErrorException";$fault="client";originalStatusCode;originalMessage;constructor(t){super({name:"ModelStreamErrorException",$fault:"client",...t}),Object.setPrototypeOf(this,W8.prototype),this.originalStatusCode=t.originalStatusCode,this.originalMessage=t.originalMessage}}const SDe="AudioBlock",CDe="AccessDeniedException",TDe="AppliedGuardrailDetails",EDe="AudioSource",kDe="AnyToolChoice",ADe="AutoToolChoice",RDe="Citation",ODe="ContentBlocks",IDe="ContentBlockDelta",PDe="ContentBlockDeltaEvent",MDe="ContentBlockStart",NDe="ContentBlockStartEvent",$De="ContentBlockStopEvent",DDe="ContentBlock",jDe="CitationsConfig",LDe="CitationsContentBlock",UDe="CacheDetail",FDe="CacheDetailsList",qDe="CitationsDelta",BDe="ConflictException",WDe="CitationGeneratedContent",zDe="CitationGeneratedContentList",GDe="CitationLocation",HDe="CachePointBlock",VDe="ConverseStream",JDe="CitationSourceContent",KDe="CitationSourceContentDelta",ZDe="CitationSourceContentList",XDe="CitationSourceContentListDelta",QDe="ConverseStreamMetrics",YDe="ConverseStreamMetadataEvent",eje="ConverseStreamOutput",tje="ConverseStreamRequest",nje="ConverseStreamResponse",rje="ConverseStreamTrace",ije="Citations",aje="DocumentBlock",sje="DocumentContentBlocks",oje="DocumentContentBlock",lje="DocumentCharLocation",cje="DocumentChunkLocation",uje="DocumentPageLocation",dje="DocumentSource",pje="ErrorBlock",fje="GuardrailAssessment",hje="GuardrailAssessmentList",mje="GuardrailAssessmentListMap",gje="GuardrailAssessmentMap",yje="GuardrailAutomatedReasoningDifferenceScenarioList",vje="GuardrailAutomatedReasoningFinding",bje="GuardrailAutomatedReasoningFindingList",wje="GuardrailAutomatedReasoningImpossibleFinding",_je="GuardrailAutomatedReasoningInvalidFinding",xje="GuardrailAutomatedReasoningInputTextReference",Sje="GuardrailAutomatedReasoningInputTextReferenceList",Cje="GuardrailAutomatedReasoningLogicWarning",Tje="GuardrailAutomatedReasoningNoTranslationsFinding",Eje="GuardrailAutomatedReasoningPolicyAssessment",kje="GuardrailAutomatedReasoningRule",Aje="GuardrailAutomatedReasoningRuleList",Rje="GuardrailAutomatedReasoningScenario",Oje="GuardrailAutomatedReasoningSatisfiableFinding",Ije="GuardrailAutomatedReasoningStatementList",Pje="GuardrailAutomatedReasoningStatementLogicContent",Mje="GuardrailAutomatedReasoningStatementNaturalLanguageContent",Nje="GuardrailAutomatedReasoningStatement",$je="GuardrailAutomatedReasoningTranslation",Dje="GuardrailAutomatedReasoningTranslationAmbiguousFinding",jje="GuardrailAutomatedReasoningTooComplexFinding",Lje="GuardrailAutomatedReasoningTranslationList",Uje="GuardrailAutomatedReasoningTranslationOption",Fje="GuardrailAutomatedReasoningTranslationOptionList",qje="GuardrailAutomatedReasoningValidFinding",Bje="GuardrailConverseContentBlock",Wje="GuardrailContentFilter",zje="GuardrailContentFilterList",Gje="GuardrailContextualGroundingFilter",Hje="GuardrailContextualGroundingFilters",Vje="GuardrailContextualGroundingPolicyAssessment",Jje="GuardrailConverseImageBlock",Kje="GuardrailConverseImageSource",Zje="GuardrailContentPolicyAssessment",Xje="GuardrailConverseTextBlock",Qje="GuardrailCustomWord",Yje="GuardrailCustomWordList",eLe="GuardrailCoverage",tLe="GuardrailImageCoverage",nLe="GuardrailInvocationMetrics",rLe="GuardrailManagedWord",iLe="GuardrailManagedWordList",aLe="GuardrailPiiEntityFilter",sLe="GuardrailPiiEntityFilterList",oLe="GuardrailRegexFilter",lLe="GuardrailRegexFilterList",cLe="GuardrailStreamConfiguration",uLe="GuardrailSensitiveInformationPolicyAssessment",dLe="GuardrailTopic",pLe="GuardrailTraceAssessment",fLe="GuardrailTextCharactersCoverage",hLe="GuardrailTopicList",mLe="GuardrailTopicPolicyAssessment",gLe="GuardrailUsage",yLe="GuardrailWordPolicyAssessment",vLe="ImageBlock",bLe="ImageBlockDelta",wLe="ImageBlockStart",_Le="InferenceConfiguration",xLe="ImageSource",SLe="InternalServerException",CLe="JsonSchemaDefinition",TLe="Message",ELe="ModelErrorException",kLe="ModelNotReadyException",ALe="MessageStartEvent",RLe="ModelStreamErrorException",OLe="MessageStopEvent",ILe="ModelTimeoutException",PLe="Messages",MLe="OutputConfig",NLe="OutputFormat",$Le="OutputFormatStructure",DLe="PerformanceConfiguration",jLe="PromptRouterTrace",LLe="PromptVariableMap",ULe="PromptVariableValues",FLe="ReasoningContentBlock",qLe="ReasoningContentBlockDelta",BLe="RequestMetadata",WLe="ResourceNotFoundException",zLe="ReasoningTextBlock",GLe="SystemContentBlocks",HLe="SystemContentBlock",VLe="S3Location",JLe="ServiceQuotaExceededException",KLe="SearchResultBlock",ZLe="SearchResultContentBlock",XLe="SearchResultContentBlocks",QLe="SearchResultLocation",YLe="ServiceTier",eUe="SpecificToolChoice",tUe="SystemTool",nUe="ServiceUnavailableException",rUe="ToolConfiguration",iUe="ToolChoice",aUe="ThrottlingException",sUe="ToolInputSchema",oUe="ToolResultBlock",lUe="ToolResultBlocksDelta",cUe="ToolResultBlockDelta",uUe="ToolResultBlockStart",dUe="ToolResultContentBlocks",pUe="ToolResultContentBlock",fUe="ToolSpecification",hUe="TokenUsage",mUe="ToolUseBlock",gUe="ToolUseBlockDelta",yUe="ToolUseBlockStart",vUe="Tools",bUe="Tool",wUe="VideoBlock",_Ue="ValidationException",xUe="VideoSource",SUe="WebLocation",Vy="action",CUe="appliedGuardrailDetails",TUe="additionalModelRequestFields",EUe="additionalModelResponseFieldPaths",kUe="additionalModelResponseFields",AUe="actionReason",RUe="automatedReasoningPolicy",OUe="automatedReasoningPolicyUnits",IUe="automatedReasoningPolicies",PUe="any",MUe="audio",NUe="auto",b2="bytes",$Ue="bucketOwner",Fc="client",DUe="contentBlockDelta",z8="contentBlockIndex",jUe="contentBlockStart",LUe="contentBlockStop",UUe="citationsContent",FUe="cacheDetails",qUe="claimsFalseScenario",BUe="contextualGroundingPolicy",WUe="contextualGroundingPolicyUnits",zUe="contentPolicy",GUe="contentPolicyImageUnits",HUe="contentPolicyUnits",G8="cachePoint",yue="contradictingRules",VUe="cacheReadInputTokens",vue="claimsTrueScenario",JUe="customWords",KUe="cacheWriteInputTokens",H8="citations",ZUe="citation",bue="claims",w2="content",XUe="context",wue="confidence",QUe="delta",YUe="documentChar",eFe="documentChunk",V8="documentIndex",tFe="documentPage",nFe="differenceScenarios",Jy="detected",_ue="description",rFe="domain",xue="document",Aa="error",iFe="enabled",CE="end",Xb="format",aFe="filterStrength",sFe="findings",Sue="filters",oFe="guardrail",lFe="guardrailArn",cFe="guardrailCoverage",uFe="guardrailConfig",Cue="guardContent",dFe="guardrailId",pFe="guardrailIdentifier",fFe="guardrailOrigin",hFe="guardrailOwnership",mFe="guardrailProcessingLatency",Tue="guardrailVersion",Eue="guarded",gFe="http",Zs="httpError",kue="input",yFe="inputAssessment",vFe="inferenceConfig",bFe="invocationMetrics",wFe="invokedModelId",_Fe="inputSchema",xFe="internalServerException",Aue="inputTokens",SFe="identifier",CFe="images",_2="image",TFe="impossible",EFe="invalid",J8="json",kFe="jsonSchema",Rue="location",AFe="latencyMs",TE="logicWarning",RFe="latency",OFe="logic",vs="message",IFe="modelId",PFe="modelOutput",MFe="messageStart",NFe="modelStreamErrorException",$Fe="messageStop",DFe="maxTokens",jFe="managedWordLists",EE="match",LFe="messages",UFe="metrics",FFe="metadata",Em="name",qFe="naturalLanguage",BFe="noTranslations",WFe="outputAssessments",zFe="outputConfig",GFe="originalMessage",Oue="originalStatusCode",HFe="outputTokens",VFe="options",Iue="premises",Pue="performanceConfig",JFe="piiEntities",KFe="promptRouter",ZFe="promptVariables",XFe="policyVersionArn",QFe="qualifiers",YFe="regex",Mue="reasoningContent",Nue="redactedContent",eqe="requestMetadata",tqe="resourceName",nqe="reasoningText",rqe="regexes",$ue="role",Due="smithy.ts.sdk.synthetic.com.amazonaws.bedrockruntime",jue="sourceContent",iqe="sensitiveInformationPolicy",aqe="sensitiveInformationPolicyFreeUnits",sqe="sensitiveInformationPolicyUnits",kE="s3Location",oqe="streamProcessingMode",lqe="stopReason",cqe="searchResultIndex",uqe="searchResultLocation",Lue="searchResult",dqe="supportingRules",pqe="stopSequences",Uue="serviceTier",fqe="systemTool",hqe="serviceUnavailableException",mqe="satisfiable",gqe="score",yqe="schema",Fue="server",que="signature",km="source",Bue="status",x2="start",vqe="statements",bqe="stream",wqe="streaming",_qe="strict",xqe="structure",Sqe="system",Wue="ttl",Cqe="translationAmbiguous",Tqe="toolConfig",Eqe="textCharacters",kqe="toolChoice",Aqe="tooComplex",Rqe="throttlingException",Oqe="textFormat",Iqe="topicPolicy",Pqe="topicPolicyUnits",Mqe="topP",K8="toolResult",Nqe="toolSpec",$qe="totalTokens",Z8="toolUse",AE="toolUseId",Xi="text",Dqe="temperature",jqe="threshold",X8="title",zue="total",Lqe="tools",Uqe="tool",Fqe="topics",Gue="trace",RE="translation",qqe="translations",bs="type",Hue="usage",Bqe="untranslatedClaims",Wqe="untranslatedPremises",zqe="uri",Gqe="url",Hqe="validationException",Vqe="valid",Vue="video",Jqe="web",Kqe="wordPolicy",Zqe="wordPolicyUnits",We="com.amazonaws.bedrockruntime",Jue=Ua.for(Due);var Xqe=[-3,Due,"BedrockRuntimeServiceException",0,[],[]];Jue.registerError(Xqe,ka);const ws=Ua.for(We);var Qqe=[-3,We,CDe,{[Aa]:Fc,[Zs]:403},[vs],[0]];ws.registerError(Qqe,P8);var Yqe=[-3,We,BDe,{[Aa]:Fc,[Zs]:400},[vs],[0]];ws.registerError(Yqe,D8);var Kue=[-3,We,SLe,{[Aa]:Fue,[Zs]:500},[vs],[0]];ws.registerError(Kue,M8);var eBe=[-3,We,ELe,{[Aa]:Fc,[Zs]:424},[vs,Oue,tqe],[0,1,0]];ws.registerError(eBe,F8);var tBe=[-3,We,kLe,{[Aa]:Fc,[Zs]:429},[vs],[0]];ws.registerError(tBe,q8);var Zue=[-3,We,RLe,{[Aa]:Fc,[Zs]:424},[vs,Oue,GFe],[0,1,0]];ws.registerError(Zue,W8);var nBe=[-3,We,ILe,{[Aa]:Fc,[Zs]:408},[vs],[0]];ws.registerError(nBe,B8);var rBe=[-3,We,WLe,{[Aa]:Fc,[Zs]:404},[vs],[0]];ws.registerError(rBe,j8);var iBe=[-3,We,JLe,{[Aa]:Fc,[Zs]:400},[vs],[0]];ws.registerError(iBe,L8);var Xue=[-3,We,nUe,{[Aa]:Fue,[Zs]:503},[vs],[0]];ws.registerError(Xue,U8);var Que=[-3,We,aUe,{[Aa]:Fc,[Zs]:429},[vs],[0]];ws.registerError(Que,N8);var Yue=[-3,We,_Ue,{[Aa]:Fc,[Zs]:400},[vs],[0]];ws.registerError(Yue,$8);const aBe=[Jue,ws];var sBe=[0,We,Pje,8,0],ede=[0,We,Mje,8,0],oBe=[3,We,kDe,0,[],[]],lBe=[3,We,TDe,0,[dFe,Tue,lFe,fFe,hFe],[0,0,0,64,0]],cBe=[3,We,SDe,0,[Xb,km,Aa],[0,[()=>aze,0],[()=>Y8,0]],2],uBe=[3,We,ADe,0,[],[]],dBe=[3,We,UDe,0,[Wue,Aue],[0,1],2],Q8=[3,We,HDe,0,[bs,Wue],[0,0],1],pBe=[3,We,RDe,0,[X8,km,jue,Rue],[0,0,()=>MWe,()=>cde]],tde=[3,We,jDe,0,[iFe],[2],1],fBe=[3,We,LDe,0,[w2,H8],[()=>IWe,()=>PWe]],hBe=[3,We,qDe,0,[X8,km,jue,Rue],[0,0,()=>NWe,()=>cde]],mBe=[3,We,KDe,0,[Xi],[0]],gBe=[3,We,PDe,0,[QUe,z8],[[()=>cze,0],1],2],yBe=[3,We,NDe,0,[x2,z8],[()=>uze,1],2],vBe=[3,We,$De,0,[z8],[1],1],bBe=[3,We,YDe,0,[Hue,UFe,Gue,Pue,Uue],[()=>_We,()=>wBe,[()=>SBe,0],()=>ade,()=>ode],2],wBe=[3,We,QDe,0,[AFe],[1],1],_Be=[3,We,tje,0,[IFe,LFe,Sqe,vFe,Tqe,uFe,TUe,ZFe,EUe,eqe,Pue,Uue,zFe],[[0,1],[()=>KWe,0],[()=>XWe,0],()=>lWe,()=>xWe,()=>YBe,15,[()=>rze,0],64,[()=>ize,0],()=>ade,()=>ode,[()=>fWe,0]],1],xBe=[3,We,nje,0,[bqe],[[()=>dze,16]]],SBe=[3,We,rje,0,[oFe,KFe],[[()=>rWe,0],()=>mWe]],nde=[3,We,aje,0,[Em,km,Xb,XUe,H8],[0,()=>fze,0,0,()=>tde],2],CBe=[3,We,lje,0,[V8,x2,CE],[1,1,1]],TBe=[3,We,cje,0,[V8,x2,CE],[1,1,1]],EBe=[3,We,uje,0,[V8,x2,CE],[1,1,1]],Y8=[3,We,pje,8,[vs],[0]],rde=[3,We,fje,0,[Iqe,zUe,Kqe,iqe,BUe,RUe,bFe,CUe],[()=>nWe,()=>FBe,()=>aWe,()=>QBe,()=>BBe,[()=>IBe,0],()=>JBe,()=>lBe]],kBe=[3,We,wje,0,[RE,yue,TE],[[()=>S2,0],()=>e7,[()=>OE,0]]],ABe=[3,We,xje,0,[Xi],[[()=>ede,0]]],RBe=[3,We,_je,0,[RE,yue,TE],[[()=>S2,0],()=>e7,[()=>OE,0]]],OE=[3,We,Cje,0,[bs,Iue,bue],[0,[()=>z_,0],[()=>z_,0]]],OBe=[3,We,Tje,0,[],[]],IBe=[3,We,Eje,0,[sFe],[[()=>UWe,0]]],PBe=[3,We,kje,0,[SFe,XFe],[0,0]],MBe=[3,We,Oje,0,[RE,vue,qUe,TE],[[()=>S2,0],[()=>e3,0],[()=>e3,0],[()=>OE,0]]],e3=[3,We,Rje,0,[vqe],[[()=>z_,0]]],NBe=[3,We,Nje,0,[OFe,qFe],[[()=>sBe,0],[()=>ede,0]]],$Be=[3,We,jje,0,[],[]],S2=[3,We,$je,0,[Iue,bue,Wqe,Bqe,wue],[[()=>z_,0],[()=>z_,0],[()=>XF,0],[()=>XF,0],1]],DBe=[3,We,Dje,0,[VFe,nFe],[[()=>qWe,0],[()=>LWe,0]]],jBe=[3,We,Uje,0,[qqe],[[()=>FWe,0]]],LBe=[3,We,qje,0,[RE,vue,dqe,TE],[[()=>S2,0],[()=>e3,0],()=>e7,[()=>OE,0]]],UBe=[3,We,Wje,0,[bs,wue,Vy,aFe,Jy],[0,0,0,0,2],3],FBe=[3,We,Zje,0,[Sue],[()=>BWe],1],qBe=[3,We,Gje,0,[bs,jqe,gqe,Vy,Jy],[0,1,1,0,2],4],BBe=[3,We,Vje,0,[Sue],[()=>WWe]],WBe=[3,We,Jje,8,[Xb,km],[0,[()=>mze,0]],2],zBe=[3,We,Xje,0,[Xi,QFe],[0,64],1],GBe=[3,We,eLe,0,[Eqe,CFe],[()=>eWe,()=>VBe]],HBe=[3,We,Qje,0,[EE,Vy,Jy],[0,0,2],2],VBe=[3,We,tLe,0,[Eue,zue],[1,1]],JBe=[3,We,nLe,0,[mFe,Hue,cFe],[1,()=>iWe,()=>GBe]],KBe=[3,We,rLe,0,[EE,bs,Vy,Jy],[0,0,0,2],3],ZBe=[3,We,aLe,0,[EE,bs,Vy,Jy],[0,0,0,2],3],XBe=[3,We,oLe,0,[Vy,Em,EE,YFe,Jy],[0,0,0,0,2],1],QBe=[3,We,uLe,0,[JFe,rqe],[()=>HWe,()=>VWe],2],YBe=[3,We,cLe,0,[pFe,Tue,Gue,oqe],[0,0,0,0]],eWe=[3,We,fLe,0,[Eue,zue],[1,1]],tWe=[3,We,dLe,0,[Em,bs,Vy,Jy],[0,0,0,2],3],nWe=[3,We,mLe,0,[Fqe],[()=>JWe],1],rWe=[3,We,pLe,0,[PFe,yFe,WFe,AUe],[64,[()=>nze,0],[()=>tze,0],0]],iWe=[3,We,gLe,0,[Pqe,HUe,Zqe,sqe,aqe,WUe,GUe,OUe,IUe],[1,1,1,1,1,1,1,1,1],6],aWe=[3,We,yLe,0,[JUe,jFe],[()=>zWe,()=>GWe],2],ide=[3,We,vLe,0,[Xb,km,Aa],[0,[()=>dde,0],[()=>Y8,0]],2],sWe=[3,We,bLe,0,[km,Aa],[[()=>dde,0],[()=>Y8,0]]],oWe=[3,We,wLe,0,[Xb],[0],1],lWe=[3,We,_Le,0,[DFe,Dqe,Mqe,pqe],[1,1,1,64]],cWe=[3,We,CLe,0,[yqe,Em,_ue],[0,0,0],1],uWe=[3,We,TLe,0,[$ue,w2],[0,[()=>$We,0]],2],dWe=[3,We,ALe,0,[$ue],[0],1],pWe=[3,We,OLe,0,[lqe,kUe],[0,15],1],fWe=[3,We,MLe,0,[Oqe],[[()=>hWe,0]]],hWe=[3,We,NLe,0,[bs,xqe],[0,[()=>gze,0]],2],ade=[3,We,DLe,0,[RFe],[0]],mWe=[3,We,jLe,0,[wFe],[0]],gWe=[3,We,zLe,8,[Xi,que],[0,0],1],IE=[3,We,VLe,0,[zqe,$Ue],[0,0],1],sde=[3,We,KLe,0,[km,X8,w2,H8],[0,0,()=>ZWe,()=>tde],3],yWe=[3,We,ZLe,0,[Xi],[0],1],vWe=[3,We,QLe,0,[cqe,x2,CE],[1,1,1]],ode=[3,We,YLe,0,[bs],[0],1],bWe=[3,We,eUe,0,[Em],[0],1],wWe=[3,We,tUe,0,[Em],[0],1],_We=[3,We,hUe,0,[Aue,HFe,$qe,VUe,KUe,FUe],[1,1,1,1,1,()=>OWe],3],xWe=[3,We,rUe,0,[Lqe,kqe],[()=>eze,()=>xze],1],SWe=[3,We,oUe,0,[AE,w2,Bue,bs],[0,[()=>YWe,0],0,0],2],CWe=[3,We,uUe,0,[AE,bs,Bue],[0,0,0],1],TWe=[3,We,fUe,0,[Em,_Fe,_ue,_qe],[0,()=>Sze,0,2],2],EWe=[3,We,mUe,0,[AE,Em,kue,bs],[0,0,15,0],3],kWe=[3,We,gUe,0,[kue],[0],1],AWe=[3,We,yUe,0,[AE,Em,bs],[0,0,0],2],lde=[3,We,wUe,0,[Xb,km],[0,()=>Eze],2],RWe=[3,We,SUe,0,[Gqe,rFe],[0,0]],OWe=[1,We,FDe,0,()=>dBe],IWe=[1,We,zDe,0,()=>sze],PWe=[1,We,ije,0,()=>pBe],MWe=[1,We,ZDe,0,()=>oze],NWe=[1,We,XDe,0,()=>mBe],$We=[1,We,ODe,0,[()=>lze,0]],DWe=[1,We,sje,0,()=>pze],jWe=[1,We,hje,0,[()=>rde,0]],LWe=[1,We,yje,0,[()=>e3,0]],UWe=[1,We,bje,0,[()=>hze,0]],XF=[1,We,Sje,0,[()=>ABe,0]],e7=[1,We,Aje,0,()=>PBe],z_=[1,We,Ije,0,[()=>NBe,0]],FWe=[1,We,Lje,0,[()=>S2,0]],qWe=[1,We,Fje,0,[()=>jBe,0]],BWe=[1,We,zje,0,()=>UBe],WWe=[1,We,Hje,0,()=>qBe],zWe=[1,We,Yje,0,()=>HBe],GWe=[1,We,iLe,0,()=>KBe],HWe=[1,We,sLe,0,()=>ZBe],VWe=[1,We,lLe,0,()=>XBe],JWe=[1,We,hLe,0,()=>tWe],KWe=[1,We,PLe,0,[()=>uWe,0]],ZWe=[1,We,XLe,0,()=>yWe],XWe=[1,We,GLe,0,[()=>wze,0]],QWe=[1,We,lUe,0,()=>Cze],YWe=[1,We,dUe,0,[()=>Tze,0]],eze=[1,We,vUe,0,()=>_ze],tze=[2,We,mje,0,[0,0],[()=>jWe,0]],nze=[2,We,gje,0,[0,0],[()=>rde,0]],rze=[2,We,LLe,8,0,()=>yze],ize=[2,We,BLe,8,0,0],aze=[4,We,EDe,8,[b2,kE],[21,()=>IE]],sze=[4,We,WDe,0,[Xi],[0]],cde=[4,We,GDe,0,[Jqe,YUe,tFe,eFe,uqe],[()=>RWe,()=>CBe,()=>EBe,()=>TBe,()=>vWe]],oze=[4,We,JDe,0,[Xi],[0]],lze=[4,We,DDe,0,[Xi,_2,xue,Vue,MUe,Z8,K8,Cue,G8,Mue,UUe,Lue],[0,[()=>ide,0],()=>nde,()=>lde,[()=>cBe,0],()=>EWe,[()=>SWe,0],[()=>ude,0],()=>Q8,[()=>vze,0],()=>fBe,()=>sde]],cze=[4,We,IDe,0,[Xi,Z8,K8,Mue,ZUe,_2],[0,()=>kWe,()=>QWe,[()=>bze,0],()=>hBe,[()=>sWe,0]]],uze=[4,We,MDe,0,[Z8,K8,_2],[()=>AWe,()=>CWe,()=>oWe]],dze=[4,We,eje,{[wqe]:1},[MFe,jUe,DUe,LUe,$Fe,FFe,xFe,NFe,Hqe,Rqe,hqe],[()=>dWe,()=>yBe,[()=>gBe,0],()=>vBe,()=>pWe,[()=>bBe,0],[()=>Kue,0],[()=>Zue,0],[()=>Yue,0],[()=>Que,0],[()=>Xue,0]]],pze=[4,We,oje,0,[Xi],[0]],fze=[4,We,dje,0,[b2,kE,Xi,w2],[21,()=>IE,0,()=>DWe]],hze=[4,We,vje,0,[Vqe,EFe,mqe,TFe,Cqe,Aqe,BFe],[[()=>LBe,0],[()=>RBe,0],[()=>MBe,0],[()=>kBe,0],[()=>DBe,0],()=>$Be,()=>OBe]],ude=[4,We,Bje,0,[Xi,_2],[()=>zBe,[()=>WBe,0]]],mze=[4,We,Kje,8,[b2],[21]],dde=[4,We,xLe,8,[b2,kE],[21,()=>IE]],gze=[4,We,$Le,8,[kFe],[()=>cWe]],yze=[4,We,ULe,0,[Xi],[0]],vze=[4,We,FLe,8,[nqe,Nue],[[()=>gWe,0],21]],bze=[4,We,qLe,8,[Xi,Nue,que],[0,21,0]],wze=[4,We,HLe,0,[Xi,Cue,G8],[0,[()=>ude,0],()=>Q8]],_ze=[4,We,bUe,0,[Nqe,fqe,G8],[()=>TWe,()=>wWe,()=>Q8]],xze=[4,We,iUe,0,[NUe,PUe,Uqe],[()=>uBe,()=>oBe,()=>bWe]],Sze=[4,We,sUe,0,[J8],[15]],Cze=[4,We,cUe,0,[Xi,J8],[0,15]],Tze=[4,We,pUe,0,[J8,Xi,_2,xue,Vue,Lue],[15,0,[()=>ide,0],()=>nde,()=>lde,()=>sde]],Eze=[4,We,xUe,0,[b2,kE],[21,()=>IE]],kze=[9,We,VDe,{[gFe]:["POST","/model/{modelId}/converse-stream",200]},()=>_Be,()=>xBe];const Aze=e=>({apiVersion:"2023-09-30",base64Decoder:e?.base64Decoder??Ly,base64Encoder:e?.base64Encoder??Fy,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??xDe,extensions:e?.extensions??[],httpAuthSchemeProvider:e?.httpAuthSchemeProvider??J$e,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:t=>t.getIdentityProvider("aws.auth#sigv4"),signer:new tMe},{schemeId:"smithy.api#httpBearerAuth",identityProvider:t=>t.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new b7e}],logger:e?.logger??new Rce,protocol:e?.protocol??QMe,protocolSettings:e?.protocolSettings??{defaultNamespace:"com.amazonaws.bedrockruntime",errorTypeRegistries:aBe,version:"2023-09-30",serviceTarget:"AmazonBedrockFrontendService"},serviceId:e?.serviceId??"Bedrock Runtime",urlParser:e?.urlParser??ZT,utf8Decoder:e?.utf8Decoder??Uy,utf8Encoder:e?.utf8Encoder??Kb}),Rze=e=>{const t=yDe(e),n=()=>t().then($Me),i=Aze(e);return{...i,...e,runtime:"browser",defaultsMode:t,bodyLengthChecker:e?.bodyLengthChecker??PMe,credentialDefaultProvider:e?.credentialDefaultProvider??(r=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:e?.defaultUserAgentProvider??hDe({serviceId:i.serviceId,clientVersion:Y$e.version}),eventStreamPayloadHandlerProvider:e?.eventStreamPayloadHandlerProvider??JNe,eventStreamSerdeProvider:e?.eventStreamSerdeProvider??LNe,maxAttempts:e?.maxAttempts??YT,region:e?.region??mDe("Region is missing"),requestHandler:A8.create(e?.requestHandler??n,L_.create(n)),retryMode:e?.retryMode??(async()=>(await n()).retryMode||y$e),sha256:e?.sha256??fDe,streamCollector:e?.streamCollector??Xle,useDualstackEndpoint:e?.useDualstackEndpoint??(()=>Promise.resolve(KNe)),useFipsEndpoint:e?.useFipsEndpoint??(()=>Promise.resolve(ZNe))}},Oze=e=>({setRegion(t){e.region=t},region(){return e.region}}),Ize=e=>({region:e.region()}),Pze=e=>{const t=e.httpAuthSchemes;let n=e.httpAuthSchemeProvider,i=e.credentials,r=e.token;return{setHttpAuthScheme(a){const l=t.findIndex(c=>c.schemeId===a.schemeId);l===-1?t.push(a):t.splice(l,1,a)},httpAuthSchemes(){return t},setHttpAuthSchemeProvider(a){n=a},httpAuthSchemeProvider(){return n},setCredentials(a){i=a},credentials(){return i},setToken(a){r=a},token(){return r}}},Mze=e=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials(),token:e.token()}),Nze=(e,t)=>{const n=Object.assign(Oze(e),FMe(e),VPe(e),Pze(e));return t.forEach(i=>i.configure(n)),Object.assign(e,Ize(n),qMe(n),JPe(n),Mze(n))};class $ze extends MMe{config;constructor(...[t]){const n=Rze(t||{});super(n),this.initConfig=n;const i=Z$e(n),r=C7e(i),a=D$e(r),l=YNe(a),c=l,o=g$e(c),s=e$e(o),u=K$e(s),d=HPe(u),p=zNe(d),f=Nze(p,t?.extensions||[]);this.config=f,this.middlewareStack.use(A8e(this.config)),this.middlewareStack.use(oNe(this.config)),this.middlewareStack.use(W$e(this.config)),this.middlewareStack.use(r$e(this.config)),this.middlewareStack.use(QPe(this.config)),this.middlewareStack.use(t8e(this.config)),this.middlewareStack.use(i8e(this.config)),this.middlewareStack.use(c8e(this.config,{httpAuthSchemeParametersProvider:G$e,identityProviderConfigProvider:async h=>new v7e({"aws.auth#sigv4":h.credentials,"smithy.api#httpBearerAuth":h.token})})),this.middlewareStack.use(m8e(this.config))}destroy(){super.destroy()}}class Dze extends kce.classBuilder().ep(X$e).m(function(t,n,i,r){return[m$e(i,t.getEndpointParameterInstructions())]}).s("AmazonBedrockFrontendService","ConverseStream",{eventStream:{output:!0}}).n("BedrockRuntimeClient","ConverseStreamCommand").sc(kze).build(){}const pde={ONE_HOUR:"1h"},fde={DEFAULT:"default"},qx={GIF:"gif",JPEG:"jpeg",PNG:"png",WEBP:"webp"},Bx={ERROR:"error",SUCCESS:"success"},Kw={ASSISTANT:"assistant",USER:"user"},t1={END_TURN:"end_turn",MAX_TOKENS:"max_tokens",MODEL_CONTEXT_WINDOW_EXCEEDED:"model_context_window_exceeded",STOP_SEQUENCE:"stop_sequence",TOOL_USE:"tool_use"};var po={};const Zw=(e,t,n={})=>{const i=new Js;return(async()=>{const r={role:"assistant",content:[],api:"bedrock-converse-stream",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()},a=r.content,l={region:n.region,profile:n.profile};if(typeof process<"u"&&(process.versions?.node||process.versions?.bun)){if(l.region=l.region||po.AWS_REGION||po.AWS_DEFAULT_REGION,po.AWS_BEDROCK_SKIP_AUTH==="1"&&(l.credentials={accessKeyId:"dummy-access-key",secretAccessKey:"dummy-secret-key"}),po.HTTP_PROXY||po.HTTPS_PROXY||po.NO_PROXY||po.http_proxy||po.https_proxy||po.no_proxy){const c=await fn(()=>import("./index-tzzI-w2Q.js"),__vite__mapDeps([0,1])),o=await fn(()=>import("./index-CTwqCjQD.js").then(u=>u.i),__vite__mapDeps([2,1,3,4])),s=new o.ProxyAgent;l.requestHandler=new c.NodeHttpHandler({httpAgent:s,httpsAgent:s})}else if(po.AWS_BEDROCK_FORCE_HTTP1==="1"){const c=await fn(()=>import("./index-tzzI-w2Q.js"),__vite__mapDeps([0,1]));l.requestHandler=new c.NodeHttpHandler}}l.region=l.region||"us-east-1";try{const c=new $ze(l),o=Wze(n.cacheRetention),s={modelId:e.id,messages:Vze(t,e,o),system:Gze(t.systemPrompt,e,o),inferenceConfig:{maxTokens:n.maxTokens,temperature:n.temperature},toolConfig:Jze(t.tools,n.toolChoice),additionalModelRequestFields:Zze(e,n)};n?.onPayload?.(s);const u=new Dze(s),d=await c.send(u,{abortSignal:n.signal});for await(const p of d.stream)if(p.messageStart){if(p.messageStart.role!==Kw.ASSISTANT)throw new Error("Unexpected assistant message start but got user message start instead");i.push({type:"start",partial:r})}else if(p.contentBlockStart)Lze(p.contentBlockStart,a,r,i);else if(p.contentBlockDelta)Uze(p.contentBlockDelta,a,r,i);else if(p.contentBlockStop)qze(p.contentBlockStop,a,r,i);else if(p.messageStop)r.stopReason=Kze(p.messageStop.stopReason);else if(p.metadata)Fze(p.metadata,e,r);else{if(p.internalServerException)throw new Error(`Internal server error: ${p.internalServerException.message}`);if(p.modelStreamErrorException)throw new Error(`Model stream error: ${p.modelStreamErrorException.message}`);if(p.validationException)throw new Error(`Validation error: ${p.validationException.message}`);if(p.throttlingException)throw new Error(`Throttling error: ${p.throttlingException.message}`);if(p.serviceUnavailableException)throw new Error(`Service unavailable: ${p.serviceUnavailableException.message}`)}if(n.signal?.aborted)throw new Error("Request was aborted");if(r.stopReason==="error"||r.stopReason==="aborted")throw new Error("An unknown error occurred");i.push({type:"done",reason:r.stopReason,message:r}),i.end()}catch(c){for(const o of r.content)delete o.index,delete o.partialJson;r.stopReason=n.signal?.aborted?"aborted":"error",r.errorMessage=c instanceof Error?c.message:JSON.stringify(c),i.push({type:"error",reason:r.stopReason,error:r}),i.end()}})(),i},jze=(e,t,n)=>{const i=Lc(e,n,void 0);if(!n?.reasoning)return Zw(e,t,{...i,reasoning:void 0});if(e.id.includes("anthropic.claude")||e.id.includes("anthropic/claude")){if(cO(e.id))return Zw(e,t,{...i,reasoning:n.reasoning,thinkingBudgets:n.thinkingBudgets});const r=IP(i.maxTokens||0,e.maxTokens,n.reasoning,n.thinkingBudgets);return Zw(e,t,{...i,maxTokens:r.maxTokens,reasoning:n.reasoning,thinkingBudgets:{...n.thinkingBudgets||{},[Uc(n.reasoning)]:r.thinkingBudget}})}return Zw(e,t,{...i,reasoning:n.reasoning,thinkingBudgets:n.thinkingBudgets})};function Lze(e,t,n,i){const r=e.contentBlockIndex,a=e.start;if(a?.toolUse){const l={type:"toolCall",id:a.toolUse.toolUseId||"",name:a.toolUse.name||"",arguments:{},partialJson:"",index:r};n.content.push(l),i.push({type:"toolcall_start",contentIndex:t.length-1,partial:n})}}function Uze(e,t,n,i){const r=e.contentBlockIndex,a=e.delta;let l=t.findIndex(o=>o.index===r),c=t[l];if(a?.text!==void 0){if(!c){const o={type:"text",text:"",index:r};n.content.push(o),l=t.length-1,c=t[l],i.push({type:"text_start",contentIndex:l,partial:n})}c.type==="text"&&(c.text+=a.text,i.push({type:"text_delta",contentIndex:l,delta:a.text,partial:n}))}else if(a?.toolUse&&c?.type==="toolCall")c.partialJson=(c.partialJson||"")+(a.toolUse.input||""),c.arguments=Rc(c.partialJson),i.push({type:"toolcall_delta",contentIndex:l,delta:a.toolUse.input||"",partial:n});else if(a?.reasoningContent){let o=c,s=l;if(!o){const u={type:"thinking",thinking:"",thinkingSignature:"",index:r};n.content.push(u),s=t.length-1,o=t[s],i.push({type:"thinking_start",contentIndex:s,partial:n})}o?.type==="thinking"&&(a.reasoningContent.text&&(o.thinking+=a.reasoningContent.text,i.push({type:"thinking_delta",contentIndex:s,delta:a.reasoningContent.text,partial:n})),a.reasoningContent.signature&&(o.thinkingSignature=(o.thinkingSignature||"")+a.reasoningContent.signature))}}function Fze(e,t,n){e.usage&&(n.usage.input=e.usage.inputTokens||0,n.usage.output=e.usage.outputTokens||0,n.usage.cacheRead=e.usage.cacheReadInputTokens||0,n.usage.cacheWrite=e.usage.cacheWriteInputTokens||0,n.usage.totalTokens=e.usage.totalTokens||n.usage.input+n.usage.output,wm(t,n.usage))}function qze(e,t,n,i){const r=t.findIndex(l=>l.index===e.contentBlockIndex),a=t[r];if(a)switch(delete a.index,a.type){case"text":i.push({type:"text_end",contentIndex:r,content:a.text,partial:n});break;case"thinking":i.push({type:"thinking_end",contentIndex:r,content:a.thinking,partial:n});break;case"toolCall":a.arguments=Rc(a.partialJson),delete a.partialJson,i.push({type:"toolcall_end",contentIndex:r,toolCall:a,partial:n});break}}function cO(e){return e.includes("opus-4-6")||e.includes("opus-4.6")||e.includes("sonnet-4-6")||e.includes("sonnet-4.6")}function Bze(e,t){switch(e){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";case"xhigh":return t.includes("opus-4-6")||t.includes("opus-4.6")?"max":"high";default:return"high"}}function Wze(e){return e||(typeof process<"u"&&po.PI_CACHE_RETENTION==="long"?"long":"short")}function hde(e){if(e.cost.cacheRead||e.cost.cacheWrite)return!0;const t=e.id.toLowerCase();return!!(t.includes("claude")&&(t.includes("-4-")||t.includes("-4."))||t.includes("claude-3-7-sonnet")||t.includes("claude-3-5-haiku"))}function zze(e){const t=e.id.toLowerCase();return t.includes("anthropic.claude")||t.includes("anthropic/claude")}function Gze(e,t,n){if(!e)return;const i=[{text:Gn(e)}];return n!=="none"&&hde(t)&&i.push({cachePoint:{type:fde.DEFAULT,...n==="long"?{ttl:pde.ONE_HOUR}:{}}}),i}function Hze(e){const t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return t.length>64?t.slice(0,64):t}function Vze(e,t,n){const i=[],r=Bb(e.messages,t,Hze);for(let a=0;a<r.length;a++){const l=r[a];switch(l.role){case"user":i.push({role:Kw.USER,content:typeof l.content=="string"?[{text:Gn(l.content)}]:l.content.map(c=>{switch(c.type){case"text":return{text:Gn(c.text)};case"image":return{image:tA(c.mimeType,c.data)};default:throw new Error("Unknown user content type")}})});break;case"assistant":{if(l.content.length===0)continue;const c=[];for(const o of l.content)switch(o.type){case"text":if(o.text.trim().length===0)continue;c.push({text:Gn(o.text)});break;case"toolCall":c.push({toolUse:{toolUseId:o.id,name:o.name,input:o.arguments}});break;case"thinking":if(o.thinking.trim().length===0)continue;zze(t)?c.push({reasoningContent:{reasoningText:{text:Gn(o.thinking),signature:o.thinkingSignature}}}):c.push({reasoningContent:{reasoningText:{text:Gn(o.thinking)}}});break;default:throw new Error("Unknown assistant content type")}if(c.length===0)continue;i.push({role:Kw.ASSISTANT,content:c});break}case"toolResult":{const c=[];c.push({toolResult:{toolUseId:l.toolCallId,content:l.content.map(s=>s.type==="image"?{image:tA(s.mimeType,s.data)}:{text:Gn(s.text)}),status:l.isError?Bx.ERROR:Bx.SUCCESS}});let o=a+1;for(;o<r.length&&r[o].role==="toolResult";){const s=r[o];c.push({toolResult:{toolUseId:s.toolCallId,content:s.content.map(u=>u.type==="image"?{image:tA(u.mimeType,u.data)}:{text:Gn(u.text)}),status:s.isError?Bx.ERROR:Bx.SUCCESS}}),o++}a=o-1,i.push({role:Kw.USER,content:c});break}default:throw new Error("Unknown message role")}}if(n!=="none"&&hde(t)&&i.length>0){const a=i[i.length-1];a.role===Kw.USER&&a.content&&a.content.push({cachePoint:{type:fde.DEFAULT,...n==="long"?{ttl:pde.ONE_HOUR}:{}}})}return i}function Jze(e,t){if(!e?.length||t==="none")return;const n=e.map(r=>({toolSpec:{name:r.name,description:r.description,inputSchema:{json:r.parameters}}}));let i;switch(t){case"auto":i={auto:{}};break;case"any":i={any:{}};break;default:t?.type==="tool"&&(i={tool:{name:t.name}})}return{tools:n,toolChoice:i}}function Kze(e){switch(e){case t1.END_TURN:case t1.STOP_SEQUENCE:return"stop";case t1.MAX_TOKENS:case t1.MODEL_CONTEXT_WINDOW_EXCEEDED:return"length";case t1.TOOL_USE:return"toolUse";default:return"error"}}function Zze(e,t){if(!(!t.reasoning||!e.reasoning)&&(e.id.includes("anthropic.claude")||e.id.includes("anthropic/claude"))){const n=cO(e.id)?{thinking:{type:"adaptive"},output_config:{effort:Bze(t.reasoning,e.id)}}:(()=>{const i={minimal:1024,low:2048,medium:8192,high:16384,xhigh:16384},r=t.reasoning==="xhigh"?"high":t.reasoning;return{thinking:{type:"enabled",budget_tokens:t.thinkingBudgets?.[r]??i[t.reasoning]}}})();return!cO(e.id)&&(t.interleavedThinking??!0)&&(n.anthropic_beta=["interleaved-thinking-2025-05-14"]),n}}function tA(e,t){let n;switch(e){case"image/jpeg":case"image/jpg":n=qx.JPEG;break;case"image/png":n=qx.PNG;break;case"image/gif":n=qx.GIF;break;case"image/webp":n=qx.WEBP;break;default:throw new Error(`Unknown image type: ${e}`)}const i=atob(t),r=new Uint8Array(i.length);for(let a=0;a<i.length;a++)r[a]=i.charCodeAt(a);return{source:{bytes:r},format:n}}let Xw=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&fn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{Xw=e});const Xze="https://chatgpt.com/backend-api",Qze="https://api.openai.com/auth",nA=3,QF=1e3,Yze=new Set(["openai","openai-codex","opencode"]),eGe=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function tGe(e,t){return e===429||e===500||e===502||e===503||e===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function YF(e,t){return new Promise((n,i)=>{if(t?.aborted){i(new Error("Request was aborted"));return}const r=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(r),i(new Error("Request was aborted"))})})}const mde=(e,t,n)=>{const i=new Js;return(async()=>{const r={role:"assistant",content:[],api:"openai-codex-responses",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const a=n?.apiKey||Vs(e.provider)||"";if(!a)throw new Error(`No API key for provider: ${e.provider}`);const l=bGe(a),c=rGe(e,t,n);n?.onPayload?.(c);const o=wGe(e.headers,n?.headers,l,a,n?.sessionId),s=JSON.stringify(c),u=n?.transport||"sse";if(u!=="sse"){let f=!1;try{if(await yGe(aGe(e.baseUrl),c,o,r,i,e,()=>{f=!0},n),n?.signal?.aborted)throw new Error("Request was aborted");i.push({type:"done",reason:r.stopReason,message:r}),i.end();return}catch(h){if(u==="websocket"||f)throw h}}let d,p;for(let f=0;f<=nA;f++){if(n?.signal?.aborted)throw new Error("Request was aborted");try{if(d=await fetch(gde(e.baseUrl),{method:"POST",headers:o,body:s,signal:n?.signal}),d.ok)break;const h=await d.text();if(f<nA&&tGe(d.status,h)){const y=QF*2**f;await YF(y,n?.signal);continue}const m=new Response(h,{status:d.status,statusText:d.statusText}),g=await vGe(m);throw new Error(g.friendlyMessage||g.message)}catch(h){if(h instanceof Error&&(h.name==="AbortError"||h.message==="Request was aborted"))throw new Error("Request was aborted");if(p=h instanceof Error?h:new Error(String(h)),f<nA&&!p.message.includes("usage limit")){const m=QF*2**f;await YF(m,n?.signal);continue}throw p}}if(!d?.ok)throw p??new Error("Failed after retries");if(!d.body)throw new Error("No response body");if(i.push({type:"start",partial:r}),await sGe(d,r,i,e),n?.signal?.aborted)throw new Error("Request was aborted");i.push({type:"done",reason:r.stopReason,message:r}),i.end()}catch(a){r.stopReason=n?.signal?.aborted?"aborted":"error",r.errorMessage=a instanceof Error?a.message:String(a),i.push({type:"error",reason:r.stopReason,error:r}),i.end()}})(),i},nGe=(e,t,n)=>{const i=n?.apiKey||Vs(e.provider);if(!i)throw new Error(`No API key for provider: ${e.provider}`);const r=Lc(e,n,i),a=Q3(e)?n?.reasoning:Uc(n?.reasoning);return mde(e,t,{...r,reasoningEffort:a})};function rGe(e,t,n){const i=e8(e,t,Yze,{includeSystemPrompt:!1}),r={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt,input:i,text:{verbosity:n?.textVerbosity||"medium"},include:["reasoning.encrypted_content"],prompt_cache_key:n?.sessionId,tool_choice:"auto",parallel_tool_calls:!0};return n?.temperature!==void 0&&(r.temperature=n.temperature),t.tools&&(r.tools=t8(t.tools,{strict:null})),n?.reasoningEffort!==void 0&&(r.reasoning={effort:iGe(e.id,n.reasoningEffort),summary:n.reasoningSummary??"auto"}),r}function iGe(e,t){const n=e.includes("/")?e.split("/").pop():e;return(n.startsWith("gpt-5.2")||n.startsWith("gpt-5.3"))&&t==="minimal"?"low":n==="gpt-5.1"&&t==="xhigh"?"high":n==="gpt-5.1-codex-mini"?t==="high"||t==="xhigh"?"high":"medium":t}function gde(e){const n=(e&&e.trim().length>0?e:Xze).replace(/\/+$/,"");return n.endsWith("/codex/responses")?n:n.endsWith("/codex")?`${n}/responses`:`${n}/codex/responses`}function aGe(e){const t=new URL(gde(e));return t.protocol==="https:"&&(t.protocol="wss:"),t.protocol==="http:"&&(t.protocol="ws:"),t.toString()}async function sGe(e,t,n,i){await dE(yde(lGe(e)),t,n,i)}async function*yde(e){for await(const t of e){const n=typeof t.type=="string"?t.type:void 0;if(n){if(n==="error"){const i=t.code||"",r=t.message||"";throw new Error(`Codex error: ${r||i||JSON.stringify(t)}`)}if(n==="response.failed"){const i=t.response?.error?.message;throw new Error(i||"Codex response failed")}if(n==="response.done"||n==="response.completed"){const i=t.response,r=i&&{...i,status:oGe(i.status)};yield{...t,type:"response.completed",response:r};continue}yield t}}}function oGe(e){if(typeof e=="string")return eGe.has(e)?e:void 0}async function*lGe(e){if(!e.body)return;const t=e.body.getReader(),n=new TextDecoder;let i="";for(;;){const{done:r,value:a}=await t.read();if(r)break;i+=n.decode(a,{stream:!0});let l=i.indexOf(`
525
+ `);return this.signString(h,{signingDate:i,signingRegion:c,signingService:l})}async signMessage(t,{signingDate:n=new Date,signingRegion:i,signingService:r}){return this.signEvent({headers:this.headerFormatter.format(t.message.headers),payload:t.message.body},{signingDate:n,signingRegion:i,signingService:r,priorSignature:t.priorSignature}).then(l=>({message:t.message,signature:l}))}async signString(t,{signingDate:n=new Date,signingRegion:i,signingService:r}={}){const a=await this.credentialProvider();this.validateResolvedCredentials(a);const l=i??await this.regionProvider(),{shortDate:c}=this.formatDate(n),o=new this.sha256(await this.getSigningKey(a,l,c,r));return o.update(j_(t)),qa(await o.digest())}async signRequest(t,{signingDate:n=new Date,signableHeaders:i,unsignableHeaders:r,signingRegion:a,signingService:l}={}){const c=await this.credentialProvider();this.validateResolvedCredentials(c);const o=a??await this.regionProvider(),s=xF(t),{longDate:u,shortDate:d}=this.formatDate(n),p=Z6(d,o,l??this.service);s.headers[Cce]=u,c.sessionToken&&(s.headers[uMe]=c.sessionToken);const f=await X6(s,this.sha256);!SMe(rO,s.headers)&&this.applyChecksum&&(s.headers[rO]=f);const h=bF(s,r,i),m=await this.getSignature(u,p,this.getSigningKey(c,o,d,l),this.createCanonicalRequest(s,h,f));return s.headers[Sce]=`${J6} Credential=${c.accessKeyId}/${p}, SignedHeaders=${this.getCanonicalHeaderList(h)}, Signature=${m}`,s}async getSignature(t,n,i,r){const a=await this.createStringToSign(t,n,r,J6),l=new this.sha256(await i);return l.update(j_(a)),qa(await l.digest())}getSigningKey(t,n,i,r){return vMe(this.sha256,t,i,n,r||this.service)}}const RMe=e=>{let t=e.credentials,n=!!e.credentials,i;Object.defineProperty(e,"credentials",{set(s){s&&s!==t&&s!==i&&(n=!0),t=s;const u=OMe(e,{credentials:t,credentialDefaultProvider:e.credentialDefaultProvider}),d=IMe(e,u);if(n&&!d.attributed){const p=typeof t=="object"&&t!==null;i=async f=>{const m=await d(f);return p&&(!m.$source||Object.keys(m.$source).length===0)?Q7e(m,"CREDENTIALS_CODE","e"):m},i.memoized=d.memoized,i.configBound=d.configBound,i.attributed=!0}else i=d},get(){return i},enumerable:!0,configurable:!0}),e.credentials=t;const{signingEscapePath:r=!0,systemClockOffset:a=e.systemClockOffset||0,sha256:l}=e;let c;return e.signer?c=b_(e.signer):e.regionInfoProvider?c=()=>b_(e.region)().then(async s=>[await e.regionInfoProvider(s,{useFipsEndpoint:await e.useFipsEndpoint(),useDualstackEndpoint:await e.useDualstackEndpoint()})||{},s]).then(([s,u])=>{const{signingRegion:d,signingService:p}=s;e.signingRegion=e.signingRegion||d||u,e.signingName=e.signingName||p||e.serviceId;const f={...e,credentials:e.credentials,region:e.signingRegion,service:e.signingName,sha256:l,uriEscapePath:r},h=e.signerConstructor||SF;return new h(f)}):c=async s=>{s=Object.assign({},{name:"sigv4",signingName:e.signingName||e.defaultSigningName,signingRegion:await b_(e.region)(),properties:{}},s);const u=s.signingRegion,d=s.signingName;e.signingRegion=e.signingRegion||u,e.signingName=e.signingName||d||e.serviceId;const p={...e,credentials:e.credentials,region:e.signingRegion,service:e.signingName,sha256:l,uriEscapePath:r},f=e.signerConstructor||SF;return new f(p)},Object.assign(e,{systemClockOffset:a,signingEscapePath:r,signer:c})};function OMe(e,{credentials:t,credentialDefaultProvider:n}){let i;return t?t?.memoized?i=t:i=sce(t,ace,x8):n?i=b_(n(Object.assign({},e,{parentClientConfig:e}))):i=async()=>{throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")},i.memoized=!0,i}function IMe(e,t){if(t.configBound)return t;const n=async i=>t({...i,callerClientConfig:e});return n.memoized=t.memoized,n.configBound=!0,n}const CF=typeof TextEncoder=="function"?new TextEncoder:null,PMe=e=>{if(typeof e=="string"){if(CF)return CF.encode(e).byteLength;let t=e.length;for(let n=t-1;n>=0;n--){const i=e.charCodeAt(n);i>127&&i<=2047?t++:i>2047&&i<=65535&&(t+=2),i>=56320&&i<=57343&&n--}return t}else{if(typeof e.byteLength=="number")return e.byteLength;if(typeof e.size=="number")return e.size}throw new Error(`Body Length computation failed for ${e}`)},Dg=(e,t)=>{const n=[];if(e&&n.push(e),t)for(const i of t)n.push(i);return n},qm=(e,t)=>`${e||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`,XT=()=>{let e=[],t=[],n=!1;const i=new Set,r=d=>d.sort((p,f)=>TF[f.step]-TF[p.step]||EF[f.priority||"normal"]-EF[p.priority||"normal"]),a=d=>{let p=!1;const f=h=>{const m=Dg(h.name,h.aliases);if(m.includes(d)){p=!0;for(const g of m)i.delete(g);return!1}return!0};return e=e.filter(f),t=t.filter(f),p},l=d=>{let p=!1;const f=h=>{if(h.middleware===d){p=!0;for(const m of Dg(h.name,h.aliases))i.delete(m);return!1}return!0};return e=e.filter(f),t=t.filter(f),p},c=d=>(e.forEach(p=>{d.add(p.middleware,{...p})}),t.forEach(p=>{d.addRelativeTo(p.middleware,{...p})}),d.identifyOnResolve?.(u.identifyOnResolve()),d),o=d=>{const p=[];return d.before.forEach(f=>{f.before.length===0&&f.after.length===0?p.push(f):p.push(...o(f))}),p.push(d),d.after.reverse().forEach(f=>{f.before.length===0&&f.after.length===0?p.push(f):p.push(...o(f))}),p},s=(d=!1)=>{const p=[],f=[],h={};return e.forEach(g=>{const y={...g,before:[],after:[]};for(const v of Dg(y.name,y.aliases))h[v]=y;p.push(y)}),t.forEach(g=>{const y={...g,before:[],after:[]};for(const v of Dg(y.name,y.aliases))h[v]=y;f.push(y)}),f.forEach(g=>{if(g.toMiddleware){const y=h[g.toMiddleware];if(y===void 0){if(d)return;throw new Error(`${g.toMiddleware} is not found when adding ${qm(g.name,g.aliases)} middleware ${g.relation} ${g.toMiddleware}`)}g.relation==="after"&&y.after.push(g),g.relation==="before"&&y.before.push(g)}}),r(p).map(o).reduce((g,y)=>(g.push(...y),g),[])},u={add:(d,p={})=>{const{name:f,override:h,aliases:m}=p,g={step:"initialize",priority:"normal",middleware:d,...p},y=Dg(f,m);if(y.length>0){if(y.some(v=>i.has(v))){if(!h)throw new Error(`Duplicate middleware name '${qm(f,m)}'`);for(const v of y){const b=e.findIndex(x=>x.name===v||x.aliases?.some(C=>C===v));if(b===-1)continue;const w=e[b];if(w.step!==g.step||g.priority!==w.priority)throw new Error(`"${qm(w.name,w.aliases)}" middleware with ${w.priority} priority in ${w.step} step cannot be overridden by "${qm(f,m)}" middleware with ${g.priority} priority in ${g.step} step.`);e.splice(b,1)}}for(const v of y)i.add(v)}e.push(g)},addRelativeTo:(d,p)=>{const{name:f,override:h,aliases:m}=p,g={middleware:d,...p},y=Dg(f,m);if(y.length>0){if(y.some(v=>i.has(v))){if(!h)throw new Error(`Duplicate middleware name '${qm(f,m)}'`);for(const v of y){const b=t.findIndex(x=>x.name===v||x.aliases?.some(C=>C===v));if(b===-1)continue;const w=t[b];if(w.toMiddleware!==g.toMiddleware||w.relation!==g.relation)throw new Error(`"${qm(w.name,w.aliases)}" middleware ${w.relation} "${w.toMiddleware}" middleware cannot be overridden by "${qm(f,m)}" middleware ${g.relation} "${g.toMiddleware}" middleware.`);t.splice(b,1)}}for(const v of y)i.add(v)}t.push(g)},clone:()=>c(XT()),use:d=>{d.applyToStack(u)},remove:d=>typeof d=="string"?a(d):l(d),removeByTag:d=>{let p=!1;const f=h=>{const{tags:m,name:g,aliases:y}=h;if(m&&m.includes(d)){const v=Dg(g,y);for(const b of v)i.delete(b);return p=!0,!1}return!0};return e=e.filter(f),t=t.filter(f),p},concat:d=>{const p=c(XT());return p.use(d),p.identifyOnResolve(n||p.identifyOnResolve()||(d.identifyOnResolve?.()??!1)),p},applyToStack:c,identify:()=>s(!0).map(d=>{const p=d.step??d.relation+" "+d.toMiddleware;return qm(d.name,d.aliases)+" - "+p}),identifyOnResolve(d){return typeof d=="boolean"&&(n=d),n},resolve:(d,p)=>{for(const f of s().map(h=>h.middleware).reverse())d=f(d,p);return n&&console.log(u.identify()),d}};return u},TF={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},EF={high:3,normal:2,low:1};class MMe{config;middlewareStack=XT();initConfig;handlers;constructor(t){this.config=t;const{protocol:n,protocolSettings:i}=t;i&&typeof n=="function"&&(t.protocol=new n(i))}send(t,n,i){const r=typeof n!="function"?n:void 0,a=typeof n=="function"?n:i,l=r===void 0&&this.config.cacheMiddleware===!0;let c;if(l){this.handlers||(this.handlers=new WeakMap);const o=this.handlers;o.has(t.constructor)?c=o.get(t.constructor):(c=t.resolveMiddleware(this.middlewareStack,this.config,r),o.set(t.constructor,c))}else delete this.handlers,c=t.resolveMiddleware(this.middlewareStack,this.config,r);if(a)c(t).then(o=>a(null,o.output),o=>a(o)).catch(()=>{});else return c(t).then(o=>o.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}const Q6="***SensitiveInformation***";function iO(e,t){if(t==null)return t;const n=Mr.of(e);if(n.getMergedTraits().sensitive)return Q6;if(n.isListSchema()){if(!!n.getValueSchema().getMergedTraits().sensitive)return Q6}else if(n.isMapSchema()){if(!!n.getKeySchema().getMergedTraits().sensitive||!!n.getValueSchema().getMergedTraits().sensitive)return Q6}else if(n.isStructSchema()&&typeof t=="object"){const i=t,r={};for(const[a,l]of n.structIterator())i[a]!=null&&(r[a]=iO(l,i[a]));return r}return t}class kce{middlewareStack=XT();schema;static classBuilder(){return new NMe}resolveMiddlewareWithContext(t,n,i,{middlewareFn:r,clientName:a,commandName:l,inputFilterSensitiveLog:c,outputFilterSensitiveLog:o,smithyContext:s,additionalContext:u,CommandCtor:d}){for(const g of r.bind(this)(d,t,n,i))this.middlewareStack.use(g);const p=t.concat(this.middlewareStack),{logger:f}=n,h={logger:f,clientName:a,commandName:l,inputFilterSensitiveLog:c,outputFilterSensitiveLog:o,[eO]:{commandInstance:this,...s},...u},{requestHandler:m}=n;return p.resolve(g=>m.handle(g.request,i||{}),h)}}class NMe{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(t){this._init=t}ep(t){return this._ep=t,this}m(t){return this._middlewareFn=t,this}s(t,n,i={}){return this._smithyContext={service:t,operation:n,...i},this}c(t={}){return this._additionalContext=t,this}n(t,n){return this._clientName=t,this._commandName=n,this}f(t=i=>i,n=i=>i){return this._inputFilterSensitiveLog=t,this._outputFilterSensitiveLog=n,this}ser(t){return this._serializer=t,this}de(t){return this._deserializer=t,this}sc(t){return this._operationSchema=t,this._smithyContext.operationSchema=t,this}build(){const t=this;let n;return n=class extends kce{input;static getEndpointParameterInstructions(){return t._ep}constructor(...[i]){super(),this.input=i??{},t._init(this),this.schema=t._operationSchema}resolveMiddleware(i,r,a){const l=t._operationSchema,c=l?.[4]??l?.input,o=l?.[5]??l?.output;return this.resolveMiddlewareWithContext(i,r,a,{CommandCtor:n,middlewareFn:t._middlewareFn,clientName:t._clientName,commandName:t._commandName,inputFilterSensitiveLog:t._inputFilterSensitiveLog??(l?iO.bind(null,c):s=>s),outputFilterSensitiveLog:t._outputFilterSensitiveLog??(l?iO.bind(null,o):s=>s),smithyContext:t._smithyContext,additionalContext:t._additionalContext})}serialize=t._serializer;deserialize=t._deserializer}}}class fb extends Error{$fault;$response;$retryable;$metadata;constructor(t){super(t.message),Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=t.name,this.$fault=t.$fault,this.$metadata=t.$metadata}static isInstance(t){if(!t)return!1;const n=t;return fb.prototype.isPrototypeOf(n)||!!n.$fault&&!!n.$metadata&&(n.$fault==="client"||n.$fault==="server")}static[Symbol.hasInstance](t){if(!t)return!1;const n=t;return this===fb?fb.isInstance(t):fb.isInstance(t)?n.name&&this.name?this.prototype.isPrototypeOf(t)||n.name===this.name:this.prototype.isPrototypeOf(t):!1}}const kF=(e,t={})=>{Object.entries(t).filter(([,i])=>i!==void 0).forEach(([i,r])=>{(e[i]==null||e[i]==="")&&(e[i]=r)});const n=e.message||e.Message||"UnknownError";return e.message=n,delete e.Message,e},$Me=e=>{switch(e){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}},Ace=Object.values(D_),DMe=e=>{const t=[];for(const n in D_){const i=D_[n];e[i]!==void 0&&t.push({algorithmId:()=>i,checksumConstructor:()=>e[i]})}for(const[n,i]of Object.entries(e.checksumAlgorithms??{}))t.push({algorithmId:()=>n,checksumConstructor:()=>i});return{addChecksumAlgorithm(n){e.checksumAlgorithms=e.checksumAlgorithms??{};const i=n.algorithmId(),r=n.checksumConstructor();Ace.includes(i)?e.checksumAlgorithms[i.toUpperCase()]=r:e.checksumAlgorithms[i]=r,t.push(n)},checksumAlgorithms(){return t}}},jMe=e=>{const t={};return e.checksumAlgorithms().forEach(n=>{const i=n.algorithmId();Ace.includes(i)&&(t[i]=n.checksumConstructor())}),t},LMe=e=>({setRetryStrategy(t){e.retryStrategy=t},retryStrategy(){return e.retryStrategy}}),UMe=e=>{const t={};return t.retryStrategy=e.retryStrategy(),t},FMe=e=>Object.assign(DMe(e),LMe(e)),qMe=e=>Object.assign(jMe(e),UMe(e));class Rce{trace(){}debug(){}info(){}warn(){}error(){}}class BMe{queryCompat;constructor(t=!1){this.queryCompat=t}resolveRestContentType(t,n){const i=n.getMemberSchemas(),r=Object.values(i).find(a=>!!a.getMergedTraits().httpPayload);if(r){const a=r.getMergedTraits().mediaType;return a||(r.isStringSchema()?"text/plain":r.isBlobSchema()?"application/octet-stream":t)}else if(!n.isUnitSchema()&&Object.values(i).find(l=>{const{httpQuery:c,httpQueryParams:o,httpHeader:s,httpLabel:u,httpPrefixHeaders:d}=l.getMergedTraits();return!c&&!o&&!s&&!u&&d===void 0}))return t}async getErrorSchemaOrThrowBaseException(t,n,i,r,a,l){let c=n,o=t;t.includes("#")&&([c,o]=t.split("#"));const s={$metadata:a,$fault:i.statusCode<500?"client":"server"},u=Ua.for(c);try{return{errorSchema:l?.(u,o)??u.getSchema(t),errorMetadata:s}}catch{r.message=r.message??r.Message??"UnknownError";const p=Ua.for("smithy.ts.sdk.synthetic."+c),f=p.getBaseException();if(f){const h=p.getErrorCtor(f)??Error;throw this.decorateServiceException(Object.assign(new h({name:o}),s),r)}throw this.decorateServiceException(Object.assign(new Error(o),s),r)}}decorateServiceException(t,n={}){if(this.queryCompat){const i=t.Message??n.Message,r=kF(t,n);i&&(r.message=i),r.Error={...r.Error,Type:r.Error?.Type,Code:r.Error?.Code,Message:r.Error?.message??r.Error?.Message??i};const a=r.$metadata.requestId;return a&&(r.RequestId=a),r}return kF(t,n)}setQueryCompatError(t,n){const i=n.headers?.["x-amzn-query-error"];if(t!==void 0&&i!=null){const[r,a]=i.split(";"),l=Object.entries(t),c={Code:r,Type:a};Object.assign(t,c);for(const[o,s]of l)c[o==="message"?"Message":o]=s;delete c.__type,t.Error=c}}queryCompatOutput(t,n){t.Error&&(n.Error=t.Error),t.Type&&(n.Type=t.Type),t.Code&&(n.Code=t.Code)}findQueryCompatibleError(t,n){try{return t.getSchema(n)}catch{return t.find(r=>Mr.of(r).getMergedTraits().awsQueryError?.[0]===n)}}}class C8{serdeContext;setSerdeContext(t){this.serdeContext=t}}class WMe{from;to;keys;constructor(t,n){this.from=t,this.to=n,this.keys=new Set(Object.keys(this.from).filter(i=>i!=="__type"))}mark(t){this.keys.delete(t)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){const t=this.keys.values().next().value,n=this.from[t];this.to.$unknown=[t,n]}}}function zMe(e,t,n){if(n?.source){const i=n.source;if(typeof t=="number"&&(t>Number.MAX_SAFE_INTEGER||t<Number.MIN_SAFE_INTEGER||i!==String(t)))return i.includes(".")?new Co(i,"bigDecimal"):BigInt(i)}return t}const GMe=(e,t)=>Jw(e,t).then(n=>(t?.utf8Encoder??Kb)(n)),HMe=(e,t)=>GMe(e,t).then(n=>{if(n.length)try{return JSON.parse(n)}catch(i){throw i?.name==="SyntaxError"&&Object.defineProperty(i,"$responseBodyText",{value:n}),i}return{}}),VMe=(e,t)=>{const n=(a,l)=>Object.keys(a).find(c=>c.toLowerCase()===l.toLowerCase()),i=a=>{let l=a;return typeof l=="number"&&(l=l.toString()),l.indexOf(",")>=0&&(l=l.split(",")[0]),l.indexOf(":")>=0&&(l=l.split(":")[0]),l.indexOf("#")>=0&&(l=l.split("#")[1]),l},r=n(e.headers,"x-amzn-errortype");if(r!==void 0)return i(e.headers[r]);if(t&&typeof t=="object"){const a=n(t,"code");if(a&&t[a]!==void 0)return i(t[a]);if(t.__type!==void 0)return i(t.__type)}};class JMe extends C8{settings;constructor(t){super(),this.settings=t}async read(t,n){return this._read(t,typeof n=="string"?JSON.parse(n,zMe):await HMe(n,this.serdeContext))}readObject(t,n){return this._read(t,n)}_read(t,n){const i=n!==null&&typeof n=="object",r=Mr.of(t);if(i){if(r.isStructSchema()){const l=n,c=r.isUnionSchema(),o={};let s;const{jsonName:u}=this.settings;u&&(s={});let d;c&&(d=new WMe(l,o));for(const[p,f]of r.structIterator()){let h=p;u&&(h=f.getMergedTraits().jsonName??h,s[h]=p),c&&d.mark(h),l[h]!=null&&(o[p]=this._read(f,l[h]))}if(c)d.writeUnknown();else if(typeof l.__type=="string")for(const[p,f]of Object.entries(l)){const h=u?s[p]??p:p;h in o||(o[h]=f)}return o}if(Array.isArray(n)&&r.isListSchema()){const l=r.getValueSchema(),c=[],o=!!r.getMergedTraits().sparse;for(const s of n)(o||s!=null)&&c.push(this._read(l,s));return c}if(r.isMapSchema()){const l=r.getValueSchema(),c={},o=!!r.getMergedTraits().sparse;for(const[s,u]of Object.entries(n))(o||u!=null)&&(c[s]=this._read(l,u));return c}}if(r.isBlobSchema()&&typeof n=="string")return Ly(n);const a=r.getMergedTraits().mediaType;if(r.isStringSchema()&&typeof n=="string"&&a)return a==="application/json"||a.endsWith("+json")?Ic.from(n):n;if(r.isTimestampSchema()&&n!=null)switch(wE(r,this.settings)){case 5:return q8e(n);case 6:return G8e(n);case 7:return H8e(n);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",n),new Date(n)}if(r.isBigIntegerSchema()&&(typeof n=="number"||typeof n=="string"))return BigInt(n);if(r.isBigDecimalSchema()&&n!=null){if(n instanceof Co)return n;const l=n;return l.type==="bigDecimal"&&"string"in l?new Co(l.string,l.type):new Co(String(n),"bigDecimal")}if(r.isNumericSchema()&&typeof n=="string"){switch(n){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return n}if(r.isDocumentSchema())if(i){const l=Array.isArray(n)?[]:{};for(const[c,o]of Object.entries(n))o instanceof Co?l[c]=o:l[c]=this._read(r,o);return l}else return structuredClone(n);return n}}const AF="Ν";class KMe{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw new Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(t,n)=>{if(n instanceof Co){const i=`${AF+"nv"+this.counter++}_`+n.string;return this.values.set(`"${i}"`,n.string),i}if(typeof n=="bigint"){const i=n.toString(),r=`${AF+"b"+this.counter++}_`+i;return this.values.set(`"${r}"`,i),r}return n}}replaceInJson(t){if(this.stage===0)throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return t;for(const[n,i]of this.values)t=t.replace(n,i);return t}}class ZMe extends C8{settings;buffer;useReplacer=!1;rootSchema;constructor(t){super(),this.settings=t}write(t,n){this.rootSchema=Mr.of(t),this.buffer=this._write(this.rootSchema,n)}writeDiscriminatedDocument(t,n){this.write(t,n),typeof this.buffer=="object"&&(this.buffer.__type=Mr.of(t).getName(!0))}flush(){const{rootSchema:t,useReplacer:n}=this;if(this.rootSchema=void 0,this.useReplacer=!1,t?.isStructSchema()||t?.isDocumentSchema()){if(!n)return JSON.stringify(this.buffer);const i=new KMe;return i.replaceInJson(JSON.stringify(this.buffer,i.createReplacer(),0))}return this.buffer}_write(t,n,i){const r=n!==null&&typeof n=="object",a=Mr.of(t);if(r){if(a.isStructSchema()){const l=n,c={},{jsonName:o}=this.settings;let s;o&&(s={});for(const[u,d]of a.structIterator()){const p=this._write(d,l[u],a);if(p!==void 0){let f=u;o&&(f=d.getMergedTraits().jsonName??u,s[u]=f),c[f]=p}}if(a.isUnionSchema()&&Object.keys(c).length===0){const{$unknown:u}=l;if(Array.isArray(u)){const[d,p]=u;c[d]=this._write(15,p)}}else if(typeof l.__type=="string")for(const[u,d]of Object.entries(l)){const p=o?s[u]??u:u;p in c||(c[p]=this._write(15,d))}return c}if(Array.isArray(n)&&a.isListSchema()){const l=a.getValueSchema(),c=[],o=!!a.getMergedTraits().sparse;for(const s of n)(o||s!=null)&&c.push(this._write(l,s));return c}if(a.isMapSchema()){const l=a.getValueSchema(),c={},o=!!a.getMergedTraits().sparse;for(const[s,u]of Object.entries(n))(o||u!=null)&&(c[s]=this._write(l,u));return c}if(n instanceof Uint8Array&&(a.isBlobSchema()||a.isDocumentSchema()))return a===this.rootSchema?n:(this.serdeContext?.base64Encoder??Fy)(n);if(n instanceof Date&&(a.isTimestampSchema()||a.isDocumentSchema()))switch(wE(a,this.settings)){case 5:return n.toISOString().replace(".000Z","Z");case 6:return tce(n);case 7:return n.getTime()/1e3;default:return console.warn("Missing timestamp format, using epoch seconds",n),n.getTime()/1e3}n instanceof Co&&(this.useReplacer=!0)}if(!(n===null&&i?.isStructSchema())){if(a.isStringSchema()){if(typeof n>"u"&&a.isIdempotencyToken())return v8();const l=a.getMergedTraits().mediaType;return n!=null&&l&&(l==="application/json"||l.endsWith("+json"))?Ic.from(n):n}if(typeof n=="number"&&a.isNumericSchema())return Math.abs(n)===1/0||isNaN(n)?String(n):n;if(typeof n=="string"&&a.isBlobSchema())return a===this.rootSchema?n:(this.serdeContext?.base64Encoder??Fy)(n);if(typeof n=="bigint"&&(this.useReplacer=!0),a.isDocumentSchema())if(r){const l=Array.isArray(n)?[]:{};for(const[c,o]of Object.entries(n))o instanceof Co?(this.useReplacer=!0,l[c]=o):l[c]=this._write(a,o);return l}else return structuredClone(n);return n}}}class XMe extends C8{settings;constructor(t){super(),this.settings=t}createSerializer(){const t=new ZMe(this.settings);return t.setSerdeContext(this.serdeContext),t}createDeserializer(){const t=new JMe(this.settings);return t.setSerdeContext(this.serdeContext),t}}class QMe extends p7e{serializer;deserializer;codec;mixin=new BMe;constructor({defaultNamespace:t}){super({defaultNamespace:t});const n={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=new XMe(n),this.serializer=new g7e(this.codec.createSerializer(),n),this.deserializer=new h7e(this.codec.createDeserializer(),n)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(t){this.codec.setSerdeContext(t),super.setSerdeContext(t)}async serializeRequest(t,n,i){const r=await super.serializeRequest(t,n,i),a=Mr.of(t.input);if(!r.headers["content-type"]){const l=this.mixin.resolveRestContentType(this.getDefaultContentType(),a);l&&(r.headers["content-type"]=l)}return r.body==null&&r.headers["content-type"]===this.getDefaultContentType()&&(r.body="{}"),r}async deserializeResponse(t,n,i){const r=await super.deserializeResponse(t,n,i),a=Mr.of(t.output);for(const[l,c]of a.structIterator())c.getMemberTraits().httpPayload&&!(l in r)&&(r[l]=null);return r}async handleError(t,n,i,r,a){const l=VMe(i,r)??"Unknown",{errorSchema:c,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(l,this.options.defaultNamespace,i,r,a),s=Mr.of(c),u=r.message??r.Message??"Unknown",d=Ua.for(c[1]).getErrorCtor(c)??Error,p=new d(u);await this.deserializeHttpMessage(c,n,i,r);const f={};for(const[h,m]of s.structIterator()){const g=m.getMergedTraits().jsonName??h;f[h]=this.codec.createDeserializer().readObject(m,r[g])}throw this.mixin.decorateServiceException(Object.assign(p,o,{$fault:s.getMergedTraits().error,message:u},f),r)}getDefaultContentType(){return"application/json"}}const YMe=/\d{12}\.ddb/;async function eNe(e,t,n){if(n.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor"&&Bo(e,"PROTOCOL_RPC_V2_CBOR","M"),typeof t.retryStrategy=="function"){const a=await t.retryStrategy();typeof a.acquireInitialRetryToken=="function"?a.constructor?.name?.includes("Adaptive")?Bo(e,"RETRY_MODE_ADAPTIVE","F"):Bo(e,"RETRY_MODE_STANDARD","E"):Bo(e,"RETRY_MODE_LEGACY","D")}if(typeof t.accountIdEndpointMode=="function"){const a=e.endpointV2;switch(String(a?.url?.hostname).match(YMe)&&Bo(e,"ACCOUNT_ID_ENDPOINT","O"),await t.accountIdEndpointMode?.()){case"disabled":Bo(e,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":Bo(e,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":Bo(e,"ACCOUNT_ID_MODE_REQUIRED","R");break}}const r=e.__smithy_context?.selectedHttpAuthScheme?.identity;if(r?.$source){const a=r;a.accountId&&Bo(e,"RESOLVED_ACCOUNT_ID","T");for(const[l,c]of Object.entries(a.$source??{}))Bo(e,l,c)}}const RF="user-agent",Y6="x-amz-user-agent",OF=" ",eA="/",tNe=/[^!$%&'*+\-.^_`|~\w]/g,nNe=/[^!$%&'*+\-.^_`|~\w#]/g,IF="-",rNe=1024;function iNe(e){let t="";for(const n in e){const i=e[n];if(t.length+i.length+1<=rNe){t.length?t+=","+i:t+=i;continue}break}return t}const aNe=e=>(t,n)=>async i=>{const{request:r}=i;if(!Ea.isInstance(r))return t(i);const{headers:a}=r,l=n?.userAgent?.map(Fx)||[],c=(await e.defaultUserAgentProvider()).map(Fx);await eNe(n,e,i);const o=n;c.push(`m/${iNe(Object.assign({},n.__smithy_context?.features,o.__aws_sdk_context?.features))}`);const s=e?.customUserAgent?.map(Fx)||[],u=await e.userAgentAppId();u&&c.push(Fx(["app",`${u}`]));const d=[].concat([...c,...l,...s]).join(OF),p=[...c.filter(f=>f.startsWith("aws-sdk-")),...s].join(OF);return e.runtime!=="browser"?(p&&(a[Y6]=a[Y6]?`${a[RF]} ${p}`:p),a[RF]=d):a[Y6]=d,t({...i,request:r})},Fx=e=>{const t=e[0].split(eA).map(l=>l.replace(tNe,IF)).join(eA),n=e[1]?.replace(nNe,IF),i=t.indexOf(eA),r=t.substring(0,i);let a=t.substring(i+1);return r==="api"&&(a=a.toLowerCase()),[r,a,n].filter(l=>l&&l.length>0).reduce((l,c,o)=>{switch(o){case 0:return c;case 1:return`${l}/${c}`;default:return`${l}#${c}`}},"")},sNe={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},oNe=e=>({applyToStack:t=>{t.add(aNe(e),sNe)}});function lNe(e){const{port:t,query:n}=e;let{protocol:i,path:r,hostname:a}=e;i&&i.slice(-1)!==":"&&(i+=":"),t&&(a+=`:${t}`),r&&r.charAt(0)!=="/"&&(r=`/${r}`);let l=n?Zle(n):"";l&&l[0]!=="?"&&(l=`?${l}`);let c="";if(e.username!=null||e.password!=null){const s=e.username??"",u=e.password??"";c=`${s}:${u}@`}let o="";return e.fragment&&(o=`#${e.fragment}`),`${i}//${c}${a}${r}${l}${o}`}var aO=function(e,t){return aO=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(n[r]=i[r])},aO(e,t)};function Oce(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");aO(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var QT=function(){return QT=Object.assign||function(t){for(var n,i=1,r=arguments.length;i<r;i++){n=arguments[i];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},QT.apply(this,arguments)};function Ice(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]]);return n}function Pce(e,t,n,i){var r=arguments.length,a=r<3?t:i===null?i=Object.getOwnPropertyDescriptor(t,n):i,l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(e,t,n,i);else for(var c=e.length-1;c>=0;c--)(l=e[c])&&(a=(r<3?l(a):r>3?l(t,n,a):l(t,n))||a);return r>3&&a&&Object.defineProperty(t,n,a),a}function Mce(e,t){return function(n,i){t(n,i,e)}}function Nce(e,t,n,i,r,a){function l(y){if(y!==void 0&&typeof y!="function")throw new TypeError("Function expected");return y}for(var c=i.kind,o=c==="getter"?"get":c==="setter"?"set":"value",s=!t&&e?i.static?e:e.prototype:null,u=t||(s?Object.getOwnPropertyDescriptor(s,i.name):{}),d,p=!1,f=n.length-1;f>=0;f--){var h={};for(var m in i)h[m]=m==="access"?{}:i[m];for(var m in i.access)h.access[m]=i.access[m];h.addInitializer=function(y){if(p)throw new TypeError("Cannot add initializers after decoration has completed");a.push(l(y||null))};var g=(0,n[f])(c==="accessor"?{get:u.get,set:u.set}:u[o],h);if(c==="accessor"){if(g===void 0)continue;if(g===null||typeof g!="object")throw new TypeError("Object expected");(d=l(g.get))&&(u.get=d),(d=l(g.set))&&(u.set=d),(d=l(g.init))&&r.unshift(d)}else(d=l(g))&&(c==="field"?r.unshift(d):u[o]=d)}s&&Object.defineProperty(s,i.name,u),p=!0}function $ce(e,t,n){for(var i=arguments.length>2,r=0;r<t.length;r++)n=i?t[r].call(e,n):t[r].call(e);return i?n:void 0}function Dce(e){return typeof e=="symbol"?e:"".concat(e)}function jce(e,t,n){return typeof t=="symbol"&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:n?"".concat(n," ",t):t})}function Lce(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}function T8(e,t,n,i){function r(a){return a instanceof n?a:new n(function(l){l(a)})}return new(n||(n=Promise))(function(a,l){function c(u){try{s(i.next(u))}catch(d){l(d)}}function o(u){try{s(i.throw(u))}catch(d){l(d)}}function s(u){u.done?a(u.value):r(u.value).then(c,o)}s((i=i.apply(e,t||[])).next())})}function E8(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,r,a,l=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return l.next=c(0),l.throw=c(1),l.return=c(2),typeof Symbol=="function"&&(l[Symbol.iterator]=function(){return this}),l;function c(s){return function(u){return o([s,u])}}function o(s){if(i)throw new TypeError("Generator is already executing.");for(;l&&(l=0,s[0]&&(n=0)),n;)try{if(i=1,r&&(a=s[0]&2?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return n.label++,{value:s[1],done:!1};case 5:n.label++,r=s[1],s=[0];continue;case 7:s=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>0&&a[a.length-1])&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){n.label=s[1];break}if(s[0]===6&&n.label<a[1]){n.label=a[1],a=s;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(s);break}a[2]&&n.ops.pop(),n.trys.pop();continue}s=t.call(e,n)}catch(u){s=[6,u],r=0}finally{i=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}var SE=Object.create?(function(e,t,n,i){i===void 0&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}):(function(e,t,n,i){i===void 0&&(i=n),e[i]=t[n]});function Uce(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&SE(t,e,n)}function q_(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function k8(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,a=[],l;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(c){l={error:c}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(l)throw l.error}}return a}function Fce(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(k8(arguments[t]));return e}function qce(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var i=Array(e),r=0,t=0;t<n;t++)for(var a=arguments[t],l=0,c=a.length;l<c;l++,r++)i[r]=a[l];return i}function Bce(e,t,n){if(n||arguments.length===2)for(var i=0,r=t.length,a;i<r;i++)(a||!(i in t))&&(a||(a=Array.prototype.slice.call(t,0,i)),a[i]=t[i]);return e.concat(a||Array.prototype.slice.call(t))}function Ob(e){return this instanceof Ob?(this.v=e,this):new Ob(e)}function Wce(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(e,t||[]),r,a=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",l),r[Symbol.asyncIterator]=function(){return this},r;function l(f){return function(h){return Promise.resolve(h).then(f,d)}}function c(f,h){i[f]&&(r[f]=function(m){return new Promise(function(g,y){a.push([f,m,g,y])>1||o(f,m)})},h&&(r[f]=h(r[f])))}function o(f,h){try{s(i[f](h))}catch(m){p(a[0][3],m)}}function s(f){f.value instanceof Ob?Promise.resolve(f.value.v).then(u,d):p(a[0][2],f)}function u(f){o("next",f)}function d(f){o("throw",f)}function p(f,h){f(h),a.shift(),a.length&&o(a[0][0],a[0][1])}}function zce(e){var t,n;return t={},i("next"),i("throw",function(r){throw r}),i("return"),t[Symbol.iterator]=function(){return this},t;function i(r,a){t[r]=e[r]?function(l){return(n=!n)?{value:Ob(e[r](l)),done:!1}:a?a(l):l}:a}}function Gce(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof q_=="function"?q_(e):e[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(a){n[a]=e[a]&&function(l){return new Promise(function(c,o){l=e[a](l),r(c,o,l.done,l.value)})}}function r(a,l,c,o){Promise.resolve(o).then(function(s){a({value:s,done:c})},l)}}function Hce(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}var cNe=Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t},sO=function(e){return sO=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},sO(e)};function Vce(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=sO(e),i=0;i<n.length;i++)n[i]!=="default"&&SE(t,e,n[i]);return cNe(t,e),t}function Jce(e){return e&&e.__esModule?e:{default:e}}function Kce(e,t,n,i){if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?i:n==="a"?i.call(e):i?i.value:t.get(e)}function Zce(e,t,n,i,r){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?r.call(e,n):r?r.value=n:t.set(e,n),n}function Xce(e,t){if(t===null||typeof t!="object"&&typeof t!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof e=="function"?t===e:e.has(t)}function Qce(e,t,n){if(t!=null){if(typeof t!="object"&&typeof t!="function")throw new TypeError("Object expected.");var i,r;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=t[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=t[Symbol.dispose],n&&(r=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");r&&(i=function(){try{r.call(this)}catch(a){return Promise.reject(a)}}),e.stack.push({value:t,dispose:i,async:n})}else n&&e.stack.push({async:!0});return t}var uNe=typeof SuppressedError=="function"?SuppressedError:function(e,t,n){var i=new Error(n);return i.name="SuppressedError",i.error=e,i.suppressed=t,i};function Yce(e){function t(a){e.error=e.hasError?new uNe(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function r(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(r);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(r,function(l){return t(l),r()})}else i|=1}catch(l){t(l)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return r()}function eue(e,t){return typeof e=="string"&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(n,i,r,a,l){return i?t?".jsx":".js":r&&(!a||!l)?n:r+a+"."+l.toLowerCase()+"js"}):e}const dNe={__extends:Oce,__assign:QT,__rest:Ice,__decorate:Pce,__param:Mce,__esDecorate:Nce,__runInitializers:$ce,__propKey:Dce,__setFunctionName:jce,__metadata:Lce,__awaiter:T8,__generator:E8,__createBinding:SE,__exportStar:Uce,__values:q_,__read:k8,__spread:Fce,__spreadArrays:qce,__spreadArray:Bce,__await:Ob,__asyncGenerator:Wce,__asyncDelegator:zce,__asyncValues:Gce,__makeTemplateObject:Hce,__importStar:Vce,__importDefault:Jce,__classPrivateFieldGet:Kce,__classPrivateFieldSet:Zce,__classPrivateFieldIn:Xce,__addDisposableResource:Qce,__disposeResources:Yce,__rewriteRelativeImportExtension:eue},I3t=Object.freeze(Object.defineProperty({__proto__:null,__addDisposableResource:Qce,get __assign(){return QT},__asyncDelegator:zce,__asyncGenerator:Wce,__asyncValues:Gce,__await:Ob,__awaiter:T8,__classPrivateFieldGet:Kce,__classPrivateFieldIn:Xce,__classPrivateFieldSet:Zce,__createBinding:SE,__decorate:Pce,__disposeResources:Yce,__esDecorate:Nce,__exportStar:Uce,__extends:Oce,__generator:E8,__importDefault:Jce,__importStar:Vce,__makeTemplateObject:Hce,__metadata:Lce,__param:Mce,__propKey:Dce,__read:k8,__rest:Ice,__rewriteRelativeImportExtension:eue,__runInitializers:$ce,__setFunctionName:jce,__spread:Fce,__spreadArray:Bce,__spreadArrays:qce,__values:q_,default:dNe},Symbol.toStringTag,{value:"Module"})),pNe=e=>new TextEncoder().encode(e);var fNe=typeof Buffer<"u"&&Buffer.from?function(e){return Buffer.from(e,"utf8")}:pNe;function B_(e){return e instanceof Uint8Array?e:typeof e=="string"?fNe(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}function oO(e){return typeof e=="string"?e.length===0:e.byteLength===0}function hNe(e){if(!Uint32Array.from){for(var t=new Uint32Array(e.length),n=0;n<e.length;)t[n]=e[n],n+=1;return t}return Uint32Array.from(e)}var tue=(function(){function e(){this.checksum=4294967295}return e.prototype.update=function(t){var n,i;try{for(var r=q_(t),a=r.next();!a.done;a=r.next()){var l=a.value;this.checksum=this.checksum>>>8^gNe[(this.checksum^l)&255]}}catch(c){n={error:c}}finally{try{a&&!a.done&&(i=r.return)&&i.call(r)}finally{if(n)throw n.error}}return this},e.prototype.digest=function(){return(this.checksum^4294967295)>>>0},e})(),mNe=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117],gNe=hNe(mNe);class x_{bytes;constructor(t){if(this.bytes=t,t.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(t){if(t>9223372036854776e3||t<-9223372036854776e3)throw new Error(`${t} is too large (or, if negative, too small) to represent as an Int64`);const n=new Uint8Array(8);for(let i=7,r=Math.abs(Math.round(t));i>-1&&r>0;i--,r/=256)n[i]=r;return t<0&&PF(n),new x_(n)}valueOf(){const t=this.bytes.slice(0),n=t[0]&128;return n&&PF(t),parseInt(qa(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function PF(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,e[t]===0);t--);}class yNe{toUtf8;fromUtf8;constructor(t,n){this.toUtf8=t,this.fromUtf8=n}format(t){const n=[];for(const a of Object.keys(t)){const l=this.fromUtf8(a);n.push(Uint8Array.from([l.byteLength]),l,this.formatHeaderValue(t[a]))}const i=new Uint8Array(n.reduce((a,l)=>a+l.byteLength,0));let r=0;for(const a of n)i.set(a,r),r+=a.byteLength;return i}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?0:1]);case"byte":return Uint8Array.from([2,t.value]);case"short":const n=new DataView(new ArrayBuffer(3));return n.setUint8(0,3),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":const i=new DataView(new ArrayBuffer(5));return i.setUint8(0,4),i.setInt32(1,t.value,!1),new Uint8Array(i.buffer);case"long":const r=new Uint8Array(9);return r[0]=5,r.set(t.value.bytes,1),r;case"binary":const a=new DataView(new ArrayBuffer(3+t.value.byteLength));a.setUint8(0,6),a.setUint16(1,t.value.byteLength,!1);const l=new Uint8Array(a.buffer);return l.set(t.value,3),l;case"string":const c=this.fromUtf8(t.value),o=new DataView(new ArrayBuffer(3+c.byteLength));o.setUint8(0,7),o.setUint16(1,c.byteLength,!1);const s=new Uint8Array(o.buffer);return s.set(c,3),s;case"timestamp":const u=new Uint8Array(9);return u[0]=8,u.set(x_.fromNumber(t.value.valueOf()).bytes,1),u;case"uuid":if(!ENe.test(t.value))throw new Error(`Invalid UUID received: ${t.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(g8(t.value.replace(/\-/g,"")),1),d}}parse(t){const n={};let i=0;for(;i<t.byteLength;){const r=t.getUint8(i++),a=this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+i,r));switch(i+=r,t.getUint8(i++)){case 0:n[a]={type:NF,value:!0};break;case 1:n[a]={type:NF,value:!1};break;case 2:n[a]={type:vNe,value:t.getInt8(i++)};break;case 3:n[a]={type:bNe,value:t.getInt16(i,!1)},i+=2;break;case 4:n[a]={type:wNe,value:t.getInt32(i,!1)},i+=4;break;case 5:n[a]={type:_Ne,value:new x_(new Uint8Array(t.buffer,t.byteOffset+i,8))},i+=8;break;case 6:const l=t.getUint16(i,!1);i+=2,n[a]={type:xNe,value:new Uint8Array(t.buffer,t.byteOffset+i,l)},i+=l;break;case 7:const c=t.getUint16(i,!1);i+=2,n[a]={type:SNe,value:this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+i,c))},i+=c;break;case 8:n[a]={type:CNe,value:new Date(new x_(new Uint8Array(t.buffer,t.byteOffset+i,8)).valueOf())},i+=8;break;case 9:const o=new Uint8Array(t.buffer,t.byteOffset+i,16);i+=16,n[a]={type:TNe,value:`${qa(o.subarray(0,4))}-${qa(o.subarray(4,6))}-${qa(o.subarray(6,8))}-${qa(o.subarray(8,10))}-${qa(o.subarray(10))}`};break;default:throw new Error("Unrecognized header type tag")}}return n}}var MF;(function(e){e[e.boolTrue=0]="boolTrue",e[e.boolFalse=1]="boolFalse",e[e.byte=2]="byte",e[e.short=3]="short",e[e.integer=4]="integer",e[e.long=5]="long",e[e.byteArray=6]="byteArray",e[e.string=7]="string",e[e.timestamp=8]="timestamp",e[e.uuid=9]="uuid"})(MF||(MF={}));const NF="boolean",vNe="byte",bNe="short",wNe="integer",_Ne="long",xNe="binary",SNe="string",CNe="timestamp",TNe="uuid",ENe=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,nue=4,Xm=nue*2,ay=4,kNe=Xm+ay*2;function ANe({byteLength:e,byteOffset:t,buffer:n}){if(e<kNe)throw new Error("Provided message too short to accommodate event stream message overhead");const i=new DataView(n,t,e),r=i.getUint32(0,!1);if(e!==r)throw new Error("Reported message length does not match received message length");const a=i.getUint32(nue,!1),l=i.getUint32(Xm,!1),c=i.getUint32(e-ay,!1),o=new tue().update(new Uint8Array(n,t,Xm));if(l!==o.digest())throw new Error(`The prelude checksum specified in the message (${l}) does not match the calculated CRC32 checksum (${o.digest()})`);if(o.update(new Uint8Array(n,t+Xm,e-(Xm+ay))),c!==o.digest())throw new Error(`The message checksum (${o.digest()}) did not match the expected value of ${c}`);return{headers:new DataView(n,t+Xm+ay,a),body:new Uint8Array(n,t+Xm+ay+a,r-a-(Xm+ay+ay))}}class rue{headerMarshaller;messageBuffer;isEndOfStream;constructor(t,n){this.headerMarshaller=new yNe(t,n),this.messageBuffer=[],this.isEndOfStream=!1}feed(t){this.messageBuffer.push(this.decode(t))}endOfStream(){this.isEndOfStream=!0}getMessage(){const t=this.messageBuffer.pop(),n=this.isEndOfStream;return{getMessage(){return t},isEndOfStream(){return n}}}getAvailableMessages(){const t=this.messageBuffer;this.messageBuffer=[];const n=this.isEndOfStream;return{getMessages(){return t},isEndOfStream(){return n}}}encode({headers:t,body:n}){const i=this.headerMarshaller.format(t),r=i.byteLength+n.byteLength+16,a=new Uint8Array(r),l=new DataView(a.buffer,a.byteOffset,a.byteLength),c=new tue;return l.setUint32(0,r,!1),l.setUint32(4,i.byteLength,!1),l.setUint32(8,c.update(a.subarray(0,8)).digest(),!1),a.set(i,12),a.set(n,i.byteLength+12),l.setUint32(r-4,c.update(a.subarray(8,r-4)).digest(),!1),a}decode(t){const{headers:n,body:i}=ANe(t);return{headers:this.headerMarshaller.parse(n),body:i}}formatHeaders(t){return this.headerMarshaller.format(t)}}class RNe{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const t of this.options.inputStream)yield this.options.decoder.decode(t)}}class ONe{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const t of this.options.messageStream)yield this.options.encoder.encode(t);this.options.includeEndFrame&&(yield new Uint8Array(0))}}class INe{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const t of this.options.messageStream){const n=await this.options.deserializer(t);n!==void 0&&(yield n)}}}class PNe{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const t of this.options.inputStream)yield this.options.serializer(t)}}function MNe(e){let t=0,n=0,i=null,r=null;const a=c=>{if(typeof c!="number")throw new Error("Attempted to allocate an event message where size was not a number: "+c);t=c,n=4,i=new Uint8Array(c),new DataView(i.buffer).setUint32(0,c,!1)},l=async function*(){const c=e[Symbol.asyncIterator]();for(;;){const{value:o,done:s}=await c.next();if(s){if(t)if(t===n)yield i;else throw new Error("Truncated event message received.");else return;return}const u=o.length;let d=0;for(;d<u;){if(!i){const f=u-d;r||(r=new Uint8Array(4));const h=Math.min(4-n,f);if(r.set(o.slice(d,d+h),n),n+=h,d+=h,n<4)break;a(new DataView(r.buffer).getUint32(0,!1)),r=null}const p=Math.min(t-n,u-d);i.set(o.slice(d,d+p),n),n+=p,d+=p,t&&t===n&&(yield i,i=null,t=0,n=0)}}};return{[Symbol.asyncIterator]:l}}function NNe(e,t){return async function(n){const{value:i}=n.headers[":message-type"];if(i==="error"){const r=new Error(n.headers[":error-message"].value||"UnknownError");throw r.name=n.headers[":error-code"].value,r}else if(i==="exception"){const r=n.headers[":exception-type"].value,a={[r]:n},l=await e(a);if(l.$unknown){const c=new Error(t(n.body));throw c.name=r,c}throw l[r]}else if(i==="event"){const r={[n.headers[":event-type"].value]:n},a=await e(r);return a.$unknown?void 0:a}else throw Error(`Unrecognizable event type: ${n.headers[":event-type"].value}`)}}let $Ne=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:t,utf8Decoder:n}){this.eventStreamCodec=new rue(t,n),this.utfEncoder=t}deserialize(t,n){const i=MNe(t);return new INe({messageStream:new RNe({inputStream:i,decoder:this.eventStreamCodec}),deserializer:NNe(n,this.utfEncoder)})}serialize(t,n){return new ONe({messageStream:new PNe({inputStream:t,serializer:n}),encoder:this.eventStreamCodec,includeEndFrame:!0})}};const iue=e=>({[Symbol.asyncIterator]:async function*(){const t=e.getReader();try{for(;;){const{done:n,value:i}=await t.read();if(n)return;yield i}}finally{t.releaseLock()}}}),aue=e=>{const t=e[Symbol.asyncIterator]();return new ReadableStream({async pull(n){const{done:i,value:r}=await t.next();if(i)return n.close();n.enqueue(r)}})};class DNe{universalMarshaller;constructor({utf8Encoder:t,utf8Decoder:n}){this.universalMarshaller=new $Ne({utf8Decoder:n,utf8Encoder:t})}deserialize(t,n){const i=jNe(t)?iue(t):t;return this.universalMarshaller.deserialize(i,n)}serialize(t,n){const i=this.universalMarshaller.serialize(t,n);return typeof ReadableStream=="function"?aue(i):i}}const jNe=e=>typeof ReadableStream=="function"&&e instanceof ReadableStream,LNe=e=>new DNe(e),sue=e=>e.protocol==="ws:"||e.protocol==="wss:",UNe=3e3;class A8{metadata={handlerProtocol:"websocket/h1.1"};config={};configPromise;httpHandler;sockets={};static create(t,n=new L_){return typeof t?.handle=="function"?t:new A8(t,n)}constructor(t,n=new L_){this.httpHandler=n;const i=r=>(this.config={...r??{}},this.config);typeof t=="function"?(this.config={},this.configPromise=t().then(r=>i(r))):this.configPromise=Promise.resolve(i(t))}destroy(){for(const[t,n]of Object.entries(this.sockets)){for(const i of n)i.close(1e3,"Socket closed through destroy() call");delete this.sockets[t]}}async handle(t){this.config=await this.configPromise;const{logger:n}=this.config;if(!sue(t))return n?.debug?.(`@aws-sdk - ws fetching ${t.protocol}${t.hostname}${t.path}`),this.httpHandler.handle(t);const i=lNe(t);n?.debug?.(`@aws-sdk - ws connecting ${i.split("?")[0]}`);const r=new WebSocket(i);this.sockets[i]||(this.sockets[i]=[]),this.sockets[i].push(r),r.binaryType="arraybuffer";const{connectionTimeout:a=UNe}=this.config;await this.waitForReady(r,a);const{body:l}=t,c=FNe(l),o=this.connect(r,c),s=qNe(o);return{response:new jy({statusCode:200,body:s})}}updateHttpClientConfig(t,n){this.configPromise=this.configPromise.then(i=>(i[t]=n,i))}httpHandlerConfigs(){return this.config??{}}removeNotUsableSockets(t){this.sockets[t]=(this.sockets[t]??[]).filter(n=>![WebSocket.CLOSING,WebSocket.CLOSED].includes(n.readyState))}waitForReady(t,n){return new Promise((i,r)=>{const a=setTimeout(()=>{this.removeNotUsableSockets(t.url),r({$metadata:{httpStatusCode:500,websocketSynthetic500Error:!0}})},n);t.onopen=()=>{clearTimeout(a),i()}})}connect(t,n){const i=[];let r=null,a=null;const l=s=>{r?(s.error?a(s.error):r({done:s.done,value:s.value}),r=null,a=null):i.push(s)};t.onmessage=s=>{const{data:u}=s;l(typeof u=="string"?{done:!1,value:Ly(u)}:{done:!1,value:new Uint8Array(u)})},t.onerror=s=>{t.close(),l({done:!0,error:s})},t.onclose=()=>{this.removeNotUsableSockets(t.url),l({done:!0})};const c={[Symbol.asyncIterator]:()=>({async next(){if(i.length>0){const s=i.shift();if(s.error)throw s.error;return{done:s.done,value:s.value}}return new Promise((s,u)=>{r=s,a=u})}})};return(async()=>{try{for await(const s of n){if(t.readyState>=WebSocket.CLOSING)break;t.send(s)}}catch(s){l({done:!0,error:s})}finally{t.close(1e3)}})(),c}}const FNe=e=>e[Symbol.asyncIterator]?e:BNe(e)?iue(e):{[Symbol.asyncIterator]:async function*(){yield e}},qNe=e=>typeof ReadableStream=="function"?aue(e):e,BNe=e=>typeof ReadableStream=="function"&&e instanceof ReadableStream;class WNe{signer;constructor(t){this.signer=t.signer}presign(t,n={}){return this.signer.presign(t,n)}async sign(t,n){return Ea.isInstance(t)&&sue(t)?{...await this.signer.presign({...t,body:""},{...n,expiresIn:60,unsignableHeaders:new Set(Object.keys(t.headers).filter(r=>r!=="host"))}),body:t.body}:this.signer.sign(t,n)}signMessage(t,n){return this.signer.signMessage(t,n)}}const zNe=e=>{const{signer:t}=e;return Object.assign(e,{signer:async n=>{const i=await t(n);if(GNe(i))return new WNe({signer:i});throw new Error("Expected WebsocketSignatureV4 signer, please check the client constructor.")}})},GNe=e=>!!e;class HNe extends TransformStream{constructor(t,n,i,r){let a=t;super({start(){},async transform(l,c){try{const o=new Date(Date.now()+await r()),s={":date":{type:"timestamp",value:o}},u=await n.sign({message:{body:l,headers:s},priorSignature:a},{signingDate:o});a=u.signature;const d=i.encode({headers:{...s,":chunk-signature":{type:"binary",value:g8(u.signature)}},body:l});c.enqueue(d)}catch(o){c.error(o)}}})}}class VNe{messageSigner;eventStreamCodec;systemClockOffsetProvider;constructor(t){this.messageSigner=t.messageSigner,this.eventStreamCodec=new rue(t.utf8Encoder,t.utf8Decoder),this.systemClockOffsetProvider=async()=>t.systemClockOffset??0}async handle(t,n,i={}){const r=n.request,{body:a,headers:l,query:c}=r;if(!(a instanceof ReadableStream))throw new Error("Eventstream payload must be a ReadableStream.");const o=new TransformStream;r.body=o.readable;let u=((l?.authorization??"").match(/Signature=(\w+)$/)??[])[1]??(c&&c["X-Amz-Signature"])??"";i.__staticSignature&&(u="");const d=new HNe(u,await this.messageSigner(),this.eventStreamCodec,this.systemClockOffsetProvider);a.pipeThrough(d).pipeThrough(o);let p;try{p=await t(n)}catch(f){const h=a.cancel?.();throw h instanceof Promise&&h.catch(()=>{}),f}return p}}const JNe=e=>new VNe(e),KNe=!1,ZNe=!1,$F=new Set,XNe=(e,t=_E)=>{if(!$F.has(e)&&!t(e))if(e==="*")console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.');else throw new Error(`Region not accepted: region="${e}" is not a valid hostname component.`);else $F.add(e)},oue=e=>typeof e=="string"&&(e.startsWith("fips-")||e.endsWith("-fips")),QNe=e=>oue(e)?["fips-aws-global","aws-fips"].includes(e)?"us-east-1":e.replace(/fips-(dkr-|prod-)?|-fips/,""):e,YNe=e=>{const{region:t,useFipsEndpoint:n}=e;if(!t)throw new Error("Region is missing");return Object.assign(e,{region:async()=>{const i=typeof t=="function"?await t():t,r=QNe(i);return XNe(r),r},useFipsEndpoint:async()=>{const i=typeof t=="string"?t:await t();return oue(i)?!0:typeof n!="function"?Promise.resolve(!!n):n()}})},e$e=e=>Object.assign(e,{eventStreamMarshaller:e.eventStreamSerdeProvider(e)}),DF="content-length";function t$e(e){return t=>async n=>{const i=n.request;if(Ea.isInstance(i)){const{body:r,headers:a}=i;if(r&&Object.keys(a).map(l=>l.toLowerCase()).indexOf(DF)===-1)try{const l=e(r);i.headers={...i.headers,[DF]:String(l)}}catch{}}return t({...n,request:i})}}const n$e={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},r$e=e=>({applyToStack:t=>{t.add(t$e(e.bodyLengthChecker),n$e)}}),i$e=async e=>{const t=e?.Bucket||"";if(typeof e.Bucket=="string"&&(e.Bucket=t.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),c$e(t)){if(e.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!l$e(t)||t.indexOf(".")!==-1&&!String(e.Endpoint).startsWith("http:")||t.toLowerCase()!==t||t.length<3)&&(e.ForcePathStyle=!0);return e.DisableMultiRegionAccessPoints&&(e.disableMultiRegionAccessPoints=!0,e.DisableMRAP=!0),e},a$e=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,s$e=/(\d+\.){3}\d+/,o$e=/\.\./,l$e=e=>a$e.test(e)&&!s$e.test(e)&&!o$e.test(e),c$e=e=>{const[t,n,i,,,r]=e.split(":"),a=t==="arn"&&e.split(":").length>=6,l=!!(a&&n&&i&&r);if(a&&!l)throw new Error(`Invalid ARN: ${e} was an invalid ARN.`);return l},u$e=(e,t,n,i=!1)=>{const r=async()=>{let a;return i?a=n.clientContextParams?.[e]??n[e]??n[t]:a=n[e]??n[t],typeof a=="function"?a():a};return e==="credentialScope"||t==="CredentialScope"?async()=>{const a=typeof n.credentials=="function"?await n.credentials():n.credentials;return a?.credentialScope??a?.CredentialScope}:e==="accountId"||t==="AccountId"?async()=>{const a=typeof n.credentials=="function"?await n.credentials():n.credentials;return a?.accountId??a?.AccountId}:e==="endpoint"||t==="endpoint"?async()=>{if(n.isCustomEndpoint===!1)return;const a=await r();if(a&&typeof a=="object"){if("url"in a)return a.url.href;if("hostname"in a){const{protocol:l,hostname:c,port:o,path:s}=a;return`${l}//${c}${o?":"+o:""}${s}`}}return a}:r},lue=async e=>{},cue=e=>typeof e=="object"?"url"in e?ZT(e.url):e:ZT(e),d$e=async(e,t,n,i)=>{if(!n.isCustomEndpoint){let l;n.serviceConfiguredEndpoint?l=await n.serviceConfiguredEndpoint():l=await lue(n.serviceId),l&&(n.endpoint=()=>Promise.resolve(cue(l)),n.isCustomEndpoint=!0)}const r=await p$e(e,t,n);if(typeof n.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");return n.endpointProvider(r,i)},p$e=async(e,t,n)=>{const i={},r=t?.getEndpointParameterInstructions?.()||{};for(const[a,l]of Object.entries(r))switch(l.type){case"staticContextParams":i[a]=l.value;break;case"contextParams":i[a]=e[l.name];break;case"clientContextParams":case"builtInParams":i[a]=await u$e(l.name,a,n,l.type!=="builtInParams")();break;case"operationContextParams":i[a]=l.get(e);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(l))}return Object.keys(r).length===0&&Object.assign(i,n),String(n.serviceId).toLowerCase()==="s3"&&await i$e(i),i},f$e=({config:e,instructions:t})=>(n,i)=>async r=>{e.isCustomEndpoint&&y7e(i,"ENDPOINT_OVERRIDE","N");const a=await d$e(r.input,{getEndpointParameterInstructions(){return t}},{...e},i);i.endpointV2=a,i.authSchemes=a.properties?.authSchemes;const l=i.authSchemes?.[0];if(l){i.signing_region=l.signingRegion,i.signing_service=l.signingName;const o=Jb(i)?.selectedHttpAuthScheme?.httpAuthOption;o&&(o.signingProperties=Object.assign(o.signingProperties||{},{signing_region:l.signingRegion,signingRegion:l.signingRegion,signing_service:l.signingName,signingName:l.signingName,signingRegionSet:l.signingRegionSet},l.properties))}return n({...r})},h$e={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:u8e.name},m$e=(e,t)=>({applyToStack:n=>{n.addRelativeTo(f$e({config:e,instructions:t}),h$e)}}),g$e=e=>{const t=e.tls??!0,{endpoint:n,useDualstackEndpoint:i,useFipsEndpoint:r}=e,a=n!=null?async()=>cue(await ym(n)()):void 0,c=Object.assign(e,{endpoint:a,tls:t,isCustomEndpoint:!!n,useDualstackEndpoint:ym(i??!1),useFipsEndpoint:ym(r??!1)});let o;return c.serviceConfiguredEndpoint=async()=>(e.serviceId&&!o&&(o=lue(e.serviceId)),o),c};var Ib;(function(e){e.STANDARD="standard",e.ADAPTIVE="adaptive"})(Ib||(Ib={}));const YT=3,y$e=Ib.STANDARD,v$e=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],b$e=["TimeoutError","RequestTimeout","RequestTimeoutException"],w$e=[500,502,503,504],_$e=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],x$e=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND"],S$e=e=>e?.$retryable!==void 0,C$e=e=>e.$metadata?.clockSkewCorrected,T$e=e=>{const t=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);return e&&e instanceof TypeError?t.has(e.message):!1},uue=e=>e.$metadata?.httpStatusCode===429||v$e.includes(e.name)||e.$retryable?.throttling==!0,R8=(e,t=0)=>S$e(e)||C$e(e)||b$e.includes(e.name)||_$e.includes(e?.code||"")||x$e.includes(e?.code||"")||w$e.includes(e.$metadata?.httpStatusCode||0)||T$e(e)||e.cause!==void 0&&t<=10&&R8(e.cause,t+1),E$e=e=>{if(e.$metadata?.httpStatusCode!==void 0){const t=e.$metadata.httpStatusCode;return 500<=t&&t<=599&&!R8(e)}return!1};class O8{static setTimeoutFn=setTimeout;beta;minCapacity;minFillRate;scaleConstant;smooth;currentCapacity=0;enabled=!1;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(t){this.beta=t?.beta??.7,this.minCapacity=t?.minCapacity??1,this.minFillRate=t?.minFillRate??.5,this.scaleConstant=t?.scaleConstant??.4,this.smooth=t?.smooth??.8;const n=this.getCurrentTimeInSeconds();this.lastThrottleTime=n,this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}getCurrentTimeInSeconds(){return Date.now()/1e3}async getSendToken(){return this.acquireTokenBucket(1)}async acquireTokenBucket(t){if(this.enabled){if(this.refillTokenBucket(),t>this.currentCapacity){const n=(t-this.currentCapacity)/this.fillRate*1e3;await new Promise(i=>O8.setTimeoutFn(i,n))}this.currentCapacity=this.currentCapacity-t}}refillTokenBucket(){const t=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=t;return}const n=(t-this.lastTimestamp)*this.fillRate;this.currentCapacity=Math.min(this.maxCapacity,this.currentCapacity+n),this.lastTimestamp=t}updateClientSendingRate(t){let n;if(this.updateMeasuredRate(),uue(t)){const r=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=r,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),n=this.cubicThrottle(r),this.enableTokenBucket()}else this.calculateTimeWindow(),n=this.cubicSuccess(this.getCurrentTimeInSeconds());const i=Math.min(n,2*this.measuredTxRate);this.updateTokenBucketRate(i)}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(t){return this.getPrecise(t*this.beta)}cubicSuccess(t){return this.getPrecise(this.scaleConstant*Math.pow(t-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(t){this.refillTokenBucket(),this.fillRate=Math.max(t,this.minFillRate),this.maxCapacity=Math.max(t,this.minCapacity),this.currentCapacity=Math.min(this.currentCapacity,this.maxCapacity)}updateMeasuredRate(){const t=this.getCurrentTimeInSeconds(),n=Math.floor(t*2)/2;if(this.requestCount++,n>this.lastTxRateBucket){const i=this.requestCount/(n-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(i*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=n}}getPrecise(t){return parseFloat(t.toFixed(8))}}const lO=100,due=20*1e3,k$e=500,jF=500,A$e=5,R$e=10,O$e=1,I$e="amz-sdk-invocation-id",P$e="amz-sdk-request",M$e=()=>{let e=lO;return{computeNextBackoffDelay:i=>Math.floor(Math.min(due,Math.random()*2**i*e)),setDelayBase:i=>{e=i}}},LF=({retryDelay:e,retryCount:t,retryCost:n})=>({getRetryCount:()=>t,getRetryDelay:()=>Math.min(due,e),getRetryCost:()=>n});class pue{maxAttempts;mode=Ib.STANDARD;capacity=jF;retryBackoffStrategy=M$e();maxAttemptsProvider;constructor(t){this.maxAttempts=t,this.maxAttemptsProvider=typeof t=="function"?t:async()=>t}async acquireInitialRetryToken(t){return LF({retryDelay:lO,retryCount:0})}async refreshRetryTokenForRetry(t,n){const i=await this.getMaxAttempts();if(this.shouldRetry(t,n,i)){const r=n.errorType;this.retryBackoffStrategy.setDelayBase(r==="THROTTLING"?k$e:lO);const a=this.retryBackoffStrategy.computeNextBackoffDelay(t.getRetryCount()),l=n.retryAfterHint?Math.max(n.retryAfterHint.getTime()-Date.now()||0,a):a,c=this.getCapacityCost(r);return this.capacity-=c,LF({retryDelay:l,retryCount:t.getRetryCount()+1,retryCost:c})}throw new Error("No retry token available")}recordSuccess(t){this.capacity=Math.max(jF,this.capacity+(t.getRetryCost()??O$e))}getCapacity(){return this.capacity}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch{return console.warn(`Max attempts provider could not resolve. Using default of ${YT}`),YT}}shouldRetry(t,n,i){return t.getRetryCount()+1<i&&this.capacity>=this.getCapacityCost(n.errorType)&&this.isRetryableError(n.errorType)}getCapacityCost(t){return t==="TRANSIENT"?R$e:A$e}isRetryableError(t){return t==="THROTTLING"||t==="TRANSIENT"}}class N$e{maxAttemptsProvider;rateLimiter;standardRetryStrategy;mode=Ib.ADAPTIVE;constructor(t,n){this.maxAttemptsProvider=t;const{rateLimiter:i}=n??{};this.rateLimiter=i??new O8,this.standardRetryStrategy=new pue(t)}async acquireInitialRetryToken(t){return await this.rateLimiter.getSendToken(),this.standardRetryStrategy.acquireInitialRetryToken(t)}async refreshRetryTokenForRetry(t,n){return this.rateLimiter.updateClientSendingRate(n),this.standardRetryStrategy.refreshRetryTokenForRetry(t,n)}recordSuccess(t){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(t)}}const $$e=e=>e instanceof Error?e:e instanceof Object?Object.assign(new Error,e):typeof e=="string"?new Error(e):new Error(`AWS SDK error wrapper for ${e}`),D$e=e=>{const{retryStrategy:t,retryMode:n,maxAttempts:i}=e,r=ym(i??YT);return Object.assign(e,{maxAttempts:r,retryStrategy:async()=>t||(await ym(n)()===Ib.ADAPTIVE?new N$e(r):new pue(r))})},j$e=e=>e?.body instanceof ReadableStream,L$e=e=>(t,n)=>async i=>{let r=await e.retryStrategy();const a=await e.maxAttempts();if(U$e(r)){r=r;let l=await r.acquireInitialRetryToken(n.partition_id),c=new Error,o=0,s=0;const{request:u}=i,d=Ea.isInstance(u);for(d&&(u.headers[I$e]=v8());;)try{d&&(u.headers[P$e]=`attempt=${o+1}; max=${a}`);const{response:p,output:f}=await t(i);return r.recordSuccess(l),f.$metadata.attempts=o+1,f.$metadata.totalRetryDelay=s,{response:p,output:f}}catch(p){const f=F$e(p);if(c=$$e(p),d&&j$e(u))throw(n.logger instanceof Rce?console:n.logger)?.warn("An error was encountered in a non-retryable streaming request."),c;try{l=await r.refreshRetryTokenForRetry(l,f)}catch{throw c.$metadata||(c.$metadata={}),c.$metadata.attempts=o+1,c.$metadata.totalRetryDelay=s,c}o=l.getRetryCount();const h=l.getRetryDelay();s+=h,await new Promise(m=>setTimeout(m,h))}}else return r=r,r?.mode&&(n.userAgent=[...n.userAgent||[],["cfg/retry-mode",r.mode]]),r.retry(t,i)},U$e=e=>typeof e.acquireInitialRetryToken<"u"&&typeof e.refreshRetryTokenForRetry<"u"&&typeof e.recordSuccess<"u",F$e=e=>{const t={error:e,errorType:q$e(e)},n=z$e(e.$response);return n&&(t.retryAfterHint=n),t},q$e=e=>uue(e)?"THROTTLING":R8(e)?"TRANSIENT":E$e(e)?"SERVER_ERROR":"CLIENT_ERROR",B$e={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0},W$e=e=>({applyToStack:t=>{t.add(L$e(e),B$e)}}),z$e=e=>{if(!jy.isInstance(e))return;const t=Object.keys(e.headers).find(a=>a.toLowerCase()==="retry-after");if(!t)return;const n=e.headers[t],i=Number(n);return Number.isNaN(i)?new Date(n):new Date(i*1e3)},G$e=async(e,t,n)=>({operation:Jb(t).operation,region:await ym(e.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function H$e(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"bedrock",region:e.region},propertiesExtractor:(t,n)=>({signingProperties:{config:t,context:n}})}}function V$e(e){return{schemeId:"smithy.api#httpBearerAuth",propertiesExtractor:({profile:t,filepath:n,configFilepath:i,ignoreCache:r},a)=>({identityProperties:{profile:t,filepath:n,configFilepath:i,ignoreCache:r}})}}const J$e=e=>{const t=[];switch(e.operation){default:t.push(H$e(e)),t.push(V$e())}return t},K$e=e=>{const t=sce(e.token,ace,x8),n=RMe(e);return Object.assign(n,{authSchemePreference:ym(e.authSchemePreference??[]),token:t})},Z$e=e=>Object.assign(e,{useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,defaultSigningName:"bedrock"}),X$e={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},Q$e="3.1000.0",Y$e={version:Q$e};var fue={name:"SHA-256"},UF={name:"HMAC",hash:fue},eDe=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85]);const tDe={};function DC(){return typeof window<"u"?window:typeof self<"u"?self:tDe}var nDe=(function(){function e(t){this.toHash=new Uint8Array(0),this.secret=t,this.reset()}return e.prototype.update=function(t){if(!oO(t)){var n=B_(t),i=new Uint8Array(this.toHash.byteLength+n.byteLength);i.set(this.toHash,0),i.set(n,this.toHash.byteLength),this.toHash=i}},e.prototype.digest=function(){var t=this;return this.key?this.key.then(function(n){return DC().crypto.subtle.sign(UF,n,t.toHash).then(function(i){return new Uint8Array(i)})}):oO(this.toHash)?Promise.resolve(eDe):Promise.resolve().then(function(){return DC().crypto.subtle.digest(fue,t.toHash)}).then(function(n){return Promise.resolve(new Uint8Array(n))})},e.prototype.reset=function(){var t=this;this.toHash=new Uint8Array(0),this.secret&&this.secret!==void 0&&(this.key=new Promise(function(n,i){DC().crypto.subtle.importKey("raw",B_(t.secret),UF,!1,["sign"]).then(n,i)}),this.key.catch(function(){}))},e})(),Ms=64,rDe=32,iDe=new Uint32Array([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]),aDe=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],sDe=Math.pow(2,53)-1,jC=(function(){function e(){this.state=Int32Array.from(aDe),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return e.prototype.update=function(t){if(this.finished)throw new Error("Attempted to update an already finished hash.");var n=0,i=t.byteLength;if(this.bytesHashed+=i,this.bytesHashed*8>sDe)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;i>0;)this.buffer[this.bufferLength++]=t[n++],i--,this.bufferLength===Ms&&(this.hashBuffer(),this.bufferLength=0)},e.prototype.digest=function(){if(!this.finished){var t=this.bytesHashed*8,n=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),i=this.bufferLength;if(n.setUint8(this.bufferLength++,128),i%Ms>=Ms-8){for(var r=this.bufferLength;r<Ms;r++)n.setUint8(r,0);this.hashBuffer(),this.bufferLength=0}for(var r=this.bufferLength;r<Ms-8;r++)n.setUint8(r,0);n.setUint32(Ms-8,Math.floor(t/4294967296),!0),n.setUint32(Ms-4,t),this.hashBuffer(),this.finished=!0}for(var a=new Uint8Array(rDe),r=0;r<8;r++)a[r*4]=this.state[r]>>>24&255,a[r*4+1]=this.state[r]>>>16&255,a[r*4+2]=this.state[r]>>>8&255,a[r*4+3]=this.state[r]>>>0&255;return a},e.prototype.hashBuffer=function(){for(var t=this,n=t.buffer,i=t.state,r=i[0],a=i[1],l=i[2],c=i[3],o=i[4],s=i[5],u=i[6],d=i[7],p=0;p<Ms;p++){if(p<16)this.temp[p]=(n[p*4]&255)<<24|(n[p*4+1]&255)<<16|(n[p*4+2]&255)<<8|n[p*4+3]&255;else{var f=this.temp[p-2],h=(f>>>17|f<<15)^(f>>>19|f<<13)^f>>>10;f=this.temp[p-15];var m=(f>>>7|f<<25)^(f>>>18|f<<14)^f>>>3;this.temp[p]=(h+this.temp[p-7]|0)+(m+this.temp[p-16]|0)}var g=(((o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7))+(o&s^~o&u)|0)+(d+(iDe[p]+this.temp[p]|0)|0)|0,y=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&a^r&l^a&l)|0;d=u,u=s,s=o,o=c+g|0,c=l,l=a,a=r,r=g+y|0}i[0]+=r,i[1]+=a,i[2]+=l,i[3]+=c,i[4]+=o,i[5]+=s,i[6]+=u,i[7]+=d},e})(),oDe=(function(){function e(t){this.secret=t,this.hash=new jC,this.reset()}return e.prototype.update=function(t){if(!(oO(t)||this.error))try{this.hash.update(B_(t))}catch(n){this.error=n}},e.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},e.prototype.digest=function(){return T8(this,void 0,void 0,function(){return E8(this,function(t){return[2,this.digestSync()]})})},e.prototype.reset=function(){if(this.hash=new jC,this.secret){this.outer=new jC;var t=lDe(this.secret),n=new Uint8Array(Ms);n.set(t);for(var i=0;i<Ms;i++)t[i]^=54,n[i]^=92;this.hash.update(t),this.outer.update(n);for(var i=0;i<t.byteLength;i++)t[i]=0}},e})();function lDe(e){var t=B_(e);if(t.byteLength>Ms){var n=new jC;n.update(t),t=n.digest()}var i=new Uint8Array(Ms);return i.set(t),i}var cDe=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function uDe(e){if(dDe(e)&&typeof e.crypto.subtle=="object"){var t=e.crypto.subtle;return pDe(t)}return!1}function dDe(e){if(typeof e=="object"&&typeof e.crypto=="object"){var t=e.crypto.getRandomValues;return typeof t=="function"}return!1}function pDe(e){return e&&cDe.every(function(t){return typeof e[t]=="function"})}var fDe=(function(){function e(t){uDe(DC())?this.hash=new nDe(t):this.hash=new oDe(t)}return e.prototype.update=function(t,n){this.hash.update(B_(t))},e.prototype.digest=function(){return this.hash.digest()},e.prototype.reset=function(){this.hash.reset()},e})();const hDe=({serviceId:e,clientVersion:t})=>async n=>{const i=typeof window<"u"?window.navigator:void 0,r=i?.userAgent??"",a=i?.userAgentData?.platform??FF.os(r)??"other",l=void 0,c=i?.userAgentData?.brands??[],o=c[c.length-1],s=o?.brand??FF.browser(r)??"unknown",u=o?.version??"unknown",d=[["aws-sdk-js",t],["ua","2.1"],[`os/${a}`,l],["lang/js"],["md/browser",`${s}_${u}`]];e&&d.push([`api/${e}`,t]);const p=await n?.userAgentAppId?.();return p&&d.push([`app/${p}`]),d},FF={os(e){if(/iPhone|iPad|iPod/.test(e))return"iOS";if(/Macintosh|Mac OS X/.test(e))return"macOS";if(/Windows NT/.test(e))return"Windows";if(/Android/.test(e))return"Android";if(/Linux/.test(e))return"Linux"},browser(e){if(/EdgiOS|EdgA|Edg\//.test(e))return"Microsoft Edge";if(/Firefox\//.test(e))return"Firefox";if(/Chrome\//.test(e))return"Chrome";if(/Safari\//.test(e))return"Safari"}},mDe=e=>()=>Promise.reject(e),gDe=["in-region","cross-region","mobile","standard","legacy"],yDe=({defaultsMode:e}={})=>nMe(async()=>{const t=typeof e=="function"?await e():e;switch(t?.toLowerCase()){case"auto":return Promise.resolve(vDe()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(t?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${gDe.join(", ")}, got ${t}`)}}),vDe=()=>{const e=window?.navigator;if(e?.connection){const{effectiveType:t,rtt:n,downlink:i}=e?.connection;if(typeof t=="string"&&t!=="4g"||Number(n)>100||Number(i)<10)return!0}return e?.userAgentData?.mobile||typeof e?.maxTouchPoints=="number"&&e?.maxTouchPoints>1},hue="required",Tc="fn",Ec="argv",Zb="ref",qF=!0,BF="isSet",W_="booleanEquals",Av="error",e1="endpoint",sa="tree",I8="PartitionResult",WF={[hue]:!1,type:"string"},zF={[hue]:!0,default:!1,type:"boolean"},GF={[Zb]:"Endpoint"},mue={[Tc]:W_,[Ec]:[{[Zb]:"UseFIPS"},!0]},gue={[Tc]:W_,[Ec]:[{[Zb]:"UseDualStack"},!0]},Wo={},HF={[Tc]:"getAttr",[Ec]:[{[Zb]:I8},"supportsFIPS"]},VF={[Tc]:W_,[Ec]:[!0,{[Tc]:"getAttr",[Ec]:[{[Zb]:I8},"supportsDualStack"]}]},JF=[mue],KF=[gue],ZF=[{[Zb]:"Region"}],bDe={parameters:{Region:WF,UseDualStack:zF,UseFIPS:zF,Endpoint:WF},rules:[{conditions:[{[Tc]:BF,[Ec]:[GF]}],rules:[{conditions:JF,error:"Invalid Configuration: FIPS and custom endpoint are not supported",type:Av},{rules:[{conditions:KF,error:"Invalid Configuration: Dualstack and custom endpoint are not supported",type:Av},{endpoint:{url:GF,properties:Wo,headers:Wo},type:e1}],type:sa}],type:sa},{rules:[{conditions:[{[Tc]:BF,[Ec]:ZF}],rules:[{conditions:[{[Tc]:"aws.partition",[Ec]:ZF,assign:I8}],rules:[{conditions:[mue,gue],rules:[{conditions:[{[Tc]:W_,[Ec]:[qF,HF]},VF],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:Wo,headers:Wo},type:e1}],type:sa}],type:sa},{error:"FIPS and DualStack are enabled, but this partition does not support one or both",type:Av}],type:sa},{conditions:JF,rules:[{conditions:[{[Tc]:W_,[Ec]:[HF,qF]}],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime-fips.{Region}.{PartitionResult#dnsSuffix}",properties:Wo,headers:Wo},type:e1}],type:sa}],type:sa},{error:"FIPS is enabled but this partition does not support FIPS",type:Av}],type:sa},{conditions:KF,rules:[{conditions:[VF],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:Wo,headers:Wo},type:e1}],type:sa}],type:sa},{error:"DualStack is enabled but this partition does not support DualStack",type:Av}],type:sa},{rules:[{endpoint:{url:"https://bedrock-runtime.{Region}.{PartitionResult#dnsSuffix}",properties:Wo,headers:Wo},type:e1}],type:sa}],type:sa}],type:sa},{error:"Invalid Configuration: Missing Region",type:Av}],type:sa}]},wDe=bDe,_De=new T7e({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),xDe=(e,t={})=>_De.get(e,()=>z7e(wDe,{endpointParams:e,logger:t.logger}));KT.aws=vce;class ka extends fb{constructor(t){super(t),Object.setPrototypeOf(this,ka.prototype)}}class P8 extends ka{name="AccessDeniedException";$fault="client";constructor(t){super({name:"AccessDeniedException",$fault:"client",...t}),Object.setPrototypeOf(this,P8.prototype)}}class M8 extends ka{name="InternalServerException";$fault="server";constructor(t){super({name:"InternalServerException",$fault:"server",...t}),Object.setPrototypeOf(this,M8.prototype)}}class N8 extends ka{name="ThrottlingException";$fault="client";constructor(t){super({name:"ThrottlingException",$fault:"client",...t}),Object.setPrototypeOf(this,N8.prototype)}}class $8 extends ka{name="ValidationException";$fault="client";constructor(t){super({name:"ValidationException",$fault:"client",...t}),Object.setPrototypeOf(this,$8.prototype)}}class D8 extends ka{name="ConflictException";$fault="client";constructor(t){super({name:"ConflictException",$fault:"client",...t}),Object.setPrototypeOf(this,D8.prototype)}}class j8 extends ka{name="ResourceNotFoundException";$fault="client";constructor(t){super({name:"ResourceNotFoundException",$fault:"client",...t}),Object.setPrototypeOf(this,j8.prototype)}}class L8 extends ka{name="ServiceQuotaExceededException";$fault="client";constructor(t){super({name:"ServiceQuotaExceededException",$fault:"client",...t}),Object.setPrototypeOf(this,L8.prototype)}}class U8 extends ka{name="ServiceUnavailableException";$fault="server";constructor(t){super({name:"ServiceUnavailableException",$fault:"server",...t}),Object.setPrototypeOf(this,U8.prototype)}}class F8 extends ka{name="ModelErrorException";$fault="client";originalStatusCode;resourceName;constructor(t){super({name:"ModelErrorException",$fault:"client",...t}),Object.setPrototypeOf(this,F8.prototype),this.originalStatusCode=t.originalStatusCode,this.resourceName=t.resourceName}}class q8 extends ka{name="ModelNotReadyException";$fault="client";$retryable={};constructor(t){super({name:"ModelNotReadyException",$fault:"client",...t}),Object.setPrototypeOf(this,q8.prototype)}}class B8 extends ka{name="ModelTimeoutException";$fault="client";constructor(t){super({name:"ModelTimeoutException",$fault:"client",...t}),Object.setPrototypeOf(this,B8.prototype)}}class W8 extends ka{name="ModelStreamErrorException";$fault="client";originalStatusCode;originalMessage;constructor(t){super({name:"ModelStreamErrorException",$fault:"client",...t}),Object.setPrototypeOf(this,W8.prototype),this.originalStatusCode=t.originalStatusCode,this.originalMessage=t.originalMessage}}const SDe="AudioBlock",CDe="AccessDeniedException",TDe="AppliedGuardrailDetails",EDe="AudioSource",kDe="AnyToolChoice",ADe="AutoToolChoice",RDe="Citation",ODe="ContentBlocks",IDe="ContentBlockDelta",PDe="ContentBlockDeltaEvent",MDe="ContentBlockStart",NDe="ContentBlockStartEvent",$De="ContentBlockStopEvent",DDe="ContentBlock",jDe="CitationsConfig",LDe="CitationsContentBlock",UDe="CacheDetail",FDe="CacheDetailsList",qDe="CitationsDelta",BDe="ConflictException",WDe="CitationGeneratedContent",zDe="CitationGeneratedContentList",GDe="CitationLocation",HDe="CachePointBlock",VDe="ConverseStream",JDe="CitationSourceContent",KDe="CitationSourceContentDelta",ZDe="CitationSourceContentList",XDe="CitationSourceContentListDelta",QDe="ConverseStreamMetrics",YDe="ConverseStreamMetadataEvent",eje="ConverseStreamOutput",tje="ConverseStreamRequest",nje="ConverseStreamResponse",rje="ConverseStreamTrace",ije="Citations",aje="DocumentBlock",sje="DocumentContentBlocks",oje="DocumentContentBlock",lje="DocumentCharLocation",cje="DocumentChunkLocation",uje="DocumentPageLocation",dje="DocumentSource",pje="ErrorBlock",fje="GuardrailAssessment",hje="GuardrailAssessmentList",mje="GuardrailAssessmentListMap",gje="GuardrailAssessmentMap",yje="GuardrailAutomatedReasoningDifferenceScenarioList",vje="GuardrailAutomatedReasoningFinding",bje="GuardrailAutomatedReasoningFindingList",wje="GuardrailAutomatedReasoningImpossibleFinding",_je="GuardrailAutomatedReasoningInvalidFinding",xje="GuardrailAutomatedReasoningInputTextReference",Sje="GuardrailAutomatedReasoningInputTextReferenceList",Cje="GuardrailAutomatedReasoningLogicWarning",Tje="GuardrailAutomatedReasoningNoTranslationsFinding",Eje="GuardrailAutomatedReasoningPolicyAssessment",kje="GuardrailAutomatedReasoningRule",Aje="GuardrailAutomatedReasoningRuleList",Rje="GuardrailAutomatedReasoningScenario",Oje="GuardrailAutomatedReasoningSatisfiableFinding",Ije="GuardrailAutomatedReasoningStatementList",Pje="GuardrailAutomatedReasoningStatementLogicContent",Mje="GuardrailAutomatedReasoningStatementNaturalLanguageContent",Nje="GuardrailAutomatedReasoningStatement",$je="GuardrailAutomatedReasoningTranslation",Dje="GuardrailAutomatedReasoningTranslationAmbiguousFinding",jje="GuardrailAutomatedReasoningTooComplexFinding",Lje="GuardrailAutomatedReasoningTranslationList",Uje="GuardrailAutomatedReasoningTranslationOption",Fje="GuardrailAutomatedReasoningTranslationOptionList",qje="GuardrailAutomatedReasoningValidFinding",Bje="GuardrailConverseContentBlock",Wje="GuardrailContentFilter",zje="GuardrailContentFilterList",Gje="GuardrailContextualGroundingFilter",Hje="GuardrailContextualGroundingFilters",Vje="GuardrailContextualGroundingPolicyAssessment",Jje="GuardrailConverseImageBlock",Kje="GuardrailConverseImageSource",Zje="GuardrailContentPolicyAssessment",Xje="GuardrailConverseTextBlock",Qje="GuardrailCustomWord",Yje="GuardrailCustomWordList",eLe="GuardrailCoverage",tLe="GuardrailImageCoverage",nLe="GuardrailInvocationMetrics",rLe="GuardrailManagedWord",iLe="GuardrailManagedWordList",aLe="GuardrailPiiEntityFilter",sLe="GuardrailPiiEntityFilterList",oLe="GuardrailRegexFilter",lLe="GuardrailRegexFilterList",cLe="GuardrailStreamConfiguration",uLe="GuardrailSensitiveInformationPolicyAssessment",dLe="GuardrailTopic",pLe="GuardrailTraceAssessment",fLe="GuardrailTextCharactersCoverage",hLe="GuardrailTopicList",mLe="GuardrailTopicPolicyAssessment",gLe="GuardrailUsage",yLe="GuardrailWordPolicyAssessment",vLe="ImageBlock",bLe="ImageBlockDelta",wLe="ImageBlockStart",_Le="InferenceConfiguration",xLe="ImageSource",SLe="InternalServerException",CLe="JsonSchemaDefinition",TLe="Message",ELe="ModelErrorException",kLe="ModelNotReadyException",ALe="MessageStartEvent",RLe="ModelStreamErrorException",OLe="MessageStopEvent",ILe="ModelTimeoutException",PLe="Messages",MLe="OutputConfig",NLe="OutputFormat",$Le="OutputFormatStructure",DLe="PerformanceConfiguration",jLe="PromptRouterTrace",LLe="PromptVariableMap",ULe="PromptVariableValues",FLe="ReasoningContentBlock",qLe="ReasoningContentBlockDelta",BLe="RequestMetadata",WLe="ResourceNotFoundException",zLe="ReasoningTextBlock",GLe="SystemContentBlocks",HLe="SystemContentBlock",VLe="S3Location",JLe="ServiceQuotaExceededException",KLe="SearchResultBlock",ZLe="SearchResultContentBlock",XLe="SearchResultContentBlocks",QLe="SearchResultLocation",YLe="ServiceTier",eUe="SpecificToolChoice",tUe="SystemTool",nUe="ServiceUnavailableException",rUe="ToolConfiguration",iUe="ToolChoice",aUe="ThrottlingException",sUe="ToolInputSchema",oUe="ToolResultBlock",lUe="ToolResultBlocksDelta",cUe="ToolResultBlockDelta",uUe="ToolResultBlockStart",dUe="ToolResultContentBlocks",pUe="ToolResultContentBlock",fUe="ToolSpecification",hUe="TokenUsage",mUe="ToolUseBlock",gUe="ToolUseBlockDelta",yUe="ToolUseBlockStart",vUe="Tools",bUe="Tool",wUe="VideoBlock",_Ue="ValidationException",xUe="VideoSource",SUe="WebLocation",Vy="action",CUe="appliedGuardrailDetails",TUe="additionalModelRequestFields",EUe="additionalModelResponseFieldPaths",kUe="additionalModelResponseFields",AUe="actionReason",RUe="automatedReasoningPolicy",OUe="automatedReasoningPolicyUnits",IUe="automatedReasoningPolicies",PUe="any",MUe="audio",NUe="auto",b2="bytes",$Ue="bucketOwner",Fc="client",DUe="contentBlockDelta",z8="contentBlockIndex",jUe="contentBlockStart",LUe="contentBlockStop",UUe="citationsContent",FUe="cacheDetails",qUe="claimsFalseScenario",BUe="contextualGroundingPolicy",WUe="contextualGroundingPolicyUnits",zUe="contentPolicy",GUe="contentPolicyImageUnits",HUe="contentPolicyUnits",G8="cachePoint",yue="contradictingRules",VUe="cacheReadInputTokens",vue="claimsTrueScenario",JUe="customWords",KUe="cacheWriteInputTokens",H8="citations",ZUe="citation",bue="claims",w2="content",XUe="context",wue="confidence",QUe="delta",YUe="documentChar",eFe="documentChunk",V8="documentIndex",tFe="documentPage",nFe="differenceScenarios",Jy="detected",_ue="description",rFe="domain",xue="document",Aa="error",iFe="enabled",CE="end",Xb="format",aFe="filterStrength",sFe="findings",Sue="filters",oFe="guardrail",lFe="guardrailArn",cFe="guardrailCoverage",uFe="guardrailConfig",Cue="guardContent",dFe="guardrailId",pFe="guardrailIdentifier",fFe="guardrailOrigin",hFe="guardrailOwnership",mFe="guardrailProcessingLatency",Tue="guardrailVersion",Eue="guarded",gFe="http",Zs="httpError",kue="input",yFe="inputAssessment",vFe="inferenceConfig",bFe="invocationMetrics",wFe="invokedModelId",_Fe="inputSchema",xFe="internalServerException",Aue="inputTokens",SFe="identifier",CFe="images",_2="image",TFe="impossible",EFe="invalid",J8="json",kFe="jsonSchema",Rue="location",AFe="latencyMs",TE="logicWarning",RFe="latency",OFe="logic",vs="message",IFe="modelId",PFe="modelOutput",MFe="messageStart",NFe="modelStreamErrorException",$Fe="messageStop",DFe="maxTokens",jFe="managedWordLists",EE="match",LFe="messages",UFe="metrics",FFe="metadata",Em="name",qFe="naturalLanguage",BFe="noTranslations",WFe="outputAssessments",zFe="outputConfig",GFe="originalMessage",Oue="originalStatusCode",HFe="outputTokens",VFe="options",Iue="premises",Pue="performanceConfig",JFe="piiEntities",KFe="promptRouter",ZFe="promptVariables",XFe="policyVersionArn",QFe="qualifiers",YFe="regex",Mue="reasoningContent",Nue="redactedContent",eqe="requestMetadata",tqe="resourceName",nqe="reasoningText",rqe="regexes",$ue="role",Due="smithy.ts.sdk.synthetic.com.amazonaws.bedrockruntime",jue="sourceContent",iqe="sensitiveInformationPolicy",aqe="sensitiveInformationPolicyFreeUnits",sqe="sensitiveInformationPolicyUnits",kE="s3Location",oqe="streamProcessingMode",lqe="stopReason",cqe="searchResultIndex",uqe="searchResultLocation",Lue="searchResult",dqe="supportingRules",pqe="stopSequences",Uue="serviceTier",fqe="systemTool",hqe="serviceUnavailableException",mqe="satisfiable",gqe="score",yqe="schema",Fue="server",que="signature",km="source",Bue="status",x2="start",vqe="statements",bqe="stream",wqe="streaming",_qe="strict",xqe="structure",Sqe="system",Wue="ttl",Cqe="translationAmbiguous",Tqe="toolConfig",Eqe="textCharacters",kqe="toolChoice",Aqe="tooComplex",Rqe="throttlingException",Oqe="textFormat",Iqe="topicPolicy",Pqe="topicPolicyUnits",Mqe="topP",K8="toolResult",Nqe="toolSpec",$qe="totalTokens",Z8="toolUse",AE="toolUseId",Xi="text",Dqe="temperature",jqe="threshold",X8="title",zue="total",Lqe="tools",Uqe="tool",Fqe="topics",Gue="trace",RE="translation",qqe="translations",bs="type",Hue="usage",Bqe="untranslatedClaims",Wqe="untranslatedPremises",zqe="uri",Gqe="url",Hqe="validationException",Vqe="valid",Vue="video",Jqe="web",Kqe="wordPolicy",Zqe="wordPolicyUnits",We="com.amazonaws.bedrockruntime",Jue=Ua.for(Due);var Xqe=[-3,Due,"BedrockRuntimeServiceException",0,[],[]];Jue.registerError(Xqe,ka);const ws=Ua.for(We);var Qqe=[-3,We,CDe,{[Aa]:Fc,[Zs]:403},[vs],[0]];ws.registerError(Qqe,P8);var Yqe=[-3,We,BDe,{[Aa]:Fc,[Zs]:400},[vs],[0]];ws.registerError(Yqe,D8);var Kue=[-3,We,SLe,{[Aa]:Fue,[Zs]:500},[vs],[0]];ws.registerError(Kue,M8);var eBe=[-3,We,ELe,{[Aa]:Fc,[Zs]:424},[vs,Oue,tqe],[0,1,0]];ws.registerError(eBe,F8);var tBe=[-3,We,kLe,{[Aa]:Fc,[Zs]:429},[vs],[0]];ws.registerError(tBe,q8);var Zue=[-3,We,RLe,{[Aa]:Fc,[Zs]:424},[vs,Oue,GFe],[0,1,0]];ws.registerError(Zue,W8);var nBe=[-3,We,ILe,{[Aa]:Fc,[Zs]:408},[vs],[0]];ws.registerError(nBe,B8);var rBe=[-3,We,WLe,{[Aa]:Fc,[Zs]:404},[vs],[0]];ws.registerError(rBe,j8);var iBe=[-3,We,JLe,{[Aa]:Fc,[Zs]:400},[vs],[0]];ws.registerError(iBe,L8);var Xue=[-3,We,nUe,{[Aa]:Fue,[Zs]:503},[vs],[0]];ws.registerError(Xue,U8);var Que=[-3,We,aUe,{[Aa]:Fc,[Zs]:429},[vs],[0]];ws.registerError(Que,N8);var Yue=[-3,We,_Ue,{[Aa]:Fc,[Zs]:400},[vs],[0]];ws.registerError(Yue,$8);const aBe=[Jue,ws];var sBe=[0,We,Pje,8,0],ede=[0,We,Mje,8,0],oBe=[3,We,kDe,0,[],[]],lBe=[3,We,TDe,0,[dFe,Tue,lFe,fFe,hFe],[0,0,0,64,0]],cBe=[3,We,SDe,0,[Xb,km,Aa],[0,[()=>aze,0],[()=>Y8,0]],2],uBe=[3,We,ADe,0,[],[]],dBe=[3,We,UDe,0,[Wue,Aue],[0,1],2],Q8=[3,We,HDe,0,[bs,Wue],[0,0],1],pBe=[3,We,RDe,0,[X8,km,jue,Rue],[0,0,()=>MWe,()=>cde]],tde=[3,We,jDe,0,[iFe],[2],1],fBe=[3,We,LDe,0,[w2,H8],[()=>IWe,()=>PWe]],hBe=[3,We,qDe,0,[X8,km,jue,Rue],[0,0,()=>NWe,()=>cde]],mBe=[3,We,KDe,0,[Xi],[0]],gBe=[3,We,PDe,0,[QUe,z8],[[()=>cze,0],1],2],yBe=[3,We,NDe,0,[x2,z8],[()=>uze,1],2],vBe=[3,We,$De,0,[z8],[1],1],bBe=[3,We,YDe,0,[Hue,UFe,Gue,Pue,Uue],[()=>_We,()=>wBe,[()=>SBe,0],()=>ade,()=>ode],2],wBe=[3,We,QDe,0,[AFe],[1],1],_Be=[3,We,tje,0,[IFe,LFe,Sqe,vFe,Tqe,uFe,TUe,ZFe,EUe,eqe,Pue,Uue,zFe],[[0,1],[()=>KWe,0],[()=>XWe,0],()=>lWe,()=>xWe,()=>YBe,15,[()=>rze,0],64,[()=>ize,0],()=>ade,()=>ode,[()=>fWe,0]],1],xBe=[3,We,nje,0,[bqe],[[()=>dze,16]]],SBe=[3,We,rje,0,[oFe,KFe],[[()=>rWe,0],()=>mWe]],nde=[3,We,aje,0,[Em,km,Xb,XUe,H8],[0,()=>fze,0,0,()=>tde],2],CBe=[3,We,lje,0,[V8,x2,CE],[1,1,1]],TBe=[3,We,cje,0,[V8,x2,CE],[1,1,1]],EBe=[3,We,uje,0,[V8,x2,CE],[1,1,1]],Y8=[3,We,pje,8,[vs],[0]],rde=[3,We,fje,0,[Iqe,zUe,Kqe,iqe,BUe,RUe,bFe,CUe],[()=>nWe,()=>FBe,()=>aWe,()=>QBe,()=>BBe,[()=>IBe,0],()=>JBe,()=>lBe]],kBe=[3,We,wje,0,[RE,yue,TE],[[()=>S2,0],()=>e7,[()=>OE,0]]],ABe=[3,We,xje,0,[Xi],[[()=>ede,0]]],RBe=[3,We,_je,0,[RE,yue,TE],[[()=>S2,0],()=>e7,[()=>OE,0]]],OE=[3,We,Cje,0,[bs,Iue,bue],[0,[()=>z_,0],[()=>z_,0]]],OBe=[3,We,Tje,0,[],[]],IBe=[3,We,Eje,0,[sFe],[[()=>UWe,0]]],PBe=[3,We,kje,0,[SFe,XFe],[0,0]],MBe=[3,We,Oje,0,[RE,vue,qUe,TE],[[()=>S2,0],[()=>e3,0],[()=>e3,0],[()=>OE,0]]],e3=[3,We,Rje,0,[vqe],[[()=>z_,0]]],NBe=[3,We,Nje,0,[OFe,qFe],[[()=>sBe,0],[()=>ede,0]]],$Be=[3,We,jje,0,[],[]],S2=[3,We,$je,0,[Iue,bue,Wqe,Bqe,wue],[[()=>z_,0],[()=>z_,0],[()=>XF,0],[()=>XF,0],1]],DBe=[3,We,Dje,0,[VFe,nFe],[[()=>qWe,0],[()=>LWe,0]]],jBe=[3,We,Uje,0,[qqe],[[()=>FWe,0]]],LBe=[3,We,qje,0,[RE,vue,dqe,TE],[[()=>S2,0],[()=>e3,0],()=>e7,[()=>OE,0]]],UBe=[3,We,Wje,0,[bs,wue,Vy,aFe,Jy],[0,0,0,0,2],3],FBe=[3,We,Zje,0,[Sue],[()=>BWe],1],qBe=[3,We,Gje,0,[bs,jqe,gqe,Vy,Jy],[0,1,1,0,2],4],BBe=[3,We,Vje,0,[Sue],[()=>WWe]],WBe=[3,We,Jje,8,[Xb,km],[0,[()=>mze,0]],2],zBe=[3,We,Xje,0,[Xi,QFe],[0,64],1],GBe=[3,We,eLe,0,[Eqe,CFe],[()=>eWe,()=>VBe]],HBe=[3,We,Qje,0,[EE,Vy,Jy],[0,0,2],2],VBe=[3,We,tLe,0,[Eue,zue],[1,1]],JBe=[3,We,nLe,0,[mFe,Hue,cFe],[1,()=>iWe,()=>GBe]],KBe=[3,We,rLe,0,[EE,bs,Vy,Jy],[0,0,0,2],3],ZBe=[3,We,aLe,0,[EE,bs,Vy,Jy],[0,0,0,2],3],XBe=[3,We,oLe,0,[Vy,Em,EE,YFe,Jy],[0,0,0,0,2],1],QBe=[3,We,uLe,0,[JFe,rqe],[()=>HWe,()=>VWe],2],YBe=[3,We,cLe,0,[pFe,Tue,Gue,oqe],[0,0,0,0]],eWe=[3,We,fLe,0,[Eue,zue],[1,1]],tWe=[3,We,dLe,0,[Em,bs,Vy,Jy],[0,0,0,2],3],nWe=[3,We,mLe,0,[Fqe],[()=>JWe],1],rWe=[3,We,pLe,0,[PFe,yFe,WFe,AUe],[64,[()=>nze,0],[()=>tze,0],0]],iWe=[3,We,gLe,0,[Pqe,HUe,Zqe,sqe,aqe,WUe,GUe,OUe,IUe],[1,1,1,1,1,1,1,1,1],6],aWe=[3,We,yLe,0,[JUe,jFe],[()=>zWe,()=>GWe],2],ide=[3,We,vLe,0,[Xb,km,Aa],[0,[()=>dde,0],[()=>Y8,0]],2],sWe=[3,We,bLe,0,[km,Aa],[[()=>dde,0],[()=>Y8,0]]],oWe=[3,We,wLe,0,[Xb],[0],1],lWe=[3,We,_Le,0,[DFe,Dqe,Mqe,pqe],[1,1,1,64]],cWe=[3,We,CLe,0,[yqe,Em,_ue],[0,0,0],1],uWe=[3,We,TLe,0,[$ue,w2],[0,[()=>$We,0]],2],dWe=[3,We,ALe,0,[$ue],[0],1],pWe=[3,We,OLe,0,[lqe,kUe],[0,15],1],fWe=[3,We,MLe,0,[Oqe],[[()=>hWe,0]]],hWe=[3,We,NLe,0,[bs,xqe],[0,[()=>gze,0]],2],ade=[3,We,DLe,0,[RFe],[0]],mWe=[3,We,jLe,0,[wFe],[0]],gWe=[3,We,zLe,8,[Xi,que],[0,0],1],IE=[3,We,VLe,0,[zqe,$Ue],[0,0],1],sde=[3,We,KLe,0,[km,X8,w2,H8],[0,0,()=>ZWe,()=>tde],3],yWe=[3,We,ZLe,0,[Xi],[0],1],vWe=[3,We,QLe,0,[cqe,x2,CE],[1,1,1]],ode=[3,We,YLe,0,[bs],[0],1],bWe=[3,We,eUe,0,[Em],[0],1],wWe=[3,We,tUe,0,[Em],[0],1],_We=[3,We,hUe,0,[Aue,HFe,$qe,VUe,KUe,FUe],[1,1,1,1,1,()=>OWe],3],xWe=[3,We,rUe,0,[Lqe,kqe],[()=>eze,()=>xze],1],SWe=[3,We,oUe,0,[AE,w2,Bue,bs],[0,[()=>YWe,0],0,0],2],CWe=[3,We,uUe,0,[AE,bs,Bue],[0,0,0],1],TWe=[3,We,fUe,0,[Em,_Fe,_ue,_qe],[0,()=>Sze,0,2],2],EWe=[3,We,mUe,0,[AE,Em,kue,bs],[0,0,15,0],3],kWe=[3,We,gUe,0,[kue],[0],1],AWe=[3,We,yUe,0,[AE,Em,bs],[0,0,0],2],lde=[3,We,wUe,0,[Xb,km],[0,()=>Eze],2],RWe=[3,We,SUe,0,[Gqe,rFe],[0,0]],OWe=[1,We,FDe,0,()=>dBe],IWe=[1,We,zDe,0,()=>sze],PWe=[1,We,ije,0,()=>pBe],MWe=[1,We,ZDe,0,()=>oze],NWe=[1,We,XDe,0,()=>mBe],$We=[1,We,ODe,0,[()=>lze,0]],DWe=[1,We,sje,0,()=>pze],jWe=[1,We,hje,0,[()=>rde,0]],LWe=[1,We,yje,0,[()=>e3,0]],UWe=[1,We,bje,0,[()=>hze,0]],XF=[1,We,Sje,0,[()=>ABe,0]],e7=[1,We,Aje,0,()=>PBe],z_=[1,We,Ije,0,[()=>NBe,0]],FWe=[1,We,Lje,0,[()=>S2,0]],qWe=[1,We,Fje,0,[()=>jBe,0]],BWe=[1,We,zje,0,()=>UBe],WWe=[1,We,Hje,0,()=>qBe],zWe=[1,We,Yje,0,()=>HBe],GWe=[1,We,iLe,0,()=>KBe],HWe=[1,We,sLe,0,()=>ZBe],VWe=[1,We,lLe,0,()=>XBe],JWe=[1,We,hLe,0,()=>tWe],KWe=[1,We,PLe,0,[()=>uWe,0]],ZWe=[1,We,XLe,0,()=>yWe],XWe=[1,We,GLe,0,[()=>wze,0]],QWe=[1,We,lUe,0,()=>Cze],YWe=[1,We,dUe,0,[()=>Tze,0]],eze=[1,We,vUe,0,()=>_ze],tze=[2,We,mje,0,[0,0],[()=>jWe,0]],nze=[2,We,gje,0,[0,0],[()=>rde,0]],rze=[2,We,LLe,8,0,()=>yze],ize=[2,We,BLe,8,0,0],aze=[4,We,EDe,8,[b2,kE],[21,()=>IE]],sze=[4,We,WDe,0,[Xi],[0]],cde=[4,We,GDe,0,[Jqe,YUe,tFe,eFe,uqe],[()=>RWe,()=>CBe,()=>EBe,()=>TBe,()=>vWe]],oze=[4,We,JDe,0,[Xi],[0]],lze=[4,We,DDe,0,[Xi,_2,xue,Vue,MUe,Z8,K8,Cue,G8,Mue,UUe,Lue],[0,[()=>ide,0],()=>nde,()=>lde,[()=>cBe,0],()=>EWe,[()=>SWe,0],[()=>ude,0],()=>Q8,[()=>vze,0],()=>fBe,()=>sde]],cze=[4,We,IDe,0,[Xi,Z8,K8,Mue,ZUe,_2],[0,()=>kWe,()=>QWe,[()=>bze,0],()=>hBe,[()=>sWe,0]]],uze=[4,We,MDe,0,[Z8,K8,_2],[()=>AWe,()=>CWe,()=>oWe]],dze=[4,We,eje,{[wqe]:1},[MFe,jUe,DUe,LUe,$Fe,FFe,xFe,NFe,Hqe,Rqe,hqe],[()=>dWe,()=>yBe,[()=>gBe,0],()=>vBe,()=>pWe,[()=>bBe,0],[()=>Kue,0],[()=>Zue,0],[()=>Yue,0],[()=>Que,0],[()=>Xue,0]]],pze=[4,We,oje,0,[Xi],[0]],fze=[4,We,dje,0,[b2,kE,Xi,w2],[21,()=>IE,0,()=>DWe]],hze=[4,We,vje,0,[Vqe,EFe,mqe,TFe,Cqe,Aqe,BFe],[[()=>LBe,0],[()=>RBe,0],[()=>MBe,0],[()=>kBe,0],[()=>DBe,0],()=>$Be,()=>OBe]],ude=[4,We,Bje,0,[Xi,_2],[()=>zBe,[()=>WBe,0]]],mze=[4,We,Kje,8,[b2],[21]],dde=[4,We,xLe,8,[b2,kE],[21,()=>IE]],gze=[4,We,$Le,8,[kFe],[()=>cWe]],yze=[4,We,ULe,0,[Xi],[0]],vze=[4,We,FLe,8,[nqe,Nue],[[()=>gWe,0],21]],bze=[4,We,qLe,8,[Xi,Nue,que],[0,21,0]],wze=[4,We,HLe,0,[Xi,Cue,G8],[0,[()=>ude,0],()=>Q8]],_ze=[4,We,bUe,0,[Nqe,fqe,G8],[()=>TWe,()=>wWe,()=>Q8]],xze=[4,We,iUe,0,[NUe,PUe,Uqe],[()=>uBe,()=>oBe,()=>bWe]],Sze=[4,We,sUe,0,[J8],[15]],Cze=[4,We,cUe,0,[Xi,J8],[0,15]],Tze=[4,We,pUe,0,[J8,Xi,_2,xue,Vue,Lue],[15,0,[()=>ide,0],()=>nde,()=>lde,()=>sde]],Eze=[4,We,xUe,0,[b2,kE],[21,()=>IE]],kze=[9,We,VDe,{[gFe]:["POST","/model/{modelId}/converse-stream",200]},()=>_Be,()=>xBe];const Aze=e=>({apiVersion:"2023-09-30",base64Decoder:e?.base64Decoder??Ly,base64Encoder:e?.base64Encoder??Fy,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??xDe,extensions:e?.extensions??[],httpAuthSchemeProvider:e?.httpAuthSchemeProvider??J$e,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:t=>t.getIdentityProvider("aws.auth#sigv4"),signer:new tMe},{schemeId:"smithy.api#httpBearerAuth",identityProvider:t=>t.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new b7e}],logger:e?.logger??new Rce,protocol:e?.protocol??QMe,protocolSettings:e?.protocolSettings??{defaultNamespace:"com.amazonaws.bedrockruntime",errorTypeRegistries:aBe,version:"2023-09-30",serviceTarget:"AmazonBedrockFrontendService"},serviceId:e?.serviceId??"Bedrock Runtime",urlParser:e?.urlParser??ZT,utf8Decoder:e?.utf8Decoder??Uy,utf8Encoder:e?.utf8Encoder??Kb}),Rze=e=>{const t=yDe(e),n=()=>t().then($Me),i=Aze(e);return{...i,...e,runtime:"browser",defaultsMode:t,bodyLengthChecker:e?.bodyLengthChecker??PMe,credentialDefaultProvider:e?.credentialDefaultProvider??(r=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:e?.defaultUserAgentProvider??hDe({serviceId:i.serviceId,clientVersion:Y$e.version}),eventStreamPayloadHandlerProvider:e?.eventStreamPayloadHandlerProvider??JNe,eventStreamSerdeProvider:e?.eventStreamSerdeProvider??LNe,maxAttempts:e?.maxAttempts??YT,region:e?.region??mDe("Region is missing"),requestHandler:A8.create(e?.requestHandler??n,L_.create(n)),retryMode:e?.retryMode??(async()=>(await n()).retryMode||y$e),sha256:e?.sha256??fDe,streamCollector:e?.streamCollector??Xle,useDualstackEndpoint:e?.useDualstackEndpoint??(()=>Promise.resolve(KNe)),useFipsEndpoint:e?.useFipsEndpoint??(()=>Promise.resolve(ZNe))}},Oze=e=>({setRegion(t){e.region=t},region(){return e.region}}),Ize=e=>({region:e.region()}),Pze=e=>{const t=e.httpAuthSchemes;let n=e.httpAuthSchemeProvider,i=e.credentials,r=e.token;return{setHttpAuthScheme(a){const l=t.findIndex(c=>c.schemeId===a.schemeId);l===-1?t.push(a):t.splice(l,1,a)},httpAuthSchemes(){return t},setHttpAuthSchemeProvider(a){n=a},httpAuthSchemeProvider(){return n},setCredentials(a){i=a},credentials(){return i},setToken(a){r=a},token(){return r}}},Mze=e=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials(),token:e.token()}),Nze=(e,t)=>{const n=Object.assign(Oze(e),FMe(e),VPe(e),Pze(e));return t.forEach(i=>i.configure(n)),Object.assign(e,Ize(n),qMe(n),JPe(n),Mze(n))};class $ze extends MMe{config;constructor(...[t]){const n=Rze(t||{});super(n),this.initConfig=n;const i=Z$e(n),r=C7e(i),a=D$e(r),l=YNe(a),c=l,o=g$e(c),s=e$e(o),u=K$e(s),d=HPe(u),p=zNe(d),f=Nze(p,t?.extensions||[]);this.config=f,this.middlewareStack.use(A8e(this.config)),this.middlewareStack.use(oNe(this.config)),this.middlewareStack.use(W$e(this.config)),this.middlewareStack.use(r$e(this.config)),this.middlewareStack.use(QPe(this.config)),this.middlewareStack.use(t8e(this.config)),this.middlewareStack.use(i8e(this.config)),this.middlewareStack.use(c8e(this.config,{httpAuthSchemeParametersProvider:G$e,identityProviderConfigProvider:async h=>new v7e({"aws.auth#sigv4":h.credentials,"smithy.api#httpBearerAuth":h.token})})),this.middlewareStack.use(m8e(this.config))}destroy(){super.destroy()}}class Dze extends kce.classBuilder().ep(X$e).m(function(t,n,i,r){return[m$e(i,t.getEndpointParameterInstructions())]}).s("AmazonBedrockFrontendService","ConverseStream",{eventStream:{output:!0}}).n("BedrockRuntimeClient","ConverseStreamCommand").sc(kze).build(){}const pde={ONE_HOUR:"1h"},fde={DEFAULT:"default"},qx={GIF:"gif",JPEG:"jpeg",PNG:"png",WEBP:"webp"},Bx={ERROR:"error",SUCCESS:"success"},Kw={ASSISTANT:"assistant",USER:"user"},t1={END_TURN:"end_turn",MAX_TOKENS:"max_tokens",MODEL_CONTEXT_WINDOW_EXCEEDED:"model_context_window_exceeded",STOP_SEQUENCE:"stop_sequence",TOOL_USE:"tool_use"};var po={};const Zw=(e,t,n={})=>{const i=new Js;return(async()=>{const r={role:"assistant",content:[],api:"bedrock-converse-stream",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()},a=r.content,l={region:n.region,profile:n.profile};if(typeof process<"u"&&(process.versions?.node||process.versions?.bun)){if(l.region=l.region||po.AWS_REGION||po.AWS_DEFAULT_REGION,po.AWS_BEDROCK_SKIP_AUTH==="1"&&(l.credentials={accessKeyId:"dummy-access-key",secretAccessKey:"dummy-secret-key"}),po.HTTP_PROXY||po.HTTPS_PROXY||po.NO_PROXY||po.http_proxy||po.https_proxy||po.no_proxy){const c=await fn(()=>import("./index-DaQtug-G.js"),__vite__mapDeps([0,1])),o=await fn(()=>import("./index-DT33yILt.js").then(u=>u.i),__vite__mapDeps([2,1,3,4])),s=new o.ProxyAgent;l.requestHandler=new c.NodeHttpHandler({httpAgent:s,httpsAgent:s})}else if(po.AWS_BEDROCK_FORCE_HTTP1==="1"){const c=await fn(()=>import("./index-DaQtug-G.js"),__vite__mapDeps([0,1]));l.requestHandler=new c.NodeHttpHandler}}l.region=l.region||"us-east-1";try{const c=new $ze(l),o=Wze(n.cacheRetention),s={modelId:e.id,messages:Vze(t,e,o),system:Gze(t.systemPrompt,e,o),inferenceConfig:{maxTokens:n.maxTokens,temperature:n.temperature},toolConfig:Jze(t.tools,n.toolChoice),additionalModelRequestFields:Zze(e,n)};n?.onPayload?.(s);const u=new Dze(s),d=await c.send(u,{abortSignal:n.signal});for await(const p of d.stream)if(p.messageStart){if(p.messageStart.role!==Kw.ASSISTANT)throw new Error("Unexpected assistant message start but got user message start instead");i.push({type:"start",partial:r})}else if(p.contentBlockStart)Lze(p.contentBlockStart,a,r,i);else if(p.contentBlockDelta)Uze(p.contentBlockDelta,a,r,i);else if(p.contentBlockStop)qze(p.contentBlockStop,a,r,i);else if(p.messageStop)r.stopReason=Kze(p.messageStop.stopReason);else if(p.metadata)Fze(p.metadata,e,r);else{if(p.internalServerException)throw new Error(`Internal server error: ${p.internalServerException.message}`);if(p.modelStreamErrorException)throw new Error(`Model stream error: ${p.modelStreamErrorException.message}`);if(p.validationException)throw new Error(`Validation error: ${p.validationException.message}`);if(p.throttlingException)throw new Error(`Throttling error: ${p.throttlingException.message}`);if(p.serviceUnavailableException)throw new Error(`Service unavailable: ${p.serviceUnavailableException.message}`)}if(n.signal?.aborted)throw new Error("Request was aborted");if(r.stopReason==="error"||r.stopReason==="aborted")throw new Error("An unknown error occurred");i.push({type:"done",reason:r.stopReason,message:r}),i.end()}catch(c){for(const o of r.content)delete o.index,delete o.partialJson;r.stopReason=n.signal?.aborted?"aborted":"error",r.errorMessage=c instanceof Error?c.message:JSON.stringify(c),i.push({type:"error",reason:r.stopReason,error:r}),i.end()}})(),i},jze=(e,t,n)=>{const i=Lc(e,n,void 0);if(!n?.reasoning)return Zw(e,t,{...i,reasoning:void 0});if(e.id.includes("anthropic.claude")||e.id.includes("anthropic/claude")){if(cO(e.id))return Zw(e,t,{...i,reasoning:n.reasoning,thinkingBudgets:n.thinkingBudgets});const r=IP(i.maxTokens||0,e.maxTokens,n.reasoning,n.thinkingBudgets);return Zw(e,t,{...i,maxTokens:r.maxTokens,reasoning:n.reasoning,thinkingBudgets:{...n.thinkingBudgets||{},[Uc(n.reasoning)]:r.thinkingBudget}})}return Zw(e,t,{...i,reasoning:n.reasoning,thinkingBudgets:n.thinkingBudgets})};function Lze(e,t,n,i){const r=e.contentBlockIndex,a=e.start;if(a?.toolUse){const l={type:"toolCall",id:a.toolUse.toolUseId||"",name:a.toolUse.name||"",arguments:{},partialJson:"",index:r};n.content.push(l),i.push({type:"toolcall_start",contentIndex:t.length-1,partial:n})}}function Uze(e,t,n,i){const r=e.contentBlockIndex,a=e.delta;let l=t.findIndex(o=>o.index===r),c=t[l];if(a?.text!==void 0){if(!c){const o={type:"text",text:"",index:r};n.content.push(o),l=t.length-1,c=t[l],i.push({type:"text_start",contentIndex:l,partial:n})}c.type==="text"&&(c.text+=a.text,i.push({type:"text_delta",contentIndex:l,delta:a.text,partial:n}))}else if(a?.toolUse&&c?.type==="toolCall")c.partialJson=(c.partialJson||"")+(a.toolUse.input||""),c.arguments=Rc(c.partialJson),i.push({type:"toolcall_delta",contentIndex:l,delta:a.toolUse.input||"",partial:n});else if(a?.reasoningContent){let o=c,s=l;if(!o){const u={type:"thinking",thinking:"",thinkingSignature:"",index:r};n.content.push(u),s=t.length-1,o=t[s],i.push({type:"thinking_start",contentIndex:s,partial:n})}o?.type==="thinking"&&(a.reasoningContent.text&&(o.thinking+=a.reasoningContent.text,i.push({type:"thinking_delta",contentIndex:s,delta:a.reasoningContent.text,partial:n})),a.reasoningContent.signature&&(o.thinkingSignature=(o.thinkingSignature||"")+a.reasoningContent.signature))}}function Fze(e,t,n){e.usage&&(n.usage.input=e.usage.inputTokens||0,n.usage.output=e.usage.outputTokens||0,n.usage.cacheRead=e.usage.cacheReadInputTokens||0,n.usage.cacheWrite=e.usage.cacheWriteInputTokens||0,n.usage.totalTokens=e.usage.totalTokens||n.usage.input+n.usage.output,wm(t,n.usage))}function qze(e,t,n,i){const r=t.findIndex(l=>l.index===e.contentBlockIndex),a=t[r];if(a)switch(delete a.index,a.type){case"text":i.push({type:"text_end",contentIndex:r,content:a.text,partial:n});break;case"thinking":i.push({type:"thinking_end",contentIndex:r,content:a.thinking,partial:n});break;case"toolCall":a.arguments=Rc(a.partialJson),delete a.partialJson,i.push({type:"toolcall_end",contentIndex:r,toolCall:a,partial:n});break}}function cO(e){return e.includes("opus-4-6")||e.includes("opus-4.6")||e.includes("sonnet-4-6")||e.includes("sonnet-4.6")}function Bze(e,t){switch(e){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";case"xhigh":return t.includes("opus-4-6")||t.includes("opus-4.6")?"max":"high";default:return"high"}}function Wze(e){return e||(typeof process<"u"&&po.PI_CACHE_RETENTION==="long"?"long":"short")}function hde(e){if(e.cost.cacheRead||e.cost.cacheWrite)return!0;const t=e.id.toLowerCase();return!!(t.includes("claude")&&(t.includes("-4-")||t.includes("-4."))||t.includes("claude-3-7-sonnet")||t.includes("claude-3-5-haiku"))}function zze(e){const t=e.id.toLowerCase();return t.includes("anthropic.claude")||t.includes("anthropic/claude")}function Gze(e,t,n){if(!e)return;const i=[{text:Gn(e)}];return n!=="none"&&hde(t)&&i.push({cachePoint:{type:fde.DEFAULT,...n==="long"?{ttl:pde.ONE_HOUR}:{}}}),i}function Hze(e){const t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return t.length>64?t.slice(0,64):t}function Vze(e,t,n){const i=[],r=Bb(e.messages,t,Hze);for(let a=0;a<r.length;a++){const l=r[a];switch(l.role){case"user":i.push({role:Kw.USER,content:typeof l.content=="string"?[{text:Gn(l.content)}]:l.content.map(c=>{switch(c.type){case"text":return{text:Gn(c.text)};case"image":return{image:tA(c.mimeType,c.data)};default:throw new Error("Unknown user content type")}})});break;case"assistant":{if(l.content.length===0)continue;const c=[];for(const o of l.content)switch(o.type){case"text":if(o.text.trim().length===0)continue;c.push({text:Gn(o.text)});break;case"toolCall":c.push({toolUse:{toolUseId:o.id,name:o.name,input:o.arguments}});break;case"thinking":if(o.thinking.trim().length===0)continue;zze(t)?c.push({reasoningContent:{reasoningText:{text:Gn(o.thinking),signature:o.thinkingSignature}}}):c.push({reasoningContent:{reasoningText:{text:Gn(o.thinking)}}});break;default:throw new Error("Unknown assistant content type")}if(c.length===0)continue;i.push({role:Kw.ASSISTANT,content:c});break}case"toolResult":{const c=[];c.push({toolResult:{toolUseId:l.toolCallId,content:l.content.map(s=>s.type==="image"?{image:tA(s.mimeType,s.data)}:{text:Gn(s.text)}),status:l.isError?Bx.ERROR:Bx.SUCCESS}});let o=a+1;for(;o<r.length&&r[o].role==="toolResult";){const s=r[o];c.push({toolResult:{toolUseId:s.toolCallId,content:s.content.map(u=>u.type==="image"?{image:tA(u.mimeType,u.data)}:{text:Gn(u.text)}),status:s.isError?Bx.ERROR:Bx.SUCCESS}}),o++}a=o-1,i.push({role:Kw.USER,content:c});break}default:throw new Error("Unknown message role")}}if(n!=="none"&&hde(t)&&i.length>0){const a=i[i.length-1];a.role===Kw.USER&&a.content&&a.content.push({cachePoint:{type:fde.DEFAULT,...n==="long"?{ttl:pde.ONE_HOUR}:{}}})}return i}function Jze(e,t){if(!e?.length||t==="none")return;const n=e.map(r=>({toolSpec:{name:r.name,description:r.description,inputSchema:{json:r.parameters}}}));let i;switch(t){case"auto":i={auto:{}};break;case"any":i={any:{}};break;default:t?.type==="tool"&&(i={tool:{name:t.name}})}return{tools:n,toolChoice:i}}function Kze(e){switch(e){case t1.END_TURN:case t1.STOP_SEQUENCE:return"stop";case t1.MAX_TOKENS:case t1.MODEL_CONTEXT_WINDOW_EXCEEDED:return"length";case t1.TOOL_USE:return"toolUse";default:return"error"}}function Zze(e,t){if(!(!t.reasoning||!e.reasoning)&&(e.id.includes("anthropic.claude")||e.id.includes("anthropic/claude"))){const n=cO(e.id)?{thinking:{type:"adaptive"},output_config:{effort:Bze(t.reasoning,e.id)}}:(()=>{const i={minimal:1024,low:2048,medium:8192,high:16384,xhigh:16384},r=t.reasoning==="xhigh"?"high":t.reasoning;return{thinking:{type:"enabled",budget_tokens:t.thinkingBudgets?.[r]??i[t.reasoning]}}})();return!cO(e.id)&&(t.interleavedThinking??!0)&&(n.anthropic_beta=["interleaved-thinking-2025-05-14"]),n}}function tA(e,t){let n;switch(e){case"image/jpeg":case"image/jpg":n=qx.JPEG;break;case"image/png":n=qx.PNG;break;case"image/gif":n=qx.GIF;break;case"image/webp":n=qx.WEBP;break;default:throw new Error(`Unknown image type: ${e}`)}const i=atob(t),r=new Uint8Array(i.length);for(let a=0;a<i.length;a++)r[a]=i.charCodeAt(a);return{source:{bytes:r},format:n}}let Xw=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&fn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{Xw=e});const Xze="https://chatgpt.com/backend-api",Qze="https://api.openai.com/auth",nA=3,QF=1e3,Yze=new Set(["openai","openai-codex","opencode"]),eGe=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function tGe(e,t){return e===429||e===500||e===502||e===503||e===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function YF(e,t){return new Promise((n,i)=>{if(t?.aborted){i(new Error("Request was aborted"));return}const r=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(r),i(new Error("Request was aborted"))})})}const mde=(e,t,n)=>{const i=new Js;return(async()=>{const r={role:"assistant",content:[],api:"openai-codex-responses",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const a=n?.apiKey||Vs(e.provider)||"";if(!a)throw new Error(`No API key for provider: ${e.provider}`);const l=bGe(a),c=rGe(e,t,n);n?.onPayload?.(c);const o=wGe(e.headers,n?.headers,l,a,n?.sessionId),s=JSON.stringify(c),u=n?.transport||"sse";if(u!=="sse"){let f=!1;try{if(await yGe(aGe(e.baseUrl),c,o,r,i,e,()=>{f=!0},n),n?.signal?.aborted)throw new Error("Request was aborted");i.push({type:"done",reason:r.stopReason,message:r}),i.end();return}catch(h){if(u==="websocket"||f)throw h}}let d,p;for(let f=0;f<=nA;f++){if(n?.signal?.aborted)throw new Error("Request was aborted");try{if(d=await fetch(gde(e.baseUrl),{method:"POST",headers:o,body:s,signal:n?.signal}),d.ok)break;const h=await d.text();if(f<nA&&tGe(d.status,h)){const y=QF*2**f;await YF(y,n?.signal);continue}const m=new Response(h,{status:d.status,statusText:d.statusText}),g=await vGe(m);throw new Error(g.friendlyMessage||g.message)}catch(h){if(h instanceof Error&&(h.name==="AbortError"||h.message==="Request was aborted"))throw new Error("Request was aborted");if(p=h instanceof Error?h:new Error(String(h)),f<nA&&!p.message.includes("usage limit")){const m=QF*2**f;await YF(m,n?.signal);continue}throw p}}if(!d?.ok)throw p??new Error("Failed after retries");if(!d.body)throw new Error("No response body");if(i.push({type:"start",partial:r}),await sGe(d,r,i,e),n?.signal?.aborted)throw new Error("Request was aborted");i.push({type:"done",reason:r.stopReason,message:r}),i.end()}catch(a){r.stopReason=n?.signal?.aborted?"aborted":"error",r.errorMessage=a instanceof Error?a.message:String(a),i.push({type:"error",reason:r.stopReason,error:r}),i.end()}})(),i},nGe=(e,t,n)=>{const i=n?.apiKey||Vs(e.provider);if(!i)throw new Error(`No API key for provider: ${e.provider}`);const r=Lc(e,n,i),a=Q3(e)?n?.reasoning:Uc(n?.reasoning);return mde(e,t,{...r,reasoningEffort:a})};function rGe(e,t,n){const i=e8(e,t,Yze,{includeSystemPrompt:!1}),r={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt,input:i,text:{verbosity:n?.textVerbosity||"medium"},include:["reasoning.encrypted_content"],prompt_cache_key:n?.sessionId,tool_choice:"auto",parallel_tool_calls:!0};return n?.temperature!==void 0&&(r.temperature=n.temperature),t.tools&&(r.tools=t8(t.tools,{strict:null})),n?.reasoningEffort!==void 0&&(r.reasoning={effort:iGe(e.id,n.reasoningEffort),summary:n.reasoningSummary??"auto"}),r}function iGe(e,t){const n=e.includes("/")?e.split("/").pop():e;return(n.startsWith("gpt-5.2")||n.startsWith("gpt-5.3"))&&t==="minimal"?"low":n==="gpt-5.1"&&t==="xhigh"?"high":n==="gpt-5.1-codex-mini"?t==="high"||t==="xhigh"?"high":"medium":t}function gde(e){const n=(e&&e.trim().length>0?e:Xze).replace(/\/+$/,"");return n.endsWith("/codex/responses")?n:n.endsWith("/codex")?`${n}/responses`:`${n}/codex/responses`}function aGe(e){const t=new URL(gde(e));return t.protocol==="https:"&&(t.protocol="wss:"),t.protocol==="http:"&&(t.protocol="ws:"),t.toString()}async function sGe(e,t,n,i){await dE(yde(lGe(e)),t,n,i)}async function*yde(e){for await(const t of e){const n=typeof t.type=="string"?t.type:void 0;if(n){if(n==="error"){const i=t.code||"",r=t.message||"";throw new Error(`Codex error: ${r||i||JSON.stringify(t)}`)}if(n==="response.failed"){const i=t.response?.error?.message;throw new Error(i||"Codex response failed")}if(n==="response.done"||n==="response.completed"){const i=t.response,r=i&&{...i,status:oGe(i.status)};yield{...t,type:"response.completed",response:r};continue}yield t}}}function oGe(e){if(typeof e=="string")return eGe.has(e)?e:void 0}async function*lGe(e){if(!e.body)return;const t=e.body.getReader(),n=new TextDecoder;let i="";for(;;){const{done:r,value:a}=await t.read();if(r)break;i+=n.decode(a,{stream:!0});let l=i.indexOf(`
526
526
 
527
527
  `);for(;l!==-1;){const c=i.slice(0,l);i=i.slice(l+2);const o=c.split(`
528
528
  `).filter(s=>s.startsWith("data:")).map(s=>s.slice(5).trim());if(o.length>0){const s=o.join(`
529
529
  `).trim();if(s&&s!=="[DONE]")try{yield JSON.parse(s)}catch{}}l=i.indexOf(`
530
530
 
531
- `)}}}const cGe="responses_websockets=2026-02-06",uGe=300*1e3,sy=new Map;function dGe(){const e=globalThis.WebSocket;return typeof e!="function"?null:e}function pGe(e){const t={};for(const[n,i]of e.entries())t[n]=i;return t}function fGe(e){const t=e.readyState;return typeof t=="number"?t:void 0}function Wx(e){const t=fGe(e);return t===void 0||t===1}function oy(e,t=1e3,n="done"){try{e.close(t,n)}catch{}}function eq(e,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{t.busy||(oy(t.socket,1e3,"idle_timeout"),sy.delete(e))},uGe)}async function rA(e,t,n){const i=dGe();if(!i)throw new Error("WebSocket transport is not available in this runtime");const r=pGe(t);return r["OpenAI-Beta"]=cGe,new Promise((a,l)=>{let c=!1,o;try{o=new i(e,{headers:r})}catch(h){l(h instanceof Error?h:new Error(String(h)));return}const s=()=>{c||(c=!0,f(),a(o))},u=h=>{c||(c=!0,f(),l(vde(h)))},d=h=>{c||(c=!0,f(),l(bde(h)))},p=()=>{c||(c=!0,f(),o.close(1e3,"aborted"),l(new Error("Request was aborted")))},f=()=>{o.removeEventListener("open",s),o.removeEventListener("error",u),o.removeEventListener("close",d),n?.removeEventListener("abort",p)};o.addEventListener("open",s),o.addEventListener("error",u),o.addEventListener("close",d),n?.addEventListener("abort",p)})}async function hGe(e,t,n,i){if(!n){const c=await rA(e,t,i);return{socket:c,release:({keep:o}={})=>{if(o===!1){oy(c);return}oy(c)}}}const r=sy.get(n);if(r){if(r.idleTimer&&(clearTimeout(r.idleTimer),r.idleTimer=void 0),!r.busy&&Wx(r.socket))return r.busy=!0,{socket:r.socket,release:({keep:c}={})=>{if(!c||!Wx(r.socket)){oy(r.socket),sy.delete(n);return}r.busy=!1,eq(n,r)}};if(r.busy){const c=await rA(e,t,i);return{socket:c,release:()=>{oy(c)}}}Wx(r.socket)||(oy(r.socket),sy.delete(n))}const a=await rA(e,t,i),l={socket:a,busy:!0};return sy.set(n,l),{socket:a,release:({keep:c}={})=>{if(!c||!Wx(l.socket)){oy(l.socket),l.idleTimer&&clearTimeout(l.idleTimer),sy.get(n)===l&&sy.delete(n);return}l.busy=!1,eq(n,l)}}}function vde(e){if(e&&typeof e=="object"&&"message"in e){const t=e.message;if(typeof t=="string"&&t.length>0)return new Error(t)}return new Error("WebSocket error")}function bde(e){if(e&&typeof e=="object"){const t="code"in e?e.code:void 0,n="reason"in e?e.reason:void 0,i=typeof t=="number"?` ${t}`:"",r=typeof n=="string"&&n.length>0?` ${n}`:"";return new Error(`WebSocket closed${i}${r}`.trim())}return new Error("WebSocket closed")}async function mGe(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){const t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(e&&typeof e=="object"&&"arrayBuffer"in e){const n=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(n))}return null}async function*gGe(e,t){const n=[];let i=null,r=!1,a=null,l=!1;const c=()=>{if(!i)return;const p=i;i=null,p()},o=p=>{(async()=>{if(!p||typeof p!="object"||!("data"in p))return;const f=await mGe(p.data);if(f)try{const h=JSON.parse(f),m=typeof h.type=="string"?h.type:"";(m==="response.completed"||m==="response.done")&&(l=!0,r=!0),n.push(h),c()}catch{}})()},s=p=>{a=vde(p),r=!0,c()},u=p=>{if(l){r=!0,c();return}a||(a=bde(p)),r=!0,c()},d=()=>{a=new Error("Request was aborted"),r=!0,c()};e.addEventListener("message",o),e.addEventListener("error",s),e.addEventListener("close",u),t?.addEventListener("abort",d);try{for(;;){if(t?.aborted)throw new Error("Request was aborted");if(n.length>0){yield n.shift();continue}if(r)break;await new Promise(p=>{i=p})}if(a)throw a;if(!l)throw new Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",o),e.removeEventListener("error",s),e.removeEventListener("close",u),t?.removeEventListener("abort",d)}}async function yGe(e,t,n,i,r,a,l,c){const{socket:o,release:s}=await hGe(e,n,c?.sessionId,c?.signal);let u=!0;try{o.send(JSON.stringify({type:"response.create",...t})),l(),r.push({type:"start",partial:i}),await dE(yde(gGe(o,c?.signal)),i,r,a),c?.signal?.aborted&&(u=!1)}catch(d){throw u=!1,d}finally{s({keep:u})}}async function vGe(e){const t=await e.text();let n=t||e.statusText||"Request failed",i;try{const a=JSON.parse(t)?.error;if(a){const l=a.code||a.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(l)||e.status===429){const c=a.plan_type?` (${a.plan_type.toLowerCase()} plan)`:"",o=a.resets_at?Math.max(0,Math.round((a.resets_at*1e3-Date.now())/6e4)):void 0,s=o!==void 0?` Try again in ~${o} min.`:"";i=`You have hit your ChatGPT usage limit${c}.${s}`.trim()}n=a.message||i||n}}catch{}return{message:n,friendlyMessage:i}}function bGe(e){try{const t=e.split(".");if(t.length!==3)throw new Error("Invalid token");const i=JSON.parse(atob(t[1]))?.[Qze]?.chatgpt_account_id;if(!i)throw new Error("No account ID in token");return i}catch{throw new Error("Failed to extract accountId from token")}}function wGe(e,t,n,i,r){const a=new Headers(e);a.set("Authorization",`Bearer ${i}`),a.set("chatgpt-account-id",n),a.set("OpenAI-Beta","responses=experimental"),a.set("originator","pi");const l=Xw?`pi (${Xw.platform()} ${Xw.release()}; ${Xw.arch()})`:"pi (browser)";a.set("User-Agent",l),a.set("accept","text/event-stream"),a.set("content-type","application/json");for(const[c,o]of Object.entries(t||{}))a.set(c,o);return r&&a.set("session_id",r),a}function _Ge(){Ps({api:"anthropic-messages",stream:m_,streamSimple:use}),Ps({api:"openai-completions",stream:m8,streamSimple:Vle}),Ps({api:"openai-responses",stream:Jle,streamSimple:qPe}),Ps({api:"azure-openai-responses",stream:Joe,streamSimple:g6e}),Ps({api:"openai-codex-responses",stream:mde,streamSimple:nGe}),Ps({api:"google-generative-ai",stream:PC,streamSimple:ZIe}),Ps({api:"google-gemini-cli",stream:MC,streamSimple:hPe}),Ps({api:"google-vertex",stream:NC,streamSimple:wPe}),Ps({api:"bedrock-converse-stream",stream:Zw,streamSimple:jze})}_Ge();typeof process<"u"&&process.versions?.node&&fn(()=>import("./index-Cj6gFnz_.js").then(e=>e.i),__vite__mapDeps([5,3,4])).then(e=>{const{EnvHttpProxyAgent:t,setGlobalDispatcher:n}=e;n(new t)});function xGe(e){const t=U3e(e);if(!t)throw new Error(`No API provider registered for api: ${e}`);return t}function wde(e,t,n){return xGe(e.api).streamSimple(e,t,n)}function tq(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function PE(){const e=new Uint8Array(32);crypto.getRandomValues(e);const t=tq(e),i=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",i),a=tq(new Uint8Array(r));return{verifier:t,challenge:a}}const SGe=e=>atob(e),uO=SGe("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl"),CGe="https://claude.ai/oauth/authorize",_de="https://console.anthropic.com/v1/oauth/token",nq="https://console.anthropic.com/oauth/code/callback",TGe="org:create_api_key user:profile user:inference";async function EGe(e,t){const{verifier:n,challenge:i}=await PE(),r=new URLSearchParams({code:"true",client_id:uO,response_type:"code",redirect_uri:nq,scope:TGe,code_challenge:i,code_challenge_method:"S256",state:n}),a=`${CGe}?${r.toString()}`;e(a);const c=(await t()).split("#"),o=c[0],s=c[1],u=await fetch(_de,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:uO,code:o,state:s,redirect_uri:nq,code_verifier:n})});if(!u.ok){const f=await u.text();throw new Error(`Token exchange failed: ${f}`)}const d=await u.json(),p=Date.now()+d.expires_in*1e3-300*1e3;return{refresh:d.refresh_token,access:d.access_token,expires:p}}async function kGe(e){const t=await fetch(_de,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:uO,refresh_token:e})});if(!t.ok){const i=await t.text();throw new Error(`Anthropic token refresh failed: ${i}`)}const n=await t.json();return{refresh:n.refresh_token,access:n.access_token,expires:Date.now()+n.expires_in*1e3-300*1e3}}const AGe={id:"anthropic",name:"Anthropic (Claude Pro/Max)",async login(e){return EGe(t=>e.onAuth({url:t}),()=>e.onPrompt({message:"Paste the authorization code:"}))},async refreshToken(e){return kGe(e.refresh)},getApiKey(e){return e.access}},RGe=e=>atob(e),xde=RGe("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),Sde={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"};function Cde(e){const t=e.trim();if(!t)return null;try{return(t.includes("://")?new URL(t):new URL(`https://${t}`)).hostname}catch{return null}}function t7(e){return{deviceCodeUrl:`https://${e}/login/device/code`,accessTokenUrl:`https://${e}/login/oauth/access_token`,copilotTokenUrl:`https://api.${e}/copilot_internal/v2/token`}}function OGe(e){const t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,"api.")}`:null}function Tde(e,t){if(e){const n=OGe(e);if(n)return n}return t?`https://copilot-api.${t}`:"https://api.individual.githubcopilot.com"}async function n7(e,t){const n=await fetch(e,t);if(!n.ok){const i=await n.text();throw new Error(`${n.status} ${n.statusText}: ${i}`)}return n.json()}async function IGe(e){const t=t7(e),n=await n7(t.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"GitHubCopilotChat/0.35.0"},body:JSON.stringify({client_id:xde,scope:"read:user"})});if(!n||typeof n!="object")throw new Error("Invalid device code response");const i=n.device_code,r=n.user_code,a=n.verification_uri,l=n.interval,c=n.expires_in;if(typeof i!="string"||typeof r!="string"||typeof a!="string"||typeof l!="number"||typeof c!="number")throw new Error("Invalid device code response fields");return{device_code:i,user_code:r,verification_uri:a,interval:l,expires_in:c}}function iA(e,t){return new Promise((n,i)=>{if(t?.aborted){i(new Error("Login cancelled"));return}const r=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(r),i(new Error("Login cancelled"))},{once:!0})})}async function PGe(e,t,n,i,r){const a=t7(e),l=Date.now()+i*1e3;let c=Math.max(1e3,Math.floor(n*1e3));for(;Date.now()<l;){if(r?.aborted)throw new Error("Login cancelled");const o=await n7(a.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"GitHubCopilotChat/0.35.0"},body:JSON.stringify({client_id:xde,device_code:t,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(o&&typeof o=="object"&&typeof o.access_token=="string")return o.access_token;if(o&&typeof o=="object"&&typeof o.error=="string"){const s=o.error;if(s==="authorization_pending"){await iA(c,r);continue}if(s==="slow_down"){c+=5e3,await iA(c,r);continue}throw new Error(`Device flow failed: ${s}`)}await iA(c,r)}throw new Error("Device flow timed out")}async function Ede(e,t){const i=t7(t||"github.com"),r=await n7(i.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`,...Sde}});if(!r||typeof r!="object")throw new Error("Invalid Copilot token response");const a=r.token,l=r.expires_at;if(typeof a!="string"||typeof l!="number")throw new Error("Invalid Copilot token response fields");return{refresh:e,access:a,expires:l*1e3-300*1e3,enterpriseUrl:t}}async function MGe(e,t,n){const r=`${Tde(e,n)}/models/${t}/policy`;try{return(await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...Sde,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})})).ok}catch{return!1}}async function NGe(e,t,n){const i=RT("github-copilot");await Promise.all(i.map(async r=>{await MGe(e,r.id,t)}))}async function $Ge(e){const t=await e.onPrompt({message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com",allowEmpty:!0});if(e.signal?.aborted)throw new Error("Login cancelled");const n=t.trim(),i=Cde(t);if(n&&!i)throw new Error("Invalid GitHub Enterprise URL/domain");const r=i||"github.com",a=await IGe(r);e.onAuth(a.verification_uri,`Enter code: ${a.user_code}`);const l=await PGe(r,a.device_code,a.interval,a.expires_in,e.signal),c=await Ede(l,i??void 0);return e.onProgress?.("Enabling models..."),await NGe(c.access,i??void 0),c}const DGe={id:"github-copilot",name:"GitHub Copilot",async login(e){return $Ge({onAuth:(t,n)=>e.onAuth({url:t,instructions:n}),onPrompt:e.onPrompt,onProgress:e.onProgress,signal:e.signal})},async refreshToken(e){const t=e;return Ede(t.refresh,t.enterpriseUrl)},getApiKey(e){return e.access},modifyModels(e,t){const n=t,i=n.enterpriseUrl?Cde(n.enterpriseUrl)??void 0:void 0,r=Tde(n.access,i);return e.map(a=>a.provider==="github-copilot"?{...a,baseUrl:r}:a)}};let Qw=null,dO=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(dO=fn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{Qw=e.createServer}));const kde=e=>atob(e),pO=kde("MTA3MTAwNjA2MDU5MS10bWhzc2luMmgyMWxjcmUyMzV2dG9sb2poNGc0MDNlcC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbQ=="),Ade=kde("R09DU1BYLUs1OEZXUjQ4NkxkTEoxbUxCOHNYQzR6NnFEQWY="),rq="http://localhost:51121/oauth-callback",jGe=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/cclog","https://www.googleapis.com/auth/experimentsandconfigs"],LGe="https://accounts.google.com/o/oauth2/v2/auth",Rde="https://oauth2.googleapis.com/token",UGe="rising-fact-p41fc";async function FGe(){if(Qw||(dO&&await dO,Qw))return Qw;throw new Error("Antigravity OAuth is only available in Node.js environments")}async function qGe(){const e=await FGe();return new Promise((t,n)=>{let i=null,r=!1;const a=e((l,c)=>{const o=new URL(l.url||"","http://localhost:51121");if(o.pathname==="/oauth-callback"){const s=o.searchParams.get("code"),u=o.searchParams.get("state"),d=o.searchParams.get("error");if(d){c.writeHead(400,{"Content-Type":"text/html"}),c.end(`<html><body><h1>Authentication Failed</h1><p>Error: ${d}</p><p>You can close this window.</p></body></html>`);return}s&&u?(c.writeHead(200,{"Content-Type":"text/html"}),c.end("<html><body><h1>Authentication Successful</h1><p>You can close this window and return to the terminal.</p></body></html>"),i={code:s,state:u}):(c.writeHead(400,{"Content-Type":"text/html"}),c.end("<html><body><h1>Authentication Failed</h1><p>Missing code or state parameter.</p></body></html>"))}else c.writeHead(404),c.end()});a.on("error",l=>{n(l)}),a.listen(51121,"127.0.0.1",()=>{t({server:a,cancelWait:()=>{r=!0},waitForCode:async()=>{const l=()=>new Promise(c=>setTimeout(c,100));for(;!i&&!r;)await l();return i}})})})}function iq(e){const t=e.trim();if(!t)return{};try{const n=new URL(t);return{code:n.searchParams.get("code")??void 0,state:n.searchParams.get("state")??void 0}}catch{return{}}}async function BGe(e,t){const n={Authorization:`Bearer ${e}`,"Content-Type":"application/json","User-Agent":"google-api-nodejs-client/9.15.1","X-Goog-Api-Client":"google-cloud-sdk vscode_cloudshelleditor/0.1","Client-Metadata":JSON.stringify({ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"})},i=["https://cloudcode-pa.googleapis.com","https://daily-cloudcode-pa.sandbox.googleapis.com"];t?.("Checking for existing project...");for(const r of i)try{const a=await fetch(`${r}/v1internal:loadCodeAssist`,{method:"POST",headers:n,body:JSON.stringify({metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}})});if(a.ok){const l=await a.json();if(typeof l.cloudaicompanionProject=="string"&&l.cloudaicompanionProject)return l.cloudaicompanionProject;if(l.cloudaicompanionProject&&typeof l.cloudaicompanionProject=="object"&&l.cloudaicompanionProject.id)return l.cloudaicompanionProject.id}}catch{}return t?.("Using default project..."),UGe}async function WGe(e){try{const t=await fetch("https://www.googleapis.com/oauth2/v1/userinfo?alt=json",{headers:{Authorization:`Bearer ${e}`}});if(t.ok)return(await t.json()).email}catch{}}async function zGe(e,t){const n=await fetch(Rde,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:pO,client_secret:Ade,refresh_token:e,grant_type:"refresh_token"})});if(!n.ok){const r=await n.text();throw new Error(`Antigravity token refresh failed: ${r}`)}const i=await n.json();return{refresh:i.refresh_token||e,access:i.access_token,expires:Date.now()+i.expires_in*1e3-300*1e3,projectId:t}}async function GGe(e,t,n){const{verifier:i,challenge:r}=await PE();t?.("Starting local server for OAuth callback...");const a=await qGe();let l;try{const c=new URLSearchParams({client_id:pO,response_type:"code",redirect_uri:rq,scope:jGe.join(" "),code_challenge:r,code_challenge_method:"S256",state:i,access_type:"offline",prompt:"consent"}),o=`${LGe}?${c.toString()}`;if(e({url:o,instructions:"Complete the sign-in in your browser."}),t?.("Waiting for OAuth callback..."),n){let m,g;const y=n().then(b=>{m=b,a.cancelWait()}).catch(b=>{g=b instanceof Error?b:new Error(String(b)),a.cancelWait()}),v=await a.waitForCode();if(g)throw g;if(v?.code){if(v.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");l=v.code}else if(m){const b=iq(m);if(b.state&&b.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");l=b.code}if(!l){if(await y,g)throw g;if(m){const b=iq(m);if(b.state&&b.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");l=b.code}}}else{const m=await a.waitForCode();if(m?.code){if(m.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");l=m.code}}if(!l)throw new Error("No authorization code received");t?.("Exchanging authorization code for tokens...");const s=await fetch(Rde,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:pO,client_secret:Ade,code:l,grant_type:"authorization_code",redirect_uri:rq,code_verifier:i})});if(!s.ok){const m=await s.text();throw new Error(`Token exchange failed: ${m}`)}const u=await s.json();if(!u.refresh_token)throw new Error("No refresh token received. Please try again.");t?.("Getting user info...");const d=await WGe(u.access_token),p=await BGe(u.access_token,t),f=Date.now()+u.expires_in*1e3-300*1e3;return{refresh:u.refresh_token,access:u.access_token,expires:f,projectId:p,email:d}}finally{a.server.close()}}const HGe={id:"google-antigravity",name:"Antigravity (Gemini 3, Claude, GPT-OSS)",usesCallbackServer:!0,async login(e){return GGe(e.onAuth,e.onProgress,e.onManualCodeInput)},async refreshToken(e){const t=e;if(!t.projectId)throw new Error("Antigravity credentials missing projectId");return zGe(t.refresh,t.projectId)},getApiKey(e){const t=e;return JSON.stringify({token:t.access,projectId:t.projectId})}};var aq={};let Yw=null,fO=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(fO=fn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{Yw=e.createServer}));const Ode=e=>atob(e),hO=Ode("NjgxMjU1ODA5Mzk1LW9vOGZ0Mm9wcmRybnA5ZTNhcWY2YXYzaG1kaWIxMzVqLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29t"),Ide=Ode("R09DU1BYLTR1SGdNUG0tMW83U2stZ2VWNkN1NWNsWEZzeGw="),sq="http://localhost:8085/oauth2callback",VGe=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile"],JGe="https://accounts.google.com/o/oauth2/v2/auth",Pde="https://oauth2.googleapis.com/token",mO="https://cloudcode-pa.googleapis.com";async function KGe(){if(Yw||(fO&&await fO,Yw))return Yw;throw new Error("Gemini CLI OAuth is only available in Node.js environments")}async function ZGe(){const e=await KGe();return new Promise((t,n)=>{let i=null,r=!1;const a=e((l,c)=>{const o=new URL(l.url||"","http://localhost:8085");if(o.pathname==="/oauth2callback"){const s=o.searchParams.get("code"),u=o.searchParams.get("state"),d=o.searchParams.get("error");if(d){c.writeHead(400,{"Content-Type":"text/html"}),c.end(`<html><body><h1>Authentication Failed</h1><p>Error: ${d}</p><p>You can close this window.</p></body></html>`);return}s&&u?(c.writeHead(200,{"Content-Type":"text/html"}),c.end("<html><body><h1>Authentication Successful</h1><p>You can close this window and return to the terminal.</p></body></html>"),i={code:s,state:u}):(c.writeHead(400,{"Content-Type":"text/html"}),c.end("<html><body><h1>Authentication Failed</h1><p>Missing code or state parameter.</p></body></html>"))}else c.writeHead(404),c.end()});a.on("error",l=>{n(l)}),a.listen(8085,"127.0.0.1",()=>{t({server:a,cancelWait:()=>{r=!0},waitForCode:async()=>{const l=()=>new Promise(c=>setTimeout(c,100));for(;!i&&!r;)await l();return i}})})})}function oq(e){const t=e.trim();if(!t)return{};try{const n=new URL(t);return{code:n.searchParams.get("code")??void 0,state:n.searchParams.get("state")??void 0}}catch{return{}}}const aA="free-tier",lq="legacy-tier",XGe="standard-tier";function QGe(e){return new Promise(t=>setTimeout(t,e))}function YGe(e){return!e||e.length===0?{id:lq}:e.find(n=>n.isDefault)??{id:lq}}function eHe(e){if(!e||typeof e!="object"||!("error"in e))return!1;const t=e.error;return!t?.details||!Array.isArray(t.details)?!1:t.details.some(n=>n.reason==="SECURITY_POLICY_VIOLATED")}async function tHe(e,t,n){let i=0;for(;;){i>0&&(n?.(`Waiting for project provisioning (attempt ${i+1})...`),await QGe(5e3));const r=await fetch(`${mO}/v1internal/${e}`,{method:"GET",headers:t});if(!r.ok)throw new Error(`Failed to poll operation: ${r.status} ${r.statusText}`);const a=await r.json();if(a.done)return a;i+=1}}async function nHe(e,t){const n=aq.GOOGLE_CLOUD_PROJECT||aq.GOOGLE_CLOUD_PROJECT_ID,i={Authorization:`Bearer ${e}`,"Content-Type":"application/json","User-Agent":"google-api-nodejs-client/9.15.1","X-Goog-Api-Client":"gl-node/22.17.0"};t?.("Checking for existing Cloud Code Assist project...");const r=await fetch(`${mO}/v1internal:loadCodeAssist`,{method:"POST",headers:i,body:JSON.stringify({cloudaicompanionProject:n,metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI",duetProject:n}})});let a;if(r.ok)a=await r.json();else{let p;try{p=await r.clone().json()}catch{p=void 0}if(eHe(p))a={currentTier:{id:XGe}};else{const f=await r.text();throw new Error(`loadCodeAssist failed: ${r.status} ${r.statusText}: ${f}`)}}if(a.currentTier){if(a.cloudaicompanionProject)return a.cloudaicompanionProject;if(n)return n;throw new Error("This account requires setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID environment variable. See https://goo.gle/gemini-cli-auth-docs#workspace-gca")}const c=YGe(a.allowedTiers)?.id??aA;if(c!==aA&&!n)throw new Error("This account requires setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID environment variable. See https://goo.gle/gemini-cli-auth-docs#workspace-gca");t?.("Provisioning Cloud Code Assist project (this may take a moment)...");const o={tierId:c,metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}};c!==aA&&n&&(o.cloudaicompanionProject=n,o.metadata.duetProject=n);const s=await fetch(`${mO}/v1internal:onboardUser`,{method:"POST",headers:i,body:JSON.stringify(o)});if(!s.ok){const p=await s.text();throw new Error(`onboardUser failed: ${s.status} ${s.statusText}: ${p}`)}let u=await s.json();!u.done&&u.name&&(u=await tHe(u.name,i,t));const d=u.response?.cloudaicompanionProject?.id;if(d)return d;if(n)return n;throw new Error("Could not discover or provision a Google Cloud project. Try setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID environment variable. See https://goo.gle/gemini-cli-auth-docs#workspace-gca")}async function rHe(e){try{const t=await fetch("https://www.googleapis.com/oauth2/v1/userinfo?alt=json",{headers:{Authorization:`Bearer ${e}`}});if(t.ok)return(await t.json()).email}catch{}}async function iHe(e,t){const n=await fetch(Pde,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:hO,client_secret:Ide,refresh_token:e,grant_type:"refresh_token"})});if(!n.ok){const r=await n.text();throw new Error(`Google Cloud token refresh failed: ${r}`)}const i=await n.json();return{refresh:i.refresh_token||e,access:i.access_token,expires:Date.now()+i.expires_in*1e3-300*1e3,projectId:t}}async function aHe(e,t,n){const{verifier:i,challenge:r}=await PE();t?.("Starting local server for OAuth callback...");const a=await ZGe();let l;try{const c=new URLSearchParams({client_id:hO,response_type:"code",redirect_uri:sq,scope:VGe.join(" "),code_challenge:r,code_challenge_method:"S256",state:i,access_type:"offline",prompt:"consent"}),o=`${JGe}?${c.toString()}`;if(e({url:o,instructions:"Complete the sign-in in your browser."}),t?.("Waiting for OAuth callback..."),n){let m,g;const y=n().then(b=>{m=b,a.cancelWait()}).catch(b=>{g=b instanceof Error?b:new Error(String(b)),a.cancelWait()}),v=await a.waitForCode();if(g)throw g;if(v?.code){if(v.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");l=v.code}else if(m){const b=oq(m);if(b.state&&b.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");l=b.code}if(!l){if(await y,g)throw g;if(m){const b=oq(m);if(b.state&&b.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");l=b.code}}}else{const m=await a.waitForCode();if(m?.code){if(m.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");l=m.code}}if(!l)throw new Error("No authorization code received");t?.("Exchanging authorization code for tokens...");const s=await fetch(Pde,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:hO,client_secret:Ide,code:l,grant_type:"authorization_code",redirect_uri:sq,code_verifier:i})});if(!s.ok){const m=await s.text();throw new Error(`Token exchange failed: ${m}`)}const u=await s.json();if(!u.refresh_token)throw new Error("No refresh token received. Please try again.");t?.("Getting user info...");const d=await rHe(u.access_token),p=await nHe(u.access_token,t),f=Date.now()+u.expires_in*1e3-300*1e3;return{refresh:u.refresh_token,access:u.access_token,expires:f,projectId:p,email:d}}finally{a.server.close()}}const sHe={id:"google-gemini-cli",name:"Google Cloud Code Assist (Gemini CLI)",usesCallbackServer:!0,async login(e){return aHe(e.onAuth,e.onProgress,e.onManualCodeInput)},async refreshToken(e){const t=e;if(!t.projectId)throw new Error("Google Cloud credentials missing projectId");return iHe(t.refresh,t.projectId)},getApiKey(e){const t=e;return JSON.stringify({token:t.access,projectId:t.projectId})}};let gO=null,yO=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(fn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{gO=e.randomBytes}),fn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{yO=e}));const r7="app_EMoamEEZ73f0CkXaXp7hrann",oHe="https://auth.openai.com/oauth/authorize",Mde="https://auth.openai.com/oauth/token",Nde="http://localhost:1455/auth/callback",lHe="openid profile email offline_access",cHe="https://api.openai.com/auth",uHe=`<!doctype html>
531
+ `)}}}const cGe="responses_websockets=2026-02-06",uGe=300*1e3,sy=new Map;function dGe(){const e=globalThis.WebSocket;return typeof e!="function"?null:e}function pGe(e){const t={};for(const[n,i]of e.entries())t[n]=i;return t}function fGe(e){const t=e.readyState;return typeof t=="number"?t:void 0}function Wx(e){const t=fGe(e);return t===void 0||t===1}function oy(e,t=1e3,n="done"){try{e.close(t,n)}catch{}}function eq(e,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{t.busy||(oy(t.socket,1e3,"idle_timeout"),sy.delete(e))},uGe)}async function rA(e,t,n){const i=dGe();if(!i)throw new Error("WebSocket transport is not available in this runtime");const r=pGe(t);return r["OpenAI-Beta"]=cGe,new Promise((a,l)=>{let c=!1,o;try{o=new i(e,{headers:r})}catch(h){l(h instanceof Error?h:new Error(String(h)));return}const s=()=>{c||(c=!0,f(),a(o))},u=h=>{c||(c=!0,f(),l(vde(h)))},d=h=>{c||(c=!0,f(),l(bde(h)))},p=()=>{c||(c=!0,f(),o.close(1e3,"aborted"),l(new Error("Request was aborted")))},f=()=>{o.removeEventListener("open",s),o.removeEventListener("error",u),o.removeEventListener("close",d),n?.removeEventListener("abort",p)};o.addEventListener("open",s),o.addEventListener("error",u),o.addEventListener("close",d),n?.addEventListener("abort",p)})}async function hGe(e,t,n,i){if(!n){const c=await rA(e,t,i);return{socket:c,release:({keep:o}={})=>{if(o===!1){oy(c);return}oy(c)}}}const r=sy.get(n);if(r){if(r.idleTimer&&(clearTimeout(r.idleTimer),r.idleTimer=void 0),!r.busy&&Wx(r.socket))return r.busy=!0,{socket:r.socket,release:({keep:c}={})=>{if(!c||!Wx(r.socket)){oy(r.socket),sy.delete(n);return}r.busy=!1,eq(n,r)}};if(r.busy){const c=await rA(e,t,i);return{socket:c,release:()=>{oy(c)}}}Wx(r.socket)||(oy(r.socket),sy.delete(n))}const a=await rA(e,t,i),l={socket:a,busy:!0};return sy.set(n,l),{socket:a,release:({keep:c}={})=>{if(!c||!Wx(l.socket)){oy(l.socket),l.idleTimer&&clearTimeout(l.idleTimer),sy.get(n)===l&&sy.delete(n);return}l.busy=!1,eq(n,l)}}}function vde(e){if(e&&typeof e=="object"&&"message"in e){const t=e.message;if(typeof t=="string"&&t.length>0)return new Error(t)}return new Error("WebSocket error")}function bde(e){if(e&&typeof e=="object"){const t="code"in e?e.code:void 0,n="reason"in e?e.reason:void 0,i=typeof t=="number"?` ${t}`:"",r=typeof n=="string"&&n.length>0?` ${n}`:"";return new Error(`WebSocket closed${i}${r}`.trim())}return new Error("WebSocket closed")}async function mGe(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){const t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(e&&typeof e=="object"&&"arrayBuffer"in e){const n=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(n))}return null}async function*gGe(e,t){const n=[];let i=null,r=!1,a=null,l=!1;const c=()=>{if(!i)return;const p=i;i=null,p()},o=p=>{(async()=>{if(!p||typeof p!="object"||!("data"in p))return;const f=await mGe(p.data);if(f)try{const h=JSON.parse(f),m=typeof h.type=="string"?h.type:"";(m==="response.completed"||m==="response.done")&&(l=!0,r=!0),n.push(h),c()}catch{}})()},s=p=>{a=vde(p),r=!0,c()},u=p=>{if(l){r=!0,c();return}a||(a=bde(p)),r=!0,c()},d=()=>{a=new Error("Request was aborted"),r=!0,c()};e.addEventListener("message",o),e.addEventListener("error",s),e.addEventListener("close",u),t?.addEventListener("abort",d);try{for(;;){if(t?.aborted)throw new Error("Request was aborted");if(n.length>0){yield n.shift();continue}if(r)break;await new Promise(p=>{i=p})}if(a)throw a;if(!l)throw new Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",o),e.removeEventListener("error",s),e.removeEventListener("close",u),t?.removeEventListener("abort",d)}}async function yGe(e,t,n,i,r,a,l,c){const{socket:o,release:s}=await hGe(e,n,c?.sessionId,c?.signal);let u=!0;try{o.send(JSON.stringify({type:"response.create",...t})),l(),r.push({type:"start",partial:i}),await dE(yde(gGe(o,c?.signal)),i,r,a),c?.signal?.aborted&&(u=!1)}catch(d){throw u=!1,d}finally{s({keep:u})}}async function vGe(e){const t=await e.text();let n=t||e.statusText||"Request failed",i;try{const a=JSON.parse(t)?.error;if(a){const l=a.code||a.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(l)||e.status===429){const c=a.plan_type?` (${a.plan_type.toLowerCase()} plan)`:"",o=a.resets_at?Math.max(0,Math.round((a.resets_at*1e3-Date.now())/6e4)):void 0,s=o!==void 0?` Try again in ~${o} min.`:"";i=`You have hit your ChatGPT usage limit${c}.${s}`.trim()}n=a.message||i||n}}catch{}return{message:n,friendlyMessage:i}}function bGe(e){try{const t=e.split(".");if(t.length!==3)throw new Error("Invalid token");const i=JSON.parse(atob(t[1]))?.[Qze]?.chatgpt_account_id;if(!i)throw new Error("No account ID in token");return i}catch{throw new Error("Failed to extract accountId from token")}}function wGe(e,t,n,i,r){const a=new Headers(e);a.set("Authorization",`Bearer ${i}`),a.set("chatgpt-account-id",n),a.set("OpenAI-Beta","responses=experimental"),a.set("originator","pi");const l=Xw?`pi (${Xw.platform()} ${Xw.release()}; ${Xw.arch()})`:"pi (browser)";a.set("User-Agent",l),a.set("accept","text/event-stream"),a.set("content-type","application/json");for(const[c,o]of Object.entries(t||{}))a.set(c,o);return r&&a.set("session_id",r),a}function _Ge(){Ps({api:"anthropic-messages",stream:m_,streamSimple:use}),Ps({api:"openai-completions",stream:m8,streamSimple:Vle}),Ps({api:"openai-responses",stream:Jle,streamSimple:qPe}),Ps({api:"azure-openai-responses",stream:Joe,streamSimple:g6e}),Ps({api:"openai-codex-responses",stream:mde,streamSimple:nGe}),Ps({api:"google-generative-ai",stream:PC,streamSimple:ZIe}),Ps({api:"google-gemini-cli",stream:MC,streamSimple:hPe}),Ps({api:"google-vertex",stream:NC,streamSimple:wPe}),Ps({api:"bedrock-converse-stream",stream:Zw,streamSimple:jze})}_Ge();typeof process<"u"&&process.versions?.node&&fn(()=>import("./index-CqKk1FTy.js").then(e=>e.i),__vite__mapDeps([5,3,4])).then(e=>{const{EnvHttpProxyAgent:t,setGlobalDispatcher:n}=e;n(new t)});function xGe(e){const t=U3e(e);if(!t)throw new Error(`No API provider registered for api: ${e}`);return t}function wde(e,t,n){return xGe(e.api).streamSimple(e,t,n)}function tq(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function PE(){const e=new Uint8Array(32);crypto.getRandomValues(e);const t=tq(e),i=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",i),a=tq(new Uint8Array(r));return{verifier:t,challenge:a}}const SGe=e=>atob(e),uO=SGe("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl"),CGe="https://claude.ai/oauth/authorize",_de="https://console.anthropic.com/v1/oauth/token",nq="https://console.anthropic.com/oauth/code/callback",TGe="org:create_api_key user:profile user:inference";async function EGe(e,t){const{verifier:n,challenge:i}=await PE(),r=new URLSearchParams({code:"true",client_id:uO,response_type:"code",redirect_uri:nq,scope:TGe,code_challenge:i,code_challenge_method:"S256",state:n}),a=`${CGe}?${r.toString()}`;e(a);const c=(await t()).split("#"),o=c[0],s=c[1],u=await fetch(_de,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:uO,code:o,state:s,redirect_uri:nq,code_verifier:n})});if(!u.ok){const f=await u.text();throw new Error(`Token exchange failed: ${f}`)}const d=await u.json(),p=Date.now()+d.expires_in*1e3-300*1e3;return{refresh:d.refresh_token,access:d.access_token,expires:p}}async function kGe(e){const t=await fetch(_de,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:uO,refresh_token:e})});if(!t.ok){const i=await t.text();throw new Error(`Anthropic token refresh failed: ${i}`)}const n=await t.json();return{refresh:n.refresh_token,access:n.access_token,expires:Date.now()+n.expires_in*1e3-300*1e3}}const AGe={id:"anthropic",name:"Anthropic (Claude Pro/Max)",async login(e){return EGe(t=>e.onAuth({url:t}),()=>e.onPrompt({message:"Paste the authorization code:"}))},async refreshToken(e){return kGe(e.refresh)},getApiKey(e){return e.access}},RGe=e=>atob(e),xde=RGe("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),Sde={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"};function Cde(e){const t=e.trim();if(!t)return null;try{return(t.includes("://")?new URL(t):new URL(`https://${t}`)).hostname}catch{return null}}function t7(e){return{deviceCodeUrl:`https://${e}/login/device/code`,accessTokenUrl:`https://${e}/login/oauth/access_token`,copilotTokenUrl:`https://api.${e}/copilot_internal/v2/token`}}function OGe(e){const t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,"api.")}`:null}function Tde(e,t){if(e){const n=OGe(e);if(n)return n}return t?`https://copilot-api.${t}`:"https://api.individual.githubcopilot.com"}async function n7(e,t){const n=await fetch(e,t);if(!n.ok){const i=await n.text();throw new Error(`${n.status} ${n.statusText}: ${i}`)}return n.json()}async function IGe(e){const t=t7(e),n=await n7(t.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"GitHubCopilotChat/0.35.0"},body:JSON.stringify({client_id:xde,scope:"read:user"})});if(!n||typeof n!="object")throw new Error("Invalid device code response");const i=n.device_code,r=n.user_code,a=n.verification_uri,l=n.interval,c=n.expires_in;if(typeof i!="string"||typeof r!="string"||typeof a!="string"||typeof l!="number"||typeof c!="number")throw new Error("Invalid device code response fields");return{device_code:i,user_code:r,verification_uri:a,interval:l,expires_in:c}}function iA(e,t){return new Promise((n,i)=>{if(t?.aborted){i(new Error("Login cancelled"));return}const r=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(r),i(new Error("Login cancelled"))},{once:!0})})}async function PGe(e,t,n,i,r){const a=t7(e),l=Date.now()+i*1e3;let c=Math.max(1e3,Math.floor(n*1e3));for(;Date.now()<l;){if(r?.aborted)throw new Error("Login cancelled");const o=await n7(a.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"GitHubCopilotChat/0.35.0"},body:JSON.stringify({client_id:xde,device_code:t,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(o&&typeof o=="object"&&typeof o.access_token=="string")return o.access_token;if(o&&typeof o=="object"&&typeof o.error=="string"){const s=o.error;if(s==="authorization_pending"){await iA(c,r);continue}if(s==="slow_down"){c+=5e3,await iA(c,r);continue}throw new Error(`Device flow failed: ${s}`)}await iA(c,r)}throw new Error("Device flow timed out")}async function Ede(e,t){const i=t7(t||"github.com"),r=await n7(i.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`,...Sde}});if(!r||typeof r!="object")throw new Error("Invalid Copilot token response");const a=r.token,l=r.expires_at;if(typeof a!="string"||typeof l!="number")throw new Error("Invalid Copilot token response fields");return{refresh:e,access:a,expires:l*1e3-300*1e3,enterpriseUrl:t}}async function MGe(e,t,n){const r=`${Tde(e,n)}/models/${t}/policy`;try{return(await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...Sde,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})})).ok}catch{return!1}}async function NGe(e,t,n){const i=RT("github-copilot");await Promise.all(i.map(async r=>{await MGe(e,r.id,t)}))}async function $Ge(e){const t=await e.onPrompt({message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com",allowEmpty:!0});if(e.signal?.aborted)throw new Error("Login cancelled");const n=t.trim(),i=Cde(t);if(n&&!i)throw new Error("Invalid GitHub Enterprise URL/domain");const r=i||"github.com",a=await IGe(r);e.onAuth(a.verification_uri,`Enter code: ${a.user_code}`);const l=await PGe(r,a.device_code,a.interval,a.expires_in,e.signal),c=await Ede(l,i??void 0);return e.onProgress?.("Enabling models..."),await NGe(c.access,i??void 0),c}const DGe={id:"github-copilot",name:"GitHub Copilot",async login(e){return $Ge({onAuth:(t,n)=>e.onAuth({url:t,instructions:n}),onPrompt:e.onPrompt,onProgress:e.onProgress,signal:e.signal})},async refreshToken(e){const t=e;return Ede(t.refresh,t.enterpriseUrl)},getApiKey(e){return e.access},modifyModels(e,t){const n=t,i=n.enterpriseUrl?Cde(n.enterpriseUrl)??void 0:void 0,r=Tde(n.access,i);return e.map(a=>a.provider==="github-copilot"?{...a,baseUrl:r}:a)}};let Qw=null,dO=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(dO=fn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{Qw=e.createServer}));const kde=e=>atob(e),pO=kde("MTA3MTAwNjA2MDU5MS10bWhzc2luMmgyMWxjcmUyMzV2dG9sb2poNGc0MDNlcC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbQ=="),Ade=kde("R09DU1BYLUs1OEZXUjQ4NkxkTEoxbUxCOHNYQzR6NnFEQWY="),rq="http://localhost:51121/oauth-callback",jGe=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/cclog","https://www.googleapis.com/auth/experimentsandconfigs"],LGe="https://accounts.google.com/o/oauth2/v2/auth",Rde="https://oauth2.googleapis.com/token",UGe="rising-fact-p41fc";async function FGe(){if(Qw||(dO&&await dO,Qw))return Qw;throw new Error("Antigravity OAuth is only available in Node.js environments")}async function qGe(){const e=await FGe();return new Promise((t,n)=>{let i=null,r=!1;const a=e((l,c)=>{const o=new URL(l.url||"","http://localhost:51121");if(o.pathname==="/oauth-callback"){const s=o.searchParams.get("code"),u=o.searchParams.get("state"),d=o.searchParams.get("error");if(d){c.writeHead(400,{"Content-Type":"text/html"}),c.end(`<html><body><h1>Authentication Failed</h1><p>Error: ${d}</p><p>You can close this window.</p></body></html>`);return}s&&u?(c.writeHead(200,{"Content-Type":"text/html"}),c.end("<html><body><h1>Authentication Successful</h1><p>You can close this window and return to the terminal.</p></body></html>"),i={code:s,state:u}):(c.writeHead(400,{"Content-Type":"text/html"}),c.end("<html><body><h1>Authentication Failed</h1><p>Missing code or state parameter.</p></body></html>"))}else c.writeHead(404),c.end()});a.on("error",l=>{n(l)}),a.listen(51121,"127.0.0.1",()=>{t({server:a,cancelWait:()=>{r=!0},waitForCode:async()=>{const l=()=>new Promise(c=>setTimeout(c,100));for(;!i&&!r;)await l();return i}})})})}function iq(e){const t=e.trim();if(!t)return{};try{const n=new URL(t);return{code:n.searchParams.get("code")??void 0,state:n.searchParams.get("state")??void 0}}catch{return{}}}async function BGe(e,t){const n={Authorization:`Bearer ${e}`,"Content-Type":"application/json","User-Agent":"google-api-nodejs-client/9.15.1","X-Goog-Api-Client":"google-cloud-sdk vscode_cloudshelleditor/0.1","Client-Metadata":JSON.stringify({ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"})},i=["https://cloudcode-pa.googleapis.com","https://daily-cloudcode-pa.sandbox.googleapis.com"];t?.("Checking for existing project...");for(const r of i)try{const a=await fetch(`${r}/v1internal:loadCodeAssist`,{method:"POST",headers:n,body:JSON.stringify({metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}})});if(a.ok){const l=await a.json();if(typeof l.cloudaicompanionProject=="string"&&l.cloudaicompanionProject)return l.cloudaicompanionProject;if(l.cloudaicompanionProject&&typeof l.cloudaicompanionProject=="object"&&l.cloudaicompanionProject.id)return l.cloudaicompanionProject.id}}catch{}return t?.("Using default project..."),UGe}async function WGe(e){try{const t=await fetch("https://www.googleapis.com/oauth2/v1/userinfo?alt=json",{headers:{Authorization:`Bearer ${e}`}});if(t.ok)return(await t.json()).email}catch{}}async function zGe(e,t){const n=await fetch(Rde,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:pO,client_secret:Ade,refresh_token:e,grant_type:"refresh_token"})});if(!n.ok){const r=await n.text();throw new Error(`Antigravity token refresh failed: ${r}`)}const i=await n.json();return{refresh:i.refresh_token||e,access:i.access_token,expires:Date.now()+i.expires_in*1e3-300*1e3,projectId:t}}async function GGe(e,t,n){const{verifier:i,challenge:r}=await PE();t?.("Starting local server for OAuth callback...");const a=await qGe();let l;try{const c=new URLSearchParams({client_id:pO,response_type:"code",redirect_uri:rq,scope:jGe.join(" "),code_challenge:r,code_challenge_method:"S256",state:i,access_type:"offline",prompt:"consent"}),o=`${LGe}?${c.toString()}`;if(e({url:o,instructions:"Complete the sign-in in your browser."}),t?.("Waiting for OAuth callback..."),n){let m,g;const y=n().then(b=>{m=b,a.cancelWait()}).catch(b=>{g=b instanceof Error?b:new Error(String(b)),a.cancelWait()}),v=await a.waitForCode();if(g)throw g;if(v?.code){if(v.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");l=v.code}else if(m){const b=iq(m);if(b.state&&b.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");l=b.code}if(!l){if(await y,g)throw g;if(m){const b=iq(m);if(b.state&&b.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");l=b.code}}}else{const m=await a.waitForCode();if(m?.code){if(m.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");l=m.code}}if(!l)throw new Error("No authorization code received");t?.("Exchanging authorization code for tokens...");const s=await fetch(Rde,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:pO,client_secret:Ade,code:l,grant_type:"authorization_code",redirect_uri:rq,code_verifier:i})});if(!s.ok){const m=await s.text();throw new Error(`Token exchange failed: ${m}`)}const u=await s.json();if(!u.refresh_token)throw new Error("No refresh token received. Please try again.");t?.("Getting user info...");const d=await WGe(u.access_token),p=await BGe(u.access_token,t),f=Date.now()+u.expires_in*1e3-300*1e3;return{refresh:u.refresh_token,access:u.access_token,expires:f,projectId:p,email:d}}finally{a.server.close()}}const HGe={id:"google-antigravity",name:"Antigravity (Gemini 3, Claude, GPT-OSS)",usesCallbackServer:!0,async login(e){return GGe(e.onAuth,e.onProgress,e.onManualCodeInput)},async refreshToken(e){const t=e;if(!t.projectId)throw new Error("Antigravity credentials missing projectId");return zGe(t.refresh,t.projectId)},getApiKey(e){const t=e;return JSON.stringify({token:t.access,projectId:t.projectId})}};var aq={};let Yw=null,fO=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(fO=fn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{Yw=e.createServer}));const Ode=e=>atob(e),hO=Ode("NjgxMjU1ODA5Mzk1LW9vOGZ0Mm9wcmRybnA5ZTNhcWY2YXYzaG1kaWIxMzVqLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29t"),Ide=Ode("R09DU1BYLTR1SGdNUG0tMW83U2stZ2VWNkN1NWNsWEZzeGw="),sq="http://localhost:8085/oauth2callback",VGe=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile"],JGe="https://accounts.google.com/o/oauth2/v2/auth",Pde="https://oauth2.googleapis.com/token",mO="https://cloudcode-pa.googleapis.com";async function KGe(){if(Yw||(fO&&await fO,Yw))return Yw;throw new Error("Gemini CLI OAuth is only available in Node.js environments")}async function ZGe(){const e=await KGe();return new Promise((t,n)=>{let i=null,r=!1;const a=e((l,c)=>{const o=new URL(l.url||"","http://localhost:8085");if(o.pathname==="/oauth2callback"){const s=o.searchParams.get("code"),u=o.searchParams.get("state"),d=o.searchParams.get("error");if(d){c.writeHead(400,{"Content-Type":"text/html"}),c.end(`<html><body><h1>Authentication Failed</h1><p>Error: ${d}</p><p>You can close this window.</p></body></html>`);return}s&&u?(c.writeHead(200,{"Content-Type":"text/html"}),c.end("<html><body><h1>Authentication Successful</h1><p>You can close this window and return to the terminal.</p></body></html>"),i={code:s,state:u}):(c.writeHead(400,{"Content-Type":"text/html"}),c.end("<html><body><h1>Authentication Failed</h1><p>Missing code or state parameter.</p></body></html>"))}else c.writeHead(404),c.end()});a.on("error",l=>{n(l)}),a.listen(8085,"127.0.0.1",()=>{t({server:a,cancelWait:()=>{r=!0},waitForCode:async()=>{const l=()=>new Promise(c=>setTimeout(c,100));for(;!i&&!r;)await l();return i}})})})}function oq(e){const t=e.trim();if(!t)return{};try{const n=new URL(t);return{code:n.searchParams.get("code")??void 0,state:n.searchParams.get("state")??void 0}}catch{return{}}}const aA="free-tier",lq="legacy-tier",XGe="standard-tier";function QGe(e){return new Promise(t=>setTimeout(t,e))}function YGe(e){return!e||e.length===0?{id:lq}:e.find(n=>n.isDefault)??{id:lq}}function eHe(e){if(!e||typeof e!="object"||!("error"in e))return!1;const t=e.error;return!t?.details||!Array.isArray(t.details)?!1:t.details.some(n=>n.reason==="SECURITY_POLICY_VIOLATED")}async function tHe(e,t,n){let i=0;for(;;){i>0&&(n?.(`Waiting for project provisioning (attempt ${i+1})...`),await QGe(5e3));const r=await fetch(`${mO}/v1internal/${e}`,{method:"GET",headers:t});if(!r.ok)throw new Error(`Failed to poll operation: ${r.status} ${r.statusText}`);const a=await r.json();if(a.done)return a;i+=1}}async function nHe(e,t){const n=aq.GOOGLE_CLOUD_PROJECT||aq.GOOGLE_CLOUD_PROJECT_ID,i={Authorization:`Bearer ${e}`,"Content-Type":"application/json","User-Agent":"google-api-nodejs-client/9.15.1","X-Goog-Api-Client":"gl-node/22.17.0"};t?.("Checking for existing Cloud Code Assist project...");const r=await fetch(`${mO}/v1internal:loadCodeAssist`,{method:"POST",headers:i,body:JSON.stringify({cloudaicompanionProject:n,metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI",duetProject:n}})});let a;if(r.ok)a=await r.json();else{let p;try{p=await r.clone().json()}catch{p=void 0}if(eHe(p))a={currentTier:{id:XGe}};else{const f=await r.text();throw new Error(`loadCodeAssist failed: ${r.status} ${r.statusText}: ${f}`)}}if(a.currentTier){if(a.cloudaicompanionProject)return a.cloudaicompanionProject;if(n)return n;throw new Error("This account requires setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID environment variable. See https://goo.gle/gemini-cli-auth-docs#workspace-gca")}const c=YGe(a.allowedTiers)?.id??aA;if(c!==aA&&!n)throw new Error("This account requires setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID environment variable. See https://goo.gle/gemini-cli-auth-docs#workspace-gca");t?.("Provisioning Cloud Code Assist project (this may take a moment)...");const o={tierId:c,metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}};c!==aA&&n&&(o.cloudaicompanionProject=n,o.metadata.duetProject=n);const s=await fetch(`${mO}/v1internal:onboardUser`,{method:"POST",headers:i,body:JSON.stringify(o)});if(!s.ok){const p=await s.text();throw new Error(`onboardUser failed: ${s.status} ${s.statusText}: ${p}`)}let u=await s.json();!u.done&&u.name&&(u=await tHe(u.name,i,t));const d=u.response?.cloudaicompanionProject?.id;if(d)return d;if(n)return n;throw new Error("Could not discover or provision a Google Cloud project. Try setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID environment variable. See https://goo.gle/gemini-cli-auth-docs#workspace-gca")}async function rHe(e){try{const t=await fetch("https://www.googleapis.com/oauth2/v1/userinfo?alt=json",{headers:{Authorization:`Bearer ${e}`}});if(t.ok)return(await t.json()).email}catch{}}async function iHe(e,t){const n=await fetch(Pde,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:hO,client_secret:Ide,refresh_token:e,grant_type:"refresh_token"})});if(!n.ok){const r=await n.text();throw new Error(`Google Cloud token refresh failed: ${r}`)}const i=await n.json();return{refresh:i.refresh_token||e,access:i.access_token,expires:Date.now()+i.expires_in*1e3-300*1e3,projectId:t}}async function aHe(e,t,n){const{verifier:i,challenge:r}=await PE();t?.("Starting local server for OAuth callback...");const a=await ZGe();let l;try{const c=new URLSearchParams({client_id:hO,response_type:"code",redirect_uri:sq,scope:VGe.join(" "),code_challenge:r,code_challenge_method:"S256",state:i,access_type:"offline",prompt:"consent"}),o=`${JGe}?${c.toString()}`;if(e({url:o,instructions:"Complete the sign-in in your browser."}),t?.("Waiting for OAuth callback..."),n){let m,g;const y=n().then(b=>{m=b,a.cancelWait()}).catch(b=>{g=b instanceof Error?b:new Error(String(b)),a.cancelWait()}),v=await a.waitForCode();if(g)throw g;if(v?.code){if(v.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");l=v.code}else if(m){const b=oq(m);if(b.state&&b.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");l=b.code}if(!l){if(await y,g)throw g;if(m){const b=oq(m);if(b.state&&b.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");l=b.code}}}else{const m=await a.waitForCode();if(m?.code){if(m.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");l=m.code}}if(!l)throw new Error("No authorization code received");t?.("Exchanging authorization code for tokens...");const s=await fetch(Pde,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:hO,client_secret:Ide,code:l,grant_type:"authorization_code",redirect_uri:sq,code_verifier:i})});if(!s.ok){const m=await s.text();throw new Error(`Token exchange failed: ${m}`)}const u=await s.json();if(!u.refresh_token)throw new Error("No refresh token received. Please try again.");t?.("Getting user info...");const d=await rHe(u.access_token),p=await nHe(u.access_token,t),f=Date.now()+u.expires_in*1e3-300*1e3;return{refresh:u.refresh_token,access:u.access_token,expires:f,projectId:p,email:d}}finally{a.server.close()}}const sHe={id:"google-gemini-cli",name:"Google Cloud Code Assist (Gemini CLI)",usesCallbackServer:!0,async login(e){return aHe(e.onAuth,e.onProgress,e.onManualCodeInput)},async refreshToken(e){const t=e;if(!t.projectId)throw new Error("Google Cloud credentials missing projectId");return iHe(t.refresh,t.projectId)},getApiKey(e){const t=e;return JSON.stringify({token:t.access,projectId:t.projectId})}};let gO=null,yO=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(fn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{gO=e.randomBytes}),fn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{yO=e}));const r7="app_EMoamEEZ73f0CkXaXp7hrann",oHe="https://auth.openai.com/oauth/authorize",Mde="https://auth.openai.com/oauth/token",Nde="http://localhost:1455/auth/callback",lHe="openid profile email offline_access",cHe="https://api.openai.com/auth",uHe=`<!doctype html>
532
532
  <html lang="en">
533
533
  <head>
534
534
  <meta charset="utf-8" />
@@ -677,7 +677,7 @@ ${a.content}
677
677
  Input: ${JSON.stringify(c.input,null,2)}
678
678
  Result: ${c.result??""}
679
679
 
680
- `}await navigator.clipboard.writeText(r),n.style.color="var(--s2-positive)",setTimeout(()=>{n.style.color=""},1500)}),t.appendChild(n),t}createLickEl(t){const n=document.createElement("details");n.className="lick";const i=t.channel==="webhook"?"Webhook":t.channel==="cron"?"Cron":"Event",r=document.createElement("summary");r.className="lick__header",r.innerHTML=`<span class="lick__icon">E</span> <span class="lick__type">${i}</span>`;const a=document.createElement("span");a.className="lick__preview";const l=t.content.replace(/\[Webhook Event:.*?\]\n```json\n?/s,"").slice(0,50);a.textContent=l.replace(/\n/g," ")+(l.length>=50?"...":""),r.appendChild(a),n.appendChild(r);const c=document.createElement("div");return c.className="lick__details",c.innerHTML=dae(t.content),n.appendChild(c),n}createToolCallEl(t){Xrt(t.name);const n=document.createElement("details");n.className="tool-call";const i=document.createElement("summary");if(i.className="tool-call__header",i.innerHTML=`<span class="tool-call__icon"><svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor"><path d="M2 3.5L5 6.5L8 3.5" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg></span> <span class="tool-call__name">${sg(t.name)}</span>`,t.input!==void 0){const c=document.createElement("span");c.className="tool-call__preview";const o=typeof t.input=="string"?t.input:JSON.stringify(t.input);c.textContent=o.slice(0,40)+(o.length>40?"...":""),i.appendChild(c)}const r=document.createElement("span");t.result===void 0?r.className="tool-call__status tool-call__status--running":t.isError?(r.className="tool-call__status tool-call__status--error",r.textContent="failed"):(r.className="tool-call__status tool-call__status--success",r.textContent="✓"),i.appendChild(r),n.appendChild(i);const a=document.createElement("div");if(a.className="tool-call__details",t.input!==void 0){const c=document.createElement("div");c.className="tool-call__input";const o=document.createElement("div");o.className="tool-call__label",o.textContent="Input:",c.appendChild(o);const s=document.createElement("pre");s.innerHTML=u3e(t.input),c.appendChild(s),a.appendChild(c)}if(t.result!==void 0){const c=document.createElement("div");c.className=`tool-call__result${t.isError?" tool-call__result--error":""}`;const o=document.createElement("div");o.className="tool-call__label",o.textContent=t.isError?"Error:":"Result:",c.appendChild(o);const s=document.createElement("pre");s.textContent=t.result,c.appendChild(s),a.appendChild(c)}const l=t._screenshotDataUrl;if(l){const c=document.createElement("img");c.src=l,c.className="tool-call__screenshot",c.title="Click to view full size",c.addEventListener("click",o=>{o.stopPropagation();const s=window.open("about:blank");if(s){const u=s.document.createElement("img");u.src=l,s.document.title="Screenshot",s.document.body.style.margin="0",s.document.body.style.background=document.documentElement.classList.contains("theme-light")?"#f0f0f0":"#141414",s.document.body.appendChild(u)}}),a.appendChild(c)}return n.appendChild(a),n}scrollToBottom(t=!1){if(!t&&!this.autoScrollAttached){this.showJumpPill();return}requestAnimationFrame(()=>{this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this.lastScrollTop=this.messagesEl.scrollTop})}showJumpPill(){this.jumpPill.classList.add("chat__jump-pill--visible")}hideJumpPill(){this.jumpPill.classList.remove("chat__jump-pill--visible")}persistSession(){this.sessionStore.saveMessages(this.sessionId,this.messages).catch(()=>{})}disposeInlineSprinklesForMessage(t){const n=this.inlineSprinkles.get(t);n&&(fj(n),this.inlineSprinkles.delete(t))}disposeAllInlineSprinkles(){for(const[,t]of this.inlineSprinkles)fj(t);this.inlineSprinkles.clear()}hydrateInlineSprinklesInEl(t,n){const i=k3e(t,(r,a)=>this.onInlineSprinkleLick?.(r,a));i.length&&this.inlineSprinkles.set(n,i)}dispose(){this.cancelPendingDelta(),this.disposeAllInlineSprinkles(),this.unsubscribe?.(),this.voiceInput?.destroy(),this.keydownListener&&(document.removeEventListener("keydown",this.keydownListener),this.keydownListener=null),this.container.innerHTML=""}}class UX{container;terminalViewEl;previewViewEl;previewEmptyEl;previewBtn;shell=null;activeView="terminal";onClearTerminal;constructor(t,n={}){this.container=t,this.onClearTerminal=n.onClearTerminal??null,this.render()}async mountShell(t){this.shell?.setPreviewStateListener(null),this.shell=t;const n=document.createElement("div");n.className="terminal-panel__mount",this.terminalViewEl.appendChild(n),await t.mount(n);const i=n.querySelector(".terminal-panel__terminal-host"),r=n.querySelector(".terminal-panel__preview");if(!i||!r)throw new Error("terminal mount did not create expected hosts");this.terminalViewEl.replaceChildren(i),this.previewViewEl.appendChild(r),t.setPreviewStateListener(a=>this.handlePreviewStateChange(a))}clearTerminal(){this.shell?.clearTerminal()}async runCommand(t){return this.shell?(/^\s*imgcat(?:\s|$)/.test(t)||this.setActiveView("terminal"),this.shell.executeCommandInTerminal(t)):{stdout:"",stderr:`terminal is unavailable
680
+ `}await navigator.clipboard.writeText(r),n.style.color="var(--s2-positive)",setTimeout(()=>{n.style.color=""},1500)}),t.appendChild(n),t}createLickEl(t){const n=document.createElement("details");n.className="lick";const i=t.channel==="webhook"?"Webhook":t.channel==="cron"?"Cron":"Event",r=document.createElement("summary");r.className="lick__header",r.innerHTML=`<span class="lick__icon">E</span> <span class="lick__type">${i}</span>`;const a=document.createElement("span");a.className="lick__preview";const l=t.content.replace(/\[Webhook Event:.*?\]\n```json\n?/s,"").slice(0,50);a.textContent=l.replace(/\n/g," ")+(l.length>=50?"...":""),r.appendChild(a),n.appendChild(r);const c=document.createElement("div");return c.className="lick__details",c.innerHTML=dae(t.content),n.appendChild(c),n}createToolCallEl(t){Xrt(t.name);const n=document.createElement("details");n.className="tool-call";const i=document.createElement("summary");if(i.className="tool-call__header",i.innerHTML=`<span class="tool-call__icon"><svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor"><path d="M2 3.5L5 6.5L8 3.5" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg></span> <span class="tool-call__name">${sg(t.name)}</span>`,t.input!==void 0){const c=document.createElement("span");c.className="tool-call__preview";const o=typeof t.input=="string"?t.input:JSON.stringify(t.input);c.textContent=o.slice(0,40)+(o.length>40?"...":""),i.appendChild(c)}const r=document.createElement("span");t.result===void 0?r.className="tool-call__status tool-call__status--running":t.isError?(r.className="tool-call__status tool-call__status--error",r.textContent="failed"):(r.className="tool-call__status tool-call__status--success",r.textContent="✓"),i.appendChild(r),n.appendChild(i);const a=document.createElement("div");if(a.className="tool-call__details",t.input!==void 0){const c=document.createElement("div");c.className="tool-call__input";const o=document.createElement("div");o.className="tool-call__label",o.textContent="Input:",c.appendChild(o);const s=document.createElement("pre");s.innerHTML=u3e(t.input),c.appendChild(s),a.appendChild(c)}if(t.result!==void 0){const c=document.createElement("div");c.className=`tool-call__result${t.isError?" tool-call__result--error":""}`;const o=document.createElement("div");o.className="tool-call__label",o.textContent=t.isError?"Error:":"Result:",c.appendChild(o);const s=document.createElement("pre");s.textContent=t.result,c.appendChild(s),a.appendChild(c)}const l=t._screenshotDataUrl;if(l){const c=document.createElement("img");c.src=l,c.className="tool-call__screenshot",c.title="Click to view full size",c.addEventListener("click",o=>{o.stopPropagation();const s=window.open("about:blank");if(s){const u=s.document.createElement("img");u.src=l,s.document.title="Screenshot",s.document.body.style.margin="0",s.document.body.style.background=document.documentElement.classList.contains("theme-light")?"#f0f0f0":"#141414",s.document.body.appendChild(u)}}),a.appendChild(c)}return n.appendChild(a),n}scrollToBottom(t=!1){if(!t&&!this.autoScrollAttached){this.showJumpPill();return}requestAnimationFrame(()=>{this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this.lastScrollTop=this.messagesEl.scrollTop})}showJumpPill(){this.jumpPill.classList.add("chat__jump-pill--visible")}hideJumpPill(){this.jumpPill.classList.remove("chat__jump-pill--visible")}persistSession(){this.sessionStore.saveMessages(this.sessionId,this.messages).catch(()=>{})}disposeInlineSprinklesForMessage(t){const n=this.inlineSprinkles.get(t);n&&(fj(n),this.inlineSprinkles.delete(t))}disposeAllInlineSprinkles(){for(const[,t]of this.inlineSprinkles)fj(t);this.inlineSprinkles.clear()}hydrateInlineSprinklesInEl(t,n){const i=k3e(t,(r,a)=>this.onInlineSprinkleLick?.(r,a));i.length&&this.inlineSprinkles.set(n,i)}dispose(){this.cancelPendingDelta(),this.disposeAllInlineSprinkles(),this.unsubscribe?.(),this.voiceInput?.destroy(),this.keydownListener&&(document.removeEventListener("keydown",this.keydownListener),this.keydownListener=null),this.container.innerHTML=""}}class UX{container;terminalViewEl;previewViewEl;previewEmptyEl;previewBtn;shell=null;activeView="terminal";onClearTerminal;constructor(t,n={}){this.container=t,this.onClearTerminal=n.onClearTerminal??null,this.render()}async mountShell(t){this.shell?.setPreviewStateListener(null),this.shell=t;const n=document.createElement("div");n.className="terminal-panel__mount",this.terminalViewEl.appendChild(n),await t.mount(n);const i=n.querySelector(".terminal-panel__terminal-host"),r=n.querySelector(".terminal-panel__preview");if(!i||!r)throw new Error("terminal mount did not create expected hosts");this.terminalViewEl.replaceChildren(i),this.previewViewEl.replaceChildren(this.previewEmptyEl),this.previewViewEl.appendChild(r),t.setPreviewStateListener(a=>this.handlePreviewStateChange(a))}clearTerminal(){this.shell?.clearTerminal()}async runCommand(t){return this.shell?(/^\s*imgcat(?:\s|$)/.test(t)||this.setActiveView("terminal"),this.shell.executeCommandInTerminal(t)):{stdout:"",stderr:`terminal is unavailable
681
681
  `,exitCode:1}}refit(){this.shell?.refit()}getBodyElement(){return this.container}render(){this.container.innerHTML="",this.container.classList.add("terminal-panel");const t=document.createElement("div");t.className="file-browser__header";const n=document.createElement("span");if(n.className="file-browser__header-title",n.textContent="Terminal",t.appendChild(n),this.onClearTerminal){const c=document.createElement("button");c.className="file-browser__header-btn",c.dataset.tooltip="Clear Terminal",c.setAttribute("aria-label","Clear Terminal"),c.innerHTML='<svg width="14" height="14" viewBox="0 0 20 20" fill="none"><path d="m8.249,15.021c-.4,0-.733-.317-.748-.72l-.25-6.5c-.017-.414.307-.763.72-.778.01-.001.021-.001.03-.001.4,0,.733.317.748.72l.25,6.5c.017.414-.307.763-.72.778-.01.001-.021.001-.03.001Z" fill="currentColor"/><path d="m11.751,15.021c-.01,0-.02,0-.03-.001-.413-.016-.736-.364-.72-.778l.25-6.5c.015-.403.348-.72.748-.72.01,0,.02,0,.03.001.413.016.736.364.72.778l-.25,6.5c-.015.403-.348.72-.748.72Z" fill="currentColor"/><path d="m17,4h-3.5v-.75c0-1.24-1.01-2.25-2.25-2.25h-2.5c-1.24,0-2.25,1.01-2.25,2.25v.75h-3.5c-.414,0-.75.336-.75.75s.336.75.75.75h.52l.422,10.342c.048,1.21,1.036,2.158,2.248,2.158h7.619c1.212,0,2.2-.948,2.248-2.158l.422-10.342h.52c.414,0,.75-.336.75-.75s-.336-.75-.75-.75Zm-9-.75c0-.413.337-.75.75-.75h2.5c.413,0,.75.337.75.75v.75h-4v-.75Zm6.56,12.531c-.017.403-.346.719-.75.719h-7.619c-.404,0-.733-.316-.75-.719l-.42-10.281h9.959l-.42,10.281Z" fill="currentColor"/></svg>',c.addEventListener("click",()=>this.onClearTerminal()),t.appendChild(c)}this.previewBtn=document.createElement("button"),this.previewBtn.className="file-browser__header-btn",this.previewBtn.setAttribute("aria-label","Toggle preview"),this.previewBtn.dataset.tooltip="Preview",this.previewBtn.disabled=!0;const i="http://www.w3.org/2000/svg",r=document.createElementNS(i,"svg");r.setAttribute("width","16"),r.setAttribute("height","16"),r.setAttribute("viewBox","0 0 20 20"),r.setAttribute("fill","none"),r.setAttribute("stroke","currentColor"),r.setAttribute("stroke-width","1.5"),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round");const a=document.createElementNS(i,"path");a.setAttribute("d","M2 10s3-6 8-6 8 6 8 6-3 6-8 6-8-6-8-6z"),r.appendChild(a);const l=document.createElementNS(i,"circle");l.setAttribute("cx","10"),l.setAttribute("cy","10"),l.setAttribute("r","2.5"),r.appendChild(l),this.previewBtn.appendChild(r),this.previewBtn.addEventListener("click",()=>{this.previewBtn.disabled||this.setActiveView(this.activeView==="preview"?"terminal":"preview")}),t.appendChild(this.previewBtn),this.container.appendChild(t),this.terminalViewEl=document.createElement("div"),this.terminalViewEl.className="terminal-panel__view",this.container.appendChild(this.terminalViewEl),this.previewViewEl=document.createElement("div"),this.previewViewEl.className="terminal-panel__view",this.container.appendChild(this.previewViewEl),this.previewEmptyEl=document.createElement("div"),this.previewEmptyEl.className="terminal-panel__empty-state",this.previewEmptyEl.textContent="Run imgcat to preview media here.",this.previewViewEl.appendChild(this.previewEmptyEl),this.setActiveView("terminal")}dispose(){this.shell?.setPreviewStateListener(null),this.shell?.dispose(),this.container.innerHTML=""}setActiveView(t){this.activeView=t,this.previewBtn.classList.toggle("file-browser__header-btn--active",t==="preview"),this.terminalViewEl.style.display=t==="terminal"?"flex":"none",this.previewViewEl.style.display=t==="preview"?"flex":"none",t==="terminal"&&this.refit()}handlePreviewStateChange(t){this.previewBtn.disabled=!t,this.previewEmptyEl.style.display=t?"none":"flex",t?this.setActiveView("preview"):this.activeView==="preview"&&this.setActiveView("terminal")}}var Hr=Uint8Array,ds=Uint16Array,EM=Int32Array,fk=new Hr([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),hk=new Hr([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),zO=new Hr([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),wge=function(e,t){for(var n=new ds(31),i=0;i<31;++i)n[i]=t+=1<<e[i-1];for(var r=new EM(n[30]),i=1;i<30;++i)for(var a=n[i];a<n[i+1];++a)r[a]=a-n[i]<<5|i;return{b:n,r}},_ge=wge(fk,2),xge=_ge.b,GO=_ge.r;xge[28]=258,GO[258]=28;var Sge=wge(hk,0),Qrt=Sge.b,FX=Sge.r,HO=new ds(32768);for(var Nr=0;Nr<32768;++Nr){var Hm=(Nr&43690)>>1|(Nr&21845)<<1;Hm=(Hm&52428)>>2|(Hm&13107)<<2,Hm=(Hm&61680)>>4|(Hm&3855)<<4,HO[Nr]=((Hm&65280)>>8|(Hm&255)<<8)>>1}var $c=(function(e,t,n){for(var i=e.length,r=0,a=new ds(t);r<i;++r)e[r]&&++a[e[r]-1];var l=new ds(t);for(r=1;r<t;++r)l[r]=l[r-1]+a[r-1]<<1;var c;if(n){c=new ds(1<<t);var o=15-t;for(r=0;r<i;++r)if(e[r])for(var s=r<<4|e[r],u=t-e[r],d=l[e[r]-1]++<<u,p=d|(1<<u)-1;d<=p;++d)c[HO[d]>>o]=s}else for(c=new ds(i),r=0;r<i;++r)e[r]&&(c[r]=HO[l[e[r]-1]++]>>15-e[r]);return c}),mg=new Hr(288);for(var Nr=0;Nr<144;++Nr)mg[Nr]=8;for(var Nr=144;Nr<256;++Nr)mg[Nr]=9;for(var Nr=256;Nr<280;++Nr)mg[Nr]=7;for(var Nr=280;Nr<288;++Nr)mg[Nr]=8;var X_=new Hr(32);for(var Nr=0;Nr<32;++Nr)X_[Nr]=5;var Yrt=$c(mg,9,0),eit=$c(mg,9,1),tit=$c(X_,5,0),nit=$c(X_,5,1),VA=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},oo=function(e,t,n){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(t&7)&n},JA=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},kM=function(e){return(e+7)/8|0},L2=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new Hr(e.subarray(t,n))},rit=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],va=function(e,t,n){var i=new Error(t||rit[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,va),!n)throw i;return i},iit=function(e,t,n,i){var r=e.length,a=i?i.length:0;if(!r||t.f&&!t.l)return n||new Hr(0);var l=!n,c=l||t.i!=2,o=t.i;l&&(n=new Hr(r*3));var s=function(xe){var we=n.length;if(xe>we){var qe=new Hr(Math.max(we*2,xe));qe.set(n),n=qe}},u=t.f||0,d=t.p||0,p=t.b||0,f=t.l,h=t.d,m=t.m,g=t.n,y=r*8;do{if(!f){u=oo(e,d,1);var v=oo(e,d+1,3);if(d+=3,v)if(v==1)f=eit,h=nit,m=9,g=5;else if(v==2){var C=oo(e,d,31)+257,A=oo(e,d+10,15)+4,M=C+oo(e,d+5,31)+1;d+=14;for(var N=new Hr(M),P=new Hr(19),k=0;k<A;++k)P[zO[k]]=oo(e,d+k*3,7);d+=A*3;for(var $=VA(P),O=(1<<$)-1,j=$c(P,$,1),k=0;k<M;){var U=j[oo(e,d,O)];d+=U&15;var b=U>>4;if(b<16)N[k++]=b;else{var G=0,V=0;for(b==16?(V=3+oo(e,d,3),d+=2,G=N[k-1]):b==17?(V=3+oo(e,d,7),d+=3):b==18&&(V=11+oo(e,d,127),d+=7);V--;)N[k++]=G}}var J=N.subarray(0,C),oe=N.subarray(C);m=VA(J),g=VA(oe),f=$c(J,m,1),h=$c(oe,g,1)}else va(1);else{var b=kM(d)+4,w=e[b-4]|e[b-3]<<8,x=b+w;if(x>r){o&&va(0);break}c&&s(p+w),n.set(e.subarray(b,x),p),t.b=p+=w,t.p=d=x*8,t.f=u;continue}if(d>y){o&&va(0);break}}c&&s(p+131072);for(var ce=(1<<m)-1,Y=(1<<g)-1,ye=d;;ye=d){var G=f[JA(e,d)&ce],de=G>>4;if(d+=G&15,d>y){o&&va(0);break}if(G||va(2),de<256)n[p++]=de;else if(de==256){ye=d,f=null;break}else{var ee=de-254;if(de>264){var k=de-257,X=fk[k];ee=oo(e,d,(1<<X)-1)+xge[k],d+=X}var ge=h[JA(e,d)&Y],Me=ge>>4;ge||va(3),d+=ge&15;var oe=Qrt[Me];if(Me>3){var X=hk[Me];oe+=JA(e,d)&(1<<X)-1,d+=X}if(d>y){o&&va(0);break}c&&s(p+131072);var De=p+ee;if(p<oe){var at=a-oe,it=Math.min(oe,De);for(at+p<0&&va(3);p<it;++p)n[p]=i[at+p]}for(;p<De;++p)n[p]=n[p-oe]}}t.l=f,t.p=ye,t.b=p,t.f=u,f&&(u=1,t.m=m,t.d=h,t.n=g)}while(!u);return p!=n.length&&l?L2(n,0,p):n.subarray(0,p)},nm=function(e,t,n){n<<=t&7;var i=t/8|0;e[i]|=n,e[i+1]|=n>>8},bw=function(e,t,n){n<<=t&7;var i=t/8|0;e[i]|=n,e[i+1]|=n>>8,e[i+2]|=n>>16},KA=function(e,t){for(var n=[],i=0;i<e.length;++i)e[i]&&n.push({s:i,f:e[i]});var r=n.length,a=n.slice();if(!r)return{t:Tge,l:0};if(r==1){var l=new Hr(n[0].s+1);return l[n[0].s]=1,{t:l,l:1}}n.sort(function(x,C){return x.f-C.f}),n.push({s:-1,f:25001});var c=n[0],o=n[1],s=0,u=1,d=2;for(n[0]={s:-1,f:c.f+o.f,l:c,r:o};u!=r-1;)c=n[n[s].f<n[d].f?s++:d++],o=n[s!=u&&n[s].f<n[d].f?s++:d++],n[u++]={s:-1,f:c.f+o.f,l:c,r:o};for(var p=a[0].s,i=1;i<r;++i)a[i].s>p&&(p=a[i].s);var f=new ds(p+1),h=VO(n[u-1],f,0);if(h>t){var i=0,m=0,g=h-t,y=1<<g;for(a.sort(function(C,A){return f[A.s]-f[C.s]||C.f-A.f});i<r;++i){var v=a[i].s;if(f[v]>t)m+=y-(1<<h-f[v]),f[v]=t;else break}for(m>>=g;m>0;){var b=a[i].s;f[b]<t?m-=1<<t-f[b]++-1:++i}for(;i>=0&&m;--i){var w=a[i].s;f[w]==t&&(--f[w],++m)}h=t}return{t:new Hr(f),l:h}},VO=function(e,t,n){return e.s==-1?Math.max(VO(e.l,t,n+1),VO(e.r,t,n+1)):t[e.s]=n},qX=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new ds(++t),i=0,r=e[0],a=1,l=function(o){n[i++]=o},c=1;c<=t;++c)if(e[c]==r&&c!=t)++a;else{if(!r&&a>2){for(;a>138;a-=138)l(32754);a>2&&(l(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(l(r),--a;a>6;a-=6)l(8304);a>2&&(l(a-3<<5|8208),a=0)}for(;a--;)l(r);a=1,r=e[c]}return{c:n.subarray(0,i),n:t}},ww=function(e,t){for(var n=0,i=0;i<t.length;++i)n+=e[i]*t[i];return n},Cge=function(e,t,n){var i=n.length,r=kM(t+2);e[r]=i&255,e[r+1]=i>>8,e[r+2]=e[r]^255,e[r+3]=e[r+1]^255;for(var a=0;a<i;++a)e[r+a+4]=n[a];return(r+4+i)*8},BX=function(e,t,n,i,r,a,l,c,o,s,u){nm(t,u++,n),++r[256];for(var d=KA(r,15),p=d.t,f=d.l,h=KA(a,15),m=h.t,g=h.l,y=qX(p),v=y.c,b=y.n,w=qX(m),x=w.c,C=w.n,A=new ds(19),M=0;M<v.length;++M)++A[v[M]&31];for(var M=0;M<x.length;++M)++A[x[M]&31];for(var N=KA(A,7),P=N.t,k=N.l,$=19;$>4&&!P[zO[$-1]];--$);var O=s+5<<3,j=ww(r,mg)+ww(a,X_)+l,U=ww(r,p)+ww(a,m)+l+14+3*$+ww(A,P)+2*A[16]+3*A[17]+7*A[18];if(o>=0&&O<=j&&O<=U)return Cge(t,u,e.subarray(o,o+s));var G,V,J,oe;if(nm(t,u,1+(U<j)),u+=2,U<j){G=$c(p,f,0),V=p,J=$c(m,g,0),oe=m;var ce=$c(P,k,0);nm(t,u,b-257),nm(t,u+5,C-1),nm(t,u+10,$-4),u+=14;for(var M=0;M<$;++M)nm(t,u+3*M,P[zO[M]]);u+=3*$;for(var Y=[v,x],ye=0;ye<2;++ye)for(var de=Y[ye],M=0;M<de.length;++M){var ee=de[M]&31;nm(t,u,ce[ee]),u+=P[ee],ee>15&&(nm(t,u,de[M]>>5&127),u+=de[M]>>12)}}else G=Yrt,V=mg,J=tit,oe=X_;for(var M=0;M<c;++M){var X=i[M];if(X>255){var ee=X>>18&31;bw(t,u,G[ee+257]),u+=V[ee+257],ee>7&&(nm(t,u,X>>23&31),u+=fk[ee]);var ge=X&31;bw(t,u,J[ge]),u+=oe[ge],ge>3&&(bw(t,u,X>>5&8191),u+=hk[ge])}else bw(t,u,G[X]),u+=V[X]}return bw(t,u,G[256]),u+V[256]},ait=new EM([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Tge=new Hr(0),sit=function(e,t,n,i,r,a){var l=a.z||e.length,c=new Hr(i+l+5*(1+Math.ceil(l/7e3))+r),o=c.subarray(i,c.length-r),s=a.l,u=(a.r||0)&7;if(t){u&&(o[0]=a.r>>3);for(var d=ait[t-1],p=d>>13,f=d&8191,h=(1<<n)-1,m=a.p||new ds(32768),g=a.h||new ds(h+1),y=Math.ceil(n/3),v=2*y,b=function(tt){return(e[tt]^e[tt+1]<<y^e[tt+2]<<v)&h},w=new EM(25e3),x=new ds(288),C=new ds(32),A=0,M=0,N=a.i||0,P=0,k=a.w||0,$=0;N+2<l;++N){var O=b(N),j=N&32767,U=g[O];if(m[j]=U,g[O]=j,k<=N){var G=l-N;if((A>7e3||P>24576)&&(G>423||!s)){u=BX(e,o,0,w,x,C,M,P,$,N-$,u),P=A=M=0,$=N;for(var V=0;V<286;++V)x[V]=0;for(var V=0;V<30;++V)C[V]=0}var J=2,oe=0,ce=f,Y=j-U&32767;if(G>2&&O==b(N-Y))for(var ye=Math.min(p,G)-1,de=Math.min(32767,N),ee=Math.min(258,G);Y<=de&&--ce&&j!=U;){if(e[N+J]==e[N+J-Y]){for(var X=0;X<ee&&e[N+X]==e[N+X-Y];++X);if(X>J){if(J=X,oe=Y,X>ye)break;for(var ge=Math.min(Y,X-2),Me=0,V=0;V<ge;++V){var De=N-Y+V&32767,at=m[De],it=De-at&32767;it>Me&&(Me=it,U=De)}}}j=U,U=m[j],Y+=j-U&32767}if(oe){w[P++]=268435456|GO[J]<<18|FX[oe];var xe=GO[J]&31,we=FX[oe]&31;M+=fk[xe]+hk[we],++x[257+xe],++C[we],k=N+J,++A}else w[P++]=e[N],++x[e[N]]}}for(N=Math.max(N,k);N<l;++N)w[P++]=e[N],++x[e[N]];u=BX(e,o,s,w,x,C,M,P,$,N-$,u),s||(a.r=u&7|o[u/8|0]<<3,u-=7,a.h=g,a.p=m,a.i=N,a.w=k)}else{for(var N=a.w||0;N<l+s;N+=65535){var qe=N+65535;qe>=l&&(o[u/8|0]=s,qe=l),u=Cge(o,u+1,e.subarray(N,qe))}a.i=l}return L2(c,0,i+kM(u)+r)},oit=(function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var n=t,i=9;--i;)n=(n&1&&-306674912)^n>>>1;e[t]=n}return e})(),lit=function(){var e=-1;return{p:function(t){for(var n=e,i=0;i<t.length;++i)n=oit[n&255^t[i]]^n>>>8;e=n},d:function(){return~e}}},cit=function(e,t,n,i,r){if(!r&&(r={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),l=new Hr(a.length+e.length);l.set(a),l.set(e,a.length),e=l,r.w=a.length}return sit(e,t.level==null?6:t.level,t.mem==null?r.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,i,r)},Ege=function(e,t){var n={};for(var i in e)n[i]=e[i];for(var i in t)n[i]=t[i];return n},kc=function(e,t){return e[t]|e[t+1]<<8},_o=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},ZA=function(e,t){return _o(e,t)+_o(e,t+4)*4294967296},qi=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function uit(e,t){return cit(e,t||{},0,0)}function dit(e,t){return iit(e,{i:2},t&&t.out,t&&t.dictionary)}var kge=function(e,t,n,i){for(var r in e){var a=e[r],l=t+r,c=i;Array.isArray(a)&&(c=Ege(i,a[1]),a=a[0]),a instanceof Hr?n[l]=[a,c]:(n[l+="/"]=[new Hr(0),c],kge(a,l,n,i))}},WX=typeof TextEncoder<"u"&&new TextEncoder,JO=typeof TextDecoder<"u"&&new TextDecoder,pit=0;try{JO.decode(Tge,{stream:!0}),pit=1}catch{}var fit=function(e){for(var t="",n=0;;){var i=e[n++],r=(i>127)+(i>223)+(i>239);if(n+r>e.length)return{s:t,r:L2(e,n-1)};r?r==3?(i=((i&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|i>>10,56320|i&1023)):r&1?t+=String.fromCharCode((i&31)<<6|e[n++]&63):t+=String.fromCharCode((i&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(i)}};function zX(e,t){var n;if(WX)return WX.encode(e);for(var i=e.length,r=new Hr(e.length+(e.length>>1)),a=0,l=function(s){r[a++]=s},n=0;n<i;++n){if(a+5>r.length){var c=new Hr(a+8+(i-n<<1));c.set(r),r=c}var o=e.charCodeAt(n);o<128||t?l(o):o<2048?(l(192|o>>6),l(128|o&63)):o>55295&&o<57344?(o=65536+(o&1047552)|e.charCodeAt(++n)&1023,l(240|o>>18),l(128|o>>12&63),l(128|o>>6&63),l(128|o&63)):(l(224|o>>12),l(128|o>>6&63),l(128|o&63))}return L2(r,0,a)}function hit(e,t){if(t){for(var n="",i=0;i<e.length;i+=16384)n+=String.fromCharCode.apply(null,e.subarray(i,i+16384));return n}else{if(JO)return JO.decode(e);var r=fit(e),a=r.s,n=r.r;return n.length&&va(8),a}}var mit=function(e,t){return t+30+kc(e,t+26)+kc(e,t+28)},git=function(e,t,n){var i=kc(e,t+28),r=hit(e.subarray(t+46,t+46+i),!(kc(e,t+8)&2048)),a=t+46+i,l=_o(e,t+20),c=n&&l==4294967295?yit(e,a):[l,_o(e,t+24),_o(e,t+42)],o=c[0],s=c[1],u=c[2];return[kc(e,t+10),o,s,r,a+kc(e,t+30)+kc(e,t+32),u]},yit=function(e,t){for(;kc(e,t)!=1;t+=4+kc(e,t+2));return[ZA(e,t+12),ZA(e,t+4),ZA(e,t+20)]},KO=function(e){var t=0;if(e)for(var n in e){var i=e[n].length;i>65535&&va(9),t+=i+4}return t},GX=function(e,t,n,i,r,a,l,c){var o=i.length,s=n.extra,u=c&&c.length,d=KO(s);qi(e,t,l!=null?33639248:67324752),t+=4,l!=null&&(e[t++]=20,e[t++]=n.os),e[t]=20,t+=2,e[t++]=n.flag<<1|(a<0&&8),e[t++]=r&&8,e[t++]=n.compression&255,e[t++]=n.compression>>8;var p=new Date(n.mtime==null?Date.now():n.mtime),f=p.getFullYear()-1980;if((f<0||f>119)&&va(10),qi(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,a!=-1&&(qi(e,t,n.crc),qi(e,t+4,a<0?-a-2:a),qi(e,t+8,n.size)),qi(e,t+12,o),qi(e,t+14,d),t+=16,l!=null&&(qi(e,t,u),qi(e,t+6,n.attrs),qi(e,t+10,l),t+=14),e.set(i,t),t+=o,d)for(var h in s){var m=s[h],g=m.length;qi(e,t,+h),qi(e,t+2,g),e.set(m,t+4),t+=4+g}return u&&(e.set(c,t),t+=u),t},vit=function(e,t,n,i,r){qi(e,t,101010256),qi(e,t+8,n),qi(e,t+10,n),qi(e,t+12,i),qi(e,t+16,r)};function Age(e,t){t||(t={});var n={},i=[];kge(e,"",n,t);var r=0,a=0;for(var l in n){var c=n[l],o=c[0],s=c[1],u=s.level==0?0:8,d=zX(l),p=d.length,f=s.comment,h=f&&zX(f),m=h&&h.length,g=KO(s.extra);p>65535&&va(11);var y=u?uit(o,s):o,v=y.length,b=lit();b.p(o),i.push(Ege(s,{size:o.length,crc:b.d(),c:y,f:d,m:h,u:p!=l.length||h&&f.length!=m,o:r,compression:u})),r+=30+p+g+v,a+=76+2*(p+g)+(m||0)+v}for(var w=new Hr(a+22),x=r,C=a-r,A=0;A<i.length;++A){var d=i[A];GX(w,d.o,d,d.f,d.u,d.c.length);var M=30+d.f.length+KO(d.extra);w.set(d.c,d.o+M),GX(w,r,d,d.f,d.u,d.c.length,d.o,d.m),r+=16+M+(d.m?d.m.length:0)}return vit(w,r,i.length,C,x),w}function mk(e,t){for(var n={},i=e.length-22;_o(e,i)!=101010256;--i)(!i||e.length-i>65558)&&va(13);var r=kc(e,i+8);if(!r)return{};var a=_o(e,i+16),l=a==4294967295||r==65535;if(l){var c=_o(e,i-12);l=_o(e,c)==101075792,l&&(r=_o(e,c+32),a=_o(e,c+48))}for(var o=t&&t.filter,s=0;s<r;++s){var u=git(e,a,l),d=u[0],p=u[1],f=u[2],h=u[3],m=u[4],g=u[5],y=mit(e,g);a=m,(!o||o({name:h,size:p,originalSize:f,compression:d}))&&(d?d==8?n[h]=dit(e.subarray(y,y+p),{out:new Hr(f)}):va(14,"unknown compression type "+d):n[h]=L2(e,y,y+p))}return n}function bit(e){return e<1024?e+" B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/(1024*1024)).toFixed(1)+"M":(e/(1024*1024*1024)).toFixed(1)+"G"}function Rge(e){const t="http://www.w3.org/2000/svg",n=document.createElementNS(t,"svg");n.setAttribute("width","14"),n.setAttribute("height","14"),n.setAttribute("viewBox","0 0 20 20"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.5"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.style.flexShrink="0";for(const i of e){const r=document.createElementNS(t,"path");r.setAttribute("d",i),n.appendChild(r)}return n}function wit(){return Rge(["M2 6V5a1 1 0 0 1 1-1h4l2 2h8a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V6z"])}function _it(){return Rge(["M6 2h5l5 5v9a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1z","M11 2v5h5"])}function xit(e){const t="http://www.w3.org/2000/svg",n=document.createElementNS(t,"svg");n.setAttribute("width","10"),n.setAttribute("height","10"),n.setAttribute("viewBox","0 0 20 20"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","2"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.style.flexShrink="0",n.style.transition="transform 130ms ease",e&&(n.style.transform="rotate(90deg)");const i=document.createElementNS(t,"path");return i.setAttribute("d","M7 5l5 5-5 5"),n.appendChild(i),n}function Sit(e){return`'${e.replace(/'/g,"'\\''")}'`}function Cit(e){return`${Xme(e)?"imgcat":"cat"} ${Sit(e)}`}class HX{container;bodyEl;fs=null;expandedDirs=new Set(["/"]);refreshTimer=null;onRunCommand;onClearFilesystem;selectedPath=null;keydownHandler=null;constructor(t,n={}){this.container=t,this.onRunCommand=n.onRunCommand??null,this.onClearFilesystem=n.onClearFilesystem??null,this.render()}setFs(t){this.fs=t,this.refresh(),this.refreshTimer=setInterval(()=>this.refresh(),3e3)}async refresh(){if(!this.fs)return;const t=document.createElement("div");try{await this.renderDir("/",t,0)}catch(i){console.warn("[FileBrowser] Refresh failed:",i instanceof Error?i.message:String(i));return}if(t.innerHTML===this.bodyEl.innerHTML){this.applySelection();return}const n=this.container.contains(document.activeElement);for(;this.bodyEl.firstChild;)this.bodyEl.removeChild(this.bodyEl.firstChild);for(;t.firstChild;)this.bodyEl.appendChild(t.firstChild);this.applySelection(),n&&this.selectedPath&&this.bodyEl.querySelector(".file-browser__item--selected")?.focus()}render(){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);if(this.container.classList.add("file-browser"),this.onClearFilesystem){const t=document.createElement("div");t.className="file-browser__header";const n=document.createElement("span");n.className="file-browser__header-title",n.textContent="Files",t.appendChild(n);const i=document.createElement("button");i.className="file-browser__header-btn",i.setAttribute("aria-label","Clear filesystem"),i.dataset.tooltip="Clear filesystem",i.innerHTML='<svg width="14" height="14" viewBox="0 0 20 20" fill="none"><path d="m8.249,15.021c-.4,0-.733-.317-.748-.72l-.25-6.5c-.017-.414.307-.763.72-.778.01-.001.021-.001.03-.001.4,0,.733.317.748.72l.25,6.5c.017.414-.307.763-.72.778-.01.001-.021.001-.03.001Z" fill="currentColor"/><path d="m11.751,15.021c-.01,0-.02,0-.03-.001-.413-.016-.736-.364-.72-.778l.25-6.5c.015-.403.348-.72.748-.72.01,0,.02,0,.03.001.413.016.736.364.72.778l-.25,6.5c-.015.403-.348.72-.748.72Z" fill="currentColor"/><path d="m17,4h-3.5v-.75c0-1.24-1.01-2.25-2.25-2.25h-2.5c-1.24,0-2.25,1.01-2.25,2.25v.75h-3.5c-.414,0-.75.336-.75.75s.336.75.75.75h.52l.422,10.342c.048,1.21,1.036,2.158,2.248,2.158h7.619c1.212,0,2.2-.948,2.248-2.158l.422-10.342h.52c.414,0,.75-.336.75-.75s-.336-.75-.75-.75Zm-9-.75c0-.413.337-.75.75-.75h2.5c.413,0,.75.337.75.75v.75h-4v-.75Zm6.56,12.531c-.017.403-.346.719-.75.719h-7.619c-.404,0-.733-.316-.75-.719l-.42-10.281h9.959l-.42,10.281Z" fill="currentColor"/></svg>',i.addEventListener("click",async()=>{await this.onClearFilesystem?.(),location.reload()}),t.appendChild(i),this.container.appendChild(t)}this.bodyEl=document.createElement("div"),this.bodyEl.className="file-browser__body",this.container.appendChild(this.bodyEl),this.setupKeydown()}async renderDir(t,n,i){if(!this.fs)return;let r;try{r=await this.fs.readDir(t)}catch(c){console.warn("[FileBrowser] readDir failed:",t,c instanceof Error?c.message:String(c));return}const a=r.filter(c=>c.type==="directory").sort((c,o)=>c.name.localeCompare(o.name)),l=r.filter(c=>c.type==="file").sort((c,o)=>c.name.localeCompare(o.name));for(const c of[...a,...l]){const o=t==="/"?"/"+c.name:t+"/"+c.name,s=document.createElement("div");if(s.className="file-browser__item",s.style.paddingLeft=12+i*16+"px",s.dataset.path=c.type==="directory"&&!o.endsWith("/")?o+"/":o,c.type==="directory"){const u=this.expandedDirs.has(o),d=document.createElement("span");d.className="file-browser__arrow",d.appendChild(xit(u)),s.appendChild(d);const p=document.createElement("span");p.className="file-browser__icon",p.appendChild(wit()),s.appendChild(p);const f=document.createElement("span");f.className="file-browser__name",f.textContent=c.name,s.appendChild(f);const h=document.createElement("button");h.className="file-browser__action-btn",h.style.marginLeft="auto",h.textContent="ZIP",h.title="Download as ZIP",h.addEventListener("click",m=>{m.stopPropagation(),this.downloadDirAsZip(o,c.name)}),s.appendChild(h),s.style.cursor="pointer",s.addEventListener("click",()=>{this.selectPath(o,"directory"),this.expandedDirs.has(o)?this.expandedDirs.delete(o):this.expandedDirs.add(o),this.refresh()}),n.appendChild(s),u&&await this.renderDir(o,n,i+1)}else{const u=document.createElement("span");u.className="file-browser__arrow",s.appendChild(u);const d=document.createElement("span");d.className="file-browser__icon",d.appendChild(_it()),s.appendChild(d);const p=document.createElement("span");p.className="file-browser__name",p.textContent=c.name,s.appendChild(p);try{const h=await this.fs.stat(o),m=document.createElement("span");m.className="file-browser__size",m.textContent=bit(h.size),s.appendChild(m)}catch(h){console.warn("[FileBrowser] stat failed:",o,h instanceof Error?h.message:String(h))}const f=document.createElement("button");f.className="file-browser__action-btn",f.style.marginLeft="8px",f.textContent="CAT",f.title=this.onRunCommand?Xme(o)?"Preview media in terminal":"Preview in terminal":"Terminal unavailable",f.disabled=!this.onRunCommand,f.addEventListener("click",h=>{h.stopPropagation(),this.previewFile(o)}),s.appendChild(f),s.addEventListener("click",()=>{this.selectPath(o,"file")}),n.appendChild(s)}}}async collectFiles(t,n){if(!this.fs)return{};const i={},r=await this.fs.readDir(t);for(const a of r){const l=t==="/"?"/"+a.name:t+"/"+a.name,c=n?n+"/"+a.name:a.name;if(a.type==="directory"){const o=await this.collectFiles(l,c);Object.assign(i,o)}else{const o=await this.fs.readFile(l,{encoding:"binary"});i[c]=o instanceof Uint8Array?o:new TextEncoder().encode(o)}}return i}async downloadDirAsZip(t,n){if(this.fs)try{const i=await this.collectFiles(t,""),r=Age(i),a=new Blob([r.buffer],{type:"application/zip"}),l=URL.createObjectURL(a),c=document.createElement("a");c.href=l,c.download=n+".zip",c.click(),URL.revokeObjectURL(l)}catch(i){console.error("[FileBrowser] ZIP download failed:",t,i instanceof Error?i.message:String(i))}}previewFile(t){if(!this.onRunCommand)return;const n=Cit(t);Promise.resolve(this.onRunCommand(n)).catch(i=>{console.error("[FileBrowser] Preview command failed:",t,i instanceof Error?i.message:String(i))})}selectPath(t,n){this.selectedPath=n==="directory"&&!t.endsWith("/")?t+"/":t,this.applySelection(),this.bodyEl.querySelector(".file-browser__item--selected")?.focus()}applySelection(){const t=this.bodyEl.querySelector(".file-browser__item--selected");if(t&&(t.classList.remove("file-browser__item--selected"),t.removeAttribute("tabindex")),!this.selectedPath)return;const n=this.bodyEl.querySelectorAll(".file-browser__item");for(const i of n)if(i.dataset.path===this.selectedPath){i.classList.add("file-browser__item--selected"),i.tabIndex=0;break}}setupKeydown(){this.keydownHandler=t=>{!(t.metaKey||t.ctrlKey)||t.key!=="c"||!this.selectedPath||!(window.getSelection()?.isCollapsed!==!1)||(t.preventDefault(),navigator.clipboard.writeText(this.selectedPath).then(()=>{this.flashCopyFeedback()}).catch(i=>{console.warn("[FileBrowser] Clipboard write failed:",i instanceof Error?i.message:String(i))}))},this.container.addEventListener("keydown",this.keydownHandler)}flashCopyFeedback(){const t=this.bodyEl.querySelector(".file-browser__item--selected");t&&(t.classList.add("file-browser__item--copy-flash"),setTimeout(()=>{t.classList.remove("file-browser__item--copy-flash")},300))}dispose(){for(this.keydownHandler&&(this.container.removeEventListener("keydown",this.keydownHandler),this.keydownHandler=null),this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null);this.container.firstChild;)this.container.removeChild(this.container.firstChild)}}class VX{container;bodyEl;orchestrator=null;selectedScoopJid=null;refreshTimer=null;constructor(t){this.container=t,this.render()}setOrchestrator(t){this.orchestrator=t,this.refresh(),this.refreshTimer=setInterval(()=>this.refresh(),5e3)}setSelectedScoop(t){this.selectedScoopJid=t,this.refresh()}async refresh(){if(!this.orchestrator)return;const t=document.createElement("div");t.className="memory-panel__content";const n=document.createElement("div");n.className="memory-panel__section";const i=document.createElement("div");i.className="memory-panel__section-header",i.textContent="Global Memory (/shared/CLAUDE.md)",n.appendChild(i);const r=document.createElement("div");r.className="memory-panel__memory-content";try{const a=await this.orchestrator.getGlobalMemory();r.textContent=a||"(empty)"}catch{r.textContent="(not available)"}if(n.appendChild(r),t.appendChild(n),this.selectedScoopJid){const a=this.orchestrator.getScoopContext(this.selectedScoopJid),l=this.orchestrator.getScoop(this.selectedScoopJid);if(a&&l){const c=document.createElement("div");c.className="memory-panel__section";const o=document.createElement("div");o.className="memory-panel__section-header",o.textContent=`${l.isCone?"Cone":"Scoop"}: ${l.assistantLabel}`,c.appendChild(o);const s=document.createElement("div");s.className="memory-panel__memory-content";try{const u=a.getFS();if(u){const d=l.isCone?"/workspace/CLAUDE.md":`/scoops/${l.folder}/CLAUDE.md`,p=await u.readFile(d,{encoding:"utf-8"});s.textContent=typeof p=="string"?p:new TextDecoder().decode(p)}else s.textContent="(filesystem not ready)"}catch{s.textContent="(no memory file yet)"}c.appendChild(s),t.appendChild(c)}}if(t.innerHTML!==this.bodyEl.innerHTML){for(;this.bodyEl.firstChild;)this.bodyEl.removeChild(this.bodyEl.firstChild);for(;t.firstChild;)this.bodyEl.appendChild(t.firstChild)}}render(){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.container.classList.add("memory-panel"),this.bodyEl=document.createElement("div"),this.bodyEl.className="memory-panel__body",this.container.appendChild(this.bodyEl)}dispose(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}}const JX=mr("scoops-panel");class KX{container;orchestrator=null;callbacks;selectedScoopJid=null;scoopStatuses=new Map;expanded=!1;constructor(t,n){this.container=t,this.callbacks=n,this.render()}toggleExpanded(){this.expanded=!this.expanded,this.container.classList.toggle("layout__scoops--expanded",this.expanded);const t=this.container.querySelector(".scoops-hamburger");t&&(t.innerHTML=this.expanded?'<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M9.86241 16.4551C9.66612 16.4551 9.46886 16.3779 9.32237 16.2246L3.83507 10.5215C3.5548 10.2315 3.5548 9.77247 3.83507 9.48243L9.33507 3.76563C9.62218 3.4668 10.0978 3.45801 10.3946 3.74512C10.6935 4.03223 10.7032 4.50684 10.4151 4.80469L5.41613 10.002L10.4025 15.1855C10.6906 15.4834 10.6808 15.958 10.382 16.2451C10.2374 16.3857 10.0499 16.4551 9.86241 16.4551Z"/><path d="M15.6124 16.4551C15.4161 16.4551 15.2189 16.3779 15.0724 16.2246L9.58507 10.5215C9.3048 10.2315 9.3048 9.77247 9.58507 9.48243L15.0851 3.76563C15.3722 3.4668 15.8478 3.45801 16.1446 3.74512C16.4435 4.03223 16.4532 4.50684 16.1652 4.80469L11.1661 10.002L16.1525 15.1855C16.4406 15.4834 16.4308 15.958 16.132 16.2451C15.9874 16.3857 15.7999 16.4551 15.6124 16.4551Z"/></svg>':'<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M9.61805 16.2451C9.31922 15.958 9.30945 15.4834 9.59754 15.1855L14.5839 10.002L9.58485 4.80469C9.29677 4.50684 9.30653 4.03223 9.60536 3.74512C9.90223 3.45801 10.3778 3.4668 10.6649 3.76563L16.1649 9.48243C16.4452 9.77247 16.4452 10.2315 16.1649 10.5215L10.6776 16.2246C10.5311 16.3779 10.3339 16.4551 10.1376 16.4551C9.95008 16.4551 9.76258 16.3857 9.61805 16.2451Z"/><path d="M3.86805 16.2451C3.56922 15.958 3.55945 15.4834 3.84754 15.1855L8.83387 10.002L3.83485 4.80469C3.54677 4.50684 3.55653 4.03223 3.85536 3.74512C4.15223 3.45801 4.62782 3.4668 4.91493 3.76563L10.4149 9.48243C10.6952 9.77247 10.6952 10.2315 10.4149 10.5215L4.92763 16.2246C4.78114 16.3779 4.58388 16.4551 4.38759 16.4551C4.20008 16.4551 4.01258 16.3857 3.86805 16.2451Z"/></svg>')}setOrchestrator(t){this.orchestrator=t,this.refreshScoops()}updateScoopStatus(t,n){this.scoopStatuses.set(t,n),this.refreshScoops()}refreshScoops(){if(!this.orchestrator)return;document.querySelectorAll(".scoop-fixed-tooltip").forEach(s=>s.remove());const t=this.orchestrator.getScoops(),n=t.find(s=>s.isCone),i=t.filter(s=>!s.isCone),r="http://www.w3.org/2000/svg",a=["#e8457a","#f08c5a","#9b6dd7","#42b8a0","#d4953e"],l=["#fde4ec","#fef0e4","#efe4f8","#e0f5ef","#fef3e0"],c=this.container.querySelector(".scoop-cone-header");if(c){for(;c.firstChild;)c.removeChild(c.firstChild);if(n){const s=this.scoopStatuses.get(n.jid)??"inactive",u=n.jid===this.selectedScoopJid,d="#e07030",p="#fef0e0",f=document.createElement("div");f.className=`scoop-item scoop-item--cone ${u?"selected":""} status-${s}`,f.dataset.jid=n.jid,f.setAttribute("aria-label",n.assistantLabel),f.style.setProperty("--scoop-accent",d),f.style.setProperty("--scoop-accent-bg",p);const h=document.createElement("div");h.className="scoop-icon-wrap scoop-icon-wrap--cone",h.style.background=p,h.style.width="40px",h.style.height="40px";const m=document.createElementNS(r,"svg");m.setAttribute("width","24"),m.setAttribute("height","24"),m.setAttribute("fill",d),m.setAttribute("viewBox","100 195 230 235");const g=document.createElementNS(r,"path");if(g.setAttribute("d","M331.2,128.8c1.6-4.8,2.4-11.2,2.4-16.8c0-20.8-12.8-40-31.2-48.8c-8-36-47.2-63.2-92.8-63.2c-48,0-88,29.6-93.6,68.8C102.4,79.2,94.4,95.2,94.4,112c0,4.8,0.8,9.6,1.6,13.6c-7.2,9.6-10.4,20.8-10.4,32C85.6,180,100,200,120,208l85.6,212.8c1.6,3.2,4,4.8,7.2,4.8s6.4-1.6,7.2-4.8L305.6,208c20-8,34.4-27.2,34.4-50.4C340,147.2,336.8,136.8,331.2,128.8z M139.2,216l-1.6-3.2h0.8c1.6,0,2.4,0,4,0L139.2,216z M145.6,232.8l23.2-24.8c4.8,6.4,11.2,11.2,18.4,14.4l12,12l-28.8,30.4l-20.8-22.4L145.6,232.8z M210.4,246.4l28.8,30.4L210.4,308l-28.8-31.2L210.4,246.4z M168.8,289.6l1.6-1.6l28.8,32l-12.8,13.6L168.8,289.6z M212,396.8l-18.4-46.4l16.8-18.4l19.2,21.6L212,396.8z M236.8,336l-15.2-16.8l28.8-31.2l4,4L236.8,336z M250.4,264.8l-28.8-30.4l11.2-12c8-3.2,14.4-8,19.2-14.4l25.6,27.2L250.4,264.8z M284,218.4l-6.4-6.4c2.4,0,4.8,0.8,8,0.8h0.8L284,218.4z M285.6,196c-9.6,0-19.2-4-26.4-11.2c-1.6-1.6-4.8-2.4-7.2-2.4c-2.4,0.8-4.8,2.4-5.6,4.8c-6.4,13.6-20,23.2-35.2,23.2c-14.4,0-28-8.8-34.4-21.6c-0.8-2.4-3.2-4-5.6-4.8c-0.8,0-0.8,0-1.6,0c-1.6,0-4,0.8-5.6,2.4c-7.2,6.4-16,9.6-25.6,9.6c-20.8,0-38.4-16.8-38.4-38.4c0-9.6,3.2-18.4,9.6-24.8c1.6-2.4,2.4-5.6,1.6-8c-1.6-4-2.4-8.8-2.4-12.8c0-12.8,6.4-24.8,17.6-32c2.4-1.6,3.2-4,4-6.4c2.4-32,36.8-57.6,78.4-57.6c39.2,0,72.8,23.2,77.6,54.4c0.8,3.2,2.4,5.6,4.8,6.4c15.2,5.6,24.8,20,24.8,36c0,4.8-0.8,10.4-3.2,15.2c-0.8,2.4-0.8,5.6,0.8,8c4.8,6.4,8,14.4,8,23.2C323.2,179.2,306.4,196,285.6,196z"),m.appendChild(g),h.appendChild(m),s==="processing"||s==="ready"||s==="error"){const x=document.createElement("span");x.className=`scoop-dot scoop-dot--${s}`,h.appendChild(x)}f.appendChild(h);const y=document.createElement("div");y.className="scoop-info";const v=document.createElement("div");if(v.className="scoop-name",v.textContent=n.assistantLabel,y.appendChild(v),s==="processing"||s==="error"){const x=document.createElement("div");x.className="scoop-subtitle",x.textContent=s==="processing"?"Working…":"Error",y.appendChild(x)}f.appendChild(y);const b=document.createElement("div");if(b.className="scoop-actions",s==="processing"){const x=document.createElement("span");x.className="scoop-spin-dot",b.appendChild(x)}else if(s==="error"){const x=document.createElement("span");x.className="scoop-err-dot",b.appendChild(x)}f.appendChild(b),f.addEventListener("click",()=>this.selectScoop(n));const w=n.assistantLabel;f.addEventListener("mouseenter",()=>{if(this.expanded)return;const x=document.createElement("div");x.className="scoop-fixed-tooltip",x.textContent=w,document.body.appendChild(x);const C=f.getBoundingClientRect();x.style.top=`${C.top+C.height/2}px`,x.style.left=`${C.right+8}px`,f.__tip=x}),f.addEventListener("mouseleave",()=>{const x=f.__tip;x&&(x.remove(),f.__tip=null)}),c.appendChild(f)}}const o=this.container.querySelector(".scoops-list");if(o){for(;o.firstChild;)o.removeChild(o.firstChild);if(i.length===0){this.callbacks.onScoopsChanged?.(t);return}for(let s=0;s<i.length;s++){const u=i[s],d=this.scoopStatuses.get(u.jid)??"inactive",p=u.jid===this.selectedScoopJid,f=a[s%a.length],h=l[s%l.length],m=document.createElement("div");m.className=`scoop-item ${p?"selected":""} status-${d}`,m.dataset.jid=u.jid;const g=u.assistantLabel.replace(/-scoop$/,"");m.setAttribute("aria-label",g),m.style.setProperty("--scoop-accent",f),m.style.setProperty("--scoop-accent-bg",h);const y=document.createElement("div");y.className="scoop-icon-wrap",y.style.background=h;const v=document.createElementNS(r,"svg");v.setAttribute("width","20"),v.setAttribute("height","20"),v.setAttribute("fill",f),v.setAttribute("viewBox","70 0 290 210");const b=document.createElementNS(r,"path");if(b.setAttribute("d","M331.2,128.8c1.6-4.8,2.4-11.2,2.4-16.8c0-20.8-12.8-40-31.2-48.8c-8-36-47.2-63.2-92.8-63.2c-48,0-88,29.6-93.6,68.8C102.4,79.2,94.4,95.2,94.4,112c0,4.8,0.8,9.6,1.6,13.6c-7.2,9.6-10.4,20.8-10.4,32C85.6,180,100,200,120,208l85.6,212.8c1.6,3.2,4,4.8,7.2,4.8s6.4-1.6,7.2-4.8L305.6,208c20-8,34.4-27.2,34.4-50.4C340,147.2,336.8,136.8,331.2,128.8z M285.6,196c-9.6,0-19.2-4-26.4-11.2c-1.6-1.6-4.8-2.4-7.2-2.4c-2.4,0.8-4.8,2.4-5.6,4.8c-6.4,13.6-20,23.2-35.2,23.2c-14.4,0-28-8.8-34.4-21.6c-0.8-2.4-3.2-4-5.6-4.8c-0.8,0-0.8,0-1.6,0c-1.6,0-4,0.8-5.6,2.4c-7.2,6.4-16,9.6-25.6,9.6c-20.8,0-38.4-16.8-38.4-38.4c0-9.6,3.2-18.4,9.6-24.8c1.6-2.4,2.4-5.6,1.6-8c-1.6-4-2.4-8.8-2.4-12.8c0-12.8,6.4-24.8,17.6-32c2.4-1.6,3.2-4,4-6.4c2.4-32,36.8-57.6,78.4-57.6c39.2,0,72.8,23.2,77.6,54.4c0.8,3.2,2.4,5.6,4.8,6.4c15.2,5.6,24.8,20,24.8,36c0,4.8-0.8,10.4-3.2,15.2c-0.8,2.4-0.8,5.6,0.8,8c4.8,6.4,8,14.4,8,23.2C323.2,179.2,306.4,196,285.6,196z"),v.appendChild(b),y.appendChild(v),d==="processing"||d==="ready"||d==="error"){const M=document.createElement("span");M.className=`scoop-dot scoop-dot--${d}`,y.appendChild(M)}m.appendChild(y);const w=document.createElement("div");w.className="scoop-info";const x=document.createElement("div");if(x.className="scoop-name",x.textContent=g,w.appendChild(x),d==="processing"||d==="error"){const M=document.createElement("div");M.className="scoop-subtitle",M.textContent=d==="processing"?"Working…":"Error",w.appendChild(M)}m.appendChild(w);const C=document.createElement("div");if(C.className="scoop-actions",d==="processing"){const M=document.createElement("span");M.className="scoop-spin-dot",C.appendChild(M)}else if(d==="error"){const M=document.createElement("span");M.className="scoop-err-dot",C.appendChild(M)}const A=document.createElement("button");A.className="scoop-delete",A.dataset.tooltip="Delete scoop",A.setAttribute("aria-label","Delete scoop"),A.innerHTML='<svg width="14" height="14" viewBox="0 0 20 20" fill="none"><path d="M6 6L14 14M14 6L6 14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>',C.appendChild(A),m.appendChild(C),m.addEventListener("click",M=>{M.target.closest(".scoop-delete")?this.deleteScoop(u.jid):this.selectScoop(u)}),m.addEventListener("mouseenter",()=>{if(this.expanded)return;const M=document.createElement("div");M.className="scoop-fixed-tooltip",M.textContent=g,document.body.appendChild(M);const N=m.getBoundingClientRect();M.style.top=`${N.top+N.height/2}px`,M.style.left=`${N.right+8}px`,m.__tip=M}),m.addEventListener("mouseleave",()=>{const M=m.__tip;M&&(M.remove(),m.__tip=null)}),o.appendChild(m)}this.callbacks.onScoopsChanged?.(t)}}selectScoop(t){this.selectedScoopJid=t.jid,this.refreshScoops(),this.callbacks.onScoopSelect(t);const n=new URL(window.location.href);t.isCone?n.searchParams.delete("scoop"):n.searchParams.set("scoop",t.folder),history.replaceState(null,"",n.toString())}selectScoopByFolder(t){if(!this.orchestrator)return;const i=this.orchestrator.getScoops().find(r=>r.folder===t);i&&this.selectScoop(i)}setSelectedJid(t){this.selectedScoopJid=t,this.refreshScoops()}getSelectedScoopJid(){return this.selectedScoopJid}async deleteScoop(t){if(!this.orchestrator)return;const n=this.orchestrator.getScoop(t);if(n){if(n.isCone){alert("Cannot delete the cone");return}if(confirm(`Delete scoop "${n.name}"? This cannot be undone.`)){try{await this.orchestrator.unregisterScoop(t)}catch(i){const r=i instanceof Error?i.message:String(i);alert(r);return}this.selectedScoopJid===t&&(this.selectedScoopJid=null),this.refreshScoops(),JX.info("Scoop deleted",{jid:t,name:n.name})}}}async createScoop(t,n=!1){if(!this.orchestrator)throw new Error("Orchestrator not set");const i=n?"cone":this.sanitizeFolderName(t)+"-scoop",r=n?`cone_${Date.now()}`:`scoop_${i}_${Date.now()}`,a={jid:r,name:t,folder:i,trigger:n?void 0:`@${i}`,requiresTrigger:!n,isCone:n,type:n?"cone":"scoop",assistantLabel:n?"sliccy":i,addedAt:new Date().toISOString()};return await this.orchestrator.registerScoop(a),this.refreshScoops(),JX.info("Scoop created",{jid:r,name:t,isCone:n}),a}sanitizeFolderName(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50)||"scoop"}render(){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);const t=document.createElement("div");t.className="scoops-panel";const n=document.createElement("button");n.className="scoops-hamburger",n.dataset.tooltip="Toggle navigation",n.dataset.tooltipPos="right",n.setAttribute("aria-label","Toggle navigation"),n.innerHTML='<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M9.61805 16.2451C9.31922 15.958 9.30945 15.4834 9.59754 15.1855L14.5839 10.002L9.58485 4.80469C9.29677 4.50684 9.30653 4.03223 9.60536 3.74512C9.90223 3.45801 10.3778 3.4668 10.6649 3.76563L16.1649 9.48243C16.4452 9.77247 16.4452 10.2315 16.1649 10.5215L10.6776 16.2246C10.5311 16.3779 10.3339 16.4551 10.1376 16.4551C9.95008 16.4551 9.76258 16.3857 9.61805 16.2451Z"/><path d="M3.86805 16.2451C3.56922 15.958 3.55945 15.4834 3.84754 15.1855L8.83387 10.002L3.83485 4.80469C3.54677 4.50684 3.55653 4.03223 3.85536 3.74512C4.15223 3.45801 4.62782 3.4668 4.91493 3.76563L10.4149 9.48243C10.6952 9.77247 10.6952 10.2315 10.4149 10.5215L4.92763 16.2246C4.78114 16.3779 4.58388 16.4551 4.38759 16.4551C4.20008 16.4551 4.01258 16.3857 3.86805 16.2451Z"/></svg>',n.addEventListener("click",()=>this.toggleExpanded()),t.appendChild(n);const i=document.createElement("div");i.className="scoop-cone-header",t.appendChild(i);const r=document.createElement("div");r.className="scoops-list",t.appendChild(r),this.container.appendChild(t);const a=document.createElement("style");a.textContent=`
682
682
  .scoops-panel {
683
683
  display: flex;
@@ -1150,7 +1150,7 @@ Result: ${c.result??""}
1150
1150
  50% { transform: scale(1.3); }
1151
1151
  100% { transform: scale(1); }
1152
1152
  }
1153
- `,document.head.appendChild(t)}}const Oge=[{id:"chat",label:"Chat"},{id:"terminal",label:"Terminal"},{id:"files",label:"Files"},{id:"memory",label:"Memory"}],Ige="slicc-hidden-tabs",ZX=["terminal","memory"];function Eit(){try{const e=localStorage.getItem(Ige);return e?new Set(JSON.parse(e)):new Set(ZX)}catch{return new Set(ZX)}}function kit(e){const t=e.filter(n=>n!=="chat");localStorage.setItem(Ige,JSON.stringify(t))}const Ait=Oge.filter(e=>!Eit().has(e.id)),XX="chat",Rit=new Set(Oge.map(e=>e.id));function Oit(e){return Rit.has(e)}class QX{zoneId;tabBar;contentArea;tabs=new Map;activeTabId=null;callbacks;addBtn=null;fullpageBtn=null;isFullpage=!1;separator=null;scrollArea=null;storageKey;classPrefix;constructor(t,n,i,r={},a={}){this.tabBar=t,this.contentArea=n,this.zoneId=i,this.callbacks=r,this.storageKey=`slicc-${i}-tab`,this.classPrefix=a.classPrefix??"mini-tabs"}addTab(t){if(this.tabs.has(t.id))return;const n=document.createElement("button");if(n.dataset.tabId=t.id,t.pinned&&t.icon){n.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--icon ${this.classPrefix}__tab--dimmed`,n.innerHTML=t.icon,n.setAttribute("aria-label",t.label),n.dataset.tooltip=t.label,n.dataset.tooltipPos="top";const i=this.separator||this.findFirstNonPinnedBtn()||this.addBtn;if(i?this.tabBar.insertBefore(n,i):this.tabBar.appendChild(n),!this.separator){this.separator=document.createElement("div"),this.separator.className=`${this.classPrefix}__separator`,this.scrollArea=document.createElement("div"),this.scrollArea.className=`${this.classPrefix}__scroll`;const r=this.addBtn||this.fullpageBtn;r?(this.tabBar.insertBefore(this.separator,r),this.tabBar.insertBefore(this.scrollArea,r)):(this.tabBar.appendChild(this.separator),this.tabBar.appendChild(this.scrollArea))}n.addEventListener("click",()=>{const r=this.tabs.get(t.id);r&&!r.mounted&&this.enablePinnedTab(t.id),this.activateTab(t.id)}),this.tabs.set(t.id,{btn:n,container:t.element,tab:t,mounted:!1})}else{if(n.className=`${this.classPrefix}__tab`,n.appendChild(document.createTextNode(t.label)),t.closable){const r=document.createElement("span");r.className=`${this.classPrefix}__tab-close`,r.title="Close panel",r.textContent="×",r.addEventListener("click",a=>{a.stopPropagation(),this.callbacks.onTabClose?.(t.id)}),n.appendChild(r)}n.addEventListener("click",()=>this.activateTab(t.id)),this.scrollArea?this.scrollArea.appendChild(n):this.addBtn?this.tabBar.insertBefore(n,this.addBtn):this.tabBar.appendChild(n);const i=t.element;i.style.display="none",this.contentArea.appendChild(i),this.tabs.set(t.id,{btn:n,container:i,tab:t,mounted:!0}),(!this.activeTabId||!this.tabs.get(this.activeTabId)?.mounted)&&this.activateTab(t.id)}}removeTab(t){const n=this.tabs.get(t);if(n&&(n.btn.remove(),n.mounted&&n.container.remove(),this.tabs.delete(t),this.activeTabId===t)){const i=Array.from(this.tabs.entries()).find(([,r])=>r.mounted);i?this.activateTab(i[0]):this.activeTabId=null}}enablePinnedTab(t){const n=this.tabs.get(t);!n||n.mounted||(n.mounted=!0,n.btn.classList.remove(`${this.classPrefix}__tab--dimmed`),n.container.style.display="none",this.contentArea.appendChild(n.container))}isPinnedTabEnabled(t){return this.tabs.get(t)?.mounted??!1}activateTab(t){const n=this.tabs.get(t);if(!(!n||!n.mounted)){this.activeTabId=t;for(const[i,{btn:r,container:a,mounted:l}]of this.tabs){const c=i===t;r.classList.toggle(`${this.classPrefix}__tab--active`,c),l&&(a.style.display=c?"flex":"none")}try{localStorage.setItem(this.storageKey,t)}catch{}n.tab.onActivate?.(),this.callbacks.onTabActivate?.(t)}}getActiveTabId(){return this.activeTabId}getTabIds(){return Array.from(this.tabs.keys())}hasTab(t){return this.tabs.has(t)}get tabCount(){return this.tabs.size}enableAddButton(){this.addBtn||(this.addBtn=document.createElement("button"),this.addBtn.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--add`,this.addBtn.textContent="+",this.addBtn.dataset.tooltip="Open panel",this.addBtn.dataset.tooltipPos="top",this.addBtn.setAttribute("aria-label","Open panel"),this.addBtn.addEventListener("click",()=>this.callbacks.onAddClick?.()),this.tabBar.appendChild(this.addBtn))}setAddButtonEnabled(t){this.addBtn&&(this.addBtn.disabled=!t)}enableFullpageButton(){this.fullpageBtn||(this.fullpageBtn=document.createElement("button"),this.fullpageBtn.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--fullpage`,this.fullpageBtn.dataset.tooltip="Full page",this.fullpageBtn.dataset.tooltipPos="top",this.fullpageBtn.setAttribute("aria-label","Toggle full page"),this.fullpageBtn.innerHTML='<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2h4v4"/><path d="M6 14H2v-4"/><path d="M14 2L9.5 6.5"/><path d="M2 14l4.5-4.5"/></svg>',this.fullpageBtn.addEventListener("click",()=>{this.isFullpage=!this.isFullpage,this.fullpageBtn.classList.toggle(`${this.classPrefix}__tab--active`,this.isFullpage),this.fullpageBtn.innerHTML=this.isFullpage?'<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14 6h-4V2"/><path d="M2 10h4v4"/><path d="M10 6l4.5-4.5"/><path d="M6 10L1.5 14.5"/></svg>':'<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2h4v4"/><path d="M6 14H2v-4"/><path d="M14 2L9.5 6.5"/><path d="M2 14l4.5-4.5"/></svg>',this.fullpageBtn.dataset.tooltip=this.isFullpage?"Exit full page":"Full page",this.callbacks.onFullpageToggle?.(this.isFullpage)}),this.tabBar.appendChild(this.fullpageBtn))}restoreActiveTab(){try{const t=localStorage.getItem(this.storageKey);if(t&&this.tabs.has(t)&&this.tabs.get(t).mounted)return this.activateTab(t),t}catch{}return null}findFirstNonPinnedBtn(){for(const[,t]of this.tabs)if(!t.tab.pinned)return t.btn;return null}}class Iit{entries=new Map;listeners=new Set;register(t){this.entries.set(t.id,{descriptor:t}),this.notify()}unregister(t){this.entries.delete(t),this.notify()}get(t){return this.entries.get(t)}getByZone(t){const n=[];for(const i of this.entries.values())i.descriptor.zone===t&&n.push(i.descriptor);return n}getClosed(){const t=[];for(const n of this.entries.values())n.descriptor.zone===null&&t.push(n.descriptor);return t}setZone(t,n){const i=this.entries.get(t);i&&(i.descriptor.zone=n,this.notify())}ids(){return Array.from(this.entries.keys())}has(t){return this.entries.has(t)}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}notify(){for(const t of this.listeners)t()}}function YX(e,t,n){const i=document.querySelector(".sprinkle-picker");if(i){i.remove();return}const{registry:r,callbacks:a,getAvailableSprinkles:l}=n,c=r.getClosed(),o=l?.()??[];if(c.length===0&&o.length===0)return;const s=document.createElement("div");s.className="sprinkle-picker",s.style.cssText="position: absolute; min-width: 160px; max-height: 300px; overflow-y: auto; background: var(--s2-bg-layer-2); border: 1px solid var(--s2-border-default); border-radius: var(--s2-radius-l); padding: 4px 0; box-shadow: var(--s2-shadow-elevated); z-index: 1000;";const u=()=>{s.remove(),document.removeEventListener("pointerdown",p,!0),document.removeEventListener("keydown",f,!0)};for(const h of c){const m=eQ(h.label,()=>{a.onSelectPanel(h.id,t),u()});s.appendChild(m)}if(c.length>0&&o.length>0){const h=document.createElement("div");h.style.cssText="height: 1px; background: var(--s2-border-default); margin: 4px 0;",s.appendChild(h)}for(const h of o){const m=eQ(h.title,()=>{a.onSelectSprinkle(h.name,t),u()});s.appendChild(m)}const d=e.getBoundingClientRect();s.style.top=`${d.bottom+4}px`,s.style.left=`${d.left}px`,document.body.appendChild(s);const p=h=>{s.contains(h.target)||u()},f=h=>{h.key==="Escape"&&u()};requestAnimationFrame(()=>{document.addEventListener("pointerdown",p,!0),document.addEventListener("keydown",f,!0)})}function eQ(e,t){const n=document.createElement("div");return n.className="sprinkle-picker__item",n.style.cssText="padding: 6px 12px; cursor: pointer; font-size: 12px; color: var(--s2-content-default); border-radius: var(--s2-radius-s); margin: 0 4px; transition: background 130ms ease;",n.textContent=e,n.addEventListener("mouseenter",()=>{n.style.background="var(--s2-bg-elevated)"}),n.addEventListener("mouseleave",()=>{n.style.background=""}),n.addEventListener("click",t),n}class Q_{root;isExtension;scoopsEl;leftEl;rightEl;verticalDivider;terminalContainer;iframeContainer;threadHeaderEl;threadHeaderName;primaryZoneEl;primaryZone;get drawerZone(){return this.primaryZone}get drawerZoneEl(){return this.primaryZoneEl}tabContainers=new Map;activeTab="chat";debugTabContainers=null;scoopSwitcher=null;scoopSwitcherEl=null;avatarEl;logoSvg=null;logoImg=null;logoScoopCount=-1;panels;registry=new Iit;onModelChange;refreshModels;onScoopSelect;onClearChat;onClearFilesystem;onSprinkleClose;getAvailableSprinkles;onOpenSprinkle;constructor(t,n=!1){this.root=t,this.isExtension=n,n?this.buildTabbedLayout():this.buildSplitLayout()}setScoopSwitcherOrchestrator(t){this.scoopSwitcher?.setOrchestrator(t)}updateScoopSwitcherStatus(t,n){this.scoopSwitcher?.updateStatus(t,n)}setScoopSwitcherSelected(t){this.scoopSwitcher?.setSelected(t)}refreshScoopSwitcher(){this.scoopSwitcher?.refresh()}setActiveTab(t){this.isExtension&&this.extensionZone?.activateTab(t)}getActiveTab(){return this.activeTab}isTerminalOpen(){return this.isExtension?!0:this.primaryZone.isPinnedTabEnabled("terminal")}setAgentProcessing(t){this.threadHeaderEl?.classList.toggle("thread-header--processing",t)}openTerminal(){if(this.isExtension)return;this.primaryZone.isPinnedTabEnabled("terminal")||this.primaryZone.enablePinnedTab("terminal");const t=this.primaryZone.getActiveTabId();t&&t.startsWith("sprinkle-")||this.primaryZone.activateTab("terminal")}setDebugTabs(t){if(!this.isExtension||!this.debugTabContainers)return;const n=[{id:"terminal",label:"Terminal",container:this.debugTabContainers.terminal,onActivate:()=>this.panels?.terminal?.refit?.()},{id:"memory",label:"Memory",container:this.debugTabContainers.memory,onActivate:()=>this.panels?.memory?.refresh()}];for(const{id:i,label:r,container:a,onActivate:l}of n)t&&!this.extensionZone.hasTab(i)?(this.extensionZone.addTab({id:i,label:r,closable:!1,element:a,onActivate:l}),this.tabContainers.set(i,a)):!t&&this.extensionZone.hasTab(i)&&(this.extensionZone.removeTab(i),this.tabContainers.delete(i));kit(t?[]:["terminal","memory"])}buildHeader(t){const n=document.createElement("div");n.className="header";const i=()=>{if(j2())return;const d=xM();for(const p of d)if(p.models.length>0){CM(`${p.providerId}:${p.models[0].id}`);return}};i(),this.refreshModels=()=>{i(),this.panels?.chat?.refreshModelSelector(),this.refreshAvatar()};const r=document.createElement("div");r.className="header__row";const a=document.createElement("div");a.className="header__brand";const l=this.isExtension?24:28,c=this.sliccLogo(l);a.appendChild(c);const o=document.createElement("div");o.className="header__title",o.textContent="slicc",a.appendChild(o),r.appendChild(a),this.isExtension&&(this.scoopSwitcherEl=document.createElement("div"),this.scoopSwitcherEl.className="scoop-switcher",this.scoopSwitcher=new Tit(this.scoopSwitcherEl,{onScoopSelect:u=>this.onScoopSelect?.(u),onCreateScoop:u=>{this.panels?.scoops?.createScoop(u)},onDeleteScoop:u=>{this.panels?.scoops?.deleteScoop?.(u)}}),r.appendChild(this.scoopSwitcherEl));const s=document.createElement("div");s.className="header__spacer",r.appendChild(s),this.avatarEl=this.buildUserAvatar(),r.appendChild(this.avatarEl),n.appendChild(r),t.appendChild(n)}static SCOOP_COLORS=["#f000a0","#00f0f0","#90f000","#15d675","#e68619"];sliccLogo(t=22){const n=document.createElement("img");return n.width=t,n.height=t,n.src="/logos/sliccy-color-0scoops-128x128.png",n.alt="slicc",n.classList.add("header__logo"),n.style.objectFit="contain",this.logoImg=n,n}static SCOOP_R=5;static SCOOP_SPACING=8.5;static ROW_STEP=7.5;pyramidLayout(t){if(t===0)return[];const{SCOOP_SPACING:n,ROW_STEP:i}=Q_;let r=1;for(;r*(r+1)/2<t;)r++;const a=[];let l=t,c=r;for(;l>0;){const p=Math.min(l,c);a.push(p),l-=p,c--}const o=16,s=19,u=[];let d=s-Q_.SCOOP_R;for(const p of a){const f=(p-1)*n,h=o-f/2;for(let m=0;m<p;m++)u.push({cx:h+m*n,cy:d});d-=i}return u}updateLogoScoops(t){const n=t.filter(a=>!a.isCone),i=this.logoScoopCount;if(i===n.length&&i>=0)return;this.logoScoopCount=n.length;const r=Math.min(Math.max(n.length,0),10);this.logoImg&&(this.logoImg.src=`/logos/sliccy-color-${r}scoops-128x128.png`),this.updateFaviconForScoops(n.length)}updateFaviconForScoops(t){const n=Math.min(Math.max(t,0),10),i=document.querySelector('link[rel="icon"]');i&&(i.href=`/logos/sliccy-color-${n}scoops-32x32.png`);const r=typeof chrome<"u"?chrome:null;r?.action?.setIcon&&r.action.setIcon({path:{16:`logos/sliccy-color-${n}scoops-16x16.png`,32:`logos/sliccy-color-${n}scoops-32x32.png`,48:`logos/sliccy-color-${n}scoops-48x48.png`,128:`logos/sliccy-color-${n}scoops-128x128.png`}}).catch(()=>{})}getInitials(t){const n=t.trim().split(/\s+/);return n.length>=2?(n[0][0]+n[n.length-1][0]).toUpperCase():t.slice(0,2).toUpperCase()}buildUserAvatar(){const t=document.createElement("div");t.className="header__avatar",t.setAttribute("aria-label","Account"),t.dataset.tooltip="Account";const i=ni().find(r=>r.userName||r.userAvatar);if(i?.userAvatar){const r=document.createElement("img");r.src=i.userAvatar,r.alt=i.userName??"User",r.addEventListener("error",()=>{t.removeChild(r),i.userName&&(t.classList.add("header__avatar--initials"),t.textContent=this.getInitials(i.userName))}),t.appendChild(r)}else i?.userName?(t.classList.add("header__avatar--initials"),t.textContent=this.getInitials(i.userName)):(t.classList.add("header__avatar--placeholder"),t.innerHTML='<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M10 10c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v1c0 .55.45 1 1 1h14c.55 0 1-.45 1-1v-1c0-2.66-5.33-4-8-4z"/></svg>');return t.addEventListener("click",()=>this.showAvatarPopover()),t}refreshAvatar(){if(!this.avatarEl)return;const t=this.avatarEl.parentElement;if(!t)return;const n=this.buildUserAvatar();t.replaceChild(n,this.avatarEl),this.avatarEl=n}showAvatarPopover(){const t=document.querySelector(".avatar-popover");if(t){t.remove();return}const n=document.createElement("div");n.className="avatar-popover";const i=ni(),r=i.find(d=>d.userName||d.accessToken||d.apiKey);if(r){const d=document.createElement("div");d.className="avatar-popover__user";const p=document.createElement("div");p.className="avatar-popover__name",p.textContent=r.userName||"Logged in",d.appendChild(p);const f=document.createElement("div");f.className="avatar-popover__provider",f.textContent=ga(r.providerId).name,d.appendChild(f),n.appendChild(d);const h=document.createElement("button");h.className="avatar-popover__item",h.textContent="Sign out",h.addEventListener("click",()=>{b3(r.providerId),n.remove(),this.refreshAvatar(),this.refreshModels?.()}),n.appendChild(h)}if(i.length>0){const d=document.createElement("div");d.className="avatar-popover__separator",n.appendChild(d);const p=document.createElement("button");p.className="avatar-popover__item avatar-popover__item--danger",p.textContent="Clear all accounts",p.addEventListener("click",()=>{WO(),n.remove(),this.refreshAvatar(),this.refreshModels?.()}),n.appendChild(p)}const a=document.createElement("div");a.className="avatar-popover__separator",n.appendChild(a);const l=document.createElement("button");l.className="avatar-popover__item avatar-popover__item--danger",l.textContent="Clear chat",l.addEventListener("click",async()=>{n.remove(),await this.panels?.chat?.clearSession(),await this.onClearChat?.(),location.reload()}),n.appendChild(l);const c=document.createElement("div");c.className="avatar-popover__separator",n.appendChild(c);const o=document.createElement("button");o.className="avatar-popover__item",o.textContent="Account settings…",o.addEventListener("click",async()=>{n.remove(),Nb()||WO(),await TM()&&(this.refreshAvatar(),this.refreshModels?.())}),n.appendChild(o),document.body.appendChild(n);const s=this.avatarEl.getBoundingClientRect();n.style.top=`${s.bottom+4}px`,n.style.right=`${window.innerWidth-s.right}px`;const u=d=>{if(d instanceof KeyboardEvent){if(d.key!=="Escape")return}else if(n.contains(d.target)||this.avatarEl.contains(d.target))return;n.remove(),document.removeEventListener("mousedown",u),document.removeEventListener("keydown",u)};requestAnimationFrame(()=>{document.addEventListener("mousedown",u),document.addEventListener("keydown",u)})}extensionZone;buildTabbedLayout(){for(;this.root.firstChild;)this.root.removeChild(this.root.firstChild);this.buildHeader(this.root);const t=document.createElement("div");t.className="tab-bar",this.root.appendChild(t);const n=document.createElement("div");n.className="tab-content",this.root.appendChild(n),this.extensionZone=new QX(t,n,"primary",{onTabActivate:c=>{this.activeTab=c,c==="terminal"&&this.panels?.terminal?.refit?.(),c==="memory"&&this.panels?.memory?.refresh()},onTabClose:c=>{const o=c.startsWith("sprinkle-")?c.slice(9):c;this.onSprinkleClose?.(o)},onAddClick:()=>this.showExtensionPicker(t)},{classPrefix:"tab-bar"});const i=document.createElement("div");i.className="tab-content__panel";const r=document.createElement("div");r.className="tab-content__panel";const a=document.createElement("div");a.className="tab-content__panel";const l=document.createElement("div");l.className="tab-content__panel";for(const{id:c,label:o}of Ait){const s=c==="chat"?i:c==="terminal"?r:c==="files"?a:l;this.extensionZone.addTab({id:c,label:o,closable:!1,element:s,onActivate:c==="terminal"?()=>this.panels?.terminal?.refit?.():c==="memory"?()=>this.panels?.memory?.refresh():void 0}),this.tabContainers.set(c,s)}this.debugTabContainers={terminal:r,memory:l},this.extensionZone.enableAddButton(),this.iframeContainer=document.createElement("div"),this.iframeContainer.id="scoop-iframes",this.iframeContainer.style.display="none",this.root.appendChild(this.iframeContainer),this.scoopsEl=document.createElement("div"),this.scoopsEl.style.display="none",this.root.appendChild(this.scoopsEl),this.panels={chat:new LX(i),terminal:new UX(r,{onClearTerminal:()=>{this.panels.terminal.clearTerminal()}}),fileBrowser:new HX(a,{onRunCommand:async c=>{await this.runFileBrowserCommand(c),this.extensionZone.activateTab("terminal")},onClearFilesystem:()=>this.onClearFilesystem?.()}),memory:new VX(l),scoops:new KX(this.scoopsEl,{onScoopSelect:c=>this.onScoopSelect?.(c),onSendMessage:()=>{},onScoopsChanged:c=>this.updateLogoScoops(c)})},this.panels.chat.onModelChange=c=>this.onModelChange?.(c)}showExtensionPicker(t){const n=this.getAvailableSprinkles?.()??[],i=new Set(this.extensionZone.getTabIds()),r=n.filter(a=>!i.has(`sprinkle-${a.name}`));r.length!==0&&YX(t,"primary",{registry:this.registry,callbacks:{onSelectPanel:()=>{},onSelectSprinkle:a=>{this.onOpenSprinkle?.(a)}},getAvailableSprinkles:()=>r})}switchTab(t){this.extensionZone&&this.extensionZone.activateTab(t)}buildSplitLayout(){for(;this.root.firstChild;)this.root.removeChild(this.root.firstChild);this.buildHeader(this.root);const t=document.createElement("div");t.className="layout",this.scoopsEl=document.createElement("div"),this.scoopsEl.className="layout__scoops",t.appendChild(this.scoopsEl),this.leftEl=document.createElement("div"),this.leftEl.className="layout__left",this.threadHeaderEl=document.createElement("div"),this.threadHeaderEl.className="thread-header";const n=document.createElement("div");n.className="thread-header__title";const i=document.createElement("span");i.className="thread-header__icon",i.innerHTML='<svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 4h14a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H7l-4 3V5a1 1 0 0 1 1-1z"/><path d="M7 8h6"/><path d="M7 11h3"/></svg>',n.appendChild(i),this.threadHeaderName=document.createElement("span"),this.threadHeaderName.className="thread-header__name",this.threadHeaderName.textContent="sliccy",n.appendChild(this.threadHeaderName),this.threadHeaderEl.appendChild(n);const r=document.createElement("button");r.className="thread-header__panel-toggle thread-header__panel-toggle--right",r.dataset.tooltip="Toggle panel",r.setAttribute("aria-label","Toggle panel"),r.innerHTML='<svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3h14a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/><path d="M12 3v14"/></svg>',r.addEventListener("click",()=>{this.rightEl.classList.toggle("layout__right--open")});const a=document.createElement("button");a.className="thread-header__panel-toggle",a.dataset.tooltip="Clear Chat",a.setAttribute("aria-label","Clear Chat"),a.innerHTML='<svg width="16" height="16" viewBox="0 0 20 20" fill="none"><path d="m8.249,15.021c-.4,0-.733-.317-.748-.72l-.25-6.5c-.017-.414.307-.763.72-.778.01-.001.021-.001.03-.001.4,0,.733.317.748.72l.25,6.5c.017.414-.307.763-.72.778-.01.001-.021.001-.03.001Z" fill="currentColor"/><path d="m11.751,15.021c-.01,0-.02,0-.03-.001-.413-.016-.736-.364-.72-.778l.25-6.5c.015-.403.348-.72.748-.72.01,0,.02,0,.03.001.413.016.736.364.72.778l-.25,6.5c-.015.403-.348.72-.748.72Z" fill="currentColor"/><path d="m17,4h-3.5v-.75c0-1.24-1.01-2.25-2.25-2.25h-2.5c-1.24,0-2.25,1.01-2.25,2.25v.75h-3.5c-.414,0-.75.336-.75.75s.336.75.75.75h.52l.422,10.342c.048,1.21,1.036,2.158,2.248,2.158h7.619c1.212,0,2.2-.948,2.248-2.158l.422-10.342h.52c.414,0,.75-.336.75-.75s-.336-.75-.75-.75Zm-9-.75c0-.413.337-.75.75-.75h2.5c.413,0,.75.337.75.75v.75h-4v-.75Zm6.56,12.531c-.017.403-.346.719-.75.719h-7.619c-.404,0-.733-.316-.75-.719l-.42-10.281h9.959l-.42,10.281Z" fill="currentColor"/></svg>',a.addEventListener("click",async()=>{await this.panels.chat.clearSession(),await this.onClearChat?.(),location.reload()});const l=document.createElement("div");l.className="thread-header__actions",l.appendChild(a),l.appendChild(r),this.threadHeaderEl.appendChild(l),this.leftEl.appendChild(this.threadHeaderEl);const c=document.createElement("div");c.style.cssText="display: flex; flex-direction: column; flex: 1; min-height: 0;",this.leftEl.appendChild(c),t.appendChild(this.leftEl),this.verticalDivider=document.createElement("div"),this.verticalDivider.className="layout__divider layout__divider--vertical",t.appendChild(this.verticalDivider),this.rightEl=document.createElement("div"),this.rightEl.className="layout__right",this.primaryZoneEl=document.createElement("div"),this.primaryZoneEl.style.cssText="display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;";const o=document.createElement("div");o.className="mini-tabs";const s=document.createElement("button");s.className="thread-header__panel-toggle thread-header__panel-toggle--right",s.dataset.tooltip="Close panel",s.setAttribute("aria-label","Close panel"),s.innerHTML='<svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v14"/><path d="M3 3h14a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/></svg>',s.addEventListener("click",()=>{this.rightEl.classList.remove("layout__right--open")}),o.appendChild(s),this.primaryZoneEl.appendChild(o);const u=document.createElement("div");u.style.cssText="flex: 1; min-height: 0; display: flex; flex-direction: column; overflow: hidden;",this.primaryZoneEl.appendChild(u),this.primaryZone=new QX(o,u,"primary",{onTabActivate:y=>{y==="terminal"&&this.panels?.terminal?.refit(),y==="memory"&&this.panels?.memory?.refresh()},onTabClose:y=>{const v=y.startsWith("sprinkle-")?y.slice(9):y;this.onSprinkleClose?.(v)},onAddClick:()=>this.showPickerForZone("primary",o),onFullpageToggle:y=>{this.leftEl.classList.toggle("layout__left--fullpage-hidden",y),this.verticalDivider.classList.toggle("layout__divider--fullpage-hidden",y),this.scoopsEl.classList.toggle("layout__scoops--fullpage-hidden",y),this.rightEl.classList.toggle("layout__right--fullpage",y)}}),this.terminalContainer=document.createElement("div"),this.terminalContainer.style.cssText="display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;";const d=document.createElement("div");d.style.cssText="display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;";const p=document.createElement("div");p.style.cssText="display: flex; flex-direction: column; min-height: 0; flex: 1;";const f=y=>`<svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">${y}</svg>`,h='<path d="M5.5 14.5C5.30762 14.5 5.11621 14.4268 4.96973 14.2803L1.21973 10.5303C0.92676 10.2373 0.92676 9.76269 1.21973 9.46972L4.96973 5.71972C5.2627 5.42675 5.73731 5.42675 6.03028 5.71972C6.32325 6.01269 6.32325 6.4873 6.03028 6.78027L2.81055 10L6.03028 13.2197C6.32325 13.5127 6.32325 13.9873 6.03028 14.2803C5.8838 14.4268 5.69238 14.5 5.5 14.5Z" fill="currentColor"/><path d="M14.5 14.5C14.3076 14.5 14.1162 14.4268 13.9697 14.2803C13.6768 13.9873 13.6768 13.5127 13.9697 13.2197L17.1895 9.99999L13.9697 6.78026C13.6768 6.48729 13.6768 6.01268 13.9697 5.71971C14.2627 5.42674 14.7373 5.42674 15.0303 5.71971L18.7803 9.46971C19.0732 9.76268 19.0732 10.2373 18.7803 10.5303L15.0303 14.2803C14.8838 14.4267 14.6924 14.5 14.5 14.5Z" fill="currentColor"/><path d="M8.22852 18C8.16993 18 8.11036 17.9932 8.05176 17.9795C7.64844 17.8818 7.40137 17.4766 7.49805 17.0742L10.998 2.57422C11.0957 2.1709 11.5078 1.92871 11.9033 2.02051C12.3066 2.11817 12.5537 2.52344 12.457 2.92578L8.95703 17.4258C8.87402 17.7695 8.56642 18 8.22852 18Z" fill="currentColor"/>',m='<path d="M18 4.75C18 2.61621 13.9756 1.5 10 1.5C6.02441 1.5 2 2.61621 2 4.75C2 4.81714 2.01538 4.88037 2.02325 4.94556C2.01696 4.98462 2 5.01978 2 5.06055V15C2 17.0615 6.14697 18 10 18C13.853 18 18 17.0615 18 15V5.06055C18 5.01978 17.983 4.98462 17.9767 4.94556C17.9846 4.88037 18 4.81714 18 4.75ZM16.5002 9.99451C16.4084 10.4097 14.2719 11.5 10 11.5C5.72705 11.5 3.59033 10.4092 3.5 10V6.72449C5.02985 7.56665 7.52393 8 10 8C12.4761 8 14.9701 7.56665 16.5001 6.72437L16.5002 9.99451ZM10 3C14.2886 3 16.5 4.22656 16.5 4.75C16.5 5.27344 14.2886 6.5 10 6.5C5.71143 6.5 3.5 5.27344 3.5 4.75C3.5 4.22656 5.71143 3 10 3ZM10 16.5C5.72705 16.5 3.59033 15.4092 3.5 15V11.8464C5.05219 12.6304 7.58337 13 10 13C12.4168 13 14.9482 12.6304 16.5003 11.8463L16.5005 14.9941C16.4097 15.4092 14.273 16.5 10 16.5Z" fill="currentColor"/>',g='<path d="M10.0039 12.5889C9.11573 12.5889 8.25098 12.1289 7.77588 11.3057C7.06787 10.0781 7.48975 8.50489 8.71582 7.79688C9.30908 7.45313 10.001 7.36329 10.665 7.54004C11.3276 7.71777 11.8814 8.14356 12.2241 8.73731C12.5674 9.33106 12.6582 10.0234 12.481 10.6855C12.3032 11.3486 11.8784 11.9024 11.2842 12.2451C10.8809 12.4785 10.4395 12.5889 10.0039 12.5889ZM9.07471 10.5557C9.36914 11.0645 10.0229 11.2392 10.5342 10.9463C10.7812 10.8037 10.958 10.5732 11.0317 10.2978C11.1055 10.0225 11.0679 9.73436 10.9253 9.48729C10.7822 9.24022 10.5522 9.06346 10.2764 8.98924C10.0015 8.916 9.71337 8.95408 9.46581 9.09569C8.95556 9.39061 8.78027 10.0449 9.07471 10.5557Z" fill="currentColor"/><path d="M6.90674 18.3184C6.56738 18.3184 6.22461 18.2334 5.91455 18.0537L5.09473 17.5811C4.20166 17.0674 3.84473 15.9316 4.28369 14.998L4.86377 13.7646C4.59863 13.4014 4.37402 13.0137 4.19189 12.6035L2.83496 12.4912C1.80615 12.4063 1.00049 11.5313 1.00049 10.5L0.99951 9.55371C0.99951 8.52051 1.80469 7.64453 2.83301 7.55957L4.1875 7.44531C4.2793 7.23633 4.37988 7.03613 4.48926 6.8457C4.59912 6.65429 4.72266 6.46679 4.8584 6.28125L4.27783 5.05176C3.83691 4.11914 4.1914 2.9834 5.08496 2.4668L5.90527 1.99317C6.79785 1.47657 7.95898 1.73438 8.54785 2.58301L9.32519 3.70117C9.76904 3.65137 10.2173 3.65332 10.666 3.70117L11.4414 2.58203C12.0303 1.73242 13.1924 1.47265 14.085 1.98828L14.9048 2.46094C15.7988 2.97656 16.1543 4.11231 15.7153 5.04492L15.1352 6.27734C15.4009 6.6416 15.6255 7.02929 15.8071 7.43847L17.164 7.55077C18.1924 7.63573 18.998 8.51073 18.999 9.54198L18.9995 10.4893C19.0005 11.5205 18.1958 12.3965 17.1675 12.4834L15.812 12.5976C15.7207 12.8066 15.6201 13.0059 15.5093 13.1973C15.3999 13.3867 15.2769 13.5752 15.1411 13.7607L15.7217 14.9902C16.1621 15.9219 15.8081 17.0576 14.915 17.5752L14.0942 18.0498C13.2007 18.5684 12.0405 18.3076 11.4517 17.459L10.6743 16.3408C10.2285 16.3897 9.78028 16.3887 9.3335 16.3418L8.55713 17.4619C8.17334 18.0156 7.54541 18.3184 6.90674 18.3184ZM6.9043 3.22461C6.81934 3.22461 6.73389 3.24609 6.65625 3.29102L5.83545 3.76563C5.61279 3.89454 5.52393 4.17774 5.63428 4.41114L6.41309 6.06153C6.53907 6.32813 6.49707 6.64356 6.30567 6.86817C6.10157 7.10743 5.93262 7.34473 5.78907 7.59376C5.64796 7.83985 5.52393 8.11231 5.42091 8.40333C5.32277 8.68165 5.07081 8.87599 4.77687 8.9004L2.95802 9.05372C2.6963 9.07618 2.49952 9.29005 2.49952 9.55274L2.5005 10.499C2.5005 10.7568 2.70167 10.9756 2.959 10.9971L4.77834 11.1475C5.07229 11.1719 5.32473 11.3662 5.42336 11.6445C5.62209 12.2051 5.92043 12.7207 6.31008 13.1768C6.50197 13.4004 6.54446 13.7168 6.41897 13.9834L5.64114 15.6358C5.53176 15.8692 5.62014 16.1533 5.84378 16.2813L6.66409 16.7549C6.88821 16.8848 7.17825 16.8184 7.32425 16.6074L8.36527 15.1055C8.53275 14.8633 8.82425 14.7363 9.11771 14.7959C9.70609 14.9033 10.3023 14.9043 10.8877 14.7949C11.1773 14.7402 11.4727 14.8613 11.6412 15.1045L12.6831 16.6035C12.8296 16.8135 13.1216 16.8799 13.3438 16.751L14.1641 16.2773C14.3902 16.1465 14.4776 15.8682 14.3653 15.6309L13.5864 13.9805C13.4605 13.7139 13.5025 13.3984 13.6939 13.1738C13.898 12.9336 14.0669 12.6973 14.2095 12.4492L14.21 12.4483C14.3526 12.2012 14.4732 11.9365 14.5786 11.6387C14.6773 11.3604 14.9292 11.166 15.2232 11.1416L17.042 10.9893C17.2984 10.9668 17.4995 10.7481 17.4995 10.4902L17.499 9.54298C17.499 9.28126 17.3018 9.06739 17.0401 9.04493L15.2212 8.89454C14.9273 8.87013 14.6748 8.67579 14.5762 8.39747C14.3784 7.8379 14.0796 7.32227 13.689 6.86524C13.4976 6.64063 13.4551 6.3252 13.5806 6.0586L14.3579 4.40626C14.4678 4.17286 14.3789 3.88868 14.1553 3.75978L13.3355 3.28712C13.1108 3.16017 12.8213 3.2256 12.6743 3.43653L11.6348 4.93653C11.4668 5.17969 11.1758 5.30469 10.8819 5.24708C10.2905 5.1377 9.69435 5.1377 9.11183 5.24708C8.81984 5.29884 8.52638 5.1797 8.35841 4.93751L7.31642 3.43849C7.22023 3.30079 7.06348 3.22461 6.9043 3.22461Z" fill="currentColor"/>';this.primaryZone.addTab({id:"terminal",label:"Terminal",closable:!1,element:this.terminalContainer,pinned:!0,icon:f(h),onActivate:()=>this.panels?.terminal?.refit()}),this.primaryZone.addTab({id:"files",label:"Files",closable:!1,element:d,pinned:!0,icon:f(m)}),this.primaryZone.addTab({id:"memory",label:"Memory",closable:!1,element:p,pinned:!0,icon:f(g),onActivate:()=>this.panels?.memory?.refresh()}),this.primaryZone.enableAddButton(),this.primaryZone.enableFullpageButton(),this.rightEl.appendChild(this.primaryZoneEl),t.appendChild(this.rightEl),this.iframeContainer=document.createElement("div"),this.iframeContainer.id="scoop-iframes",this.iframeContainer.style.display="none",t.appendChild(this.iframeContainer),this.root.appendChild(t),this.panels={chat:new LX(c),terminal:new UX(this.terminalContainer,{onClearTerminal:()=>{this.panels.terminal.clearTerminal(),this.openTerminal()}}),fileBrowser:new HX(d,{onRunCommand:y=>{this.runFileBrowserCommand(y)},onClearFilesystem:()=>this.onClearFilesystem?.()}),memory:new VX(p),scoops:new KX(this.scoopsEl,{onScoopSelect:y=>{this.onScoopSelect?.(y),this.threadHeaderName.textContent=y.assistantLabel},onSendMessage:()=>{},onScoopsChanged:y=>this.updateLogoScoops(y)})},this.panels.chat.onModelChange=y=>this.onModelChange?.(y),this.setupVerticalDrag(),window.addEventListener("resize",()=>{})}getIframeContainer(){return this.iframeContainer}async runFileBrowserCommand(t){const n=await this.panels.terminal.runCommand(t);n.exitCode!==0&&n.stderr&&console.warn("[Layout] File browser command failed:",n.stderr.trim())}setupVerticalDrag(){if(!this.verticalDivider)return;let t=!1;const n=r=>{if(!t)return;const a=this.root.querySelector(".layout")?.getBoundingClientRect();if(!a)return;const l=58,c=r.clientX-a.left-l,o=a.width-l,s=Math.max(.3,Math.min(.7,c/o));this.leftEl.style.flex=`${s*100} 0 0`,this.rightEl.style.flex=`${(1-s)*100} 0 0`},i=()=>{t=!1,this.verticalDivider.classList.remove("active"),document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",n),window.removeEventListener("mouseup",i),this.panels?.terminal?.refit()};this.verticalDivider.addEventListener("mousedown",r=>{r.preventDefault(),t=!0,this.verticalDivider.classList.add("active"),document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",n),window.addEventListener("mouseup",i)})}updateAddButtons(){const t=this.registry.getClosed().length,n=this.getAvailableSprinkles?.()??[],i=new Set;for(const l of this.registry.ids())l.startsWith("sprinkle-")&&this.registry.get(l)?.descriptor.zone!==null&&i.add(l.slice(9));const r=n.filter(l=>!i.has(l.name)).length,a=t+r>0;this.primaryZone?.setAddButtonEnabled(a)}showPickerForZone(t,n){const i=new Set;for(const a of this.registry.ids())a.startsWith("sprinkle-")&&this.registry.get(a)?.descriptor.zone!==null&&i.add(a.slice(9));const r=(this.getAvailableSprinkles?.()??[]).filter(a=>!i.has(a.name));YX(n,t,{registry:this.registry,callbacks:{onSelectPanel:(a,l)=>{this.openPanelInZone(a,l)},onSelectSprinkle:(a,l)=>{this.onOpenSprinkle?.(a,l)}},getAvailableSprinkles:()=>r})}openPanelInZone(t,n){const i=this.registry.get(t);if(!i)return;const r=this.primaryZone;this.registry.setZone(t,n),r.addTab({id:i.descriptor.id,label:i.descriptor.label,closable:i.descriptor.closable,element:i.descriptor.element,onActivate:i.descriptor.onActivate}),r.activateTab(t)}dynamicSprinkles=new Map;addSprinkle(t,n,i,r){if(this.isExtension){const a=`sprinkle-${t}`,l=document.createElement("div");l.className="tab-content__panel",l.appendChild(i),this.extensionZone.addTab({id:a,label:n,closable:!0,element:l}),this.tabContainers.set(a,l),this.dynamicSprinkles.set(t,l),this.extensionZone.activateTab(a)}else{const a=r??"primary",l=this.primaryZone,c=`sprinkle-${t}`,o=document.createElement("div");o.style.cssText="display: flex; flex-direction: column; min-height: 0; overflow: auto; flex: 1;",o.appendChild(i),this.registry.register({id:c,label:n,zone:a,closable:!0,element:o,onClose:()=>this.onSprinkleClose?.(t)}),l.addTab({id:c,label:n,closable:!0,element:o}),this.dynamicSprinkles.set(t,o),l.activateTab(c),this.updateAddButtons()}}removeSprinkle(t){if(this.isExtension){const n=`sprinkle-${t}`;this.extensionZone.removeTab(n),this.tabContainers.delete(n),this.dynamicSprinkles.delete(t)}else{const n=`sprinkle-${t}`;this.primaryZone.removeTab(n),this.registry.unregister(n),this.dynamicSprinkles.delete(t),this.updateAddButtons()}}dispose(){for(this.panels.chat.dispose(),this.panels.terminal.dispose(),this.panels.fileBrowser.dispose(),this.panels.memory.dispose();this.root.firstChild;)this.root.removeChild(this.root.firstChild)}}const Pit=300,_w=6;let eb=null,YC=null;function Mit(){return eb||(eb=document.createElement("div"),eb.className="s2-tooltip",document.body.appendChild(eb)),eb}function Nit(e){const t=e.getAttribute("data-tooltip");if(!t)return;const n=Mit();n.textContent=t,n.classList.remove("s2-tooltip--visible"),n.style.left="0",n.style.top="0";const i=e.getBoundingClientRect(),r=n.getBoundingClientRect(),a=e.getAttribute("data-tooltip-pos")||"bottom";let l,c;a==="top"?(l=i.top-r.height-_w,c=i.left+i.width/2-r.width/2):a==="right"?(l=i.top+i.height/2-r.height/2,c=i.right+_w):(l=i.bottom+_w,c=i.left+i.width/2-r.width/2),a==="bottom"&&l+r.height>window.innerHeight-4?l=i.top-r.height-_w:a==="top"&&l<4&&(l=i.bottom+_w),c<4&&(c=4),c+r.width>window.innerWidth-4&&(c=window.innerWidth-r.width-4),n.style.top=`${l}px`,n.style.left=`${c}px`,n.classList.add("s2-tooltip--visible")}function XA(){YC&&(clearTimeout(YC),YC=null),eb?.classList.remove("s2-tooltip--visible")}function $it(){document.addEventListener("pointerenter",e=>{const t=e.target.closest?.("[data-tooltip]");t&&(XA(),YC=setTimeout(()=>Nit(t),Pit))},!0),document.addEventListener("pointerleave",e=>{e.target.closest?.("[data-tooltip]")&&XA()},!0),document.addEventListener("pointerdown",XA,!0)}var QA,tQ;function Dit(){if(tQ)return QA;tQ=1,QA=e;function e(t){var n,i;if(typeof t!="function")throw new Error("expected a function but got "+t);return function(){return n||(n=!0,i=t.apply(this,arguments)),i}}return QA}var YA={},nQ;function jit(){return nQ||(nQ=1,(function(e){function t(y,v){var b;return y instanceof Buffer?b=y:b=Buffer.from(y.buffer,y.byteOffset,y.byteLength),b.toString(v)}var n=function(y){return Buffer.from(y)};function i(y){for(var v=0,b=Math.min(256*256,y.length+1),w=new Uint16Array(b),x=[],C=0;;){var A=v<y.length;if(!A||C>=b-1){var M=w.subarray(0,C),N=M;if(x.push(String.fromCharCode.apply(null,N)),!A)return x.join("");y=y.subarray(v),v=0,C=0}var P=y[v++];if((P&128)===0)w[C++]=P;else if((P&224)===192){var k=y[v++]&63;w[C++]=(P&31)<<6|k}else if((P&240)===224){var k=y[v++]&63,$=y[v++]&63;w[C++]=(P&31)<<12|k<<6|$}else if((P&248)===240){var k=y[v++]&63,$=y[v++]&63,O=y[v++]&63,j=(P&7)<<18|k<<12|$<<6|O;j>65535&&(j-=65536,w[C++]=j>>>10&1023|55296,j=56320|j&1023),w[C++]=j}}}function r(y){for(var v=0,b=y.length,w=0,x=Math.max(32,b+(b>>>1)+7),C=new Uint8Array(x>>>3<<3);v<b;){var A=y.charCodeAt(v++);if(A>=55296&&A<=56319){if(v<b){var M=y.charCodeAt(v);(M&64512)===56320&&(++v,A=((A&1023)<<10)+(M&1023)+65536)}if(A>=55296&&A<=56319)continue}if(w+4>C.length){x+=8,x*=1+v/y.length*2,x=x>>>3<<3;var N=new Uint8Array(x);N.set(C),C=N}if((A&4294967168)===0){C[w++]=A;continue}else if((A&4294965248)===0)C[w++]=A>>>6&31|192;else if((A&4294901760)===0)C[w++]=A>>>12&15|224,C[w++]=A>>>6&63|128;else if((A&4292870144)===0)C[w++]=A>>>18&7|240,C[w++]=A>>>12&63|128,C[w++]=A>>>6&63|128;else continue;C[w++]=A&63|128}return C.slice?C.slice(0,w):C.subarray(0,w)}var a="Failed to ",l=function(y,v,b){if(y)throw new Error("".concat(a).concat(v,": the '").concat(b,"' option is unsupported."))},c=typeof Buffer=="function"&&Buffer.from,o=c?n:r;function s(){this.encoding="utf-8"}s.prototype.encode=function(y,v){return l(v&&v.stream,"encode","stream"),o(y)};function u(y){var v;try{var b=new Blob([y],{type:"text/plain;charset=UTF-8"});v=URL.createObjectURL(b);var w=new XMLHttpRequest;return w.open("GET",v,!1),w.send(),w.responseText}finally{v&&URL.revokeObjectURL(v)}}var d=!c&&typeof Blob=="function"&&typeof URL=="function"&&typeof URL.createObjectURL=="function",p=["utf-8","utf8","unicode-1-1-utf-8"],f=i;c?f=t:d&&(f=function(y){try{return u(y)}catch{return i(y)}});var h="construct 'TextDecoder'",m="".concat(a," ").concat(h,": the ");function g(y,v){l(v&&v.fatal,h,"fatal"),y=y||"utf-8";var b;if(c?b=Buffer.isEncoding(y):b=p.indexOf(y.toLowerCase())!==-1,!b)throw new RangeError("".concat(m," encoding label provided ('").concat(y,"') is invalid."));this.encoding=y,this.fatal=!1,this.ignoreBOM=!1}g.prototype.decode=function(y,v){l(v&&v.stream,"decode","stream");var b;return y instanceof Uint8Array?b=y:y.buffer instanceof ArrayBuffer?b=new Uint8Array(y.buffer):b=new Uint8Array(y),f(b,this.encoding)},e.TextEncoder=e.TextEncoder||s,e.TextDecoder=e.TextDecoder||g})(typeof window<"u"?window:typeof globalThis<"u"?globalThis:YA)),YA}var e9,rQ;function Lit(){return rQ||(rQ=1,jit(),e9={encode:e=>new TextEncoder().encode(e),decode:e=>new TextDecoder().decode(e)}),e9}var t9,iQ;function Uit(){if(iQ)return t9;iQ=1,t9=e;function e(t,n,i){var r;return function(){if(!n)return t.apply(this,arguments);var a=this,l=arguments,c=i&&!r;if(clearTimeout(r),r=setTimeout(function(){if(r=null,!c)return t.apply(a,l)},n),c)return t.apply(this,arguments)}}return t9}var n9,aQ;function AM(){if(aQ)return n9;aQ=1;function e(c){if(c.length===0)return".";let o=i(c);return o=o.reduce(l,[]),n(...o)}function t(...c){let o="";for(let s of c)s.startsWith("/")?o=s:o=e(n(o,s));return o}function n(...c){if(c.length===0)return"";let o=c.join("/");return o=o.replace(/\/{2,}/g,"/"),o}function i(c){if(c.length===0)return[];if(c==="/")return["/"];let o=c.split("/");return o[o.length-1]===""&&o.pop(),c[0]==="/"?o[0]="/":o[0]!=="."&&o.unshift("."),o}function r(c){const o=c.lastIndexOf("/");if(o===-1)throw new Error(`Cannot get dirname of "${c}"`);return o===0?"/":c.slice(0,o)}function a(c){if(c==="/")throw new Error(`Cannot get basename of "${c}"`);const o=c.lastIndexOf("/");return o===-1?c:c.slice(o+1)}function l(c,o){if(c.length===0)return c.push(o),c;if(o===".")return c;if(o===".."){if(c.length===1){if(c[0]==="/")throw new Error("Unable to normalize path - traverses above root directory");if(c[0]===".")return c.push(o),c}return c[c.length-1]===".."?(c.push(".."),c):(c.pop(),c)}return c.push(o),c}return n9={join:n,normalize:e,split:i,basename:a,dirname:r,resolve:t},n9}var r9,sQ;function Pge(){if(sQ)return r9;sQ=1;function e(c){return class extends Error{constructor(...o){super(...o),this.code=c,this.message?this.message=c+": "+this.message:this.message=c}}}const t=e("EEXIST"),n=e("ENOENT"),i=e("ENOTDIR"),r=e("ENOTEMPTY"),a=e("ETIMEDOUT"),l=e("EISDIR");return r9={EEXIST:t,ENOENT:n,ENOTDIR:i,ENOTEMPTY:r,ETIMEDOUT:a,EISDIR:l},r9}var i9,oQ;function Fit(){if(oQ)return i9;oQ=1;const e=AM(),{EEXIST:t,ENOENT:n,ENOTDIR:i,ENOTEMPTY:r,EISDIR:a}=Pge(),l=0;return i9=class{constructor(){}_makeRoot(o=new Map){return o.set(l,{mode:511,type:"dir",size:0,ino:0,mtimeMs:Date.now()}),o}activate(o=null){o===null?this._root=new Map([["/",this._makeRoot()]]):typeof o=="string"?this._root=new Map([["/",this._makeRoot(this.parse(o))]]):this._root=o}get activated(){return!!this._root}deactivate(){this._root=void 0}size(){return this._countInodes(this._root.get("/"))-1}_countInodes(o){let s=1;for(let[u,d]of o)u!==l&&(s+=this._countInodes(d));return s}autoinc(){return this._maxInode(this._root.get("/"))+1}_maxInode(o){let s=o.get(l).ino;for(let[u,d]of o)u!==l&&(s=Math.max(s,this._maxInode(d)));return s}print(o=this._root.get("/")){let s="";const u=(d,p)=>{for(let[f,h]of d){if(f===0)continue;let m=h.get(l),g=m.mode.toString(8);s+=`${" ".repeat(p)}${f} ${g}`,m.type==="file"?s+=` ${m.size} ${m.mtimeMs}
1153
+ `,document.head.appendChild(t)}}const Oge=[{id:"chat",label:"Chat"},{id:"terminal",label:"Terminal"},{id:"files",label:"Files"},{id:"memory",label:"Memory"}],Ige="slicc-hidden-tabs",ZX=["terminal","memory"];function Eit(){try{const e=localStorage.getItem(Ige);return e?new Set(JSON.parse(e)):new Set(ZX)}catch{return new Set(ZX)}}function kit(e){const t=e.filter(n=>n!=="chat");localStorage.setItem(Ige,JSON.stringify(t))}const Ait=Oge.filter(e=>!Eit().has(e.id)),XX="chat",Rit=new Set(Oge.map(e=>e.id));function Oit(e){return Rit.has(e)}class QX{zoneId;tabBar;contentArea;tabs=new Map;activeTabId=null;callbacks;addBtn=null;fullpageBtn=null;isFullpage=!1;separator=null;scrollArea=null;storageKey;classPrefix;constructor(t,n,i,r={},a={}){this.tabBar=t,this.contentArea=n,this.zoneId=i,this.callbacks=r,this.storageKey=`slicc-${i}-tab`,this.classPrefix=a.classPrefix??"mini-tabs"}addTab(t){if(this.tabs.has(t.id))return;const n=document.createElement("button");if(n.dataset.tabId=t.id,t.pinned&&t.icon){n.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--icon ${this.classPrefix}__tab--dimmed`,n.innerHTML=t.icon,n.setAttribute("aria-label",t.label),n.dataset.tooltip=t.label,n.dataset.tooltipPos="top";const i=this.separator||this.findFirstNonPinnedBtn()||this.addBtn;if(i?this.tabBar.insertBefore(n,i):this.tabBar.appendChild(n),!this.separator){this.separator=document.createElement("div"),this.separator.className=`${this.classPrefix}__separator`,this.scrollArea=document.createElement("div"),this.scrollArea.className=`${this.classPrefix}__scroll`;const r=this.addBtn||this.fullpageBtn;r?(this.tabBar.insertBefore(this.separator,r),this.tabBar.insertBefore(this.scrollArea,r)):(this.tabBar.appendChild(this.separator),this.tabBar.appendChild(this.scrollArea))}n.addEventListener("click",()=>{const r=this.tabs.get(t.id);r&&!r.mounted&&this.enablePinnedTab(t.id),this.activateTab(t.id)}),this.tabs.set(t.id,{btn:n,container:t.element,tab:t,mounted:!1})}else{if(n.className=`${this.classPrefix}__tab`,n.appendChild(document.createTextNode(t.label)),t.closable){const r=document.createElement("span");r.className=`${this.classPrefix}__tab-close`,r.title="Close panel",r.textContent="×",r.addEventListener("click",a=>{a.stopPropagation(),this.callbacks.onTabClose?.(t.id)}),n.appendChild(r)}n.addEventListener("click",()=>this.activateTab(t.id)),this.scrollArea?this.scrollArea.appendChild(n):this.addBtn?this.tabBar.insertBefore(n,this.addBtn):this.tabBar.appendChild(n);const i=t.element;i.style.display="none",this.contentArea.appendChild(i),this.tabs.set(t.id,{btn:n,container:i,tab:t,mounted:!0}),(!this.activeTabId||!this.tabs.get(this.activeTabId)?.mounted)&&this.activateTab(t.id)}}removeTab(t){const n=this.tabs.get(t);if(n&&(n.btn.remove(),n.mounted&&n.container.remove(),this.tabs.delete(t),this.activeTabId===t)){const i=Array.from(this.tabs.entries()).find(([,r])=>r.mounted);i?this.activateTab(i[0]):this.activeTabId=null}}enablePinnedTab(t){const n=this.tabs.get(t);!n||n.mounted||(n.mounted=!0,n.btn.classList.remove(`${this.classPrefix}__tab--dimmed`),n.container.style.display="none",this.contentArea.appendChild(n.container))}isPinnedTabEnabled(t){return this.tabs.get(t)?.mounted??!1}activateTab(t){const n=this.tabs.get(t);if(!(!n||!n.mounted)){this.activeTabId=t;for(const[i,{btn:r,container:a,mounted:l}]of this.tabs){const c=i===t;r.classList.toggle(`${this.classPrefix}__tab--active`,c),l&&(a.style.display=c?"flex":"none")}try{localStorage.setItem(this.storageKey,t)}catch{}n.tab.onActivate?.(),this.callbacks.onTabActivate?.(t)}}getActiveTabId(){return this.activeTabId}getTabIds(){return Array.from(this.tabs.keys())}hasTab(t){return this.tabs.has(t)}get tabCount(){return this.tabs.size}enableAddButton(){this.addBtn||(this.addBtn=document.createElement("button"),this.addBtn.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--add`,this.addBtn.textContent="+",this.addBtn.dataset.tooltip="Open panel",this.addBtn.dataset.tooltipPos="top",this.addBtn.setAttribute("aria-label","Open panel"),this.addBtn.addEventListener("click",()=>this.callbacks.onAddClick?.()),this.tabBar.appendChild(this.addBtn))}setAddButtonEnabled(t){this.addBtn&&(this.addBtn.disabled=!t)}enableFullpageButton(){this.fullpageBtn||(this.fullpageBtn=document.createElement("button"),this.fullpageBtn.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--fullpage`,this.fullpageBtn.dataset.tooltip="Full page",this.fullpageBtn.dataset.tooltipPos="top",this.fullpageBtn.setAttribute("aria-label","Toggle full page"),this.fullpageBtn.innerHTML='<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2h4v4"/><path d="M6 14H2v-4"/><path d="M14 2L9.5 6.5"/><path d="M2 14l4.5-4.5"/></svg>',this.fullpageBtn.addEventListener("click",()=>{this.isFullpage=!this.isFullpage,this.fullpageBtn.classList.toggle(`${this.classPrefix}__tab--active`,this.isFullpage),this.fullpageBtn.innerHTML=this.isFullpage?'<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14 6h-4V2"/><path d="M2 10h4v4"/><path d="M10 6l4.5-4.5"/><path d="M6 10L1.5 14.5"/></svg>':'<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2h4v4"/><path d="M6 14H2v-4"/><path d="M14 2L9.5 6.5"/><path d="M2 14l4.5-4.5"/></svg>',this.fullpageBtn.dataset.tooltip=this.isFullpage?"Exit full page":"Full page",this.callbacks.onFullpageToggle?.(this.isFullpage)}),this.tabBar.appendChild(this.fullpageBtn))}restoreActiveTab(){try{const t=localStorage.getItem(this.storageKey);if(t&&this.tabs.has(t)&&this.tabs.get(t).mounted)return this.activateTab(t),t}catch{}return null}findFirstNonPinnedBtn(){for(const[,t]of this.tabs)if(!t.tab.pinned)return t.btn;return null}}class Iit{entries=new Map;listeners=new Set;register(t){this.entries.set(t.id,{descriptor:t}),this.notify()}unregister(t){this.entries.delete(t),this.notify()}get(t){return this.entries.get(t)}getByZone(t){const n=[];for(const i of this.entries.values())i.descriptor.zone===t&&n.push(i.descriptor);return n}getClosed(){const t=[];for(const n of this.entries.values())n.descriptor.zone===null&&t.push(n.descriptor);return t}setZone(t,n){const i=this.entries.get(t);i&&(i.descriptor.zone=n,this.notify())}ids(){return Array.from(this.entries.keys())}has(t){return this.entries.has(t)}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}notify(){for(const t of this.listeners)t()}}function YX(e,t,n){const i=document.querySelector(".sprinkle-picker");if(i){i.remove();return}const{registry:r,callbacks:a,getAvailableSprinkles:l}=n,c=r.getClosed(),o=l?.()??[];if(c.length===0&&o.length===0)return;const s=document.createElement("div");s.className="sprinkle-picker",s.style.cssText="position: absolute; min-width: 160px; max-height: 300px; overflow-y: auto; background: var(--s2-bg-layer-2); border: 1px solid var(--s2-border-default); border-radius: var(--s2-radius-l); padding: 4px 0; box-shadow: var(--s2-shadow-elevated); z-index: 1000;";const u=()=>{s.remove(),document.removeEventListener("pointerdown",p,!0),document.removeEventListener("keydown",f,!0)};for(const h of c){const m=eQ(h.label,()=>{a.onSelectPanel(h.id,t),u()});s.appendChild(m)}if(c.length>0&&o.length>0){const h=document.createElement("div");h.style.cssText="height: 1px; background: var(--s2-border-default); margin: 4px 0;",s.appendChild(h)}for(const h of o){const m=eQ(h.title,()=>{a.onSelectSprinkle(h.name,t),u()});s.appendChild(m)}const d=e.getBoundingClientRect();s.style.top=`${d.bottom+4}px`,s.style.left=`${d.left}px`,document.body.appendChild(s);const p=h=>{s.contains(h.target)||u()},f=h=>{h.key==="Escape"&&u()};requestAnimationFrame(()=>{document.addEventListener("pointerdown",p,!0),document.addEventListener("keydown",f,!0)})}function eQ(e,t){const n=document.createElement("div");return n.className="sprinkle-picker__item",n.style.cssText="padding: 6px 12px; cursor: pointer; font-size: 12px; color: var(--s2-content-default); border-radius: var(--s2-radius-s); margin: 0 4px; transition: background 130ms ease;",n.textContent=e,n.addEventListener("mouseenter",()=>{n.style.background="var(--s2-bg-elevated)"}),n.addEventListener("mouseleave",()=>{n.style.background=""}),n.addEventListener("click",t),n}class Q_{root;isExtension;scoopsEl;leftEl;rightEl;verticalDivider;terminalContainer;iframeContainer;threadHeaderEl;threadHeaderName;primaryZoneEl;primaryZone;get drawerZone(){return this.primaryZone}get drawerZoneEl(){return this.primaryZoneEl}tabContainers=new Map;activeTab="chat";debugTabContainers=null;scoopSwitcher=null;scoopSwitcherEl=null;avatarEl;logoSvg=null;logoImg=null;logoScoopCount=-1;panels;registry=new Iit;onModelChange;refreshModels;onScoopSelect;onClearChat;onClearFilesystem;onSprinkleClose;getAvailableSprinkles;onOpenSprinkle;constructor(t,n=!1){this.root=t,this.isExtension=n,n?this.buildTabbedLayout():this.buildSplitLayout()}setScoopSwitcherOrchestrator(t){this.scoopSwitcher?.setOrchestrator(t)}updateScoopSwitcherStatus(t,n){this.scoopSwitcher?.updateStatus(t,n)}setScoopSwitcherSelected(t){this.scoopSwitcher?.setSelected(t)}refreshScoopSwitcher(){this.scoopSwitcher?.refresh()}setActiveTab(t){this.isExtension&&this.extensionZone?.activateTab(t)}getActiveTab(){return this.activeTab}isTerminalOpen(){return this.isExtension?!0:this.primaryZone.isPinnedTabEnabled("terminal")}setAgentProcessing(t){this.threadHeaderEl?.classList.toggle("thread-header--processing",t)}openTerminal(){if(this.isExtension)return;this.primaryZone.isPinnedTabEnabled("terminal")||this.primaryZone.enablePinnedTab("terminal");const t=this.primaryZone.getActiveTabId();t&&t.startsWith("sprinkle-")||this.primaryZone.activateTab("terminal")}setDebugTabs(t){if(!this.isExtension||!this.debugTabContainers)return;const n=[{id:"terminal",label:"Terminal",container:this.debugTabContainers.terminal,onActivate:()=>this.panels?.terminal?.refit?.()},{id:"memory",label:"Memory",container:this.debugTabContainers.memory,onActivate:()=>this.panels?.memory?.refresh()}];for(const{id:i,label:r,container:a,onActivate:l}of n)t&&!this.extensionZone.hasTab(i)?(this.extensionZone.addTab({id:i,label:r,closable:!1,element:a,onActivate:l}),this.tabContainers.set(i,a)):!t&&this.extensionZone.hasTab(i)&&(this.extensionZone.removeTab(i),this.tabContainers.delete(i));kit(t?[]:["terminal","memory"])}buildHeader(t){const n=document.createElement("div");n.className="header";const i=()=>{if(j2())return;const d=xM();for(const p of d)if(p.models.length>0){CM(`${p.providerId}:${p.models[0].id}`);return}};i(),this.refreshModels=()=>{i(),this.panels?.chat?.refreshModelSelector(),this.refreshAvatar()};const r=document.createElement("div");r.className="header__row";const a=document.createElement("div");a.className="header__brand";const l=this.isExtension?24:28,c=this.sliccLogo(l);a.appendChild(c);const o=document.createElement("div");o.className="header__title",o.textContent="slicc",a.appendChild(o),r.appendChild(a),this.isExtension&&(this.scoopSwitcherEl=document.createElement("div"),this.scoopSwitcherEl.className="scoop-switcher",this.scoopSwitcher=new Tit(this.scoopSwitcherEl,{onScoopSelect:u=>this.onScoopSelect?.(u),onCreateScoop:u=>{this.panels?.scoops?.createScoop(u)},onDeleteScoop:u=>{this.panels?.scoops?.deleteScoop?.(u)}}),r.appendChild(this.scoopSwitcherEl));const s=document.createElement("div");s.className="header__spacer",r.appendChild(s),this.avatarEl=this.buildUserAvatar(),r.appendChild(this.avatarEl),n.appendChild(r),t.appendChild(n)}static SCOOP_COLORS=["#f000a0","#00f0f0","#90f000","#15d675","#e68619"];sliccLogo(t=22){const n=document.createElement("img");return n.width=t,n.height=t,n.src="/logos/sliccy-color-0scoops-128x128.png",n.alt="slicc",n.classList.add("header__logo"),n.style.objectFit="contain",this.logoImg=n,n}static SCOOP_R=5;static SCOOP_SPACING=8.5;static ROW_STEP=7.5;pyramidLayout(t){if(t===0)return[];const{SCOOP_SPACING:n,ROW_STEP:i}=Q_;let r=1;for(;r*(r+1)/2<t;)r++;const a=[];let l=t,c=r;for(;l>0;){const p=Math.min(l,c);a.push(p),l-=p,c--}const o=16,s=19,u=[];let d=s-Q_.SCOOP_R;for(const p of a){const f=(p-1)*n,h=o-f/2;for(let m=0;m<p;m++)u.push({cx:h+m*n,cy:d});d-=i}return u}updateLogoScoops(t){const n=t.filter(a=>!a.isCone),i=this.logoScoopCount;if(i===n.length&&i>=0)return;this.logoScoopCount=n.length;const r=Math.min(Math.max(n.length,0),10);this.logoImg&&(this.logoImg.src=`/logos/sliccy-color-${r}scoops-128x128.png`),this.updateFaviconForScoops(n.length)}updateFaviconForScoops(t){const n=Math.min(Math.max(t,0),10),i=document.querySelector('link[rel="icon"]');i&&(i.href=`/logos/sliccy-color-${n}scoops-32x32.png`);const r=typeof chrome<"u"?chrome:null;r?.action?.setIcon&&r.action.setIcon({path:{16:`logos/sliccy-color-${n}scoops-16x16.png`,32:`logos/sliccy-color-${n}scoops-32x32.png`,48:`logos/sliccy-color-${n}scoops-48x48.png`,128:`logos/sliccy-color-${n}scoops-128x128.png`}}).catch(()=>{})}getInitials(t){const n=t.trim().split(/\s+/);return n.length>=2?(n[0][0]+n[n.length-1][0]).toUpperCase():t.slice(0,2).toUpperCase()}buildUserAvatar(){const t=document.createElement("div");t.className="header__avatar",t.setAttribute("aria-label","Account"),t.dataset.tooltip="Account";const i=ni().find(r=>r.userName||r.userAvatar);if(i?.userAvatar){const r=document.createElement("img");r.src=i.userAvatar,r.alt=i.userName??"User",r.addEventListener("error",()=>{t.removeChild(r),i.userName&&(t.classList.add("header__avatar--initials"),t.textContent=this.getInitials(i.userName))}),t.appendChild(r)}else i?.userName?(t.classList.add("header__avatar--initials"),t.textContent=this.getInitials(i.userName)):(t.classList.add("header__avatar--placeholder"),t.innerHTML='<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M10 10c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v1c0 .55.45 1 1 1h14c.55 0 1-.45 1-1v-1c0-2.66-5.33-4-8-4z"/></svg>');return t.addEventListener("click",()=>this.showAvatarPopover()),t}refreshAvatar(){if(!this.avatarEl)return;const t=this.avatarEl.parentElement;if(!t)return;const n=this.buildUserAvatar();t.replaceChild(n,this.avatarEl),this.avatarEl=n}showAvatarPopover(){const t=document.querySelector(".avatar-popover");if(t){t.remove();return}const n=document.createElement("div");n.className="avatar-popover";const i=ni(),r=i.find(d=>d.userName||d.accessToken||d.apiKey);if(r){const d=document.createElement("div");d.className="avatar-popover__user";const p=document.createElement("div");p.className="avatar-popover__name",p.textContent=r.userName||"Logged in",d.appendChild(p);const f=document.createElement("div");f.className="avatar-popover__provider",f.textContent=ga(r.providerId).name,d.appendChild(f),n.appendChild(d);const h=document.createElement("button");h.className="avatar-popover__item",h.textContent="Sign out",h.addEventListener("click",()=>{b3(r.providerId),n.remove(),this.refreshAvatar(),this.refreshModels?.()}),n.appendChild(h)}if(i.length>0){const d=document.createElement("div");d.className="avatar-popover__separator",n.appendChild(d);const p=document.createElement("button");p.className="avatar-popover__item avatar-popover__item--danger",p.textContent="Clear all accounts",p.addEventListener("click",()=>{WO(),n.remove(),this.refreshAvatar(),this.refreshModels?.()}),n.appendChild(p)}const a=document.createElement("div");a.className="avatar-popover__separator",n.appendChild(a);const l=document.createElement("button");l.className="avatar-popover__item avatar-popover__item--danger",l.textContent="Clear chat",l.addEventListener("click",async()=>{n.remove(),await this.panels?.chat?.clearSession(),await this.onClearChat?.(),location.reload()}),n.appendChild(l);const c=document.createElement("div");c.className="avatar-popover__separator",n.appendChild(c);const o=document.createElement("button");o.className="avatar-popover__item",o.textContent="Account settings…",o.addEventListener("click",async()=>{n.remove(),Nb()||WO(),await TM()&&(this.refreshAvatar(),this.refreshModels?.())}),n.appendChild(o),document.body.appendChild(n);const s=this.avatarEl.getBoundingClientRect();n.style.top=`${s.bottom+4}px`,n.style.right=`${window.innerWidth-s.right}px`;const u=d=>{if(d instanceof KeyboardEvent){if(d.key!=="Escape")return}else if(n.contains(d.target)||this.avatarEl.contains(d.target))return;n.remove(),document.removeEventListener("mousedown",u),document.removeEventListener("keydown",u)};requestAnimationFrame(()=>{document.addEventListener("mousedown",u),document.addEventListener("keydown",u)})}extensionZone;buildTabbedLayout(){for(;this.root.firstChild;)this.root.removeChild(this.root.firstChild);this.buildHeader(this.root);const t=document.createElement("div");t.className="tab-bar",this.root.appendChild(t);const n=document.createElement("div");n.className="tab-content",this.root.appendChild(n),this.extensionZone=new QX(t,n,"primary",{onTabActivate:c=>{this.activeTab=c,c==="terminal"&&this.panels?.terminal?.refit?.(),c==="memory"&&this.panels?.memory?.refresh()},onTabClose:c=>{const o=c.startsWith("sprinkle-")?c.slice(9):c;this.onSprinkleClose?.(o)},onAddClick:()=>this.showExtensionPicker(t)},{classPrefix:"tab-bar"});const i=document.createElement("div");i.className="tab-content__panel";const r=document.createElement("div");r.className="tab-content__panel";const a=document.createElement("div");a.className="tab-content__panel";const l=document.createElement("div");l.className="tab-content__panel";for(const{id:c,label:o}of Ait){const s=c==="chat"?i:c==="terminal"?r:c==="files"?a:l;this.extensionZone.addTab({id:c,label:o,closable:!1,element:s,onActivate:c==="terminal"?()=>this.panels?.terminal?.refit?.():c==="memory"?()=>this.panels?.memory?.refresh():void 0}),this.tabContainers.set(c,s)}this.debugTabContainers={terminal:r,memory:l},this.extensionZone.enableAddButton(),this.iframeContainer=document.createElement("div"),this.iframeContainer.id="scoop-iframes",this.iframeContainer.style.display="none",this.root.appendChild(this.iframeContainer),this.scoopsEl=document.createElement("div"),this.scoopsEl.style.display="none",this.root.appendChild(this.scoopsEl),this.panels={chat:new LX(i),terminal:new UX(r,{onClearTerminal:()=>{this.panels.terminal.clearTerminal()}}),fileBrowser:new HX(a,{onRunCommand:async c=>{await this.runFileBrowserCommand(c),this.extensionZone.activateTab("terminal")},onClearFilesystem:()=>this.onClearFilesystem?.()}),memory:new VX(l),scoops:new KX(this.scoopsEl,{onScoopSelect:c=>this.onScoopSelect?.(c),onSendMessage:()=>{},onScoopsChanged:c=>this.updateLogoScoops(c)})},this.panels.chat.onModelChange=c=>this.onModelChange?.(c)}showExtensionPicker(t){const n=this.getAvailableSprinkles?.()??[],i=new Set(this.extensionZone.getTabIds()),r=n.filter(a=>!i.has(`sprinkle-${a.name}`));r.length!==0&&YX(t,"primary",{registry:this.registry,callbacks:{onSelectPanel:()=>{},onSelectSprinkle:a=>{this.onOpenSprinkle?.(a)}},getAvailableSprinkles:()=>r})}switchTab(t){this.extensionZone&&this.extensionZone.activateTab(t)}buildSplitLayout(){for(;this.root.firstChild;)this.root.removeChild(this.root.firstChild);this.buildHeader(this.root);const t=document.createElement("div");t.className="layout",this.scoopsEl=document.createElement("div"),this.scoopsEl.className="layout__scoops",t.appendChild(this.scoopsEl),this.leftEl=document.createElement("div"),this.leftEl.className="layout__left",this.threadHeaderEl=document.createElement("div"),this.threadHeaderEl.className="thread-header";const n=document.createElement("div");n.className="thread-header__title";const i=document.createElement("span");i.className="thread-header__icon",i.innerHTML='<svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 4h14a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H7l-4 3V5a1 1 0 0 1 1-1z"/><path d="M7 8h6"/><path d="M7 11h3"/></svg>',n.appendChild(i),this.threadHeaderName=document.createElement("span"),this.threadHeaderName.className="thread-header__name",this.threadHeaderName.textContent="sliccy",n.appendChild(this.threadHeaderName),this.threadHeaderEl.appendChild(n);const r=document.createElement("button");r.className="thread-header__panel-toggle thread-header__panel-toggle--right",r.dataset.tooltip="Toggle panel",r.setAttribute("aria-label","Toggle panel"),r.innerHTML='<svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3h14a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/><path d="M12 3v14"/></svg>',r.addEventListener("click",()=>{this.rightEl.classList.toggle("layout__right--open")});const a=document.createElement("button");a.className="thread-header__panel-toggle",a.dataset.tooltip="Clear Chat",a.setAttribute("aria-label","Clear Chat"),a.innerHTML='<svg width="16" height="16" viewBox="0 0 20 20" fill="none"><path d="m8.249,15.021c-.4,0-.733-.317-.748-.72l-.25-6.5c-.017-.414.307-.763.72-.778.01-.001.021-.001.03-.001.4,0,.733.317.748.72l.25,6.5c.017.414-.307.763-.72.778-.01.001-.021.001-.03.001Z" fill="currentColor"/><path d="m11.751,15.021c-.01,0-.02,0-.03-.001-.413-.016-.736-.364-.72-.778l.25-6.5c.015-.403.348-.72.748-.72.01,0,.02,0,.03.001.413.016.736.364.72.778l-.25,6.5c-.015.403-.348.72-.748.72Z" fill="currentColor"/><path d="m17,4h-3.5v-.75c0-1.24-1.01-2.25-2.25-2.25h-2.5c-1.24,0-2.25,1.01-2.25,2.25v.75h-3.5c-.414,0-.75.336-.75.75s.336.75.75.75h.52l.422,10.342c.048,1.21,1.036,2.158,2.248,2.158h7.619c1.212,0,2.2-.948,2.248-2.158l.422-10.342h.52c.414,0,.75-.336.75-.75s-.336-.75-.75-.75Zm-9-.75c0-.413.337-.75.75-.75h2.5c.413,0,.75.337.75.75v.75h-4v-.75Zm6.56,12.531c-.017.403-.346.719-.75.719h-7.619c-.404,0-.733-.316-.75-.719l-.42-10.281h9.959l-.42,10.281Z" fill="currentColor"/></svg>',a.addEventListener("click",async()=>{await this.panels.chat.clearSession(),await this.onClearChat?.(),location.reload()});const l=document.createElement("div");l.className="thread-header__actions",l.appendChild(a),l.appendChild(r),this.threadHeaderEl.appendChild(l),this.leftEl.appendChild(this.threadHeaderEl);const c=document.createElement("div");c.style.cssText="display: flex; flex-direction: column; flex: 1; min-height: 0;",this.leftEl.appendChild(c),t.appendChild(this.leftEl),this.verticalDivider=document.createElement("div"),this.verticalDivider.className="layout__divider layout__divider--vertical",t.appendChild(this.verticalDivider),this.rightEl=document.createElement("div"),this.rightEl.className="layout__right",this.primaryZoneEl=document.createElement("div"),this.primaryZoneEl.style.cssText="display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;";const o=document.createElement("div");o.className="mini-tabs";const s=document.createElement("button");s.className="thread-header__panel-toggle thread-header__panel-toggle--right",s.dataset.tooltip="Close panel",s.setAttribute("aria-label","Close panel"),s.innerHTML='<svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v14"/><path d="M3 3h14a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/></svg>',s.addEventListener("click",()=>{this.rightEl.classList.remove("layout__right--open")}),o.appendChild(s),this.primaryZoneEl.appendChild(o);const u=document.createElement("div");u.style.cssText="flex: 1; min-height: 0; display: flex; flex-direction: column; overflow: hidden;",this.primaryZoneEl.appendChild(u),this.primaryZone=new QX(o,u,"primary",{onTabActivate:y=>{y==="terminal"&&this.panels?.terminal?.refit(),y==="memory"&&this.panels?.memory?.refresh()},onTabClose:y=>{const v=y.startsWith("sprinkle-")?y.slice(9):y;this.onSprinkleClose?.(v)},onAddClick:()=>this.showPickerForZone("primary",o),onFullpageToggle:y=>{this.leftEl.classList.toggle("layout__left--fullpage-hidden",y),this.verticalDivider.classList.toggle("layout__divider--fullpage-hidden",y),this.scoopsEl.classList.toggle("layout__scoops--fullpage-hidden",y),this.rightEl.classList.toggle("layout__right--fullpage",y)}}),this.terminalContainer=document.createElement("div"),this.terminalContainer.style.cssText="display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;";const d=document.createElement("div");d.style.cssText="display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;";const p=document.createElement("div");p.style.cssText="display: flex; flex-direction: column; min-height: 0; flex: 1;";const f=y=>`<svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">${y}</svg>`,h='<path d="M5.5 14.5C5.30762 14.5 5.11621 14.4268 4.96973 14.2803L1.21973 10.5303C0.92676 10.2373 0.92676 9.76269 1.21973 9.46972L4.96973 5.71972C5.2627 5.42675 5.73731 5.42675 6.03028 5.71972C6.32325 6.01269 6.32325 6.4873 6.03028 6.78027L2.81055 10L6.03028 13.2197C6.32325 13.5127 6.32325 13.9873 6.03028 14.2803C5.8838 14.4268 5.69238 14.5 5.5 14.5Z" fill="currentColor"/><path d="M14.5 14.5C14.3076 14.5 14.1162 14.4268 13.9697 14.2803C13.6768 13.9873 13.6768 13.5127 13.9697 13.2197L17.1895 9.99999L13.9697 6.78026C13.6768 6.48729 13.6768 6.01268 13.9697 5.71971C14.2627 5.42674 14.7373 5.42674 15.0303 5.71971L18.7803 9.46971C19.0732 9.76268 19.0732 10.2373 18.7803 10.5303L15.0303 14.2803C14.8838 14.4267 14.6924 14.5 14.5 14.5Z" fill="currentColor"/><path d="M8.22852 18C8.16993 18 8.11036 17.9932 8.05176 17.9795C7.64844 17.8818 7.40137 17.4766 7.49805 17.0742L10.998 2.57422C11.0957 2.1709 11.5078 1.92871 11.9033 2.02051C12.3066 2.11817 12.5537 2.52344 12.457 2.92578L8.95703 17.4258C8.87402 17.7695 8.56642 18 8.22852 18Z" fill="currentColor"/>',m='<path d="M18 4.75C18 2.61621 13.9756 1.5 10 1.5C6.02441 1.5 2 2.61621 2 4.75C2 4.81714 2.01538 4.88037 2.02325 4.94556C2.01696 4.98462 2 5.01978 2 5.06055V15C2 17.0615 6.14697 18 10 18C13.853 18 18 17.0615 18 15V5.06055C18 5.01978 17.983 4.98462 17.9767 4.94556C17.9846 4.88037 18 4.81714 18 4.75ZM16.5002 9.99451C16.4084 10.4097 14.2719 11.5 10 11.5C5.72705 11.5 3.59033 10.4092 3.5 10V6.72449C5.02985 7.56665 7.52393 8 10 8C12.4761 8 14.9701 7.56665 16.5001 6.72437L16.5002 9.99451ZM10 3C14.2886 3 16.5 4.22656 16.5 4.75C16.5 5.27344 14.2886 6.5 10 6.5C5.71143 6.5 3.5 5.27344 3.5 4.75C3.5 4.22656 5.71143 3 10 3ZM10 16.5C5.72705 16.5 3.59033 15.4092 3.5 15V11.8464C5.05219 12.6304 7.58337 13 10 13C12.4168 13 14.9482 12.6304 16.5003 11.8463L16.5005 14.9941C16.4097 15.4092 14.273 16.5 10 16.5Z" fill="currentColor"/>',g='<path d="M10.0039 12.5889C9.11573 12.5889 8.25098 12.1289 7.77588 11.3057C7.06787 10.0781 7.48975 8.50489 8.71582 7.79688C9.30908 7.45313 10.001 7.36329 10.665 7.54004C11.3276 7.71777 11.8814 8.14356 12.2241 8.73731C12.5674 9.33106 12.6582 10.0234 12.481 10.6855C12.3032 11.3486 11.8784 11.9024 11.2842 12.2451C10.8809 12.4785 10.4395 12.5889 10.0039 12.5889ZM9.07471 10.5557C9.36914 11.0645 10.0229 11.2392 10.5342 10.9463C10.7812 10.8037 10.958 10.5732 11.0317 10.2978C11.1055 10.0225 11.0679 9.73436 10.9253 9.48729C10.7822 9.24022 10.5522 9.06346 10.2764 8.98924C10.0015 8.916 9.71337 8.95408 9.46581 9.09569C8.95556 9.39061 8.78027 10.0449 9.07471 10.5557Z" fill="currentColor"/><path d="M6.90674 18.3184C6.56738 18.3184 6.22461 18.2334 5.91455 18.0537L5.09473 17.5811C4.20166 17.0674 3.84473 15.9316 4.28369 14.998L4.86377 13.7646C4.59863 13.4014 4.37402 13.0137 4.19189 12.6035L2.83496 12.4912C1.80615 12.4063 1.00049 11.5313 1.00049 10.5L0.99951 9.55371C0.99951 8.52051 1.80469 7.64453 2.83301 7.55957L4.1875 7.44531C4.2793 7.23633 4.37988 7.03613 4.48926 6.8457C4.59912 6.65429 4.72266 6.46679 4.8584 6.28125L4.27783 5.05176C3.83691 4.11914 4.1914 2.9834 5.08496 2.4668L5.90527 1.99317C6.79785 1.47657 7.95898 1.73438 8.54785 2.58301L9.32519 3.70117C9.76904 3.65137 10.2173 3.65332 10.666 3.70117L11.4414 2.58203C12.0303 1.73242 13.1924 1.47265 14.085 1.98828L14.9048 2.46094C15.7988 2.97656 16.1543 4.11231 15.7153 5.04492L15.1352 6.27734C15.4009 6.6416 15.6255 7.02929 15.8071 7.43847L17.164 7.55077C18.1924 7.63573 18.998 8.51073 18.999 9.54198L18.9995 10.4893C19.0005 11.5205 18.1958 12.3965 17.1675 12.4834L15.812 12.5976C15.7207 12.8066 15.6201 13.0059 15.5093 13.1973C15.3999 13.3867 15.2769 13.5752 15.1411 13.7607L15.7217 14.9902C16.1621 15.9219 15.8081 17.0576 14.915 17.5752L14.0942 18.0498C13.2007 18.5684 12.0405 18.3076 11.4517 17.459L10.6743 16.3408C10.2285 16.3897 9.78028 16.3887 9.3335 16.3418L8.55713 17.4619C8.17334 18.0156 7.54541 18.3184 6.90674 18.3184ZM6.9043 3.22461C6.81934 3.22461 6.73389 3.24609 6.65625 3.29102L5.83545 3.76563C5.61279 3.89454 5.52393 4.17774 5.63428 4.41114L6.41309 6.06153C6.53907 6.32813 6.49707 6.64356 6.30567 6.86817C6.10157 7.10743 5.93262 7.34473 5.78907 7.59376C5.64796 7.83985 5.52393 8.11231 5.42091 8.40333C5.32277 8.68165 5.07081 8.87599 4.77687 8.9004L2.95802 9.05372C2.6963 9.07618 2.49952 9.29005 2.49952 9.55274L2.5005 10.499C2.5005 10.7568 2.70167 10.9756 2.959 10.9971L4.77834 11.1475C5.07229 11.1719 5.32473 11.3662 5.42336 11.6445C5.62209 12.2051 5.92043 12.7207 6.31008 13.1768C6.50197 13.4004 6.54446 13.7168 6.41897 13.9834L5.64114 15.6358C5.53176 15.8692 5.62014 16.1533 5.84378 16.2813L6.66409 16.7549C6.88821 16.8848 7.17825 16.8184 7.32425 16.6074L8.36527 15.1055C8.53275 14.8633 8.82425 14.7363 9.11771 14.7959C9.70609 14.9033 10.3023 14.9043 10.8877 14.7949C11.1773 14.7402 11.4727 14.8613 11.6412 15.1045L12.6831 16.6035C12.8296 16.8135 13.1216 16.8799 13.3438 16.751L14.1641 16.2773C14.3902 16.1465 14.4776 15.8682 14.3653 15.6309L13.5864 13.9805C13.4605 13.7139 13.5025 13.3984 13.6939 13.1738C13.898 12.9336 14.0669 12.6973 14.2095 12.4492L14.21 12.4483C14.3526 12.2012 14.4732 11.9365 14.5786 11.6387C14.6773 11.3604 14.9292 11.166 15.2232 11.1416L17.042 10.9893C17.2984 10.9668 17.4995 10.7481 17.4995 10.4902L17.499 9.54298C17.499 9.28126 17.3018 9.06739 17.0401 9.04493L15.2212 8.89454C14.9273 8.87013 14.6748 8.67579 14.5762 8.39747C14.3784 7.8379 14.0796 7.32227 13.689 6.86524C13.4976 6.64063 13.4551 6.3252 13.5806 6.0586L14.3579 4.40626C14.4678 4.17286 14.3789 3.88868 14.1553 3.75978L13.3355 3.28712C13.1108 3.16017 12.8213 3.2256 12.6743 3.43653L11.6348 4.93653C11.4668 5.17969 11.1758 5.30469 10.8819 5.24708C10.2905 5.1377 9.69435 5.1377 9.11183 5.24708C8.81984 5.29884 8.52638 5.1797 8.35841 4.93751L7.31642 3.43849C7.22023 3.30079 7.06348 3.22461 6.9043 3.22461Z" fill="currentColor"/>';this.primaryZone.addTab({id:"terminal",label:"Terminal",closable:!1,element:this.terminalContainer,pinned:!0,icon:f(h),onActivate:()=>this.panels?.terminal?.refit()}),this.primaryZone.addTab({id:"files",label:"Files",closable:!1,element:d,pinned:!0,icon:f(m)}),this.primaryZone.addTab({id:"memory",label:"Memory",closable:!1,element:p,pinned:!0,icon:f(g),onActivate:()=>this.panels?.memory?.refresh()}),this.primaryZone.enableAddButton(),this.primaryZone.enableFullpageButton(),this.rightEl.appendChild(this.primaryZoneEl),t.appendChild(this.rightEl),this.iframeContainer=document.createElement("div"),this.iframeContainer.id="scoop-iframes",this.iframeContainer.style.display="none",t.appendChild(this.iframeContainer),this.root.appendChild(t),this.panels={chat:new LX(c),terminal:new UX(this.terminalContainer,{onClearTerminal:()=>{this.panels.terminal.clearTerminal(),this.openTerminal()}}),fileBrowser:new HX(d,{onRunCommand:async y=>{await this.runFileBrowserCommand(y),this.openTerminal()},onClearFilesystem:()=>this.onClearFilesystem?.()}),memory:new VX(p),scoops:new KX(this.scoopsEl,{onScoopSelect:y=>{this.onScoopSelect?.(y),this.threadHeaderName.textContent=y.assistantLabel},onSendMessage:()=>{},onScoopsChanged:y=>this.updateLogoScoops(y)})},this.panels.chat.onModelChange=y=>this.onModelChange?.(y),this.setupVerticalDrag(),window.addEventListener("resize",()=>{})}getIframeContainer(){return this.iframeContainer}async runFileBrowserCommand(t){const n=await this.panels.terminal.runCommand(t);n.exitCode!==0&&n.stderr&&console.warn("[Layout] File browser command failed:",n.stderr.trim())}setupVerticalDrag(){if(!this.verticalDivider)return;let t=!1;const n=r=>{if(!t)return;const a=this.root.querySelector(".layout")?.getBoundingClientRect();if(!a)return;const l=58,c=r.clientX-a.left-l,o=a.width-l,s=Math.max(.3,Math.min(.7,c/o));this.leftEl.style.flex=`${s*100} 0 0`,this.rightEl.style.flex=`${(1-s)*100} 0 0`},i=()=>{t=!1,this.verticalDivider.classList.remove("active"),document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",n),window.removeEventListener("mouseup",i),this.panels?.terminal?.refit()};this.verticalDivider.addEventListener("mousedown",r=>{r.preventDefault(),t=!0,this.verticalDivider.classList.add("active"),document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",n),window.addEventListener("mouseup",i)})}updateAddButtons(){const t=this.registry.getClosed().length,n=this.getAvailableSprinkles?.()??[],i=new Set;for(const l of this.registry.ids())l.startsWith("sprinkle-")&&this.registry.get(l)?.descriptor.zone!==null&&i.add(l.slice(9));const r=n.filter(l=>!i.has(l.name)).length,a=t+r>0;this.primaryZone?.setAddButtonEnabled(a)}showPickerForZone(t,n){const i=new Set;for(const a of this.registry.ids())a.startsWith("sprinkle-")&&this.registry.get(a)?.descriptor.zone!==null&&i.add(a.slice(9));const r=(this.getAvailableSprinkles?.()??[]).filter(a=>!i.has(a.name));YX(n,t,{registry:this.registry,callbacks:{onSelectPanel:(a,l)=>{this.openPanelInZone(a,l)},onSelectSprinkle:(a,l)=>{this.onOpenSprinkle?.(a,l)}},getAvailableSprinkles:()=>r})}openPanelInZone(t,n){const i=this.registry.get(t);if(!i)return;const r=this.primaryZone;this.registry.setZone(t,n),r.addTab({id:i.descriptor.id,label:i.descriptor.label,closable:i.descriptor.closable,element:i.descriptor.element,onActivate:i.descriptor.onActivate}),r.activateTab(t)}dynamicSprinkles=new Map;addSprinkle(t,n,i,r){if(this.isExtension){const a=`sprinkle-${t}`,l=document.createElement("div");l.className="tab-content__panel",l.appendChild(i),this.extensionZone.addTab({id:a,label:n,closable:!0,element:l}),this.tabContainers.set(a,l),this.dynamicSprinkles.set(t,l),this.extensionZone.activateTab(a)}else{const a=r??"primary",l=this.primaryZone,c=`sprinkle-${t}`,o=document.createElement("div");o.style.cssText="display: flex; flex-direction: column; min-height: 0; overflow: auto; flex: 1;",o.appendChild(i),this.registry.register({id:c,label:n,zone:a,closable:!0,element:o,onClose:()=>this.onSprinkleClose?.(t)}),l.addTab({id:c,label:n,closable:!0,element:o}),this.dynamicSprinkles.set(t,o),l.activateTab(c),this.updateAddButtons()}}removeSprinkle(t){if(this.isExtension){const n=`sprinkle-${t}`;this.extensionZone.removeTab(n),this.tabContainers.delete(n),this.dynamicSprinkles.delete(t)}else{const n=`sprinkle-${t}`;this.primaryZone.removeTab(n),this.registry.unregister(n),this.dynamicSprinkles.delete(t),this.updateAddButtons()}}dispose(){for(this.panels.chat.dispose(),this.panels.terminal.dispose(),this.panels.fileBrowser.dispose(),this.panels.memory.dispose();this.root.firstChild;)this.root.removeChild(this.root.firstChild)}}const Pit=300,_w=6;let eb=null,YC=null;function Mit(){return eb||(eb=document.createElement("div"),eb.className="s2-tooltip",document.body.appendChild(eb)),eb}function Nit(e){const t=e.getAttribute("data-tooltip");if(!t)return;const n=Mit();n.textContent=t,n.classList.remove("s2-tooltip--visible"),n.style.left="0",n.style.top="0";const i=e.getBoundingClientRect(),r=n.getBoundingClientRect(),a=e.getAttribute("data-tooltip-pos")||"bottom";let l,c;a==="top"?(l=i.top-r.height-_w,c=i.left+i.width/2-r.width/2):a==="right"?(l=i.top+i.height/2-r.height/2,c=i.right+_w):(l=i.bottom+_w,c=i.left+i.width/2-r.width/2),a==="bottom"&&l+r.height>window.innerHeight-4?l=i.top-r.height-_w:a==="top"&&l<4&&(l=i.bottom+_w),c<4&&(c=4),c+r.width>window.innerWidth-4&&(c=window.innerWidth-r.width-4),n.style.top=`${l}px`,n.style.left=`${c}px`,n.classList.add("s2-tooltip--visible")}function XA(){YC&&(clearTimeout(YC),YC=null),eb?.classList.remove("s2-tooltip--visible")}function $it(){document.addEventListener("pointerenter",e=>{const t=e.target.closest?.("[data-tooltip]");t&&(XA(),YC=setTimeout(()=>Nit(t),Pit))},!0),document.addEventListener("pointerleave",e=>{e.target.closest?.("[data-tooltip]")&&XA()},!0),document.addEventListener("pointerdown",XA,!0)}var QA,tQ;function Dit(){if(tQ)return QA;tQ=1,QA=e;function e(t){var n,i;if(typeof t!="function")throw new Error("expected a function but got "+t);return function(){return n||(n=!0,i=t.apply(this,arguments)),i}}return QA}var YA={},nQ;function jit(){return nQ||(nQ=1,(function(e){function t(y,v){var b;return y instanceof Buffer?b=y:b=Buffer.from(y.buffer,y.byteOffset,y.byteLength),b.toString(v)}var n=function(y){return Buffer.from(y)};function i(y){for(var v=0,b=Math.min(256*256,y.length+1),w=new Uint16Array(b),x=[],C=0;;){var A=v<y.length;if(!A||C>=b-1){var M=w.subarray(0,C),N=M;if(x.push(String.fromCharCode.apply(null,N)),!A)return x.join("");y=y.subarray(v),v=0,C=0}var P=y[v++];if((P&128)===0)w[C++]=P;else if((P&224)===192){var k=y[v++]&63;w[C++]=(P&31)<<6|k}else if((P&240)===224){var k=y[v++]&63,$=y[v++]&63;w[C++]=(P&31)<<12|k<<6|$}else if((P&248)===240){var k=y[v++]&63,$=y[v++]&63,O=y[v++]&63,j=(P&7)<<18|k<<12|$<<6|O;j>65535&&(j-=65536,w[C++]=j>>>10&1023|55296,j=56320|j&1023),w[C++]=j}}}function r(y){for(var v=0,b=y.length,w=0,x=Math.max(32,b+(b>>>1)+7),C=new Uint8Array(x>>>3<<3);v<b;){var A=y.charCodeAt(v++);if(A>=55296&&A<=56319){if(v<b){var M=y.charCodeAt(v);(M&64512)===56320&&(++v,A=((A&1023)<<10)+(M&1023)+65536)}if(A>=55296&&A<=56319)continue}if(w+4>C.length){x+=8,x*=1+v/y.length*2,x=x>>>3<<3;var N=new Uint8Array(x);N.set(C),C=N}if((A&4294967168)===0){C[w++]=A;continue}else if((A&4294965248)===0)C[w++]=A>>>6&31|192;else if((A&4294901760)===0)C[w++]=A>>>12&15|224,C[w++]=A>>>6&63|128;else if((A&4292870144)===0)C[w++]=A>>>18&7|240,C[w++]=A>>>12&63|128,C[w++]=A>>>6&63|128;else continue;C[w++]=A&63|128}return C.slice?C.slice(0,w):C.subarray(0,w)}var a="Failed to ",l=function(y,v,b){if(y)throw new Error("".concat(a).concat(v,": the '").concat(b,"' option is unsupported."))},c=typeof Buffer=="function"&&Buffer.from,o=c?n:r;function s(){this.encoding="utf-8"}s.prototype.encode=function(y,v){return l(v&&v.stream,"encode","stream"),o(y)};function u(y){var v;try{var b=new Blob([y],{type:"text/plain;charset=UTF-8"});v=URL.createObjectURL(b);var w=new XMLHttpRequest;return w.open("GET",v,!1),w.send(),w.responseText}finally{v&&URL.revokeObjectURL(v)}}var d=!c&&typeof Blob=="function"&&typeof URL=="function"&&typeof URL.createObjectURL=="function",p=["utf-8","utf8","unicode-1-1-utf-8"],f=i;c?f=t:d&&(f=function(y){try{return u(y)}catch{return i(y)}});var h="construct 'TextDecoder'",m="".concat(a," ").concat(h,": the ");function g(y,v){l(v&&v.fatal,h,"fatal"),y=y||"utf-8";var b;if(c?b=Buffer.isEncoding(y):b=p.indexOf(y.toLowerCase())!==-1,!b)throw new RangeError("".concat(m," encoding label provided ('").concat(y,"') is invalid."));this.encoding=y,this.fatal=!1,this.ignoreBOM=!1}g.prototype.decode=function(y,v){l(v&&v.stream,"decode","stream");var b;return y instanceof Uint8Array?b=y:y.buffer instanceof ArrayBuffer?b=new Uint8Array(y.buffer):b=new Uint8Array(y),f(b,this.encoding)},e.TextEncoder=e.TextEncoder||s,e.TextDecoder=e.TextDecoder||g})(typeof window<"u"?window:typeof globalThis<"u"?globalThis:YA)),YA}var e9,rQ;function Lit(){return rQ||(rQ=1,jit(),e9={encode:e=>new TextEncoder().encode(e),decode:e=>new TextDecoder().decode(e)}),e9}var t9,iQ;function Uit(){if(iQ)return t9;iQ=1,t9=e;function e(t,n,i){var r;return function(){if(!n)return t.apply(this,arguments);var a=this,l=arguments,c=i&&!r;if(clearTimeout(r),r=setTimeout(function(){if(r=null,!c)return t.apply(a,l)},n),c)return t.apply(this,arguments)}}return t9}var n9,aQ;function AM(){if(aQ)return n9;aQ=1;function e(c){if(c.length===0)return".";let o=i(c);return o=o.reduce(l,[]),n(...o)}function t(...c){let o="";for(let s of c)s.startsWith("/")?o=s:o=e(n(o,s));return o}function n(...c){if(c.length===0)return"";let o=c.join("/");return o=o.replace(/\/{2,}/g,"/"),o}function i(c){if(c.length===0)return[];if(c==="/")return["/"];let o=c.split("/");return o[o.length-1]===""&&o.pop(),c[0]==="/"?o[0]="/":o[0]!=="."&&o.unshift("."),o}function r(c){const o=c.lastIndexOf("/");if(o===-1)throw new Error(`Cannot get dirname of "${c}"`);return o===0?"/":c.slice(0,o)}function a(c){if(c==="/")throw new Error(`Cannot get basename of "${c}"`);const o=c.lastIndexOf("/");return o===-1?c:c.slice(o+1)}function l(c,o){if(c.length===0)return c.push(o),c;if(o===".")return c;if(o===".."){if(c.length===1){if(c[0]==="/")throw new Error("Unable to normalize path - traverses above root directory");if(c[0]===".")return c.push(o),c}return c[c.length-1]===".."?(c.push(".."),c):(c.pop(),c)}return c.push(o),c}return n9={join:n,normalize:e,split:i,basename:a,dirname:r,resolve:t},n9}var r9,sQ;function Pge(){if(sQ)return r9;sQ=1;function e(c){return class extends Error{constructor(...o){super(...o),this.code=c,this.message?this.message=c+": "+this.message:this.message=c}}}const t=e("EEXIST"),n=e("ENOENT"),i=e("ENOTDIR"),r=e("ENOTEMPTY"),a=e("ETIMEDOUT"),l=e("EISDIR");return r9={EEXIST:t,ENOENT:n,ENOTDIR:i,ENOTEMPTY:r,ETIMEDOUT:a,EISDIR:l},r9}var i9,oQ;function Fit(){if(oQ)return i9;oQ=1;const e=AM(),{EEXIST:t,ENOENT:n,ENOTDIR:i,ENOTEMPTY:r,EISDIR:a}=Pge(),l=0;return i9=class{constructor(){}_makeRoot(o=new Map){return o.set(l,{mode:511,type:"dir",size:0,ino:0,mtimeMs:Date.now()}),o}activate(o=null){o===null?this._root=new Map([["/",this._makeRoot()]]):typeof o=="string"?this._root=new Map([["/",this._makeRoot(this.parse(o))]]):this._root=o}get activated(){return!!this._root}deactivate(){this._root=void 0}size(){return this._countInodes(this._root.get("/"))-1}_countInodes(o){let s=1;for(let[u,d]of o)u!==l&&(s+=this._countInodes(d));return s}autoinc(){return this._maxInode(this._root.get("/"))+1}_maxInode(o){let s=o.get(l).ino;for(let[u,d]of o)u!==l&&(s=Math.max(s,this._maxInode(d)));return s}print(o=this._root.get("/")){let s="";const u=(d,p)=>{for(let[f,h]of d){if(f===0)continue;let m=h.get(l),g=m.mode.toString(8);s+=`${" ".repeat(p)}${f} ${g}`,m.type==="file"?s+=` ${m.size} ${m.mtimeMs}
1154
1154
  `:(s+=`
1155
1155
  `,u(h,p+1))}};return u(o,0),s}parse(o){let s=0;function u(h){const m=++s,g=h.length===1?"dir":"file";let[y,v,b]=h;return y=parseInt(y,8),v=v?parseInt(v):0,b=b?parseInt(b):Date.now(),new Map([[l,{mode:y,type:g,size:v,mtimeMs:b,ino:m}]])}let d=o.trim().split(`
1156
1156
  `),p=this._makeRoot(),f=[{indent:-1,node:p},{indent:0,node:null}];for(let h of d){let g=h.match(/^\t*/)[0].length;h=h.slice(g);let[y,...v]=h.split(" "),b=u(v);if(g<=f[f.length-1].indent)for(;g<=f[f.length-1].indent;)f.pop();f.push({indent:g,node:b}),f[f.length-2].node.set(y,b)}return p}_lookup(o,s=!0){let u=this._root,d="/",p=e.split(o);for(let f=0;f<p.length;++f){let h=p[f];if(u=u.get(h),!u)throw new n(o);if(s||f<p.length-1){const m=u.get(l);if(m.type==="symlink"){let g=e.resolve(d,m.target);u=this._lookup(g)}d?d=e.join(d,h):d=h}}return u}mkdir(o,{mode:s}){if(o==="/")throw new t;let u=this._lookup(e.dirname(o)),d=e.basename(o);if(u.has(d))throw new t;let p=new Map,f={mode:s,type:"dir",size:0,mtimeMs:Date.now(),ino:this.autoinc()};p.set(l,f),u.set(d,p)}rmdir(o){let s=this._lookup(o);if(s.get(l).type!=="dir")throw new i;if(s.size>1)throw new r;let u=this._lookup(e.dirname(o)),d=e.basename(o);u.delete(d)}readdir(o){let s=this._lookup(o);if(s.get(l).type!=="dir")throw new i;return[...s.keys()].filter(u=>typeof u=="string")}writeStat(o,s,{mode:u}){let d,p;try{p=this.stat(o)}catch{}if(p!==void 0){if(p.type==="dir")throw new a;u==null&&(u=p.mode),d=p.ino}u==null&&(u=438),d==null&&(d=this.autoinc());let f=this._lookup(e.dirname(o)),h=e.basename(o),m={mode:u,type:"file",size:s,mtimeMs:Date.now(),ino:d},g=new Map;return g.set(l,m),f.set(h,g),m}unlink(o){let s=this._lookup(e.dirname(o)),u=e.basename(o);s.delete(u)}rename(o,s){let u=e.basename(s),d=this._lookup(o);this._lookup(e.dirname(s)).set(u,d),this.unlink(o)}stat(o){return this._lookup(o).get(l)}lstat(o){return this._lookup(o,!1).get(l)}readlink(o){return this._lookup(o,!1).get(l).target}symlink(o,s){let u,d;try{let g=this.stat(s);d===null&&(d=g.mode),u=g.ino}catch{}d==null&&(d=40960),u==null&&(u=this.autoinc());let p=this._lookup(e.dirname(s)),f=e.basename(s),h={mode:d,type:"symlink",target:o,size:0,mtimeMs:Date.now(),ino:u},m=new Map;return m.set(l,h),p.set(f,m),h}_du(o){let s=0;for(const[u,d]of o.entries())u===l?s+=d.size:s+=this._du(d);return s}du(o){let s=this._lookup(o);return this._du(s)}},i9}class Mge{constructor(t="keyval-store",n="keyval"){this.storeName=n,this._dbName=t,this._storeName=n,this._init()}_init(){this._dbp||(this._dbp=new Promise((t,n)=>{const i=indexedDB.open(this._dbName);i.onerror=()=>n(i.error),i.onsuccess=()=>t(i.result),i.onupgradeneeded=()=>{i.result.createObjectStore(this._storeName)}}))}_withIDBStore(t,n){return this._init(),this._dbp.then(i=>new Promise((r,a)=>{const l=i.transaction(this.storeName,t);l.oncomplete=()=>r(),l.onabort=l.onerror=()=>a(l.error),n(l.objectStore(this.storeName))}))}_close(){return this._init(),this._dbp.then(t=>{t.close(),this._dbp=void 0})}}let a9;function dv(){return a9||(a9=new Mge),a9}function qit(e,t=dv()){let n;return t._withIDBStore("readwrite",i=>{n=i.get(e)}).then(()=>n.result)}function Bit(e,t,n=dv()){return n._withIDBStore("readwrite",i=>{i.put(t,e)})}function Wit(e,t,n=dv()){return n._withIDBStore("readwrite",i=>{const r=i.get(e);r.onsuccess=()=>{i.put(t(r.result),e)}})}function zit(e,t=dv()){return t._withIDBStore("readwrite",n=>{n.delete(e)})}function Git(e=dv()){return e._withIDBStore("readwrite",t=>{t.clear()})}function Hit(e=dv()){const t=[];return e._withIDBStore("readwrite",n=>{(n.openKeyCursor||n.openCursor).call(n).onsuccess=function(){this.result&&(t.push(this.result.key),this.result.continue())}}).then(()=>t)}function Vit(e=dv()){return e._close()}const Jit=Object.freeze(Object.defineProperty({__proto__:null,Store:Mge,clear:Git,close:Vit,del:zit,get:qit,keys:Hit,set:Bit,update:Wit},Symbol.toStringTag,{value:"Module"})),Nge=NEe(Jit);var s9,lQ;function Kit(){if(lQ)return s9;lQ=1;const e=Nge;return s9=class{constructor(n,i){this._database=n,this._storename=i,this._store=new e.Store(this._database,this._storename)}saveSuperblock(n){return e.set("!root",n,this._store)}loadSuperblock(){return e.get("!root",this._store)}readFile(n){return e.get(n,this._store)}writeFile(n,i){return e.set(n,i,this._store)}unlink(n){return e.del(n,this._store)}wipe(){return e.clear(this._store)}close(){return e.close(this._store)}},s9}var o9,cQ;function Zit(){return cQ||(cQ=1,o9=class{constructor(t){this._url=t}loadSuperblock(){return fetch(this._url+"/.superblock.txt").then(t=>t.ok?t.text():null)}async readFile(t){const n=await fetch(this._url+t);if(n.status===200)return n.arrayBuffer();throw new Error("ENOENT")}async sizeFile(t){const n=await fetch(this._url+t,{method:"HEAD"});if(n.status===200)return n.headers.get("content-length");throw new Error("ENOENT")}}),o9}var l9,uQ;function Xit(){if(uQ)return l9;uQ=1;const e=Nge,t=n=>new Promise(i=>setTimeout(i,n));return l9=class{constructor(i,r){this._id=Math.random(),this._database=i,this._storename=r,this._store=new e.Store(this._database,this._storename),this._lock=null}async has({margin:i=2e3}={}){if(this._lock&&this._lock.holder===this._id){const r=Date.now();return this._lock.expires>r+i?!0:await this.renew()}else return!1}async renew({ttl:i=5e3}={}){let r;return await e.update("lock",a=>{const c=Date.now()+i;return r=a&&a.holder===this._id,this._lock=r?{holder:this._id,expires:c}:a,this._lock},this._store),r}async acquire({ttl:i=5e3}={}){let r,a,l;if(await e.update("lock",c=>{const o=Date.now(),s=o+i;return a=c&&c.expires<o,r=c===void 0||a,l=c&&c.holder===this._id,this._lock=r?{holder:this._id,expires:s}:c,this._lock},this._store),l)throw new Error("Mutex double-locked");return r}async wait({interval:i=100,limit:r=6e3,ttl:a}={}){for(;r--;){if(await this.acquire({ttl:a}))return!0;await t(i)}throw new Error("Mutex timeout")}async release({force:i=!1}={}){let r,a,l;if(await e.update("lock",c=>(r=i||c&&c.holder===this._id,a=c===void 0,l=c&&c.holder!==this._id,this._lock=r?void 0:c,this._lock),this._store),await e.close(this._store),!r&&!i){if(a)throw new Error("Mutex double-freed");if(l)throw new Error("Mutex lost ownership")}return r}},l9}var c9,dQ;function Qit(){return dQ||(dQ=1,c9=class{constructor(t){this._id=Math.random(),this._database=t,this._has=!1,this._release=null}async has(){return this._has}async acquire(){return new Promise(t=>{navigator.locks.request(this._database+"_lock",{ifAvailable:!0},n=>(this._has=!!n,t(!!n),new Promise(i=>{this._release=i})))})}async wait({timeout:t=6e5}={}){return new Promise((n,i)=>{const r=new AbortController;setTimeout(()=>{r.abort(),i(new Error("Mutex timeout"))},t),navigator.locks.request(this._database+"_lock",{signal:r.signal},a=>(this._has=!!a,n(!!a),new Promise(l=>{this._release=l})))})}async release({force:t=!1}={}){this._has=!1,this._release?this._release():t&&navigator.locks.request(this._database+"_lock",{steal:!0},n=>!0)}}),c9}var u9,pQ;function Yit(){if(pQ)return u9;pQ=1;const{encode:e,decode:t}=Lit(),n=Uit(),i=Fit(),{ENOENT:r,ENOTEMPTY:a,ETIMEDOUT:l}=Pge(),c=Kit(),o=Zit(),s=Xit(),u=Qit(),d=AM();return u9=class{constructor(){this.saveSuperblock=n(()=>{this.flush()},500)}async init(f,{wipe:h,url:m,urlauto:g,fileDbName:y=f,db:v=null,fileStoreName:b=f+"_files",lockDbName:w=f+"_lock",lockStoreName:x=f+"_lock"}={}){this._name=f,this._idb=v||new c(y,b),this._mutex=navigator.locks?new u(f):new s(w,x),this._cache=new i(f),this._opts={wipe:h,url:m},this._needsWipe=!!h,m&&(this._http=new o(m),this._urlauto=!!g)}async activate(){if(this._cache.activated)return;this._needsWipe&&(this._needsWipe=!1,await this._idb.wipe(),await this._mutex.release({force:!0})),await this._mutex.has()||await this._mutex.wait();const f=await this._idb.loadSuperblock();if(f)this._cache.activate(f);else if(this._http){const h=await this._http.loadSuperblock();this._cache.activate(h),await this._saveSuperblock()}else this._cache.activate();if(!await this._mutex.has())throw new l}async deactivate(){await this._mutex.has()&&await this._saveSuperblock(),this._cache.deactivate();try{await this._mutex.release()}catch(f){console.log(f)}await this._idb.close()}async _saveSuperblock(){this._cache.activated&&(this._lastSavedAt=Date.now(),await this._idb.saveSuperblock(this._cache._root))}_writeStat(f,h,m){let g=d.split(d.dirname(f)),y=g.shift();for(let v of g){y=d.join(y,v);try{this._cache.mkdir(y,{mode:511})}catch{}}return this._cache.writeStat(f,h,m)}async readFile(f,h){const m=typeof h=="string"?h:h&&h.encoding;if(m&&m!=="utf8")throw new Error('Only "utf8" encoding is supported in readFile');let g=null,y=null;try{y=this._cache.stat(f),g=await this._idb.readFile(y.ino)}catch(v){if(!this._urlauto)throw v}if(!g&&this._http){let v=this._cache.lstat(f);for(;v.type==="symlink";)f=d.resolve(d.dirname(f),v.target),v=this._cache.lstat(f);g=await this._http.readFile(f)}if(g&&((!y||y.size!=g.byteLength)&&(y=await this._writeStat(f,g.byteLength,{mode:y?y.mode:438}),this.saveSuperblock()),m==="utf8"?g=t(g):g.toString=()=>t(g)),!y)throw new r(f);return g}async writeFile(f,h,m){const{mode:g,encoding:y="utf8"}=m;if(typeof h=="string"){if(y!=="utf8")throw new Error('Only "utf8" encoding is supported in writeFile');h=e(h)}const v=await this._cache.writeStat(f,h.byteLength,{mode:g});await this._idb.writeFile(v.ino,h)}async unlink(f,h){const m=this._cache.lstat(f);this._cache.unlink(f),m.type!=="symlink"&&await this._idb.unlink(m.ino)}readdir(f,h){return this._cache.readdir(f)}mkdir(f,h){const{mode:m=511}=h;this._cache.mkdir(f,{mode:m})}rmdir(f,h){if(f==="/")throw new a;this._cache.rmdir(f)}rename(f,h){this._cache.rename(f,h)}stat(f,h){return this._cache.stat(f)}lstat(f,h){return this._cache.lstat(f)}readlink(f,h){return this._cache.readlink(f)}symlink(f,h){this._cache.symlink(f,h)}async backFile(f,h){let m=await this._http.sizeFile(f);await this._writeStat(f,m,h)}du(f){return this._cache.du(f)}flush(){return this._saveSuperblock()}},u9}var d9,fQ;function eat(){return fQ||(fQ=1,d9=class{constructor(t){this.type=t.type,this.mode=t.mode,this.size=t.size,this.ino=t.ino,this.mtimeMs=t.mtimeMs,this.ctimeMs=t.ctimeMs||t.mtimeMs,this.uid=1,this.gid=1,this.dev=1}isFile(){return this.type==="file"}isDirectory(){return this.type==="dir"}isSymbolicLink(){return this.type==="symlink"}}),d9}var p9,hQ;function tat(){if(hQ)return p9;hQ=1;const e=Yit(),t=eat(),n=AM();function i(l,c,...o){return l=n.normalize(l),(typeof c>"u"||typeof c=="function")&&(c={}),typeof c=="string"&&(c={encoding:c}),[l,c,...o]}function r(l,c,o,...s){return l=n.normalize(l),(typeof o>"u"||typeof o=="function")&&(o={}),typeof o=="string"&&(o={encoding:o}),[l,c,o,...s]}function a(l,c,...o){return[n.normalize(l),n.normalize(c),...o]}return p9=class{constructor(c,o={}){this.init=this.init.bind(this),this.readFile=this._wrap(this.readFile,i,!1),this.writeFile=this._wrap(this.writeFile,r,!0),this.unlink=this._wrap(this.unlink,i,!0),this.readdir=this._wrap(this.readdir,i,!1),this.mkdir=this._wrap(this.mkdir,i,!0),this.rmdir=this._wrap(this.rmdir,i,!0),this.rename=this._wrap(this.rename,a,!0),this.stat=this._wrap(this.stat,i,!1),this.lstat=this._wrap(this.lstat,i,!1),this.readlink=this._wrap(this.readlink,i,!1),this.symlink=this._wrap(this.symlink,a,!0),this.backFile=this._wrap(this.backFile,i,!0),this.du=this._wrap(this.du,i,!1),this._deactivationPromise=null,this._deactivationTimeout=null,this._activationPromise=null,this._operations=new Set,c&&this.init(c,o)}async init(...c){return this._initPromiseResolve&&await this._initPromise,this._initPromise=this._init(...c),this._initPromise}async _init(c,o={}){await this._gracefulShutdown(),this._activationPromise&&await this._deactivate(),this._backend&&this._backend.destroy&&await this._backend.destroy(),this._backend=o.backend||new e,this._backend.init&&await this._backend.init(c,o),this._initPromiseResolve&&(this._initPromiseResolve(),this._initPromiseResolve=null),o.defer||this.stat("/")}async _gracefulShutdown(){this._operations.size>0&&(this._isShuttingDown=!0,await new Promise(c=>this._gracefulShutdownResolve=c),this._isShuttingDown=!1,this._gracefulShutdownResolve=null)}_wrap(c,o,s){return async(...u)=>{u=o(...u);let d={name:c.name,args:u};this._operations.add(d);try{return await this._activate(),await c.apply(this,u)}finally{this._operations.delete(d),s&&this._backend.saveSuperblock(),this._operations.size===0&&(this._deactivationTimeout||clearTimeout(this._deactivationTimeout),this._deactivationTimeout=setTimeout(this._deactivate.bind(this),500))}}}async _activate(){this._initPromise||console.warn(new Error(`Attempted to use LightningFS ${this._name} before it was initialized.`)),await this._initPromise,this._deactivationTimeout&&(clearTimeout(this._deactivationTimeout),this._deactivationTimeout=null),this._deactivationPromise&&await this._deactivationPromise,this._deactivationPromise=null,this._activationPromise||(this._activationPromise=this._backend.activate?this._backend.activate():Promise.resolve()),await this._activationPromise}async _deactivate(){return this._activationPromise&&await this._activationPromise,this._deactivationPromise||(this._deactivationPromise=this._backend.deactivate?this._backend.deactivate():Promise.resolve()),this._activationPromise=null,this._gracefulShutdownResolve&&this._gracefulShutdownResolve(),this._deactivationPromise}async readFile(c,o){return this._backend.readFile(c,o)}async writeFile(c,o,s){return await this._backend.writeFile(c,o,s),null}async unlink(c,o){return await this._backend.unlink(c,o),null}async readdir(c,o){return this._backend.readdir(c,o)}async mkdir(c,o){return await this._backend.mkdir(c,o),null}async rmdir(c,o){return await this._backend.rmdir(c,o),null}async rename(c,o){return await this._backend.rename(c,o),null}async stat(c,o){const s=await this._backend.stat(c,o);return new t(s)}async lstat(c,o){const s=await this._backend.lstat(c,o);return new t(s)}async readlink(c,o){return this._backend.readlink(c,o)}async symlink(c,o){return await this._backend.symlink(c,o),null}async backFile(c,o){return await this._backend.backFile(c,o),null}async du(c){return this._backend.du(c)}async flush(){return this._backend.flush()}},p9}var f9,mQ;function nat(){if(mQ)return f9;mQ=1;const e=Dit(),t=tat();function n(i,r){return typeof i=="function"&&(r=i),r=e(r),[(...l)=>r(null,...l),r]}return f9=class{constructor(...r){this.promises=new t(...r),this.init=this.init.bind(this),this.readFile=this.readFile.bind(this),this.writeFile=this.writeFile.bind(this),this.unlink=this.unlink.bind(this),this.readdir=this.readdir.bind(this),this.mkdir=this.mkdir.bind(this),this.rmdir=this.rmdir.bind(this),this.rename=this.rename.bind(this),this.stat=this.stat.bind(this),this.lstat=this.lstat.bind(this),this.readlink=this.readlink.bind(this),this.symlink=this.symlink.bind(this),this.backFile=this.backFile.bind(this),this.du=this.du.bind(this),this.flush=this.flush.bind(this)}init(r,a){return this.promises.init(r,a)}readFile(r,a,l){const[c,o]=n(a,l);this.promises.readFile(r,a).then(c).catch(o)}writeFile(r,a,l,c){const[o,s]=n(l,c);this.promises.writeFile(r,a,l).then(o).catch(s)}unlink(r,a,l){const[c,o]=n(a,l);this.promises.unlink(r,a).then(c).catch(o)}readdir(r,a,l){const[c,o]=n(a,l);this.promises.readdir(r,a).then(c).catch(o)}mkdir(r,a,l){const[c,o]=n(a,l);this.promises.mkdir(r,a).then(c).catch(o)}rmdir(r,a,l){const[c,o]=n(a,l);this.promises.rmdir(r,a).then(c).catch(o)}rename(r,a,l){const[c,o]=n(l);this.promises.rename(r,a).then(c).catch(o)}stat(r,a,l){const[c,o]=n(a,l);this.promises.stat(r).then(c).catch(o)}lstat(r,a,l){const[c,o]=n(a,l);this.promises.lstat(r).then(c).catch(o)}readlink(r,a,l){const[c,o]=n(a,l);this.promises.readlink(r).then(c).catch(o)}symlink(r,a,l){const[c,o]=n(l);this.promises.symlink(r,a).then(c).catch(o)}backFile(r,a,l){const[c,o]=n(a,l);this.promises.backFile(r,a).then(c).catch(o)}du(r,a){const[l,c]=n(a);this.promises.du(r).then(l).catch(c)}flush(r){const[a,l]=n(r);this.promises.flush().then(a).catch(l)}},f9}var rat=nat();const iat=tE(rat);class Pr extends Error{constructor(t,n,i){super(`${t}: ${n}${i?` '${i}'`:""}`),this.code=t,this.path=i,this.name="FsError"}}function An(e){if(!e||e==="/")return"/";e.startsWith("/")||(e="/"+e);const t=e.split("/"),n=[];for(const i of t)i===""||i==="."||(i===".."?n.pop():n.push(i));return"/"+n.join("/")}function gb(e){const t=An(e);if(t==="/")return{dir:"/",base:""};const n=t.lastIndexOf("/");return{dir:n===0?"/":t.slice(0,n),base:t.slice(n+1)}}function Iy(...e){return An(e.join("/"))}class ya{lfs;_ready;mountPoints=new Map;constructor(t,n){const i=new iat(t,{wipe:n});this.lfs=i.promises,this._ready=this.lfs.stat("/").then(()=>{}).catch(()=>{})}static async create(t){const n=t?.dbName??"browser-fs",i=t?.wipe??!1,r=new ya(n,i);return await r._ready,r}getLightningFS(){return this.lfs}async mount(t,n){const i=An(t),{dir:r}=gb(i);r!=="/"&&await this.mkdir(r,{recursive:!0});try{await this.lfs.mkdir(i)}catch{}this.mountPoints.set(i,n)}unmount(t){this.mountPoints.delete(An(t))}listMounts(){return[...this.mountPoints.keys()]}findMount(t){for(const[n,i]of this.mountPoints){if(t===n)return{handle:i,relParts:[]};if(t.startsWith(n+"/"))return{handle:i,relParts:t.slice(n.length+1).split("/").filter(Boolean)}}return null}static async fsaNavDir(t,n,i=!1){let r=t;for(const a of n)r=await r.getDirectoryHandle(a,{create:i});return r}static async fsaGetFile(t,n,i=!1){return(await ya.fsaNavDir(t,n.slice(0,-1),i)).getFileHandle(n[n.length-1],{create:i})}convertFsaError(t,n){if(t instanceof Pr)return t;if(t instanceof Error){if(t.name==="NotFoundError")return new Pr("ENOENT","no such file or directory",n);if(t.name==="TypeMismatchError")return new Pr("ENOTDIR","not a directory",n);if(t.name==="NotAllowedError")return new Pr("EINVAL","permission denied",n)}return new Pr("EINVAL",t instanceof Error?t.message:String(t),n)}async readFile(t,n){const i=An(t),r=this.findMount(i);if(r){if(r.relParts.length===0)throw new Pr("EISDIR","is a directory",i);try{const l=await(await ya.fsaGetFile(r.handle,r.relParts)).getFile();return(n?.encoding??"utf-8")==="utf-8"?await l.text():new Uint8Array(await l.arrayBuffer())}catch(a){throw this.convertFsaError(a,i)}}try{return(n?.encoding??"utf-8")==="utf-8"?await this.lfs.readFile(i,{encoding:"utf8"}):await this.lfs.readFile(i)}catch(a){throw this.convertError(a,i)}}async writeFile(t,n,i){const r=An(t),a=this.findMount(r);if(a){if(a.relParts.length===0)throw new Pr("EISDIR","is a directory",r);try{const o=await(await ya.fsaGetFile(a.handle,a.relParts,!0)).createWritable(),s=typeof n=="string"?new TextEncoder().encode(n):new Uint8Array(n instanceof Uint8Array?n.buffer:n);await o.write(s),await o.close()}catch(c){throw this.convertFsaError(c,r)}return}const{dir:l}=gb(r);l!=="/"&&await this.mkdir(l,{recursive:!0});try{await this.lfs.writeFile(r,n)}catch(c){throw this.convertError(c,r)}}async readDir(t){const n=An(t),i=this.findMount(n);if(i)try{const r=i.relParts.length===0?i.handle:await ya.fsaNavDir(i.handle,i.relParts),a=[];for await(const[l,c]of r)a.push({name:l,type:c.kind==="directory"?"directory":"file"});return a}catch(r){throw this.convertFsaError(r,n)}try{const r=await this.lfs.readdir(n),a=[];for(const l of r){const c=n==="/"?`/${l}`:`${n}/${l}`;try{const o=await this.lfs.stat(c);a.push({name:l,type:o.isDirectory()?"directory":"file"})}catch{}}return a}catch(r){throw this.convertError(r,n)}}async mkdir(t,n){const i=An(t);if(i==="/")return;const r=this.findMount(i);if(r){if(r.relParts.length===0)return;try{await ya.fsaNavDir(r.handle,r.relParts,!0)}catch(a){throw this.convertFsaError(a,i)}return}if(n?.recursive){const a=i.split("/").filter(Boolean);let l="";for(const c of a){l+="/"+c;try{await this.lfs.mkdir(l)}catch(o){if(o instanceof Error&&!o.message.includes("EEXIST"))throw this.convertError(o,l)}}}else try{await this.lfs.mkdir(i)}catch(a){throw this.convertError(a,i)}}async rm(t,n){const i=An(t),r=this.findMount(i);if(r){if(r.relParts.length===0)throw new Pr("EINVAL","cannot remove a mount point — use unmount",i);try{const a=r.relParts.slice(0,-1),l=r.relParts[r.relParts.length-1];await(a.length===0?r.handle:await ya.fsaNavDir(r.handle,a)).removeEntry(l,{recursive:n?.recursive})}catch(a){throw this.convertFsaError(a,i)}return}try{(await this.lfs.stat(i)).isDirectory()?n?.recursive?await this.rmRecursive(i):await this.lfs.rmdir(i):await this.lfs.unlink(i)}catch(a){throw this.convertError(a,i)}}async rmRecursive(t){const n=await this.lfs.readdir(t);for(const i of n){const r=t==="/"?`/${i}`:`${t}/${i}`;(await this.lfs.stat(r)).isDirectory()?await this.rmRecursive(r):await this.lfs.unlink(r)}await this.lfs.rmdir(t)}async stat(t){const n=An(t),i=this.findMount(n);if(i){if(i.relParts.length===0)try{const r=await this.lfs.stat(n);return{type:"directory",size:r.size,mtime:r.mtimeMs,ctime:r.ctimeMs}}catch{return{type:"directory",size:0,mtime:Date.now(),ctime:Date.now()}}try{try{const a=await(await ya.fsaGetFile(i.handle,i.relParts)).getFile();return{type:"file",size:a.size,mtime:a.lastModified,ctime:a.lastModified}}catch{return await ya.fsaNavDir(i.handle,i.relParts),{type:"directory",size:0,mtime:Date.now(),ctime:Date.now()}}}catch(r){throw this.convertFsaError(r,n)}}try{const r=await this.lfs.stat(n);return{type:r.isDirectory()?"directory":"file",size:r.size,mtime:r.mtimeMs,ctime:r.ctimeMs}}catch(r){throw this.convertError(r,n)}}async exists(t){const n=An(t),i=this.findMount(n);if(i){if(i.relParts.length===0)return!0;try{return await this.stat(n),!0}catch{return!1}}try{return await this.lfs.stat(n),!0}catch{return!1}}async rename(t,n){const i=An(t),r=An(n);try{await this.lfs.rename(i,r)}catch(a){throw this.convertError(a,i)}}async readTextFile(t){return await this.readFile(t,{encoding:"utf-8"})}async*walk(t){const n=An(t),i=await this.readDir(n);for(const r of i){const a=n==="/"?`/${r.name}`:`${n}/${r.name}`;r.type==="file"?yield a:yield*this.walk(a)}}async copyFile(t,n){if((await this.stat(t)).type==="directory")throw new Pr("EISDIR","is a directory",t);const r=await this.readFile(t,{encoding:"binary"});await this.writeFile(n,r)}dirname(t){return gb(An(t)).dir}basename(t){return gb(An(t)).base}convertError(t,n){if(t instanceof Pr)return t;const i=t instanceof Error?t.message:String(t);return i.includes("ENOENT")?new Pr("ENOENT","no such file or directory",n):i.includes("EEXIST")?new Pr("EEXIST","file already exists",n):i.includes("ENOTDIR")?new Pr("ENOTDIR","not a directory",n):i.includes("EISDIR")?new Pr("EISDIR","is a directory",n):i.includes("ENOTEMPTY")?new Pr("ENOTEMPTY","directory not empty",n):new Pr("EINVAL",i,n)}}class $ge{vfs;allowedPrefixes;constructor(t,n){this.vfs=t,this.allowedPrefixes=n.map(i=>{const r=An(i);return r.endsWith("/")?r:r+"/"})}isAllowed(t){const n=An(t);return this.allowedPrefixes.some(i=>n===i.slice(0,-1)||n.startsWith(i)||n==="/"||i.startsWith(n+"/"))}isAllowedStrict(t){const n=An(t);return this.allowedPrefixes.some(i=>n===i.slice(0,-1)||n.startsWith(i))}checkWrite(t){if(!this.isAllowedStrict(t))throw new Pr("EACCES","permission denied",An(t))}getUnderlyingFS(){return this.vfs}getLightningFS(){return this.vfs.getLightningFS()}async readFile(t,n){if(!this.isAllowedStrict(t))throw new Pr("ENOENT","no such file or directory",An(t));return this.vfs.readFile(t,n)}async readDir(t){if(!this.isAllowed(t))return[];const n=await this.vfs.readDir(t);if(!this.isAllowedStrict(t)){const i=An(t);return n.filter(r=>{const a=i==="/"?`/${r.name}`:`${i}/${r.name}`;return this.isAllowed(a)})}return n}async stat(t){if(!this.isAllowed(t))throw new Pr("ENOENT","no such file or directory",An(t));return this.vfs.stat(t)}async exists(t){return this.isAllowed(t)?this.vfs.exists(t):!1}async readTextFile(t){if(!this.isAllowedStrict(t))throw new Pr("ENOENT","no such file or directory",An(t));return this.vfs.readTextFile(t)}async*walk(t){if(this.isAllowed(t))for await(const n of this.vfs.walk(t))this.isAllowed(n)&&(yield n)}async writeFile(t,n,i){return this.checkWrite(t),this.vfs.writeFile(t,n,i)}async mkdir(t,n){return this.checkWrite(t),this.vfs.mkdir(t,n)}async rm(t,n){return this.checkWrite(t),this.vfs.rm(t,n)}async rename(t,n){return this.checkWrite(t),this.checkWrite(n),this.vfs.rename(t,n)}async copyFile(t,n){if(!this.isAllowed(t))throw new Pr("ENOENT","no such file or directory",An(t));return this.checkWrite(n),this.vfs.copyFile(t,n)}dirname(t){return this.vfs.dirname(t)}basename(t){return this.vfs.basename(t)}}const aat=Object.freeze(Object.defineProperty({__proto__:null,FsError:Pr,RestrictedFS:$ge,VirtualFS:ya,joinPath:Iy,normalizePath:An,splitPath:gb},Symbol.toStringTag,{value:"Module"})),Dge=".slicc",sat="state.json",tEt="skills",gm="manifest.yaml",ZO=".skill",oat=50*1024*1024,lat=50*1024*1024,gQ=1e3,RM="/workspace/skills",jge="SKILL.md",Lge="1.0.0";function cat(e){const t={},n=e.split(`
@@ -3409,7 +3409,7 @@ except SystemExit as exc:
3409
3409
  except BaseException:
3410
3410
  traceback.print_exc()
3411
3411
  __slicc_exit_code = 1
3412
- `;let W5=null,z5=null;const Mxe=Object.create(null);class G3 extends Error{constructor(t){super(`Process exited with code ${t}`),this.code=t,this.name="NodeExitError"}}function zN(e){const t=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function a_t(e){const t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function s_t(e,t){return e==="/"?`/${t}`:`${e}/${t}`}function o_t(e){if(/^(https?:\/\/|about:|file:|chrome:)/i.test(e))return!0;try{return new URL(e).protocol.length>0}catch{return!1}}function l_t(e,t){return e==="/"?t.startsWith("/"):t===e||t.startsWith(`${e}/`)}function c_t(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function u_t(e){return e==null?"":e instanceof Uint8Array?`x'${c_t(e)}'`:String(e)}function iP(e){return vM(e)}function H3(e){const t=typeof chrome<"u"&&!!chrome?.runtime?.id,n=`/preview${e}`;return t?chrome.runtime.getURL(n):`${typeof window<"u"&&window.location?.origin?window.location.origin:"http://localhost:5710"}${n}`}function d_t(e){return e.length===0||e.startsWith("/")?!1:!e.split("/").some(t=>t==="..")}function p_t(e,t){return An(`${e}/${t}`)}function ag(e){if(typeof e=="string")return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function Nxe(e,t){const n=import.meta.resolve;if(typeof n=="function")try{return new URL("./",n(e))}catch{}return new URL(t,import.meta.url)}async function f_t(){return W5||(W5=(async()=>{const t=(await fn(()=>import("./sql-wasm-CgIJhlRQ.js").then(i=>i.s),__vite__mapDeps([6,3,4]))).default,n=typeof window>"u"?Nxe("sql.js/dist/sql-wasm.js","../../../../../node_modules/sql.js/dist/").toString():t_t;return t({locateFile:i=>`${n}${i}`})})()),W5}const h_t=typeof chrome<"u"&&!!chrome?.runtime?.id;async function m_t(){return z5||(z5=(async()=>{let e;return typeof window>"u"?e=decodeURIComponent(Nxe("pyodide/pyodide.mjs","../../../../../node_modules/pyodide/").pathname):h_t?e=chrome.runtime.getURL("pyodide/"):e=n_t,Pxe({indexURL:e,fullStdLib:!1})})()),z5}function g_t(){return{stdout:`usage: node -e <code> [args...]
3412
+ `;let W5=null,z5=null;const Mxe=Object.create(null);class G3 extends Error{constructor(t){super(`Process exited with code ${t}`),this.code=t,this.name="NodeExitError"}}function zN(e){const t=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function a_t(e){const t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function s_t(e,t){return e==="/"?`/${t}`:`${e}/${t}`}function o_t(e){if(/^(https?:\/\/|about:|file:|chrome:)/i.test(e))return!0;try{return new URL(e).protocol.length>0}catch{return!1}}function l_t(e,t){return e==="/"?t.startsWith("/"):t===e||t.startsWith(`${e}/`)}function c_t(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function u_t(e){return e==null?"":e instanceof Uint8Array?`x'${c_t(e)}'`:String(e)}function iP(e){return vM(e)}function H3(e){const t=typeof chrome<"u"&&!!chrome?.runtime?.id,n=`/preview${e}`;return t?chrome.runtime.getURL(n):`${typeof window<"u"&&window.location?.origin?window.location.origin:"http://localhost:5710"}${n}`}function d_t(e){return e.length===0||e.startsWith("/")?!1:!e.split("/").some(t=>t==="..")}function p_t(e,t){return An(`${e}/${t}`)}function ag(e){if(typeof e=="string")return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function Nxe(e,t){const n=import.meta.resolve;if(typeof n=="function")try{return new URL("./",n(e))}catch{}return new URL(t,import.meta.url)}async function f_t(){return W5||(W5=(async()=>{const t=(await fn(()=>import("./sql-wasm-r2NFfZ6X.js").then(i=>i.s),__vite__mapDeps([6,3,4]))).default,n=typeof window>"u"?Nxe("sql.js/dist/sql-wasm.js","../../../../../node_modules/sql.js/dist/").toString():t_t;return t({locateFile:i=>`${n}${i}`})})()),W5}const h_t=typeof chrome<"u"&&!!chrome?.runtime?.id;async function m_t(){return z5||(z5=(async()=>{let e;return typeof window>"u"?e=decodeURIComponent(Nxe("pyodide/pyodide.mjs","../../../../../node_modules/pyodide/").pathname):h_t?e=chrome.runtime.getURL("pyodide/"):e=n_t,Pxe({indexURL:e,fullStdLib:!1})})()),z5}function g_t(){return{stdout:`usage: node -e <code> [args...]
3413
3413
  `,stderr:"",exitCode:0}}function y_t(){return{stdout:`${r_t}
3414
3414
  `,stderr:"",exitCode:0}}function v_t(){return cr("node",async(e,t)=>{if(e.includes("--help")||e.includes("-h"))return g_t();if(e.includes("--version")||e.includes("-v"))return y_t();let n="",i="<stdin>",r=["node"];if(e.length>0&&(e[0]==="-e"||e[0]==="--eval")){if(!e[1])return{stdout:"",stderr:`node: option requires an argument -- eval
3415
3415
  `,exitCode:9};n=e[1],i="[eval]",r=["node",...e.slice(2)]}else if(e.length>0&&!e[0].startsWith("-")){const m=e[0],g=t.fs.resolvePath(t.cwd,m);if(!await t.fs.exists(g))return{stdout:"",stderr:`node: cannot find module '${m}'
@@ -3484,7 +3484,7 @@ ${n}`)(d,u,s,f,h,h.exports,Mxe,p),{stdout:a.join(""),stderr:l.join(""),exitCode:
3484
3484
  `,exitCode:1};let s;try{s=await t.fs.readFileBuffer(c)}catch{return{stdout:"",stderr:`open: failed to read: ${l}
3485
3485
  `,exitCode:1}}const u=new Uint8Array(s.byteLength);u.set(s);const d=new Blob([u.buffer],{type:iP(c)}),p=URL.createObjectURL(d),f=document.createElement("a");f.href=p,f.download=zN(c)||"download",f.style.display="none",document.body.appendChild(f),f.click(),document.body.removeChild(f),setTimeout(()=>URL.revokeObjectURL(p),0),a.push(`downloaded ${c}`)}else{const o=H3(c);window.open(o,"_blank","noopener,noreferrer"),a.push(`opened ${c} → ${o}`)}}return{stdout:a.join(`
3486
3486
  `)+`
3487
- `,stderr:"",exitCode:0}})}let G5=null,H5=null;async function V5(){return G5||(G5=fn(()=>import("./index-DzGPKzGT.js"),__vite__mapDeps([7,3,4]))),G5}async function x_t(){return H5||(H5=fn(()=>import("./index-B5Pp2r00.js"),[])),H5}function S_t(e){return e.endsWith("right")?{range:e.slice(0,-5),rotation:90}:e.endsWith("left")?{range:e.slice(0,-4),rotation:270}:e.endsWith("down")?{range:e.slice(0,-4),rotation:180}:{range:e}}function vie(e){const{range:t,rotation:n}=S_t(e);if(/^\d+$/.test(t)){const r=parseInt(t,10);return{start:r,end:r,rotation:n}}const i=t.match(/^(\d+)-(\d+|end)$/);if(i){const r=parseInt(i[1],10),a=i[2]==="end"?"end":parseInt(i[2],10);return{start:r,end:a,rotation:n}}throw new Error(`Invalid page range: ${e}`)}function bie(e,t){const n=e.start,i=e.end;if(n<1||n>t)throw new Error(`Page ${n} out of range (1-${t})`);const r=i==="end"?t:i;if(r<1||r>t)throw new Error(`Page ${r} out of range (1-${t})`);if(r<n)throw new Error(`Invalid range: ${n}-${r}`);const a=[];for(let l=n;l<=r;l++)a.push(l);return a}function C_t(){return{stdout:`usage: pdftk <input.pdf> <operation> [args...]
3487
+ `,stderr:"",exitCode:0}})}let G5=null,H5=null;async function V5(){return G5||(G5=fn(()=>import("./index-B73vno6G.js"),__vite__mapDeps([7,3,4]))),G5}async function x_t(){return H5||(H5=fn(()=>import("./index-DtM-71bP.js"),[])),H5}function S_t(e){return e.endsWith("right")?{range:e.slice(0,-5),rotation:90}:e.endsWith("left")?{range:e.slice(0,-4),rotation:270}:e.endsWith("down")?{range:e.slice(0,-4),rotation:180}:{range:e}}function vie(e){const{range:t,rotation:n}=S_t(e);if(/^\d+$/.test(t)){const r=parseInt(t,10);return{start:r,end:r,rotation:n}}const i=t.match(/^(\d+)-(\d+|end)$/);if(i){const r=parseInt(i[1],10),a=i[2]==="end"?"end":parseInt(i[2],10);return{start:r,end:a,rotation:n}}throw new Error(`Invalid page range: ${e}`)}function bie(e,t){const n=e.start,i=e.end;if(n<1||n>t)throw new Error(`Page ${n} out of range (1-${t})`);const r=i==="end"?t:i;if(r<1||r>t)throw new Error(`Page ${r} out of range (1-${t})`);if(r<n)throw new Error(`Invalid range: ${n}-${r}`);const a=[];for(let l=n;l<=r;l++)a.push(l);return a}function C_t(){return{stdout:`usage: pdftk <input.pdf> <operation> [args...]
3488
3488
 
3489
3489
  Operations:
3490
3490
  dump_data Print metadata (page count, title, author, etc.)
@@ -3975,7 +3975,7 @@ ${h}`,stderr:"",exitCode:0}}catch(a){return{stdout:"",stderr:`upskill: failed to
3975
3975
  `,stderr:"",exitCode:0}}catch(s){return{stdout:"",stderr:`upskill: failed to install from GitHub: ${s instanceof Error?s.message:String(s)}
3976
3976
  `,exitCode:1}}}function q2t(e){const t=e.match(/^https?:\/\/clawhub\.ai\/[^\/]+\/([^\/]+)/);if(t)return t[1];if(e.startsWith("clawhub:")){const n=e.slice(8);return n.includes("/")?n.split("/")[1]:n}return null}function B2t(e){const t=e.match(/^([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_.-]+)(?:@([a-zA-Z0-9_./\-]+))?$/);return t?{owner:t[1],repo:t[2],branch:t[3]}:null}async function u2(){try{if(typeof window>"u")return;const e=window.__slicc_sprinkleManager;e&&typeof e.openNewAutoOpenSprinkles=="function"&&await e.openNewAutoOpenSprinkles()}catch{}}async function W2t(e,t,n){let i=null;try{const s=await e.readDir("/home");for(const u of s)try{const d=await e.readTextFile(`/home/${u.name}/.welcome.json`);i=JSON.parse(d);break}catch{}}catch{}if(!i)return{stdout:"",stderr:`upskill: no user profile found. Complete the welcome onboarding first, or create /home/<name>/.welcome.json manually.
3977
3977
  `,exitCode:1};let r;try{const s=await e.readTextFile("/shared/skill-catalog.json");r=JSON.parse(s)}catch{return{stdout:"",stderr:`upskill: skill catalog not found at /shared/skill-catalog.json
3978
- `,exitCode:1}}const a=new Set;try{const u=await(await fn(()=>import("./index-i3ABK3vk.js"),[])).discoverSkills(e);for(const d of u)a.add(d.name)}catch{}const l=E2t(r.skills,i).filter(s=>!a.has(s.entry.name));if(l.length===0)return{stdout:`No new skill recommendations — all matching skills are already installed.
3978
+ `,exitCode:1}}const a=new Set;try{const u=await(await fn(()=>import("./index-CM2CRGkL.js"),[])).discoverSkills(e);for(const d of u)a.add(d.name)}catch{}const l=E2t(r.skills,i).filter(s=>!a.has(s.entry.name));if(l.length===0)return{stdout:`No new skill recommendations — all matching skills are already installed.
3979
3979
  `,stderr:"",exitCode:0};if(n){let s="",u="",d=0;for(const p of l){const f=p.entry.source,h=await sP(t),[m,g]=f.repo.split("/"),y=await tSe(m,g,h,f.path,t);if(y.error){u+=`upskill: failed to list ${p.entry.name}: ${y.error}
3980
3980
  `;continue}const v=f.skill?y.skills.filter(b=>b.name===f.skill):y.skills;for(const b of v){const w=await oP(m,g,b.path,b.name,e,h,!1,t);w.exitCode===0?(s+=w.stdout,d++):u+=w.stderr}}return d>0&&(s+=`
3981
3981
  Installed ${d} recommended skill(s)
@@ -3987,10 +3987,10 @@ Installed ${d} recommended skill(s)
3987
3987
  `,c+=` Install: ${u}
3988
3988
 
3989
3989
  `}return c+=`To install all recommended: upskill recommendations --install
3990
- `,{stdout:c,stderr:"",exitCode:0}}function z2t(e,t){return cr("upskill",async(n,i)=>{if(n.length===0||n.includes("--help")||n.includes("-h"))return Pie();const r=[];let a,l=!1,c=!1,o=!1,s="",u,d="",p=1,f=0;for(;f<n.length;){const g=n[f];if(g==="search"){const y=n.slice(f+1),v=y.indexOf("--page");v>=0&&(p=parseInt(y[v+1],10)||1,y.splice(v,2)),d=y.join(" ");break}else if(g==="recommendations"){const y=n.includes("--install");return W2t(e,t,y)}else if(g==="list"){const v=await(await fn(()=>import("./index-i3ABK3vk.js"),[])).discoverSkills(e);return v.length===0?{stdout:`No discoverable local skills found.
3990
+ `,{stdout:c,stderr:"",exitCode:0}}function z2t(e,t){return cr("upskill",async(n,i)=>{if(n.length===0||n.includes("--help")||n.includes("-h"))return Pie();const r=[];let a,l=!1,c=!1,o=!1,s="",u,d="",p=1,f=0;for(;f<n.length;){const g=n[f];if(g==="search"){const y=n.slice(f+1),v=y.indexOf("--page");v>=0&&(p=parseInt(y[v+1],10)||1,y.splice(v,2)),d=y.join(" ");break}else if(g==="recommendations"){const y=n.includes("--install");return W2t(e,t,y)}else if(g==="list"){const v=await(await fn(()=>import("./index-CM2CRGkL.js"),[])).discoverSkills(e);return v.length===0?{stdout:`No discoverable local skills found.
3991
3991
 
3992
3992
  ${l2()}${c2()}`,stderr:"",exitCode:0}:{stdout:Xxe(v,"Discoverable local skills"),stderr:"",exitCode:0}}else if(g==="info"||g==="read"){const y=n[f+1];if(!y)return{stdout:"",stderr:`upskill: ${g} requires a skill name
3993
- `,exitCode:1};const v=await fn(()=>import("./index-i3ABK3vk.js"),[]);if(g==="info"){const b=await v.getSkillInfo(e,y);return b?{stdout:Qxe(b),stderr:"",exitCode:0}:{stdout:"",stderr:`upskill: skill "${y}" not found
3993
+ `,exitCode:1};const v=await fn(()=>import("./index-CM2CRGkL.js"),[]);if(g==="info"){const b=await v.getSkillInfo(e,y);return b?{stdout:Qxe(b),stderr:"",exitCode:0}:{stdout:"",stderr:`upskill: skill "${y}" not found
3994
3994
  `,exitCode:1}}else{const b=await v.readSkillInstructions(e,y);return b===null?{stdout:"",stderr:`upskill: no SKILL.md found for "${y}"
3995
3995
  `,exitCode:1}:{stdout:b+`
3996
3996
  `,stderr:"",exitCode:0}}}else if(g==="--skill")r.push(n[++f]);else if(g==="--path"||g==="-p")a=n[++f];else if(g==="--list")l=!0;else if(g==="--all")c=!0;else if(g==="--force")o=!0;else if(g==="--branch"||g==="-b"){const y=n[f+1];if(!y||y.startsWith("-"))return{stdout:"",stderr:`upskill: --branch requires a value
@@ -4041,7 +4041,7 @@ Examples:
4041
4041
  skill list
4042
4042
  skill info bluebubbles
4043
4043
  skill read bluebubbles
4044
- `,stderr:"",exitCode:0};const i=t[0],r=await fn(()=>import("./index-i3ABK3vk.js"),[]);try{switch(i){case"list":{const a=await r.discoverSkills(e);return a.length===0?{stdout:`No discoverable skills found.
4044
+ `,stderr:"",exitCode:0};const i=t[0],r=await fn(()=>import("./index-CM2CRGkL.js"),[]);try{switch(i){case"list":{const a=await r.discoverSkills(e);return a.length===0?{stdout:`No discoverable skills found.
4045
4045
 
4046
4046
  ${l2()}${c2()}
4047
4047
  Install install-managed skills with: upskill owner/repo --all
@@ -14744,7 +14744,7 @@ ${r}`)}let nR=null;function nSt(){return nR||(nR=new uSe),nR}const rSt=Object.fr
14744
14744
  ${n.prompt}`,"scheduler","Scheduled Task")},getScoop:n=>{for(const i of this.scoops.values())if(i.folder===n)return i}}),this.scheduler.start(),Wn.info("Orchestrator initialized",{scoopCount:this.scoops.size});for(const n of this.scoops.values())await this.createScoopTab(n.jid);this.startMessageLoop()}async ensureRootStructure(){if(!this.sharedFs)return;const t=["/workspace","/shared","/scoops","/home","/tmp"];for(const n of t)try{await this.sharedFs.mkdir(n,{recursive:!0})}catch{}}async ensureGlobalMemory(){if(this.sharedFs){await Xxt(this.sharedFs);try{const t=await this.sharedFs.readFile("/shared/CLAUDE.md",{encoding:"utf-8"});this.globalMemoryCache=typeof t=="string"?t:new TextDecoder().decode(t)}catch{Wn.warn("Global memory file not found after creating defaults")}}}async getGlobalMemory(){if(this.globalMemoryCache)return this.globalMemoryCache;if(this.sharedFs)try{const t=await this.sharedFs.readFile("/shared/CLAUDE.md",{encoding:"utf-8"});this.globalMemoryCache=typeof t=="string"?t:new TextDecoder().decode(t)}catch{}return this.globalMemoryCache}async setGlobalMemory(t){this.sharedFs&&(await this.sharedFs.writeFile("/shared/CLAUDE.md",t),this.globalMemoryCache=t,Wn.info("Global memory updated"))}getSharedFS(){return this.sharedFs}setLickManager(t){this.lickManager=t}async registerScoop(t){await Pat(t),this.scoops.set(t.jid,t),this.messageQueues.set(t.jid,[]),Wn.info("Scoop registered",{jid:t.jid,name:t.name}),this.createScoopTab(t.jid).catch(n=>{const i=n instanceof Error?n.message:String(n);Wn.error("Scoop init failed",{jid:t.jid,error:i})})}async unregisterScoop(t){const n=this.scoops.get(t);if(n&&this.lickManager){const{webhooks:i,cronTasks:r}=this.lickManager.getLicksForScoop(n.name,n.folder),a=dSe(n.folder,i,r);if(a)throw a}await this.destroyScoopTab(t),this.sessionStore?.delete(t).catch(i=>{Wn.warn("Failed to delete agent session",{jid:t,error:i instanceof Error?i.message:String(i)})}),await Nat(t),this.scoops.delete(t),this.messageQueues.delete(t),this.lastAgentTimestamp.delete(t),Wn.info("Scoop unregistered",{jid:t})}getScoops(){return Array.from(this.scoops.values())}getScoop(t){return this.scoops.get(t)}async resetFilesystem(){for(const[t,n]of this.contexts.entries())n.stop(),this.contexts.delete(t);this.sharedFs=await ya.create({dbName:"slicc-fs",wipe:!0}),await this.ensureRootStructure(),await this.ensureGlobalMemory(),await cSe(this.sharedFs).catch(t=>{Wn.warn("Failed to re-seed default skills",{error:t instanceof Error?t.message:String(t)})}),Wn.info("Filesystem reset and defaults re-seeded")}async clearAllMessages(){await $at(),this.sessionStore&&await this.sessionStore.clearAll().catch(t=>{Wn.warn("Failed to clear agent sessions",{error:t instanceof Error?t.message:String(t)})});for(const t of this.contexts.values())t.clearMessages();this.lastAgentTimestamp.clear();for(const t of this.scoops.keys())this.messageQueues.set(t,[]);Wn.info("All messages cleared")}async handleMessage(t){Wn.info("handleMessage",{id:t.id,chatJid:t.chatJid,sender:t.senderName,channel:t.channel,contentPreview:t.content.slice(0,80)});const n=this.scoops.get(t.chatJid),i=n?.isCone?"cone":n?.name??"unknown";X2t(i,localStorage.getItem("selected-model")??"unknown"),await wQ(t),await this.routeToScoop(t)}async delegateToScoop(t,n,i){const r=this.scoops.get(t);if(!r)throw new Error(`Scoop not found: ${t}`);const a={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:t,senderId:"cone",senderName:i,content:n,timestamp:new Date().toISOString(),fromAssistant:!0,channel:"delegation"};await wQ(a),this.callbacks.onIncomingMessage?.(t,a),Wn.info("Delegating to scoop",{scoopJid:t,scoopName:r.name,promptLength:n.length}),this.sendPrompt(t,n,"cone",i).catch(l=>{const c=l instanceof Error?l.message:String(l);Wn.error("Delegation failed",{scoopJid:t,error:c}),this.callbacks.onError(t,`Delegation failed: ${c}`)})}async routeToScoop(t){const n=this.scoops.get(t.chatJid);if(!n){Wn.info("routeToScoop: unregistered target",{chatJid:t.chatJid});return}const i=t.channel==="webhook"||t.channel==="cron";if(!n.isCone&&n.requiresTrigger&&n.trigger&&!i&&!t.content.includes(n.trigger)){Wn.info("routeToScoop: trigger not found in content",{chatJid:t.chatJid,trigger:n.trigger,contentPreview:t.content.slice(0,80)});return}const r=this.messageQueues.get(t.chatJid)??[];r.push(t),this.messageQueues.set(t.chatJid,r);let a=this.tabs.get(t.chatJid);if(Wn.debug("routeToScoop: queued",{chatJid:t.chatJid,scoopName:n.name,tabStatus:a?.status??"no-tab",queueLength:r.length}),a?.status==="error"){Wn.info("routeToScoop: tab in error state, retrying init",{chatJid:t.chatJid});try{await this.createScoopTab(t.chatJid),a=this.tabs.get(t.chatJid)}catch{Wn.warn("routeToScoop: retry init failed",{chatJid:t.chatJid})}}a?.status==="ready"&&await this.processScoopQueue(t.chatJid)}async createScoopTab(t){const n=this.scoops.get(t);if(!n)throw new Error(`Scoop not found: ${t}`);if(this.contexts.has(t))if(this.tabs.get(t)?.status==="error")Wn.info("Re-creating context after error",{jid:t}),this.contexts.get(t)?.dispose(),this.contexts.delete(t),this.tabs.delete(t);else{Wn.debug("Context already exists",{jid:t});return}if(!this.sharedFs)throw new Error("Shared filesystem not initialized");const i=`scoop-${n.folder}-${Date.now()}`,r=n.isCone?this.sharedFs:new $ge(this.sharedFs,[`/scoops/${n.folder}/`,"/shared/"]),a={onResponse:(o,s)=>{if(this.callbacks.onResponse(t,o,s),!n.isCone)if(s){const u=this.scoopResponseBuffer.get(t)??"";this.scoopResponseBuffer.set(t,u+o)}else this.scoopResponseBuffer.set(t,o)},onResponseDone:()=>{const o=this.tabs.get(t);o&&(o.lastActivity=new Date().toISOString(),this.tabs.set(t,o)),this.callbacks.onResponseDone(t)},onError:o=>{const s=this.tabs.get(t);s&&(s.status="error",s.error=o,this.tabs.set(t,s)),this.callbacks.onError(t,o),this.callbacks.onStatusChange(t,"error")},onStatusChange:o=>{const s=this.tabs.get(t);if(s&&(s.status=o,s.lastActivity=new Date().toISOString(),this.tabs.set(t,s)),this.callbacks.onStatusChange(t,o),o==="ready"&&!n.isCone){const u=this.scoopResponseBuffer.get(t);if(this.scoopResponseBuffer.delete(t),u){const d=Array.from(this.scoops.values()).find(p=>p.isCone);if(d){const p=u.length>2e3?u.slice(0,2e3)+`
14745
14745
  ... (truncated)`:u,f={id:`scoop-done-${t}-${Date.now()}`,chatJid:d.jid,senderId:n.folder,senderName:n.assistantLabel,content:`[@${n.assistantLabel} completed]:
14746
14746
  ${p}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:"scoop-notify"};Wn.info("Routing scoop completion to cone",{scoop:n.folder,responseLength:u.length}),this.handleMessage(f).catch(h=>{const m=h instanceof Error?h.message:String(h);Wn.error("Failed to route scoop completion to cone",{scoop:n.folder,error:m}),this.callbacks.onError(d.jid,`Scoop ${n.folder} completed but notification failed: ${m}`)})}}}},onToolStart:(o,s)=>{this.callbacks.onToolStart?.(t,o,s)},onToolEnd:(o,s,u)=>{this.callbacks.onToolEnd?.(t,o,s,u)},onToolUI:(o,s,u)=>{this.callbacks.onToolUI?.(t,o,s,u)},onToolUIDone:o=>{this.callbacks.onToolUIDone?.(t,o)},onSendMessage:(o,s)=>{this.callbacks.onSendMessage(t,`${s?`[${s}] `:""}${o}`)},getScoops:()=>this.getScoops(),onFeedScoop:n.isCone?(o,s)=>this.delegateToScoop(o,s,n.assistantLabel):void 0,onScoopScoop:n.isCone?async o=>{const s={...o,jid:`scoop_${o.folder}_${Date.now()}`};return await this.registerScoop(s),s}:void 0,onDropScoop:n.isCone?async o=>{await this.unregisterScoop(o)}:void 0,getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:n.isCone?o=>this.setGlobalMemory(o):void 0,getBrowserAPI:()=>this.callbacks.getBrowserAPI()},l=new eSt(n,a,r,this.sessionStore??void 0);this.contexts.set(t,l),this.tabs.set(t,{jid:t,contextId:i,status:"initializing",lastActivity:new Date().toISOString()}),await l.init();const c=this.tabs.get(t);c&&c.status==="initializing"&&(c.status="ready",this.tabs.set(t,c),this.callbacks.onStatusChange(t,"ready")),Wn.info("Scoop context created",{jid:t,contextId:i})}async destroyScoopTab(t){const n=this.contexts.get(t);n&&(n.dispose(),this.contexts.delete(t),this.tabs.delete(t),Wn.info("Scoop context destroyed",{jid:t}))}isProcessing(t){return this.tabs.get(t)?.status==="processing"}getScoopContext(t){return this.contexts.get(t)}async clearQueuedMessages(t){const n=this.messageQueues.get(t);if(n&&n.length>0){for(const i of n)await _Q(i.id);this.messageQueues.set(t,[])}}async deleteQueuedMessage(t,n){const i=this.messageQueues.get(t);if(i){const r=i.findIndex(a=>a.id===n);r!==-1&&i.splice(r,1)}await _Q(n)}async getMessagesForScoop(t){return Dat(t)}async waitForTabReady(t,n=1e4){const i=Date.now();for(;Date.now()-i<n;){const r=this.tabs.get(t);if(!r)return!1;if(r.status==="ready"||r.status==="processing")return!0;if(r.status==="error")return!1;await new Promise(a=>setTimeout(a,100))}return Wn.warn("Timed out waiting for tab to become ready",{jid:t}),!1}async sendPrompt(t,n,i,r){let a=this.contexts.get(t);a||(await this.createScoopTab(t),a=this.contexts.get(t));let l=this.tabs.get(t);if(l?.status==="initializing"){if(Wn.debug("Context initializing, waiting to send message",{jid:t}),!await this.waitForTabReady(t)){Wn.error("Context did not become ready in time, dropping prompt",{jid:t});return}a=this.contexts.get(t),l=this.tabs.get(t)}if(!a){Wn.error("Context not found after creation",{jid:t});return}this.scoopResponseBuffer.delete(t),l&&(l.status="processing",l.lastActivity=new Date().toISOString(),this.tabs.set(t,l),this.callbacks.onStatusChange(t,"processing")),Wn.debug("Prompt sent to scoop",{jid:t,textLength:n.length}),await a.prompt(n)}async processScoopQueue(t){const n=this.messageQueues.get(t);if(!n||n.length===0){Wn.debug("processScoopQueue: empty queue",{jid:t});return}const i=this.tabs.get(t);if(i?.status!=="ready"){Wn.debug("processScoopQueue: tab not ready",{jid:t,status:i?.status??"no-tab"});return}const r=this.scoops.get(t),a=r?.assistantLabel??t,l=this.lastAgentTimestamp.get(t)??"",c=await jat(t,l,a);if(Wn.debug("processScoopQueue: DB query",{jid:t,scoopName:r?.name,excludeName:a,since:l,dbMessageCount:c.length,queueLength:n.length}),c.length===0){Wn.debug("processScoopQueue: no messages from DB, clearing queue",{jid:t}),this.messageQueues.set(t,[]);return}const o=c.map(u=>`[${new Date(u.timestamp).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}] ${u.senderName}: ${u.content}`).join(`
14747
- `);this.messageQueues.set(t,[]);const s=c[c.length-1];this.lastAgentTimestamp.set(t,s.timestamp),await YO(`lastAgentTs_${t}`,s.timestamp),await this.sendPrompt(t,o,s.senderId,s.senderName)}startMessageLoop(){this.pollInterval||(this.pollInterval=window.setInterval(()=>{for(const t of this.scoops.keys())this.tabs.get(t)?.status==="ready"&&this.processScoopQueue(t).catch(i=>{const r=i instanceof Error?i.message:String(i);Wn.error("Message queue processing failed",{jid:t,error:r}),this.callbacks.onError(t,`Queue processing failed: ${r}`)})},2e3))}stopMessageLoop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null)}updateModel(){for(const t of this.contexts.values())t.updateModel();Wn.info("Model updated on all active contexts",{contextCount:this.contexts.size})}stopScoop(t){const n=this.contexts.get(t);n&&n.stop()}async shutdown(){this.stopMessageLoop(),this.scheduler?.stop(),this.scheduler=null;for(const t of this.contexts.keys())await this.destroyScoopTab(t);Wn.info("Orchestrator shutdown")}}const pSe=mr("tray-follower");async function aSt(e){const t=await(e.fetchImpl??fetch)(e.joinUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({controllerId:e.controllerId,runtime:e.runtime})}),n=await dSt(t);return pSe.info("Follower tray attach response",{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),sSt(n)}function sSt(e){const t={trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,action:e.result.action,code:e.result.code,iceServers:e.iceServers};return e.result.action==="wait"?{...t,retryAfterMs:e.result.retryAfterMs}:e.result.action==="signal"?{...t,bootstrap:e.result.bootstrap}:e.result.action==="fail"?{...t,error:e.result.error}:t}async function oSt(e){return Fk(await qk(e,{action:"poll",controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function lSt(e){return Fk(await qk(e,{action:"answer",controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function cSt(e){return Fk(await qk(e,{action:"ice-candidate",controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function uSt(e){return Fk(await qk(e,{action:"retry",controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function Fk(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function dSt(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!pSt(n)){const i=t?t.slice(0,200):"(empty)";throw pSe.warn("Tray follower attach returned an invalid response",{status:e.status,body:i}),new Error(`Tray follower attach returned an invalid response (${e.status}): ${i}`)}return n}async function qk(e,t){const n=await(e.fetchImpl??fetch)(e.joinUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),i=await n.json().catch(()=>null);if(!fSt(i))throw new Error(`Tray follower bootstrap returned an invalid response (${n.status})`);return i}function pSt(e){if(!e||typeof e!="object")return!1;const t=e;if(typeof t.trayId!="string"||typeof t.controllerId!="string"||t.role!=="follower"||typeof t.participantCount!="number")return!1;const n=t.result;if(!n||typeof n!="object")return!1;const i=n;return i.action==="wait"?(i.code==="LEADER_NOT_ELECTED"||i.code==="LEADER_NOT_CONNECTED")&&typeof i.retryAfterMs=="number":i.action==="signal"?i.code==="LEADER_CONNECTED"&&fSe(i.bootstrap):i.action==="fail"?(i.code==="INVALID_JOIN_CAPABILITY"||i.code==="TRAY_EXPIRED")&&typeof i.error=="string":!1}function fSt(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.trayId=="string"&&typeof t.controllerId=="string"&&t.role==="follower"&&typeof t.participantCount=="number"&&fSe(t.bootstrap)&&Array.isArray(t.events)}function fSe(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.controllerId=="string"&&typeof t.bootstrapId=="string"&&typeof t.attempt=="number"&&typeof t.state=="string"&&typeof t.expiresAt=="string"&&typeof t.cursor=="number"&&typeof t.maxRetries=="number"&&typeof t.retriesRemaining=="number"}const ti=mr("tray-webrtc"),hSt="tray-control",mSt=250;class gSt{constructor(t){this.options=t,this.iceServers=t.iceServers,this.peerConnectionFactory=t.peerConnectionFactory??(()=>hSe(this.iceServers)),this.dataChannelLabel=t.dataChannelLabel??hSt}peerConnectionFactory;dataChannelLabel;peers=new Map;iceServers;setIceServers(t){this.iceServers=t}async handleControlMessage(t){t.type==="follower.join_requested"?(t.iceServers&&!this.iceServers&&(this.iceServers=t.iceServers),await this.handleJoinRequested(t)):t.type==="bootstrap.answer"?await this.peers.get(t.bootstrapId)?.peer.setRemoteDescription(t.answer):t.type==="bootstrap.ice_candidate"&&await this.peers.get(t.bootstrapId)?.peer.addIceCandidate(t.candidate)}getPeers(){return Array.from(this.peers.values()).map(({state:t})=>({...t}))}getChannel(t){return this.peers.get(t)?.channel??null}stop(){for(const t of this.peers.values())t.peer.close();this.peers.clear()}async handleJoinRequested(t){this.closeControllerPeers(t.controllerId);const n=this.peerConnectionFactory(),i={controllerId:t.controllerId,bootstrapId:t.bootstrapId,attempt:t.attempt,state:"connecting",connectedAt:null,runtime:t.runtime},r=n.createDataChannel(this.dataChannelLabel);this.peers.set(t.bootstrapId,{state:i,peer:n,channel:r}),n.addEventListener("icecandidate",({candidate:a})=>{const l=gSe(a);l&&this.options.sendControlMessage({type:"bootstrap.ice_candidate",controllerId:t.controllerId,bootstrapId:t.bootstrapId,candidate:l})}),n.addEventListener("connectionstatechange",()=>{const a=this.peers.get(t.bootstrapId);a&&(a.state.state!=="connected"?n.connectionState==="failed"&&this.failPeer(t,"Leader peer connection failed before the data channel opened"):(n.connectionState==="disconnected"||n.connectionState==="failed")&&(ti.warn("Leader peer connection state changed post-connect",{bootstrapId:t.bootstrapId,state:n.connectionState}),this.options.onPeerDisconnected?.(t.bootstrapId,`Peer connection ${n.connectionState}`)))}),r.addEventListener("open",()=>{const a=this.peers.get(t.bootstrapId);!a||a.state.state==="connected"||(a.state.state="connected",a.state.connectedAt=new Date().toISOString(),this.options.onPeerConnected?.({...a.state},a.channel))}),r.addEventListener("close",()=>{const a=this.peers.get(t.bootstrapId);a&&(a.state.state!=="connected"?this.failPeer(t,"Leader data channel closed before opening"):(ti.warn("Leader data channel closed post-connect",{bootstrapId:t.bootstrapId}),this.options.onPeerDisconnected?.(t.bootstrapId,"Data channel closed")))}),r.addEventListener("error",()=>{const a=this.peers.get(t.bootstrapId);a&&(a.state.state!=="connected"?this.failPeer(t,"Leader data channel failed before opening"):(ti.warn("Leader data channel error post-connect",{bootstrapId:t.bootstrapId}),this.options.onPeerDisconnected?.(t.bootstrapId,"Data channel error")))});try{const a=await n.createOffer();await n.setLocalDescription(a),this.options.sendControlMessage({type:"bootstrap.offer",controllerId:t.controllerId,bootstrapId:t.bootstrapId,offer:mSe(n.localDescription??a,"offer")})}catch(a){this.failPeer(t,a instanceof Error?a.message:String(a))}}closeControllerPeers(t){for(const[n,i]of this.peers.entries())i.state.controllerId===t&&(i.peer.close(),this.peers.delete(n))}failPeer(t,n){const i=this.peers.get(t.bootstrapId);if(i){i.peer.close(),this.peers.delete(t.bootstrapId);try{this.options.sendControlMessage({type:"bootstrap.failed",controllerId:t.controllerId,bootstrapId:t.bootstrapId,code:"WEBRTC_BOOTSTRAP_FAILED",message:n,retryable:!0,retryAfterMs:1e3})}catch(r){ti.warn("Failed to report tray bootstrap failure",{error:r instanceof Error?r.message:String(r)})}}}}class ySt{constructor(t){this.options=t,this.fetchImpl=t.fetchImpl??fetch,this.iceServers=t.iceServers,this.peerConnectionFactory=t.peerConnectionFactory??(()=>hSe(this.iceServers)),this.controllerIdFactory=t.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=t.sleep??(n=>new Promise(i=>setTimeout(i,n))),this.pollIntervalMs=t.pollIntervalMs??mSt}fetchImpl;peerConnectionFactory;controllerIdFactory;sleep;pollIntervalMs;iceServers;activePeer=null;stopped=!1;async start(){this.stopped=!1;const t=this.controllerIdFactory(),n=Date.now();yo({state:"connecting",joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:n,lastError:null}),ti.info("Follower tray join starting",{joinUrl:this.options.joinUrl});let i=0;for(;;){Fie(this.stopped),i++;let r;try{r=await aSt({joinUrl:this.options.joinUrl,controllerId:t,runtime:this.options.runtime,fetchImpl:this.fetchImpl})}catch(a){const l=a instanceof Error?a.message:String(a);throw yo({...lg(),attachAttempts:i,lastError:l}),a}if(yo({...lg(),attachAttempts:i,lastAttachCode:r.code}),r.action==="wait"){const a=r.retryAfterMs??1e3;ti.info("Follower tray attach waiting",{attempt:i,code:r.code,retryAfterMs:a}),i%10===0&&ti.warn(`Follower tray attach still waiting after ${i} attempts`,{attempt:i,code:r.code,retryAfterMs:a}),await this.sleep(a);continue}if(r.action==="fail"||!r.bootstrap){const a=r.error??`Tray follower attach failed (${r.code})`;throw yo({state:"error",joinUrl:this.options.joinUrl,trayId:null,error:a,lastPingTime:null,reconnectAttempts:0,attachAttempts:i,lastAttachCode:r.code,connectingSince:null,lastError:a}),ti.warn("Follower tray attach failed",{error:a}),new Error(a)}r.iceServers&&(this.iceServers=r.iceServers);try{const a=await this.completeBootstrap(r.trayId,t,r.bootstrap);return yo({state:"connected",joinUrl:this.options.joinUrl,trayId:a.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:i,lastAttachCode:r.code,connectingSince:null,lastError:null}),ti.info("Follower tray connected",{trayId:a.trayId,controllerId:t}),a}catch(a){const l=a instanceof Error?a.message:String(a);throw yo({state:"error",joinUrl:this.options.joinUrl,trayId:r.trayId,error:l,lastPingTime:null,reconnectAttempts:0,attachAttempts:i,lastAttachCode:r.code,connectingSince:null,lastError:l}),ti.warn("Follower tray bootstrap failed",{error:l}),a}}}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,yo({state:"inactive",joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null})}async completeBootstrap(t,n,i){let r=i,a=0;for(this.activePeer=this.createFollowerPeer(n,r.bootstrapId);;){if(Fie(this.stopped),this.activePeer.open&&this.activePeer.channel)return{trayId:t,controllerId:n,bootstrapId:r.bootstrapId,channel:this.activePeer.channel};if(this.activePeer.openError)throw new Error(this.activePeer.openError);const l=await oSt({joinUrl:this.options.joinUrl,controllerId:n,bootstrapId:r.bootstrapId,cursor:a,fetchImpl:this.fetchImpl});r=l.bootstrap,a=r.cursor;try{for(const c of l.events)if(c.type==="bootstrap.offer"){await this.activePeer.peer.setRemoteDescription(c.offer);const o=await this.activePeer.peer.createAnswer();await this.activePeer.peer.setLocalDescription(o),await lSt({joinUrl:this.options.joinUrl,controllerId:n,bootstrapId:r.bootstrapId,answer:mSe(this.activePeer.peer.localDescription??o,"answer"),fetchImpl:this.fetchImpl})}else if(c.type==="bootstrap.ice_candidate")await this.activePeer.peer.addIceCandidate(c.candidate);else if(c.type==="bootstrap.failed")throw new Error(c.failure.message)}catch(c){if(r.failure?.retryable&&r.retriesRemaining>0){r=(await uSt({joinUrl:this.options.joinUrl,controllerId:n,bootstrapId:r.bootstrapId,runtime:this.options.runtime,fetchImpl:this.fetchImpl})).bootstrap,a=0,this.activePeer.peer.close(),this.activePeer=this.createFollowerPeer(n,r.bootstrapId);continue}throw c}this.activePeer.open||await this.sleep(this.pollIntervalMs)}}createFollowerPeer(t,n){const i=this.peerConnectionFactory(),r={peer:i,channel:null,open:!1,openError:null};return i.addEventListener("connectionstatechange",()=>{r.open&&(i.connectionState==="disconnected"||i.connectionState==="failed")&&(ti.warn("Follower peer connection state changed post-connect",{bootstrapId:n,state:i.connectionState}),this.options.onDisconnected?.(`Peer connection ${i.connectionState}`))}),i.addEventListener("datachannel",({channel:a})=>{r.channel=a,a.addEventListener("open",()=>{r.open=!0}),a.addEventListener("close",()=>{r.open?(ti.warn("Follower data channel closed post-connect",{bootstrapId:n}),this.options.onDisconnected?.("Data channel closed")):r.openError="Follower data channel closed before opening"}),a.addEventListener("error",()=>{r.open?(ti.warn("Follower data channel error post-connect",{bootstrapId:n}),this.options.onDisconnected?.("Data channel error")):r.openError="Follower data channel failed before opening"})}),i.addEventListener("icecandidate",({candidate:a})=>{const l=gSe(a);l&&cSt({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:n,candidate:l,fetchImpl:this.fetchImpl}).catch(c=>{ti.warn("Failed to send follower ICE candidate",{error:c instanceof Error?c.message:String(c)})})}),r}}function vSt(e,t){const n=t.baseDelayMs??1e3,i=t.backoffMultiplier??2,r=t.maxDelayMs??3e4,a=t.maxAttempts??10,l=t.sleep??e.sleep??(h=>new Promise(m=>setTimeout(m,h)));let c=!1,o=!1,s=null;const u={cancel(){c=!0,o=!1,s?.stop(),s=null},get reconnecting(){return o}},d=()=>{const h=new ySt({...e,sleep:l,onDisconnected:m=>{c||(ti.warn("Follower disconnected, starting reconnect loop",{reason:m}),p(m))}});return s=h,{manager:h,connectionPromise:h.start()}},p=async h=>{if(c||o)return;o=!0,s?.stop(),s=null;let m=0,g=n,y=h??"Unknown disconnect";for(;!c&&m<a&&(m++,t.onReconnecting?.(m),yo({...lg(),state:"reconnecting",error:null,reconnectAttempts:m}),ti.info("Reconnect attempt",{attempt:m,delay:g}),await l(g),!c);){let v=null;try{const b=d();v=b.manager;const w=await b.connectionPromise;if(c){v.stop();break}o=!1,yo({...lg(),state:"connected",joinUrl:e.joinUrl,trayId:w.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),ti.info("Reconnect successful",{attempt:m,trayId:w.trayId}),t.onConnected(w);return}catch(b){y=b instanceof Error?b.message:String(b),ti.warn("Reconnect attempt failed",{attempt:m,error:y}),v?.stop(),s=null}g=Math.min(g*i,r)}c||(o=!1,yo({...lg(),state:"error",error:`Reconnect failed after ${m} attempts: ${y}`,reconnectAttempts:m}),ti.warn("Reconnect gave up",{attempts:m,lastError:y}),t.onGaveUp?.(y))},{connectionPromise:f}=d();return f.then(h=>{c||t.onConnected(h)}).catch(h=>{c||ti.warn("Initial follower connection failed",{error:h instanceof Error?h.message:String(h)})}),u}function hSe(e){if(typeof RTCPeerConnection>"u")throw new Error("RTCPeerConnection is not available in this runtime");const t=e?.length?{iceServers:e}:void 0;return new RTCPeerConnection(t)}function mSe(e,t){if(!e||e.type!==t||typeof e.sdp!="string")throw new Error(`Expected a local ${t} description before signaling`);return{type:e.type,sdp:e.sdp}}function gSe(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.candidate=="string"?{candidate:t.candidate,sdpMid:typeof t.sdpMid=="string"?t.sdpMid:null,sdpMLineIndex:typeof t.sdpMLineIndex=="number"?t.sdpMLineIndex:null,usernameFragment:typeof t.usernameFragment=="string"?t.usernameFragment:null}:null}function Fie(e){if(e)throw new Error("Tray follower stopped before WebRTC bootstrap completed")}const fC=64*1024;async function dP(e,t){try{switch(t.op){case"readFile":return await bSt(e,t.path,t.encoding);case"writeFile":return[await wSt(e,t.path,t.content,t.encoding)];case"stat":return[await _St(e,t.path)];case"readDir":return[await xSt(e,t.path)];case"mkdir":return[await SSt(e,t.path,t.recursive)];case"rm":return[await CSt(e,t.path,t.recursive)];case"exists":return[await TSt(e,t.path)];case"walk":return[await ESt(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(n){return[kSt(n)]}}async function bSt(e,t,n){if((n??"utf-8")==="utf-8"){const l=await e.readFile(t,{encoding:"utf-8"});return qie(l,"utf-8")}const r=await e.readFile(t,{encoding:"binary"}),a=ASt(r);return qie(a,"base64")}async function wSt(e,t,n,i){if(i==="base64"){const r=RSt(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:"void"}}}async function _St(e,t){return{ok:!0,data:{type:"stat",stat:await e.stat(t)}}}async function xSt(e,t){return{ok:!0,data:{type:"dirEntries",entries:await e.readDir(t)}}}async function SSt(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:"void"}}}async function CSt(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:"void"}}}async function TSt(e,t){return{ok:!0,data:{type:"exists",exists:await e.exists(t)}}}async function ESt(e,t){const n=[];for await(const i of e.walk(t))n.push(i);return{ok:!0,data:{type:"paths",paths:n}}}function qie(e,t){if(e.length<=fC)return[{ok:!0,data:{type:"file",content:e,encoding:t}}];const n=Math.ceil(e.length/fC),i=[];for(let r=0;r<n;r++){const a=r*fC,l=e.slice(a,a+fC);i.push({ok:!0,data:{type:"file",content:l,encoding:t},chunkIndex:r,totalChunks:n})}return i}function kSt(e){return e instanceof Error&&"code"in e?{ok:!1,error:e.message,code:e.code}:{ok:!1,error:e instanceof Error?e.message:String(e)}}function ASt(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function RSt(e){const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n}class OSt{runtimes=new Map;dirty=!1;setTargets(t,n){this.runtimes.set(t,n),this.dirty=!0}removeRuntime(t){this.runtimes.delete(t)&&(this.dirty=!0)}getEntries(){this.dirty=!1;const t=[];for(const[n,i]of this.runtimes)for(const r of i)t.push({targetId:`${n}:${r.targetId}`,localTargetId:r.targetId,runtimeId:n,title:r.title,url:r.url,isLocal:!1});return t}hasChanged(){return this.dirty}getRuntimeIds(){return[...this.runtimes.keys()]}}const Bie=mr("data-channel-keepalive");class ySe{sendPing;onDead;intervalMs;maxMissed;timer=null;missedPongs=0;awaitingPong=!1;stopped=!1;constructor(t){this.sendPing=t.sendPing,this.onDead=t.onDead,this.intervalMs=t.intervalMs??1e4,this.maxMissed=t.maxMissed??3}start(){this.timer||this.stopped||(this.timer=setInterval(()=>this.tick(),this.intervalMs))}stop(){this.stopped=!0,this.timer&&(clearInterval(this.timer),this.timer=null)}receivePong(){this.awaitingPong=!1,this.missedPongs=0}receivePing(){this.missedPongs=0,this.awaitingPong=!1}get missed(){return this.missedPongs}tick(){if(!this.stopped){if(this.awaitingPong&&(this.missedPongs++,Bie.debug("Missed pong",{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){Bie.warn("Channel declared dead",{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}}const yc=mr("tray-leader-sync");function ISt(e){return e?e.includes("standalone")?"standalone":e.includes("extension")?"extension":e.includes("electron")?"electron":"unknown":"unknown"}class PSt{constructor(t){this.options=t}followers=new Map;registry=new OSt;runtimeToBootstrap=new Map;pendingCDPRoutes=new Map;cdpChunkBuffers=new Map;remoteTransports=new Map;pendingTabOpenRoutes=new Map;tabOpenResolvers=new Map;pendingFsRoutes=new Map;fsResolvers=new Map;addFollower(t,n,i){this.removeFollower(t);const r=Rat(n),a=r.onMessage(o=>{this.handleFollowerMessage(t,o)}),l=new ySe({sendPing:()=>r.send({type:"ping"}),onDead:()=>{yc.warn("Follower keepalive dead, removing follower",{bootstrapId:t}),this.removeFollower(t),this.options.onFollowerDead?.(t)}});l.start(),this.followers.set(t,{bootstrapId:t,sync:r,unsubscribe:a,keepalive:l,runtime:i?.runtime,connectedAt:i?.connectedAt,lastActivity:Date.now(),floatType:ISt(i?.runtime)}),yc.info("Follower added to sync",{bootstrapId:t,followerCount:this.followers.size}),this.sendSnapshotToFollower(t);const c=this.getConnectedEntries();c.length>0&&r.send({type:"targets.registry",targets:c})}removeFollower(t){const n=this.followers.get(t);if(n){n.keepalive.stop(),n.unsubscribe(),n.sync.close(),this.followers.delete(t);for(const[i,r]of this.runtimeToBootstrap)if(r===t){this.cleanupRemoteTransports(i),this.registry.removeRuntime(i),this.runtimeToBootstrap.delete(i);break}this.registry.hasChanged()&&this.broadcastTargetRegistry(),yc.info("Follower removed from sync",{bootstrapId:t,followerCount:this.followers.size})}}broadcastEvent(t){if(this.followers.size===0)return;const n=this.options.getScoopJid(),i={type:"agent_event",event:t,scoopJid:n};for(const r of this.followers.values())r.sync.send(i)}broadcastUserMessage(t,n){if(this.followers.size===0)return;const i=this.options.getScoopJid(),r={type:"user_message_echo",text:t,messageId:n,scoopJid:i};for(const a of this.followers.values())a.sync.send(r)}broadcastStatus(t){if(this.followers.size===0)return;const n={type:"status",scoopStatus:t};for(const i of this.followers.values())i.sync.send(n)}sendSnapshotToFollower(t){const n=this.followers.get(t);if(!n)return;const i=this.options.getMessages(),r=this.options.getScoopJid();kat(n.sync,i,r),yc.debug("Snapshot sent to follower",{bootstrapId:t,messageCount:i.length})}handleFollowerMessage(t,n){switch(n.type){case"user_message":yc.info("Follower user message received",{bootstrapId:t,messageId:n.messageId}),this.options.onFollowerMessage(n.text,n.messageId);break;case"abort":yc.info("Follower abort received",{bootstrapId:t}),this.options.onFollowerAbort();break;case"request_snapshot":yc.info("Follower snapshot request received",{bootstrapId:t}),this.sendSnapshotToFollower(t);break;case"targets.advertise":{yc.info("Follower targets advertised",{bootstrapId:t,runtimeId:n.runtimeId,targetCount:n.targets.length});for(const i of[...this.remoteTransports.keys()]){const r=i.substring(0,i.indexOf(":"));r!=="leader"&&!this.runtimeToBootstrap.has(r)&&r!==n.runtimeId&&(this.remoteTransports.get(i)?.disconnect(),this.remoteTransports.delete(i),yc.debug("Cleaned up orphaned remote transport on advertise",{key:i}))}this.runtimeToBootstrap.set(n.runtimeId,t),this.registry.setTargets(n.runtimeId,n.targets),this.broadcastTargetRegistry();break}case"cdp.request":{const{requestId:i,targetRuntimeId:r,localTargetId:a,method:l,params:c,sessionId:o}=n;r==="leader"?this.executeLocalCDP(i,a,l,c,o,t):this.forwardCDPRequest(i,r,a,l,c,o,t);break}case"cdp.response":{this.handleCDPResponse(n);break}case"cdp.event":{this.handleCDPEvent(t,n.method,n.params,n.sessionId);break}case"tab.open":{const{requestId:i,targetRuntimeId:r,url:a}=n;r==="leader"?this.executeLocalTabOpen(i,a,t):this.forwardTabOpen(i,r,a,t);break}case"tab.opened":{this.handleTabOpenResponse(n.requestId,n.targetId);break}case"tab.open.error":{this.handleTabOpenError(n.requestId,n.error);break}case"fs.request":{const{requestId:i,targetRuntimeId:r,request:a}=n;r==="leader"?this.executeLocalFs(i,a,t):this.forwardFsRequest(i,r,a,t);break}case"fs.response":{this.handleFsResponse(n.requestId,n.response);break}case"ping":{const i=this.followers.get(t);i&&(i.keepalive.receivePing(),i.lastActivity=Date.now(),i.sync.send({type:"pong"}));break}case"pong":{const i=this.followers.get(t);i&&(i.keepalive.receivePong(),i.lastActivity=Date.now());break}}}setLocalTargets(t){this.registry.setTargets("leader",t),this.registry.hasChanged()&&this.broadcastTargetRegistry()}broadcastTargetRegistry(){if(this.followers.size===0)return;const n={type:"targets.registry",targets:this.getConnectedEntries()};for(const i of this.followers.values())i.sync.send(n)}getTargets(){return this.getConnectedEntries()}getConnectedEntries(){return this.registry.getEntries().filter(t=>{if(t.runtimeId==="leader")return!0;const n=this.runtimeToBootstrap.get(t.runtimeId);return n?this.followers.has(n):!1})}createRemoteTransport(t,n){const i={sendCDPRequest:(a,l,c,o)=>{const s=this.runtimeToBootstrap.get(t),u=s?this.followers.get(s):void 0;if(!u){this.remoteTransports.get(`${t}:${n}`)?.handleResponse(a,void 0,`Target runtime "${t}" not connected`);return}this.pendingCDPRoutes.set(a,{requesterBootstrapId:"__leader__",requestId:a}),u.sync.send({type:"cdp.request",requestId:a,localTargetId:n,method:l,params:c,sessionId:o})}},r=new Wge(i);return this.remoteTransports.set(`${t}:${n}`,r),r}removeRemoteTransport(t,n){const i=`${t}:${n}`,r=this.remoteTransports.get(i);r&&(r.disconnect(),this.remoteTransports.delete(i))}cleanupRemoteTransports(t){const n=`${t}:`;for(const i of[...this.remoteTransports.keys()])i.startsWith(n)&&(this.remoteTransports.get(i)?.disconnect(),this.remoteTransports.delete(i),yc.debug("Cleaned up stale remote transport",{key:i}))}getConnectedFollowers(){return[...this.runtimeToBootstrap.entries()].map(([t,n])=>{const i=this.followers.get(n);return{runtimeId:t,runtime:i?.runtime,connectedAt:i?.connectedAt,lastActivity:i?.lastActivity,floatType:i?.floatType}})}getBestFollowerForTeleport(){const t=[];for(const[r,a]of this.runtimeToBootstrap){const l=this.followers.get(a);l&&t.push({runtimeId:r,bootstrapId:a,floatType:l.floatType,lastActivity:l.lastActivity})}if(t.length===0)return null;const n=t.filter(r=>r.floatType==="standalone"),i=n.length>0?n:t;return i.sort((r,a)=>a.lastActivity-r.lastActivity),i[0]}get hasFollowers(){return this.followers.size>0}stop(){for(const t of[...this.followers.keys()])this.removeFollower(t)}async executeLocalCDP(t,n,i,r,a,l){const c=this.followers.get(l);if(!c)return;const o=this.options.browserTransport;if(!o){c.sync.send({type:"cdp.response",requestId:t,error:"Leader has no browser transport"});return}try{const s=await o.send(i,r,a);QO(c.sync,t,s)}catch(s){c.sync.send({type:"cdp.response",requestId:t,error:s instanceof Error?s.message:String(s)})}}forwardCDPRequest(t,n,i,r,a,l,c){const o=this.runtimeToBootstrap.get(n),s=o?this.followers.get(o):void 0,u=this.followers.get(c);if(!s){u&&u.sync.send({type:"cdp.response",requestId:t,error:`Target runtime "${n}" not connected`});return}this.pendingCDPRoutes.set(t,{requesterBootstrapId:c,requestId:t}),s.sync.send({type:"cdp.request",requestId:t,localTargetId:i,method:r,params:a,sessionId:l})}handleCDPResponse(t){const{requestId:n,result:i,error:r,chunkData:a,chunkIndex:l,totalChunks:c}=t,o=this.pendingCDPRoutes.get(n);if(!o)return;const s=OM(this.cdpChunkBuffers,t);if(!s)return;if(this.pendingCDPRoutes.delete(n),o.requesterBootstrapId==="__leader__"){for(const d of this.remoteTransports.values())d.handleResponse(n,s.result,s.error);return}const u=this.followers.get(o.requesterBootstrapId);u&&QO(u.sync,n,s.result,s.error)}handleCDPEvent(t,n,i,r){let a;for(const[c,o]of this.runtimeToBootstrap)if(o===t){a=c;break}if(!a)return;const l=`${a}:`;for(const[c,o]of this.remoteTransports)c.startsWith(l)&&o.handleEvent(n,i)}openRemoteTab(t,n){const i=this.runtimeToBootstrap.get(t),r=i?this.followers.get(i):void 0;if(!r)return Promise.reject(new Error(`Target runtime "${t}" not connected`));const a=`tab-open-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((l,c)=>{this.tabOpenResolvers.set(a,{resolve:l,reject:c}),this.pendingTabOpenRoutes.set(a,{requesterBootstrapId:"__leader__",requestId:a}),r.sync.send({type:"tab.open",requestId:a,url:n})})}async executeLocalTabOpen(t,n,i){const r=this.followers.get(i);if(!r)return;const a=this.options.browserTransport;if(!a){r.sync.send({type:"tab.open.error",requestId:t,error:"Leader has no browser transport"});return}try{const c=(await a.send("Target.createTarget",{url:n,background:!0})).targetId;r.sync.send({type:"tab.opened",requestId:t,targetId:`leader:${c}`})}catch(l){r.sync.send({type:"tab.open.error",requestId:t,error:l instanceof Error?l.message:String(l)})}}forwardTabOpen(t,n,i,r){const a=this.runtimeToBootstrap.get(n),l=a?this.followers.get(a):void 0,c=this.followers.get(r);if(!l){c&&c.sync.send({type:"tab.open.error",requestId:t,error:`Target runtime "${n}" not connected`});return}this.pendingTabOpenRoutes.set(t,{requesterBootstrapId:r,requestId:t}),l.sync.send({type:"tab.open",requestId:t,url:i})}handleTabOpenResponse(t,n){const i=this.pendingTabOpenRoutes.get(t);if(!i)return;if(this.pendingTabOpenRoutes.delete(t),i.requesterBootstrapId==="__leader__"){const a=this.tabOpenResolvers.get(t);a&&(this.tabOpenResolvers.delete(t),a.resolve(n));return}const r=this.followers.get(i.requesterBootstrapId);r&&r.sync.send({type:"tab.opened",requestId:t,targetId:n})}handleTabOpenError(t,n){const i=this.pendingTabOpenRoutes.get(t);if(!i)return;if(this.pendingTabOpenRoutes.delete(t),i.requesterBootstrapId==="__leader__"){const a=this.tabOpenResolvers.get(t);a&&(this.tabOpenResolvers.delete(t),a.reject(new Error(n)));return}const r=this.followers.get(i.requesterBootstrapId);r&&r.sync.send({type:"tab.open.error",requestId:t,error:n})}async executeLocalFs(t,n,i){const r=this.followers.get(i);if(!r)return;const a=this.options.vfs;if(!a){r.sync.send({type:"fs.response",requestId:t,response:{ok:!1,error:"Leader has no VFS"}});return}const l=await dP(a,n);for(const c of l)r.sync.send({type:"fs.response",requestId:t,response:c})}forwardFsRequest(t,n,i,r){const a=this.runtimeToBootstrap.get(n),l=a?this.followers.get(a):void 0,c=this.followers.get(r);if(!l){c&&c.sync.send({type:"fs.response",requestId:t,response:{ok:!1,error:`Target runtime "${n}" not connected`}});return}this.pendingFsRoutes.set(t,{requesterBootstrapId:r,requestId:t,chunks:[],totalChunks:1}),l.sync.send({type:"fs.request",requestId:t,request:i})}handleFsResponse(t,n){const i=this.pendingFsRoutes.get(t);if(!i){const l=this.fsResolvers.get(t);if(l){l.responses.push(n);const c=n.ok&&n.totalChunks||1;l.responses.length>=c&&(this.fsResolvers.delete(t),l.resolve(l.responses))}return}if(i.requesterBootstrapId==="__leader__"){const l=this.fsResolvers.get(t);if(l){l.responses.push(n);const c=n.ok&&n.totalChunks||1;l.responses.length>=c&&(this.fsResolvers.delete(t),this.pendingFsRoutes.delete(t),l.resolve(l.responses))}return}const r=this.followers.get(i.requesterBootstrapId);r&&r.sync.send({type:"fs.response",requestId:t,response:n}),i.chunks.push(n);const a=n.ok&&n.totalChunks||1;i.totalChunks=a,i.chunks.length>=i.totalChunks&&this.pendingFsRoutes.delete(t)}sendFsRequest(t,n){if(t==="leader"){const l=this.options.vfs;return l?dP(l,n):Promise.resolve([{ok:!1,error:"Leader has no VFS"}])}const i=this.runtimeToBootstrap.get(t),r=i?this.followers.get(i):void 0;if(!r)return Promise.resolve([{ok:!1,error:`Target runtime "${t}" not connected`}]);const a=`fs-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((l,c)=>{this.fsResolvers.set(a,{resolve:l,reject:c,responses:[]}),this.pendingFsRoutes.set(a,{requesterBootstrapId:"__leader__",requestId:a,chunks:[],totalChunks:1}),r.sync.send({type:"fs.request",requestId:a,request:n})})}}const ua=mr("tray-follower-sync");class MSt{constructor(t,n={}){this.options=n,this.sync=Oat(t),this.unsubscribe=this.sync.onMessage(i=>{this.handleLeaderMessage(i)}),this.keepalive=new ySe({sendPing:()=>this.sync.send({type:"ping"}),onDead:()=>{ua.warn("Leader keepalive dead, cleaning up"),this.handleDisconnect("Keepalive timeout — leader not responding"),this.options.onDead?.()}}),this.keepalive.start(),t.addEventListener("close",()=>{ua.warn("Data channel closed"),this.handleDisconnect("Data channel closed")}),t.addEventListener("error",()=>{ua.warn("Data channel error"),this.handleDisconnect("Data channel error")})}sync;eventListeners=new Set;unsubscribe;keepalive;latestSnapshot=null;sentMessageIds=new Set;targetEntries=[];remoteTransports=new Map;cdpChunkBuffers=new Map;snapshotChunkBuffer=null;remoteCDPSessions=new Set;cdpEventCleanups=[];tabOpenResolvers=new Map;fsResolvers=new Map;sendMessage(t,n){const i=n??`follower-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.sentMessageIds.add(i),this.sync.send({type:"user_message",text:t,messageId:i}),ua.info("Sent user message to leader",{messageId:i})}onEvent(t){return this.eventListeners.add(t),()=>this.eventListeners.delete(t)}stop(){this.sync.send({type:"abort"}),ua.info("Sent abort to leader")}requestSnapshot(){this.sync.send({type:"request_snapshot"})}getLatestSnapshot(){return this.latestSnapshot}close(){this.keepalive.stop(),this.unsubscribe(),this.sync.close(),this.eventListeners.clear(),this.cleanupCDPEventForwarding(),ua.info("Follower sync closed")}advertiseTargets(t,n){this.sync.send({type:"targets.advertise",targets:t,runtimeId:n})}getTargets(){return this.targetEntries}disconnected=!1;handleDisconnect(t){if(this.disconnected)return;this.disconnected=!0;const n=lg();yo({...n,state:"error",error:t}),this.emitEvent({type:"error",error:`Connection to leader lost: ${t}`}),this.keepalive.stop(),this.cleanupCDPEventForwarding(),this.unsubscribe(),this.sync.close(),this.options.onDisconnect?.(t)}handleLeaderMessage(t){switch(t.type){case"snapshot":ua.info("Snapshot received from leader",{messageCount:t.messages.length,scoopJid:t.scoopJid}),this.snapshotChunkBuffer=null,this.latestSnapshot={messages:t.messages,scoopJid:t.scoopJid},this.options.onSnapshot?.(t.messages,t.scoopJid);break;case"snapshot_chunk":{const n=Aat(this.snapshotChunkBuffer,t);this.snapshotChunkBuffer=n.buffer,n.result&&(ua.info("Chunked snapshot reassembled from leader",{messageCount:n.result.messages.length,scoopJid:n.result.scoopJid}),this.latestSnapshot=n.result,this.options.onSnapshot?.(n.result.messages,n.result.scoopJid));break}case"agent_event":this.emitEvent(t.event);break;case"user_message_echo":if(this.sentMessageIds.has(t.messageId)){this.sentMessageIds.delete(t.messageId),ua.debug("Skipping own message echo",{messageId:t.messageId});break}ua.info("User message echo received",{messageId:t.messageId,scoopJid:t.scoopJid}),this.options.onUserMessage?.(t.text,t.messageId,t.scoopJid);break;case"status":this.options.onStatus?.(t.scoopStatus);break;case"error":ua.warn("Error from leader",{error:t.error}),this.emitEvent({type:"error",error:t.error});break;case"targets.registry":ua.info("Target registry received from leader",{targetCount:t.targets.length}),this.targetEntries=t.targets,this.options.onTargetsUpdated?.(this.targetEntries);break;case"cdp.request":{const{requestId:n,localTargetId:i,method:r,params:a,sessionId:l}=t;this.executeLocalCDP(n,i,r,a,l);break}case"cdp.response":{this.routeCDPResponse(t);break}case"cdp.event":{for(const n of this.remoteTransports.values())n.handleEvent(t.method,t.params);break}case"tab.open":{this.executeLocalTabOpen(t.requestId,t.url);break}case"tab.opened":{const n=this.tabOpenResolvers.get(t.requestId);n&&(this.tabOpenResolvers.delete(t.requestId),n.resolve(t.targetId));break}case"tab.open.error":{const n=this.tabOpenResolvers.get(t.requestId);n&&(this.tabOpenResolvers.delete(t.requestId),n.reject(new Error(t.error)));break}case"fs.request":{this.executeLocalFs(t.requestId,t.request);break}case"fs.response":{this.routeFsResponse(t.requestId,t.response);break}case"ping":{this.keepalive.receivePing(),this.sync.send({type:"pong"});break}case"pong":{this.keepalive.receivePong(),irt(Date.now());break}}}emitEvent(t){for(const n of this.eventListeners)try{n(t)}catch(i){ua.error("Listener error",{eventType:t.type,error:i instanceof Error?i.message:String(i)})}}createRemoteTransport(t,n){const i={sendCDPRequest:(a,l,c,o)=>{this.sync.send({type:"cdp.request",requestId:a,targetRuntimeId:t,localTargetId:n,method:l,params:c,sessionId:o})}},r=new Wge(i);return this.remoteTransports.set(`${t}:${n}`,r),r}removeRemoteTransport(t,n){const i=`${t}:${n}`,r=this.remoteTransports.get(i);r&&(r.disconnect(),this.remoteTransports.delete(i))}openRemoteTab(t,n){const i=`tab-open-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((r,a)=>{this.tabOpenResolvers.set(i,{resolve:r,reject:a}),this.sync.send({type:"tab.open",requestId:i,targetRuntimeId:t,url:n})})}async executeLocalTabOpen(t,n){const i=this.options.browserTransport;if(!i){this.sync.send({type:"tab.open.error",requestId:t,error:"Follower has no browser transport"});return}try{const a=(await i.send("Target.createTarget",{url:n,background:!0})).targetId;this.sync.send({type:"tab.opened",requestId:t,targetId:a}),this.options.onTargetsChanged?.()}catch(r){this.sync.send({type:"tab.open.error",requestId:t,error:r instanceof Error?r.message:String(r)})}}async executeLocalCDP(t,n,i,r,a){const l=this.options.browserTransport;if(!l){this.sync.send({type:"cdp.response",requestId:t,error:"Follower has no browser transport"});return}try{const c=await l.send(i,r,a);if(i==="Target.attachToTarget"&&c.sessionId){const o=c.sessionId;this.remoteCDPSessions.add(o),this.setupCDPEventForwarding(l,o),ua.debug("Tracking remote CDP session",{remoteSessionId:o})}i==="Target.detachFromTarget"&&a&&this.remoteCDPSessions.has(a)&&(this.remoteCDPSessions.delete(a),ua.debug("Removed remote CDP session on detach",{sessionId:a})),QO(this.sync,t,c)}catch(c){this.sync.send({type:"cdp.response",requestId:t,error:c instanceof Error?c.message:String(c)})}}setupCDPEventForwarding(t,n){const i=["Page.frameNavigated","Page.loadEventFired","Page.domContentEventFired","Network.responseReceived","Network.loadingFinished","Network.requestWillBeSent"];for(const r of i){const a=l=>{if(l.sessionId!==n||!this.remoteCDPSessions.has(n))return;const{sessionId:c,...o}=l;this.sync.send({type:"cdp.event",method:r,params:o,sessionId:n})};t.on(r,a),this.cdpEventCleanups.push(()=>t.off(r,a))}}cleanupCDPEventForwarding(){for(const t of this.cdpEventCleanups)t();this.cdpEventCleanups.length=0,this.remoteCDPSessions.clear()}routeCDPResponse(t){const n=OM(this.cdpChunkBuffers,t);if(n)for(const i of this.remoteTransports.values())i.handleResponse(t.requestId,n.result,n.error)}async executeLocalFs(t,n){const i=this.options.vfs;if(!i){this.sync.send({type:"fs.response",requestId:t,response:{ok:!1,error:"Follower has no VFS"}});return}const r=await dP(i,n);for(const a of r)this.sync.send({type:"fs.response",requestId:t,response:a})}routeFsResponse(t,n){const i=this.fsResolvers.get(t);if(!i)return;i.responses.push(n);const r=n.ok&&n.totalChunks||1;i.responses.length>=r&&(this.fsResolvers.delete(t),i.resolve(i.responses))}sendFsRequest(t,n){const i=`fs-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((r,a)=>{this.fsResolvers.set(i,{resolve:r,reject:a,responses:[]}),this.sync.send({type:"fs.request",requestId:i,targetRuntimeId:t,request:n})})}}const NSt="electron-overlay",Wie="/electron",$St="slicc-electron-overlay:set-tab";function DSt(e,t){if(t)return"extension";try{const n=new URL(e);return LSt(n)?"electron-overlay":"standalone"}catch{return"standalone"}}function jSt(e,t){return e==="electron-overlay"||e==="standalone"&&t}function zie(e){try{const n=new URL(e).searchParams.get("tab");return n&&Oit(n)?n:XX}catch{return XX}}function LSt(e){return e.pathname===Wie||e.pathname===`${Wie}/`||e.searchParams.get("runtime")===NSt}function USt(e){const t=new URL(e);return`${t.protocol==="https:"?"wss:":"ws:"}//${t.host}/licks-ws`}function FSt(e,t){return`${new URL(e).origin}/webhooks/${t}`}function qSt(e,t){const n=e.replace(/\/+$/,""),i=t.replace(/^\/+/,"");return`${n}/${i}`}function BSt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type===$St}const WSt=["/shared/sprinkles"];async function zSt(e){const t=new Map;for(const n of WSt)await e.exists(n)&&await Gie(e,n,t);return await Gie(e,"/",t),t}async function Gie(e,t,n){for await(const i of e.walk(t)){if(!i.endsWith(".shtml"))continue;const r=GSt(i);if(!n.has(r)){let a;try{a=await e.readFile(i,{encoding:"utf-8"})??""}catch{a=""}n.set(r,{name:r,path:i,title:HSt(a,r),autoOpen:VSt(a)})}}}function GSt(e){const t=e.split("/").pop()??e;return t.endsWith(".shtml")?t.slice(0,-6):t}function HSt(e,t){const n=e.match(/data-sprinkle-title=["']([^"']+)["']/);if(n)return n[1];const i=e.match(/<title>([^<]+)<\/title>/i);return i?i[1].trim():t}function VSt(e){return/data-sprinkle-autoopen\b/.test(e)}class JSt{listeners=new Map;lickHandler;fs;closeHandler;constructor(t,n,i){this.fs=t,this.lickHandler=n,this.closeHandler=i}createAPI(t){return{name:t,lick:n=>{const i=typeof n=="string"?n:n.action,r=typeof n=="string"?void 0:n.data,a={type:"sprinkle",sprinkleName:t,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:i,data:r}};this.lickHandler(a)},on:(n,i)=>{const r=`${t}:${n}`;let a=this.listeners.get(r);a||(a=new Set,this.listeners.set(r,a)),a.add(i)},off:(n,i)=>{const r=`${t}:${n}`;this.listeners.get(r)?.delete(i)},readFile:async n=>await this.fs.readFile(n,{encoding:"utf-8"}),setState:n=>{try{localStorage.setItem(`slicc-sprinkle-state:${t}`,JSON.stringify(n))}catch{}},getState:()=>{try{const n=localStorage.getItem(`slicc-sprinkle-state:${t}`);return n?JSON.parse(n):null}catch{return null}},open:n=>{const i=/^https?:|^chrome-extension:/.test(n)?n:H3(n);window.open(i,"_blank")},close:()=>this.closeHandler(t)}}pushUpdate(t,n){const i=`${t}:update`,r=this.listeners.get(i);if(r)for(const a of r)try{a(n)}catch{}}removeSprinkle(t){for(const n of this.listeners.keys())n.startsWith(`${t}:`)&&this.listeners.delete(n)}}const lm=mr("sprinkle-manager"),Hie="slicc-open-sprinkles";class vSe{fs;bridge;callbacks;availableSprinkles=new Map;openSprinkles=new Map;constructor(t,n,i){this.fs=t,this.bridge=new JSt(t,n,r=>this.close(r)),this.callbacks=i}async restoreOpenSprinkles(){try{const t=localStorage.getItem(Hie);if(!t){for(const i of this.availableSprinkles.values())if(i.autoOpen)try{await this.open(i.name)}catch{lm.warn("Failed to auto-open sprinkle",{name:i.name})}return}const n=JSON.parse(t);for(const i of n)try{await this.open(i)}catch{lm.warn("Failed to restore sprinkle",{name:i})}}catch{}}persistOpenSprinkles(){try{localStorage.setItem(Hie,JSON.stringify([...this.openSprinkles.keys()]))}catch{}}async openNewAutoOpenSprinkles(){await this.refresh();for(const t of this.availableSprinkles.values())if(t.autoOpen&&!this.openSprinkles.has(t.name))try{await this.open(t.name),lm.info("Auto-opened new sprinkle after install",{name:t.name})}catch{lm.warn("Failed to auto-open new sprinkle",{name:t.name})}}async refresh(){this.availableSprinkles=await zSt(this.fs),lm.info("Discovered sprinkles",{count:this.availableSprinkles.size})}async open(t,n){if(this.openSprinkles.has(t)){lm.info("Sprinkle already open",{name:t});return}let i=this.availableSprinkles.get(t);if(i||(await this.refresh(),i=this.availableSprinkles.get(t)),!i)throw new Error(`Sprinkle not found: ${t}`);const r=await this.fs.readFile(i.path,{encoding:"utf-8"}),a=document.createElement("div");a.className="sprinkle-panel",a.style.cssText="width: 100%; height: 100%; display: flex; flex-direction: column; overflow: hidden;",a.dataset.sprinkle=t,this.openSprinkles.set(t,{renderer:null,container:a}),this.callbacks.addSprinkle(t,i.title,a,n);const l=this.bridge.createAPI(t),c=new fae(a,l);await c.render(r,t),this.openSprinkles.get(t).renderer=c,this.persistOpenSprinkles(),Y2t(t),lm.info("Sprinkle opened",{name:t,title:i.title})}close(t){const n=this.openSprinkles.get(t);n&&(n.renderer.dispose(),n.container.remove(),this.bridge.removeSprinkle(t),this.openSprinkles.delete(t),this.callbacks.removeSprinkle(t),this.persistOpenSprinkles(),lm.info("Sprinkle closed",{name:t}))}available(){return Array.from(this.availableSprinkles.values())}opened(){return Array.from(this.openSprinkles.keys())}sendToSprinkle(t,n){const i=this.openSprinkles.get(t);if(!i){lm.warn("Cannot send to closed sprinkle",{name:t});return}this.bridge.pushUpdate(t,n),i.renderer.pushUpdate(n)}}const mn=mr("main");function KSt(){const e=document.createElement("div");e.className="skill-drop-overlay";const t=document.createElement("div");t.className="skill-drop-overlay__card";const n=document.createElement("div");n.className="skill-drop-overlay__title",t.appendChild(n);const i=document.createElement("div");return i.className="skill-drop-overlay__desc",t.appendChild(i),e.appendChild(t),document.body.appendChild(e),{show(r,a){n.textContent=r,i.textContent=a,e.classList.add("skill-drop-overlay--visible")},hide(){e.classList.remove("skill-drop-overlay--visible")}}}function bSe(){const e=document.createElement("div");return e.className="skill-drop-toast-container",document.body.appendChild(e),(t,n)=>{const i=document.createElement("div");i.className=`skill-drop-toast skill-drop-toast--${n}`,i.textContent=t,e.appendChild(i),requestAnimationFrame(()=>i.classList.add("skill-drop-toast--visible"));const r=()=>{i.classList.remove("skill-drop-toast--visible"),window.setTimeout(()=>i.remove(),180)};window.setTimeout(r,4200)}}function wSe(e,t,n){const i=KSt();let r=0,a=!1;const l=()=>{r=0,a||i.hide()};window.addEventListener("dragenter",c=>{yQ(c.dataTransfer)&&(c.preventDefault(),r+=1,a||i.show("Drop .skill to install","Unpack into /workspace/skills/{name}."))}),window.addEventListener("dragover",c=>{yQ(c.dataTransfer)&&(c.preventDefault(),c.dataTransfer&&(c.dataTransfer.dropEffect="copy"),a||i.show("Drop .skill to install","Unpack into /workspace/skills/{name}."))}),window.addEventListener("dragleave",()=>{r!==0&&(r=Math.max(0,r-1),r===0&&!a&&i.hide())}),window.addEventListener("dragend",l),window.addEventListener("blur",l),window.addEventListener("drop",async c=>{const o=_at(c.dataTransfer);if(!o){l();return}if(c.preventDefault(),r=0,a){i.hide(),t("Another .skill installation is already in progress.","error");return}a=!0,i.show("Installing skill…",o.name);try{const s=await bat(e,o);await n(),t(`Installed "${s.skillName}" to ${s.destinationPath} (${s.fileCount} files). Run "skill install ${s.skillName}" to apply it.`,"success")}catch(s){const u=s instanceof Error?s.message:String(s);t(`Failed to install dropped skill: ${u}`,"error")}finally{a=!1,i.hide()}})}async function ZSt(e){const{OffscreenClient:t}=await fn(async()=>{const{OffscreenClient:f}=await import("./offscreen-client-CO5fJLap.js");return{OffscreenClient:f}},[]),{VirtualFS:n}=await fn(async()=>{const{VirtualFS:f}=await Promise.resolve().then(()=>aat);return{VirtualFS:f}},void 0),i=new Q_(e,!0);window.__slicc_debug_tabs=f=>i.setDebugTabs(f),await i.panels.chat.initSession("session-cone");let r=null;const a=await n.create({dbName:"slicc-fs"});i.panels.fileBrowser.setFs(a),mn.info("File browser wired to shared VFS (local IndexedDB)");const l=new BroadcastChannel("preview-vfs");l.onmessage=f=>{if(f.data?.type!=="preview-vfs-read")return;const{id:h,path:m,asText:g}=f.data;(async()=>{try{const y=g?"utf-8":"binary",v=await a.readFile(m,{encoding:y});l.postMessage({type:"preview-vfs-response",id:h,content:v})}catch(y){const v=y instanceof Error?y.message:String(y);v.includes("ENOENT")||mn.error("Preview VFS read failed",{path:m,error:v}),l.postMessage({type:"preview-vfs-response",id:h,error:v})}})()};const c=bSe();wSe(a,c,async()=>{await i.panels.fileBrowser.refresh()});try{const{WasmShell:f}=await fn(async()=>{const{WasmShell:b}=await Promise.resolve().then(()=>iSe);return{WasmShell:b}},void 0),{PanelCdpProxy:h,BrowserAPI:m}=await fn(async()=>{const{PanelCdpProxy:b,BrowserAPI:w}=await import("./index-DlCxPcMj.js");return{PanelCdpProxy:b,BrowserAPI:w}},[]),g=new h;await g.connect();const y=new m(g),v=new f({fs:a,browserAPI:y});await i.panels.terminal.mountShell(v),mn.info("Terminal mounted with shared VFS and BrowserAPI (CDP proxy)")}catch(f){mn.warn("Failed to mount shell to terminal",f)}let o,s=new Set;const u=async f=>{r=f,o.selectedScoopJid=f.jid,i.panels.memory.setSelectedScoop(f.jid),i.setScoopSwitcherSelected?.(f.jid),i.panels.scoops.setSelectedJid(f.jid);const h=f.isCone?"session-cone":`session-${f.folder}`,m=f.isCone?void 0:f.name;await i.panels.chat.switchToContext(h,!f.isCone,m),o.isProcessing(f.jid)&&i.panels.chat.setProcessing(!0)};o=new t({onStatusChange:(f,h)=>{i.panels.scoops.updateScoopStatus(f,h),i.updateScoopSwitcherStatus?.(f,h),r?.jid===f&&(i.setAgentProcessing(h==="processing"),h==="processing"?i.panels.chat.setProcessing(!0):h==="ready"&&i.panels.chat.setProcessing(!1))},onScoopCreated:f=>{i.panels.scoops.refreshScoops(),i.refreshScoopSwitcher?.(),r||(r=f,o.selectedScoopJid=f.jid,i.panels.memory.setSelectedScoop(f.jid))},onScoopListUpdate:()=>{const f=new Set(o.getScoops().map(h=>h.folder));for(const h of s)f.has(h)||i.panels.chat.deleteSessionById(`session-${h}`);if(s=f,i.panels.scoops.refreshScoops(),i.refreshScoopSwitcher?.(),!r){const m=o.getScoops().find(g=>g.isCone);m&&(r=m,o.selectedScoopJid=m.jid,i.panels.memory.setSelectedScoop(m.jid))}},onIncomingMessage:(f,h)=>{if(r?.jid===f){const m=h.channel==="delegation"?`**[Instructions from sliccy]**
14747
+ `);this.messageQueues.set(t,[]);const s=c[c.length-1];this.lastAgentTimestamp.set(t,s.timestamp),await YO(`lastAgentTs_${t}`,s.timestamp),await this.sendPrompt(t,o,s.senderId,s.senderName)}startMessageLoop(){this.pollInterval||(this.pollInterval=window.setInterval(()=>{for(const t of this.scoops.keys())this.tabs.get(t)?.status==="ready"&&this.processScoopQueue(t).catch(i=>{const r=i instanceof Error?i.message:String(i);Wn.error("Message queue processing failed",{jid:t,error:r}),this.callbacks.onError(t,`Queue processing failed: ${r}`)})},2e3))}stopMessageLoop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null)}updateModel(){for(const t of this.contexts.values())t.updateModel();Wn.info("Model updated on all active contexts",{contextCount:this.contexts.size})}stopScoop(t){const n=this.contexts.get(t);n&&n.stop()}async shutdown(){this.stopMessageLoop(),this.scheduler?.stop(),this.scheduler=null;for(const t of this.contexts.keys())await this.destroyScoopTab(t);Wn.info("Orchestrator shutdown")}}const pSe=mr("tray-follower");async function aSt(e){const t=await(e.fetchImpl??fetch)(e.joinUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({controllerId:e.controllerId,runtime:e.runtime})}),n=await dSt(t);return pSe.info("Follower tray attach response",{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),sSt(n)}function sSt(e){const t={trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,action:e.result.action,code:e.result.code,iceServers:e.iceServers};return e.result.action==="wait"?{...t,retryAfterMs:e.result.retryAfterMs}:e.result.action==="signal"?{...t,bootstrap:e.result.bootstrap}:e.result.action==="fail"?{...t,error:e.result.error}:t}async function oSt(e){return Fk(await qk(e,{action:"poll",controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function lSt(e){return Fk(await qk(e,{action:"answer",controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function cSt(e){return Fk(await qk(e,{action:"ice-candidate",controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function uSt(e){return Fk(await qk(e,{action:"retry",controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function Fk(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function dSt(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!pSt(n)){const i=t?t.slice(0,200):"(empty)";throw pSe.warn("Tray follower attach returned an invalid response",{status:e.status,body:i}),new Error(`Tray follower attach returned an invalid response (${e.status}): ${i}`)}return n}async function qk(e,t){const n=await(e.fetchImpl??fetch)(e.joinUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),i=await n.json().catch(()=>null);if(!fSt(i))throw new Error(`Tray follower bootstrap returned an invalid response (${n.status})`);return i}function pSt(e){if(!e||typeof e!="object")return!1;const t=e;if(typeof t.trayId!="string"||typeof t.controllerId!="string"||t.role!=="follower"||typeof t.participantCount!="number")return!1;const n=t.result;if(!n||typeof n!="object")return!1;const i=n;return i.action==="wait"?(i.code==="LEADER_NOT_ELECTED"||i.code==="LEADER_NOT_CONNECTED")&&typeof i.retryAfterMs=="number":i.action==="signal"?i.code==="LEADER_CONNECTED"&&fSe(i.bootstrap):i.action==="fail"?(i.code==="INVALID_JOIN_CAPABILITY"||i.code==="TRAY_EXPIRED")&&typeof i.error=="string":!1}function fSt(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.trayId=="string"&&typeof t.controllerId=="string"&&t.role==="follower"&&typeof t.participantCount=="number"&&fSe(t.bootstrap)&&Array.isArray(t.events)}function fSe(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.controllerId=="string"&&typeof t.bootstrapId=="string"&&typeof t.attempt=="number"&&typeof t.state=="string"&&typeof t.expiresAt=="string"&&typeof t.cursor=="number"&&typeof t.maxRetries=="number"&&typeof t.retriesRemaining=="number"}const ti=mr("tray-webrtc"),hSt="tray-control",mSt=250;class gSt{constructor(t){this.options=t,this.iceServers=t.iceServers,this.peerConnectionFactory=t.peerConnectionFactory??(()=>hSe(this.iceServers)),this.dataChannelLabel=t.dataChannelLabel??hSt}peerConnectionFactory;dataChannelLabel;peers=new Map;iceServers;setIceServers(t){this.iceServers=t}async handleControlMessage(t){t.type==="follower.join_requested"?(t.iceServers&&!this.iceServers&&(this.iceServers=t.iceServers),await this.handleJoinRequested(t)):t.type==="bootstrap.answer"?await this.peers.get(t.bootstrapId)?.peer.setRemoteDescription(t.answer):t.type==="bootstrap.ice_candidate"&&await this.peers.get(t.bootstrapId)?.peer.addIceCandidate(t.candidate)}getPeers(){return Array.from(this.peers.values()).map(({state:t})=>({...t}))}getChannel(t){return this.peers.get(t)?.channel??null}stop(){for(const t of this.peers.values())t.peer.close();this.peers.clear()}async handleJoinRequested(t){this.closeControllerPeers(t.controllerId);const n=this.peerConnectionFactory(),i={controllerId:t.controllerId,bootstrapId:t.bootstrapId,attempt:t.attempt,state:"connecting",connectedAt:null,runtime:t.runtime},r=n.createDataChannel(this.dataChannelLabel);this.peers.set(t.bootstrapId,{state:i,peer:n,channel:r}),n.addEventListener("icecandidate",({candidate:a})=>{const l=gSe(a);l&&this.options.sendControlMessage({type:"bootstrap.ice_candidate",controllerId:t.controllerId,bootstrapId:t.bootstrapId,candidate:l})}),n.addEventListener("connectionstatechange",()=>{const a=this.peers.get(t.bootstrapId);a&&(a.state.state!=="connected"?n.connectionState==="failed"&&this.failPeer(t,"Leader peer connection failed before the data channel opened"):(n.connectionState==="disconnected"||n.connectionState==="failed")&&(ti.warn("Leader peer connection state changed post-connect",{bootstrapId:t.bootstrapId,state:n.connectionState}),this.options.onPeerDisconnected?.(t.bootstrapId,`Peer connection ${n.connectionState}`)))}),r.addEventListener("open",()=>{const a=this.peers.get(t.bootstrapId);!a||a.state.state==="connected"||(a.state.state="connected",a.state.connectedAt=new Date().toISOString(),this.options.onPeerConnected?.({...a.state},a.channel))}),r.addEventListener("close",()=>{const a=this.peers.get(t.bootstrapId);a&&(a.state.state!=="connected"?this.failPeer(t,"Leader data channel closed before opening"):(ti.warn("Leader data channel closed post-connect",{bootstrapId:t.bootstrapId}),this.options.onPeerDisconnected?.(t.bootstrapId,"Data channel closed")))}),r.addEventListener("error",()=>{const a=this.peers.get(t.bootstrapId);a&&(a.state.state!=="connected"?this.failPeer(t,"Leader data channel failed before opening"):(ti.warn("Leader data channel error post-connect",{bootstrapId:t.bootstrapId}),this.options.onPeerDisconnected?.(t.bootstrapId,"Data channel error")))});try{const a=await n.createOffer();await n.setLocalDescription(a),this.options.sendControlMessage({type:"bootstrap.offer",controllerId:t.controllerId,bootstrapId:t.bootstrapId,offer:mSe(n.localDescription??a,"offer")})}catch(a){this.failPeer(t,a instanceof Error?a.message:String(a))}}closeControllerPeers(t){for(const[n,i]of this.peers.entries())i.state.controllerId===t&&(i.peer.close(),this.peers.delete(n))}failPeer(t,n){const i=this.peers.get(t.bootstrapId);if(i){i.peer.close(),this.peers.delete(t.bootstrapId);try{this.options.sendControlMessage({type:"bootstrap.failed",controllerId:t.controllerId,bootstrapId:t.bootstrapId,code:"WEBRTC_BOOTSTRAP_FAILED",message:n,retryable:!0,retryAfterMs:1e3})}catch(r){ti.warn("Failed to report tray bootstrap failure",{error:r instanceof Error?r.message:String(r)})}}}}class ySt{constructor(t){this.options=t,this.fetchImpl=t.fetchImpl??fetch,this.iceServers=t.iceServers,this.peerConnectionFactory=t.peerConnectionFactory??(()=>hSe(this.iceServers)),this.controllerIdFactory=t.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=t.sleep??(n=>new Promise(i=>setTimeout(i,n))),this.pollIntervalMs=t.pollIntervalMs??mSt}fetchImpl;peerConnectionFactory;controllerIdFactory;sleep;pollIntervalMs;iceServers;activePeer=null;stopped=!1;async start(){this.stopped=!1;const t=this.controllerIdFactory(),n=Date.now();yo({state:"connecting",joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:n,lastError:null}),ti.info("Follower tray join starting",{joinUrl:this.options.joinUrl});let i=0;for(;;){Fie(this.stopped),i++;let r;try{r=await aSt({joinUrl:this.options.joinUrl,controllerId:t,runtime:this.options.runtime,fetchImpl:this.fetchImpl})}catch(a){const l=a instanceof Error?a.message:String(a);throw yo({...lg(),attachAttempts:i,lastError:l}),a}if(yo({...lg(),attachAttempts:i,lastAttachCode:r.code}),r.action==="wait"){const a=r.retryAfterMs??1e3;ti.info("Follower tray attach waiting",{attempt:i,code:r.code,retryAfterMs:a}),i%10===0&&ti.warn(`Follower tray attach still waiting after ${i} attempts`,{attempt:i,code:r.code,retryAfterMs:a}),await this.sleep(a);continue}if(r.action==="fail"||!r.bootstrap){const a=r.error??`Tray follower attach failed (${r.code})`;throw yo({state:"error",joinUrl:this.options.joinUrl,trayId:null,error:a,lastPingTime:null,reconnectAttempts:0,attachAttempts:i,lastAttachCode:r.code,connectingSince:null,lastError:a}),ti.warn("Follower tray attach failed",{error:a}),new Error(a)}r.iceServers&&(this.iceServers=r.iceServers);try{const a=await this.completeBootstrap(r.trayId,t,r.bootstrap);return yo({state:"connected",joinUrl:this.options.joinUrl,trayId:a.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:i,lastAttachCode:r.code,connectingSince:null,lastError:null}),ti.info("Follower tray connected",{trayId:a.trayId,controllerId:t}),a}catch(a){const l=a instanceof Error?a.message:String(a);throw yo({state:"error",joinUrl:this.options.joinUrl,trayId:r.trayId,error:l,lastPingTime:null,reconnectAttempts:0,attachAttempts:i,lastAttachCode:r.code,connectingSince:null,lastError:l}),ti.warn("Follower tray bootstrap failed",{error:l}),a}}}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,yo({state:"inactive",joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null})}async completeBootstrap(t,n,i){let r=i,a=0;for(this.activePeer=this.createFollowerPeer(n,r.bootstrapId);;){if(Fie(this.stopped),this.activePeer.open&&this.activePeer.channel)return{trayId:t,controllerId:n,bootstrapId:r.bootstrapId,channel:this.activePeer.channel};if(this.activePeer.openError)throw new Error(this.activePeer.openError);const l=await oSt({joinUrl:this.options.joinUrl,controllerId:n,bootstrapId:r.bootstrapId,cursor:a,fetchImpl:this.fetchImpl});r=l.bootstrap,a=r.cursor;try{for(const c of l.events)if(c.type==="bootstrap.offer"){await this.activePeer.peer.setRemoteDescription(c.offer);const o=await this.activePeer.peer.createAnswer();await this.activePeer.peer.setLocalDescription(o),await lSt({joinUrl:this.options.joinUrl,controllerId:n,bootstrapId:r.bootstrapId,answer:mSe(this.activePeer.peer.localDescription??o,"answer"),fetchImpl:this.fetchImpl})}else if(c.type==="bootstrap.ice_candidate")await this.activePeer.peer.addIceCandidate(c.candidate);else if(c.type==="bootstrap.failed")throw new Error(c.failure.message)}catch(c){if(r.failure?.retryable&&r.retriesRemaining>0){r=(await uSt({joinUrl:this.options.joinUrl,controllerId:n,bootstrapId:r.bootstrapId,runtime:this.options.runtime,fetchImpl:this.fetchImpl})).bootstrap,a=0,this.activePeer.peer.close(),this.activePeer=this.createFollowerPeer(n,r.bootstrapId);continue}throw c}this.activePeer.open||await this.sleep(this.pollIntervalMs)}}createFollowerPeer(t,n){const i=this.peerConnectionFactory(),r={peer:i,channel:null,open:!1,openError:null};return i.addEventListener("connectionstatechange",()=>{r.open&&(i.connectionState==="disconnected"||i.connectionState==="failed")&&(ti.warn("Follower peer connection state changed post-connect",{bootstrapId:n,state:i.connectionState}),this.options.onDisconnected?.(`Peer connection ${i.connectionState}`))}),i.addEventListener("datachannel",({channel:a})=>{r.channel=a,a.addEventListener("open",()=>{r.open=!0}),a.addEventListener("close",()=>{r.open?(ti.warn("Follower data channel closed post-connect",{bootstrapId:n}),this.options.onDisconnected?.("Data channel closed")):r.openError="Follower data channel closed before opening"}),a.addEventListener("error",()=>{r.open?(ti.warn("Follower data channel error post-connect",{bootstrapId:n}),this.options.onDisconnected?.("Data channel error")):r.openError="Follower data channel failed before opening"})}),i.addEventListener("icecandidate",({candidate:a})=>{const l=gSe(a);l&&cSt({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:n,candidate:l,fetchImpl:this.fetchImpl}).catch(c=>{ti.warn("Failed to send follower ICE candidate",{error:c instanceof Error?c.message:String(c)})})}),r}}function vSt(e,t){const n=t.baseDelayMs??1e3,i=t.backoffMultiplier??2,r=t.maxDelayMs??3e4,a=t.maxAttempts??10,l=t.sleep??e.sleep??(h=>new Promise(m=>setTimeout(m,h)));let c=!1,o=!1,s=null;const u={cancel(){c=!0,o=!1,s?.stop(),s=null},get reconnecting(){return o}},d=()=>{const h=new ySt({...e,sleep:l,onDisconnected:m=>{c||(ti.warn("Follower disconnected, starting reconnect loop",{reason:m}),p(m))}});return s=h,{manager:h,connectionPromise:h.start()}},p=async h=>{if(c||o)return;o=!0,s?.stop(),s=null;let m=0,g=n,y=h??"Unknown disconnect";for(;!c&&m<a&&(m++,t.onReconnecting?.(m),yo({...lg(),state:"reconnecting",error:null,reconnectAttempts:m}),ti.info("Reconnect attempt",{attempt:m,delay:g}),await l(g),!c);){let v=null;try{const b=d();v=b.manager;const w=await b.connectionPromise;if(c){v.stop();break}o=!1,yo({...lg(),state:"connected",joinUrl:e.joinUrl,trayId:w.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),ti.info("Reconnect successful",{attempt:m,trayId:w.trayId}),t.onConnected(w);return}catch(b){y=b instanceof Error?b.message:String(b),ti.warn("Reconnect attempt failed",{attempt:m,error:y}),v?.stop(),s=null}g=Math.min(g*i,r)}c||(o=!1,yo({...lg(),state:"error",error:`Reconnect failed after ${m} attempts: ${y}`,reconnectAttempts:m}),ti.warn("Reconnect gave up",{attempts:m,lastError:y}),t.onGaveUp?.(y))},{connectionPromise:f}=d();return f.then(h=>{c||t.onConnected(h)}).catch(h=>{c||ti.warn("Initial follower connection failed",{error:h instanceof Error?h.message:String(h)})}),u}function hSe(e){if(typeof RTCPeerConnection>"u")throw new Error("RTCPeerConnection is not available in this runtime");const t=e?.length?{iceServers:e}:void 0;return new RTCPeerConnection(t)}function mSe(e,t){if(!e||e.type!==t||typeof e.sdp!="string")throw new Error(`Expected a local ${t} description before signaling`);return{type:e.type,sdp:e.sdp}}function gSe(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.candidate=="string"?{candidate:t.candidate,sdpMid:typeof t.sdpMid=="string"?t.sdpMid:null,sdpMLineIndex:typeof t.sdpMLineIndex=="number"?t.sdpMLineIndex:null,usernameFragment:typeof t.usernameFragment=="string"?t.usernameFragment:null}:null}function Fie(e){if(e)throw new Error("Tray follower stopped before WebRTC bootstrap completed")}const fC=64*1024;async function dP(e,t){try{switch(t.op){case"readFile":return await bSt(e,t.path,t.encoding);case"writeFile":return[await wSt(e,t.path,t.content,t.encoding)];case"stat":return[await _St(e,t.path)];case"readDir":return[await xSt(e,t.path)];case"mkdir":return[await SSt(e,t.path,t.recursive)];case"rm":return[await CSt(e,t.path,t.recursive)];case"exists":return[await TSt(e,t.path)];case"walk":return[await ESt(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(n){return[kSt(n)]}}async function bSt(e,t,n){if((n??"utf-8")==="utf-8"){const l=await e.readFile(t,{encoding:"utf-8"});return qie(l,"utf-8")}const r=await e.readFile(t,{encoding:"binary"}),a=ASt(r);return qie(a,"base64")}async function wSt(e,t,n,i){if(i==="base64"){const r=RSt(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:"void"}}}async function _St(e,t){return{ok:!0,data:{type:"stat",stat:await e.stat(t)}}}async function xSt(e,t){return{ok:!0,data:{type:"dirEntries",entries:await e.readDir(t)}}}async function SSt(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:"void"}}}async function CSt(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:"void"}}}async function TSt(e,t){return{ok:!0,data:{type:"exists",exists:await e.exists(t)}}}async function ESt(e,t){const n=[];for await(const i of e.walk(t))n.push(i);return{ok:!0,data:{type:"paths",paths:n}}}function qie(e,t){if(e.length<=fC)return[{ok:!0,data:{type:"file",content:e,encoding:t}}];const n=Math.ceil(e.length/fC),i=[];for(let r=0;r<n;r++){const a=r*fC,l=e.slice(a,a+fC);i.push({ok:!0,data:{type:"file",content:l,encoding:t},chunkIndex:r,totalChunks:n})}return i}function kSt(e){return e instanceof Error&&"code"in e?{ok:!1,error:e.message,code:e.code}:{ok:!1,error:e instanceof Error?e.message:String(e)}}function ASt(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function RSt(e){const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n}class OSt{runtimes=new Map;dirty=!1;setTargets(t,n){this.runtimes.set(t,n),this.dirty=!0}removeRuntime(t){this.runtimes.delete(t)&&(this.dirty=!0)}getEntries(){this.dirty=!1;const t=[];for(const[n,i]of this.runtimes)for(const r of i)t.push({targetId:`${n}:${r.targetId}`,localTargetId:r.targetId,runtimeId:n,title:r.title,url:r.url,isLocal:!1});return t}hasChanged(){return this.dirty}getRuntimeIds(){return[...this.runtimes.keys()]}}const Bie=mr("data-channel-keepalive");class ySe{sendPing;onDead;intervalMs;maxMissed;timer=null;missedPongs=0;awaitingPong=!1;stopped=!1;constructor(t){this.sendPing=t.sendPing,this.onDead=t.onDead,this.intervalMs=t.intervalMs??1e4,this.maxMissed=t.maxMissed??3}start(){this.timer||this.stopped||(this.timer=setInterval(()=>this.tick(),this.intervalMs))}stop(){this.stopped=!0,this.timer&&(clearInterval(this.timer),this.timer=null)}receivePong(){this.awaitingPong=!1,this.missedPongs=0}receivePing(){this.missedPongs=0,this.awaitingPong=!1}get missed(){return this.missedPongs}tick(){if(!this.stopped){if(this.awaitingPong&&(this.missedPongs++,Bie.debug("Missed pong",{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){Bie.warn("Channel declared dead",{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}}const yc=mr("tray-leader-sync");function ISt(e){return e?e.includes("standalone")?"standalone":e.includes("extension")?"extension":e.includes("electron")?"electron":"unknown":"unknown"}class PSt{constructor(t){this.options=t}followers=new Map;registry=new OSt;runtimeToBootstrap=new Map;pendingCDPRoutes=new Map;cdpChunkBuffers=new Map;remoteTransports=new Map;pendingTabOpenRoutes=new Map;tabOpenResolvers=new Map;pendingFsRoutes=new Map;fsResolvers=new Map;addFollower(t,n,i){this.removeFollower(t);const r=Rat(n),a=r.onMessage(o=>{this.handleFollowerMessage(t,o)}),l=new ySe({sendPing:()=>r.send({type:"ping"}),onDead:()=>{yc.warn("Follower keepalive dead, removing follower",{bootstrapId:t}),this.removeFollower(t),this.options.onFollowerDead?.(t)}});l.start(),this.followers.set(t,{bootstrapId:t,sync:r,unsubscribe:a,keepalive:l,runtime:i?.runtime,connectedAt:i?.connectedAt,lastActivity:Date.now(),floatType:ISt(i?.runtime)}),yc.info("Follower added to sync",{bootstrapId:t,followerCount:this.followers.size}),this.sendSnapshotToFollower(t);const c=this.getConnectedEntries();c.length>0&&r.send({type:"targets.registry",targets:c})}removeFollower(t){const n=this.followers.get(t);if(n){n.keepalive.stop(),n.unsubscribe(),n.sync.close(),this.followers.delete(t);for(const[i,r]of this.runtimeToBootstrap)if(r===t){this.cleanupRemoteTransports(i),this.registry.removeRuntime(i),this.runtimeToBootstrap.delete(i);break}this.registry.hasChanged()&&this.broadcastTargetRegistry(),yc.info("Follower removed from sync",{bootstrapId:t,followerCount:this.followers.size})}}broadcastEvent(t){if(this.followers.size===0)return;const n=this.options.getScoopJid(),i={type:"agent_event",event:t,scoopJid:n};for(const r of this.followers.values())r.sync.send(i)}broadcastUserMessage(t,n){if(this.followers.size===0)return;const i=this.options.getScoopJid(),r={type:"user_message_echo",text:t,messageId:n,scoopJid:i};for(const a of this.followers.values())a.sync.send(r)}broadcastStatus(t){if(this.followers.size===0)return;const n={type:"status",scoopStatus:t};for(const i of this.followers.values())i.sync.send(n)}sendSnapshotToFollower(t){const n=this.followers.get(t);if(!n)return;const i=this.options.getMessages(),r=this.options.getScoopJid();kat(n.sync,i,r),yc.debug("Snapshot sent to follower",{bootstrapId:t,messageCount:i.length})}handleFollowerMessage(t,n){switch(n.type){case"user_message":yc.info("Follower user message received",{bootstrapId:t,messageId:n.messageId}),this.options.onFollowerMessage(n.text,n.messageId);break;case"abort":yc.info("Follower abort received",{bootstrapId:t}),this.options.onFollowerAbort();break;case"request_snapshot":yc.info("Follower snapshot request received",{bootstrapId:t}),this.sendSnapshotToFollower(t);break;case"targets.advertise":{yc.info("Follower targets advertised",{bootstrapId:t,runtimeId:n.runtimeId,targetCount:n.targets.length});for(const i of[...this.remoteTransports.keys()]){const r=i.substring(0,i.indexOf(":"));r!=="leader"&&!this.runtimeToBootstrap.has(r)&&r!==n.runtimeId&&(this.remoteTransports.get(i)?.disconnect(),this.remoteTransports.delete(i),yc.debug("Cleaned up orphaned remote transport on advertise",{key:i}))}this.runtimeToBootstrap.set(n.runtimeId,t),this.registry.setTargets(n.runtimeId,n.targets),this.broadcastTargetRegistry();break}case"cdp.request":{const{requestId:i,targetRuntimeId:r,localTargetId:a,method:l,params:c,sessionId:o}=n;r==="leader"?this.executeLocalCDP(i,a,l,c,o,t):this.forwardCDPRequest(i,r,a,l,c,o,t);break}case"cdp.response":{this.handleCDPResponse(n);break}case"cdp.event":{this.handleCDPEvent(t,n.method,n.params,n.sessionId);break}case"tab.open":{const{requestId:i,targetRuntimeId:r,url:a}=n;r==="leader"?this.executeLocalTabOpen(i,a,t):this.forwardTabOpen(i,r,a,t);break}case"tab.opened":{this.handleTabOpenResponse(n.requestId,n.targetId);break}case"tab.open.error":{this.handleTabOpenError(n.requestId,n.error);break}case"fs.request":{const{requestId:i,targetRuntimeId:r,request:a}=n;r==="leader"?this.executeLocalFs(i,a,t):this.forwardFsRequest(i,r,a,t);break}case"fs.response":{this.handleFsResponse(n.requestId,n.response);break}case"ping":{const i=this.followers.get(t);i&&(i.keepalive.receivePing(),i.lastActivity=Date.now(),i.sync.send({type:"pong"}));break}case"pong":{const i=this.followers.get(t);i&&(i.keepalive.receivePong(),i.lastActivity=Date.now());break}}}setLocalTargets(t){this.registry.setTargets("leader",t),this.registry.hasChanged()&&this.broadcastTargetRegistry()}broadcastTargetRegistry(){if(this.followers.size===0)return;const n={type:"targets.registry",targets:this.getConnectedEntries()};for(const i of this.followers.values())i.sync.send(n)}getTargets(){return this.getConnectedEntries()}getConnectedEntries(){return this.registry.getEntries().filter(t=>{if(t.runtimeId==="leader")return!0;const n=this.runtimeToBootstrap.get(t.runtimeId);return n?this.followers.has(n):!1})}createRemoteTransport(t,n){const i={sendCDPRequest:(a,l,c,o)=>{const s=this.runtimeToBootstrap.get(t),u=s?this.followers.get(s):void 0;if(!u){this.remoteTransports.get(`${t}:${n}`)?.handleResponse(a,void 0,`Target runtime "${t}" not connected`);return}this.pendingCDPRoutes.set(a,{requesterBootstrapId:"__leader__",requestId:a}),u.sync.send({type:"cdp.request",requestId:a,localTargetId:n,method:l,params:c,sessionId:o})}},r=new Wge(i);return this.remoteTransports.set(`${t}:${n}`,r),r}removeRemoteTransport(t,n){const i=`${t}:${n}`,r=this.remoteTransports.get(i);r&&(r.disconnect(),this.remoteTransports.delete(i))}cleanupRemoteTransports(t){const n=`${t}:`;for(const i of[...this.remoteTransports.keys()])i.startsWith(n)&&(this.remoteTransports.get(i)?.disconnect(),this.remoteTransports.delete(i),yc.debug("Cleaned up stale remote transport",{key:i}))}getConnectedFollowers(){return[...this.runtimeToBootstrap.entries()].map(([t,n])=>{const i=this.followers.get(n);return{runtimeId:t,runtime:i?.runtime,connectedAt:i?.connectedAt,lastActivity:i?.lastActivity,floatType:i?.floatType}})}getBestFollowerForTeleport(){const t=[];for(const[r,a]of this.runtimeToBootstrap){const l=this.followers.get(a);l&&t.push({runtimeId:r,bootstrapId:a,floatType:l.floatType,lastActivity:l.lastActivity})}if(t.length===0)return null;const n=t.filter(r=>r.floatType==="standalone"),i=n.length>0?n:t;return i.sort((r,a)=>a.lastActivity-r.lastActivity),i[0]}get hasFollowers(){return this.followers.size>0}stop(){for(const t of[...this.followers.keys()])this.removeFollower(t)}async executeLocalCDP(t,n,i,r,a,l){const c=this.followers.get(l);if(!c)return;const o=this.options.browserTransport;if(!o){c.sync.send({type:"cdp.response",requestId:t,error:"Leader has no browser transport"});return}try{const s=await o.send(i,r,a);QO(c.sync,t,s)}catch(s){c.sync.send({type:"cdp.response",requestId:t,error:s instanceof Error?s.message:String(s)})}}forwardCDPRequest(t,n,i,r,a,l,c){const o=this.runtimeToBootstrap.get(n),s=o?this.followers.get(o):void 0,u=this.followers.get(c);if(!s){u&&u.sync.send({type:"cdp.response",requestId:t,error:`Target runtime "${n}" not connected`});return}this.pendingCDPRoutes.set(t,{requesterBootstrapId:c,requestId:t}),s.sync.send({type:"cdp.request",requestId:t,localTargetId:i,method:r,params:a,sessionId:l})}handleCDPResponse(t){const{requestId:n,result:i,error:r,chunkData:a,chunkIndex:l,totalChunks:c}=t,o=this.pendingCDPRoutes.get(n);if(!o)return;const s=OM(this.cdpChunkBuffers,t);if(!s)return;if(this.pendingCDPRoutes.delete(n),o.requesterBootstrapId==="__leader__"){for(const d of this.remoteTransports.values())d.handleResponse(n,s.result,s.error);return}const u=this.followers.get(o.requesterBootstrapId);u&&QO(u.sync,n,s.result,s.error)}handleCDPEvent(t,n,i,r){let a;for(const[c,o]of this.runtimeToBootstrap)if(o===t){a=c;break}if(!a)return;const l=`${a}:`;for(const[c,o]of this.remoteTransports)c.startsWith(l)&&o.handleEvent(n,i)}openRemoteTab(t,n){const i=this.runtimeToBootstrap.get(t),r=i?this.followers.get(i):void 0;if(!r)return Promise.reject(new Error(`Target runtime "${t}" not connected`));const a=`tab-open-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((l,c)=>{this.tabOpenResolvers.set(a,{resolve:l,reject:c}),this.pendingTabOpenRoutes.set(a,{requesterBootstrapId:"__leader__",requestId:a}),r.sync.send({type:"tab.open",requestId:a,url:n})})}async executeLocalTabOpen(t,n,i){const r=this.followers.get(i);if(!r)return;const a=this.options.browserTransport;if(!a){r.sync.send({type:"tab.open.error",requestId:t,error:"Leader has no browser transport"});return}try{const c=(await a.send("Target.createTarget",{url:n,background:!0})).targetId;r.sync.send({type:"tab.opened",requestId:t,targetId:`leader:${c}`})}catch(l){r.sync.send({type:"tab.open.error",requestId:t,error:l instanceof Error?l.message:String(l)})}}forwardTabOpen(t,n,i,r){const a=this.runtimeToBootstrap.get(n),l=a?this.followers.get(a):void 0,c=this.followers.get(r);if(!l){c&&c.sync.send({type:"tab.open.error",requestId:t,error:`Target runtime "${n}" not connected`});return}this.pendingTabOpenRoutes.set(t,{requesterBootstrapId:r,requestId:t}),l.sync.send({type:"tab.open",requestId:t,url:i})}handleTabOpenResponse(t,n){const i=this.pendingTabOpenRoutes.get(t);if(!i)return;if(this.pendingTabOpenRoutes.delete(t),i.requesterBootstrapId==="__leader__"){const a=this.tabOpenResolvers.get(t);a&&(this.tabOpenResolvers.delete(t),a.resolve(n));return}const r=this.followers.get(i.requesterBootstrapId);r&&r.sync.send({type:"tab.opened",requestId:t,targetId:n})}handleTabOpenError(t,n){const i=this.pendingTabOpenRoutes.get(t);if(!i)return;if(this.pendingTabOpenRoutes.delete(t),i.requesterBootstrapId==="__leader__"){const a=this.tabOpenResolvers.get(t);a&&(this.tabOpenResolvers.delete(t),a.reject(new Error(n)));return}const r=this.followers.get(i.requesterBootstrapId);r&&r.sync.send({type:"tab.open.error",requestId:t,error:n})}async executeLocalFs(t,n,i){const r=this.followers.get(i);if(!r)return;const a=this.options.vfs;if(!a){r.sync.send({type:"fs.response",requestId:t,response:{ok:!1,error:"Leader has no VFS"}});return}const l=await dP(a,n);for(const c of l)r.sync.send({type:"fs.response",requestId:t,response:c})}forwardFsRequest(t,n,i,r){const a=this.runtimeToBootstrap.get(n),l=a?this.followers.get(a):void 0,c=this.followers.get(r);if(!l){c&&c.sync.send({type:"fs.response",requestId:t,response:{ok:!1,error:`Target runtime "${n}" not connected`}});return}this.pendingFsRoutes.set(t,{requesterBootstrapId:r,requestId:t,chunks:[],totalChunks:1}),l.sync.send({type:"fs.request",requestId:t,request:i})}handleFsResponse(t,n){const i=this.pendingFsRoutes.get(t);if(!i){const l=this.fsResolvers.get(t);if(l){l.responses.push(n);const c=n.ok&&n.totalChunks||1;l.responses.length>=c&&(this.fsResolvers.delete(t),l.resolve(l.responses))}return}if(i.requesterBootstrapId==="__leader__"){const l=this.fsResolvers.get(t);if(l){l.responses.push(n);const c=n.ok&&n.totalChunks||1;l.responses.length>=c&&(this.fsResolvers.delete(t),this.pendingFsRoutes.delete(t),l.resolve(l.responses))}return}const r=this.followers.get(i.requesterBootstrapId);r&&r.sync.send({type:"fs.response",requestId:t,response:n}),i.chunks.push(n);const a=n.ok&&n.totalChunks||1;i.totalChunks=a,i.chunks.length>=i.totalChunks&&this.pendingFsRoutes.delete(t)}sendFsRequest(t,n){if(t==="leader"){const l=this.options.vfs;return l?dP(l,n):Promise.resolve([{ok:!1,error:"Leader has no VFS"}])}const i=this.runtimeToBootstrap.get(t),r=i?this.followers.get(i):void 0;if(!r)return Promise.resolve([{ok:!1,error:`Target runtime "${t}" not connected`}]);const a=`fs-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((l,c)=>{this.fsResolvers.set(a,{resolve:l,reject:c,responses:[]}),this.pendingFsRoutes.set(a,{requesterBootstrapId:"__leader__",requestId:a,chunks:[],totalChunks:1}),r.sync.send({type:"fs.request",requestId:a,request:n})})}}const ua=mr("tray-follower-sync");class MSt{constructor(t,n={}){this.options=n,this.sync=Oat(t),this.unsubscribe=this.sync.onMessage(i=>{this.handleLeaderMessage(i)}),this.keepalive=new ySe({sendPing:()=>this.sync.send({type:"ping"}),onDead:()=>{ua.warn("Leader keepalive dead, cleaning up"),this.handleDisconnect("Keepalive timeout — leader not responding"),this.options.onDead?.()}}),this.keepalive.start(),t.addEventListener("close",()=>{ua.warn("Data channel closed"),this.handleDisconnect("Data channel closed")}),t.addEventListener("error",()=>{ua.warn("Data channel error"),this.handleDisconnect("Data channel error")})}sync;eventListeners=new Set;unsubscribe;keepalive;latestSnapshot=null;sentMessageIds=new Set;targetEntries=[];remoteTransports=new Map;cdpChunkBuffers=new Map;snapshotChunkBuffer=null;remoteCDPSessions=new Set;cdpEventCleanups=[];tabOpenResolvers=new Map;fsResolvers=new Map;sendMessage(t,n){const i=n??`follower-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.sentMessageIds.add(i),this.sync.send({type:"user_message",text:t,messageId:i}),ua.info("Sent user message to leader",{messageId:i})}onEvent(t){return this.eventListeners.add(t),()=>this.eventListeners.delete(t)}stop(){this.sync.send({type:"abort"}),ua.info("Sent abort to leader")}requestSnapshot(){this.sync.send({type:"request_snapshot"})}getLatestSnapshot(){return this.latestSnapshot}close(){this.keepalive.stop(),this.unsubscribe(),this.sync.close(),this.eventListeners.clear(),this.cleanupCDPEventForwarding(),ua.info("Follower sync closed")}advertiseTargets(t,n){this.sync.send({type:"targets.advertise",targets:t,runtimeId:n})}getTargets(){return this.targetEntries}disconnected=!1;handleDisconnect(t){if(this.disconnected)return;this.disconnected=!0;const n=lg();yo({...n,state:"error",error:t}),this.emitEvent({type:"error",error:`Connection to leader lost: ${t}`}),this.keepalive.stop(),this.cleanupCDPEventForwarding(),this.unsubscribe(),this.sync.close(),this.options.onDisconnect?.(t)}handleLeaderMessage(t){switch(t.type){case"snapshot":ua.info("Snapshot received from leader",{messageCount:t.messages.length,scoopJid:t.scoopJid}),this.snapshotChunkBuffer=null,this.latestSnapshot={messages:t.messages,scoopJid:t.scoopJid},this.options.onSnapshot?.(t.messages,t.scoopJid);break;case"snapshot_chunk":{const n=Aat(this.snapshotChunkBuffer,t);this.snapshotChunkBuffer=n.buffer,n.result&&(ua.info("Chunked snapshot reassembled from leader",{messageCount:n.result.messages.length,scoopJid:n.result.scoopJid}),this.latestSnapshot=n.result,this.options.onSnapshot?.(n.result.messages,n.result.scoopJid));break}case"agent_event":this.emitEvent(t.event);break;case"user_message_echo":if(this.sentMessageIds.has(t.messageId)){this.sentMessageIds.delete(t.messageId),ua.debug("Skipping own message echo",{messageId:t.messageId});break}ua.info("User message echo received",{messageId:t.messageId,scoopJid:t.scoopJid}),this.options.onUserMessage?.(t.text,t.messageId,t.scoopJid);break;case"status":this.options.onStatus?.(t.scoopStatus);break;case"error":ua.warn("Error from leader",{error:t.error}),this.emitEvent({type:"error",error:t.error});break;case"targets.registry":ua.info("Target registry received from leader",{targetCount:t.targets.length}),this.targetEntries=t.targets,this.options.onTargetsUpdated?.(this.targetEntries);break;case"cdp.request":{const{requestId:n,localTargetId:i,method:r,params:a,sessionId:l}=t;this.executeLocalCDP(n,i,r,a,l);break}case"cdp.response":{this.routeCDPResponse(t);break}case"cdp.event":{for(const n of this.remoteTransports.values())n.handleEvent(t.method,t.params);break}case"tab.open":{this.executeLocalTabOpen(t.requestId,t.url);break}case"tab.opened":{const n=this.tabOpenResolvers.get(t.requestId);n&&(this.tabOpenResolvers.delete(t.requestId),n.resolve(t.targetId));break}case"tab.open.error":{const n=this.tabOpenResolvers.get(t.requestId);n&&(this.tabOpenResolvers.delete(t.requestId),n.reject(new Error(t.error)));break}case"fs.request":{this.executeLocalFs(t.requestId,t.request);break}case"fs.response":{this.routeFsResponse(t.requestId,t.response);break}case"ping":{this.keepalive.receivePing(),this.sync.send({type:"pong"});break}case"pong":{this.keepalive.receivePong(),irt(Date.now());break}}}emitEvent(t){for(const n of this.eventListeners)try{n(t)}catch(i){ua.error("Listener error",{eventType:t.type,error:i instanceof Error?i.message:String(i)})}}createRemoteTransport(t,n){const i={sendCDPRequest:(a,l,c,o)=>{this.sync.send({type:"cdp.request",requestId:a,targetRuntimeId:t,localTargetId:n,method:l,params:c,sessionId:o})}},r=new Wge(i);return this.remoteTransports.set(`${t}:${n}`,r),r}removeRemoteTransport(t,n){const i=`${t}:${n}`,r=this.remoteTransports.get(i);r&&(r.disconnect(),this.remoteTransports.delete(i))}openRemoteTab(t,n){const i=`tab-open-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((r,a)=>{this.tabOpenResolvers.set(i,{resolve:r,reject:a}),this.sync.send({type:"tab.open",requestId:i,targetRuntimeId:t,url:n})})}async executeLocalTabOpen(t,n){const i=this.options.browserTransport;if(!i){this.sync.send({type:"tab.open.error",requestId:t,error:"Follower has no browser transport"});return}try{const a=(await i.send("Target.createTarget",{url:n,background:!0})).targetId;this.sync.send({type:"tab.opened",requestId:t,targetId:a}),this.options.onTargetsChanged?.()}catch(r){this.sync.send({type:"tab.open.error",requestId:t,error:r instanceof Error?r.message:String(r)})}}async executeLocalCDP(t,n,i,r,a){const l=this.options.browserTransport;if(!l){this.sync.send({type:"cdp.response",requestId:t,error:"Follower has no browser transport"});return}try{const c=await l.send(i,r,a);if(i==="Target.attachToTarget"&&c.sessionId){const o=c.sessionId;this.remoteCDPSessions.add(o),this.setupCDPEventForwarding(l,o),ua.debug("Tracking remote CDP session",{remoteSessionId:o})}i==="Target.detachFromTarget"&&a&&this.remoteCDPSessions.has(a)&&(this.remoteCDPSessions.delete(a),ua.debug("Removed remote CDP session on detach",{sessionId:a})),QO(this.sync,t,c)}catch(c){this.sync.send({type:"cdp.response",requestId:t,error:c instanceof Error?c.message:String(c)})}}setupCDPEventForwarding(t,n){const i=["Page.frameNavigated","Page.loadEventFired","Page.domContentEventFired","Network.responseReceived","Network.loadingFinished","Network.requestWillBeSent"];for(const r of i){const a=l=>{if(l.sessionId!==n||!this.remoteCDPSessions.has(n))return;const{sessionId:c,...o}=l;this.sync.send({type:"cdp.event",method:r,params:o,sessionId:n})};t.on(r,a),this.cdpEventCleanups.push(()=>t.off(r,a))}}cleanupCDPEventForwarding(){for(const t of this.cdpEventCleanups)t();this.cdpEventCleanups.length=0,this.remoteCDPSessions.clear()}routeCDPResponse(t){const n=OM(this.cdpChunkBuffers,t);if(n)for(const i of this.remoteTransports.values())i.handleResponse(t.requestId,n.result,n.error)}async executeLocalFs(t,n){const i=this.options.vfs;if(!i){this.sync.send({type:"fs.response",requestId:t,response:{ok:!1,error:"Follower has no VFS"}});return}const r=await dP(i,n);for(const a of r)this.sync.send({type:"fs.response",requestId:t,response:a})}routeFsResponse(t,n){const i=this.fsResolvers.get(t);if(!i)return;i.responses.push(n);const r=n.ok&&n.totalChunks||1;i.responses.length>=r&&(this.fsResolvers.delete(t),i.resolve(i.responses))}sendFsRequest(t,n){const i=`fs-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((r,a)=>{this.fsResolvers.set(i,{resolve:r,reject:a,responses:[]}),this.sync.send({type:"fs.request",requestId:i,targetRuntimeId:t,request:n})})}}const NSt="electron-overlay",Wie="/electron",$St="slicc-electron-overlay:set-tab";function DSt(e,t){if(t)return"extension";try{const n=new URL(e);return LSt(n)?"electron-overlay":"standalone"}catch{return"standalone"}}function jSt(e,t){return e==="electron-overlay"||e==="standalone"&&t}function zie(e){try{const n=new URL(e).searchParams.get("tab");return n&&Oit(n)?n:XX}catch{return XX}}function LSt(e){return e.pathname===Wie||e.pathname===`${Wie}/`||e.searchParams.get("runtime")===NSt}function USt(e){const t=new URL(e);return`${t.protocol==="https:"?"wss:":"ws:"}//${t.host}/licks-ws`}function FSt(e,t){return`${new URL(e).origin}/webhooks/${t}`}function qSt(e,t){const n=e.replace(/\/+$/,""),i=t.replace(/^\/+/,"");return`${n}/${i}`}function BSt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type===$St}const WSt=["/shared/sprinkles"];async function zSt(e){const t=new Map;for(const n of WSt)await e.exists(n)&&await Gie(e,n,t);return await Gie(e,"/",t),t}async function Gie(e,t,n){for await(const i of e.walk(t)){if(!i.endsWith(".shtml"))continue;const r=GSt(i);if(!n.has(r)){let a;try{a=await e.readFile(i,{encoding:"utf-8"})??""}catch{a=""}n.set(r,{name:r,path:i,title:HSt(a,r),autoOpen:VSt(a)})}}}function GSt(e){const t=e.split("/").pop()??e;return t.endsWith(".shtml")?t.slice(0,-6):t}function HSt(e,t){const n=e.match(/data-sprinkle-title=["']([^"']+)["']/);if(n)return n[1];const i=e.match(/<title>([^<]+)<\/title>/i);return i?i[1].trim():t}function VSt(e){return/data-sprinkle-autoopen\b/.test(e)}class JSt{listeners=new Map;lickHandler;fs;closeHandler;constructor(t,n,i){this.fs=t,this.lickHandler=n,this.closeHandler=i}createAPI(t){return{name:t,lick:n=>{const i=typeof n=="string"?n:n.action,r=typeof n=="string"?void 0:n.data,a={type:"sprinkle",sprinkleName:t,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:i,data:r}};this.lickHandler(a)},on:(n,i)=>{const r=`${t}:${n}`;let a=this.listeners.get(r);a||(a=new Set,this.listeners.set(r,a)),a.add(i)},off:(n,i)=>{const r=`${t}:${n}`;this.listeners.get(r)?.delete(i)},readFile:async n=>await this.fs.readFile(n,{encoding:"utf-8"}),setState:n=>{try{localStorage.setItem(`slicc-sprinkle-state:${t}`,JSON.stringify(n))}catch{}},getState:()=>{try{const n=localStorage.getItem(`slicc-sprinkle-state:${t}`);return n?JSON.parse(n):null}catch{return null}},open:n=>{const i=/^https?:|^chrome-extension:/.test(n)?n:H3(n);window.open(i,"_blank")},close:()=>this.closeHandler(t)}}pushUpdate(t,n){const i=`${t}:update`,r=this.listeners.get(i);if(r)for(const a of r)try{a(n)}catch{}}removeSprinkle(t){for(const n of this.listeners.keys())n.startsWith(`${t}:`)&&this.listeners.delete(n)}}const lm=mr("sprinkle-manager"),Hie="slicc-open-sprinkles";class vSe{fs;bridge;callbacks;availableSprinkles=new Map;openSprinkles=new Map;constructor(t,n,i){this.fs=t,this.bridge=new JSt(t,n,r=>this.close(r)),this.callbacks=i}async restoreOpenSprinkles(){try{const t=localStorage.getItem(Hie);if(!t){for(const i of this.availableSprinkles.values())if(i.autoOpen)try{await this.open(i.name)}catch{lm.warn("Failed to auto-open sprinkle",{name:i.name})}return}const n=JSON.parse(t);for(const i of n)try{await this.open(i)}catch{lm.warn("Failed to restore sprinkle",{name:i})}}catch{}}persistOpenSprinkles(){try{localStorage.setItem(Hie,JSON.stringify([...this.openSprinkles.keys()]))}catch{}}async openNewAutoOpenSprinkles(){await this.refresh();for(const t of this.availableSprinkles.values())if(t.autoOpen&&!this.openSprinkles.has(t.name))try{await this.open(t.name),lm.info("Auto-opened new sprinkle after install",{name:t.name})}catch{lm.warn("Failed to auto-open new sprinkle",{name:t.name})}}async refresh(){this.availableSprinkles=await zSt(this.fs),lm.info("Discovered sprinkles",{count:this.availableSprinkles.size})}async open(t,n){if(this.openSprinkles.has(t)){lm.info("Sprinkle already open",{name:t});return}let i=this.availableSprinkles.get(t);if(i||(await this.refresh(),i=this.availableSprinkles.get(t)),!i)throw new Error(`Sprinkle not found: ${t}`);const r=await this.fs.readFile(i.path,{encoding:"utf-8"}),a=document.createElement("div");a.className="sprinkle-panel",a.style.cssText="width: 100%; height: 100%; display: flex; flex-direction: column; overflow: hidden;",a.dataset.sprinkle=t,this.openSprinkles.set(t,{renderer:null,container:a}),this.callbacks.addSprinkle(t,i.title,a,n);const l=this.bridge.createAPI(t),c=new fae(a,l);await c.render(r,t),this.openSprinkles.get(t).renderer=c,this.persistOpenSprinkles(),Y2t(t),lm.info("Sprinkle opened",{name:t,title:i.title})}close(t){const n=this.openSprinkles.get(t);n&&(n.renderer.dispose(),n.container.remove(),this.bridge.removeSprinkle(t),this.openSprinkles.delete(t),this.callbacks.removeSprinkle(t),this.persistOpenSprinkles(),lm.info("Sprinkle closed",{name:t}))}available(){return Array.from(this.availableSprinkles.values())}opened(){return Array.from(this.openSprinkles.keys())}sendToSprinkle(t,n){const i=this.openSprinkles.get(t);if(!i){lm.warn("Cannot send to closed sprinkle",{name:t});return}this.bridge.pushUpdate(t,n),i.renderer.pushUpdate(n)}}const mn=mr("main");function KSt(){const e=document.createElement("div");e.className="skill-drop-overlay";const t=document.createElement("div");t.className="skill-drop-overlay__card";const n=document.createElement("div");n.className="skill-drop-overlay__title",t.appendChild(n);const i=document.createElement("div");return i.className="skill-drop-overlay__desc",t.appendChild(i),e.appendChild(t),document.body.appendChild(e),{show(r,a){n.textContent=r,i.textContent=a,e.classList.add("skill-drop-overlay--visible")},hide(){e.classList.remove("skill-drop-overlay--visible")}}}function bSe(){const e=document.createElement("div");return e.className="skill-drop-toast-container",document.body.appendChild(e),(t,n)=>{const i=document.createElement("div");i.className=`skill-drop-toast skill-drop-toast--${n}`,i.textContent=t,e.appendChild(i),requestAnimationFrame(()=>i.classList.add("skill-drop-toast--visible"));const r=()=>{i.classList.remove("skill-drop-toast--visible"),window.setTimeout(()=>i.remove(),180)};window.setTimeout(r,4200)}}function wSe(e,t,n){const i=KSt();let r=0,a=!1;const l=()=>{r=0,a||i.hide()};window.addEventListener("dragenter",c=>{yQ(c.dataTransfer)&&(c.preventDefault(),r+=1,a||i.show("Drop .skill to install","Unpack into /workspace/skills/{name}."))}),window.addEventListener("dragover",c=>{yQ(c.dataTransfer)&&(c.preventDefault(),c.dataTransfer&&(c.dataTransfer.dropEffect="copy"),a||i.show("Drop .skill to install","Unpack into /workspace/skills/{name}."))}),window.addEventListener("dragleave",()=>{r!==0&&(r=Math.max(0,r-1),r===0&&!a&&i.hide())}),window.addEventListener("dragend",l),window.addEventListener("blur",l),window.addEventListener("drop",async c=>{const o=_at(c.dataTransfer);if(!o){l();return}if(c.preventDefault(),r=0,a){i.hide(),t("Another .skill installation is already in progress.","error");return}a=!0,i.show("Installing skill…",o.name);try{const s=await bat(e,o);await n(),t(`Installed "${s.skillName}" to ${s.destinationPath} (${s.fileCount} files). Run "skill install ${s.skillName}" to apply it.`,"success")}catch(s){const u=s instanceof Error?s.message:String(s);t(`Failed to install dropped skill: ${u}`,"error")}finally{a=!1,i.hide()}})}async function ZSt(e){const{OffscreenClient:t}=await fn(async()=>{const{OffscreenClient:f}=await import("./offscreen-client-PiUvXXMe.js");return{OffscreenClient:f}},[]),{VirtualFS:n}=await fn(async()=>{const{VirtualFS:f}=await Promise.resolve().then(()=>aat);return{VirtualFS:f}},void 0),i=new Q_(e,!0);window.__slicc_debug_tabs=f=>i.setDebugTabs(f),await i.panels.chat.initSession("session-cone");let r=null;const a=await n.create({dbName:"slicc-fs"});i.panels.fileBrowser.setFs(a),mn.info("File browser wired to shared VFS (local IndexedDB)");const l=new BroadcastChannel("preview-vfs");l.onmessage=f=>{if(f.data?.type!=="preview-vfs-read")return;const{id:h,path:m,asText:g}=f.data;(async()=>{try{const y=g?"utf-8":"binary",v=await a.readFile(m,{encoding:y});l.postMessage({type:"preview-vfs-response",id:h,content:v})}catch(y){const v=y instanceof Error?y.message:String(y);v.includes("ENOENT")||mn.error("Preview VFS read failed",{path:m,error:v}),l.postMessage({type:"preview-vfs-response",id:h,error:v})}})()};const c=bSe();wSe(a,c,async()=>{await i.panels.fileBrowser.refresh()});try{const{WasmShell:f}=await fn(async()=>{const{WasmShell:b}=await Promise.resolve().then(()=>iSe);return{WasmShell:b}},void 0),{PanelCdpProxy:h,BrowserAPI:m}=await fn(async()=>{const{PanelCdpProxy:b,BrowserAPI:w}=await import("./index-MTjFRzVr.js");return{PanelCdpProxy:b,BrowserAPI:w}},[]),g=new h;await g.connect();const y=new m(g),v=new f({fs:a,browserAPI:y});await i.panels.terminal.mountShell(v),mn.info("Terminal mounted with shared VFS and BrowserAPI (CDP proxy)")}catch(f){mn.warn("Failed to mount shell to terminal",f)}let o,s=new Set;const u=async f=>{r=f,o.selectedScoopJid=f.jid,i.panels.memory.setSelectedScoop(f.jid),i.setScoopSwitcherSelected?.(f.jid),i.panels.scoops.setSelectedJid(f.jid);const h=f.isCone?"session-cone":`session-${f.folder}`,m=f.isCone?void 0:f.name;await i.panels.chat.switchToContext(h,!f.isCone,m),o.isProcessing(f.jid)&&i.panels.chat.setProcessing(!0)};o=new t({onStatusChange:(f,h)=>{i.panels.scoops.updateScoopStatus(f,h),i.updateScoopSwitcherStatus?.(f,h),r?.jid===f&&(i.setAgentProcessing(h==="processing"),h==="processing"?i.panels.chat.setProcessing(!0):h==="ready"&&i.panels.chat.setProcessing(!1))},onScoopCreated:f=>{i.panels.scoops.refreshScoops(),i.refreshScoopSwitcher?.(),r||(r=f,o.selectedScoopJid=f.jid,i.panels.memory.setSelectedScoop(f.jid))},onScoopListUpdate:()=>{const f=new Set(o.getScoops().map(h=>h.folder));for(const h of s)f.has(h)||i.panels.chat.deleteSessionById(`session-${h}`);if(s=f,i.panels.scoops.refreshScoops(),i.refreshScoopSwitcher?.(),!r){const m=o.getScoops().find(g=>g.isCone);m&&(r=m,o.selectedScoopJid=m.jid,i.panels.memory.setSelectedScoop(m.jid))}},onIncomingMessage:(f,h)=>{if(r?.jid===f){const m=h.channel==="delegation"?`**[Instructions from sliccy]**
14748
14748
 
14749
14749
  ${h.content}`:h.content;i.panels.chat.addUserMessage(m)}},onReady:async()=>{try{mn.info("Offscreen engine ready, scoop count:",o.getScoops().length),window.localStorage.getItem(Tb)&&chrome.runtime.sendMessage({source:"panel",payload:{type:"refresh-tray-runtime"}}).catch(()=>{});const f=r??o.getScoops().find(h=>h.isCone)??o.getScoops()[0];f&&(r=f,o.selectedScoopJid=f.jid,await u(f))}catch(f){mn.error("Failed to initialize on ready",{error:f instanceof Error?f.message:String(f)})}}}),o.setLocalFS(a);const d=o.createAgentHandle();i.panels.chat.setAgent(d),i.panels.scoops.setOrchestrator(o),i.panels.memory.setOrchestrator(o),i.setScoopSwitcherOrchestrator?.(o),i.onScoopSelect=u,i.onModelChange=f=>{localStorage.setItem("selected-model",f),o.updateModel()},i.onClearChat=async()=>{const f=o.getScoops();for(const h of f){const m=h.isCone?"session-cone":`session-${h.folder}`;await i.panels.chat.deleteSessionById(m)}o.clearAllMessages()},i.onClearFilesystem=async()=>{o.clearFilesystem()},i.panels.chat.onInlineSprinkleLick=(f,h)=>{o.sendSprinkleLick("inline",{action:f,data:h})};const p=new vSe(a,f=>{f.type==="sprinkle"&&(f.sprinkleName==="welcome"&&f.body?.action==="onboarding-complete"&&localStorage.setItem("slicc-welcomed","1"),o.sendSprinkleLick(f.sprinkleName,f.body))},{addSprinkle:(f,h,m,g)=>i.addSprinkle(f,h,m,g),removeSprinkle:f=>i.removeSprinkle(f)});if(window.__slicc_sprinkleManager=p,o.setSprinkleOpHandler(f=>{const{id:h,op:m,name:g,data:y}=f;console.log("[main-ext] sprinkle-op handler called",{id:h,op:m,name:g}),(async()=>{try{let v;switch(m){case"list":await p.refresh(),v=p.available();break;case"opened":v=p.opened();break;case"refresh":await p.refresh(),v=p.available().length;break;case"open":await p.open(g),v=!0;break;case"close":p.close(g),v=!0;break;case"send":p.sendToSprinkle(g,y),v=!0;break;case"openNewAutoOpen":await p.openNewAutoOpenSprinkles(),v=!0;break}console.log("[main-ext] sprinkle-op response sending",{id:h,op:m,result:typeof v}),chrome.runtime.sendMessage({source:"panel",payload:{type:"sprinkle-op-response",id:h,result:v}}).catch(()=>{})}catch(v){chrome.runtime.sendMessage({source:"panel",payload:{type:"sprinkle-op-response",id:h,error:v instanceof Error?v.message:String(v)}}).catch(()=>{})}})()}),await p.refresh(),i.onSprinkleClose=f=>p.close(f),i.getAvailableSprinkles=()=>{const f=new Set(p.opened());return p.available().filter(h=>!f.has(h.name)).map(h=>({name:h.name,title:h.title}))},i.onOpenSprinkle=(f,h)=>p.open(f,h),i.updateAddButtons(),await p.restoreOpenSprinkles(),!localStorage.getItem("slicc-welcomed")&&p.available().some(f=>f.name==="welcome"))try{await p.open("welcome")}catch(f){mn.warn("Failed to open welcome sprinkle",f)}mn.info("SprinkleManager initialized (extension mode)"),o.requestState(),mn.info("Extension UI connected to offscreen agent engine"),nSe().catch(()=>{})}async function XSt(){ort(),$it();const e=document.getElementById("app");if(!e)throw new Error("#app element not found");"serviceWorker"in navigator&&navigator.serviceWorker.register("/preview-sw.js",{scope:"/preview/"}).then(()=>mn.info("Preview SW registered")).catch(O=>mn.error("Preview SW registration failed — preview feature will not work",O)),mge();let t=Nb();const n=LO(window.localStorage);if(!t&&!n){const O=window.location.port==="5710"||window.location.port==="3000"||window.location.port==="";await TM({preferTrayJoin:!O}),t=Nb()}const i=!t&&LO(window.localStorage),r=typeof chrome<"u"&&!!chrome?.runtime?.id,a=DSt(window.location.href,r);if(a==="extension")return ZSt(e);const l=new Q_(e,a==="electron-overlay");if(a==="electron-overlay"){const O=zie(window.location.href);l.setActiveTab(O);const j=document.createElement("style");j.id="slicc-electron-overlay-runtime-style",j.textContent=`
14750
14750
  #app > .tab-bar { display: none !important; }
@@ -14756,7 +14756,7 @@ ${h.content}`:h.content;i.panels.chat.addUserMessage(m)}},onReady:async()=>{try{
14756
14756
  }
14757
14757
  `,document.head.appendChild(j),window.addEventListener("message",U=>{U.source===window.parent&&BSt(U.data)&&l.setActiveTab(zie(`http://localhost/?tab=${U.data.tab??""}`))}),window.addEventListener("keydown",U=>{U.code==="Semicolon"&&(U.metaKey||U.ctrlKey)&&!U.shiftKey&&!U.altKey&&!U.repeat&&(U.preventDefault(),U.stopPropagation(),window.parent.postMessage({type:"slicc-electron-overlay:toggle"},"*"))},!0)}const c=bSe();await l.panels.chat.initSession("session-cone"),mn.info("Session initialized");const o=new Tat,s=new Set,u=O=>{mn.debug("Emit to UI",{type:O.type,listenerCount:s.size});for(const j of s)try{j(O)}catch(U){mn.error("Listener error",{eventType:O.type,error:U instanceof Error?U.message:String(U)})}};let d=null;const p=new Map,f=new Map;function h(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function m(O){let j=f.get(O);return j||(j=[],f.set(O,j)),j}function g(O,j){const U=m(O);let G=p.get(O);if(G){const Y=U.find(ye=>ye.id===G);if(Y)return Y}G=`scoop-${O}-${h()}`,p.set(O,G);const J=y.getScoops().find(Y=>Y.jid===O),oe=J?.isCone?"cone":J?.name??"unknown",ce={id:G,role:"assistant",content:"",timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:oe,channel:j};return U.push(ce),d?.jid===O&&u({type:"message_start",messageId:G}),ce}const y=new iSt(l.getIframeContainer(),{onResponse:(O,j,U)=>{const G=g(O);U?G.content+=j:(G.content=j,G.isStreaming=!1),d?.jid===O&&(u({type:"content_delta",messageId:G.id,text:j}),U||u({type:"content_done",messageId:G.id}))},onResponseDone:O=>{const j=m(O),U=p.get(O);if(U){const G=j.find(V=>V.id===U);G&&(G.isStreaming=!1),d?.jid===O&&u({type:"content_done",messageId:U}),p.delete(O)}},onSendMessage:(O,j)=>{mn.debug("Send message requested",{targetJid:O,textLength:j.length});const U=`msg-${h()}`,G={id:U,chatJid:O,senderId:"assistant",senderName:"sliccy",content:j,timestamp:new Date().toISOString(),fromAssistant:!0,channel:"web"};y.handleMessage(G),m(O).push({id:U,role:"assistant",content:j,timestamp:Date.now()}),d?.jid===O&&(u({type:"message_start",messageId:U}),u({type:"content_delta",messageId:U,text:j}),u({type:"content_done",messageId:U}))},onStatusChange:(O,j)=>{if(l.panels.scoops.updateScoopStatus(O,j),l.updateScoopSwitcherStatus?.(O,j),d?.jid===O){if(l.setAgentProcessing(j==="processing"),j==="processing")l.panels.chat.setProcessing(!0);else if(j==="ready"){l.panels.chat.setProcessing(!1);const U=p.get(O)??`done-${O}-${h()}`;p.delete(O),u({type:"turn_end",messageId:U})}}},onError:(O,j)=>{mn.error("Scoop error",{scoopJid:O,error:j}),d?.jid===O&&u({type:"error",error:j})},getBrowserAPI:()=>o,onToolStart:(O,j,U)=>{if(new Set(["send_message","list_scoops","list_tasks"]).has(j))return;const V=g(O);V.toolCalls||(V.toolCalls=[]),V.toolCalls.push({id:h(),name:j,input:U}),d?.jid===O&&u({type:"tool_use_start",messageId:V.id,toolName:j,toolInput:U})},onToolEnd:(O,j,U,G)=>{if(new Set(["send_message","list_scoops","list_tasks"]).has(j))return;const J=m(O),oe=p.get(O);if(oe){const ce=J.find(Y=>Y.id===oe);if(ce?.toolCalls){const Y=[...ce.toolCalls].reverse().find(ye=>ye.name===j&&ye.result===void 0);Y&&(Y.result=U,Y.isError=G)}}d?.jid===O&&oe&&u({type:"tool_result",messageId:oe,toolName:j,result:U,isError:G})},onToolUI:(O,j,U,G)=>{const V=p.get(O);V?u({type:"tool_ui",messageId:V,toolName:j,requestId:U,html:G}):mn.warn("Cannot emit tool_ui - no message ID for scoop",{scoopJid:O,requestId:U})},onToolUIDone:(O,j)=>{const U=p.get(O);U&&u({type:"tool_ui_done",messageId:U,requestId:j})},onIncomingMessage:(O,j)=>{const U={id:j.id,role:"user",content:j.channel==="delegation"?`**[Instructions from sliccy]**
14758
14758
 
14759
- ${j.content}`:j.content,timestamp:new Date(j.timestamp).getTime(),source:j.channel==="delegation"?"delegation":void 0,channel:j.channel};m(O).push(U),d?.jid===O&&(u({type:"message_start",messageId:j.id}),u({type:"content_delta",messageId:j.id,text:U.content}),u({type:"content_done",messageId:j.id}))}});await y.init(),l.panels.scoops.setOrchestrator(y),l.panels.memory.setOrchestrator(y),l.setScoopSwitcherOrchestrator?.(y);const v=y.getSharedFS();if(v){l.panels.fileBrowser.setFs(v),mn.info("File browser wired to shared VFS");const O=new BroadcastChannel("preview-vfs");O.onmessage=j=>{if(j.data?.type!=="preview-vfs-read")return;const{id:U,path:G,asText:V}=j.data;(async()=>{try{const J=V?"utf-8":"binary",oe=await v.readFile(G,{encoding:J});O.postMessage({type:"preview-vfs-response",id:U,content:oe})}catch(J){const oe=J instanceof Error?J.message:String(J);oe.includes("ENOENT")||mn.error("Preview VFS read failed",{path:G,error:oe}),O.postMessage({type:"preview-vfs-response",id:U,error:oe})}})()},wSe(v,(j,U)=>{U==="error"?mn.warn("Dropped skill install failed",{message:j}):mn.info("Dropped skill installed",{message:j}),c(j,U)},async()=>{await l.panels.fileBrowser.refresh()});try{const{WasmShell:j}=await fn(async()=>{const{WasmShell:G}=await Promise.resolve().then(()=>iSe);return{WasmShell:G}},void 0),U=new j({fs:v,browserAPI:o});await l.panels.terminal.mountShell(U),mn.info("Terminal mounted with shared VFS");try{const{BshWatchdog:G}=await fn(async()=>{const{BshWatchdog:J}=await import("./bsh-watchdog-Cm3Aj_S6.js");return{BshWatchdog:J}},[]),V=new G({transport:o.getTransport(),fs:v,execute:J=>U.executeScriptFile(J)});V.start(),window.addEventListener("beforeunload",()=>V.stop(),{once:!0}),mn.info("BSH navigation watchdog started")}catch(G){mn.warn("Failed to start BSH watchdog",G)}}catch(j){mn.warn("Failed to mount shell to terminal",j)}}const b=y.getScoops(),w=b.some(O=>O.isCone);if(i)mn.info("Skipping local cone bootstrap while joining a tray without a configured provider");else if(!w)d=await l.panels.scoops.createScoop("Cone",!0),mn.info("Created cone");else{const j=new URLSearchParams(window.location.search).get("scoop");if(j){const U=b.find(G=>G.folder===j);U?(d=U,mn.info("Restored scoop from URL",{folder:j})):d=b.find(G=>G.isCone)??b[0]}else d=b.find(U=>U.isCone)??b[0]}d&&l.panels.memory.setSelectedScoop(d.jid);let x=null;const C={sendMessage(O,j){if(!d){u({type:"error",error:"No scoop selected"});return}const U={id:j??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:d.jid,senderId:"user",senderName:"User",content:O,timestamp:new Date().toISOString(),fromAssistant:!1,channel:"web"};m(d.jid).push({id:U.id,role:"user",content:O,timestamp:Date.now()}),x?.broadcastUserMessage(O,U.id),y.handleMessage(U),y.createScoopTab(d.jid)},onEvent(O){return s.add(O),()=>s.delete(O)},stop(){d&&(y.stopScoop(d.jid),y.clearQueuedMessages(d.jid).catch(O=>{mn.error("Failed to clear queued messages on stop",{error:O instanceof Error?O.message:String(O)})}))}};l.panels.chat.setAgent(C),l.panels.chat.setDeleteQueuedMessageCallback(O=>{if(d){y.deleteQueuedMessage(d.jid,O).catch(U=>{mn.error("Failed to delete queued message",{messageId:O,error:U instanceof Error?U.message:String(U)})});const j=f.get(d.jid);if(j){const U=j.findIndex(G=>G.id===O);U!==-1&&j.splice(U,1)}}}),mn.info("Cone agent handle wired to chat UI");const{getLickManager:A}=await fn(async()=>{const{getLickManager:O}=await Promise.resolve().then(()=>rSt);return{getLickManager:O}},void 0),M=A();await M.init(),y.setLickManager(M);const N=O=>{const j=O.type==="webhook",U=O.type==="sprinkle",G=j?O.webhookName:U?O.sprinkleName:O.cronName,V=j?O.webhookId:U?O.sprinkleName:O.cronId,J=O.type;mn.debug("Lick event",{type:O.type,name:G,targetScoop:O.targetScoop}),U&&O.sprinkleName==="welcome"&&O.body?.action==="onboarding-complete"&&localStorage.setItem("slicc-welcomed","1");const oe=y.getScoops();let ce;if(U||!O.targetScoop?ce=oe.find(Y=>Y.isCone):ce=oe.find(Y=>Y.name===O.targetScoop||Y.folder===O.targetScoop||Y.folder===`${O.targetScoop}-scoop`),ce){const Y=`${J}-${V}-${Date.now()}`,de=`[${j?"Webhook Event":U?"Sprinkle Event":"Cron Event"}: ${G}]
14759
+ ${j.content}`:j.content,timestamp:new Date(j.timestamp).getTime(),source:j.channel==="delegation"?"delegation":void 0,channel:j.channel};m(O).push(U),d?.jid===O&&(u({type:"message_start",messageId:j.id}),u({type:"content_delta",messageId:j.id,text:U.content}),u({type:"content_done",messageId:j.id}))}});await y.init(),l.panels.scoops.setOrchestrator(y),l.panels.memory.setOrchestrator(y),l.setScoopSwitcherOrchestrator?.(y);const v=y.getSharedFS();if(v){l.panels.fileBrowser.setFs(v),mn.info("File browser wired to shared VFS");const O=new BroadcastChannel("preview-vfs");O.onmessage=j=>{if(j.data?.type!=="preview-vfs-read")return;const{id:U,path:G,asText:V}=j.data;(async()=>{try{const J=V?"utf-8":"binary",oe=await v.readFile(G,{encoding:J});O.postMessage({type:"preview-vfs-response",id:U,content:oe})}catch(J){const oe=J instanceof Error?J.message:String(J);oe.includes("ENOENT")||mn.error("Preview VFS read failed",{path:G,error:oe}),O.postMessage({type:"preview-vfs-response",id:U,error:oe})}})()},wSe(v,(j,U)=>{U==="error"?mn.warn("Dropped skill install failed",{message:j}):mn.info("Dropped skill installed",{message:j}),c(j,U)},async()=>{await l.panels.fileBrowser.refresh()});try{const{WasmShell:j}=await fn(async()=>{const{WasmShell:G}=await Promise.resolve().then(()=>iSe);return{WasmShell:G}},void 0),U=new j({fs:v,browserAPI:o});await l.panels.terminal.mountShell(U),mn.info("Terminal mounted with shared VFS");try{const{BshWatchdog:G}=await fn(async()=>{const{BshWatchdog:J}=await import("./bsh-watchdog-DDiweuEz.js");return{BshWatchdog:J}},[]),V=new G({transport:o.getTransport(),fs:v,execute:J=>U.executeScriptFile(J)});V.start(),window.addEventListener("beforeunload",()=>V.stop(),{once:!0}),mn.info("BSH navigation watchdog started")}catch(G){mn.warn("Failed to start BSH watchdog",G)}}catch(j){mn.warn("Failed to mount shell to terminal",j)}}const b=y.getScoops(),w=b.some(O=>O.isCone);if(i)mn.info("Skipping local cone bootstrap while joining a tray without a configured provider");else if(!w)d=await l.panels.scoops.createScoop("Cone",!0),mn.info("Created cone");else{const j=new URLSearchParams(window.location.search).get("scoop");if(j){const U=b.find(G=>G.folder===j);U?(d=U,mn.info("Restored scoop from URL",{folder:j})):d=b.find(G=>G.isCone)??b[0]}else d=b.find(U=>U.isCone)??b[0]}d&&l.panels.memory.setSelectedScoop(d.jid);let x=null;const C={sendMessage(O,j){if(!d){u({type:"error",error:"No scoop selected"});return}const U={id:j??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:d.jid,senderId:"user",senderName:"User",content:O,timestamp:new Date().toISOString(),fromAssistant:!1,channel:"web"};m(d.jid).push({id:U.id,role:"user",content:O,timestamp:Date.now()}),x?.broadcastUserMessage(O,U.id),y.handleMessage(U),y.createScoopTab(d.jid)},onEvent(O){return s.add(O),()=>s.delete(O)},stop(){d&&(y.stopScoop(d.jid),y.clearQueuedMessages(d.jid).catch(O=>{mn.error("Failed to clear queued messages on stop",{error:O instanceof Error?O.message:String(O)})}))}};l.panels.chat.setAgent(C),l.panels.chat.setDeleteQueuedMessageCallback(O=>{if(d){y.deleteQueuedMessage(d.jid,O).catch(U=>{mn.error("Failed to delete queued message",{messageId:O,error:U instanceof Error?U.message:String(U)})});const j=f.get(d.jid);if(j){const U=j.findIndex(G=>G.id===O);U!==-1&&j.splice(U,1)}}}),mn.info("Cone agent handle wired to chat UI");const{getLickManager:A}=await fn(async()=>{const{getLickManager:O}=await Promise.resolve().then(()=>rSt);return{getLickManager:O}},void 0),M=A();await M.init(),y.setLickManager(M);const N=O=>{const j=O.type==="webhook",U=O.type==="sprinkle",G=j?O.webhookName:U?O.sprinkleName:O.cronName,V=j?O.webhookId:U?O.sprinkleName:O.cronId,J=O.type;mn.debug("Lick event",{type:O.type,name:G,targetScoop:O.targetScoop}),U&&O.sprinkleName==="welcome"&&O.body?.action==="onboarding-complete"&&localStorage.setItem("slicc-welcomed","1");const oe=y.getScoops();let ce;if(U||!O.targetScoop?ce=oe.find(Y=>Y.isCone):ce=oe.find(Y=>Y.name===O.targetScoop||Y.folder===O.targetScoop||Y.folder===`${O.targetScoop}-scoop`),ce){const Y=`${J}-${V}-${Date.now()}`,de=`[${j?"Webhook Event":U?"Sprinkle Event":"Cron Event"}: ${G}]
14760
14760
  \`\`\`json
14761
14761
  ${JSON.stringify(O.body,null,2)}
14762
14762
  \`\`\``,ee={id:Y,chatJid:ce.jid,senderId:J,senderName:`${J}:${G}`,content:de,timestamp:O.timestamp,fromAssistant:!1,channel:J};m(ce.jid).push({id:Y,role:"user",content:de,timestamp:Date.now(),source:"lick",channel:J}),d?.jid===ce.jid&&l.panels.chat.addLickMessage(Y,de,J),mn.info("Routing lick to scoop",{type:J,name:G,scoopJid:ce.jid}),y.handleMessage(ee)}else mn.warn("Lick target scoop not found",{targetScoop:O.targetScoop})};M.setEventHandler(N),l.panels.chat.onInlineSprinkleLick=(O,j)=>{const U={type:"sprinkle",sprinkleName:"inline",targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:O,data:j}};N(U)};let P=null;if(v){if(P=new vSe(v,N,{addSprinkle:(O,j,U,G)=>l.addSprinkle(O,j,U,G),removeSprinkle:O=>l.removeSprinkle(O)}),window.__slicc_sprinkleManager=P,await P.refresh(),l.onSprinkleClose=O=>P.close(O),l.getAvailableSprinkles=()=>{const O=new Set(P.opened());return P.available().filter(j=>!O.has(j.name)).map(j=>({name:j.name,title:j.title}))},l.onOpenSprinkle=(O,j)=>P.open(O,j),l.updateAddButtons(),!localStorage.getItem("slicc-welcomed")&&P.available().some(O=>O.name==="welcome"))try{await P.open("welcome")}catch(O){mn.warn("Failed to open welcome sprinkle",O)}await P.restoreOpenSprinkles(),mn.info("SprinkleManager initialized")}const k=()=>{const O=USt(window.location.href),j=new WebSocket(O);j.onopen=()=>{mn.info("Lick WebSocket connected")},j.onmessage=async U=>{try{const G=JSON.parse(U.data);if(G.requestId){let V;try{switch(G.type){case"list_webhooks":V={type:"response",requestId:G.requestId,data:M.listWebhooks()};break;case"create_webhook":{const J=await M.createWebhook(G.name||"default",G.scoop,G.filter),oe=wT().session,ce=oe?.webhookUrl?qSt(oe.webhookUrl,J.id):FSt(window.location.href,J.id);V={type:"response",requestId:G.requestId,data:{...J,url:ce}};break}case"delete_webhook":{V=await M.deleteWebhook(G.id)?{type:"response",requestId:G.requestId,data:{ok:!0}}:{type:"response",requestId:G.requestId,data:{error:"Webhook not found"}};break}case"list_crontasks":V={type:"response",requestId:G.requestId,data:M.listCronTasks()};break;case"create_crontask":{if(!G.name)throw new Error("name is required");if(!G.cron)throw new Error("cron is required");const J=await M.createCronTask(G.name,G.cron,G.scoop,G.filter);V={type:"response",requestId:G.requestId,data:J};break}case"delete_crontask":{V=await M.deleteCronTask(G.id)?{type:"response",requestId:G.requestId,data:{ok:!0}}:{type:"response",requestId:G.requestId,data:{error:"Cron task not found"}};break}case"tray_status":{const J=wT();V={type:"response",requestId:G.requestId,data:{state:J.state,joinUrl:J.session?.joinUrl??null,workerBaseUrl:J.session?.workerBaseUrl??null,trayId:J.session?.trayId??null}};break}default:V={type:"response",requestId:G.requestId,error:`Unknown request type: ${G.type}`}}}catch(J){V={type:"response",requestId:G.requestId,error:J instanceof Error?J.message:String(J)}}j.send(JSON.stringify(V));return}G.type==="webhook_event"&&M.handleWebhookEvent(G.webhookId,G.headers,G.body)}catch(G){mn.error("Failed to process lick message",{error:G instanceof Error?G.message:String(G)})}},j.onclose=()=>{mn.warn("Lick WebSocket disconnected, reconnecting in 3s..."),setTimeout(k,3e3)},j.onerror=U=>{mn.error("Lick WebSocket error",{error:String(U)})}};k(),l.onModelChange=O=>{localStorage.setItem("selected-model",O),y.updateModel()},l.onClearChat=async()=>{await y.clearAllMessages(),f.clear()},l.onClearFilesystem=async()=>{await y.resetFilesystem()};const $=async O=>{mn.info("Scoop selected",{jid:O.jid,name:O.name}),d=O,y.createScoopTab(O.jid),l.panels.memory.setSelectedScoop(O.jid),l.panels.scoops.setSelectedJid(O.jid);const j=O.isCone?"session-cone":`session-${O.folder}`,U=f.get(O.jid),G=O.isCone?void 0:O.name;if(U&&U.length>0)await l.panels.chat.switchToContext(j,!O.isCone,G),l.panels.chat.loadMessages(U);else if(await l.panels.chat.switchToContext(j,!O.isCone,G),l.panels.chat.getMessages().length===0){const V=await y.getMessagesForScoop(O.jid);for(const J of V){const oe=J.channel==="webhook"||J.channel==="cron",ce=J.channel==="delegation";if(oe){const Y={id:J.id,role:"user",content:J.content,timestamp:new Date(J.timestamp).getTime(),source:"lick",channel:J.channel};m(O.jid).push(Y),l.panels.chat.addUserMessage(J.content)}else if(ce){const Y={id:J.id,role:"user",content:`**[Instructions from sliccy]**