sliccy 1.0.2 → 1.0.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-9crYr7pn.js","assets/stream-lEC9OYG2.js","assets/index-DJA4jgWl.js","assets/___vite-browser-external_commonjs-proxy-DI43bbQw.js","assets/__vite-browser-external-D7Ct-6yo.js","assets/index-bo18OtLo.js","assets/sql-wasm-8C3CnQsV.js","assets/index-xzVzlu9M.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-COWGW4FB.js","assets/stream-lEC9OYG2.js","assets/index-Cg4KUhhA.js","assets/___vite-browser-external_commonjs-proxy-C4US5Rir.js","assets/__vite-browser-external-D7Ct-6yo.js","assets/index-BQQ3oExA.js","assets/sql-wasm-D66sddMs.js","assets/index-CJv-O0EK.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 o of a.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).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 i6e="modulepreload",a6e=function(e){return"/"+e},yq={},Tn=function(t,n,i){let r=Promise.resolve();if(n&&n.length>0){let o=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]"),l=c?.nonce||c?.getAttribute("nonce");r=o(n.map(s=>{if(s=a6e(s),s in yq)return;yq[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":i6e,u||(p.as="script"),p.crossOrigin="",p.href=s,l&&p.setAttribute("nonce",l),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(o){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=o,window.dispatchEvent(c),!c.defaultPrevented)throw o}return r.then(o=>{for(const c of o||[])c.status==="rejected"&&a(c.reason);return t().catch(a)})};function M8(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var qv=M8();function hde(e){qv=e}var ov={exec:()=>null};function cr(e,t=""){let n=typeof e=="string"?e:e.source,i={replace:(r,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(Fa.caret,"$1"),n=n.replace(r,o),i},getRegex:()=>new RegExp(n,t)};return i}var s6e=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),Fa={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)}}>`)},o6e=/^(?:[ \t]*(?:\n|$))+/,l6e=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,c6e=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,P2=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,u6e=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,N8=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,mde=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,gde=cr(mde).replace(/bull/g,N8).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(),d6e=cr(mde).replace(/bull/g,N8).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(),$8=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,p6e=/^[^\n]+/,D8=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,f6e=cr(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",D8).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),h6e=cr(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,N8).getRegex(),VA="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",j8=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,m6e=cr("^ {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",j8).replace("tag",VA).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),yde=cr($8).replace("hr",P2).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",VA).getRegex(),g6e=cr(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",yde).getRegex(),L8={blockquote:g6e,code:l6e,def:f6e,fences:c6e,heading:u6e,hr:P2,html:m6e,lheading:gde,list:h6e,newline:o6e,paragraph:yde,table:ov,text:p6e},vq=cr("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",P2).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",VA).getRegex(),y6e={...L8,lheading:d6e,table:vq,paragraph:cr($8).replace("hr",P2).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",vq).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",VA).getRegex()},v6e={...L8,html:cr(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",j8).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:ov,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:cr($8).replace("hr",P2).replace("heading",` *#{1,6} *[^
3
3
  ]`).replace("lheading",gde).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},b6e=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,w6e=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,vde=/^( {2,}|\\)\n(?!\s*$)/,_6e=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,JA=/[\p{P}\p{S}]/u,F8=/[\s\p{P}\p{S}]/u,bde=/[^\s\p{P}\p{S}]/u,x6e=cr(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,F8).getRegex(),wde=/(?!~)[\p{P}\p{S}]/u,S6e=/(?!~)[\s\p{P}\p{S}]/u,T6e=/(?:[^\s\p{P}\p{S}]|~)/u,_de=/(?![*_])[\p{P}\p{S}]/u,C6e=/(?![*_])[\s\p{P}\p{S}]/u,E6e=/(?:[^\s\p{P}\p{S}]|[*_])/u,A6e=cr(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",s6e?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),xde=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,k6e=cr(xde,"u").replace(/punct/g,JA).getRegex(),R6e=cr(xde,"u").replace(/punct/g,wde).getRegex(),Sde="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",O6e=cr(Sde,"gu").replace(/notPunctSpace/g,bde).replace(/punctSpace/g,F8).replace(/punct/g,JA).getRegex(),I6e=cr(Sde,"gu").replace(/notPunctSpace/g,T6e).replace(/punctSpace/g,S6e).replace(/punct/g,wde).getRegex(),P6e=cr("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,bde).replace(/punctSpace/g,F8).replace(/punct/g,JA).getRegex(),M6e=cr(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,_de).getRegex(),N6e="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",$6e=cr(N6e,"gu").replace(/notPunctSpace/g,E6e).replace(/punctSpace/g,C6e).replace(/punct/g,_de).getRegex(),D6e=cr(/\\(punct)/,"gu").replace(/punct/g,JA).getRegex(),j6e=cr(/^<(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(),L6e=cr(j8).replace("(?:-->|$)","-->").getRegex(),F6e=cr("^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",L6e).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),f3=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,U6e=cr(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",f3).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Tde=cr(/^!?\[(label)\]\[(ref)\]/).replace("label",f3).replace("ref",D8).getRegex(),Cde=cr(/^!?\[(ref)\](?:\[\])?/).replace("ref",D8).getRegex(),q6e=cr("reflink|nolink(?!\\()","g").replace("reflink",Tde).replace("nolink",Cde).getRegex(),bq=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,U8={_backpedal:ov,anyPunctuation:D6e,autolink:j6e,blockSkip:A6e,br:vde,code:w6e,del:ov,delLDelim:ov,delRDelim:ov,emStrongLDelim:k6e,emStrongRDelimAst:O6e,emStrongRDelimUnd:P6e,escape:b6e,link:U6e,nolink:Cde,punctuation:x6e,reflink:Tde,reflinkSearch:q6e,tag:F6e,text:_6e,url:ov},B6e={...U8,link:cr(/^!?\[(label)\]\((.*?)\)/).replace("label",f3).getRegex(),reflink:cr(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",f3).getRegex()},rP={...U8,emStrongRDelimAst:I6e,emStrongLDelim:R6e,delLDelim:M6e,delRDelim:$6e,url:cr(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",bq).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:cr(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",bq).getRegex()},W6e={...rP,br:cr(vde).replace("{2,}","*").getRegex(),text:cr(rP.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},DS={normal:L8,gfm:y6e,pedantic:v6e},jw={normal:U8,gfm:rP,breaks:W6e,pedantic:B6e},z6e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},wq=e=>z6e[e];function Jc(e,t){if(t){if(Fa.escapeTest.test(e))return e.replace(Fa.escapeReplace,wq)}else if(Fa.escapeTestNoEncode.test(e))return e.replace(Fa.escapeReplaceNoEncode,wq);return e}function _q(e){try{e=encodeURI(e).replace(Fa.percentDecode,"%")}catch{return null}return e}function xq(e,t){let n=e.replace(Fa.findPipe,(a,o,c)=>{let l=!1,s=o;for(;--s>=0&&c[s]==="\\";)l=!l;return l?"|":" |"}),i=n.split(Fa.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(Fa.slashPipe,"|");return i}function Lw(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 G6e(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 H6e(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 Sq(e,t,n,i,r){let a=t.href,o=t.title||null,c=e[1].replace(r.other.outputLinkReplace,"$1");i.state.inLink=!0;let l={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:a,title:o,text:c,tokens:i.inlineTokens(c)};return i.state.inLink=!1,l}function V6e(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 o=a.match(n.other.beginningSpace);if(o===null)return a;let[c]=o;return c.length>=r.length?a.slice(r.length):a}).join(`
@@ -850,7 +850,7 @@ ${o}`),i.push({type:"error",reason:r.stopReason,error:r}),i.end()}})(),i},CFe=(e
850
850
  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 Pv(a);if(r==="hex")return ss(a);if(r===void 0||r==="utf8"||r==="utf-8")return rw(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(Lz);if(t=!0,Fz(e))return i(e);if(Dz(e))return e;throw new Error(`Cannot transform payload to web stream, got ${e}`)}})},Fz=e=>typeof Blob=="function"&&e instanceof Blob,cx=async(e=new Uint8Array,t)=>{if(e instanceof Uint8Array)return bv.mutate(e);if(!e)return bv.mutate(new Uint8Array);const n=t.streamCollector(e);return bv.mutate(await n)};function Uz(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}const u9=e=>typeof e=="function"?e():e,Pme=(e,t,n,i,r)=>({name:t,namespace:e,traits:n,input:i,output:r}),wUe=e=>(t,n)=>async i=>{const{response:r}=await t(i),{operationSchema:a}=nw(n),[,o,c,l,s,u]=a??[];try{const d=await e.protocol.deserializeResponse(Pme(o,c,l,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+=`
851
851
  `+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(Rv.isInstance(r)){const{headers:f={}}=r,h=Object.entries(f);d.$metadata={httpStatusCode:r.statusCode,requestId:d9(/^x-[\w-]+-request-?id$/,h),extendedRequestId:d9(/^x-[\w-]+-id-2$/,h),cfId:d9(/^x-[\w-]+-cf-id$/,h)}}}catch{}}throw d}},d9=(e,t)=>(t.find(([n])=>n.match(e))||[void 0,void 0])[1],_Ue=e=>(t,n)=>async i=>{const{operationSchema:r}=nw(n),[,a,o,c,l,s]=r??[],u=n.endpointV2?.url&&e.urlParser?async()=>e.urlParser(n.endpointV2.url):e.endpoint,d=await e.protocol.serializeRequest(Pme(a,o,c,l,s),i.input,{...e,...n,endpoint:u});return t({...i,request:d})},xUe={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},SUe={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function TUe(e){return{applyToStack:t=>{t.add(_Ue(e),SUe),t.add(wUe(e),xUe),e.protocol.setSerdeContext(e)}}}function p0(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 qz={it:Symbol.for("@smithy/nor-struct-it")};class Gr{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=Gr.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;p9(r);)i.push(r[1]),r=r[0],a=u9(r),this._isMemberSchema=!0;if(i.length>0){this.memberTraits={};for(let o=i.length-1;o>=0;--o){const c=i[o];Object.assign(this.memberTraits,p0(c))}}else this.memberTraits=0;if(a instanceof Gr){const o=this.memberTraits;Object.assign(this,a),this.memberTraits=Object.assign({},o,a.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=n??a.memberName;return}if(this.schema=u9(a),CUe(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=u9(t);if(n instanceof Gr)return n;if(p9(n)){const[i,r]=n;if(i instanceof Gr)return Object.assign(i.getMergedTraits(),p0(r)),i;throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(t,null,2)}.`)}return new Gr(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 p0(this.memberTraits)}getOwnTraits(){return p0(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 h1([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 h1([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 h1(p9(r)?r:[r,0],t)}if(this.isDocumentSchema())return h1([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[qz.it];if(i&&n===i.length){yield*i;return}i=Array(n);for(let r=0;r<n;++r){const a=t[4][r],o=h1([t[5][r],0],a);yield i[r]=[a,o]}t[qz.it]=i}}function h1(e,t){if(e instanceof Gr)return Object.assign(e,{memberName:t,_isMemberSchema:!0});const n=Gr;return new n(e,t)}const p9=e=>Array.isArray(e)&&e.length===2,CUe=e=>Array.isArray(e)&&e.length>=5;class is{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 is.registries.has(t)||is.registries.set(t,new is(t)),is.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,is.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,is.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):is.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 cM=e=>{if(e!=null){if(typeof e=="string"){const t=parseFloat(e);if(!Number.isNaN(t))return String(t)!==String(e)&&NUe.warn(MUe(`Expected number but observed string: ${e}`)),t}if(typeof e=="number")return e;throw new TypeError(`Expected number, got ${typeof e}: ${e}`)}},EUe=Math.ceil(2**127*(2-2**-23)),Bz=e=>{const t=cM(e);if(t!==void 0&&!Number.isNaN(t)&&t!==1/0&&t!==-1/0&&Math.abs(t)>EUe)throw new TypeError(`Expected 32-bit float, got ${e}`);return t},AUe=e=>{if(e!=null){if(Number.isInteger(e)&&!Number.isNaN(e))return e;throw new TypeError(`Expected integer, got ${typeof e}: ${e}`)}},Wz=e=>Mme(e,16),zz=e=>Mme(e,8),Mme=(e,t)=>{const n=AUe(e);if(n!==void 0&&kUe(n,t)!==n)throw new TypeError(`Expected ${t}-bit integer, got ${e}`);return n},kUe=(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]}},RUe=e=>cM(typeof e=="string"?vk(e):e),OUe=e=>Bz(typeof e=="string"?vk(e):e),IUe=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,vk=e=>{const t=e.match(IUe);if(t===null||t[0].length!==e.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(e)},L3=e=>Wz(typeof e=="string"?vk(e):e),PUe=e=>zz(typeof e=="string"?vk(e):e),MUe=e=>String(new TypeError(e).stack||e).split(`
852
852
  `).slice(0,5).filter(t=>!t.includes("stackTraceWarning")).join(`
853
- `),NUe={warn:console.warn},$Ue=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],U7=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Nme(e){const t=e.getUTCFullYear(),n=e.getUTCMonth(),i=e.getUTCDay(),r=e.getUTCDate(),a=e.getUTCHours(),o=e.getUTCMinutes(),c=e.getUTCSeconds(),l=r<10?`0${r}`:`${r}`,s=a<10?`0${a}`:`${a}`,u=o<10?`0${o}`:`${o}`,d=c<10?`0${c}`:`${c}`;return`${$Ue[i]}, ${l} ${U7[n]} ${t} ${s}:${u}:${d} GMT`}const DUe=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),jUe=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");const t=DUe.exec(e);if(!t)throw new TypeError("Invalid RFC-3339 date-time value");const[n,i,r,a,o,c,l,s,u]=t,d=L3(o2(i)),p=Xg(r,"month",1,12),f=Xg(a,"day",1,31),h=yE(d,p,f,{hours:o,minutes:c,seconds:l,fractionalMilliseconds:s});return u.toUpperCase()!="Z"&&h.setTime(h.getTime()-XUe(u)),h},LUe=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$/),FUe=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$/),UUe=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})$/),qUe=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let t=LUe.exec(e);if(t){const[n,i,r,a,o,c,l,s]=t;return yE(L3(o2(a)),f9(r),Xg(i,"day",1,31),{hours:o,minutes:c,seconds:l,fractionalMilliseconds:s})}if(t=FUe.exec(e),t){const[n,i,r,a,o,c,l,s]=t;return GUe(yE(WUe(a),f9(r),Xg(i,"day",1,31),{hours:o,minutes:c,seconds:l,fractionalMilliseconds:s}))}if(t=UUe.exec(e),t){const[n,i,r,a,o,c,l,s]=t;return yE(L3(o2(s)),f9(i),Xg(r.trimLeft(),"day",1,31),{hours:a,minutes:o,seconds:c,fractionalMilliseconds:l})}throw new TypeError("Invalid RFC-7231 date-time value")},BUe=e=>{if(e==null)return;let t;if(typeof e=="number")t=e;else if(typeof e=="string")t=RUe(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))},yE=(e,t,n,i)=>{const r=t-1;return VUe(e,r,n),new Date(Date.UTC(e,r,n,Xg(i.hours,"hour",0,23),Xg(i.minutes,"minute",0,59),Xg(i.seconds,"seconds",0,60),KUe(i.fractionalMilliseconds)))},WUe=e=>{const t=new Date().getUTCFullYear(),n=Math.floor(t/100)*100+L3(o2(e));return n<t?n+100:n},zUe=50*365*24*60*60*1e3,GUe=e=>e.getTime()-new Date().getTime()>zUe?new Date(Date.UTC(e.getUTCFullYear()-100,e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())):e,f9=e=>{const t=U7.indexOf(e);if(t<0)throw new TypeError(`Invalid month: ${e}`);return t+1},HUe=[31,28,31,30,31,30,31,31,30,31,30,31],VUe=(e,t,n)=>{let i=HUe[t];if(t===1&&JUe(e)&&(i=29),n>i)throw new TypeError(`Invalid day for ${U7[t]} in ${e}: ${n}`)},JUe=e=>e%4===0&&(e%100!==0||e%400===0),Xg=(e,t,n,i)=>{const r=PUe(o2(e));if(r<n||r>i)throw new TypeError(`${t} must be between ${n} and ${i}, inclusive`);return r},KUe=e=>e==null?0:OUe("0."+e)*1e3,XUe=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},o2=e=>{let t=0;for(;t<e.length-1&&e.charAt(t)==="0";)t++;return t===0?e:e.slice(t)},Gz=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ga=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0")),q7=()=>{if(Gz)return Gz();const e=new Uint8Array(16);return crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128,ga[e[0]]+ga[e[1]]+ga[e[2]]+ga[e[3]]+"-"+ga[e[4]]+ga[e[5]]+"-"+ga[e[6]]+ga[e[7]]+"-"+ga[e[8]]+ga[e[9]]+"-"+ga[e[10]]+ga[e[11]]+ga[e[12]]+ga[e[13]]+ga[e[14]]+ga[e[15]]},du=function(t){return Object.assign(new String(t),{deserializeJSON(){return JSON.parse(String(t))},toString(){return String(t)},toJSON(){return String(t)}})};du.from=e=>e&&typeof e=="object"&&(e instanceof du||"deserializeJSON"in e)?e:typeof e=="string"||Object.getPrototypeOf(e)===String.prototype?du(String(e)):du(JSON.stringify(e));du.fromObject=du.from;function ZUe(e){return(e.includes(",")||e.includes('"'))&&(e=`"${e.replace(/"/g,'\\"')}"`),e}const B7="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",W7="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",z7="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",$me="(\\d?\\d)",Dme="(\\d{4})",YUe=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),QUe=new RegExp(`^${B7}, ${$me} ${W7} ${Dme} ${z7} GMT$`),eqe=new RegExp(`^${B7}, ${$me}-${W7}-(\\d\\d) ${z7} GMT$`),tqe=new RegExp(`^${B7} ${W7} ( [1-9]|\\d\\d) ${z7} ${Dme}$`),nqe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],rqe=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))},iqe=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC3339 timestamps must be strings");const t=YUe.exec(e);if(!t)throw new TypeError(`Invalid RFC3339 timestamp format ${e}`);const[,n,i,r,a,o,c,,l,s]=t;Qm(i,1,12),Qm(r,1,31),Qm(a,0,23),Qm(o,0,59),Qm(c,0,60);const u=new Date(Date.UTC(Number(n),Number(i)-1,Number(r),Number(a),Number(o),Number(c),Number(l)?Math.round(parseFloat(`0.${l}`)*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},aqe=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC7231 timestamps must be strings.");let t,n,i,r,a,o,c,l;if((l=QUe.exec(e))?[,t,n,i,r,a,o,c]=l:(l=eqe.exec(e))?([,t,n,i,r,a,o,c]=l,i=(Number(i)+1900).toString()):(l=tqe.exec(e))&&([,n,t,r,a,o,c,i]=l),i&&o){const s=Date.UTC(Number(i),nqe.indexOf(n),Number(t),Number(r),Number(a),Number(o),c?Math.round(parseFloat(`0.${c}`)*1e3):0);Qm(t,1,31),Qm(r,0,23),Qm(a,0,59),Qm(o,0,60);const u=new Date(s);return u.setUTCFullYear(Number(i)),u}throw new TypeError(`Invalid RFC7231 date-time value ${e}.`)};function Qm(e,t,n){const i=Number(e);if(i<t||i>n)throw new Error(`Value ${i} out of range [${t}, ${n}]`)}function sqe(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 o=0;o<i.length;o++)a===""?a=i[o]:a+=t+i[o],(o+1)%n===0&&(r.push(a),a="");return a!==""&&r.push(a),r}const jme=e=>{const t=e.length,n=[];let i=!1,r,a=0;for(let o=0;o<t;++o){const c=e[o];switch(c){case'"':r!=="\\"&&(i=!i);break;case",":i||(n.push(e.slice(a,o)),a=o+1);break}r=c}return n.push(e.slice(a)),n.map(o=>{o=o.trim();const c=o.length;return c<2?o:(o[0]==='"'&&o[c-1]==='"'&&(o=o.slice(1,c-1)),o.replace(/\\"/g,'"'))})},Hz=/^-?\d*(\.\d+)?$/;class Xo{string;type;constructor(t,n){if(this.string=t,this.type=n,!Hz.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 Xo.prototype.isPrototypeOf(t)||n.type==="bigDecimal"&&Hz.test(n.string)}}class bk{serdeContext;setSerdeContext(t){this.serdeContext=t}}class oqe extends bk{options;compositeErrorRegistry;constructor(t){super(),this.options=t,this.compositeErrorRegistry=is.for(t.defaultNamespace);for(const n of t.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(n)}getRequestType(){return Ga}getResponseType(){return Rv}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=Gr.of(n.input),a=p0(n.traits??{});if(a.endpoint){let o=a.endpoint?.[0];if(typeof o=="string"){const c=[...r.structIterator()].filter(([,l])=>l.getMergedTraits().hostLabel);for(const[l]of c){const s=i[l];if(typeof s!="string")throw new Error(`@smithy/core/schema - ${l} in input must be a string as hostLabel.`);o=o.replace(`{${l}}`,s)}t.hostname=o+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 Tn(async()=>{const{EventStreamSerde:n}=await import("./index-COMQCYh-.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 lqe extends oqe{async serializeRequest(t,n,i){const r={...n??{}},a=this.serializer,o={},c={},l=await i.endpoint(),s=Gr.of(t?.input),u=[],d=[];let p=!1,f;const h=new Ga({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:o,headers:c,body:void 0});if(l){this.updateServiceEndpoint(h,l),this.setHostPrefix(h,t,r);const m=p0(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(o,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(Uz).join("/")):h.path.includes(`{${m}}`)&&(h.path=h.path.replace(`{${m}}`,Uz(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 _=y.httpPrefixHeaders+b;a.write([g.getValueSchema(),{httpHeader:_}],w),c[_.toLowerCase()]=a.flush()}delete r[m]}else y.httpQuery||y.httpQueryParams?(this.serializeQuery(g,v,o),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=o,h.body=f,h}serializeQuery(t,n,i){const r=this.serializer,a=t.getMergedTraits();if(a.httpQueryParams){for(const[o,c]of Object.entries(n))if(!(o in i)){const l=t.getValueSchema();Object.assign(l.getMergedTraits(),{...a,httpQuery:o,httpQueryParams:void 0}),this.serializeQuery(l,c,i)}return}if(t.isListSchema()){const o=!!t.getMergedTraits().sparse,c=[];for(const l of n){r.write([t.getValueSchema(),a],l);const s=r.flush();(o||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=Gr.of(t.output),o={};if(i.statusCode>=300){const l=await cx(i.body,n);throw l.byteLength>0&&Object.assign(o,await r.read(15,l)),await this.handleError(t,n,i,o,this.deserializeMetadata(i)),new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(const l in i.headers){const s=i.headers[l];delete i.headers[l],i.headers[l.toLowerCase()]=s}const c=await this.deserializeHttpMessage(a,n,i,o);if(c.length){const l=await cx(i.body,n);if(l.byteLength>0){const s=await r.read(a,l);for(const u of c)s[u]!=null&&(o[u]=s[u])}}else c.discardResponseBody&&await cx(i.body,n);return o.$metadata=this.deserializeMetadata(i),o}async deserializeHttpMessage(t,n,i,r,a){let o;r instanceof Set?o=a:o=r;let c=!0;const l=this.deserializer,s=Gr.of(t),u=[];for(const[d,p]of s.structIterator()){const f=p.getMemberTraits();if(f.httpPayload){if(c=!1,p.isStreaming())p.isStructSchema()?o[d]=await this.deserializeEventStream({response:i,responseSchema:s}):o[d]=bUe(i.body);else if(i.body){const m=await cx(i.body,n);m.byteLength>0&&(o[d]=await l.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=sqe(m,",",2):y=jme(m);const v=[];for(const b of y)v.push(await l.read(g,b.trim()));o[d]=v}else o[d]=await l.read(p,m)}else if(f.httpPrefixHeaders!==void 0){o[d]={};for(const[h,m]of Object.entries(i.headers))if(h.startsWith(f.httpPrefixHeaders)){const g=p.getValueSchema();g.getMergedTraits().httpHeader=h,o[d][h.slice(f.httpPrefixHeaders.length)]=await l.read(g,m)}}else f.httpResponseCode?o[d]=i.statusCode:u.push(d)}return u.discardResponseBody=c,u}}function wk(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 cqe extends bk{settings;constructor(t){super(),this.settings=t}read(t,n){const i=Gr.of(t);if(i.isListSchema())return jme(n).map(r=>this.read(i.getValueSchema(),r));if(i.isBlobSchema())return(this.serdeContext?.base64Decoder??Ov)(n);if(i.isTimestampSchema())switch(wk(i,this.settings)){case 5:return iqe(n);case 6:return aqe(n);case 7:return rqe(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=du.from(a)),a}return i.isNumericSchema()?Number(n):i.isBigIntegerSchema()?BigInt(n):i.isBigDecimalSchema()?new Xo(n,"bigDecimal"):i.isBooleanSchema()?String(n).toLowerCase()==="true":n}base64ToUtf8(t){return(this.serdeContext?.utf8Encoder??rw)((this.serdeContext?.base64Decoder??Ov)(t))}}class uqe extends bk{codecDeserializer;stringDeserializer;constructor(t,n){super(),this.codecDeserializer=t,this.stringDeserializer=new cqe(n)}setSerdeContext(t){this.stringDeserializer.setSerdeContext(t),this.codecDeserializer.setSerdeContext(t),this.serdeContext=t}read(t,n){const i=Gr.of(t),r=i.getMergedTraits(),a=this.serdeContext?.utf8Encoder??rw;if(r.httpHeader||r.httpResponseCode)return this.stringDeserializer.read(i,a(n));if(r.httpPayload){if(i.isBlobSchema()){const o=this.serdeContext?.utf8Decoder??Iv;return typeof n=="string"?o(n):n}else if(i.isStringSchema())return"byteLength"in n?a(n):n}return this.codecDeserializer.read(i,n)}}class dqe extends bk{settings;stringBuffer="";constructor(t){super(),this.settings=t}write(t,n){const i=Gr.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(wk(i,this.settings)){case 5:this.stringBuffer=n.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=Nme(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??Pv)(n);return}if(i.isListSchema()&&Array.isArray(n)){let o="";for(const c of n){this.write([i.getValueSchema(),i.getMergedTraits()],c);const l=this.flush(),s=i.getValueSchema().isTimestampSchema()?l:ZUe(l);o!==""&&(o+=", "),o+=s}this.stringBuffer=o;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=du.from(a)),i.getMergedTraits().httpHeader)){this.stringBuffer=(this.serdeContext?.base64Encoder??Pv)(a.toString());return}this.stringBuffer=n;break;default:i.isIdempotencyToken()?this.stringBuffer=q7():this.stringBuffer=String(n)}}flush(){const t=this.stringBuffer;return this.stringBuffer="",t}}class pqe{codecSerializer;stringSerializer;buffer;constructor(t,n,i=new dqe(n)){this.codecSerializer=t,this.stringSerializer=i}setSerdeContext(t){this.codecSerializer.setSerdeContext(t),this.stringSerializer.setSerdeContext(t)}write(t,n){const i=Gr.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 fqe(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 hqe{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 mqe{async sign(t,n,i){const r=Ga.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 gqe=e=>function(n){return G7(n)&&n.expiration.getTime()-Date.now()<e},yqe=3e5,Lme=gqe(yqe),G7=e=>e.expiration!==void 0,Fme=(e,t,n)=>{if(e===void 0)return;const i=typeof e!="function"?async()=>Promise.resolve(e):e;let r,a,o,c=!1;const l=async s=>{a||(a=i(s));try{r=await a,o=!0,c=!1}finally{a=void 0}return r};return t===void 0?async s=>((!o||s?.forceRefresh)&&(r=await l(s)),r):async s=>((!o||s?.forceRefresh)&&(r=await l(s)),c?r:n(r)?(t(r)&&await l(s),r):(c=!0,r))},vqe=void 0;function bqe(e){return e===void 0?!0:typeof e=="string"&&e.length<=50}function wqe(e){const t=$x(e.userAgentAppId??vqe),{customUserAgent:n}=e;return Object.assign(e,{customUserAgent:typeof n=="string"?[[n]]:n,userAgentAppId:async()=>{const i=await t();if(!bqe(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 _qe{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:o,done:c}=r.next();if(this.data.delete(o),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 xqe=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}$"),Ume=e=>xqe.test(e)||e.startsWith("[")&&e.endsWith("]"),Sqe=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),_k=(e,t=!1)=>{if(!t)return Sqe.test(e);const n=e.split(".");for(const i of n)if(!_k(i))return!1;return!0},F3={},l2="endpoints";function iy(e){return typeof e!="object"||e==null?e:"ref"in e?`$${iy(e.ref)}`:"fn"in e?`${e.fn}(${(e.argv||[]).map(iy).join(", ")})`:JSON.stringify(e,null,2)}class Ls extends Error{constructor(t){super(t),this.name="EndpointError"}}const Tqe=(e,t)=>e===t,Cqe=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 Ls(`Path: '${e}' does not end with ']'`);const a=i.slice(r+1,-1);if(Number.isNaN(parseInt(a)))throw new Ls(`Invalid array index: '${a}' in path: '${e}'`);r!==0&&n.push(i.slice(0,r)),n.push(a)}else n.push(i)}return n},qme=(e,t)=>Cqe(t).reduce((n,i)=>{if(typeof n!="object")throw new Ls(`Index '${i}' in '${t}' not found in '${JSON.stringify(e)}'`);return Array.isArray(n)?n[parseInt(i)]:n[i]},e),Eqe=e=>e!=null,Aqe=e=>!e,h9={[r2.HTTP]:80,[r2.HTTPS]:443},kqe=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:o,search:c}=t;if(c)return null;const l=o.slice(0,-1);if(!Object.values(r2).includes(l))return null;const s=Ume(r),u=n.includes(`${i}:${h9[l]}`)||typeof e=="string"&&e.includes(`${i}:${h9[l]}`),d=`${i}${u?`:${h9[l]}`:""}`;return{scheme:l,authority:d,path:a,normalizedPath:a.endsWith("/")?a:`${a}/`,isIp:s}},Rqe=(e,t)=>e===t,Oqe=(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),Iqe=e=>encodeURIComponent(e).replace(/[!*'()]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Pqe={booleanEquals:Tqe,getAttr:qme,isSet:Eqe,isValidHostLabel:_k,not:Aqe,parseURL:kqe,stringEquals:Rqe,substring:Oqe,uriEncode:Iqe},Bme=(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 o=e.indexOf("}",a);if(o===-1){n.push(e.slice(a));break}e[a+1]==="{"&&e[o+1]==="}"&&(n.push(e.slice(a+1,o)),r=o+2);const c=e.substring(a+1,o);if(c.includes("#")){const[l,s]=c.split("#");n.push(qme(i[l],s))}else n.push(i[c]);r=o+1}return n.join("")},Mqe=({ref:e},t)=>({...t.endpointParams,...t.referenceRecord})[e],xk=(e,t,n)=>{if(typeof e=="string")return Bme(e,n);if(e.fn)return zme.callFunction(e,n);if(e.ref)return Mqe(e,n);throw new Ls(`'${t}': ${String(e)} is not a string, function or reference.`)},Wme=({fn:e,argv:t},n)=>{const i=t.map(a=>["boolean","number"].includes(typeof a)?a:zme.evaluateExpression(a,"arg",n)),r=e.split(".");return r[0]in F3&&r[1]!=null?F3[r[0]][r[1]](...i):Pqe[e](...i)},zme={evaluateExpression:xk,callFunction:Wme},Nqe=({assign:e,...t},n)=>{if(e&&e in n.referenceRecord)throw new Ls(`'${e}' is already defined in Reference Record.`);const i=Wme(t,n);return n.logger?.debug?.(`${l2} evaluateCondition: ${iy(t)} = ${iy(i)}`),{result:i===""?!0:!!i,...e!=null&&{toAssign:{name:e,value:i}}}},H7=(e=[],t)=>{const n={};for(const i of e){const{result:r,toAssign:a}=Nqe(i,{...t,referenceRecord:{...t.referenceRecord,...n}});if(!r)return{result:r};a&&(n[a.name]=a.value,t.logger?.debug?.(`${l2} assign: ${a.name} := ${iy(a.value)}`))}return{result:!0,referenceRecord:n}},$qe=(e,t)=>Object.entries(e).reduce((n,[i,r])=>({...n,[i]:r.map(a=>{const o=xk(a,"Header value entry",t);if(typeof o!="string")throw new Ls(`Header '${i}' value '${o}' is not a string`);return o})}),{}),Gme=(e,t)=>Object.entries(e).reduce((n,[i,r])=>({...n,[i]:Vme.getEndpointProperty(r,t)}),{}),Hme=(e,t)=>{if(Array.isArray(e))return e.map(n=>Hme(n,t));switch(typeof e){case"string":return Bme(e,t);case"object":if(e===null)throw new Ls(`Unexpected endpoint property: ${e}`);return Vme.getEndpointProperties(e,t);case"boolean":return e;default:throw new Ls(`Unexpected endpoint property type: ${typeof e}`)}},Vme={getEndpointProperty:Hme,getEndpointProperties:Gme},Dqe=(e,t)=>{const n=xk(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 Ls(`Endpoint URL must be a string, got ${typeof n}`)},jqe=(e,t)=>{const{conditions:n,endpoint:i}=e,{result:r,referenceRecord:a}=H7(n,t);if(!r)return;const o={...t,referenceRecord:{...t.referenceRecord,...a}},{url:c,properties:l,headers:s}=i;return t.logger?.debug?.(`${l2} Resolving endpoint from template: ${iy(i)}`),{...s!=null&&{headers:$qe(s,o)},...l!=null&&{properties:Gme(l,o)},url:Dqe(c,o)}},Lqe=(e,t)=>{const{conditions:n,error:i}=e,{result:r,referenceRecord:a}=H7(n,t);if(r)throw new Ls(xk(i,"Error",{...t,referenceRecord:{...t.referenceRecord,...a}}))},Jme=(e,t)=>{for(const n of e)if(n.type==="endpoint"){const i=jqe(n,t);if(i)return i}else if(n.type==="error")Lqe(n,t);else if(n.type==="tree"){const i=Kme.evaluateTreeRule(n,t);if(i)return i}else throw new Ls(`Unknown endpoint rule: ${n}`);throw new Ls("Rules evaluation failed")},Fqe=(e,t)=>{const{conditions:n,rules:i}=e,{result:r,referenceRecord:a}=H7(n,t);if(r)return Kme.evaluateRules(i,{...t,referenceRecord:{...t.referenceRecord,...a}})},Kme={evaluateRules:Jme,evaluateTreeRule:Fqe},Uqe=(e,t)=>{const{endpointParams:n,logger:i}=t,{parameters:r,rules:a}=e;t.logger?.debug?.(`${l2} Initial EndpointParams: ${iy(n)}`);const o=Object.entries(r).filter(([,s])=>s.default!=null).map(([s,u])=>[s,u.default]);if(o.length>0)for(const[s,u]of o)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 Ls(`Missing required parameter: '${s}'`);const l=Jme(a,{endpointParams:n,logger:i,referenceRecord:{}});return t.logger?.debug?.(`${l2} Resolved endpoint: ${iy(l)}`),l},Xme=(e,t=!1)=>{if(t){for(const n of e.split("."))if(!Xme(n))return!1;return!0}return!(!_k(e)||e.length<3||e.length>63||e!==e.toLowerCase()||Ume(e))},Vz=":",qqe="/",Bqe=e=>{const t=e.split(Vz);if(t.length<6)return null;const[n,i,r,a,o,...c]=t;if(n!=="arn"||i===""||r===""||c.join(Vz)==="")return null;const l=c.map(s=>s.split(qqe)).flat();return{partition:i,service:r,region:a,accountId:o,resourceId:l}},Wqe=[{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)"}}}],zqe={partitions:Wqe};let Gqe=zqe;const Hqe=e=>{const{partitions:t}=Gqe;for(const i of t){const{regions:r,outputs:a}=i;for(const[o,c]of Object.entries(r))if(o===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}},Zme={isVirtualHostableS3Bucket:Xme,parseArn:Bqe,partition:Hqe};F3.aws=Zme;function Vqe(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 U3=e=>{if(typeof e=="string")return U3(new URL(e));const{hostname:t,pathname:n,port:i,protocol:r,search:a}=e;let o;return a&&(o=Vqe(a)),{hostname:t,port:i?parseInt(i):void 0,protocol:r,path:n,query:o}};function Jqe(e,t,n){return e.$source||(e.$source={}),e.$source[t]=n,e}function vl(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 Jz=e=>Rv.isInstance(e)?e.headers?.date??e.headers?.Date:void 0,Yme=e=>new Date(Date.now()+e),Kqe=(e,t)=>Math.abs(Yme(t).getTime()-e)>=3e5,Kz=(e,t)=>{const n=Date.parse(e);return Kqe(n,t)?n-Date.now():t},jx=(e,t)=>{if(!t)throw new Error(`Property \`${e}\` is not resolved for AWS SDK SigV4Auth`);return t},Xqe=async e=>{const t=jx("context",e.context),n=jx("config",e.config),i=t.endpointV2?.properties?.authSchemes?.[0],a=await jx("signer",n.signer)(i),o=e?.signingRegion,c=e?.signingRegionSet,l=e?.signingName;return{config:n,signer:a,signingRegion:o,signingRegionSet:c,signingName:l}};class Zqe{async sign(t,n,i){if(!Ga.isInstance(t))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const r=await Xqe(i),{config:a,signer:o}=r;let{signingRegion:c,signingName:l}=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,l=p?.signingName??l)}return await o.sign(t,{signingDate:Yme(a.systemClockOffset),signingRegion:c,signingService:l})}errorHandler(t){return n=>{const i=n.ServerTime??Jz(n.$response);if(i){const r=jx("config",t.config),a=r.systemClockOffset;r.systemClockOffset=Kz(i,r.systemClockOffset),r.systemClockOffset!==a&&n.$metadata&&(n.$metadata.clockSkewCorrected=!0)}throw n}}successHandler(t,n){const i=Jz(t);if(i){const r=jx("config",n.config);r.systemClockOffset=Kz(i,r.systemClockOffset)}}}const Yqe=(e,t,n)=>{let i,r,a,o=!1;const c=async()=>{r||(r=e());try{i=await r,a=!0,o=!1}finally{r=void 0}return i};return async l=>((!a||l?.forceRefresh)&&(i=await c()),i)},Qqe="X-Amz-Algorithm",eBe="X-Amz-Credential",Qme="X-Amz-Date",tBe="X-Amz-SignedHeaders",nBe="X-Amz-Expires",ege="X-Amz-Signature",tge="X-Amz-Security-Token",nge="authorization",rge=Qme.toLowerCase(),rBe="date",iBe=[nge,rge,rBe],aBe=ege.toLowerCase(),uM="x-amz-content-sha256",sBe=tge.toLowerCase(),oBe={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},lBe=/^proxy-/,cBe=/^sec-/,m9="AWS4-HMAC-SHA256",uBe="AWS4-HMAC-SHA256-PAYLOAD",dBe="UNSIGNED-PAYLOAD",pBe=50,ige="aws4_request",fBe=3600*24*7,hT={},g9=[],y9=(e,t,n)=>`${e}/${t}/${n}/${ige}`,hBe=async(e,t,n,i,r)=>{const a=await Xz(e,t.secretAccessKey,t.accessKeyId),o=`${n}:${i}:${r}:${ss(a)}:${t.sessionToken}`;if(o in hT)return hT[o];for(g9.push(o);g9.length>pBe;)delete hT[g9.shift()];let c=`AWS4${t.secretAccessKey}`;for(const l of[n,i,r,ige])c=await Xz(e,c,l);return hT[o]=c},Xz=(e,t,n)=>{const i=new e(t);return i.update(a2(n)),i.digest()},Zz=({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 oBe||t?.has(a)||lBe.test(a)||cBe.test(a))&&(!n||n&&!n.has(a))||(i[a]=e[r].trim().replace(/\s+/g," "))}return i},mBe=e=>typeof ArrayBuffer=="function"&&e instanceof ArrayBuffer||Object.prototype.toString.call(e)==="[object ArrayBuffer]",v9=async({headers:e,body:t},n)=>{for(const i of Object.keys(e))if(i.toLowerCase()===uM)return e[i];if(t==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if(typeof t=="string"||ArrayBuffer.isView(t)||mBe(t)){const i=new n;return i.update(a2(t)),ss(await i.digest())}return dBe};class gBe{format(t){const n=[];for(const a of Object.keys(t)){const o=Iv(a);n.push(Uint8Array.from([o.byteLength]),o,this.formatHeaderValue(t[a]))}const i=new Uint8Array(n.reduce((a,o)=>a+o.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 o=new Uint8Array(a.buffer);return o.set(t.value,3),o;case"string":const c=Iv(t.value),l=new DataView(new ArrayBuffer(3+c.byteLength));l.setUint8(0,7),l.setUint16(1,c.byteLength,!1);const s=new Uint8Array(l.buffer);return s.set(c,3),s;case"timestamp":const u=new Uint8Array(9);return u[0]=8,u.set(vBe.fromNumber(t.value.valueOf()).bytes,1),u;case"uuid":if(!yBe.test(t.value))throw new Error(`Invalid UUID received: ${t.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(F7(t.value.replace(/\-/g,"")),1),d}}}var Yz;(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"})(Yz||(Yz={}));const yBe=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;let vBe=class age{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&&Qz(n),new age(n)}valueOf(){const t=this.bytes.slice(0),n=t[0]&128;return n&&Qz(t),parseInt(ss(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}};function Qz(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,e[t]===0);t--);}const bBe=(e,t)=>{e=e.toLowerCase();for(const n of Object.keys(t))if(e===n.toLowerCase())return!0;return!1},wBe=(e,t={})=>{const{headers:n,query:i={}}=Ga.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}},eG=e=>{e=Ga.clone(e);for(const t of Object.keys(e.headers))iBe.indexOf(t.toLowerCase())>-1&&delete e.headers[t];return e},_Be=({query:e={}})=>{const t=[],n={};for(const i of Object.keys(e)){if(i.toLowerCase()===aBe)continue;const r=wv(i);t.push(r);const a=e[i];typeof a=="string"?n[r]=`${r}=${wv(a)}`:Array.isArray(a)&&(n[r]=a.slice(0).reduce((o,c)=>o.concat([`${r}=${wv(c)}`]),[]).sort().join("&"))}return t.sort().map(i=>n[i]).filter(i=>i).join("&")},xBe=e=>SBe(e).toISOString().replace(/\.\d{3}Z$/,"Z"),SBe=e=>typeof e=="number"?new Date(e*1e3):typeof e=="string"?Number(e)?new Date(Number(e)*1e3):new Date(e):e;class TBe{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:t,credentials:n,region:i,service:r,sha256:a,uriEscapePath:o=!0}){this.service=r,this.sha256=a,this.uriEscapePath=o,this.applyChecksum=typeof t=="boolean"?t:!0,this.regionProvider=eg(i),this.credentialProvider=eg(n)}createCanonicalRequest(t,n,i){const r=Object.keys(n).sort();return`${t.method}
853
+ `),NUe={warn:console.warn},$Ue=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],U7=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Nme(e){const t=e.getUTCFullYear(),n=e.getUTCMonth(),i=e.getUTCDay(),r=e.getUTCDate(),a=e.getUTCHours(),o=e.getUTCMinutes(),c=e.getUTCSeconds(),l=r<10?`0${r}`:`${r}`,s=a<10?`0${a}`:`${a}`,u=o<10?`0${o}`:`${o}`,d=c<10?`0${c}`:`${c}`;return`${$Ue[i]}, ${l} ${U7[n]} ${t} ${s}:${u}:${d} GMT`}const DUe=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),jUe=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");const t=DUe.exec(e);if(!t)throw new TypeError("Invalid RFC-3339 date-time value");const[n,i,r,a,o,c,l,s,u]=t,d=L3(o2(i)),p=Xg(r,"month",1,12),f=Xg(a,"day",1,31),h=yE(d,p,f,{hours:o,minutes:c,seconds:l,fractionalMilliseconds:s});return u.toUpperCase()!="Z"&&h.setTime(h.getTime()-XUe(u)),h},LUe=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$/),FUe=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$/),UUe=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})$/),qUe=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let t=LUe.exec(e);if(t){const[n,i,r,a,o,c,l,s]=t;return yE(L3(o2(a)),f9(r),Xg(i,"day",1,31),{hours:o,minutes:c,seconds:l,fractionalMilliseconds:s})}if(t=FUe.exec(e),t){const[n,i,r,a,o,c,l,s]=t;return GUe(yE(WUe(a),f9(r),Xg(i,"day",1,31),{hours:o,minutes:c,seconds:l,fractionalMilliseconds:s}))}if(t=UUe.exec(e),t){const[n,i,r,a,o,c,l,s]=t;return yE(L3(o2(s)),f9(i),Xg(r.trimLeft(),"day",1,31),{hours:a,minutes:o,seconds:c,fractionalMilliseconds:l})}throw new TypeError("Invalid RFC-7231 date-time value")},BUe=e=>{if(e==null)return;let t;if(typeof e=="number")t=e;else if(typeof e=="string")t=RUe(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))},yE=(e,t,n,i)=>{const r=t-1;return VUe(e,r,n),new Date(Date.UTC(e,r,n,Xg(i.hours,"hour",0,23),Xg(i.minutes,"minute",0,59),Xg(i.seconds,"seconds",0,60),KUe(i.fractionalMilliseconds)))},WUe=e=>{const t=new Date().getUTCFullYear(),n=Math.floor(t/100)*100+L3(o2(e));return n<t?n+100:n},zUe=50*365*24*60*60*1e3,GUe=e=>e.getTime()-new Date().getTime()>zUe?new Date(Date.UTC(e.getUTCFullYear()-100,e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())):e,f9=e=>{const t=U7.indexOf(e);if(t<0)throw new TypeError(`Invalid month: ${e}`);return t+1},HUe=[31,28,31,30,31,30,31,31,30,31,30,31],VUe=(e,t,n)=>{let i=HUe[t];if(t===1&&JUe(e)&&(i=29),n>i)throw new TypeError(`Invalid day for ${U7[t]} in ${e}: ${n}`)},JUe=e=>e%4===0&&(e%100!==0||e%400===0),Xg=(e,t,n,i)=>{const r=PUe(o2(e));if(r<n||r>i)throw new TypeError(`${t} must be between ${n} and ${i}, inclusive`);return r},KUe=e=>e==null?0:OUe("0."+e)*1e3,XUe=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},o2=e=>{let t=0;for(;t<e.length-1&&e.charAt(t)==="0";)t++;return t===0?e:e.slice(t)},Gz=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ga=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0")),q7=()=>{if(Gz)return Gz();const e=new Uint8Array(16);return crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128,ga[e[0]]+ga[e[1]]+ga[e[2]]+ga[e[3]]+"-"+ga[e[4]]+ga[e[5]]+"-"+ga[e[6]]+ga[e[7]]+"-"+ga[e[8]]+ga[e[9]]+"-"+ga[e[10]]+ga[e[11]]+ga[e[12]]+ga[e[13]]+ga[e[14]]+ga[e[15]]},du=function(t){return Object.assign(new String(t),{deserializeJSON(){return JSON.parse(String(t))},toString(){return String(t)},toJSON(){return String(t)}})};du.from=e=>e&&typeof e=="object"&&(e instanceof du||"deserializeJSON"in e)?e:typeof e=="string"||Object.getPrototypeOf(e)===String.prototype?du(String(e)):du(JSON.stringify(e));du.fromObject=du.from;function ZUe(e){return(e.includes(",")||e.includes('"'))&&(e=`"${e.replace(/"/g,'\\"')}"`),e}const B7="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",W7="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",z7="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",$me="(\\d?\\d)",Dme="(\\d{4})",YUe=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),QUe=new RegExp(`^${B7}, ${$me} ${W7} ${Dme} ${z7} GMT$`),eqe=new RegExp(`^${B7}, ${$me}-${W7}-(\\d\\d) ${z7} GMT$`),tqe=new RegExp(`^${B7} ${W7} ( [1-9]|\\d\\d) ${z7} ${Dme}$`),nqe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],rqe=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))},iqe=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC3339 timestamps must be strings");const t=YUe.exec(e);if(!t)throw new TypeError(`Invalid RFC3339 timestamp format ${e}`);const[,n,i,r,a,o,c,,l,s]=t;Qm(i,1,12),Qm(r,1,31),Qm(a,0,23),Qm(o,0,59),Qm(c,0,60);const u=new Date(Date.UTC(Number(n),Number(i)-1,Number(r),Number(a),Number(o),Number(c),Number(l)?Math.round(parseFloat(`0.${l}`)*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},aqe=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC7231 timestamps must be strings.");let t,n,i,r,a,o,c,l;if((l=QUe.exec(e))?[,t,n,i,r,a,o,c]=l:(l=eqe.exec(e))?([,t,n,i,r,a,o,c]=l,i=(Number(i)+1900).toString()):(l=tqe.exec(e))&&([,n,t,r,a,o,c,i]=l),i&&o){const s=Date.UTC(Number(i),nqe.indexOf(n),Number(t),Number(r),Number(a),Number(o),c?Math.round(parseFloat(`0.${c}`)*1e3):0);Qm(t,1,31),Qm(r,0,23),Qm(a,0,59),Qm(o,0,60);const u=new Date(s);return u.setUTCFullYear(Number(i)),u}throw new TypeError(`Invalid RFC7231 date-time value ${e}.`)};function Qm(e,t,n){const i=Number(e);if(i<t||i>n)throw new Error(`Value ${i} out of range [${t}, ${n}]`)}function sqe(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 o=0;o<i.length;o++)a===""?a=i[o]:a+=t+i[o],(o+1)%n===0&&(r.push(a),a="");return a!==""&&r.push(a),r}const jme=e=>{const t=e.length,n=[];let i=!1,r,a=0;for(let o=0;o<t;++o){const c=e[o];switch(c){case'"':r!=="\\"&&(i=!i);break;case",":i||(n.push(e.slice(a,o)),a=o+1);break}r=c}return n.push(e.slice(a)),n.map(o=>{o=o.trim();const c=o.length;return c<2?o:(o[0]==='"'&&o[c-1]==='"'&&(o=o.slice(1,c-1)),o.replace(/\\"/g,'"'))})},Hz=/^-?\d*(\.\d+)?$/;class Xo{string;type;constructor(t,n){if(this.string=t,this.type=n,!Hz.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 Xo.prototype.isPrototypeOf(t)||n.type==="bigDecimal"&&Hz.test(n.string)}}class bk{serdeContext;setSerdeContext(t){this.serdeContext=t}}class oqe extends bk{options;compositeErrorRegistry;constructor(t){super(),this.options=t,this.compositeErrorRegistry=is.for(t.defaultNamespace);for(const n of t.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(n)}getRequestType(){return Ga}getResponseType(){return Rv}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=Gr.of(n.input),a=p0(n.traits??{});if(a.endpoint){let o=a.endpoint?.[0];if(typeof o=="string"){const c=[...r.structIterator()].filter(([,l])=>l.getMergedTraits().hostLabel);for(const[l]of c){const s=i[l];if(typeof s!="string")throw new Error(`@smithy/core/schema - ${l} in input must be a string as hostLabel.`);o=o.replace(`{${l}}`,s)}t.hostname=o+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 Tn(async()=>{const{EventStreamSerde:n}=await import("./index-vXNfi5ps.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 lqe extends oqe{async serializeRequest(t,n,i){const r={...n??{}},a=this.serializer,o={},c={},l=await i.endpoint(),s=Gr.of(t?.input),u=[],d=[];let p=!1,f;const h=new Ga({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:o,headers:c,body:void 0});if(l){this.updateServiceEndpoint(h,l),this.setHostPrefix(h,t,r);const m=p0(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(o,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(Uz).join("/")):h.path.includes(`{${m}}`)&&(h.path=h.path.replace(`{${m}}`,Uz(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 _=y.httpPrefixHeaders+b;a.write([g.getValueSchema(),{httpHeader:_}],w),c[_.toLowerCase()]=a.flush()}delete r[m]}else y.httpQuery||y.httpQueryParams?(this.serializeQuery(g,v,o),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=o,h.body=f,h}serializeQuery(t,n,i){const r=this.serializer,a=t.getMergedTraits();if(a.httpQueryParams){for(const[o,c]of Object.entries(n))if(!(o in i)){const l=t.getValueSchema();Object.assign(l.getMergedTraits(),{...a,httpQuery:o,httpQueryParams:void 0}),this.serializeQuery(l,c,i)}return}if(t.isListSchema()){const o=!!t.getMergedTraits().sparse,c=[];for(const l of n){r.write([t.getValueSchema(),a],l);const s=r.flush();(o||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=Gr.of(t.output),o={};if(i.statusCode>=300){const l=await cx(i.body,n);throw l.byteLength>0&&Object.assign(o,await r.read(15,l)),await this.handleError(t,n,i,o,this.deserializeMetadata(i)),new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(const l in i.headers){const s=i.headers[l];delete i.headers[l],i.headers[l.toLowerCase()]=s}const c=await this.deserializeHttpMessage(a,n,i,o);if(c.length){const l=await cx(i.body,n);if(l.byteLength>0){const s=await r.read(a,l);for(const u of c)s[u]!=null&&(o[u]=s[u])}}else c.discardResponseBody&&await cx(i.body,n);return o.$metadata=this.deserializeMetadata(i),o}async deserializeHttpMessage(t,n,i,r,a){let o;r instanceof Set?o=a:o=r;let c=!0;const l=this.deserializer,s=Gr.of(t),u=[];for(const[d,p]of s.structIterator()){const f=p.getMemberTraits();if(f.httpPayload){if(c=!1,p.isStreaming())p.isStructSchema()?o[d]=await this.deserializeEventStream({response:i,responseSchema:s}):o[d]=bUe(i.body);else if(i.body){const m=await cx(i.body,n);m.byteLength>0&&(o[d]=await l.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=sqe(m,",",2):y=jme(m);const v=[];for(const b of y)v.push(await l.read(g,b.trim()));o[d]=v}else o[d]=await l.read(p,m)}else if(f.httpPrefixHeaders!==void 0){o[d]={};for(const[h,m]of Object.entries(i.headers))if(h.startsWith(f.httpPrefixHeaders)){const g=p.getValueSchema();g.getMergedTraits().httpHeader=h,o[d][h.slice(f.httpPrefixHeaders.length)]=await l.read(g,m)}}else f.httpResponseCode?o[d]=i.statusCode:u.push(d)}return u.discardResponseBody=c,u}}function wk(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 cqe extends bk{settings;constructor(t){super(),this.settings=t}read(t,n){const i=Gr.of(t);if(i.isListSchema())return jme(n).map(r=>this.read(i.getValueSchema(),r));if(i.isBlobSchema())return(this.serdeContext?.base64Decoder??Ov)(n);if(i.isTimestampSchema())switch(wk(i,this.settings)){case 5:return iqe(n);case 6:return aqe(n);case 7:return rqe(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=du.from(a)),a}return i.isNumericSchema()?Number(n):i.isBigIntegerSchema()?BigInt(n):i.isBigDecimalSchema()?new Xo(n,"bigDecimal"):i.isBooleanSchema()?String(n).toLowerCase()==="true":n}base64ToUtf8(t){return(this.serdeContext?.utf8Encoder??rw)((this.serdeContext?.base64Decoder??Ov)(t))}}class uqe extends bk{codecDeserializer;stringDeserializer;constructor(t,n){super(),this.codecDeserializer=t,this.stringDeserializer=new cqe(n)}setSerdeContext(t){this.stringDeserializer.setSerdeContext(t),this.codecDeserializer.setSerdeContext(t),this.serdeContext=t}read(t,n){const i=Gr.of(t),r=i.getMergedTraits(),a=this.serdeContext?.utf8Encoder??rw;if(r.httpHeader||r.httpResponseCode)return this.stringDeserializer.read(i,a(n));if(r.httpPayload){if(i.isBlobSchema()){const o=this.serdeContext?.utf8Decoder??Iv;return typeof n=="string"?o(n):n}else if(i.isStringSchema())return"byteLength"in n?a(n):n}return this.codecDeserializer.read(i,n)}}class dqe extends bk{settings;stringBuffer="";constructor(t){super(),this.settings=t}write(t,n){const i=Gr.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(wk(i,this.settings)){case 5:this.stringBuffer=n.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=Nme(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??Pv)(n);return}if(i.isListSchema()&&Array.isArray(n)){let o="";for(const c of n){this.write([i.getValueSchema(),i.getMergedTraits()],c);const l=this.flush(),s=i.getValueSchema().isTimestampSchema()?l:ZUe(l);o!==""&&(o+=", "),o+=s}this.stringBuffer=o;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=du.from(a)),i.getMergedTraits().httpHeader)){this.stringBuffer=(this.serdeContext?.base64Encoder??Pv)(a.toString());return}this.stringBuffer=n;break;default:i.isIdempotencyToken()?this.stringBuffer=q7():this.stringBuffer=String(n)}}flush(){const t=this.stringBuffer;return this.stringBuffer="",t}}class pqe{codecSerializer;stringSerializer;buffer;constructor(t,n,i=new dqe(n)){this.codecSerializer=t,this.stringSerializer=i}setSerdeContext(t){this.codecSerializer.setSerdeContext(t),this.stringSerializer.setSerdeContext(t)}write(t,n){const i=Gr.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 fqe(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 hqe{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 mqe{async sign(t,n,i){const r=Ga.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 gqe=e=>function(n){return G7(n)&&n.expiration.getTime()-Date.now()<e},yqe=3e5,Lme=gqe(yqe),G7=e=>e.expiration!==void 0,Fme=(e,t,n)=>{if(e===void 0)return;const i=typeof e!="function"?async()=>Promise.resolve(e):e;let r,a,o,c=!1;const l=async s=>{a||(a=i(s));try{r=await a,o=!0,c=!1}finally{a=void 0}return r};return t===void 0?async s=>((!o||s?.forceRefresh)&&(r=await l(s)),r):async s=>((!o||s?.forceRefresh)&&(r=await l(s)),c?r:n(r)?(t(r)&&await l(s),r):(c=!0,r))},vqe=void 0;function bqe(e){return e===void 0?!0:typeof e=="string"&&e.length<=50}function wqe(e){const t=$x(e.userAgentAppId??vqe),{customUserAgent:n}=e;return Object.assign(e,{customUserAgent:typeof n=="string"?[[n]]:n,userAgentAppId:async()=>{const i=await t();if(!bqe(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 _qe{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:o,done:c}=r.next();if(this.data.delete(o),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 xqe=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}$"),Ume=e=>xqe.test(e)||e.startsWith("[")&&e.endsWith("]"),Sqe=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),_k=(e,t=!1)=>{if(!t)return Sqe.test(e);const n=e.split(".");for(const i of n)if(!_k(i))return!1;return!0},F3={},l2="endpoints";function iy(e){return typeof e!="object"||e==null?e:"ref"in e?`$${iy(e.ref)}`:"fn"in e?`${e.fn}(${(e.argv||[]).map(iy).join(", ")})`:JSON.stringify(e,null,2)}class Ls extends Error{constructor(t){super(t),this.name="EndpointError"}}const Tqe=(e,t)=>e===t,Cqe=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 Ls(`Path: '${e}' does not end with ']'`);const a=i.slice(r+1,-1);if(Number.isNaN(parseInt(a)))throw new Ls(`Invalid array index: '${a}' in path: '${e}'`);r!==0&&n.push(i.slice(0,r)),n.push(a)}else n.push(i)}return n},qme=(e,t)=>Cqe(t).reduce((n,i)=>{if(typeof n!="object")throw new Ls(`Index '${i}' in '${t}' not found in '${JSON.stringify(e)}'`);return Array.isArray(n)?n[parseInt(i)]:n[i]},e),Eqe=e=>e!=null,Aqe=e=>!e,h9={[r2.HTTP]:80,[r2.HTTPS]:443},kqe=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:o,search:c}=t;if(c)return null;const l=o.slice(0,-1);if(!Object.values(r2).includes(l))return null;const s=Ume(r),u=n.includes(`${i}:${h9[l]}`)||typeof e=="string"&&e.includes(`${i}:${h9[l]}`),d=`${i}${u?`:${h9[l]}`:""}`;return{scheme:l,authority:d,path:a,normalizedPath:a.endsWith("/")?a:`${a}/`,isIp:s}},Rqe=(e,t)=>e===t,Oqe=(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),Iqe=e=>encodeURIComponent(e).replace(/[!*'()]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Pqe={booleanEquals:Tqe,getAttr:qme,isSet:Eqe,isValidHostLabel:_k,not:Aqe,parseURL:kqe,stringEquals:Rqe,substring:Oqe,uriEncode:Iqe},Bme=(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 o=e.indexOf("}",a);if(o===-1){n.push(e.slice(a));break}e[a+1]==="{"&&e[o+1]==="}"&&(n.push(e.slice(a+1,o)),r=o+2);const c=e.substring(a+1,o);if(c.includes("#")){const[l,s]=c.split("#");n.push(qme(i[l],s))}else n.push(i[c]);r=o+1}return n.join("")},Mqe=({ref:e},t)=>({...t.endpointParams,...t.referenceRecord})[e],xk=(e,t,n)=>{if(typeof e=="string")return Bme(e,n);if(e.fn)return zme.callFunction(e,n);if(e.ref)return Mqe(e,n);throw new Ls(`'${t}': ${String(e)} is not a string, function or reference.`)},Wme=({fn:e,argv:t},n)=>{const i=t.map(a=>["boolean","number"].includes(typeof a)?a:zme.evaluateExpression(a,"arg",n)),r=e.split(".");return r[0]in F3&&r[1]!=null?F3[r[0]][r[1]](...i):Pqe[e](...i)},zme={evaluateExpression:xk,callFunction:Wme},Nqe=({assign:e,...t},n)=>{if(e&&e in n.referenceRecord)throw new Ls(`'${e}' is already defined in Reference Record.`);const i=Wme(t,n);return n.logger?.debug?.(`${l2} evaluateCondition: ${iy(t)} = ${iy(i)}`),{result:i===""?!0:!!i,...e!=null&&{toAssign:{name:e,value:i}}}},H7=(e=[],t)=>{const n={};for(const i of e){const{result:r,toAssign:a}=Nqe(i,{...t,referenceRecord:{...t.referenceRecord,...n}});if(!r)return{result:r};a&&(n[a.name]=a.value,t.logger?.debug?.(`${l2} assign: ${a.name} := ${iy(a.value)}`))}return{result:!0,referenceRecord:n}},$qe=(e,t)=>Object.entries(e).reduce((n,[i,r])=>({...n,[i]:r.map(a=>{const o=xk(a,"Header value entry",t);if(typeof o!="string")throw new Ls(`Header '${i}' value '${o}' is not a string`);return o})}),{}),Gme=(e,t)=>Object.entries(e).reduce((n,[i,r])=>({...n,[i]:Vme.getEndpointProperty(r,t)}),{}),Hme=(e,t)=>{if(Array.isArray(e))return e.map(n=>Hme(n,t));switch(typeof e){case"string":return Bme(e,t);case"object":if(e===null)throw new Ls(`Unexpected endpoint property: ${e}`);return Vme.getEndpointProperties(e,t);case"boolean":return e;default:throw new Ls(`Unexpected endpoint property type: ${typeof e}`)}},Vme={getEndpointProperty:Hme,getEndpointProperties:Gme},Dqe=(e,t)=>{const n=xk(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 Ls(`Endpoint URL must be a string, got ${typeof n}`)},jqe=(e,t)=>{const{conditions:n,endpoint:i}=e,{result:r,referenceRecord:a}=H7(n,t);if(!r)return;const o={...t,referenceRecord:{...t.referenceRecord,...a}},{url:c,properties:l,headers:s}=i;return t.logger?.debug?.(`${l2} Resolving endpoint from template: ${iy(i)}`),{...s!=null&&{headers:$qe(s,o)},...l!=null&&{properties:Gme(l,o)},url:Dqe(c,o)}},Lqe=(e,t)=>{const{conditions:n,error:i}=e,{result:r,referenceRecord:a}=H7(n,t);if(r)throw new Ls(xk(i,"Error",{...t,referenceRecord:{...t.referenceRecord,...a}}))},Jme=(e,t)=>{for(const n of e)if(n.type==="endpoint"){const i=jqe(n,t);if(i)return i}else if(n.type==="error")Lqe(n,t);else if(n.type==="tree"){const i=Kme.evaluateTreeRule(n,t);if(i)return i}else throw new Ls(`Unknown endpoint rule: ${n}`);throw new Ls("Rules evaluation failed")},Fqe=(e,t)=>{const{conditions:n,rules:i}=e,{result:r,referenceRecord:a}=H7(n,t);if(r)return Kme.evaluateRules(i,{...t,referenceRecord:{...t.referenceRecord,...a}})},Kme={evaluateRules:Jme,evaluateTreeRule:Fqe},Uqe=(e,t)=>{const{endpointParams:n,logger:i}=t,{parameters:r,rules:a}=e;t.logger?.debug?.(`${l2} Initial EndpointParams: ${iy(n)}`);const o=Object.entries(r).filter(([,s])=>s.default!=null).map(([s,u])=>[s,u.default]);if(o.length>0)for(const[s,u]of o)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 Ls(`Missing required parameter: '${s}'`);const l=Jme(a,{endpointParams:n,logger:i,referenceRecord:{}});return t.logger?.debug?.(`${l2} Resolved endpoint: ${iy(l)}`),l},Xme=(e,t=!1)=>{if(t){for(const n of e.split("."))if(!Xme(n))return!1;return!0}return!(!_k(e)||e.length<3||e.length>63||e!==e.toLowerCase()||Ume(e))},Vz=":",qqe="/",Bqe=e=>{const t=e.split(Vz);if(t.length<6)return null;const[n,i,r,a,o,...c]=t;if(n!=="arn"||i===""||r===""||c.join(Vz)==="")return null;const l=c.map(s=>s.split(qqe)).flat();return{partition:i,service:r,region:a,accountId:o,resourceId:l}},Wqe=[{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)"}}}],zqe={partitions:Wqe};let Gqe=zqe;const Hqe=e=>{const{partitions:t}=Gqe;for(const i of t){const{regions:r,outputs:a}=i;for(const[o,c]of Object.entries(r))if(o===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}},Zme={isVirtualHostableS3Bucket:Xme,parseArn:Bqe,partition:Hqe};F3.aws=Zme;function Vqe(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 U3=e=>{if(typeof e=="string")return U3(new URL(e));const{hostname:t,pathname:n,port:i,protocol:r,search:a}=e;let o;return a&&(o=Vqe(a)),{hostname:t,port:i?parseInt(i):void 0,protocol:r,path:n,query:o}};function Jqe(e,t,n){return e.$source||(e.$source={}),e.$source[t]=n,e}function vl(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 Jz=e=>Rv.isInstance(e)?e.headers?.date??e.headers?.Date:void 0,Yme=e=>new Date(Date.now()+e),Kqe=(e,t)=>Math.abs(Yme(t).getTime()-e)>=3e5,Kz=(e,t)=>{const n=Date.parse(e);return Kqe(n,t)?n-Date.now():t},jx=(e,t)=>{if(!t)throw new Error(`Property \`${e}\` is not resolved for AWS SDK SigV4Auth`);return t},Xqe=async e=>{const t=jx("context",e.context),n=jx("config",e.config),i=t.endpointV2?.properties?.authSchemes?.[0],a=await jx("signer",n.signer)(i),o=e?.signingRegion,c=e?.signingRegionSet,l=e?.signingName;return{config:n,signer:a,signingRegion:o,signingRegionSet:c,signingName:l}};class Zqe{async sign(t,n,i){if(!Ga.isInstance(t))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const r=await Xqe(i),{config:a,signer:o}=r;let{signingRegion:c,signingName:l}=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,l=p?.signingName??l)}return await o.sign(t,{signingDate:Yme(a.systemClockOffset),signingRegion:c,signingService:l})}errorHandler(t){return n=>{const i=n.ServerTime??Jz(n.$response);if(i){const r=jx("config",t.config),a=r.systemClockOffset;r.systemClockOffset=Kz(i,r.systemClockOffset),r.systemClockOffset!==a&&n.$metadata&&(n.$metadata.clockSkewCorrected=!0)}throw n}}successHandler(t,n){const i=Jz(t);if(i){const r=jx("config",n.config);r.systemClockOffset=Kz(i,r.systemClockOffset)}}}const Yqe=(e,t,n)=>{let i,r,a,o=!1;const c=async()=>{r||(r=e());try{i=await r,a=!0,o=!1}finally{r=void 0}return i};return async l=>((!a||l?.forceRefresh)&&(i=await c()),i)},Qqe="X-Amz-Algorithm",eBe="X-Amz-Credential",Qme="X-Amz-Date",tBe="X-Amz-SignedHeaders",nBe="X-Amz-Expires",ege="X-Amz-Signature",tge="X-Amz-Security-Token",nge="authorization",rge=Qme.toLowerCase(),rBe="date",iBe=[nge,rge,rBe],aBe=ege.toLowerCase(),uM="x-amz-content-sha256",sBe=tge.toLowerCase(),oBe={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},lBe=/^proxy-/,cBe=/^sec-/,m9="AWS4-HMAC-SHA256",uBe="AWS4-HMAC-SHA256-PAYLOAD",dBe="UNSIGNED-PAYLOAD",pBe=50,ige="aws4_request",fBe=3600*24*7,hT={},g9=[],y9=(e,t,n)=>`${e}/${t}/${n}/${ige}`,hBe=async(e,t,n,i,r)=>{const a=await Xz(e,t.secretAccessKey,t.accessKeyId),o=`${n}:${i}:${r}:${ss(a)}:${t.sessionToken}`;if(o in hT)return hT[o];for(g9.push(o);g9.length>pBe;)delete hT[g9.shift()];let c=`AWS4${t.secretAccessKey}`;for(const l of[n,i,r,ige])c=await Xz(e,c,l);return hT[o]=c},Xz=(e,t,n)=>{const i=new e(t);return i.update(a2(n)),i.digest()},Zz=({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 oBe||t?.has(a)||lBe.test(a)||cBe.test(a))&&(!n||n&&!n.has(a))||(i[a]=e[r].trim().replace(/\s+/g," "))}return i},mBe=e=>typeof ArrayBuffer=="function"&&e instanceof ArrayBuffer||Object.prototype.toString.call(e)==="[object ArrayBuffer]",v9=async({headers:e,body:t},n)=>{for(const i of Object.keys(e))if(i.toLowerCase()===uM)return e[i];if(t==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if(typeof t=="string"||ArrayBuffer.isView(t)||mBe(t)){const i=new n;return i.update(a2(t)),ss(await i.digest())}return dBe};class gBe{format(t){const n=[];for(const a of Object.keys(t)){const o=Iv(a);n.push(Uint8Array.from([o.byteLength]),o,this.formatHeaderValue(t[a]))}const i=new Uint8Array(n.reduce((a,o)=>a+o.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 o=new Uint8Array(a.buffer);return o.set(t.value,3),o;case"string":const c=Iv(t.value),l=new DataView(new ArrayBuffer(3+c.byteLength));l.setUint8(0,7),l.setUint16(1,c.byteLength,!1);const s=new Uint8Array(l.buffer);return s.set(c,3),s;case"timestamp":const u=new Uint8Array(9);return u[0]=8,u.set(vBe.fromNumber(t.value.valueOf()).bytes,1),u;case"uuid":if(!yBe.test(t.value))throw new Error(`Invalid UUID received: ${t.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(F7(t.value.replace(/\-/g,"")),1),d}}}var Yz;(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"})(Yz||(Yz={}));const yBe=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;let vBe=class age{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&&Qz(n),new age(n)}valueOf(){const t=this.bytes.slice(0),n=t[0]&128;return n&&Qz(t),parseInt(ss(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}};function Qz(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,e[t]===0);t--);}const bBe=(e,t)=>{e=e.toLowerCase();for(const n of Object.keys(t))if(e===n.toLowerCase())return!0;return!1},wBe=(e,t={})=>{const{headers:n,query:i={}}=Ga.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}},eG=e=>{e=Ga.clone(e);for(const t of Object.keys(e.headers))iBe.indexOf(t.toLowerCase())>-1&&delete e.headers[t];return e},_Be=({query:e={}})=>{const t=[],n={};for(const i of Object.keys(e)){if(i.toLowerCase()===aBe)continue;const r=wv(i);t.push(r);const a=e[i];typeof a=="string"?n[r]=`${r}=${wv(a)}`:Array.isArray(a)&&(n[r]=a.slice(0).reduce((o,c)=>o.concat([`${r}=${wv(c)}`]),[]).sort().join("&"))}return t.sort().map(i=>n[i]).filter(i=>i).join("&")},xBe=e=>SBe(e).toISOString().replace(/\.\d{3}Z$/,"Z"),SBe=e=>typeof e=="number"?new Date(e*1e3):typeof e=="string"?Number(e)?new Date(Number(e)*1e3):new Date(e):e;class TBe{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:t,credentials:n,region:i,service:r,sha256:a,uriEscapePath:o=!0}){this.service=r,this.sha256=a,this.uriEscapePath=o,this.applyChecksum=typeof t=="boolean"?t:!0,this.regionProvider=eg(i),this.credentialProvider=eg(n)}createCanonicalRequest(t,n,i){const r=Object.keys(n).sort();return`${t.method}
854
854
  ${this.getCanonicalPath(t)}
855
855
  ${_Be(t)}
856
856
  ${r.map(a=>`${a}:${n[a]}`).join(`
@@ -861,13 +861,13 @@ ${i}`}async createStringToSign(t,n,i,r){const a=new this.sha256;a.update(a2(i));
861
861
  ${t}
862
862
  ${n}
863
863
  ${ss(o)}`}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 wv(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=xBe(t).replace(/[\-:]/g,"");return{longDate:n,shortDate:n.slice(0,8)}}getCanonicalHeaderList(t){return Object.keys(t).sort().join(";")}}class tG extends TBe{headerFormatter=new gBe;constructor({applyChecksum:t,credentials:n,region:i,service:r,sha256:a,uriEscapePath:o=!0}){super({applyChecksum:t,credentials:n,region:i,service:r,sha256:a,uriEscapePath:o})}async presign(t,n={}){const{signingDate:i=new Date,expiresIn:r=3600,unsignableHeaders:a,unhoistableHeaders:o,signableHeaders:c,hoistableHeaders:l,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>fBe)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");const m=y9(h,p,u??this.service),g=wBe(eG(t),{unhoistableHeaders:o,hoistableHeaders:l});d.sessionToken&&(g.query[tge]=d.sessionToken),g.query[Qqe]=m9,g.query[eBe]=`${d.accessKeyId}/${m}`,g.query[Qme]=f,g.query[nBe]=r.toString(10);const y=Zz(g,a,c);return g.query[tBe]=this.getCanonicalHeaderList(y),g.query[ege]=await this.getSignature(f,m,this.getSigningKey(d,p,h,u),this.createCanonicalRequest(g,y,await v9(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:o}){const c=a??await this.regionProvider(),{shortDate:l,longDate:s}=this.formatDate(i),u=y9(l,c,o??this.service),d=await v9({headers:{},body:n},this.sha256),p=new this.sha256;p.update(t);const f=ss(await p.digest()),h=[uBe,s,u,r,f,d].join(`
864
- `);return this.signString(h,{signingDate:i,signingRegion:c,signingService:o})}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(o=>({message:t.message,signature:o}))}async signString(t,{signingDate:n=new Date,signingRegion:i,signingService:r}={}){const a=await this.credentialProvider();this.validateResolvedCredentials(a);const o=i??await this.regionProvider(),{shortDate:c}=this.formatDate(n),l=new this.sha256(await this.getSigningKey(a,o,c,r));return l.update(a2(t)),ss(await l.digest())}async signRequest(t,{signingDate:n=new Date,signableHeaders:i,unsignableHeaders:r,signingRegion:a,signingService:o}={}){const c=await this.credentialProvider();this.validateResolvedCredentials(c);const l=a??await this.regionProvider(),s=eG(t),{longDate:u,shortDate:d}=this.formatDate(n),p=y9(d,l,o??this.service);s.headers[rge]=u,c.sessionToken&&(s.headers[sBe]=c.sessionToken);const f=await v9(s,this.sha256);!bBe(uM,s.headers)&&this.applyChecksum&&(s.headers[uM]=f);const h=Zz(s,r,i),m=await this.getSignature(u,p,this.getSigningKey(c,l,d,o),this.createCanonicalRequest(s,h,f));return s.headers[nge]=`${m9} 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,m9),o=new this.sha256(await i);return o.update(a2(a)),ss(await o.digest())}getSigningKey(t,n,i,r){return hBe(this.sha256,t,i,n,r||this.service)}}const CBe=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=EBe(e,{credentials:t,credentialDefaultProvider:e.credentialDefaultProvider}),d=ABe(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)?Jqe(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:o}=e;let c;return e.signer?c=$x(e.signer):e.regionInfoProvider?c=()=>$x(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:o,uriEscapePath:r},h=e.signerConstructor||tG;return new h(f)}):c=async s=>{s=Object.assign({},{name:"sigv4",signingName:e.signingName||e.defaultSigningName,signingRegion:await $x(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:o,uriEscapePath:r},f=e.signerConstructor||tG;return new f(p)},Object.assign(e,{systemClockOffset:a,signingEscapePath:r,signer:c})};function EBe(e,{credentials:t,credentialDefaultProvider:n}){let i;return t?t?.memoized?i=t:i=Fme(t,Lme,G7):n?i=$x(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 ABe(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 nG=typeof TextEncoder=="function"?new TextEncoder:null,kBe=e=>{if(typeof e=="string"){if(nG)return nG.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}`)},Cy=(e,t)=>{const n=[];if(e&&n.push(e),t)for(const i of t)n.push(i);return n},Eg=(e,t)=>`${e||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`,q3=()=>{let e=[],t=[],n=!1;const i=new Set,r=d=>d.sort((p,f)=>rG[f.step]-rG[p.step]||iG[f.priority||"normal"]-iG[p.priority||"normal"]),a=d=>{let p=!1;const f=h=>{const m=Cy(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},o=d=>{let p=!1;const f=h=>{if(h.middleware===d){p=!0;for(const m of Cy(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),l=d=>{const p=[];return d.before.forEach(f=>{f.before.length===0&&f.after.length===0?p.push(f):p.push(...l(f))}),p.push(d),d.after.reverse().forEach(f=>{f.before.length===0&&f.after.length===0?p.push(f):p.push(...l(f))}),p},s=(d=!1)=>{const p=[],f=[],h={};return e.forEach(g=>{const y={...g,before:[],after:[]};for(const v of Cy(y.name,y.aliases))h[v]=y;p.push(y)}),t.forEach(g=>{const y={...g,before:[],after:[]};for(const v of Cy(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 ${Eg(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(l).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=Cy(f,m);if(y.length>0){if(y.some(v=>i.has(v))){if(!h)throw new Error(`Duplicate middleware name '${Eg(f,m)}'`);for(const v of y){const b=e.findIndex(_=>_.name===v||_.aliases?.some(T=>T===v));if(b===-1)continue;const w=e[b];if(w.step!==g.step||g.priority!==w.priority)throw new Error(`"${Eg(w.name,w.aliases)}" middleware with ${w.priority} priority in ${w.step} step cannot be overridden by "${Eg(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=Cy(f,m);if(y.length>0){if(y.some(v=>i.has(v))){if(!h)throw new Error(`Duplicate middleware name '${Eg(f,m)}'`);for(const v of y){const b=t.findIndex(_=>_.name===v||_.aliases?.some(T=>T===v));if(b===-1)continue;const w=t[b];if(w.toMiddleware!==g.toMiddleware||w.relation!==g.relation)throw new Error(`"${Eg(w.name,w.aliases)}" middleware ${w.relation} "${w.toMiddleware}" middleware cannot be overridden by "${Eg(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(q3()),use:d=>{d.applyToStack(u)},remove:d=>typeof d=="string"?a(d):o(d),removeByTag:d=>{let p=!1;const f=h=>{const{tags:m,name:g,aliases:y}=h;if(m&&m.includes(d)){const v=Cy(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(q3());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 Eg(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},rG={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},iG={high:3,normal:2,low:1};class RBe{config;middlewareStack=q3();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,o=r===void 0&&this.config.cacheMiddleware===!0;let c;if(o){this.handlers||(this.handlers=new WeakMap);const l=this.handlers;l.has(t.constructor)?c=l.get(t.constructor):(c=t.resolveMiddleware(this.middlewareStack,this.config,r),l.set(t.constructor,c))}else delete this.handlers,c=t.resolveMiddleware(this.middlewareStack,this.config,r);if(a)c(t).then(l=>a(null,l.output),l=>a(l)).catch(()=>{});else return c(t).then(l=>l.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}const b9="***SensitiveInformation***";function dM(e,t){if(t==null)return t;const n=Gr.of(e);if(n.getMergedTraits().sensitive)return b9;if(n.isListSchema()){if(!!n.getValueSchema().getMergedTraits().sensitive)return b9}else if(n.isMapSchema()){if(!!n.getKeySchema().getMergedTraits().sensitive||!!n.getValueSchema().getMergedTraits().sensitive)return b9}else if(n.isStructSchema()&&typeof t=="object"){const i=t,r={};for(const[a,o]of n.structIterator())i[a]!=null&&(r[a]=dM(o,i[a]));return r}return t}class sge{middlewareStack=q3();schema;static classBuilder(){return new OBe}resolveMiddlewareWithContext(t,n,i,{middlewareFn:r,clientName:a,commandName:o,inputFilterSensitiveLog:c,outputFilterSensitiveLog:l,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:o,inputFilterSensitiveLog:c,outputFilterSensitiveLog:l,[oM]:{commandInstance:this,...s},...u},{requestHandler:m}=n;return p.resolve(g=>m.handle(g.request,i||{}),h)}}class OBe{_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 sge{input;static getEndpointParameterInstructions(){return t._ep}constructor(...[i]){super(),this.input=i??{},t._init(this),this.schema=t._operationSchema}resolveMiddleware(i,r,a){const o=t._operationSchema,c=o?.[4]??o?.input,l=o?.[5]??o?.output;return this.resolveMiddlewareWithContext(i,r,a,{CommandCtor:n,middlewareFn:t._middlewareFn,clientName:t._clientName,commandName:t._commandName,inputFilterSensitiveLog:t._inputFilterSensitiveLog??(o?dM.bind(null,c):s=>s),outputFilterSensitiveLog:t._outputFilterSensitiveLog??(o?dM.bind(null,l):s=>s),smithyContext:t._smithyContext,additionalContext:t._additionalContext})}serialize=t._serializer;deserialize=t._deserializer}}}class f0 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 f0.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===f0?f0.isInstance(t):f0.isInstance(t)?n.name&&this.name?this.prototype.isPrototypeOf(t)||n.name===this.name:this.prototype.isPrototypeOf(t):!1}}const aG=(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},IBe=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{}}},oge=Object.values(i2),PBe=e=>{const t=[];for(const n in i2){const i=i2[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();oge.includes(i)?e.checksumAlgorithms[i.toUpperCase()]=r:e.checksumAlgorithms[i]=r,t.push(n)},checksumAlgorithms(){return t}}},MBe=e=>{const t={};return e.checksumAlgorithms().forEach(n=>{const i=n.algorithmId();oge.includes(i)&&(t[i]=n.checksumConstructor())}),t},NBe=e=>({setRetryStrategy(t){e.retryStrategy=t},retryStrategy(){return e.retryStrategy}}),$Be=e=>{const t={};return t.retryStrategy=e.retryStrategy(),t},DBe=e=>Object.assign(PBe(e),NBe(e)),jBe=e=>Object.assign(MBe(e),$Be(e));class lge{trace(){}debug(){}info(){}warn(){}error(){}}class LBe{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(o=>{const{httpQuery:c,httpQueryParams:l,httpHeader:s,httpLabel:u,httpPrefixHeaders:d}=o.getMergedTraits();return!c&&!l&&!s&&!u&&d===void 0}))return t}async getErrorSchemaOrThrowBaseException(t,n,i,r,a,o){let c=n,l=t;t.includes("#")&&([c,l]=t.split("#"));const s={$metadata:a,$fault:i.statusCode<500?"client":"server"},u=is.for(c);try{return{errorSchema:o?.(u,l)??u.getSchema(t),errorMetadata:s}}catch{r.message=r.message??r.Message??"UnknownError";const p=is.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:l}),s),r)}throw this.decorateServiceException(Object.assign(new Error(l),s),r)}}decorateServiceException(t,n={}){if(this.queryCompat){const i=t.Message??n.Message,r=aG(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 aG(t,n)}setQueryCompatError(t,n){const i=n.headers?.["x-amzn-query-error"];if(t!==void 0&&i!=null){const[r,a]=i.split(";"),o=Object.entries(t),c={Code:r,Type:a};Object.assign(t,c);for(const[l,s]of o)c[l==="message"?"Message":l]=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=>Gr.of(r).getMergedTraits().awsQueryError?.[0]===n)}}}class V7{serdeContext;setSerdeContext(t){this.serdeContext=t}}class FBe{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 UBe(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 Xo(i,"bigDecimal"):BigInt(i)}return t}const qBe=(e,t)=>cx(e,t).then(n=>(t?.utf8Encoder??rw)(n)),BBe=(e,t)=>qBe(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{}}),WBe=(e,t)=>{const n=(a,o)=>Object.keys(a).find(c=>c.toLowerCase()===o.toLowerCase()),i=a=>{let o=a;return typeof o=="number"&&(o=o.toString()),o.indexOf(",")>=0&&(o=o.split(",")[0]),o.indexOf(":")>=0&&(o=o.split(":")[0]),o.indexOf("#")>=0&&(o=o.split("#")[1]),o},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 zBe extends V7{settings;constructor(t){super(),this.settings=t}async read(t,n){return this._read(t,typeof n=="string"?JSON.parse(n,UBe):await BBe(n,this.serdeContext))}readObject(t,n){return this._read(t,n)}_read(t,n){const i=n!==null&&typeof n=="object",r=Gr.of(t);if(i){if(r.isStructSchema()){const o=n,c=r.isUnionSchema(),l={};let s;const{jsonName:u}=this.settings;u&&(s={});let d;c&&(d=new FBe(o,l));for(const[p,f]of r.structIterator()){let h=p;u&&(h=f.getMergedTraits().jsonName??h,s[h]=p),c&&d.mark(h),o[h]!=null&&(l[p]=this._read(f,o[h]))}if(c)d.writeUnknown();else if(typeof o.__type=="string")for(const[p,f]of Object.entries(o)){const h=u?s[p]??p:p;h in l||(l[h]=f)}return l}if(Array.isArray(n)&&r.isListSchema()){const o=r.getValueSchema(),c=[],l=!!r.getMergedTraits().sparse;for(const s of n)(l||s!=null)&&c.push(this._read(o,s));return c}if(r.isMapSchema()){const o=r.getValueSchema(),c={},l=!!r.getMergedTraits().sparse;for(const[s,u]of Object.entries(n))(l||u!=null)&&(c[s]=this._read(o,u));return c}}if(r.isBlobSchema()&&typeof n=="string")return Ov(n);const a=r.getMergedTraits().mediaType;if(r.isStringSchema()&&typeof n=="string"&&a)return a==="application/json"||a.endsWith("+json")?du.from(n):n;if(r.isTimestampSchema()&&n!=null)switch(wk(r,this.settings)){case 5:return jUe(n);case 6:return qUe(n);case 7:return BUe(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 Xo)return n;const o=n;return o.type==="bigDecimal"&&"string"in o?new Xo(o.string,o.type):new Xo(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 o=Array.isArray(n)?[]:{};for(const[c,l]of Object.entries(n))l instanceof Xo?o[c]=l:o[c]=this._read(r,l);return o}else return structuredClone(n);return n}}const sG="Ν";class GBe{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 Xo){const i=`${sG+"nv"+this.counter++}_`+n.string;return this.values.set(`"${i}"`,n.string),i}if(typeof n=="bigint"){const i=n.toString(),r=`${sG+"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 HBe extends V7{settings;buffer;useReplacer=!1;rootSchema;constructor(t){super(),this.settings=t}write(t,n){this.rootSchema=Gr.of(t),this.buffer=this._write(this.rootSchema,n)}writeDiscriminatedDocument(t,n){this.write(t,n),typeof this.buffer=="object"&&(this.buffer.__type=Gr.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 GBe;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=Gr.of(t);if(r){if(a.isStructSchema()){const o=n,c={},{jsonName:l}=this.settings;let s;l&&(s={});for(const[u,d]of a.structIterator()){const p=this._write(d,o[u],a);if(p!==void 0){let f=u;l&&(f=d.getMergedTraits().jsonName??u,s[u]=f),c[f]=p}}if(a.isUnionSchema()&&Object.keys(c).length===0){const{$unknown:u}=o;if(Array.isArray(u)){const[d,p]=u;c[d]=this._write(15,p)}}else if(typeof o.__type=="string")for(const[u,d]of Object.entries(o)){const p=l?s[u]??u:u;p in c||(c[p]=this._write(15,d))}return c}if(Array.isArray(n)&&a.isListSchema()){const o=a.getValueSchema(),c=[],l=!!a.getMergedTraits().sparse;for(const s of n)(l||s!=null)&&c.push(this._write(o,s));return c}if(a.isMapSchema()){const o=a.getValueSchema(),c={},l=!!a.getMergedTraits().sparse;for(const[s,u]of Object.entries(n))(l||u!=null)&&(c[s]=this._write(o,u));return c}if(n instanceof Uint8Array&&(a.isBlobSchema()||a.isDocumentSchema()))return a===this.rootSchema?n:(this.serdeContext?.base64Encoder??Pv)(n);if(n instanceof Date&&(a.isTimestampSchema()||a.isDocumentSchema()))switch(wk(a,this.settings)){case 5:return n.toISOString().replace(".000Z","Z");case 6:return Nme(n);case 7:return n.getTime()/1e3;default:return console.warn("Missing timestamp format, using epoch seconds",n),n.getTime()/1e3}n instanceof Xo&&(this.useReplacer=!0)}if(!(n===null&&i?.isStructSchema())){if(a.isStringSchema()){if(typeof n>"u"&&a.isIdempotencyToken())return q7();const o=a.getMergedTraits().mediaType;return n!=null&&o&&(o==="application/json"||o.endsWith("+json"))?du.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??Pv)(n);if(typeof n=="bigint"&&(this.useReplacer=!0),a.isDocumentSchema())if(r){const o=Array.isArray(n)?[]:{};for(const[c,l]of Object.entries(n))l instanceof Xo?(this.useReplacer=!0,o[c]=l):o[c]=this._write(a,l);return o}else return structuredClone(n);return n}}}class VBe extends V7{settings;constructor(t){super(),this.settings=t}createSerializer(){const t=new HBe(this.settings);return t.setSerdeContext(this.serdeContext),t}createDeserializer(){const t=new zBe(this.settings);return t.setSerdeContext(this.serdeContext),t}}class JBe extends lqe{serializer;deserializer;codec;mixin=new LBe;constructor({defaultNamespace:t}){super({defaultNamespace:t});const n={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=new VBe(n),this.serializer=new pqe(this.codec.createSerializer(),n),this.deserializer=new uqe(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=Gr.of(t.input);if(!r.headers["content-type"]){const o=this.mixin.resolveRestContentType(this.getDefaultContentType(),a);o&&(r.headers["content-type"]=o)}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=Gr.of(t.output);for(const[o,c]of a.structIterator())c.getMemberTraits().httpPayload&&!(o in r)&&(r[o]=null);return r}async handleError(t,n,i,r,a){const o=WBe(i,r)??"Unknown",{errorSchema:c,errorMetadata:l}=await this.mixin.getErrorSchemaOrThrowBaseException(o,this.options.defaultNamespace,i,r,a),s=Gr.of(c),u=r.message??r.Message??"Unknown",d=is.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,l,{$fault:s.getMergedTraits().error,message:u},f),r)}getDefaultContentType(){return"application/json"}}const KBe=/\d{12}\.ddb/;async function XBe(e,t,n){if(n.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor"&&vl(e,"PROTOCOL_RPC_V2_CBOR","M"),typeof t.retryStrategy=="function"){const a=await t.retryStrategy();typeof a.acquireInitialRetryToken=="function"?a.constructor?.name?.includes("Adaptive")?vl(e,"RETRY_MODE_ADAPTIVE","F"):vl(e,"RETRY_MODE_STANDARD","E"):vl(e,"RETRY_MODE_LEGACY","D")}if(typeof t.accountIdEndpointMode=="function"){const a=e.endpointV2;switch(String(a?.url?.hostname).match(KBe)&&vl(e,"ACCOUNT_ID_ENDPOINT","O"),await t.accountIdEndpointMode?.()){case"disabled":vl(e,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":vl(e,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":vl(e,"ACCOUNT_ID_MODE_REQUIRED","R");break}}const r=e.__smithy_context?.selectedHttpAuthScheme?.identity;if(r?.$source){const a=r;a.accountId&&vl(e,"RESOLVED_ACCOUNT_ID","T");for(const[o,c]of Object.entries(a.$source??{}))vl(e,o,c)}}const oG="user-agent",w9="x-amz-user-agent",lG=" ",_9="/",ZBe=/[^!$%&'*+\-.^_`|~\w]/g,YBe=/[^!$%&'*+\-.^_`|~\w#]/g,cG="-",QBe=1024;function eWe(e){let t="";for(const n in e){const i=e[n];if(t.length+i.length+1<=QBe){t.length?t+=","+i:t+=i;continue}break}return t}const tWe=e=>(t,n)=>async i=>{const{request:r}=i;if(!Ga.isInstance(r))return t(i);const{headers:a}=r,o=n?.userAgent?.map(mT)||[],c=(await e.defaultUserAgentProvider()).map(mT);await XBe(n,e,i);const l=n;c.push(`m/${eWe(Object.assign({},n.__smithy_context?.features,l.__aws_sdk_context?.features))}`);const s=e?.customUserAgent?.map(mT)||[],u=await e.userAgentAppId();u&&c.push(mT(["app",`${u}`]));const d=[].concat([...c,...o,...s]).join(lG),p=[...c.filter(f=>f.startsWith("aws-sdk-")),...s].join(lG);return e.runtime!=="browser"?(p&&(a[w9]=a[w9]?`${a[oG]} ${p}`:p),a[oG]=d):a[w9]=d,t({...i,request:r})},mT=e=>{const t=e[0].split(_9).map(o=>o.replace(ZBe,cG)).join(_9),n=e[1]?.replace(YBe,cG),i=t.indexOf(_9),r=t.substring(0,i);let a=t.substring(i+1);return r==="api"&&(a=a.toLowerCase()),[r,a,n].filter(o=>o&&o.length>0).reduce((o,c,l)=>{switch(l){case 0:return c;case 1:return`${o}/${c}`;default:return`${o}#${c}`}},"")},nWe={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},rWe=e=>({applyToStack:t=>{t.add(tWe(e),nWe)}});function iWe(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 o=n?Rme(n):"";o&&o[0]!=="?"&&(o=`?${o}`);let c="";if(e.username!=null||e.password!=null){const s=e.username??"",u=e.password??"";c=`${s}:${u}@`}let l="";return e.fragment&&(l=`#${e.fragment}`),`${i}//${c}${a}${r}${o}${l}`}var pM=function(e,t){return pM=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])},pM(e,t)};function cge(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");pM(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var B3=function(){return B3=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},B3.apply(this,arguments)};function uge(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 dge(e,t,n,i){var r=arguments.length,a=r<3?t:i===null?i=Object.getOwnPropertyDescriptor(t,n):i,o;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--)(o=e[c])&&(a=(r<3?o(a):r>3?o(t,n,a):o(t,n))||a);return r>3&&a&&Object.defineProperty(t,n,a),a}function pge(e,t){return function(n,i){t(n,i,e)}}function fge(e,t,n,i,r,a){function o(y){if(y!==void 0&&typeof y!="function")throw new TypeError("Function expected");return y}for(var c=i.kind,l=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(o(y||null))};var g=(0,n[f])(c==="accessor"?{get:u.get,set:u.set}:u[l],h);if(c==="accessor"){if(g===void 0)continue;if(g===null||typeof g!="object")throw new TypeError("Object expected");(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&r.unshift(d)}else(d=o(g))&&(c==="field"?r.unshift(d):u[l]=d)}s&&Object.defineProperty(s,i.name,u),p=!0}function hge(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 mge(e){return typeof e=="symbol"?e:"".concat(e)}function gge(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 yge(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}function J7(e,t,n,i){function r(a){return a instanceof n?a:new n(function(o){o(a)})}return new(n||(n=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(d){o(d)}}function l(u){try{s(i.throw(u))}catch(d){o(d)}}function s(u){u.done?a(u.value):r(u.value).then(c,l)}s((i=i.apply(e,t||[])).next())})}function K7(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,r,a,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=c(0),o.throw=c(1),o.return=c(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function c(s){return function(u){return l([s,u])}}function l(s){if(i)throw new TypeError("Generator is already executing.");for(;o&&(o=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 Sk=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 vge(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&Sk(t,e,n)}function c2(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 X7(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,a=[],o;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(c){o={error:c}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a}function bge(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(X7(arguments[t]));return e}function wge(){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],o=0,c=a.length;o<c;o++,r++)i[r]=a[o];return i}function _ge(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 $0(e){return this instanceof $0?(this.v=e,this):new $0(e)}function xge(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",o),r[Symbol.asyncIterator]=function(){return this},r;function o(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||l(f,m)})},h&&(r[f]=h(r[f])))}function l(f,h){try{s(i[f](h))}catch(m){p(a[0][3],m)}}function s(f){f.value instanceof $0?Promise.resolve(f.value.v).then(u,d):p(a[0][2],f)}function u(f){l("next",f)}function d(f){l("throw",f)}function p(f,h){f(h),a.shift(),a.length&&l(a[0][0],a[0][1])}}function Sge(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(o){return(n=!n)?{value:$0(e[r](o)),done:!1}:a?a(o):o}:a}}function Tge(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 c2=="function"?c2(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(o){return new Promise(function(c,l){o=e[a](o),r(c,l,o.done,o.value)})}}function r(a,o,c,l){Promise.resolve(l).then(function(s){a({value:s,done:c})},o)}}function Cge(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}var aWe=Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t},fM=function(e){return fM=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},fM(e)};function Ege(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=fM(e),i=0;i<n.length;i++)n[i]!=="default"&&Sk(t,e,n[i]);return aWe(t,e),t}function Age(e){return e&&e.__esModule?e:{default:e}}function kge(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 Rge(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 Oge(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 Ige(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 sWe=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 Pge(e){function t(a){e.error=e.hasError?new sWe(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(o){return t(o),r()})}else i|=1}catch(o){t(o)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return r()}function Mge(e,t){return typeof e=="string"&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(n,i,r,a,o){return i?t?".jsx":".js":r&&(!a||!o)?n:r+a+"."+o.toLowerCase()+"js"}):e}const oWe={__extends:cge,__assign:B3,__rest:uge,__decorate:dge,__param:pge,__esDecorate:fge,__runInitializers:hge,__propKey:mge,__setFunctionName:gge,__metadata:yge,__awaiter:J7,__generator:K7,__createBinding:Sk,__exportStar:vge,__values:c2,__read:X7,__spread:bge,__spreadArrays:wge,__spreadArray:_ge,__await:$0,__asyncGenerator:xge,__asyncDelegator:Sge,__asyncValues:Tge,__makeTemplateObject:Cge,__importStar:Ege,__importDefault:Age,__classPrivateFieldGet:kge,__classPrivateFieldSet:Rge,__classPrivateFieldIn:Oge,__addDisposableResource:Ige,__disposeResources:Pge,__rewriteRelativeImportExtension:Mge},o7t=Object.freeze(Object.defineProperty({__proto__:null,__addDisposableResource:Ige,get __assign(){return B3},__asyncDelegator:Sge,__asyncGenerator:xge,__asyncValues:Tge,__await:$0,__awaiter:J7,__classPrivateFieldGet:kge,__classPrivateFieldIn:Oge,__classPrivateFieldSet:Rge,__createBinding:Sk,__decorate:dge,__disposeResources:Pge,__esDecorate:fge,__exportStar:vge,__extends:cge,__generator:K7,__importDefault:Age,__importStar:Ege,__makeTemplateObject:Cge,__metadata:yge,__param:pge,__propKey:mge,__read:X7,__rest:uge,__rewriteRelativeImportExtension:Mge,__runInitializers:hge,__setFunctionName:gge,__spread:bge,__spreadArray:_ge,__spreadArrays:wge,__values:c2,default:oWe},Symbol.toStringTag,{value:"Module"})),lWe=e=>new TextEncoder().encode(e);var cWe=typeof Buffer<"u"&&Buffer.from?function(e){return Buffer.from(e,"utf8")}:lWe;function u2(e){return e instanceof Uint8Array?e:typeof e=="string"?cWe(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}function hM(e){return typeof e=="string"?e.length===0:e.byteLength===0}function uWe(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 Nge=(function(){function e(){this.checksum=4294967295}return e.prototype.update=function(t){var n,i;try{for(var r=c2(t),a=r.next();!a.done;a=r.next()){var o=a.value;this.checksum=this.checksum>>>8^pWe[(this.checksum^o)&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})(),dWe=[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],pWe=uWe(dWe);class Lx{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&&uG(n),new Lx(n)}valueOf(){const t=this.bytes.slice(0),n=t[0]&128;return n&&uG(t),parseInt(ss(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function uG(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,e[t]===0);t--);}class fWe{toUtf8;fromUtf8;constructor(t,n){this.toUtf8=t,this.fromUtf8=n}format(t){const n=[];for(const a of Object.keys(t)){const o=this.fromUtf8(a);n.push(Uint8Array.from([o.byteLength]),o,this.formatHeaderValue(t[a]))}const i=new Uint8Array(n.reduce((a,o)=>a+o.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 o=new Uint8Array(a.buffer);return o.set(t.value,3),o;case"string":const c=this.fromUtf8(t.value),l=new DataView(new ArrayBuffer(3+c.byteLength));l.setUint8(0,7),l.setUint16(1,c.byteLength,!1);const s=new Uint8Array(l.buffer);return s.set(c,3),s;case"timestamp":const u=new Uint8Array(9);return u[0]=8,u.set(Lx.fromNumber(t.value.valueOf()).bytes,1),u;case"uuid":if(!xWe.test(t.value))throw new Error(`Invalid UUID received: ${t.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(F7(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:pG,value:!0};break;case 1:n[a]={type:pG,value:!1};break;case 2:n[a]={type:hWe,value:t.getInt8(i++)};break;case 3:n[a]={type:mWe,value:t.getInt16(i,!1)},i+=2;break;case 4:n[a]={type:gWe,value:t.getInt32(i,!1)},i+=4;break;case 5:n[a]={type:yWe,value:new Lx(new Uint8Array(t.buffer,t.byteOffset+i,8))},i+=8;break;case 6:const o=t.getUint16(i,!1);i+=2,n[a]={type:vWe,value:new Uint8Array(t.buffer,t.byteOffset+i,o)},i+=o;break;case 7:const c=t.getUint16(i,!1);i+=2,n[a]={type:bWe,value:this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+i,c))},i+=c;break;case 8:n[a]={type:wWe,value:new Date(new Lx(new Uint8Array(t.buffer,t.byteOffset+i,8)).valueOf())},i+=8;break;case 9:const l=new Uint8Array(t.buffer,t.byteOffset+i,16);i+=16,n[a]={type:_We,value:`${ss(l.subarray(0,4))}-${ss(l.subarray(4,6))}-${ss(l.subarray(6,8))}-${ss(l.subarray(8,10))}-${ss(l.subarray(10))}`};break;default:throw new Error("Unrecognized header type tag")}}return n}}var dG;(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"})(dG||(dG={}));const pG="boolean",hWe="byte",mWe="short",gWe="integer",yWe="long",vWe="binary",bWe="string",wWe="timestamp",_We="uuid",xWe=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,$ge=4,$g=$ge*2,Jy=4,SWe=$g+Jy*2;function TWe({byteLength:e,byteOffset:t,buffer:n}){if(e<SWe)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($ge,!1),o=i.getUint32($g,!1),c=i.getUint32(e-Jy,!1),l=new Nge().update(new Uint8Array(n,t,$g));if(o!==l.digest())throw new Error(`The prelude checksum specified in the message (${o}) does not match the calculated CRC32 checksum (${l.digest()})`);if(l.update(new Uint8Array(n,t+$g,e-($g+Jy))),c!==l.digest())throw new Error(`The message checksum (${l.digest()}) did not match the expected value of ${c}`);return{headers:new DataView(n,t+$g+Jy,a),body:new Uint8Array(n,t+$g+Jy+a,r-a-($g+Jy+Jy))}}class Dge{headerMarshaller;messageBuffer;isEndOfStream;constructor(t,n){this.headerMarshaller=new fWe(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),o=new DataView(a.buffer,a.byteOffset,a.byteLength),c=new Nge;return o.setUint32(0,r,!1),o.setUint32(4,i.byteLength,!1),o.setUint32(8,c.update(a.subarray(0,8)).digest(),!1),a.set(i,12),a.set(n,i.byteLength+12),o.setUint32(r-4,c.update(a.subarray(8,r-4)).digest(),!1),a}decode(t){const{headers:n,body:i}=TWe(t);return{headers:this.headerMarshaller.parse(n),body:i}}formatHeaders(t){return this.headerMarshaller.format(t)}}class CWe{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 EWe{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 AWe{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 kWe{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 RWe(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)},o=async function*(){const c=e[Symbol.asyncIterator]();for(;;){const{value:l,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=l.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(l.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(l.slice(d,d+p),n),n+=p,d+=p,t&&t===n&&(yield i,i=null,t=0,n=0)}}};return{[Symbol.asyncIterator]:o}}function OWe(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},o=await e(a);if(o.$unknown){const c=new Error(t(n.body));throw c.name=r,c}throw o[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 IWe=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:t,utf8Decoder:n}){this.eventStreamCodec=new Dge(t,n),this.utfEncoder=t}deserialize(t,n){const i=RWe(t);return new AWe({messageStream:new CWe({inputStream:i,decoder:this.eventStreamCodec}),deserializer:OWe(n,this.utfEncoder)})}serialize(t,n){return new EWe({messageStream:new kWe({inputStream:t,serializer:n}),encoder:this.eventStreamCodec,includeEndFrame:!0})}};const jge=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()}}}),Lge=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 PWe{universalMarshaller;constructor({utf8Encoder:t,utf8Decoder:n}){this.universalMarshaller=new IWe({utf8Decoder:n,utf8Encoder:t})}deserialize(t,n){const i=MWe(t)?jge(t):t;return this.universalMarshaller.deserialize(i,n)}serialize(t,n){const i=this.universalMarshaller.serialize(t,n);return typeof ReadableStream=="function"?Lge(i):i}}const MWe=e=>typeof ReadableStream=="function"&&e instanceof ReadableStream,NWe=e=>new PWe(e),Fge=e=>e.protocol==="ws:"||e.protocol==="wss:",$We=3e3;class Z7{metadata={handlerProtocol:"websocket/h1.1"};config={};configPromise;httpHandler;sockets={};static create(t,n=new s2){return typeof t?.handle=="function"?t:new Z7(t,n)}constructor(t,n=new s2){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(!Fge(t))return n?.debug?.(`@aws-sdk - ws fetching ${t.protocol}${t.hostname}${t.path}`),this.httpHandler.handle(t);const i=iWe(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=$We}=this.config;await this.waitForReady(r,a);const{body:o}=t,c=DWe(o),l=this.connect(r,c),s=jWe(l);return{response:new Rv({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 o=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;o(typeof u=="string"?{done:!1,value:Ov(u)}:{done:!1,value:new Uint8Array(u)})},t.onerror=s=>{t.close(),o({done:!0,error:s})},t.onclose=()=>{this.removeNotUsableSockets(t.url),o({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){o({done:!0,error:s})}finally{t.close(1e3)}})(),c}}const DWe=e=>e[Symbol.asyncIterator]?e:LWe(e)?jge(e):{[Symbol.asyncIterator]:async function*(){yield e}},jWe=e=>typeof ReadableStream=="function"?Lge(e):e,LWe=e=>typeof ReadableStream=="function"&&e instanceof ReadableStream;class FWe{signer;constructor(t){this.signer=t.signer}presign(t,n={}){return this.signer.presign(t,n)}async sign(t,n){return Ga.isInstance(t)&&Fge(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 UWe=e=>{const{signer:t}=e;return Object.assign(e,{signer:async n=>{const i=await t(n);if(qWe(i))return new FWe({signer:i});throw new Error("Expected WebsocketSignatureV4 signer, please check the client constructor.")}})},qWe=e=>!!e;class BWe extends TransformStream{constructor(t,n,i,r){let a=t;super({start(){},async transform(o,c){try{const l=new Date(Date.now()+await r()),s={":date":{type:"timestamp",value:l}},u=await n.sign({message:{body:o,headers:s},priorSignature:a},{signingDate:l});a=u.signature;const d=i.encode({headers:{...s,":chunk-signature":{type:"binary",value:F7(u.signature)}},body:o});c.enqueue(d)}catch(l){c.error(l)}}})}}class WWe{messageSigner;eventStreamCodec;systemClockOffsetProvider;constructor(t){this.messageSigner=t.messageSigner,this.eventStreamCodec=new Dge(t.utf8Encoder,t.utf8Decoder),this.systemClockOffsetProvider=async()=>t.systemClockOffset??0}async handle(t,n,i={}){const r=n.request,{body:a,headers:o,query:c}=r;if(!(a instanceof ReadableStream))throw new Error("Eventstream payload must be a ReadableStream.");const l=new TransformStream;r.body=l.readable;let u=((o?.authorization??"").match(/Signature=(\w+)$/)??[])[1]??(c&&c["X-Amz-Signature"])??"";i.__staticSignature&&(u="");const d=new BWe(u,await this.messageSigner(),this.eventStreamCodec,this.systemClockOffsetProvider);a.pipeThrough(d).pipeThrough(l);let p;try{p=await t(n)}catch(f){const h=a.cancel?.();throw h instanceof Promise&&h.catch(()=>{}),f}return p}}const zWe=e=>new WWe(e),GWe=!1,HWe=!1,fG=new Set,VWe=(e,t=_k)=>{if(!fG.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 fG.add(e)},Uge=e=>typeof e=="string"&&(e.startsWith("fips-")||e.endsWith("-fips")),JWe=e=>Uge(e)?["fips-aws-global","aws-fips"].includes(e)?"us-east-1":e.replace(/fips-(dkr-|prod-)?|-fips/,""):e,KWe=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=JWe(i);return VWe(r),r},useFipsEndpoint:async()=>{const i=typeof t=="string"?t:await t();return Uge(i)?!0:typeof n!="function"?Promise.resolve(!!n):n()}})},XWe=e=>Object.assign(e,{eventStreamMarshaller:e.eventStreamSerdeProvider(e)}),hG="content-length";function ZWe(e){return t=>async n=>{const i=n.request;if(Ga.isInstance(i)){const{body:r,headers:a}=i;if(r&&Object.keys(a).map(o=>o.toLowerCase()).indexOf(hG)===-1)try{const o=e(r);i.headers={...i.headers,[hG]:String(o)}}catch{}}return t({...n,request:i})}}const YWe={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},QWe=e=>({applyToStack:t=>{t.add(ZWe(e.bodyLengthChecker),YWe)}}),eze=async e=>{const t=e?.Bucket||"";if(typeof e.Bucket=="string"&&(e.Bucket=t.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),aze(t)){if(e.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!ize(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},tze=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,nze=/(\d+\.){3}\d+/,rze=/\.\./,ize=e=>tze.test(e)&&!nze.test(e)&&!rze.test(e),aze=e=>{const[t,n,i,,,r]=e.split(":"),a=t==="arn"&&e.split(":").length>=6,o=!!(a&&n&&i&&r);if(a&&!o)throw new Error(`Invalid ARN: ${e} was an invalid ARN.`);return o},sze=(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:o,hostname:c,port:l,path:s}=a;return`${o}//${c}${l?":"+l:""}${s}`}}return a}:r},qge=async e=>{},Bge=e=>typeof e=="object"?"url"in e?U3(e.url):e:U3(e),oze=async(e,t,n,i)=>{if(!n.isCustomEndpoint){let o;n.serviceConfiguredEndpoint?o=await n.serviceConfiguredEndpoint():o=await qge(n.serviceId),o&&(n.endpoint=()=>Promise.resolve(Bge(o)),n.isCustomEndpoint=!0)}const r=await lze(e,t,n);if(typeof n.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");return n.endpointProvider(r,i)},lze=async(e,t,n)=>{const i={},r=t?.getEndpointParameterInstructions?.()||{};for(const[a,o]of Object.entries(r))switch(o.type){case"staticContextParams":i[a]=o.value;break;case"contextParams":i[a]=e[o.name];break;case"clientContextParams":case"builtInParams":i[a]=await sze(o.name,a,n,o.type!=="builtInParams")();break;case"operationContextParams":i[a]=o.get(e);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(o))}return Object.keys(r).length===0&&Object.assign(i,n),String(n.serviceId).toLowerCase()==="s3"&&await eze(i),i},cze=({config:e,instructions:t})=>(n,i)=>async r=>{e.isCustomEndpoint&&fqe(i,"ENDPOINT_OVERRIDE","N");const a=await oze(r.input,{getEndpointParameterInstructions(){return t}},{...e},i);i.endpointV2=a,i.authSchemes=a.properties?.authSchemes;const o=i.authSchemes?.[0];if(o){i.signing_region=o.signingRegion,i.signing_service=o.signingName;const l=nw(i)?.selectedHttpAuthScheme?.httpAuthOption;l&&(l.signingProperties=Object.assign(l.signingProperties||{},{signing_region:o.signingRegion,signingRegion:o.signingRegion,signing_service:o.signingName,signingName:o.signingName,signingRegionSet:o.signingRegionSet},o.properties))}return n({...r})},uze={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:sUe.name},dze=(e,t)=>({applyToStack:n=>{n.addRelativeTo(cze({config:e,instructions:t}),uze)}}),pze=e=>{const t=e.tls??!0,{endpoint:n,useDualstackEndpoint:i,useFipsEndpoint:r}=e,a=n!=null?async()=>Bge(await eg(n)()):void 0,c=Object.assign(e,{endpoint:a,tls:t,isCustomEndpoint:!!n,useDualstackEndpoint:eg(i??!1),useFipsEndpoint:eg(r??!1)});let l;return c.serviceConfiguredEndpoint=async()=>(e.serviceId&&!l&&(l=qge(e.serviceId)),l),c};var D0;(function(e){e.STANDARD="standard",e.ADAPTIVE="adaptive"})(D0||(D0={}));const W3=3,fze=D0.STANDARD,hze=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],mze=["TimeoutError","RequestTimeout","RequestTimeoutException"],gze=[500,502,503,504],yze=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],vze=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND"],bze=e=>e?.$retryable!==void 0,wze=e=>e.$metadata?.clockSkewCorrected,_ze=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},Wge=e=>e.$metadata?.httpStatusCode===429||hze.includes(e.name)||e.$retryable?.throttling==!0,Y7=(e,t=0)=>bze(e)||wze(e)||mze.includes(e.name)||yze.includes(e?.code||"")||vze.includes(e?.code||"")||gze.includes(e.$metadata?.httpStatusCode||0)||_ze(e)||e.cause!==void 0&&t<=10&&Y7(e.cause,t+1),xze=e=>{if(e.$metadata?.httpStatusCode!==void 0){const t=e.$metadata.httpStatusCode;return 500<=t&&t<=599&&!Y7(e)}return!1};class Q7{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=>Q7.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(),Wge(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 mM=100,zge=20*1e3,Sze=500,mG=500,Tze=5,Cze=10,Eze=1,Aze="amz-sdk-invocation-id",kze="amz-sdk-request",Rze=()=>{let e=mM;return{computeNextBackoffDelay:i=>Math.floor(Math.min(zge,Math.random()*2**i*e)),setDelayBase:i=>{e=i}}},gG=({retryDelay:e,retryCount:t,retryCost:n})=>({getRetryCount:()=>t,getRetryDelay:()=>Math.min(zge,e),getRetryCost:()=>n});class Gge{maxAttempts;mode=D0.STANDARD;capacity=mG;retryBackoffStrategy=Rze();maxAttemptsProvider;constructor(t){this.maxAttempts=t,this.maxAttemptsProvider=typeof t=="function"?t:async()=>t}async acquireInitialRetryToken(t){return gG({retryDelay:mM,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"?Sze:mM);const a=this.retryBackoffStrategy.computeNextBackoffDelay(t.getRetryCount()),o=n.retryAfterHint?Math.max(n.retryAfterHint.getTime()-Date.now()||0,a):a,c=this.getCapacityCost(r);return this.capacity-=c,gG({retryDelay:o,retryCount:t.getRetryCount()+1,retryCost:c})}throw new Error("No retry token available")}recordSuccess(t){this.capacity=Math.max(mG,this.capacity+(t.getRetryCost()??Eze))}getCapacity(){return this.capacity}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch{return console.warn(`Max attempts provider could not resolve. Using default of ${W3}`),W3}}shouldRetry(t,n,i){return t.getRetryCount()+1<i&&this.capacity>=this.getCapacityCost(n.errorType)&&this.isRetryableError(n.errorType)}getCapacityCost(t){return t==="TRANSIENT"?Cze:Tze}isRetryableError(t){return t==="THROTTLING"||t==="TRANSIENT"}}class Oze{maxAttemptsProvider;rateLimiter;standardRetryStrategy;mode=D0.ADAPTIVE;constructor(t,n){this.maxAttemptsProvider=t;const{rateLimiter:i}=n??{};this.rateLimiter=i??new Q7,this.standardRetryStrategy=new Gge(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 Ize=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}`),Pze=e=>{const{retryStrategy:t,retryMode:n,maxAttempts:i}=e,r=eg(i??W3);return Object.assign(e,{maxAttempts:r,retryStrategy:async()=>t||(await eg(n)()===D0.ADAPTIVE?new Oze(r):new Gge(r))})},Mze=e=>e?.body instanceof ReadableStream,Nze=e=>(t,n)=>async i=>{let r=await e.retryStrategy();const a=await e.maxAttempts();if($ze(r)){r=r;let o=await r.acquireInitialRetryToken(n.partition_id),c=new Error,l=0,s=0;const{request:u}=i,d=Ga.isInstance(u);for(d&&(u.headers[Aze]=q7());;)try{d&&(u.headers[kze]=`attempt=${l+1}; max=${a}`);const{response:p,output:f}=await t(i);return r.recordSuccess(o),f.$metadata.attempts=l+1,f.$metadata.totalRetryDelay=s,{response:p,output:f}}catch(p){const f=Dze(p);if(c=Ize(p),d&&Mze(u))throw(n.logger instanceof lge?console:n.logger)?.warn("An error was encountered in a non-retryable streaming request."),c;try{o=await r.refreshRetryTokenForRetry(o,f)}catch{throw c.$metadata||(c.$metadata={}),c.$metadata.attempts=l+1,c.$metadata.totalRetryDelay=s,c}l=o.getRetryCount();const h=o.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)},$ze=e=>typeof e.acquireInitialRetryToken<"u"&&typeof e.refreshRetryTokenForRetry<"u"&&typeof e.recordSuccess<"u",Dze=e=>{const t={error:e,errorType:jze(e)},n=Uze(e.$response);return n&&(t.retryAfterHint=n),t},jze=e=>Wge(e)?"THROTTLING":Y7(e)?"TRANSIENT":xze(e)?"SERVER_ERROR":"CLIENT_ERROR",Lze={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0},Fze=e=>({applyToStack:t=>{t.add(Nze(e),Lze)}}),Uze=e=>{if(!Rv.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)},qze=async(e,t,n)=>({operation:nw(t).operation,region:await eg(e.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function Bze(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"bedrock",region:e.region},propertiesExtractor:(t,n)=>({signingProperties:{config:t,context:n}})}}function Wze(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 zze=e=>{const t=[];switch(e.operation){default:t.push(Bze(e)),t.push(Wze())}return t},Gze=e=>{const t=Fme(e.token,Lme,G7),n=CBe(e);return Object.assign(n,{authSchemePreference:eg(e.authSchemePreference??[]),token:t})},Hze=e=>Object.assign(e,{useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,defaultSigningName:"bedrock"}),Vze={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},Jze="3.1000.0",Kze={version:Jze};var Hge={name:"SHA-256"},yG={name:"HMAC",hash:Hge},Xze=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 Zze={};function vE(){return typeof window<"u"?window:typeof self<"u"?self:Zze}var Yze=(function(){function e(t){this.toHash=new Uint8Array(0),this.secret=t,this.reset()}return e.prototype.update=function(t){if(!hM(t)){var n=u2(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 vE().crypto.subtle.sign(yG,n,t.toHash).then(function(i){return new Uint8Array(i)})}):hM(this.toHash)?Promise.resolve(Xze):Promise.resolve().then(function(){return vE().crypto.subtle.digest(Hge,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){vE().crypto.subtle.importKey("raw",u2(t.secret),yG,!1,["sign"]).then(n,i)}),this.key.catch(function(){}))},e})(),no=64,Qze=32,eGe=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]),tGe=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],nGe=Math.pow(2,53)-1,bE=(function(){function e(){this.state=Int32Array.from(tGe),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>nGe)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;i>0;)this.buffer[this.bufferLength++]=t[n++],i--,this.bufferLength===no&&(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%no>=no-8){for(var r=this.bufferLength;r<no;r++)n.setUint8(r,0);this.hashBuffer(),this.bufferLength=0}for(var r=this.bufferLength;r<no-8;r++)n.setUint8(r,0);n.setUint32(no-8,Math.floor(t/4294967296),!0),n.setUint32(no-4,t),this.hashBuffer(),this.finished=!0}for(var a=new Uint8Array(Qze),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],o=i[2],c=i[3],l=i[4],s=i[5],u=i[6],d=i[7],p=0;p<no;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=(((l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7))+(l&s^~l&u)|0)+(d+(eGe[p]+this.temp[p]|0)|0)|0,y=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&a^r&o^a&o)|0;d=u,u=s,s=l,l=c+g|0,c=o,o=a,a=r,r=g+y|0}i[0]+=r,i[1]+=a,i[2]+=o,i[3]+=c,i[4]+=l,i[5]+=s,i[6]+=u,i[7]+=d},e})(),rGe=(function(){function e(t){this.secret=t,this.hash=new bE,this.reset()}return e.prototype.update=function(t){if(!(hM(t)||this.error))try{this.hash.update(u2(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 J7(this,void 0,void 0,function(){return K7(this,function(t){return[2,this.digestSync()]})})},e.prototype.reset=function(){if(this.hash=new bE,this.secret){this.outer=new bE;var t=iGe(this.secret),n=new Uint8Array(no);n.set(t);for(var i=0;i<no;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 iGe(e){var t=u2(e);if(t.byteLength>no){var n=new bE;n.update(t),t=n.digest()}var i=new Uint8Array(no);return i.set(t),i}var aGe=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function sGe(e){if(oGe(e)&&typeof e.crypto.subtle=="object"){var t=e.crypto.subtle;return lGe(t)}return!1}function oGe(e){if(typeof e=="object"&&typeof e.crypto=="object"){var t=e.crypto.getRandomValues;return typeof t=="function"}return!1}function lGe(e){return e&&aGe.every(function(t){return typeof e[t]=="function"})}var cGe=(function(){function e(t){sGe(vE())?this.hash=new Yze(t):this.hash=new rGe(t)}return e.prototype.update=function(t,n){this.hash.update(u2(t))},e.prototype.digest=function(){return this.hash.digest()},e.prototype.reset=function(){this.hash.reset()},e})();const uGe=({serviceId:e,clientVersion:t})=>async n=>{const i=typeof window<"u"?window.navigator:void 0,r=i?.userAgent??"",a=i?.userAgentData?.platform??vG.os(r)??"other",o=void 0,c=i?.userAgentData?.brands??[],l=c[c.length-1],s=l?.brand??vG.browser(r)??"unknown",u=l?.version??"unknown",d=[["aws-sdk-js",t],["ua","2.1"],[`os/${a}`,o],["lang/js"],["md/browser",`${s}_${u}`]];e&&d.push([`api/${e}`,t]);const p=await n?.userAgentAppId?.();return p&&d.push([`app/${p}`]),d},vG={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"}},dGe=e=>()=>Promise.reject(e),pGe=["in-region","cross-region","mobile","standard","legacy"],fGe=({defaultsMode:e}={})=>Yqe(async()=>{const t=typeof e=="function"?await e():e;switch(t?.toLowerCase()){case"auto":return Promise.resolve(hGe()?"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 ${pGe.join(", ")}, got ${t}`)}}),hGe=()=>{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},Vge="required",au="fn",su="argv",iw="ref",bG=!0,wG="isSet",d2="booleanEquals",Ab="error",m1="endpoint",Ca="tree",e$="PartitionResult",_G={[Vge]:!1,type:"string"},xG={[Vge]:!0,default:!1,type:"boolean"},SG={[iw]:"Endpoint"},Jge={[au]:d2,[su]:[{[iw]:"UseFIPS"},!0]},Kge={[au]:d2,[su]:[{[iw]:"UseDualStack"},!0]},bl={},TG={[au]:"getAttr",[su]:[{[iw]:e$},"supportsFIPS"]},CG={[au]:d2,[su]:[!0,{[au]:"getAttr",[su]:[{[iw]:e$},"supportsDualStack"]}]},EG=[Jge],AG=[Kge],kG=[{[iw]:"Region"}],mGe={parameters:{Region:_G,UseDualStack:xG,UseFIPS:xG,Endpoint:_G},rules:[{conditions:[{[au]:wG,[su]:[SG]}],rules:[{conditions:EG,error:"Invalid Configuration: FIPS and custom endpoint are not supported",type:Ab},{rules:[{conditions:AG,error:"Invalid Configuration: Dualstack and custom endpoint are not supported",type:Ab},{endpoint:{url:SG,properties:bl,headers:bl},type:m1}],type:Ca}],type:Ca},{rules:[{conditions:[{[au]:wG,[su]:kG}],rules:[{conditions:[{[au]:"aws.partition",[su]:kG,assign:e$}],rules:[{conditions:[Jge,Kge],rules:[{conditions:[{[au]:d2,[su]:[bG,TG]},CG],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:bl,headers:bl},type:m1}],type:Ca}],type:Ca},{error:"FIPS and DualStack are enabled, but this partition does not support one or both",type:Ab}],type:Ca},{conditions:EG,rules:[{conditions:[{[au]:d2,[su]:[TG,bG]}],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime-fips.{Region}.{PartitionResult#dnsSuffix}",properties:bl,headers:bl},type:m1}],type:Ca}],type:Ca},{error:"FIPS is enabled but this partition does not support FIPS",type:Ab}],type:Ca},{conditions:AG,rules:[{conditions:[CG],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:bl,headers:bl},type:m1}],type:Ca}],type:Ca},{error:"DualStack is enabled but this partition does not support DualStack",type:Ab}],type:Ca},{rules:[{endpoint:{url:"https://bedrock-runtime.{Region}.{PartitionResult#dnsSuffix}",properties:bl,headers:bl},type:m1}],type:Ca}],type:Ca}],type:Ca},{error:"Invalid Configuration: Missing Region",type:Ab}],type:Ca}]},gGe=mGe,yGe=new _qe({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),vGe=(e,t={})=>yGe.get(e,()=>Uqe(gGe,{endpointParams:e,logger:t.logger}));F3.aws=Zme;class Ha extends f0{constructor(t){super(t),Object.setPrototypeOf(this,Ha.prototype)}}class t$ extends Ha{name="AccessDeniedException";$fault="client";constructor(t){super({name:"AccessDeniedException",$fault:"client",...t}),Object.setPrototypeOf(this,t$.prototype)}}class n$ extends Ha{name="InternalServerException";$fault="server";constructor(t){super({name:"InternalServerException",$fault:"server",...t}),Object.setPrototypeOf(this,n$.prototype)}}class r$ extends Ha{name="ThrottlingException";$fault="client";constructor(t){super({name:"ThrottlingException",$fault:"client",...t}),Object.setPrototypeOf(this,r$.prototype)}}class i$ extends Ha{name="ValidationException";$fault="client";constructor(t){super({name:"ValidationException",$fault:"client",...t}),Object.setPrototypeOf(this,i$.prototype)}}class a$ extends Ha{name="ConflictException";$fault="client";constructor(t){super({name:"ConflictException",$fault:"client",...t}),Object.setPrototypeOf(this,a$.prototype)}}class s$ extends Ha{name="ResourceNotFoundException";$fault="client";constructor(t){super({name:"ResourceNotFoundException",$fault:"client",...t}),Object.setPrototypeOf(this,s$.prototype)}}class o$ extends Ha{name="ServiceQuotaExceededException";$fault="client";constructor(t){super({name:"ServiceQuotaExceededException",$fault:"client",...t}),Object.setPrototypeOf(this,o$.prototype)}}class l$ extends Ha{name="ServiceUnavailableException";$fault="server";constructor(t){super({name:"ServiceUnavailableException",$fault:"server",...t}),Object.setPrototypeOf(this,l$.prototype)}}class c$ extends Ha{name="ModelErrorException";$fault="client";originalStatusCode;resourceName;constructor(t){super({name:"ModelErrorException",$fault:"client",...t}),Object.setPrototypeOf(this,c$.prototype),this.originalStatusCode=t.originalStatusCode,this.resourceName=t.resourceName}}class u$ extends Ha{name="ModelNotReadyException";$fault="client";$retryable={};constructor(t){super({name:"ModelNotReadyException",$fault:"client",...t}),Object.setPrototypeOf(this,u$.prototype)}}class d$ extends Ha{name="ModelTimeoutException";$fault="client";constructor(t){super({name:"ModelTimeoutException",$fault:"client",...t}),Object.setPrototypeOf(this,d$.prototype)}}class p$ extends Ha{name="ModelStreamErrorException";$fault="client";originalStatusCode;originalMessage;constructor(t){super({name:"ModelStreamErrorException",$fault:"client",...t}),Object.setPrototypeOf(this,p$.prototype),this.originalStatusCode=t.originalStatusCode,this.originalMessage=t.originalMessage}}const bGe="AudioBlock",wGe="AccessDeniedException",_Ge="AppliedGuardrailDetails",xGe="AudioSource",SGe="AnyToolChoice",TGe="AutoToolChoice",CGe="Citation",EGe="ContentBlocks",AGe="ContentBlockDelta",kGe="ContentBlockDeltaEvent",RGe="ContentBlockStart",OGe="ContentBlockStartEvent",IGe="ContentBlockStopEvent",PGe="ContentBlock",MGe="CitationsConfig",NGe="CitationsContentBlock",$Ge="CacheDetail",DGe="CacheDetailsList",jGe="CitationsDelta",LGe="ConflictException",FGe="CitationGeneratedContent",UGe="CitationGeneratedContentList",qGe="CitationLocation",BGe="CachePointBlock",WGe="ConverseStream",zGe="CitationSourceContent",GGe="CitationSourceContentDelta",HGe="CitationSourceContentList",VGe="CitationSourceContentListDelta",JGe="ConverseStreamMetrics",KGe="ConverseStreamMetadataEvent",XGe="ConverseStreamOutput",ZGe="ConverseStreamRequest",YGe="ConverseStreamResponse",QGe="ConverseStreamTrace",eHe="Citations",tHe="DocumentBlock",nHe="DocumentContentBlocks",rHe="DocumentContentBlock",iHe="DocumentCharLocation",aHe="DocumentChunkLocation",sHe="DocumentPageLocation",oHe="DocumentSource",lHe="ErrorBlock",cHe="GuardrailAssessment",uHe="GuardrailAssessmentList",dHe="GuardrailAssessmentListMap",pHe="GuardrailAssessmentMap",fHe="GuardrailAutomatedReasoningDifferenceScenarioList",hHe="GuardrailAutomatedReasoningFinding",mHe="GuardrailAutomatedReasoningFindingList",gHe="GuardrailAutomatedReasoningImpossibleFinding",yHe="GuardrailAutomatedReasoningInvalidFinding",vHe="GuardrailAutomatedReasoningInputTextReference",bHe="GuardrailAutomatedReasoningInputTextReferenceList",wHe="GuardrailAutomatedReasoningLogicWarning",_He="GuardrailAutomatedReasoningNoTranslationsFinding",xHe="GuardrailAutomatedReasoningPolicyAssessment",SHe="GuardrailAutomatedReasoningRule",THe="GuardrailAutomatedReasoningRuleList",CHe="GuardrailAutomatedReasoningScenario",EHe="GuardrailAutomatedReasoningSatisfiableFinding",AHe="GuardrailAutomatedReasoningStatementList",kHe="GuardrailAutomatedReasoningStatementLogicContent",RHe="GuardrailAutomatedReasoningStatementNaturalLanguageContent",OHe="GuardrailAutomatedReasoningStatement",IHe="GuardrailAutomatedReasoningTranslation",PHe="GuardrailAutomatedReasoningTranslationAmbiguousFinding",MHe="GuardrailAutomatedReasoningTooComplexFinding",NHe="GuardrailAutomatedReasoningTranslationList",$He="GuardrailAutomatedReasoningTranslationOption",DHe="GuardrailAutomatedReasoningTranslationOptionList",jHe="GuardrailAutomatedReasoningValidFinding",LHe="GuardrailConverseContentBlock",FHe="GuardrailContentFilter",UHe="GuardrailContentFilterList",qHe="GuardrailContextualGroundingFilter",BHe="GuardrailContextualGroundingFilters",WHe="GuardrailContextualGroundingPolicyAssessment",zHe="GuardrailConverseImageBlock",GHe="GuardrailConverseImageSource",HHe="GuardrailContentPolicyAssessment",VHe="GuardrailConverseTextBlock",JHe="GuardrailCustomWord",KHe="GuardrailCustomWordList",XHe="GuardrailCoverage",ZHe="GuardrailImageCoverage",YHe="GuardrailInvocationMetrics",QHe="GuardrailManagedWord",eVe="GuardrailManagedWordList",tVe="GuardrailPiiEntityFilter",nVe="GuardrailPiiEntityFilterList",rVe="GuardrailRegexFilter",iVe="GuardrailRegexFilterList",aVe="GuardrailStreamConfiguration",sVe="GuardrailSensitiveInformationPolicyAssessment",oVe="GuardrailTopic",lVe="GuardrailTraceAssessment",cVe="GuardrailTextCharactersCoverage",uVe="GuardrailTopicList",dVe="GuardrailTopicPolicyAssessment",pVe="GuardrailUsage",fVe="GuardrailWordPolicyAssessment",hVe="ImageBlock",mVe="ImageBlockDelta",gVe="ImageBlockStart",yVe="InferenceConfiguration",vVe="ImageSource",bVe="InternalServerException",wVe="JsonSchemaDefinition",_Ve="Message",xVe="ModelErrorException",SVe="ModelNotReadyException",TVe="MessageStartEvent",CVe="ModelStreamErrorException",EVe="MessageStopEvent",AVe="ModelTimeoutException",kVe="Messages",RVe="OutputConfig",OVe="OutputFormat",IVe="OutputFormatStructure",PVe="PerformanceConfiguration",MVe="PromptRouterTrace",NVe="PromptVariableMap",$Ve="PromptVariableValues",DVe="ReasoningContentBlock",jVe="ReasoningContentBlockDelta",LVe="RequestMetadata",FVe="ResourceNotFoundException",UVe="ReasoningTextBlock",qVe="SystemContentBlocks",BVe="SystemContentBlock",WVe="S3Location",zVe="ServiceQuotaExceededException",GVe="SearchResultBlock",HVe="SearchResultContentBlock",VVe="SearchResultContentBlocks",JVe="SearchResultLocation",KVe="ServiceTier",XVe="SpecificToolChoice",ZVe="SystemTool",YVe="ServiceUnavailableException",QVe="ToolConfiguration",eJe="ToolChoice",tJe="ThrottlingException",nJe="ToolInputSchema",rJe="ToolResultBlock",iJe="ToolResultBlocksDelta",aJe="ToolResultBlockDelta",sJe="ToolResultBlockStart",oJe="ToolResultContentBlocks",lJe="ToolResultContentBlock",cJe="ToolSpecification",uJe="TokenUsage",dJe="ToolUseBlock",pJe="ToolUseBlockDelta",fJe="ToolUseBlockStart",hJe="Tools",mJe="Tool",gJe="VideoBlock",yJe="ValidationException",vJe="VideoSource",bJe="WebLocation",Wv="action",wJe="appliedGuardrailDetails",_Je="additionalModelRequestFields",xJe="additionalModelResponseFieldPaths",SJe="additionalModelResponseFields",TJe="actionReason",CJe="automatedReasoningPolicy",EJe="automatedReasoningPolicyUnits",AJe="automatedReasoningPolicies",kJe="any",RJe="audio",OJe="auto",q2="bytes",IJe="bucketOwner",xu="client",PJe="contentBlockDelta",f$="contentBlockIndex",MJe="contentBlockStart",NJe="contentBlockStop",$Je="citationsContent",DJe="cacheDetails",jJe="claimsFalseScenario",LJe="contextualGroundingPolicy",FJe="contextualGroundingPolicyUnits",UJe="contentPolicy",qJe="contentPolicyImageUnits",BJe="contentPolicyUnits",h$="cachePoint",Xge="contradictingRules",WJe="cacheReadInputTokens",Zge="claimsTrueScenario",zJe="customWords",GJe="cacheWriteInputTokens",m$="citations",HJe="citation",Yge="claims",B2="content",VJe="context",Qge="confidence",JJe="delta",KJe="documentChar",XJe="documentChunk",g$="documentIndex",ZJe="documentPage",YJe="differenceScenarios",zv="detected",eye="description",QJe="domain",tye="document",Va="error",eKe="enabled",Tk="end",aw="format",tKe="filterStrength",nKe="findings",nye="filters",rKe="guardrail",iKe="guardrailArn",aKe="guardrailCoverage",sKe="guardrailConfig",rye="guardContent",oKe="guardrailId",lKe="guardrailIdentifier",cKe="guardrailOrigin",uKe="guardrailOwnership",dKe="guardrailProcessingLatency",iye="guardrailVersion",aye="guarded",pKe="http",_o="httpError",sye="input",fKe="inputAssessment",hKe="inferenceConfig",mKe="invocationMetrics",gKe="invokedModelId",yKe="inputSchema",vKe="internalServerException",oye="inputTokens",bKe="identifier",wKe="images",W2="image",_Ke="impossible",xKe="invalid",y$="json",SKe="jsonSchema",lye="location",TKe="latencyMs",Ck="logicWarning",CKe="latency",EKe="logic",Bs="message",AKe="modelId",kKe="modelOutput",RKe="messageStart",OKe="modelStreamErrorException",IKe="messageStop",PKe="maxTokens",MKe="managedWordLists",Ek="match",NKe="messages",$Ke="metrics",DKe="metadata",cg="name",jKe="naturalLanguage",LKe="noTranslations",FKe="outputAssessments",UKe="outputConfig",qKe="originalMessage",cye="originalStatusCode",BKe="outputTokens",WKe="options",uye="premises",dye="performanceConfig",zKe="piiEntities",GKe="promptRouter",HKe="promptVariables",VKe="policyVersionArn",JKe="qualifiers",KKe="regex",pye="reasoningContent",fye="redactedContent",XKe="requestMetadata",ZKe="resourceName",YKe="reasoningText",QKe="regexes",hye="role",mye="smithy.ts.sdk.synthetic.com.amazonaws.bedrockruntime",gye="sourceContent",eXe="sensitiveInformationPolicy",tXe="sensitiveInformationPolicyFreeUnits",nXe="sensitiveInformationPolicyUnits",Ak="s3Location",rXe="streamProcessingMode",iXe="stopReason",aXe="searchResultIndex",sXe="searchResultLocation",yye="searchResult",oXe="supportingRules",lXe="stopSequences",vye="serviceTier",cXe="systemTool",uXe="serviceUnavailableException",dXe="satisfiable",pXe="score",fXe="schema",bye="server",wye="signature",ug="source",_ye="status",z2="start",hXe="statements",mXe="stream",gXe="streaming",yXe="strict",vXe="structure",bXe="system",xye="ttl",wXe="translationAmbiguous",_Xe="toolConfig",xXe="textCharacters",SXe="toolChoice",TXe="tooComplex",CXe="throttlingException",EXe="textFormat",AXe="topicPolicy",kXe="topicPolicyUnits",RXe="topP",v$="toolResult",OXe="toolSpec",IXe="totalTokens",b$="toolUse",kk="toolUseId",ha="text",PXe="temperature",MXe="threshold",w$="title",Sye="total",NXe="tools",$Xe="tool",DXe="topics",Tye="trace",Rk="translation",jXe="translations",Ws="type",Cye="usage",LXe="untranslatedClaims",FXe="untranslatedPremises",UXe="uri",qXe="url",BXe="validationException",WXe="valid",Eye="video",zXe="web",GXe="wordPolicy",HXe="wordPolicyUnits",Xe="com.amazonaws.bedrockruntime",Aye=is.for(mye);var VXe=[-3,mye,"BedrockRuntimeServiceException",0,[],[]];Aye.registerError(VXe,Ha);const zs=is.for(Xe);var JXe=[-3,Xe,wGe,{[Va]:xu,[_o]:403},[Bs],[0]];zs.registerError(JXe,t$);var KXe=[-3,Xe,LGe,{[Va]:xu,[_o]:400},[Bs],[0]];zs.registerError(KXe,a$);var kye=[-3,Xe,bVe,{[Va]:bye,[_o]:500},[Bs],[0]];zs.registerError(kye,n$);var XXe=[-3,Xe,xVe,{[Va]:xu,[_o]:424},[Bs,cye,ZKe],[0,1,0]];zs.registerError(XXe,c$);var ZXe=[-3,Xe,SVe,{[Va]:xu,[_o]:429},[Bs],[0]];zs.registerError(ZXe,u$);var Rye=[-3,Xe,CVe,{[Va]:xu,[_o]:424},[Bs,cye,qKe],[0,1,0]];zs.registerError(Rye,p$);var YXe=[-3,Xe,AVe,{[Va]:xu,[_o]:408},[Bs],[0]];zs.registerError(YXe,d$);var QXe=[-3,Xe,FVe,{[Va]:xu,[_o]:404},[Bs],[0]];zs.registerError(QXe,s$);var eZe=[-3,Xe,zVe,{[Va]:xu,[_o]:400},[Bs],[0]];zs.registerError(eZe,o$);var Oye=[-3,Xe,YVe,{[Va]:bye,[_o]:503},[Bs],[0]];zs.registerError(Oye,l$);var Iye=[-3,Xe,tJe,{[Va]:xu,[_o]:429},[Bs],[0]];zs.registerError(Iye,r$);var Pye=[-3,Xe,yJe,{[Va]:xu,[_o]:400},[Bs],[0]];zs.registerError(Pye,i$);const tZe=[Aye,zs];var nZe=[0,Xe,kHe,8,0],Mye=[0,Xe,RHe,8,0],rZe=[3,Xe,SGe,0,[],[]],iZe=[3,Xe,_Ge,0,[oKe,iye,iKe,cKe,uKe],[0,0,0,64,0]],aZe=[3,Xe,bGe,0,[aw,ug,Va],[0,[()=>tQe,0],[()=>x$,0]],2],sZe=[3,Xe,TGe,0,[],[]],oZe=[3,Xe,$Ge,0,[xye,oye],[0,1],2],_$=[3,Xe,BGe,0,[Ws,xye],[0,0],1],lZe=[3,Xe,CGe,0,[w$,ug,gye,lye],[0,0,()=>RYe,()=>Bye]],Nye=[3,Xe,MGe,0,[eKe],[2],1],cZe=[3,Xe,NGe,0,[B2,m$],[()=>AYe,()=>kYe]],uZe=[3,Xe,jGe,0,[w$,ug,gye,lye],[0,0,()=>OYe,()=>Bye]],dZe=[3,Xe,GGe,0,[ha],[0]],pZe=[3,Xe,kGe,0,[JJe,f$],[[()=>aQe,0],1],2],fZe=[3,Xe,OGe,0,[z2,f$],[()=>sQe,1],2],hZe=[3,Xe,IGe,0,[f$],[1],1],mZe=[3,Xe,KGe,0,[Cye,$Ke,Tye,dye,vye],[()=>yYe,()=>gZe,[()=>bZe,0],()=>Lye,()=>Uye],2],gZe=[3,Xe,JGe,0,[TKe],[1],1],yZe=[3,Xe,ZGe,0,[AKe,NKe,bXe,hKe,_Xe,sKe,_Je,HKe,xJe,XKe,dye,vye,UKe],[[0,1],[()=>GYe,0],[()=>VYe,0],()=>iYe,()=>vYe,()=>KZe,15,[()=>QYe,0],64,[()=>eQe,0],()=>Lye,()=>Uye,[()=>cYe,0]],1],vZe=[3,Xe,YGe,0,[mXe],[[()=>oQe,16]]],bZe=[3,Xe,QGe,0,[rKe,GKe],[[()=>QZe,0],()=>dYe]],$ye=[3,Xe,tHe,0,[cg,ug,aw,VJe,m$],[0,()=>cQe,0,0,()=>Nye],2],wZe=[3,Xe,iHe,0,[g$,z2,Tk],[1,1,1]],_Ze=[3,Xe,aHe,0,[g$,z2,Tk],[1,1,1]],xZe=[3,Xe,sHe,0,[g$,z2,Tk],[1,1,1]],x$=[3,Xe,lHe,8,[Bs],[0]],Dye=[3,Xe,cHe,0,[AXe,UJe,GXe,eXe,LJe,CJe,mKe,wJe],[()=>YZe,()=>DZe,()=>tYe,()=>JZe,()=>LZe,[()=>AZe,0],()=>zZe,()=>iZe]],SZe=[3,Xe,gHe,0,[Rk,Xge,Ck],[[()=>G2,0],()=>S$,[()=>Ok,0]]],TZe=[3,Xe,vHe,0,[ha],[[()=>Mye,0]]],CZe=[3,Xe,yHe,0,[Rk,Xge,Ck],[[()=>G2,0],()=>S$,[()=>Ok,0]]],Ok=[3,Xe,wHe,0,[Ws,uye,Yge],[0,[()=>p2,0],[()=>p2,0]]],EZe=[3,Xe,_He,0,[],[]],AZe=[3,Xe,xHe,0,[nKe],[[()=>$Ye,0]]],kZe=[3,Xe,SHe,0,[bKe,VKe],[0,0]],RZe=[3,Xe,EHe,0,[Rk,Zge,jJe,Ck],[[()=>G2,0],[()=>z3,0],[()=>z3,0],[()=>Ok,0]]],z3=[3,Xe,CHe,0,[hXe],[[()=>p2,0]]],OZe=[3,Xe,OHe,0,[EKe,jKe],[[()=>nZe,0],[()=>Mye,0]]],IZe=[3,Xe,MHe,0,[],[]],G2=[3,Xe,IHe,0,[uye,Yge,FXe,LXe,Qge],[[()=>p2,0],[()=>p2,0],[()=>RG,0],[()=>RG,0],1]],PZe=[3,Xe,PHe,0,[WKe,YJe],[[()=>jYe,0],[()=>NYe,0]]],MZe=[3,Xe,$He,0,[jXe],[[()=>DYe,0]]],NZe=[3,Xe,jHe,0,[Rk,Zge,oXe,Ck],[[()=>G2,0],[()=>z3,0],()=>S$,[()=>Ok,0]]],$Ze=[3,Xe,FHe,0,[Ws,Qge,Wv,tKe,zv],[0,0,0,0,2],3],DZe=[3,Xe,HHe,0,[nye],[()=>LYe],1],jZe=[3,Xe,qHe,0,[Ws,MXe,pXe,Wv,zv],[0,1,1,0,2],4],LZe=[3,Xe,WHe,0,[nye],[()=>FYe]],FZe=[3,Xe,zHe,8,[aw,ug],[0,[()=>dQe,0]],2],UZe=[3,Xe,VHe,0,[ha,JKe],[0,64],1],qZe=[3,Xe,XHe,0,[xXe,wKe],[()=>XZe,()=>WZe]],BZe=[3,Xe,JHe,0,[Ek,Wv,zv],[0,0,2],2],WZe=[3,Xe,ZHe,0,[aye,Sye],[1,1]],zZe=[3,Xe,YHe,0,[dKe,Cye,aKe],[1,()=>eYe,()=>qZe]],GZe=[3,Xe,QHe,0,[Ek,Ws,Wv,zv],[0,0,0,2],3],HZe=[3,Xe,tVe,0,[Ek,Ws,Wv,zv],[0,0,0,2],3],VZe=[3,Xe,rVe,0,[Wv,cg,Ek,KKe,zv],[0,0,0,0,2],1],JZe=[3,Xe,sVe,0,[zKe,QKe],[()=>BYe,()=>WYe],2],KZe=[3,Xe,aVe,0,[lKe,iye,Tye,rXe],[0,0,0,0]],XZe=[3,Xe,cVe,0,[aye,Sye],[1,1]],ZZe=[3,Xe,oVe,0,[cg,Ws,Wv,zv],[0,0,0,2],3],YZe=[3,Xe,dVe,0,[DXe],[()=>zYe],1],QZe=[3,Xe,lVe,0,[kKe,fKe,FKe,TJe],[64,[()=>YYe,0],[()=>ZYe,0],0]],eYe=[3,Xe,pVe,0,[kXe,BJe,HXe,nXe,tXe,FJe,qJe,EJe,AJe],[1,1,1,1,1,1,1,1,1],6],tYe=[3,Xe,fVe,0,[zJe,MKe],[()=>UYe,()=>qYe],2],jye=[3,Xe,hVe,0,[aw,ug,Va],[0,[()=>zye,0],[()=>x$,0]],2],nYe=[3,Xe,mVe,0,[ug,Va],[[()=>zye,0],[()=>x$,0]]],rYe=[3,Xe,gVe,0,[aw],[0],1],iYe=[3,Xe,yVe,0,[PKe,PXe,RXe,lXe],[1,1,1,64]],aYe=[3,Xe,wVe,0,[fXe,cg,eye],[0,0,0],1],sYe=[3,Xe,_Ve,0,[hye,B2],[0,[()=>IYe,0]],2],oYe=[3,Xe,TVe,0,[hye],[0],1],lYe=[3,Xe,EVe,0,[iXe,SJe],[0,15],1],cYe=[3,Xe,RVe,0,[EXe],[[()=>uYe,0]]],uYe=[3,Xe,OVe,0,[Ws,vXe],[0,[()=>pQe,0]],2],Lye=[3,Xe,PVe,0,[CKe],[0]],dYe=[3,Xe,MVe,0,[gKe],[0]],pYe=[3,Xe,UVe,8,[ha,wye],[0,0],1],Ik=[3,Xe,WVe,0,[UXe,IJe],[0,0],1],Fye=[3,Xe,GVe,0,[ug,w$,B2,m$],[0,0,()=>HYe,()=>Nye],3],fYe=[3,Xe,HVe,0,[ha],[0],1],hYe=[3,Xe,JVe,0,[aXe,z2,Tk],[1,1,1]],Uye=[3,Xe,KVe,0,[Ws],[0],1],mYe=[3,Xe,XVe,0,[cg],[0],1],gYe=[3,Xe,ZVe,0,[cg],[0],1],yYe=[3,Xe,uJe,0,[oye,BKe,IXe,WJe,GJe,DJe],[1,1,1,1,1,()=>EYe],3],vYe=[3,Xe,QVe,0,[NXe,SXe],[()=>XYe,()=>vQe],1],bYe=[3,Xe,rJe,0,[kk,B2,_ye,Ws],[0,[()=>KYe,0],0,0],2],wYe=[3,Xe,sJe,0,[kk,Ws,_ye],[0,0,0],1],_Ye=[3,Xe,cJe,0,[cg,yKe,eye,yXe],[0,()=>bQe,0,2],2],xYe=[3,Xe,dJe,0,[kk,cg,sye,Ws],[0,0,15,0],3],SYe=[3,Xe,pJe,0,[sye],[0],1],TYe=[3,Xe,fJe,0,[kk,cg,Ws],[0,0,0],2],qye=[3,Xe,gJe,0,[aw,ug],[0,()=>xQe],2],CYe=[3,Xe,bJe,0,[qXe,QJe],[0,0]],EYe=[1,Xe,DGe,0,()=>oZe],AYe=[1,Xe,UGe,0,()=>nQe],kYe=[1,Xe,eHe,0,()=>lZe],RYe=[1,Xe,HGe,0,()=>rQe],OYe=[1,Xe,VGe,0,()=>dZe],IYe=[1,Xe,EGe,0,[()=>iQe,0]],PYe=[1,Xe,nHe,0,()=>lQe],MYe=[1,Xe,uHe,0,[()=>Dye,0]],NYe=[1,Xe,fHe,0,[()=>z3,0]],$Ye=[1,Xe,mHe,0,[()=>uQe,0]],RG=[1,Xe,bHe,0,[()=>TZe,0]],S$=[1,Xe,THe,0,()=>kZe],p2=[1,Xe,AHe,0,[()=>OZe,0]],DYe=[1,Xe,NHe,0,[()=>G2,0]],jYe=[1,Xe,DHe,0,[()=>MZe,0]],LYe=[1,Xe,UHe,0,()=>$Ze],FYe=[1,Xe,BHe,0,()=>jZe],UYe=[1,Xe,KHe,0,()=>BZe],qYe=[1,Xe,eVe,0,()=>GZe],BYe=[1,Xe,nVe,0,()=>HZe],WYe=[1,Xe,iVe,0,()=>VZe],zYe=[1,Xe,uVe,0,()=>ZZe],GYe=[1,Xe,kVe,0,[()=>sYe,0]],HYe=[1,Xe,VVe,0,()=>fYe],VYe=[1,Xe,qVe,0,[()=>gQe,0]],JYe=[1,Xe,iJe,0,()=>wQe],KYe=[1,Xe,oJe,0,[()=>_Qe,0]],XYe=[1,Xe,hJe,0,()=>yQe],ZYe=[2,Xe,dHe,0,[0,0],[()=>MYe,0]],YYe=[2,Xe,pHe,0,[0,0],[()=>Dye,0]],QYe=[2,Xe,NVe,8,0,()=>fQe],eQe=[2,Xe,LVe,8,0,0],tQe=[4,Xe,xGe,8,[q2,Ak],[21,()=>Ik]],nQe=[4,Xe,FGe,0,[ha],[0]],Bye=[4,Xe,qGe,0,[zXe,KJe,ZJe,XJe,sXe],[()=>CYe,()=>wZe,()=>xZe,()=>_Ze,()=>hYe]],rQe=[4,Xe,zGe,0,[ha],[0]],iQe=[4,Xe,PGe,0,[ha,W2,tye,Eye,RJe,b$,v$,rye,h$,pye,$Je,yye],[0,[()=>jye,0],()=>$ye,()=>qye,[()=>aZe,0],()=>xYe,[()=>bYe,0],[()=>Wye,0],()=>_$,[()=>hQe,0],()=>cZe,()=>Fye]],aQe=[4,Xe,AGe,0,[ha,b$,v$,pye,HJe,W2],[0,()=>SYe,()=>JYe,[()=>mQe,0],()=>uZe,[()=>nYe,0]]],sQe=[4,Xe,RGe,0,[b$,v$,W2],[()=>TYe,()=>wYe,()=>rYe]],oQe=[4,Xe,XGe,{[gXe]:1},[RKe,MJe,PJe,NJe,IKe,DKe,vKe,OKe,BXe,CXe,uXe],[()=>oYe,()=>fZe,[()=>pZe,0],()=>hZe,()=>lYe,[()=>mZe,0],[()=>kye,0],[()=>Rye,0],[()=>Pye,0],[()=>Iye,0],[()=>Oye,0]]],lQe=[4,Xe,rHe,0,[ha],[0]],cQe=[4,Xe,oHe,0,[q2,Ak,ha,B2],[21,()=>Ik,0,()=>PYe]],uQe=[4,Xe,hHe,0,[WXe,xKe,dXe,_Ke,wXe,TXe,LKe],[[()=>NZe,0],[()=>CZe,0],[()=>RZe,0],[()=>SZe,0],[()=>PZe,0],()=>IZe,()=>EZe]],Wye=[4,Xe,LHe,0,[ha,W2],[()=>UZe,[()=>FZe,0]]],dQe=[4,Xe,GHe,8,[q2],[21]],zye=[4,Xe,vVe,8,[q2,Ak],[21,()=>Ik]],pQe=[4,Xe,IVe,8,[SKe],[()=>aYe]],fQe=[4,Xe,$Ve,0,[ha],[0]],hQe=[4,Xe,DVe,8,[YKe,fye],[[()=>pYe,0],21]],mQe=[4,Xe,jVe,8,[ha,fye,wye],[0,21,0]],gQe=[4,Xe,BVe,0,[ha,rye,h$],[0,[()=>Wye,0],()=>_$]],yQe=[4,Xe,mJe,0,[OXe,cXe,h$],[()=>_Ye,()=>gYe,()=>_$]],vQe=[4,Xe,eJe,0,[OJe,kJe,$Xe],[()=>sZe,()=>rZe,()=>mYe]],bQe=[4,Xe,nJe,0,[y$],[15]],wQe=[4,Xe,aJe,0,[ha,y$],[0,15]],_Qe=[4,Xe,lJe,0,[y$,ha,W2,tye,Eye,yye],[15,0,[()=>jye,0],()=>$ye,()=>qye,()=>Fye]],xQe=[4,Xe,vJe,0,[q2,Ak],[21,()=>Ik]],SQe=[9,Xe,WGe,{[pKe]:["POST","/model/{modelId}/converse-stream",200]},()=>yZe,()=>vZe];const TQe=e=>({apiVersion:"2023-09-30",base64Decoder:e?.base64Decoder??Ov,base64Encoder:e?.base64Encoder??Pv,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??vGe,extensions:e?.extensions??[],httpAuthSchemeProvider:e?.httpAuthSchemeProvider??zze,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:t=>t.getIdentityProvider("aws.auth#sigv4"),signer:new Zqe},{schemeId:"smithy.api#httpBearerAuth",identityProvider:t=>t.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new mqe}],logger:e?.logger??new lge,protocol:e?.protocol??JBe,protocolSettings:e?.protocolSettings??{defaultNamespace:"com.amazonaws.bedrockruntime",errorTypeRegistries:tZe,version:"2023-09-30",serviceTarget:"AmazonBedrockFrontendService"},serviceId:e?.serviceId??"Bedrock Runtime",urlParser:e?.urlParser??U3,utf8Decoder:e?.utf8Decoder??Iv,utf8Encoder:e?.utf8Encoder??rw}),CQe=e=>{const t=fGe(e),n=()=>t().then(IBe),i=TQe(e);return{...i,...e,runtime:"browser",defaultsMode:t,bodyLengthChecker:e?.bodyLengthChecker??kBe,credentialDefaultProvider:e?.credentialDefaultProvider??(r=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:e?.defaultUserAgentProvider??uGe({serviceId:i.serviceId,clientVersion:Kze.version}),eventStreamPayloadHandlerProvider:e?.eventStreamPayloadHandlerProvider??zWe,eventStreamSerdeProvider:e?.eventStreamSerdeProvider??NWe,maxAttempts:e?.maxAttempts??W3,region:e?.region??dGe("Region is missing"),requestHandler:Z7.create(e?.requestHandler??n,s2.create(n)),retryMode:e?.retryMode??(async()=>(await n()).retryMode||fze),sha256:e?.sha256??cGe,streamCollector:e?.streamCollector??Ome,useDualstackEndpoint:e?.useDualstackEndpoint??(()=>Promise.resolve(GWe)),useFipsEndpoint:e?.useFipsEndpoint??(()=>Promise.resolve(HWe))}},EQe=e=>({setRegion(t){e.region=t},region(){return e.region}}),AQe=e=>({region:e.region()}),kQe=e=>{const t=e.httpAuthSchemes;let n=e.httpAuthSchemeProvider,i=e.credentials,r=e.token;return{setHttpAuthScheme(a){const o=t.findIndex(c=>c.schemeId===a.schemeId);o===-1?t.push(a):t.splice(o,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}}},RQe=e=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials(),token:e.token()}),OQe=(e,t)=>{const n=Object.assign(EQe(e),DBe(e),WFe(e),kQe(e));return t.forEach(i=>i.configure(n)),Object.assign(e,AQe(n),jBe(n),zFe(n),RQe(n))};class IQe extends RBe{config;constructor(...[t]){const n=CQe(t||{});super(n),this.initConfig=n;const i=Hze(n),r=wqe(i),a=Pze(r),o=KWe(a),c=o,l=pze(c),s=XWe(l),u=Gze(s),d=BFe(u),p=UWe(d),f=OQe(p,t?.extensions||[]);this.config=f,this.middlewareStack.use(TUe(this.config)),this.middlewareStack.use(rWe(this.config)),this.middlewareStack.use(Fze(this.config)),this.middlewareStack.use(QWe(this.config)),this.middlewareStack.use(JFe(this.config)),this.middlewareStack.use(ZFe(this.config)),this.middlewareStack.use(eUe(this.config)),this.middlewareStack.use(aUe(this.config,{httpAuthSchemeParametersProvider:qze,identityProviderConfigProvider:async h=>new hqe({"aws.auth#sigv4":h.credentials,"smithy.api#httpBearerAuth":h.token})})),this.middlewareStack.use(dUe(this.config))}destroy(){super.destroy()}}class PQe extends sge.classBuilder().ep(Vze).m(function(t,n,i,r){return[dze(i,t.getEndpointParameterInstructions())]}).s("AmazonBedrockFrontendService","ConverseStream",{eventStream:{output:!0}}).n("BedrockRuntimeClient","ConverseStreamCommand").sc(SQe).build(){}const Gye={ONE_HOUR:"1h"},Hye={DEFAULT:"default"},gT={GIF:"gif",JPEG:"jpeg",PNG:"png",WEBP:"webp"},yT={ERROR:"error",SUCCESS:"success"},ux={ASSISTANT:"assistant",USER:"user"},g1={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 Do={};const dx=(e,t,n={})=>{const i=new bo;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,o={region:n.region,profile:n.profile};if(typeof process<"u"&&(process.versions?.node||process.versions?.bun)){if(o.region=o.region||Do.AWS_REGION||Do.AWS_DEFAULT_REGION,Do.AWS_BEDROCK_SKIP_AUTH==="1"&&(o.credentials={accessKeyId:"dummy-access-key",secretAccessKey:"dummy-secret-key"}),Do.HTTP_PROXY||Do.HTTPS_PROXY||Do.NO_PROXY||Do.http_proxy||Do.https_proxy||Do.no_proxy){const c=await Tn(()=>import("./index-9crYr7pn.js"),__vite__mapDeps([0,1])),l=await Tn(()=>import("./index-DJA4jgWl.js").then(u=>u.i),__vite__mapDeps([2,1,3,4])),s=new l.ProxyAgent;o.requestHandler=new c.NodeHttpHandler({httpAgent:s,httpsAgent:s})}else if(Do.AWS_BEDROCK_FORCE_HTTP1==="1"){const c=await Tn(()=>import("./index-9crYr7pn.js"),__vite__mapDeps([0,1]));o.requestHandler=new c.NodeHttpHandler}}o.region=o.region||"us-east-1";try{const c=new IQe(o),l=FQe(n.cacheRetention),s={modelId:e.id,messages:WQe(t,e,l),system:qQe(t.systemPrompt,e,l),inferenceConfig:{maxTokens:n.maxTokens,temperature:n.temperature},toolConfig:zQe(t.tools,n.toolChoice),additionalModelRequestFields:HQe(e,n)};n?.onPayload?.(s);const u=new PQe(s),d=await c.send(u,{abortSignal:n.signal});for await(const p of d.stream)if(p.messageStart){if(p.messageStart.role!==ux.ASSISTANT)throw new Error("Unexpected assistant message start but got user message start instead");i.push({type:"start",partial:r})}else if(p.contentBlockStart)NQe(p.contentBlockStart,a,r,i);else if(p.contentBlockDelta)$Qe(p.contentBlockDelta,a,r,i);else if(p.contentBlockStop)jQe(p.contentBlockStop,a,r,i);else if(p.messageStop)r.stopReason=GQe(p.messageStop.stopReason);else if(p.metadata)DQe(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 l of r.content)delete l.index,delete l.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},MQe=(e,t,n)=>{const i=wu(e,n,void 0);if(!n?.reasoning)return dx(e,t,{...i,reasoning:void 0});if(e.id.includes("anthropic.claude")||e.id.includes("anthropic/claude")){if(gM(e.id))return dx(e,t,{...i,reasoning:n.reasoning,thinkingBudgets:n.thinkingBudgets});const r=t7(i.maxTokens||0,e.maxTokens,n.reasoning,n.thinkingBudgets);return dx(e,t,{...i,maxTokens:r.maxTokens,reasoning:n.reasoning,thinkingBudgets:{...n.thinkingBudgets||{},[_u(n.reasoning)]:r.thinkingBudget}})}return dx(e,t,{...i,reasoning:n.reasoning,thinkingBudgets:n.thinkingBudgets})};function NQe(e,t,n,i){const r=e.contentBlockIndex,a=e.start;if(a?.toolUse){const o={type:"toolCall",id:a.toolUse.toolUseId||"",name:a.toolUse.name||"",arguments:{},partialJson:"",index:r};n.content.push(o),i.push({type:"toolcall_start",contentIndex:t.length-1,partial:n})}}function $Qe(e,t,n,i){const r=e.contentBlockIndex,a=e.delta;let o=t.findIndex(l=>l.index===r),c=t[o];if(a?.text!==void 0){if(!c){const l={type:"text",text:"",index:r};n.content.push(l),o=t.length-1,c=t[o],i.push({type:"text_start",contentIndex:o,partial:n})}c.type==="text"&&(c.text+=a.text,i.push({type:"text_delta",contentIndex:o,delta:a.text,partial:n}))}else if(a?.toolUse&&c?.type==="toolCall")c.partialJson=(c.partialJson||"")+(a.toolUse.input||""),c.arguments=cu(c.partialJson),i.push({type:"toolcall_delta",contentIndex:o,delta:a.toolUse.input||"",partial:n});else if(a?.reasoningContent){let l=c,s=o;if(!l){const u={type:"thinking",thinking:"",thinkingSignature:"",index:r};n.content.push(u),s=t.length-1,l=t[s],i.push({type:"thinking_start",contentIndex:s,partial:n})}l?.type==="thinking"&&(a.reasoningContent.text&&(l.thinking+=a.reasoningContent.text,i.push({type:"thinking_delta",contentIndex:s,delta:a.reasoningContent.text,partial:n})),a.reasoningContent.signature&&(l.thinkingSignature=(l.thinkingSignature||"")+a.reasoningContent.signature))}}function DQe(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,rg(t,n.usage))}function jQe(e,t,n,i){const r=t.findIndex(o=>o.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=cu(a.partialJson),delete a.partialJson,i.push({type:"toolcall_end",contentIndex:r,toolCall:a,partial:n});break}}function gM(e){return e.includes("opus-4-6")||e.includes("opus-4.6")||e.includes("sonnet-4-6")||e.includes("sonnet-4.6")}function LQe(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 FQe(e){return e||(typeof process<"u"&&Do.PI_CACHE_RETENTION==="long"?"long":"short")}function Vye(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 UQe(e){const t=e.id.toLowerCase();return t.includes("anthropic.claude")||t.includes("anthropic/claude")}function qQe(e,t,n){if(!e)return;const i=[{text:Qn(e)}];return n!=="none"&&Vye(t)&&i.push({cachePoint:{type:Hye.DEFAULT,...n==="long"?{ttl:Gye.ONE_HOUR}:{}}}),i}function BQe(e){const t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return t.length>64?t.slice(0,64):t}function WQe(e,t,n){const i=[],r=X0(e.messages,t,BQe);for(let a=0;a<r.length;a++){const o=r[a];switch(o.role){case"user":i.push({role:ux.USER,content:typeof o.content=="string"?[{text:Qn(o.content)}]:o.content.map(c=>{switch(c.type){case"text":return{text:Qn(c.text)};case"image":return{image:x9(c.mimeType,c.data)};default:throw new Error("Unknown user content type")}})});break;case"assistant":{if(o.content.length===0)continue;const c=[];for(const l of o.content)switch(l.type){case"text":if(l.text.trim().length===0)continue;c.push({text:Qn(l.text)});break;case"toolCall":c.push({toolUse:{toolUseId:l.id,name:l.name,input:l.arguments}});break;case"thinking":if(l.thinking.trim().length===0)continue;UQe(t)?c.push({reasoningContent:{reasoningText:{text:Qn(l.thinking),signature:l.thinkingSignature}}}):c.push({reasoningContent:{reasoningText:{text:Qn(l.thinking)}}});break;default:throw new Error("Unknown assistant content type")}if(c.length===0)continue;i.push({role:ux.ASSISTANT,content:c});break}case"toolResult":{const c=[];c.push({toolResult:{toolUseId:o.toolCallId,content:o.content.map(s=>s.type==="image"?{image:x9(s.mimeType,s.data)}:{text:Qn(s.text)}),status:o.isError?yT.ERROR:yT.SUCCESS}});let l=a+1;for(;l<r.length&&r[l].role==="toolResult";){const s=r[l];c.push({toolResult:{toolUseId:s.toolCallId,content:s.content.map(u=>u.type==="image"?{image:x9(u.mimeType,u.data)}:{text:Qn(u.text)}),status:s.isError?yT.ERROR:yT.SUCCESS}}),l++}a=l-1,i.push({role:ux.USER,content:c});break}default:throw new Error("Unknown message role")}}if(n!=="none"&&Vye(t)&&i.length>0){const a=i[i.length-1];a.role===ux.USER&&a.content&&a.content.push({cachePoint:{type:Hye.DEFAULT,...n==="long"?{ttl:Gye.ONE_HOUR}:{}}})}return i}function zQe(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 GQe(e){switch(e){case g1.END_TURN:case g1.STOP_SEQUENCE:return"stop";case g1.MAX_TOKENS:case g1.MODEL_CONTEXT_WINDOW_EXCEEDED:return"length";case g1.TOOL_USE:return"toolUse";default:return"error"}}function HQe(e,t){if(!(!t.reasoning||!e.reasoning)&&(e.id.includes("anthropic.claude")||e.id.includes("anthropic/claude"))){const n=gM(e.id)?{thinking:{type:"adaptive"},output_config:{effort:LQe(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!gM(e.id)&&(t.interleavedThinking??!0)&&(n.anthropic_beta=["interleaved-thinking-2025-05-14"]),n}}function x9(e,t){let n;switch(e){case"image/jpeg":case"image/jpg":n=gT.JPEG;break;case"image/png":n=gT.PNG;break;case"image/gif":n=gT.GIF;break;case"image/webp":n=gT.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 px=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&Tn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{px=e});const VQe="https://chatgpt.com/backend-api",JQe="https://api.openai.com/auth",S9=3,OG=1e3,KQe=new Set(["openai","openai-codex","opencode"]),XQe=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function ZQe(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 IG(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 Jye=(e,t,n)=>{const i=new bo;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||vo(e.provider)||"";if(!a)throw new Error(`No API key for provider: ${e.provider}`);const o=get(a),c=QQe(e,t,n);n?.onPayload?.(c);const l=yet(e.headers,n?.headers,o,a,n?.sessionId),s=JSON.stringify(c),u=n?.transport||"sse";if(u!=="sse"){let f=!1;try{if(await het(tet(e.baseUrl),c,l,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<=S9;f++){if(n?.signal?.aborted)throw new Error("Request was aborted");try{if(d=await fetch(Kye(e.baseUrl),{method:"POST",headers:l,body:s,signal:n?.signal}),d.ok)break;const h=await d.text();if(f<S9&&ZQe(d.status,h)){const y=OG*2**f;await IG(y,n?.signal);continue}const m=new Response(h,{status:d.status,statusText:d.statusText}),g=await met(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<S9&&!p.message.includes("usage limit")){const m=OG*2**f;await IG(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 net(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},YQe=(e,t,n)=>{const i=n?.apiKey||vo(e.provider);if(!i)throw new Error(`No API key for provider: ${e.provider}`);const r=wu(e,n,i),a=YA(e)?n?.reasoning:_u(n?.reasoning);return Jye(e,t,{...r,reasoningEffort:a})};function QQe(e,t,n){const i=T7(e,t,KQe,{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=C7(t.tools,{strict:null})),n?.reasoningEffort!==void 0&&(r.reasoning={effort:eet(e.id,n.reasoningEffort),summary:n.reasoningSummary??"auto"}),r}function eet(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 Kye(e){const n=(e&&e.trim().length>0?e:VQe).replace(/\/+$/,"");return n.endsWith("/codex/responses")?n:n.endsWith("/codex")?`${n}/responses`:`${n}/codex/responses`}function tet(e){const t=new URL(Kye(e));return t.protocol==="https:"&&(t.protocol="wss:"),t.protocol==="http:"&&(t.protocol="ws:"),t.toString()}async function net(e,t,n,i){await dk(Xye(iet(e)),t,n,i)}async function*Xye(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:ret(i.status)};yield{...t,type:"response.completed",response:r};continue}yield t}}}function ret(e){if(typeof e=="string")return XQe.has(e)?e:void 0}async function*iet(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 o=i.indexOf(`
864
+ `);return this.signString(h,{signingDate:i,signingRegion:c,signingService:o})}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(o=>({message:t.message,signature:o}))}async signString(t,{signingDate:n=new Date,signingRegion:i,signingService:r}={}){const a=await this.credentialProvider();this.validateResolvedCredentials(a);const o=i??await this.regionProvider(),{shortDate:c}=this.formatDate(n),l=new this.sha256(await this.getSigningKey(a,o,c,r));return l.update(a2(t)),ss(await l.digest())}async signRequest(t,{signingDate:n=new Date,signableHeaders:i,unsignableHeaders:r,signingRegion:a,signingService:o}={}){const c=await this.credentialProvider();this.validateResolvedCredentials(c);const l=a??await this.regionProvider(),s=eG(t),{longDate:u,shortDate:d}=this.formatDate(n),p=y9(d,l,o??this.service);s.headers[rge]=u,c.sessionToken&&(s.headers[sBe]=c.sessionToken);const f=await v9(s,this.sha256);!bBe(uM,s.headers)&&this.applyChecksum&&(s.headers[uM]=f);const h=Zz(s,r,i),m=await this.getSignature(u,p,this.getSigningKey(c,l,d,o),this.createCanonicalRequest(s,h,f));return s.headers[nge]=`${m9} 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,m9),o=new this.sha256(await i);return o.update(a2(a)),ss(await o.digest())}getSigningKey(t,n,i,r){return hBe(this.sha256,t,i,n,r||this.service)}}const CBe=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=EBe(e,{credentials:t,credentialDefaultProvider:e.credentialDefaultProvider}),d=ABe(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)?Jqe(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:o}=e;let c;return e.signer?c=$x(e.signer):e.regionInfoProvider?c=()=>$x(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:o,uriEscapePath:r},h=e.signerConstructor||tG;return new h(f)}):c=async s=>{s=Object.assign({},{name:"sigv4",signingName:e.signingName||e.defaultSigningName,signingRegion:await $x(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:o,uriEscapePath:r},f=e.signerConstructor||tG;return new f(p)},Object.assign(e,{systemClockOffset:a,signingEscapePath:r,signer:c})};function EBe(e,{credentials:t,credentialDefaultProvider:n}){let i;return t?t?.memoized?i=t:i=Fme(t,Lme,G7):n?i=$x(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 ABe(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 nG=typeof TextEncoder=="function"?new TextEncoder:null,kBe=e=>{if(typeof e=="string"){if(nG)return nG.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}`)},Cy=(e,t)=>{const n=[];if(e&&n.push(e),t)for(const i of t)n.push(i);return n},Eg=(e,t)=>`${e||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`,q3=()=>{let e=[],t=[],n=!1;const i=new Set,r=d=>d.sort((p,f)=>rG[f.step]-rG[p.step]||iG[f.priority||"normal"]-iG[p.priority||"normal"]),a=d=>{let p=!1;const f=h=>{const m=Cy(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},o=d=>{let p=!1;const f=h=>{if(h.middleware===d){p=!0;for(const m of Cy(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),l=d=>{const p=[];return d.before.forEach(f=>{f.before.length===0&&f.after.length===0?p.push(f):p.push(...l(f))}),p.push(d),d.after.reverse().forEach(f=>{f.before.length===0&&f.after.length===0?p.push(f):p.push(...l(f))}),p},s=(d=!1)=>{const p=[],f=[],h={};return e.forEach(g=>{const y={...g,before:[],after:[]};for(const v of Cy(y.name,y.aliases))h[v]=y;p.push(y)}),t.forEach(g=>{const y={...g,before:[],after:[]};for(const v of Cy(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 ${Eg(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(l).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=Cy(f,m);if(y.length>0){if(y.some(v=>i.has(v))){if(!h)throw new Error(`Duplicate middleware name '${Eg(f,m)}'`);for(const v of y){const b=e.findIndex(_=>_.name===v||_.aliases?.some(T=>T===v));if(b===-1)continue;const w=e[b];if(w.step!==g.step||g.priority!==w.priority)throw new Error(`"${Eg(w.name,w.aliases)}" middleware with ${w.priority} priority in ${w.step} step cannot be overridden by "${Eg(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=Cy(f,m);if(y.length>0){if(y.some(v=>i.has(v))){if(!h)throw new Error(`Duplicate middleware name '${Eg(f,m)}'`);for(const v of y){const b=t.findIndex(_=>_.name===v||_.aliases?.some(T=>T===v));if(b===-1)continue;const w=t[b];if(w.toMiddleware!==g.toMiddleware||w.relation!==g.relation)throw new Error(`"${Eg(w.name,w.aliases)}" middleware ${w.relation} "${w.toMiddleware}" middleware cannot be overridden by "${Eg(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(q3()),use:d=>{d.applyToStack(u)},remove:d=>typeof d=="string"?a(d):o(d),removeByTag:d=>{let p=!1;const f=h=>{const{tags:m,name:g,aliases:y}=h;if(m&&m.includes(d)){const v=Cy(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(q3());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 Eg(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},rG={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},iG={high:3,normal:2,low:1};class RBe{config;middlewareStack=q3();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,o=r===void 0&&this.config.cacheMiddleware===!0;let c;if(o){this.handlers||(this.handlers=new WeakMap);const l=this.handlers;l.has(t.constructor)?c=l.get(t.constructor):(c=t.resolveMiddleware(this.middlewareStack,this.config,r),l.set(t.constructor,c))}else delete this.handlers,c=t.resolveMiddleware(this.middlewareStack,this.config,r);if(a)c(t).then(l=>a(null,l.output),l=>a(l)).catch(()=>{});else return c(t).then(l=>l.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}const b9="***SensitiveInformation***";function dM(e,t){if(t==null)return t;const n=Gr.of(e);if(n.getMergedTraits().sensitive)return b9;if(n.isListSchema()){if(!!n.getValueSchema().getMergedTraits().sensitive)return b9}else if(n.isMapSchema()){if(!!n.getKeySchema().getMergedTraits().sensitive||!!n.getValueSchema().getMergedTraits().sensitive)return b9}else if(n.isStructSchema()&&typeof t=="object"){const i=t,r={};for(const[a,o]of n.structIterator())i[a]!=null&&(r[a]=dM(o,i[a]));return r}return t}class sge{middlewareStack=q3();schema;static classBuilder(){return new OBe}resolveMiddlewareWithContext(t,n,i,{middlewareFn:r,clientName:a,commandName:o,inputFilterSensitiveLog:c,outputFilterSensitiveLog:l,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:o,inputFilterSensitiveLog:c,outputFilterSensitiveLog:l,[oM]:{commandInstance:this,...s},...u},{requestHandler:m}=n;return p.resolve(g=>m.handle(g.request,i||{}),h)}}class OBe{_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 sge{input;static getEndpointParameterInstructions(){return t._ep}constructor(...[i]){super(),this.input=i??{},t._init(this),this.schema=t._operationSchema}resolveMiddleware(i,r,a){const o=t._operationSchema,c=o?.[4]??o?.input,l=o?.[5]??o?.output;return this.resolveMiddlewareWithContext(i,r,a,{CommandCtor:n,middlewareFn:t._middlewareFn,clientName:t._clientName,commandName:t._commandName,inputFilterSensitiveLog:t._inputFilterSensitiveLog??(o?dM.bind(null,c):s=>s),outputFilterSensitiveLog:t._outputFilterSensitiveLog??(o?dM.bind(null,l):s=>s),smithyContext:t._smithyContext,additionalContext:t._additionalContext})}serialize=t._serializer;deserialize=t._deserializer}}}class f0 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 f0.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===f0?f0.isInstance(t):f0.isInstance(t)?n.name&&this.name?this.prototype.isPrototypeOf(t)||n.name===this.name:this.prototype.isPrototypeOf(t):!1}}const aG=(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},IBe=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{}}},oge=Object.values(i2),PBe=e=>{const t=[];for(const n in i2){const i=i2[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();oge.includes(i)?e.checksumAlgorithms[i.toUpperCase()]=r:e.checksumAlgorithms[i]=r,t.push(n)},checksumAlgorithms(){return t}}},MBe=e=>{const t={};return e.checksumAlgorithms().forEach(n=>{const i=n.algorithmId();oge.includes(i)&&(t[i]=n.checksumConstructor())}),t},NBe=e=>({setRetryStrategy(t){e.retryStrategy=t},retryStrategy(){return e.retryStrategy}}),$Be=e=>{const t={};return t.retryStrategy=e.retryStrategy(),t},DBe=e=>Object.assign(PBe(e),NBe(e)),jBe=e=>Object.assign(MBe(e),$Be(e));class lge{trace(){}debug(){}info(){}warn(){}error(){}}class LBe{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(o=>{const{httpQuery:c,httpQueryParams:l,httpHeader:s,httpLabel:u,httpPrefixHeaders:d}=o.getMergedTraits();return!c&&!l&&!s&&!u&&d===void 0}))return t}async getErrorSchemaOrThrowBaseException(t,n,i,r,a,o){let c=n,l=t;t.includes("#")&&([c,l]=t.split("#"));const s={$metadata:a,$fault:i.statusCode<500?"client":"server"},u=is.for(c);try{return{errorSchema:o?.(u,l)??u.getSchema(t),errorMetadata:s}}catch{r.message=r.message??r.Message??"UnknownError";const p=is.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:l}),s),r)}throw this.decorateServiceException(Object.assign(new Error(l),s),r)}}decorateServiceException(t,n={}){if(this.queryCompat){const i=t.Message??n.Message,r=aG(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 aG(t,n)}setQueryCompatError(t,n){const i=n.headers?.["x-amzn-query-error"];if(t!==void 0&&i!=null){const[r,a]=i.split(";"),o=Object.entries(t),c={Code:r,Type:a};Object.assign(t,c);for(const[l,s]of o)c[l==="message"?"Message":l]=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=>Gr.of(r).getMergedTraits().awsQueryError?.[0]===n)}}}class V7{serdeContext;setSerdeContext(t){this.serdeContext=t}}class FBe{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 UBe(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 Xo(i,"bigDecimal"):BigInt(i)}return t}const qBe=(e,t)=>cx(e,t).then(n=>(t?.utf8Encoder??rw)(n)),BBe=(e,t)=>qBe(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{}}),WBe=(e,t)=>{const n=(a,o)=>Object.keys(a).find(c=>c.toLowerCase()===o.toLowerCase()),i=a=>{let o=a;return typeof o=="number"&&(o=o.toString()),o.indexOf(",")>=0&&(o=o.split(",")[0]),o.indexOf(":")>=0&&(o=o.split(":")[0]),o.indexOf("#")>=0&&(o=o.split("#")[1]),o},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 zBe extends V7{settings;constructor(t){super(),this.settings=t}async read(t,n){return this._read(t,typeof n=="string"?JSON.parse(n,UBe):await BBe(n,this.serdeContext))}readObject(t,n){return this._read(t,n)}_read(t,n){const i=n!==null&&typeof n=="object",r=Gr.of(t);if(i){if(r.isStructSchema()){const o=n,c=r.isUnionSchema(),l={};let s;const{jsonName:u}=this.settings;u&&(s={});let d;c&&(d=new FBe(o,l));for(const[p,f]of r.structIterator()){let h=p;u&&(h=f.getMergedTraits().jsonName??h,s[h]=p),c&&d.mark(h),o[h]!=null&&(l[p]=this._read(f,o[h]))}if(c)d.writeUnknown();else if(typeof o.__type=="string")for(const[p,f]of Object.entries(o)){const h=u?s[p]??p:p;h in l||(l[h]=f)}return l}if(Array.isArray(n)&&r.isListSchema()){const o=r.getValueSchema(),c=[],l=!!r.getMergedTraits().sparse;for(const s of n)(l||s!=null)&&c.push(this._read(o,s));return c}if(r.isMapSchema()){const o=r.getValueSchema(),c={},l=!!r.getMergedTraits().sparse;for(const[s,u]of Object.entries(n))(l||u!=null)&&(c[s]=this._read(o,u));return c}}if(r.isBlobSchema()&&typeof n=="string")return Ov(n);const a=r.getMergedTraits().mediaType;if(r.isStringSchema()&&typeof n=="string"&&a)return a==="application/json"||a.endsWith("+json")?du.from(n):n;if(r.isTimestampSchema()&&n!=null)switch(wk(r,this.settings)){case 5:return jUe(n);case 6:return qUe(n);case 7:return BUe(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 Xo)return n;const o=n;return o.type==="bigDecimal"&&"string"in o?new Xo(o.string,o.type):new Xo(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 o=Array.isArray(n)?[]:{};for(const[c,l]of Object.entries(n))l instanceof Xo?o[c]=l:o[c]=this._read(r,l);return o}else return structuredClone(n);return n}}const sG="Ν";class GBe{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 Xo){const i=`${sG+"nv"+this.counter++}_`+n.string;return this.values.set(`"${i}"`,n.string),i}if(typeof n=="bigint"){const i=n.toString(),r=`${sG+"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 HBe extends V7{settings;buffer;useReplacer=!1;rootSchema;constructor(t){super(),this.settings=t}write(t,n){this.rootSchema=Gr.of(t),this.buffer=this._write(this.rootSchema,n)}writeDiscriminatedDocument(t,n){this.write(t,n),typeof this.buffer=="object"&&(this.buffer.__type=Gr.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 GBe;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=Gr.of(t);if(r){if(a.isStructSchema()){const o=n,c={},{jsonName:l}=this.settings;let s;l&&(s={});for(const[u,d]of a.structIterator()){const p=this._write(d,o[u],a);if(p!==void 0){let f=u;l&&(f=d.getMergedTraits().jsonName??u,s[u]=f),c[f]=p}}if(a.isUnionSchema()&&Object.keys(c).length===0){const{$unknown:u}=o;if(Array.isArray(u)){const[d,p]=u;c[d]=this._write(15,p)}}else if(typeof o.__type=="string")for(const[u,d]of Object.entries(o)){const p=l?s[u]??u:u;p in c||(c[p]=this._write(15,d))}return c}if(Array.isArray(n)&&a.isListSchema()){const o=a.getValueSchema(),c=[],l=!!a.getMergedTraits().sparse;for(const s of n)(l||s!=null)&&c.push(this._write(o,s));return c}if(a.isMapSchema()){const o=a.getValueSchema(),c={},l=!!a.getMergedTraits().sparse;for(const[s,u]of Object.entries(n))(l||u!=null)&&(c[s]=this._write(o,u));return c}if(n instanceof Uint8Array&&(a.isBlobSchema()||a.isDocumentSchema()))return a===this.rootSchema?n:(this.serdeContext?.base64Encoder??Pv)(n);if(n instanceof Date&&(a.isTimestampSchema()||a.isDocumentSchema()))switch(wk(a,this.settings)){case 5:return n.toISOString().replace(".000Z","Z");case 6:return Nme(n);case 7:return n.getTime()/1e3;default:return console.warn("Missing timestamp format, using epoch seconds",n),n.getTime()/1e3}n instanceof Xo&&(this.useReplacer=!0)}if(!(n===null&&i?.isStructSchema())){if(a.isStringSchema()){if(typeof n>"u"&&a.isIdempotencyToken())return q7();const o=a.getMergedTraits().mediaType;return n!=null&&o&&(o==="application/json"||o.endsWith("+json"))?du.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??Pv)(n);if(typeof n=="bigint"&&(this.useReplacer=!0),a.isDocumentSchema())if(r){const o=Array.isArray(n)?[]:{};for(const[c,l]of Object.entries(n))l instanceof Xo?(this.useReplacer=!0,o[c]=l):o[c]=this._write(a,l);return o}else return structuredClone(n);return n}}}class VBe extends V7{settings;constructor(t){super(),this.settings=t}createSerializer(){const t=new HBe(this.settings);return t.setSerdeContext(this.serdeContext),t}createDeserializer(){const t=new zBe(this.settings);return t.setSerdeContext(this.serdeContext),t}}class JBe extends lqe{serializer;deserializer;codec;mixin=new LBe;constructor({defaultNamespace:t}){super({defaultNamespace:t});const n={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=new VBe(n),this.serializer=new pqe(this.codec.createSerializer(),n),this.deserializer=new uqe(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=Gr.of(t.input);if(!r.headers["content-type"]){const o=this.mixin.resolveRestContentType(this.getDefaultContentType(),a);o&&(r.headers["content-type"]=o)}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=Gr.of(t.output);for(const[o,c]of a.structIterator())c.getMemberTraits().httpPayload&&!(o in r)&&(r[o]=null);return r}async handleError(t,n,i,r,a){const o=WBe(i,r)??"Unknown",{errorSchema:c,errorMetadata:l}=await this.mixin.getErrorSchemaOrThrowBaseException(o,this.options.defaultNamespace,i,r,a),s=Gr.of(c),u=r.message??r.Message??"Unknown",d=is.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,l,{$fault:s.getMergedTraits().error,message:u},f),r)}getDefaultContentType(){return"application/json"}}const KBe=/\d{12}\.ddb/;async function XBe(e,t,n){if(n.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor"&&vl(e,"PROTOCOL_RPC_V2_CBOR","M"),typeof t.retryStrategy=="function"){const a=await t.retryStrategy();typeof a.acquireInitialRetryToken=="function"?a.constructor?.name?.includes("Adaptive")?vl(e,"RETRY_MODE_ADAPTIVE","F"):vl(e,"RETRY_MODE_STANDARD","E"):vl(e,"RETRY_MODE_LEGACY","D")}if(typeof t.accountIdEndpointMode=="function"){const a=e.endpointV2;switch(String(a?.url?.hostname).match(KBe)&&vl(e,"ACCOUNT_ID_ENDPOINT","O"),await t.accountIdEndpointMode?.()){case"disabled":vl(e,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":vl(e,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":vl(e,"ACCOUNT_ID_MODE_REQUIRED","R");break}}const r=e.__smithy_context?.selectedHttpAuthScheme?.identity;if(r?.$source){const a=r;a.accountId&&vl(e,"RESOLVED_ACCOUNT_ID","T");for(const[o,c]of Object.entries(a.$source??{}))vl(e,o,c)}}const oG="user-agent",w9="x-amz-user-agent",lG=" ",_9="/",ZBe=/[^!$%&'*+\-.^_`|~\w]/g,YBe=/[^!$%&'*+\-.^_`|~\w#]/g,cG="-",QBe=1024;function eWe(e){let t="";for(const n in e){const i=e[n];if(t.length+i.length+1<=QBe){t.length?t+=","+i:t+=i;continue}break}return t}const tWe=e=>(t,n)=>async i=>{const{request:r}=i;if(!Ga.isInstance(r))return t(i);const{headers:a}=r,o=n?.userAgent?.map(mT)||[],c=(await e.defaultUserAgentProvider()).map(mT);await XBe(n,e,i);const l=n;c.push(`m/${eWe(Object.assign({},n.__smithy_context?.features,l.__aws_sdk_context?.features))}`);const s=e?.customUserAgent?.map(mT)||[],u=await e.userAgentAppId();u&&c.push(mT(["app",`${u}`]));const d=[].concat([...c,...o,...s]).join(lG),p=[...c.filter(f=>f.startsWith("aws-sdk-")),...s].join(lG);return e.runtime!=="browser"?(p&&(a[w9]=a[w9]?`${a[oG]} ${p}`:p),a[oG]=d):a[w9]=d,t({...i,request:r})},mT=e=>{const t=e[0].split(_9).map(o=>o.replace(ZBe,cG)).join(_9),n=e[1]?.replace(YBe,cG),i=t.indexOf(_9),r=t.substring(0,i);let a=t.substring(i+1);return r==="api"&&(a=a.toLowerCase()),[r,a,n].filter(o=>o&&o.length>0).reduce((o,c,l)=>{switch(l){case 0:return c;case 1:return`${o}/${c}`;default:return`${o}#${c}`}},"")},nWe={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},rWe=e=>({applyToStack:t=>{t.add(tWe(e),nWe)}});function iWe(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 o=n?Rme(n):"";o&&o[0]!=="?"&&(o=`?${o}`);let c="";if(e.username!=null||e.password!=null){const s=e.username??"",u=e.password??"";c=`${s}:${u}@`}let l="";return e.fragment&&(l=`#${e.fragment}`),`${i}//${c}${a}${r}${o}${l}`}var pM=function(e,t){return pM=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])},pM(e,t)};function cge(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");pM(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var B3=function(){return B3=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},B3.apply(this,arguments)};function uge(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 dge(e,t,n,i){var r=arguments.length,a=r<3?t:i===null?i=Object.getOwnPropertyDescriptor(t,n):i,o;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--)(o=e[c])&&(a=(r<3?o(a):r>3?o(t,n,a):o(t,n))||a);return r>3&&a&&Object.defineProperty(t,n,a),a}function pge(e,t){return function(n,i){t(n,i,e)}}function fge(e,t,n,i,r,a){function o(y){if(y!==void 0&&typeof y!="function")throw new TypeError("Function expected");return y}for(var c=i.kind,l=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(o(y||null))};var g=(0,n[f])(c==="accessor"?{get:u.get,set:u.set}:u[l],h);if(c==="accessor"){if(g===void 0)continue;if(g===null||typeof g!="object")throw new TypeError("Object expected");(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&r.unshift(d)}else(d=o(g))&&(c==="field"?r.unshift(d):u[l]=d)}s&&Object.defineProperty(s,i.name,u),p=!0}function hge(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 mge(e){return typeof e=="symbol"?e:"".concat(e)}function gge(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 yge(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}function J7(e,t,n,i){function r(a){return a instanceof n?a:new n(function(o){o(a)})}return new(n||(n=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(d){o(d)}}function l(u){try{s(i.throw(u))}catch(d){o(d)}}function s(u){u.done?a(u.value):r(u.value).then(c,l)}s((i=i.apply(e,t||[])).next())})}function K7(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,r,a,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=c(0),o.throw=c(1),o.return=c(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function c(s){return function(u){return l([s,u])}}function l(s){if(i)throw new TypeError("Generator is already executing.");for(;o&&(o=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 Sk=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 vge(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&Sk(t,e,n)}function c2(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 X7(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,a=[],o;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(c){o={error:c}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a}function bge(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(X7(arguments[t]));return e}function wge(){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],o=0,c=a.length;o<c;o++,r++)i[r]=a[o];return i}function _ge(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 $0(e){return this instanceof $0?(this.v=e,this):new $0(e)}function xge(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",o),r[Symbol.asyncIterator]=function(){return this},r;function o(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||l(f,m)})},h&&(r[f]=h(r[f])))}function l(f,h){try{s(i[f](h))}catch(m){p(a[0][3],m)}}function s(f){f.value instanceof $0?Promise.resolve(f.value.v).then(u,d):p(a[0][2],f)}function u(f){l("next",f)}function d(f){l("throw",f)}function p(f,h){f(h),a.shift(),a.length&&l(a[0][0],a[0][1])}}function Sge(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(o){return(n=!n)?{value:$0(e[r](o)),done:!1}:a?a(o):o}:a}}function Tge(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 c2=="function"?c2(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(o){return new Promise(function(c,l){o=e[a](o),r(c,l,o.done,o.value)})}}function r(a,o,c,l){Promise.resolve(l).then(function(s){a({value:s,done:c})},o)}}function Cge(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}var aWe=Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t},fM=function(e){return fM=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},fM(e)};function Ege(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=fM(e),i=0;i<n.length;i++)n[i]!=="default"&&Sk(t,e,n[i]);return aWe(t,e),t}function Age(e){return e&&e.__esModule?e:{default:e}}function kge(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 Rge(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 Oge(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 Ige(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 sWe=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 Pge(e){function t(a){e.error=e.hasError?new sWe(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(o){return t(o),r()})}else i|=1}catch(o){t(o)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return r()}function Mge(e,t){return typeof e=="string"&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(n,i,r,a,o){return i?t?".jsx":".js":r&&(!a||!o)?n:r+a+"."+o.toLowerCase()+"js"}):e}const oWe={__extends:cge,__assign:B3,__rest:uge,__decorate:dge,__param:pge,__esDecorate:fge,__runInitializers:hge,__propKey:mge,__setFunctionName:gge,__metadata:yge,__awaiter:J7,__generator:K7,__createBinding:Sk,__exportStar:vge,__values:c2,__read:X7,__spread:bge,__spreadArrays:wge,__spreadArray:_ge,__await:$0,__asyncGenerator:xge,__asyncDelegator:Sge,__asyncValues:Tge,__makeTemplateObject:Cge,__importStar:Ege,__importDefault:Age,__classPrivateFieldGet:kge,__classPrivateFieldSet:Rge,__classPrivateFieldIn:Oge,__addDisposableResource:Ige,__disposeResources:Pge,__rewriteRelativeImportExtension:Mge},o7t=Object.freeze(Object.defineProperty({__proto__:null,__addDisposableResource:Ige,get __assign(){return B3},__asyncDelegator:Sge,__asyncGenerator:xge,__asyncValues:Tge,__await:$0,__awaiter:J7,__classPrivateFieldGet:kge,__classPrivateFieldIn:Oge,__classPrivateFieldSet:Rge,__createBinding:Sk,__decorate:dge,__disposeResources:Pge,__esDecorate:fge,__exportStar:vge,__extends:cge,__generator:K7,__importDefault:Age,__importStar:Ege,__makeTemplateObject:Cge,__metadata:yge,__param:pge,__propKey:mge,__read:X7,__rest:uge,__rewriteRelativeImportExtension:Mge,__runInitializers:hge,__setFunctionName:gge,__spread:bge,__spreadArray:_ge,__spreadArrays:wge,__values:c2,default:oWe},Symbol.toStringTag,{value:"Module"})),lWe=e=>new TextEncoder().encode(e);var cWe=typeof Buffer<"u"&&Buffer.from?function(e){return Buffer.from(e,"utf8")}:lWe;function u2(e){return e instanceof Uint8Array?e:typeof e=="string"?cWe(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}function hM(e){return typeof e=="string"?e.length===0:e.byteLength===0}function uWe(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 Nge=(function(){function e(){this.checksum=4294967295}return e.prototype.update=function(t){var n,i;try{for(var r=c2(t),a=r.next();!a.done;a=r.next()){var o=a.value;this.checksum=this.checksum>>>8^pWe[(this.checksum^o)&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})(),dWe=[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],pWe=uWe(dWe);class Lx{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&&uG(n),new Lx(n)}valueOf(){const t=this.bytes.slice(0),n=t[0]&128;return n&&uG(t),parseInt(ss(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function uG(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,e[t]===0);t--);}class fWe{toUtf8;fromUtf8;constructor(t,n){this.toUtf8=t,this.fromUtf8=n}format(t){const n=[];for(const a of Object.keys(t)){const o=this.fromUtf8(a);n.push(Uint8Array.from([o.byteLength]),o,this.formatHeaderValue(t[a]))}const i=new Uint8Array(n.reduce((a,o)=>a+o.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 o=new Uint8Array(a.buffer);return o.set(t.value,3),o;case"string":const c=this.fromUtf8(t.value),l=new DataView(new ArrayBuffer(3+c.byteLength));l.setUint8(0,7),l.setUint16(1,c.byteLength,!1);const s=new Uint8Array(l.buffer);return s.set(c,3),s;case"timestamp":const u=new Uint8Array(9);return u[0]=8,u.set(Lx.fromNumber(t.value.valueOf()).bytes,1),u;case"uuid":if(!xWe.test(t.value))throw new Error(`Invalid UUID received: ${t.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(F7(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:pG,value:!0};break;case 1:n[a]={type:pG,value:!1};break;case 2:n[a]={type:hWe,value:t.getInt8(i++)};break;case 3:n[a]={type:mWe,value:t.getInt16(i,!1)},i+=2;break;case 4:n[a]={type:gWe,value:t.getInt32(i,!1)},i+=4;break;case 5:n[a]={type:yWe,value:new Lx(new Uint8Array(t.buffer,t.byteOffset+i,8))},i+=8;break;case 6:const o=t.getUint16(i,!1);i+=2,n[a]={type:vWe,value:new Uint8Array(t.buffer,t.byteOffset+i,o)},i+=o;break;case 7:const c=t.getUint16(i,!1);i+=2,n[a]={type:bWe,value:this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+i,c))},i+=c;break;case 8:n[a]={type:wWe,value:new Date(new Lx(new Uint8Array(t.buffer,t.byteOffset+i,8)).valueOf())},i+=8;break;case 9:const l=new Uint8Array(t.buffer,t.byteOffset+i,16);i+=16,n[a]={type:_We,value:`${ss(l.subarray(0,4))}-${ss(l.subarray(4,6))}-${ss(l.subarray(6,8))}-${ss(l.subarray(8,10))}-${ss(l.subarray(10))}`};break;default:throw new Error("Unrecognized header type tag")}}return n}}var dG;(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"})(dG||(dG={}));const pG="boolean",hWe="byte",mWe="short",gWe="integer",yWe="long",vWe="binary",bWe="string",wWe="timestamp",_We="uuid",xWe=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,$ge=4,$g=$ge*2,Jy=4,SWe=$g+Jy*2;function TWe({byteLength:e,byteOffset:t,buffer:n}){if(e<SWe)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($ge,!1),o=i.getUint32($g,!1),c=i.getUint32(e-Jy,!1),l=new Nge().update(new Uint8Array(n,t,$g));if(o!==l.digest())throw new Error(`The prelude checksum specified in the message (${o}) does not match the calculated CRC32 checksum (${l.digest()})`);if(l.update(new Uint8Array(n,t+$g,e-($g+Jy))),c!==l.digest())throw new Error(`The message checksum (${l.digest()}) did not match the expected value of ${c}`);return{headers:new DataView(n,t+$g+Jy,a),body:new Uint8Array(n,t+$g+Jy+a,r-a-($g+Jy+Jy))}}class Dge{headerMarshaller;messageBuffer;isEndOfStream;constructor(t,n){this.headerMarshaller=new fWe(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),o=new DataView(a.buffer,a.byteOffset,a.byteLength),c=new Nge;return o.setUint32(0,r,!1),o.setUint32(4,i.byteLength,!1),o.setUint32(8,c.update(a.subarray(0,8)).digest(),!1),a.set(i,12),a.set(n,i.byteLength+12),o.setUint32(r-4,c.update(a.subarray(8,r-4)).digest(),!1),a}decode(t){const{headers:n,body:i}=TWe(t);return{headers:this.headerMarshaller.parse(n),body:i}}formatHeaders(t){return this.headerMarshaller.format(t)}}class CWe{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 EWe{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 AWe{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 kWe{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 RWe(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)},o=async function*(){const c=e[Symbol.asyncIterator]();for(;;){const{value:l,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=l.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(l.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(l.slice(d,d+p),n),n+=p,d+=p,t&&t===n&&(yield i,i=null,t=0,n=0)}}};return{[Symbol.asyncIterator]:o}}function OWe(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},o=await e(a);if(o.$unknown){const c=new Error(t(n.body));throw c.name=r,c}throw o[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 IWe=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:t,utf8Decoder:n}){this.eventStreamCodec=new Dge(t,n),this.utfEncoder=t}deserialize(t,n){const i=RWe(t);return new AWe({messageStream:new CWe({inputStream:i,decoder:this.eventStreamCodec}),deserializer:OWe(n,this.utfEncoder)})}serialize(t,n){return new EWe({messageStream:new kWe({inputStream:t,serializer:n}),encoder:this.eventStreamCodec,includeEndFrame:!0})}};const jge=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()}}}),Lge=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 PWe{universalMarshaller;constructor({utf8Encoder:t,utf8Decoder:n}){this.universalMarshaller=new IWe({utf8Decoder:n,utf8Encoder:t})}deserialize(t,n){const i=MWe(t)?jge(t):t;return this.universalMarshaller.deserialize(i,n)}serialize(t,n){const i=this.universalMarshaller.serialize(t,n);return typeof ReadableStream=="function"?Lge(i):i}}const MWe=e=>typeof ReadableStream=="function"&&e instanceof ReadableStream,NWe=e=>new PWe(e),Fge=e=>e.protocol==="ws:"||e.protocol==="wss:",$We=3e3;class Z7{metadata={handlerProtocol:"websocket/h1.1"};config={};configPromise;httpHandler;sockets={};static create(t,n=new s2){return typeof t?.handle=="function"?t:new Z7(t,n)}constructor(t,n=new s2){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(!Fge(t))return n?.debug?.(`@aws-sdk - ws fetching ${t.protocol}${t.hostname}${t.path}`),this.httpHandler.handle(t);const i=iWe(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=$We}=this.config;await this.waitForReady(r,a);const{body:o}=t,c=DWe(o),l=this.connect(r,c),s=jWe(l);return{response:new Rv({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 o=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;o(typeof u=="string"?{done:!1,value:Ov(u)}:{done:!1,value:new Uint8Array(u)})},t.onerror=s=>{t.close(),o({done:!0,error:s})},t.onclose=()=>{this.removeNotUsableSockets(t.url),o({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){o({done:!0,error:s})}finally{t.close(1e3)}})(),c}}const DWe=e=>e[Symbol.asyncIterator]?e:LWe(e)?jge(e):{[Symbol.asyncIterator]:async function*(){yield e}},jWe=e=>typeof ReadableStream=="function"?Lge(e):e,LWe=e=>typeof ReadableStream=="function"&&e instanceof ReadableStream;class FWe{signer;constructor(t){this.signer=t.signer}presign(t,n={}){return this.signer.presign(t,n)}async sign(t,n){return Ga.isInstance(t)&&Fge(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 UWe=e=>{const{signer:t}=e;return Object.assign(e,{signer:async n=>{const i=await t(n);if(qWe(i))return new FWe({signer:i});throw new Error("Expected WebsocketSignatureV4 signer, please check the client constructor.")}})},qWe=e=>!!e;class BWe extends TransformStream{constructor(t,n,i,r){let a=t;super({start(){},async transform(o,c){try{const l=new Date(Date.now()+await r()),s={":date":{type:"timestamp",value:l}},u=await n.sign({message:{body:o,headers:s},priorSignature:a},{signingDate:l});a=u.signature;const d=i.encode({headers:{...s,":chunk-signature":{type:"binary",value:F7(u.signature)}},body:o});c.enqueue(d)}catch(l){c.error(l)}}})}}class WWe{messageSigner;eventStreamCodec;systemClockOffsetProvider;constructor(t){this.messageSigner=t.messageSigner,this.eventStreamCodec=new Dge(t.utf8Encoder,t.utf8Decoder),this.systemClockOffsetProvider=async()=>t.systemClockOffset??0}async handle(t,n,i={}){const r=n.request,{body:a,headers:o,query:c}=r;if(!(a instanceof ReadableStream))throw new Error("Eventstream payload must be a ReadableStream.");const l=new TransformStream;r.body=l.readable;let u=((o?.authorization??"").match(/Signature=(\w+)$/)??[])[1]??(c&&c["X-Amz-Signature"])??"";i.__staticSignature&&(u="");const d=new BWe(u,await this.messageSigner(),this.eventStreamCodec,this.systemClockOffsetProvider);a.pipeThrough(d).pipeThrough(l);let p;try{p=await t(n)}catch(f){const h=a.cancel?.();throw h instanceof Promise&&h.catch(()=>{}),f}return p}}const zWe=e=>new WWe(e),GWe=!1,HWe=!1,fG=new Set,VWe=(e,t=_k)=>{if(!fG.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 fG.add(e)},Uge=e=>typeof e=="string"&&(e.startsWith("fips-")||e.endsWith("-fips")),JWe=e=>Uge(e)?["fips-aws-global","aws-fips"].includes(e)?"us-east-1":e.replace(/fips-(dkr-|prod-)?|-fips/,""):e,KWe=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=JWe(i);return VWe(r),r},useFipsEndpoint:async()=>{const i=typeof t=="string"?t:await t();return Uge(i)?!0:typeof n!="function"?Promise.resolve(!!n):n()}})},XWe=e=>Object.assign(e,{eventStreamMarshaller:e.eventStreamSerdeProvider(e)}),hG="content-length";function ZWe(e){return t=>async n=>{const i=n.request;if(Ga.isInstance(i)){const{body:r,headers:a}=i;if(r&&Object.keys(a).map(o=>o.toLowerCase()).indexOf(hG)===-1)try{const o=e(r);i.headers={...i.headers,[hG]:String(o)}}catch{}}return t({...n,request:i})}}const YWe={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},QWe=e=>({applyToStack:t=>{t.add(ZWe(e.bodyLengthChecker),YWe)}}),eze=async e=>{const t=e?.Bucket||"";if(typeof e.Bucket=="string"&&(e.Bucket=t.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),aze(t)){if(e.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!ize(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},tze=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,nze=/(\d+\.){3}\d+/,rze=/\.\./,ize=e=>tze.test(e)&&!nze.test(e)&&!rze.test(e),aze=e=>{const[t,n,i,,,r]=e.split(":"),a=t==="arn"&&e.split(":").length>=6,o=!!(a&&n&&i&&r);if(a&&!o)throw new Error(`Invalid ARN: ${e} was an invalid ARN.`);return o},sze=(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:o,hostname:c,port:l,path:s}=a;return`${o}//${c}${l?":"+l:""}${s}`}}return a}:r},qge=async e=>{},Bge=e=>typeof e=="object"?"url"in e?U3(e.url):e:U3(e),oze=async(e,t,n,i)=>{if(!n.isCustomEndpoint){let o;n.serviceConfiguredEndpoint?o=await n.serviceConfiguredEndpoint():o=await qge(n.serviceId),o&&(n.endpoint=()=>Promise.resolve(Bge(o)),n.isCustomEndpoint=!0)}const r=await lze(e,t,n);if(typeof n.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");return n.endpointProvider(r,i)},lze=async(e,t,n)=>{const i={},r=t?.getEndpointParameterInstructions?.()||{};for(const[a,o]of Object.entries(r))switch(o.type){case"staticContextParams":i[a]=o.value;break;case"contextParams":i[a]=e[o.name];break;case"clientContextParams":case"builtInParams":i[a]=await sze(o.name,a,n,o.type!=="builtInParams")();break;case"operationContextParams":i[a]=o.get(e);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(o))}return Object.keys(r).length===0&&Object.assign(i,n),String(n.serviceId).toLowerCase()==="s3"&&await eze(i),i},cze=({config:e,instructions:t})=>(n,i)=>async r=>{e.isCustomEndpoint&&fqe(i,"ENDPOINT_OVERRIDE","N");const a=await oze(r.input,{getEndpointParameterInstructions(){return t}},{...e},i);i.endpointV2=a,i.authSchemes=a.properties?.authSchemes;const o=i.authSchemes?.[0];if(o){i.signing_region=o.signingRegion,i.signing_service=o.signingName;const l=nw(i)?.selectedHttpAuthScheme?.httpAuthOption;l&&(l.signingProperties=Object.assign(l.signingProperties||{},{signing_region:o.signingRegion,signingRegion:o.signingRegion,signing_service:o.signingName,signingName:o.signingName,signingRegionSet:o.signingRegionSet},o.properties))}return n({...r})},uze={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:sUe.name},dze=(e,t)=>({applyToStack:n=>{n.addRelativeTo(cze({config:e,instructions:t}),uze)}}),pze=e=>{const t=e.tls??!0,{endpoint:n,useDualstackEndpoint:i,useFipsEndpoint:r}=e,a=n!=null?async()=>Bge(await eg(n)()):void 0,c=Object.assign(e,{endpoint:a,tls:t,isCustomEndpoint:!!n,useDualstackEndpoint:eg(i??!1),useFipsEndpoint:eg(r??!1)});let l;return c.serviceConfiguredEndpoint=async()=>(e.serviceId&&!l&&(l=qge(e.serviceId)),l),c};var D0;(function(e){e.STANDARD="standard",e.ADAPTIVE="adaptive"})(D0||(D0={}));const W3=3,fze=D0.STANDARD,hze=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],mze=["TimeoutError","RequestTimeout","RequestTimeoutException"],gze=[500,502,503,504],yze=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],vze=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND"],bze=e=>e?.$retryable!==void 0,wze=e=>e.$metadata?.clockSkewCorrected,_ze=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},Wge=e=>e.$metadata?.httpStatusCode===429||hze.includes(e.name)||e.$retryable?.throttling==!0,Y7=(e,t=0)=>bze(e)||wze(e)||mze.includes(e.name)||yze.includes(e?.code||"")||vze.includes(e?.code||"")||gze.includes(e.$metadata?.httpStatusCode||0)||_ze(e)||e.cause!==void 0&&t<=10&&Y7(e.cause,t+1),xze=e=>{if(e.$metadata?.httpStatusCode!==void 0){const t=e.$metadata.httpStatusCode;return 500<=t&&t<=599&&!Y7(e)}return!1};class Q7{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=>Q7.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(),Wge(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 mM=100,zge=20*1e3,Sze=500,mG=500,Tze=5,Cze=10,Eze=1,Aze="amz-sdk-invocation-id",kze="amz-sdk-request",Rze=()=>{let e=mM;return{computeNextBackoffDelay:i=>Math.floor(Math.min(zge,Math.random()*2**i*e)),setDelayBase:i=>{e=i}}},gG=({retryDelay:e,retryCount:t,retryCost:n})=>({getRetryCount:()=>t,getRetryDelay:()=>Math.min(zge,e),getRetryCost:()=>n});class Gge{maxAttempts;mode=D0.STANDARD;capacity=mG;retryBackoffStrategy=Rze();maxAttemptsProvider;constructor(t){this.maxAttempts=t,this.maxAttemptsProvider=typeof t=="function"?t:async()=>t}async acquireInitialRetryToken(t){return gG({retryDelay:mM,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"?Sze:mM);const a=this.retryBackoffStrategy.computeNextBackoffDelay(t.getRetryCount()),o=n.retryAfterHint?Math.max(n.retryAfterHint.getTime()-Date.now()||0,a):a,c=this.getCapacityCost(r);return this.capacity-=c,gG({retryDelay:o,retryCount:t.getRetryCount()+1,retryCost:c})}throw new Error("No retry token available")}recordSuccess(t){this.capacity=Math.max(mG,this.capacity+(t.getRetryCost()??Eze))}getCapacity(){return this.capacity}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch{return console.warn(`Max attempts provider could not resolve. Using default of ${W3}`),W3}}shouldRetry(t,n,i){return t.getRetryCount()+1<i&&this.capacity>=this.getCapacityCost(n.errorType)&&this.isRetryableError(n.errorType)}getCapacityCost(t){return t==="TRANSIENT"?Cze:Tze}isRetryableError(t){return t==="THROTTLING"||t==="TRANSIENT"}}class Oze{maxAttemptsProvider;rateLimiter;standardRetryStrategy;mode=D0.ADAPTIVE;constructor(t,n){this.maxAttemptsProvider=t;const{rateLimiter:i}=n??{};this.rateLimiter=i??new Q7,this.standardRetryStrategy=new Gge(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 Ize=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}`),Pze=e=>{const{retryStrategy:t,retryMode:n,maxAttempts:i}=e,r=eg(i??W3);return Object.assign(e,{maxAttempts:r,retryStrategy:async()=>t||(await eg(n)()===D0.ADAPTIVE?new Oze(r):new Gge(r))})},Mze=e=>e?.body instanceof ReadableStream,Nze=e=>(t,n)=>async i=>{let r=await e.retryStrategy();const a=await e.maxAttempts();if($ze(r)){r=r;let o=await r.acquireInitialRetryToken(n.partition_id),c=new Error,l=0,s=0;const{request:u}=i,d=Ga.isInstance(u);for(d&&(u.headers[Aze]=q7());;)try{d&&(u.headers[kze]=`attempt=${l+1}; max=${a}`);const{response:p,output:f}=await t(i);return r.recordSuccess(o),f.$metadata.attempts=l+1,f.$metadata.totalRetryDelay=s,{response:p,output:f}}catch(p){const f=Dze(p);if(c=Ize(p),d&&Mze(u))throw(n.logger instanceof lge?console:n.logger)?.warn("An error was encountered in a non-retryable streaming request."),c;try{o=await r.refreshRetryTokenForRetry(o,f)}catch{throw c.$metadata||(c.$metadata={}),c.$metadata.attempts=l+1,c.$metadata.totalRetryDelay=s,c}l=o.getRetryCount();const h=o.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)},$ze=e=>typeof e.acquireInitialRetryToken<"u"&&typeof e.refreshRetryTokenForRetry<"u"&&typeof e.recordSuccess<"u",Dze=e=>{const t={error:e,errorType:jze(e)},n=Uze(e.$response);return n&&(t.retryAfterHint=n),t},jze=e=>Wge(e)?"THROTTLING":Y7(e)?"TRANSIENT":xze(e)?"SERVER_ERROR":"CLIENT_ERROR",Lze={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0},Fze=e=>({applyToStack:t=>{t.add(Nze(e),Lze)}}),Uze=e=>{if(!Rv.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)},qze=async(e,t,n)=>({operation:nw(t).operation,region:await eg(e.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function Bze(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"bedrock",region:e.region},propertiesExtractor:(t,n)=>({signingProperties:{config:t,context:n}})}}function Wze(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 zze=e=>{const t=[];switch(e.operation){default:t.push(Bze(e)),t.push(Wze())}return t},Gze=e=>{const t=Fme(e.token,Lme,G7),n=CBe(e);return Object.assign(n,{authSchemePreference:eg(e.authSchemePreference??[]),token:t})},Hze=e=>Object.assign(e,{useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,defaultSigningName:"bedrock"}),Vze={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},Jze="3.1000.0",Kze={version:Jze};var Hge={name:"SHA-256"},yG={name:"HMAC",hash:Hge},Xze=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 Zze={};function vE(){return typeof window<"u"?window:typeof self<"u"?self:Zze}var Yze=(function(){function e(t){this.toHash=new Uint8Array(0),this.secret=t,this.reset()}return e.prototype.update=function(t){if(!hM(t)){var n=u2(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 vE().crypto.subtle.sign(yG,n,t.toHash).then(function(i){return new Uint8Array(i)})}):hM(this.toHash)?Promise.resolve(Xze):Promise.resolve().then(function(){return vE().crypto.subtle.digest(Hge,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){vE().crypto.subtle.importKey("raw",u2(t.secret),yG,!1,["sign"]).then(n,i)}),this.key.catch(function(){}))},e})(),no=64,Qze=32,eGe=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]),tGe=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],nGe=Math.pow(2,53)-1,bE=(function(){function e(){this.state=Int32Array.from(tGe),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>nGe)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;i>0;)this.buffer[this.bufferLength++]=t[n++],i--,this.bufferLength===no&&(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%no>=no-8){for(var r=this.bufferLength;r<no;r++)n.setUint8(r,0);this.hashBuffer(),this.bufferLength=0}for(var r=this.bufferLength;r<no-8;r++)n.setUint8(r,0);n.setUint32(no-8,Math.floor(t/4294967296),!0),n.setUint32(no-4,t),this.hashBuffer(),this.finished=!0}for(var a=new Uint8Array(Qze),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],o=i[2],c=i[3],l=i[4],s=i[5],u=i[6],d=i[7],p=0;p<no;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=(((l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7))+(l&s^~l&u)|0)+(d+(eGe[p]+this.temp[p]|0)|0)|0,y=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&a^r&o^a&o)|0;d=u,u=s,s=l,l=c+g|0,c=o,o=a,a=r,r=g+y|0}i[0]+=r,i[1]+=a,i[2]+=o,i[3]+=c,i[4]+=l,i[5]+=s,i[6]+=u,i[7]+=d},e})(),rGe=(function(){function e(t){this.secret=t,this.hash=new bE,this.reset()}return e.prototype.update=function(t){if(!(hM(t)||this.error))try{this.hash.update(u2(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 J7(this,void 0,void 0,function(){return K7(this,function(t){return[2,this.digestSync()]})})},e.prototype.reset=function(){if(this.hash=new bE,this.secret){this.outer=new bE;var t=iGe(this.secret),n=new Uint8Array(no);n.set(t);for(var i=0;i<no;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 iGe(e){var t=u2(e);if(t.byteLength>no){var n=new bE;n.update(t),t=n.digest()}var i=new Uint8Array(no);return i.set(t),i}var aGe=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function sGe(e){if(oGe(e)&&typeof e.crypto.subtle=="object"){var t=e.crypto.subtle;return lGe(t)}return!1}function oGe(e){if(typeof e=="object"&&typeof e.crypto=="object"){var t=e.crypto.getRandomValues;return typeof t=="function"}return!1}function lGe(e){return e&&aGe.every(function(t){return typeof e[t]=="function"})}var cGe=(function(){function e(t){sGe(vE())?this.hash=new Yze(t):this.hash=new rGe(t)}return e.prototype.update=function(t,n){this.hash.update(u2(t))},e.prototype.digest=function(){return this.hash.digest()},e.prototype.reset=function(){this.hash.reset()},e})();const uGe=({serviceId:e,clientVersion:t})=>async n=>{const i=typeof window<"u"?window.navigator:void 0,r=i?.userAgent??"",a=i?.userAgentData?.platform??vG.os(r)??"other",o=void 0,c=i?.userAgentData?.brands??[],l=c[c.length-1],s=l?.brand??vG.browser(r)??"unknown",u=l?.version??"unknown",d=[["aws-sdk-js",t],["ua","2.1"],[`os/${a}`,o],["lang/js"],["md/browser",`${s}_${u}`]];e&&d.push([`api/${e}`,t]);const p=await n?.userAgentAppId?.();return p&&d.push([`app/${p}`]),d},vG={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"}},dGe=e=>()=>Promise.reject(e),pGe=["in-region","cross-region","mobile","standard","legacy"],fGe=({defaultsMode:e}={})=>Yqe(async()=>{const t=typeof e=="function"?await e():e;switch(t?.toLowerCase()){case"auto":return Promise.resolve(hGe()?"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 ${pGe.join(", ")}, got ${t}`)}}),hGe=()=>{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},Vge="required",au="fn",su="argv",iw="ref",bG=!0,wG="isSet",d2="booleanEquals",Ab="error",m1="endpoint",Ca="tree",e$="PartitionResult",_G={[Vge]:!1,type:"string"},xG={[Vge]:!0,default:!1,type:"boolean"},SG={[iw]:"Endpoint"},Jge={[au]:d2,[su]:[{[iw]:"UseFIPS"},!0]},Kge={[au]:d2,[su]:[{[iw]:"UseDualStack"},!0]},bl={},TG={[au]:"getAttr",[su]:[{[iw]:e$},"supportsFIPS"]},CG={[au]:d2,[su]:[!0,{[au]:"getAttr",[su]:[{[iw]:e$},"supportsDualStack"]}]},EG=[Jge],AG=[Kge],kG=[{[iw]:"Region"}],mGe={parameters:{Region:_G,UseDualStack:xG,UseFIPS:xG,Endpoint:_G},rules:[{conditions:[{[au]:wG,[su]:[SG]}],rules:[{conditions:EG,error:"Invalid Configuration: FIPS and custom endpoint are not supported",type:Ab},{rules:[{conditions:AG,error:"Invalid Configuration: Dualstack and custom endpoint are not supported",type:Ab},{endpoint:{url:SG,properties:bl,headers:bl},type:m1}],type:Ca}],type:Ca},{rules:[{conditions:[{[au]:wG,[su]:kG}],rules:[{conditions:[{[au]:"aws.partition",[su]:kG,assign:e$}],rules:[{conditions:[Jge,Kge],rules:[{conditions:[{[au]:d2,[su]:[bG,TG]},CG],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:bl,headers:bl},type:m1}],type:Ca}],type:Ca},{error:"FIPS and DualStack are enabled, but this partition does not support one or both",type:Ab}],type:Ca},{conditions:EG,rules:[{conditions:[{[au]:d2,[su]:[TG,bG]}],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime-fips.{Region}.{PartitionResult#dnsSuffix}",properties:bl,headers:bl},type:m1}],type:Ca}],type:Ca},{error:"FIPS is enabled but this partition does not support FIPS",type:Ab}],type:Ca},{conditions:AG,rules:[{conditions:[CG],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:bl,headers:bl},type:m1}],type:Ca}],type:Ca},{error:"DualStack is enabled but this partition does not support DualStack",type:Ab}],type:Ca},{rules:[{endpoint:{url:"https://bedrock-runtime.{Region}.{PartitionResult#dnsSuffix}",properties:bl,headers:bl},type:m1}],type:Ca}],type:Ca}],type:Ca},{error:"Invalid Configuration: Missing Region",type:Ab}],type:Ca}]},gGe=mGe,yGe=new _qe({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),vGe=(e,t={})=>yGe.get(e,()=>Uqe(gGe,{endpointParams:e,logger:t.logger}));F3.aws=Zme;class Ha extends f0{constructor(t){super(t),Object.setPrototypeOf(this,Ha.prototype)}}class t$ extends Ha{name="AccessDeniedException";$fault="client";constructor(t){super({name:"AccessDeniedException",$fault:"client",...t}),Object.setPrototypeOf(this,t$.prototype)}}class n$ extends Ha{name="InternalServerException";$fault="server";constructor(t){super({name:"InternalServerException",$fault:"server",...t}),Object.setPrototypeOf(this,n$.prototype)}}class r$ extends Ha{name="ThrottlingException";$fault="client";constructor(t){super({name:"ThrottlingException",$fault:"client",...t}),Object.setPrototypeOf(this,r$.prototype)}}class i$ extends Ha{name="ValidationException";$fault="client";constructor(t){super({name:"ValidationException",$fault:"client",...t}),Object.setPrototypeOf(this,i$.prototype)}}class a$ extends Ha{name="ConflictException";$fault="client";constructor(t){super({name:"ConflictException",$fault:"client",...t}),Object.setPrototypeOf(this,a$.prototype)}}class s$ extends Ha{name="ResourceNotFoundException";$fault="client";constructor(t){super({name:"ResourceNotFoundException",$fault:"client",...t}),Object.setPrototypeOf(this,s$.prototype)}}class o$ extends Ha{name="ServiceQuotaExceededException";$fault="client";constructor(t){super({name:"ServiceQuotaExceededException",$fault:"client",...t}),Object.setPrototypeOf(this,o$.prototype)}}class l$ extends Ha{name="ServiceUnavailableException";$fault="server";constructor(t){super({name:"ServiceUnavailableException",$fault:"server",...t}),Object.setPrototypeOf(this,l$.prototype)}}class c$ extends Ha{name="ModelErrorException";$fault="client";originalStatusCode;resourceName;constructor(t){super({name:"ModelErrorException",$fault:"client",...t}),Object.setPrototypeOf(this,c$.prototype),this.originalStatusCode=t.originalStatusCode,this.resourceName=t.resourceName}}class u$ extends Ha{name="ModelNotReadyException";$fault="client";$retryable={};constructor(t){super({name:"ModelNotReadyException",$fault:"client",...t}),Object.setPrototypeOf(this,u$.prototype)}}class d$ extends Ha{name="ModelTimeoutException";$fault="client";constructor(t){super({name:"ModelTimeoutException",$fault:"client",...t}),Object.setPrototypeOf(this,d$.prototype)}}class p$ extends Ha{name="ModelStreamErrorException";$fault="client";originalStatusCode;originalMessage;constructor(t){super({name:"ModelStreamErrorException",$fault:"client",...t}),Object.setPrototypeOf(this,p$.prototype),this.originalStatusCode=t.originalStatusCode,this.originalMessage=t.originalMessage}}const bGe="AudioBlock",wGe="AccessDeniedException",_Ge="AppliedGuardrailDetails",xGe="AudioSource",SGe="AnyToolChoice",TGe="AutoToolChoice",CGe="Citation",EGe="ContentBlocks",AGe="ContentBlockDelta",kGe="ContentBlockDeltaEvent",RGe="ContentBlockStart",OGe="ContentBlockStartEvent",IGe="ContentBlockStopEvent",PGe="ContentBlock",MGe="CitationsConfig",NGe="CitationsContentBlock",$Ge="CacheDetail",DGe="CacheDetailsList",jGe="CitationsDelta",LGe="ConflictException",FGe="CitationGeneratedContent",UGe="CitationGeneratedContentList",qGe="CitationLocation",BGe="CachePointBlock",WGe="ConverseStream",zGe="CitationSourceContent",GGe="CitationSourceContentDelta",HGe="CitationSourceContentList",VGe="CitationSourceContentListDelta",JGe="ConverseStreamMetrics",KGe="ConverseStreamMetadataEvent",XGe="ConverseStreamOutput",ZGe="ConverseStreamRequest",YGe="ConverseStreamResponse",QGe="ConverseStreamTrace",eHe="Citations",tHe="DocumentBlock",nHe="DocumentContentBlocks",rHe="DocumentContentBlock",iHe="DocumentCharLocation",aHe="DocumentChunkLocation",sHe="DocumentPageLocation",oHe="DocumentSource",lHe="ErrorBlock",cHe="GuardrailAssessment",uHe="GuardrailAssessmentList",dHe="GuardrailAssessmentListMap",pHe="GuardrailAssessmentMap",fHe="GuardrailAutomatedReasoningDifferenceScenarioList",hHe="GuardrailAutomatedReasoningFinding",mHe="GuardrailAutomatedReasoningFindingList",gHe="GuardrailAutomatedReasoningImpossibleFinding",yHe="GuardrailAutomatedReasoningInvalidFinding",vHe="GuardrailAutomatedReasoningInputTextReference",bHe="GuardrailAutomatedReasoningInputTextReferenceList",wHe="GuardrailAutomatedReasoningLogicWarning",_He="GuardrailAutomatedReasoningNoTranslationsFinding",xHe="GuardrailAutomatedReasoningPolicyAssessment",SHe="GuardrailAutomatedReasoningRule",THe="GuardrailAutomatedReasoningRuleList",CHe="GuardrailAutomatedReasoningScenario",EHe="GuardrailAutomatedReasoningSatisfiableFinding",AHe="GuardrailAutomatedReasoningStatementList",kHe="GuardrailAutomatedReasoningStatementLogicContent",RHe="GuardrailAutomatedReasoningStatementNaturalLanguageContent",OHe="GuardrailAutomatedReasoningStatement",IHe="GuardrailAutomatedReasoningTranslation",PHe="GuardrailAutomatedReasoningTranslationAmbiguousFinding",MHe="GuardrailAutomatedReasoningTooComplexFinding",NHe="GuardrailAutomatedReasoningTranslationList",$He="GuardrailAutomatedReasoningTranslationOption",DHe="GuardrailAutomatedReasoningTranslationOptionList",jHe="GuardrailAutomatedReasoningValidFinding",LHe="GuardrailConverseContentBlock",FHe="GuardrailContentFilter",UHe="GuardrailContentFilterList",qHe="GuardrailContextualGroundingFilter",BHe="GuardrailContextualGroundingFilters",WHe="GuardrailContextualGroundingPolicyAssessment",zHe="GuardrailConverseImageBlock",GHe="GuardrailConverseImageSource",HHe="GuardrailContentPolicyAssessment",VHe="GuardrailConverseTextBlock",JHe="GuardrailCustomWord",KHe="GuardrailCustomWordList",XHe="GuardrailCoverage",ZHe="GuardrailImageCoverage",YHe="GuardrailInvocationMetrics",QHe="GuardrailManagedWord",eVe="GuardrailManagedWordList",tVe="GuardrailPiiEntityFilter",nVe="GuardrailPiiEntityFilterList",rVe="GuardrailRegexFilter",iVe="GuardrailRegexFilterList",aVe="GuardrailStreamConfiguration",sVe="GuardrailSensitiveInformationPolicyAssessment",oVe="GuardrailTopic",lVe="GuardrailTraceAssessment",cVe="GuardrailTextCharactersCoverage",uVe="GuardrailTopicList",dVe="GuardrailTopicPolicyAssessment",pVe="GuardrailUsage",fVe="GuardrailWordPolicyAssessment",hVe="ImageBlock",mVe="ImageBlockDelta",gVe="ImageBlockStart",yVe="InferenceConfiguration",vVe="ImageSource",bVe="InternalServerException",wVe="JsonSchemaDefinition",_Ve="Message",xVe="ModelErrorException",SVe="ModelNotReadyException",TVe="MessageStartEvent",CVe="ModelStreamErrorException",EVe="MessageStopEvent",AVe="ModelTimeoutException",kVe="Messages",RVe="OutputConfig",OVe="OutputFormat",IVe="OutputFormatStructure",PVe="PerformanceConfiguration",MVe="PromptRouterTrace",NVe="PromptVariableMap",$Ve="PromptVariableValues",DVe="ReasoningContentBlock",jVe="ReasoningContentBlockDelta",LVe="RequestMetadata",FVe="ResourceNotFoundException",UVe="ReasoningTextBlock",qVe="SystemContentBlocks",BVe="SystemContentBlock",WVe="S3Location",zVe="ServiceQuotaExceededException",GVe="SearchResultBlock",HVe="SearchResultContentBlock",VVe="SearchResultContentBlocks",JVe="SearchResultLocation",KVe="ServiceTier",XVe="SpecificToolChoice",ZVe="SystemTool",YVe="ServiceUnavailableException",QVe="ToolConfiguration",eJe="ToolChoice",tJe="ThrottlingException",nJe="ToolInputSchema",rJe="ToolResultBlock",iJe="ToolResultBlocksDelta",aJe="ToolResultBlockDelta",sJe="ToolResultBlockStart",oJe="ToolResultContentBlocks",lJe="ToolResultContentBlock",cJe="ToolSpecification",uJe="TokenUsage",dJe="ToolUseBlock",pJe="ToolUseBlockDelta",fJe="ToolUseBlockStart",hJe="Tools",mJe="Tool",gJe="VideoBlock",yJe="ValidationException",vJe="VideoSource",bJe="WebLocation",Wv="action",wJe="appliedGuardrailDetails",_Je="additionalModelRequestFields",xJe="additionalModelResponseFieldPaths",SJe="additionalModelResponseFields",TJe="actionReason",CJe="automatedReasoningPolicy",EJe="automatedReasoningPolicyUnits",AJe="automatedReasoningPolicies",kJe="any",RJe="audio",OJe="auto",q2="bytes",IJe="bucketOwner",xu="client",PJe="contentBlockDelta",f$="contentBlockIndex",MJe="contentBlockStart",NJe="contentBlockStop",$Je="citationsContent",DJe="cacheDetails",jJe="claimsFalseScenario",LJe="contextualGroundingPolicy",FJe="contextualGroundingPolicyUnits",UJe="contentPolicy",qJe="contentPolicyImageUnits",BJe="contentPolicyUnits",h$="cachePoint",Xge="contradictingRules",WJe="cacheReadInputTokens",Zge="claimsTrueScenario",zJe="customWords",GJe="cacheWriteInputTokens",m$="citations",HJe="citation",Yge="claims",B2="content",VJe="context",Qge="confidence",JJe="delta",KJe="documentChar",XJe="documentChunk",g$="documentIndex",ZJe="documentPage",YJe="differenceScenarios",zv="detected",eye="description",QJe="domain",tye="document",Va="error",eKe="enabled",Tk="end",aw="format",tKe="filterStrength",nKe="findings",nye="filters",rKe="guardrail",iKe="guardrailArn",aKe="guardrailCoverage",sKe="guardrailConfig",rye="guardContent",oKe="guardrailId",lKe="guardrailIdentifier",cKe="guardrailOrigin",uKe="guardrailOwnership",dKe="guardrailProcessingLatency",iye="guardrailVersion",aye="guarded",pKe="http",_o="httpError",sye="input",fKe="inputAssessment",hKe="inferenceConfig",mKe="invocationMetrics",gKe="invokedModelId",yKe="inputSchema",vKe="internalServerException",oye="inputTokens",bKe="identifier",wKe="images",W2="image",_Ke="impossible",xKe="invalid",y$="json",SKe="jsonSchema",lye="location",TKe="latencyMs",Ck="logicWarning",CKe="latency",EKe="logic",Bs="message",AKe="modelId",kKe="modelOutput",RKe="messageStart",OKe="modelStreamErrorException",IKe="messageStop",PKe="maxTokens",MKe="managedWordLists",Ek="match",NKe="messages",$Ke="metrics",DKe="metadata",cg="name",jKe="naturalLanguage",LKe="noTranslations",FKe="outputAssessments",UKe="outputConfig",qKe="originalMessage",cye="originalStatusCode",BKe="outputTokens",WKe="options",uye="premises",dye="performanceConfig",zKe="piiEntities",GKe="promptRouter",HKe="promptVariables",VKe="policyVersionArn",JKe="qualifiers",KKe="regex",pye="reasoningContent",fye="redactedContent",XKe="requestMetadata",ZKe="resourceName",YKe="reasoningText",QKe="regexes",hye="role",mye="smithy.ts.sdk.synthetic.com.amazonaws.bedrockruntime",gye="sourceContent",eXe="sensitiveInformationPolicy",tXe="sensitiveInformationPolicyFreeUnits",nXe="sensitiveInformationPolicyUnits",Ak="s3Location",rXe="streamProcessingMode",iXe="stopReason",aXe="searchResultIndex",sXe="searchResultLocation",yye="searchResult",oXe="supportingRules",lXe="stopSequences",vye="serviceTier",cXe="systemTool",uXe="serviceUnavailableException",dXe="satisfiable",pXe="score",fXe="schema",bye="server",wye="signature",ug="source",_ye="status",z2="start",hXe="statements",mXe="stream",gXe="streaming",yXe="strict",vXe="structure",bXe="system",xye="ttl",wXe="translationAmbiguous",_Xe="toolConfig",xXe="textCharacters",SXe="toolChoice",TXe="tooComplex",CXe="throttlingException",EXe="textFormat",AXe="topicPolicy",kXe="topicPolicyUnits",RXe="topP",v$="toolResult",OXe="toolSpec",IXe="totalTokens",b$="toolUse",kk="toolUseId",ha="text",PXe="temperature",MXe="threshold",w$="title",Sye="total",NXe="tools",$Xe="tool",DXe="topics",Tye="trace",Rk="translation",jXe="translations",Ws="type",Cye="usage",LXe="untranslatedClaims",FXe="untranslatedPremises",UXe="uri",qXe="url",BXe="validationException",WXe="valid",Eye="video",zXe="web",GXe="wordPolicy",HXe="wordPolicyUnits",Xe="com.amazonaws.bedrockruntime",Aye=is.for(mye);var VXe=[-3,mye,"BedrockRuntimeServiceException",0,[],[]];Aye.registerError(VXe,Ha);const zs=is.for(Xe);var JXe=[-3,Xe,wGe,{[Va]:xu,[_o]:403},[Bs],[0]];zs.registerError(JXe,t$);var KXe=[-3,Xe,LGe,{[Va]:xu,[_o]:400},[Bs],[0]];zs.registerError(KXe,a$);var kye=[-3,Xe,bVe,{[Va]:bye,[_o]:500},[Bs],[0]];zs.registerError(kye,n$);var XXe=[-3,Xe,xVe,{[Va]:xu,[_o]:424},[Bs,cye,ZKe],[0,1,0]];zs.registerError(XXe,c$);var ZXe=[-3,Xe,SVe,{[Va]:xu,[_o]:429},[Bs],[0]];zs.registerError(ZXe,u$);var Rye=[-3,Xe,CVe,{[Va]:xu,[_o]:424},[Bs,cye,qKe],[0,1,0]];zs.registerError(Rye,p$);var YXe=[-3,Xe,AVe,{[Va]:xu,[_o]:408},[Bs],[0]];zs.registerError(YXe,d$);var QXe=[-3,Xe,FVe,{[Va]:xu,[_o]:404},[Bs],[0]];zs.registerError(QXe,s$);var eZe=[-3,Xe,zVe,{[Va]:xu,[_o]:400},[Bs],[0]];zs.registerError(eZe,o$);var Oye=[-3,Xe,YVe,{[Va]:bye,[_o]:503},[Bs],[0]];zs.registerError(Oye,l$);var Iye=[-3,Xe,tJe,{[Va]:xu,[_o]:429},[Bs],[0]];zs.registerError(Iye,r$);var Pye=[-3,Xe,yJe,{[Va]:xu,[_o]:400},[Bs],[0]];zs.registerError(Pye,i$);const tZe=[Aye,zs];var nZe=[0,Xe,kHe,8,0],Mye=[0,Xe,RHe,8,0],rZe=[3,Xe,SGe,0,[],[]],iZe=[3,Xe,_Ge,0,[oKe,iye,iKe,cKe,uKe],[0,0,0,64,0]],aZe=[3,Xe,bGe,0,[aw,ug,Va],[0,[()=>tQe,0],[()=>x$,0]],2],sZe=[3,Xe,TGe,0,[],[]],oZe=[3,Xe,$Ge,0,[xye,oye],[0,1],2],_$=[3,Xe,BGe,0,[Ws,xye],[0,0],1],lZe=[3,Xe,CGe,0,[w$,ug,gye,lye],[0,0,()=>RYe,()=>Bye]],Nye=[3,Xe,MGe,0,[eKe],[2],1],cZe=[3,Xe,NGe,0,[B2,m$],[()=>AYe,()=>kYe]],uZe=[3,Xe,jGe,0,[w$,ug,gye,lye],[0,0,()=>OYe,()=>Bye]],dZe=[3,Xe,GGe,0,[ha],[0]],pZe=[3,Xe,kGe,0,[JJe,f$],[[()=>aQe,0],1],2],fZe=[3,Xe,OGe,0,[z2,f$],[()=>sQe,1],2],hZe=[3,Xe,IGe,0,[f$],[1],1],mZe=[3,Xe,KGe,0,[Cye,$Ke,Tye,dye,vye],[()=>yYe,()=>gZe,[()=>bZe,0],()=>Lye,()=>Uye],2],gZe=[3,Xe,JGe,0,[TKe],[1],1],yZe=[3,Xe,ZGe,0,[AKe,NKe,bXe,hKe,_Xe,sKe,_Je,HKe,xJe,XKe,dye,vye,UKe],[[0,1],[()=>GYe,0],[()=>VYe,0],()=>iYe,()=>vYe,()=>KZe,15,[()=>QYe,0],64,[()=>eQe,0],()=>Lye,()=>Uye,[()=>cYe,0]],1],vZe=[3,Xe,YGe,0,[mXe],[[()=>oQe,16]]],bZe=[3,Xe,QGe,0,[rKe,GKe],[[()=>QZe,0],()=>dYe]],$ye=[3,Xe,tHe,0,[cg,ug,aw,VJe,m$],[0,()=>cQe,0,0,()=>Nye],2],wZe=[3,Xe,iHe,0,[g$,z2,Tk],[1,1,1]],_Ze=[3,Xe,aHe,0,[g$,z2,Tk],[1,1,1]],xZe=[3,Xe,sHe,0,[g$,z2,Tk],[1,1,1]],x$=[3,Xe,lHe,8,[Bs],[0]],Dye=[3,Xe,cHe,0,[AXe,UJe,GXe,eXe,LJe,CJe,mKe,wJe],[()=>YZe,()=>DZe,()=>tYe,()=>JZe,()=>LZe,[()=>AZe,0],()=>zZe,()=>iZe]],SZe=[3,Xe,gHe,0,[Rk,Xge,Ck],[[()=>G2,0],()=>S$,[()=>Ok,0]]],TZe=[3,Xe,vHe,0,[ha],[[()=>Mye,0]]],CZe=[3,Xe,yHe,0,[Rk,Xge,Ck],[[()=>G2,0],()=>S$,[()=>Ok,0]]],Ok=[3,Xe,wHe,0,[Ws,uye,Yge],[0,[()=>p2,0],[()=>p2,0]]],EZe=[3,Xe,_He,0,[],[]],AZe=[3,Xe,xHe,0,[nKe],[[()=>$Ye,0]]],kZe=[3,Xe,SHe,0,[bKe,VKe],[0,0]],RZe=[3,Xe,EHe,0,[Rk,Zge,jJe,Ck],[[()=>G2,0],[()=>z3,0],[()=>z3,0],[()=>Ok,0]]],z3=[3,Xe,CHe,0,[hXe],[[()=>p2,0]]],OZe=[3,Xe,OHe,0,[EKe,jKe],[[()=>nZe,0],[()=>Mye,0]]],IZe=[3,Xe,MHe,0,[],[]],G2=[3,Xe,IHe,0,[uye,Yge,FXe,LXe,Qge],[[()=>p2,0],[()=>p2,0],[()=>RG,0],[()=>RG,0],1]],PZe=[3,Xe,PHe,0,[WKe,YJe],[[()=>jYe,0],[()=>NYe,0]]],MZe=[3,Xe,$He,0,[jXe],[[()=>DYe,0]]],NZe=[3,Xe,jHe,0,[Rk,Zge,oXe,Ck],[[()=>G2,0],[()=>z3,0],()=>S$,[()=>Ok,0]]],$Ze=[3,Xe,FHe,0,[Ws,Qge,Wv,tKe,zv],[0,0,0,0,2],3],DZe=[3,Xe,HHe,0,[nye],[()=>LYe],1],jZe=[3,Xe,qHe,0,[Ws,MXe,pXe,Wv,zv],[0,1,1,0,2],4],LZe=[3,Xe,WHe,0,[nye],[()=>FYe]],FZe=[3,Xe,zHe,8,[aw,ug],[0,[()=>dQe,0]],2],UZe=[3,Xe,VHe,0,[ha,JKe],[0,64],1],qZe=[3,Xe,XHe,0,[xXe,wKe],[()=>XZe,()=>WZe]],BZe=[3,Xe,JHe,0,[Ek,Wv,zv],[0,0,2],2],WZe=[3,Xe,ZHe,0,[aye,Sye],[1,1]],zZe=[3,Xe,YHe,0,[dKe,Cye,aKe],[1,()=>eYe,()=>qZe]],GZe=[3,Xe,QHe,0,[Ek,Ws,Wv,zv],[0,0,0,2],3],HZe=[3,Xe,tVe,0,[Ek,Ws,Wv,zv],[0,0,0,2],3],VZe=[3,Xe,rVe,0,[Wv,cg,Ek,KKe,zv],[0,0,0,0,2],1],JZe=[3,Xe,sVe,0,[zKe,QKe],[()=>BYe,()=>WYe],2],KZe=[3,Xe,aVe,0,[lKe,iye,Tye,rXe],[0,0,0,0]],XZe=[3,Xe,cVe,0,[aye,Sye],[1,1]],ZZe=[3,Xe,oVe,0,[cg,Ws,Wv,zv],[0,0,0,2],3],YZe=[3,Xe,dVe,0,[DXe],[()=>zYe],1],QZe=[3,Xe,lVe,0,[kKe,fKe,FKe,TJe],[64,[()=>YYe,0],[()=>ZYe,0],0]],eYe=[3,Xe,pVe,0,[kXe,BJe,HXe,nXe,tXe,FJe,qJe,EJe,AJe],[1,1,1,1,1,1,1,1,1],6],tYe=[3,Xe,fVe,0,[zJe,MKe],[()=>UYe,()=>qYe],2],jye=[3,Xe,hVe,0,[aw,ug,Va],[0,[()=>zye,0],[()=>x$,0]],2],nYe=[3,Xe,mVe,0,[ug,Va],[[()=>zye,0],[()=>x$,0]]],rYe=[3,Xe,gVe,0,[aw],[0],1],iYe=[3,Xe,yVe,0,[PKe,PXe,RXe,lXe],[1,1,1,64]],aYe=[3,Xe,wVe,0,[fXe,cg,eye],[0,0,0],1],sYe=[3,Xe,_Ve,0,[hye,B2],[0,[()=>IYe,0]],2],oYe=[3,Xe,TVe,0,[hye],[0],1],lYe=[3,Xe,EVe,0,[iXe,SJe],[0,15],1],cYe=[3,Xe,RVe,0,[EXe],[[()=>uYe,0]]],uYe=[3,Xe,OVe,0,[Ws,vXe],[0,[()=>pQe,0]],2],Lye=[3,Xe,PVe,0,[CKe],[0]],dYe=[3,Xe,MVe,0,[gKe],[0]],pYe=[3,Xe,UVe,8,[ha,wye],[0,0],1],Ik=[3,Xe,WVe,0,[UXe,IJe],[0,0],1],Fye=[3,Xe,GVe,0,[ug,w$,B2,m$],[0,0,()=>HYe,()=>Nye],3],fYe=[3,Xe,HVe,0,[ha],[0],1],hYe=[3,Xe,JVe,0,[aXe,z2,Tk],[1,1,1]],Uye=[3,Xe,KVe,0,[Ws],[0],1],mYe=[3,Xe,XVe,0,[cg],[0],1],gYe=[3,Xe,ZVe,0,[cg],[0],1],yYe=[3,Xe,uJe,0,[oye,BKe,IXe,WJe,GJe,DJe],[1,1,1,1,1,()=>EYe],3],vYe=[3,Xe,QVe,0,[NXe,SXe],[()=>XYe,()=>vQe],1],bYe=[3,Xe,rJe,0,[kk,B2,_ye,Ws],[0,[()=>KYe,0],0,0],2],wYe=[3,Xe,sJe,0,[kk,Ws,_ye],[0,0,0],1],_Ye=[3,Xe,cJe,0,[cg,yKe,eye,yXe],[0,()=>bQe,0,2],2],xYe=[3,Xe,dJe,0,[kk,cg,sye,Ws],[0,0,15,0],3],SYe=[3,Xe,pJe,0,[sye],[0],1],TYe=[3,Xe,fJe,0,[kk,cg,Ws],[0,0,0],2],qye=[3,Xe,gJe,0,[aw,ug],[0,()=>xQe],2],CYe=[3,Xe,bJe,0,[qXe,QJe],[0,0]],EYe=[1,Xe,DGe,0,()=>oZe],AYe=[1,Xe,UGe,0,()=>nQe],kYe=[1,Xe,eHe,0,()=>lZe],RYe=[1,Xe,HGe,0,()=>rQe],OYe=[1,Xe,VGe,0,()=>dZe],IYe=[1,Xe,EGe,0,[()=>iQe,0]],PYe=[1,Xe,nHe,0,()=>lQe],MYe=[1,Xe,uHe,0,[()=>Dye,0]],NYe=[1,Xe,fHe,0,[()=>z3,0]],$Ye=[1,Xe,mHe,0,[()=>uQe,0]],RG=[1,Xe,bHe,0,[()=>TZe,0]],S$=[1,Xe,THe,0,()=>kZe],p2=[1,Xe,AHe,0,[()=>OZe,0]],DYe=[1,Xe,NHe,0,[()=>G2,0]],jYe=[1,Xe,DHe,0,[()=>MZe,0]],LYe=[1,Xe,UHe,0,()=>$Ze],FYe=[1,Xe,BHe,0,()=>jZe],UYe=[1,Xe,KHe,0,()=>BZe],qYe=[1,Xe,eVe,0,()=>GZe],BYe=[1,Xe,nVe,0,()=>HZe],WYe=[1,Xe,iVe,0,()=>VZe],zYe=[1,Xe,uVe,0,()=>ZZe],GYe=[1,Xe,kVe,0,[()=>sYe,0]],HYe=[1,Xe,VVe,0,()=>fYe],VYe=[1,Xe,qVe,0,[()=>gQe,0]],JYe=[1,Xe,iJe,0,()=>wQe],KYe=[1,Xe,oJe,0,[()=>_Qe,0]],XYe=[1,Xe,hJe,0,()=>yQe],ZYe=[2,Xe,dHe,0,[0,0],[()=>MYe,0]],YYe=[2,Xe,pHe,0,[0,0],[()=>Dye,0]],QYe=[2,Xe,NVe,8,0,()=>fQe],eQe=[2,Xe,LVe,8,0,0],tQe=[4,Xe,xGe,8,[q2,Ak],[21,()=>Ik]],nQe=[4,Xe,FGe,0,[ha],[0]],Bye=[4,Xe,qGe,0,[zXe,KJe,ZJe,XJe,sXe],[()=>CYe,()=>wZe,()=>xZe,()=>_Ze,()=>hYe]],rQe=[4,Xe,zGe,0,[ha],[0]],iQe=[4,Xe,PGe,0,[ha,W2,tye,Eye,RJe,b$,v$,rye,h$,pye,$Je,yye],[0,[()=>jye,0],()=>$ye,()=>qye,[()=>aZe,0],()=>xYe,[()=>bYe,0],[()=>Wye,0],()=>_$,[()=>hQe,0],()=>cZe,()=>Fye]],aQe=[4,Xe,AGe,0,[ha,b$,v$,pye,HJe,W2],[0,()=>SYe,()=>JYe,[()=>mQe,0],()=>uZe,[()=>nYe,0]]],sQe=[4,Xe,RGe,0,[b$,v$,W2],[()=>TYe,()=>wYe,()=>rYe]],oQe=[4,Xe,XGe,{[gXe]:1},[RKe,MJe,PJe,NJe,IKe,DKe,vKe,OKe,BXe,CXe,uXe],[()=>oYe,()=>fZe,[()=>pZe,0],()=>hZe,()=>lYe,[()=>mZe,0],[()=>kye,0],[()=>Rye,0],[()=>Pye,0],[()=>Iye,0],[()=>Oye,0]]],lQe=[4,Xe,rHe,0,[ha],[0]],cQe=[4,Xe,oHe,0,[q2,Ak,ha,B2],[21,()=>Ik,0,()=>PYe]],uQe=[4,Xe,hHe,0,[WXe,xKe,dXe,_Ke,wXe,TXe,LKe],[[()=>NZe,0],[()=>CZe,0],[()=>RZe,0],[()=>SZe,0],[()=>PZe,0],()=>IZe,()=>EZe]],Wye=[4,Xe,LHe,0,[ha,W2],[()=>UZe,[()=>FZe,0]]],dQe=[4,Xe,GHe,8,[q2],[21]],zye=[4,Xe,vVe,8,[q2,Ak],[21,()=>Ik]],pQe=[4,Xe,IVe,8,[SKe],[()=>aYe]],fQe=[4,Xe,$Ve,0,[ha],[0]],hQe=[4,Xe,DVe,8,[YKe,fye],[[()=>pYe,0],21]],mQe=[4,Xe,jVe,8,[ha,fye,wye],[0,21,0]],gQe=[4,Xe,BVe,0,[ha,rye,h$],[0,[()=>Wye,0],()=>_$]],yQe=[4,Xe,mJe,0,[OXe,cXe,h$],[()=>_Ye,()=>gYe,()=>_$]],vQe=[4,Xe,eJe,0,[OJe,kJe,$Xe],[()=>sZe,()=>rZe,()=>mYe]],bQe=[4,Xe,nJe,0,[y$],[15]],wQe=[4,Xe,aJe,0,[ha,y$],[0,15]],_Qe=[4,Xe,lJe,0,[y$,ha,W2,tye,Eye,yye],[15,0,[()=>jye,0],()=>$ye,()=>qye,()=>Fye]],xQe=[4,Xe,vJe,0,[q2,Ak],[21,()=>Ik]],SQe=[9,Xe,WGe,{[pKe]:["POST","/model/{modelId}/converse-stream",200]},()=>yZe,()=>vZe];const TQe=e=>({apiVersion:"2023-09-30",base64Decoder:e?.base64Decoder??Ov,base64Encoder:e?.base64Encoder??Pv,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??vGe,extensions:e?.extensions??[],httpAuthSchemeProvider:e?.httpAuthSchemeProvider??zze,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:t=>t.getIdentityProvider("aws.auth#sigv4"),signer:new Zqe},{schemeId:"smithy.api#httpBearerAuth",identityProvider:t=>t.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new mqe}],logger:e?.logger??new lge,protocol:e?.protocol??JBe,protocolSettings:e?.protocolSettings??{defaultNamespace:"com.amazonaws.bedrockruntime",errorTypeRegistries:tZe,version:"2023-09-30",serviceTarget:"AmazonBedrockFrontendService"},serviceId:e?.serviceId??"Bedrock Runtime",urlParser:e?.urlParser??U3,utf8Decoder:e?.utf8Decoder??Iv,utf8Encoder:e?.utf8Encoder??rw}),CQe=e=>{const t=fGe(e),n=()=>t().then(IBe),i=TQe(e);return{...i,...e,runtime:"browser",defaultsMode:t,bodyLengthChecker:e?.bodyLengthChecker??kBe,credentialDefaultProvider:e?.credentialDefaultProvider??(r=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:e?.defaultUserAgentProvider??uGe({serviceId:i.serviceId,clientVersion:Kze.version}),eventStreamPayloadHandlerProvider:e?.eventStreamPayloadHandlerProvider??zWe,eventStreamSerdeProvider:e?.eventStreamSerdeProvider??NWe,maxAttempts:e?.maxAttempts??W3,region:e?.region??dGe("Region is missing"),requestHandler:Z7.create(e?.requestHandler??n,s2.create(n)),retryMode:e?.retryMode??(async()=>(await n()).retryMode||fze),sha256:e?.sha256??cGe,streamCollector:e?.streamCollector??Ome,useDualstackEndpoint:e?.useDualstackEndpoint??(()=>Promise.resolve(GWe)),useFipsEndpoint:e?.useFipsEndpoint??(()=>Promise.resolve(HWe))}},EQe=e=>({setRegion(t){e.region=t},region(){return e.region}}),AQe=e=>({region:e.region()}),kQe=e=>{const t=e.httpAuthSchemes;let n=e.httpAuthSchemeProvider,i=e.credentials,r=e.token;return{setHttpAuthScheme(a){const o=t.findIndex(c=>c.schemeId===a.schemeId);o===-1?t.push(a):t.splice(o,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}}},RQe=e=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials(),token:e.token()}),OQe=(e,t)=>{const n=Object.assign(EQe(e),DBe(e),WFe(e),kQe(e));return t.forEach(i=>i.configure(n)),Object.assign(e,AQe(n),jBe(n),zFe(n),RQe(n))};class IQe extends RBe{config;constructor(...[t]){const n=CQe(t||{});super(n),this.initConfig=n;const i=Hze(n),r=wqe(i),a=Pze(r),o=KWe(a),c=o,l=pze(c),s=XWe(l),u=Gze(s),d=BFe(u),p=UWe(d),f=OQe(p,t?.extensions||[]);this.config=f,this.middlewareStack.use(TUe(this.config)),this.middlewareStack.use(rWe(this.config)),this.middlewareStack.use(Fze(this.config)),this.middlewareStack.use(QWe(this.config)),this.middlewareStack.use(JFe(this.config)),this.middlewareStack.use(ZFe(this.config)),this.middlewareStack.use(eUe(this.config)),this.middlewareStack.use(aUe(this.config,{httpAuthSchemeParametersProvider:qze,identityProviderConfigProvider:async h=>new hqe({"aws.auth#sigv4":h.credentials,"smithy.api#httpBearerAuth":h.token})})),this.middlewareStack.use(dUe(this.config))}destroy(){super.destroy()}}class PQe extends sge.classBuilder().ep(Vze).m(function(t,n,i,r){return[dze(i,t.getEndpointParameterInstructions())]}).s("AmazonBedrockFrontendService","ConverseStream",{eventStream:{output:!0}}).n("BedrockRuntimeClient","ConverseStreamCommand").sc(SQe).build(){}const Gye={ONE_HOUR:"1h"},Hye={DEFAULT:"default"},gT={GIF:"gif",JPEG:"jpeg",PNG:"png",WEBP:"webp"},yT={ERROR:"error",SUCCESS:"success"},ux={ASSISTANT:"assistant",USER:"user"},g1={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 Do={};const dx=(e,t,n={})=>{const i=new bo;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,o={region:n.region,profile:n.profile};if(typeof process<"u"&&(process.versions?.node||process.versions?.bun)){if(o.region=o.region||Do.AWS_REGION||Do.AWS_DEFAULT_REGION,Do.AWS_BEDROCK_SKIP_AUTH==="1"&&(o.credentials={accessKeyId:"dummy-access-key",secretAccessKey:"dummy-secret-key"}),Do.HTTP_PROXY||Do.HTTPS_PROXY||Do.NO_PROXY||Do.http_proxy||Do.https_proxy||Do.no_proxy){const c=await Tn(()=>import("./index-COWGW4FB.js"),__vite__mapDeps([0,1])),l=await Tn(()=>import("./index-Cg4KUhhA.js").then(u=>u.i),__vite__mapDeps([2,1,3,4])),s=new l.ProxyAgent;o.requestHandler=new c.NodeHttpHandler({httpAgent:s,httpsAgent:s})}else if(Do.AWS_BEDROCK_FORCE_HTTP1==="1"){const c=await Tn(()=>import("./index-COWGW4FB.js"),__vite__mapDeps([0,1]));o.requestHandler=new c.NodeHttpHandler}}o.region=o.region||"us-east-1";try{const c=new IQe(o),l=FQe(n.cacheRetention),s={modelId:e.id,messages:WQe(t,e,l),system:qQe(t.systemPrompt,e,l),inferenceConfig:{maxTokens:n.maxTokens,temperature:n.temperature},toolConfig:zQe(t.tools,n.toolChoice),additionalModelRequestFields:HQe(e,n)};n?.onPayload?.(s);const u=new PQe(s),d=await c.send(u,{abortSignal:n.signal});for await(const p of d.stream)if(p.messageStart){if(p.messageStart.role!==ux.ASSISTANT)throw new Error("Unexpected assistant message start but got user message start instead");i.push({type:"start",partial:r})}else if(p.contentBlockStart)NQe(p.contentBlockStart,a,r,i);else if(p.contentBlockDelta)$Qe(p.contentBlockDelta,a,r,i);else if(p.contentBlockStop)jQe(p.contentBlockStop,a,r,i);else if(p.messageStop)r.stopReason=GQe(p.messageStop.stopReason);else if(p.metadata)DQe(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 l of r.content)delete l.index,delete l.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},MQe=(e,t,n)=>{const i=wu(e,n,void 0);if(!n?.reasoning)return dx(e,t,{...i,reasoning:void 0});if(e.id.includes("anthropic.claude")||e.id.includes("anthropic/claude")){if(gM(e.id))return dx(e,t,{...i,reasoning:n.reasoning,thinkingBudgets:n.thinkingBudgets});const r=t7(i.maxTokens||0,e.maxTokens,n.reasoning,n.thinkingBudgets);return dx(e,t,{...i,maxTokens:r.maxTokens,reasoning:n.reasoning,thinkingBudgets:{...n.thinkingBudgets||{},[_u(n.reasoning)]:r.thinkingBudget}})}return dx(e,t,{...i,reasoning:n.reasoning,thinkingBudgets:n.thinkingBudgets})};function NQe(e,t,n,i){const r=e.contentBlockIndex,a=e.start;if(a?.toolUse){const o={type:"toolCall",id:a.toolUse.toolUseId||"",name:a.toolUse.name||"",arguments:{},partialJson:"",index:r};n.content.push(o),i.push({type:"toolcall_start",contentIndex:t.length-1,partial:n})}}function $Qe(e,t,n,i){const r=e.contentBlockIndex,a=e.delta;let o=t.findIndex(l=>l.index===r),c=t[o];if(a?.text!==void 0){if(!c){const l={type:"text",text:"",index:r};n.content.push(l),o=t.length-1,c=t[o],i.push({type:"text_start",contentIndex:o,partial:n})}c.type==="text"&&(c.text+=a.text,i.push({type:"text_delta",contentIndex:o,delta:a.text,partial:n}))}else if(a?.toolUse&&c?.type==="toolCall")c.partialJson=(c.partialJson||"")+(a.toolUse.input||""),c.arguments=cu(c.partialJson),i.push({type:"toolcall_delta",contentIndex:o,delta:a.toolUse.input||"",partial:n});else if(a?.reasoningContent){let l=c,s=o;if(!l){const u={type:"thinking",thinking:"",thinkingSignature:"",index:r};n.content.push(u),s=t.length-1,l=t[s],i.push({type:"thinking_start",contentIndex:s,partial:n})}l?.type==="thinking"&&(a.reasoningContent.text&&(l.thinking+=a.reasoningContent.text,i.push({type:"thinking_delta",contentIndex:s,delta:a.reasoningContent.text,partial:n})),a.reasoningContent.signature&&(l.thinkingSignature=(l.thinkingSignature||"")+a.reasoningContent.signature))}}function DQe(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,rg(t,n.usage))}function jQe(e,t,n,i){const r=t.findIndex(o=>o.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=cu(a.partialJson),delete a.partialJson,i.push({type:"toolcall_end",contentIndex:r,toolCall:a,partial:n});break}}function gM(e){return e.includes("opus-4-6")||e.includes("opus-4.6")||e.includes("sonnet-4-6")||e.includes("sonnet-4.6")}function LQe(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 FQe(e){return e||(typeof process<"u"&&Do.PI_CACHE_RETENTION==="long"?"long":"short")}function Vye(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 UQe(e){const t=e.id.toLowerCase();return t.includes("anthropic.claude")||t.includes("anthropic/claude")}function qQe(e,t,n){if(!e)return;const i=[{text:Qn(e)}];return n!=="none"&&Vye(t)&&i.push({cachePoint:{type:Hye.DEFAULT,...n==="long"?{ttl:Gye.ONE_HOUR}:{}}}),i}function BQe(e){const t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return t.length>64?t.slice(0,64):t}function WQe(e,t,n){const i=[],r=X0(e.messages,t,BQe);for(let a=0;a<r.length;a++){const o=r[a];switch(o.role){case"user":i.push({role:ux.USER,content:typeof o.content=="string"?[{text:Qn(o.content)}]:o.content.map(c=>{switch(c.type){case"text":return{text:Qn(c.text)};case"image":return{image:x9(c.mimeType,c.data)};default:throw new Error("Unknown user content type")}})});break;case"assistant":{if(o.content.length===0)continue;const c=[];for(const l of o.content)switch(l.type){case"text":if(l.text.trim().length===0)continue;c.push({text:Qn(l.text)});break;case"toolCall":c.push({toolUse:{toolUseId:l.id,name:l.name,input:l.arguments}});break;case"thinking":if(l.thinking.trim().length===0)continue;UQe(t)?c.push({reasoningContent:{reasoningText:{text:Qn(l.thinking),signature:l.thinkingSignature}}}):c.push({reasoningContent:{reasoningText:{text:Qn(l.thinking)}}});break;default:throw new Error("Unknown assistant content type")}if(c.length===0)continue;i.push({role:ux.ASSISTANT,content:c});break}case"toolResult":{const c=[];c.push({toolResult:{toolUseId:o.toolCallId,content:o.content.map(s=>s.type==="image"?{image:x9(s.mimeType,s.data)}:{text:Qn(s.text)}),status:o.isError?yT.ERROR:yT.SUCCESS}});let l=a+1;for(;l<r.length&&r[l].role==="toolResult";){const s=r[l];c.push({toolResult:{toolUseId:s.toolCallId,content:s.content.map(u=>u.type==="image"?{image:x9(u.mimeType,u.data)}:{text:Qn(u.text)}),status:s.isError?yT.ERROR:yT.SUCCESS}}),l++}a=l-1,i.push({role:ux.USER,content:c});break}default:throw new Error("Unknown message role")}}if(n!=="none"&&Vye(t)&&i.length>0){const a=i[i.length-1];a.role===ux.USER&&a.content&&a.content.push({cachePoint:{type:Hye.DEFAULT,...n==="long"?{ttl:Gye.ONE_HOUR}:{}}})}return i}function zQe(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 GQe(e){switch(e){case g1.END_TURN:case g1.STOP_SEQUENCE:return"stop";case g1.MAX_TOKENS:case g1.MODEL_CONTEXT_WINDOW_EXCEEDED:return"length";case g1.TOOL_USE:return"toolUse";default:return"error"}}function HQe(e,t){if(!(!t.reasoning||!e.reasoning)&&(e.id.includes("anthropic.claude")||e.id.includes("anthropic/claude"))){const n=gM(e.id)?{thinking:{type:"adaptive"},output_config:{effort:LQe(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!gM(e.id)&&(t.interleavedThinking??!0)&&(n.anthropic_beta=["interleaved-thinking-2025-05-14"]),n}}function x9(e,t){let n;switch(e){case"image/jpeg":case"image/jpg":n=gT.JPEG;break;case"image/png":n=gT.PNG;break;case"image/gif":n=gT.GIF;break;case"image/webp":n=gT.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 px=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&Tn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{px=e});const VQe="https://chatgpt.com/backend-api",JQe="https://api.openai.com/auth",S9=3,OG=1e3,KQe=new Set(["openai","openai-codex","opencode"]),XQe=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function ZQe(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 IG(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 Jye=(e,t,n)=>{const i=new bo;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||vo(e.provider)||"";if(!a)throw new Error(`No API key for provider: ${e.provider}`);const o=get(a),c=QQe(e,t,n);n?.onPayload?.(c);const l=yet(e.headers,n?.headers,o,a,n?.sessionId),s=JSON.stringify(c),u=n?.transport||"sse";if(u!=="sse"){let f=!1;try{if(await het(tet(e.baseUrl),c,l,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<=S9;f++){if(n?.signal?.aborted)throw new Error("Request was aborted");try{if(d=await fetch(Kye(e.baseUrl),{method:"POST",headers:l,body:s,signal:n?.signal}),d.ok)break;const h=await d.text();if(f<S9&&ZQe(d.status,h)){const y=OG*2**f;await IG(y,n?.signal);continue}const m=new Response(h,{status:d.status,statusText:d.statusText}),g=await met(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<S9&&!p.message.includes("usage limit")){const m=OG*2**f;await IG(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 net(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},YQe=(e,t,n)=>{const i=n?.apiKey||vo(e.provider);if(!i)throw new Error(`No API key for provider: ${e.provider}`);const r=wu(e,n,i),a=YA(e)?n?.reasoning:_u(n?.reasoning);return Jye(e,t,{...r,reasoningEffort:a})};function QQe(e,t,n){const i=T7(e,t,KQe,{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=C7(t.tools,{strict:null})),n?.reasoningEffort!==void 0&&(r.reasoning={effort:eet(e.id,n.reasoningEffort),summary:n.reasoningSummary??"auto"}),r}function eet(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 Kye(e){const n=(e&&e.trim().length>0?e:VQe).replace(/\/+$/,"");return n.endsWith("/codex/responses")?n:n.endsWith("/codex")?`${n}/responses`:`${n}/codex/responses`}function tet(e){const t=new URL(Kye(e));return t.protocol==="https:"&&(t.protocol="wss:"),t.protocol==="http:"&&(t.protocol="ws:"),t.toString()}async function net(e,t,n,i){await dk(Xye(iet(e)),t,n,i)}async function*Xye(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:ret(i.status)};yield{...t,type:"response.completed",response:r};continue}yield t}}}function ret(e){if(typeof e=="string")return XQe.has(e)?e:void 0}async function*iet(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 o=i.indexOf(`
865
865
 
866
866
  `);for(;o!==-1;){const c=i.slice(0,o);i=i.slice(o+2);const l=c.split(`
867
867
  `).filter(s=>s.startsWith("data:")).map(s=>s.slice(5).trim());if(l.length>0){const s=l.join(`
868
868
  `).trim();if(s&&s!=="[DONE]")try{yield JSON.parse(s)}catch{}}o=i.indexOf(`
869
869
 
870
- `)}}}const aet="responses_websockets=2026-02-06",set=300*1e3,Ky=new Map;function oet(){const e=globalThis.WebSocket;return typeof e!="function"?null:e}function cet(e){const t={};for(const[n,i]of e.entries())t[n]=i;return t}function uet(e){const t=e.readyState;return typeof t=="number"?t:void 0}function vT(e){const t=uet(e);return t===void 0||t===1}function Xy(e,t=1e3,n="done"){try{e.close(t,n)}catch{}}function PG(e,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{t.busy||(Xy(t.socket,1e3,"idle_timeout"),Ky.delete(e))},set)}async function T9(e,t,n){const i=oet();if(!i)throw new Error("WebSocket transport is not available in this runtime");const r=cet(t);return r["OpenAI-Beta"]=aet,new Promise((a,o)=>{let c=!1,l;try{l=new i(e,{headers:r})}catch(h){o(h instanceof Error?h:new Error(String(h)));return}const s=()=>{c||(c=!0,f(),a(l))},u=h=>{c||(c=!0,f(),o(Zye(h)))},d=h=>{c||(c=!0,f(),o(Yye(h)))},p=()=>{c||(c=!0,f(),l.close(1e3,"aborted"),o(new Error("Request was aborted")))},f=()=>{l.removeEventListener("open",s),l.removeEventListener("error",u),l.removeEventListener("close",d),n?.removeEventListener("abort",p)};l.addEventListener("open",s),l.addEventListener("error",u),l.addEventListener("close",d),n?.addEventListener("abort",p)})}async function det(e,t,n,i){if(!n){const c=await T9(e,t,i);return{socket:c,release:({keep:l}={})=>{if(l===!1){Xy(c);return}Xy(c)}}}const r=Ky.get(n);if(r){if(r.idleTimer&&(clearTimeout(r.idleTimer),r.idleTimer=void 0),!r.busy&&vT(r.socket))return r.busy=!0,{socket:r.socket,release:({keep:c}={})=>{if(!c||!vT(r.socket)){Xy(r.socket),Ky.delete(n);return}r.busy=!1,PG(n,r)}};if(r.busy){const c=await T9(e,t,i);return{socket:c,release:()=>{Xy(c)}}}vT(r.socket)||(Xy(r.socket),Ky.delete(n))}const a=await T9(e,t,i),o={socket:a,busy:!0};return Ky.set(n,o),{socket:a,release:({keep:c}={})=>{if(!c||!vT(o.socket)){Xy(o.socket),o.idleTimer&&clearTimeout(o.idleTimer),Ky.get(n)===o&&Ky.delete(n);return}o.busy=!1,PG(n,o)}}}function Zye(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 Yye(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 pet(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*fet(e,t){const n=[];let i=null,r=!1,a=null,o=!1;const c=()=>{if(!i)return;const p=i;i=null,p()},l=p=>{(async()=>{if(!p||typeof p!="object"||!("data"in p))return;const f=await pet(p.data);if(f)try{const h=JSON.parse(f),m=typeof h.type=="string"?h.type:"";(m==="response.completed"||m==="response.done")&&(o=!0,r=!0),n.push(h),c()}catch{}})()},s=p=>{a=Zye(p),r=!0,c()},u=p=>{if(o){r=!0,c();return}a||(a=Yye(p)),r=!0,c()},d=()=>{a=new Error("Request was aborted"),r=!0,c()};e.addEventListener("message",l),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(!o)throw new Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",l),e.removeEventListener("error",s),e.removeEventListener("close",u),t?.removeEventListener("abort",d)}}async function het(e,t,n,i,r,a,o,c){const{socket:l,release:s}=await det(e,n,c?.sessionId,c?.signal);let u=!0;try{l.send(JSON.stringify({type:"response.create",...t})),o(),r.push({type:"start",partial:i}),await dk(Xye(fet(l,c?.signal)),i,r,a),c?.signal?.aborted&&(u=!1)}catch(d){throw u=!1,d}finally{s({keep:u})}}async function met(e){const t=await e.text();let n=t||e.statusText||"Request failed",i;try{const a=JSON.parse(t)?.error;if(a){const o=a.code||a.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(o)||e.status===429){const c=a.plan_type?` (${a.plan_type.toLowerCase()} plan)`:"",l=a.resets_at?Math.max(0,Math.round((a.resets_at*1e3-Date.now())/6e4)):void 0,s=l!==void 0?` Try again in ~${l} min.`:"";i=`You have hit your ChatGPT usage limit${c}.${s}`.trim()}n=a.message||i||n}}catch{}return{message:n,friendlyMessage:i}}function get(e){try{const t=e.split(".");if(t.length!==3)throw new Error("Invalid token");const i=JSON.parse(atob(t[1]))?.[JQe]?.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 yet(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 o=px?`pi (${px.platform()} ${px.release()}; ${px.arch()})`:"pi (browser)";a.set("User-Agent",o),a.set("accept","text/event-stream"),a.set("content-type","application/json");for(const[c,l]of Object.entries(t||{}))a.set(c,l);return r&&a.set("session_id",r),a}function vet(){Lo({api:"anthropic-messages",stream:Ix,streamSimple:Wpe}),Lo({api:"openai-completions",stream:Eme,streamSimple:CFe}),Lo({api:"openai-responses",stream:Ame,streamSimple:jFe}),Lo({api:"azure-openai-responses",stream:Ahe,streamSimple:dMe}),Lo({api:"openai-codex-responses",stream:Jye,streamSimple:YQe}),Lo({api:"google-generative-ai",stream:hE,streamSimple:GLe}),Lo({api:"google-gemini-cli",stream:mE,streamSimple:cFe}),Lo({api:"google-vertex",stream:gE,streamSimple:mFe}),Lo({api:"bedrock-converse-stream",stream:dx,streamSimple:MQe})}vet();typeof process<"u"&&process.versions?.node&&Tn(()=>import("./index-bo18OtLo.js").then(e=>e.i),__vite__mapDeps([5,3,4])).then(e=>{const{EnvHttpProxyAgent:t,setGlobalDispatcher:n}=e;n(new t)});function bet(e){const t=mP(e);if(!t)throw new Error(`No API provider registered for api: ${e}`);return t}function Qye(e,t,n){return bet(e.api).streamSimple(e,t,n)}function MG(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function Pk(){const e=new Uint8Array(32);crypto.getRandomValues(e);const t=MG(e),i=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",i),a=MG(new Uint8Array(r));return{verifier:t,challenge:a}}const wet=e=>atob(e),yM=wet("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl"),_et="https://claude.ai/oauth/authorize",eve="https://console.anthropic.com/v1/oauth/token",NG="https://console.anthropic.com/oauth/code/callback",xet="org:create_api_key user:profile user:inference";async function Tet(e,t){const{verifier:n,challenge:i}=await Pk(),r=new URLSearchParams({code:"true",client_id:yM,response_type:"code",redirect_uri:NG,scope:xet,code_challenge:i,code_challenge_method:"S256",state:n}),a=`${_et}?${r.toString()}`;e(a);const c=(await t()).split("#"),l=c[0],s=c[1],u=await fetch(eve,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:yM,code:l,state:s,redirect_uri:NG,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 Cet(e){const t=await fetch(eve,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:yM,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 Eet={id:"anthropic",name:"Anthropic (Claude Pro/Max)",async login(e){return Tet(t=>e.onAuth({url:t}),()=>e.onPrompt({message:"Paste the authorization code:"}))},async refreshToken(e){return Cet(e.refresh)},getApiKey(e){return e.access}},Aet=e=>atob(e),tve=Aet("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),nve={"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 rve(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 T$(e){return{deviceCodeUrl:`https://${e}/login/device/code`,accessTokenUrl:`https://${e}/login/oauth/access_token`,copilotTokenUrl:`https://api.${e}/copilot_internal/v2/token`}}function ket(e){const t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,"api.")}`:null}function ive(e,t){if(e){const n=ket(e);if(n)return n}return t?`https://copilot-api.${t}`:"https://api.individual.githubcopilot.com"}async function C$(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 Ret(e){const t=T$(e),n=await C$(t.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"GitHubCopilotChat/0.35.0"},body:JSON.stringify({client_id:tve,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,o=n.interval,c=n.expires_in;if(typeof i!="string"||typeof r!="string"||typeof a!="string"||typeof o!="number"||typeof c!="number")throw new Error("Invalid device code response fields");return{device_code:i,user_code:r,verification_uri:a,interval:o,expires_in:c}}function C9(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 Oet(e,t,n,i,r){const a=T$(e),o=Date.now()+i*1e3;let c=Math.max(1e3,Math.floor(n*1e3));for(;Date.now()<o;){if(r?.aborted)throw new Error("Login cancelled");const l=await C$(a.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"GitHubCopilotChat/0.35.0"},body:JSON.stringify({client_id:tve,device_code:t,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(l&&typeof l=="object"&&typeof l.access_token=="string")return l.access_token;if(l&&typeof l=="object"&&typeof l.error=="string"){const s=l.error;if(s==="authorization_pending"){await C9(c,r);continue}if(s==="slow_down"){c+=5e3,await C9(c,r);continue}throw new Error(`Device flow failed: ${s}`)}await C9(c,r)}throw new Error("Device flow timed out")}async function ave(e,t){const i=T$(t||"github.com"),r=await C$(i.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`,...nve}});if(!r||typeof r!="object")throw new Error("Invalid Copilot token response");const a=r.token,o=r.expires_at;if(typeof a!="string"||typeof o!="number")throw new Error("Invalid Copilot token response fields");return{refresh:e,access:a,expires:o*1e3-300*1e3,enterpriseUrl:t}}async function Iet(e,t,n){const r=`${ive(e,n)}/models/${t}/policy`;try{return(await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...nve,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})})).ok}catch{return!1}}async function Pet(e,t,n){const i=b3("github-copilot");await Promise.all(i.map(async r=>{await Iet(e,r.id,t)}))}async function Met(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=rve(t);if(n&&!i)throw new Error("Invalid GitHub Enterprise URL/domain");const r=i||"github.com",a=await Ret(r);e.onAuth(a.verification_uri,`Enter code: ${a.user_code}`);const o=await Oet(r,a.device_code,a.interval,a.expires_in,e.signal),c=await ave(o,i??void 0);return e.onProgress?.("Enabling models..."),await Pet(c.access,i??void 0),c}const Net={id:"github-copilot",name:"GitHub Copilot",async login(e){return Met({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 ave(t.refresh,t.enterpriseUrl)},getApiKey(e){return e.access},modifyModels(e,t){const n=t,i=n.enterpriseUrl?rve(n.enterpriseUrl)??void 0:void 0,r=ive(n.access,i);return e.map(a=>a.provider==="github-copilot"?{...a,baseUrl:r}:a)}};let fx=null,vM=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(vM=Tn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{fx=e.createServer}));const sve=e=>atob(e),bM=sve("MTA3MTAwNjA2MDU5MS10bWhzc2luMmgyMWxjcmUyMzV2dG9sb2poNGc0MDNlcC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbQ=="),ove=sve("R09DU1BYLUs1OEZXUjQ4NkxkTEoxbUxCOHNYQzR6NnFEQWY="),$G="http://localhost:51121/oauth-callback",$et=["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"],Det="https://accounts.google.com/o/oauth2/v2/auth",lve="https://oauth2.googleapis.com/token",jet="rising-fact-p41fc";async function Let(){if(fx||(vM&&await vM,fx))return fx;throw new Error("Antigravity OAuth is only available in Node.js environments")}async function Fet(){const e=await Let();return new Promise((t,n)=>{let i=null,r=!1;const a=e((o,c)=>{const l=new URL(o.url||"","http://localhost:51121");if(l.pathname==="/oauth-callback"){const s=l.searchParams.get("code"),u=l.searchParams.get("state"),d=l.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",o=>{n(o)}),a.listen(51121,"127.0.0.1",()=>{t({server:a,cancelWait:()=>{r=!0},waitForCode:async()=>{const o=()=>new Promise(c=>setTimeout(c,100));for(;!i&&!r;)await o();return i}})})})}function DG(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 Uet(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 o=await a.json();if(typeof o.cloudaicompanionProject=="string"&&o.cloudaicompanionProject)return o.cloudaicompanionProject;if(o.cloudaicompanionProject&&typeof o.cloudaicompanionProject=="object"&&o.cloudaicompanionProject.id)return o.cloudaicompanionProject.id}}catch{}return t?.("Using default project..."),jet}async function qet(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 Bet(e,t){const n=await fetch(lve,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:bM,client_secret:ove,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 Wet(e,t,n){const{verifier:i,challenge:r}=await Pk();t?.("Starting local server for OAuth callback...");const a=await Fet();let o;try{const c=new URLSearchParams({client_id:bM,response_type:"code",redirect_uri:$G,scope:$et.join(" "),code_challenge:r,code_challenge_method:"S256",state:i,access_type:"offline",prompt:"consent"}),l=`${Det}?${c.toString()}`;if(e({url:l,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");o=v.code}else if(m){const b=DG(m);if(b.state&&b.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");o=b.code}if(!o){if(await y,g)throw g;if(m){const b=DG(m);if(b.state&&b.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");o=b.code}}}else{const m=await a.waitForCode();if(m?.code){if(m.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");o=m.code}}if(!o)throw new Error("No authorization code received");t?.("Exchanging authorization code for tokens...");const s=await fetch(lve,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:bM,client_secret:ove,code:o,grant_type:"authorization_code",redirect_uri:$G,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 qet(u.access_token),p=await Uet(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 zet={id:"google-antigravity",name:"Antigravity (Gemini 3, Claude, GPT-OSS)",usesCallbackServer:!0,async login(e){return Wet(e.onAuth,e.onProgress,e.onManualCodeInput)},async refreshToken(e){const t=e;if(!t.projectId)throw new Error("Antigravity credentials missing projectId");return Bet(t.refresh,t.projectId)},getApiKey(e){const t=e;return JSON.stringify({token:t.access,projectId:t.projectId})}};var jG={};let hx=null,wM=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(wM=Tn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{hx=e.createServer}));const cve=e=>atob(e),_M=cve("NjgxMjU1ODA5Mzk1LW9vOGZ0Mm9wcmRybnA5ZTNhcWY2YXYzaG1kaWIxMzVqLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29t"),uve=cve("R09DU1BYLTR1SGdNUG0tMW83U2stZ2VWNkN1NWNsWEZzeGw="),LG="http://localhost:8085/oauth2callback",Get=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile"],Het="https://accounts.google.com/o/oauth2/v2/auth",dve="https://oauth2.googleapis.com/token",xM="https://cloudcode-pa.googleapis.com";async function Vet(){if(hx||(wM&&await wM,hx))return hx;throw new Error("Gemini CLI OAuth is only available in Node.js environments")}async function Jet(){const e=await Vet();return new Promise((t,n)=>{let i=null,r=!1;const a=e((o,c)=>{const l=new URL(o.url||"","http://localhost:8085");if(l.pathname==="/oauth2callback"){const s=l.searchParams.get("code"),u=l.searchParams.get("state"),d=l.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",o=>{n(o)}),a.listen(8085,"127.0.0.1",()=>{t({server:a,cancelWait:()=>{r=!0},waitForCode:async()=>{const o=()=>new Promise(c=>setTimeout(c,100));for(;!i&&!r;)await o();return i}})})})}function FG(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 E9="free-tier",UG="legacy-tier",Ket="standard-tier";function Xet(e){return new Promise(t=>setTimeout(t,e))}function Zet(e){return!e||e.length===0?{id:UG}:e.find(n=>n.isDefault)??{id:UG}}function Yet(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 Qet(e,t,n){let i=0;for(;;){i>0&&(n?.(`Waiting for project provisioning (attempt ${i+1})...`),await Xet(5e3));const r=await fetch(`${xM}/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 ett(e,t){const n=jG.GOOGLE_CLOUD_PROJECT||jG.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(`${xM}/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(Yet(p))a={currentTier:{id:Ket}};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=Zet(a.allowedTiers)?.id??E9;if(c!==E9&&!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 l={tierId:c,metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}};c!==E9&&n&&(l.cloudaicompanionProject=n,l.metadata.duetProject=n);const s=await fetch(`${xM}/v1internal:onboardUser`,{method:"POST",headers:i,body:JSON.stringify(l)});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 Qet(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 ttt(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 ntt(e,t){const n=await fetch(dve,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:_M,client_secret:uve,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 rtt(e,t,n){const{verifier:i,challenge:r}=await Pk();t?.("Starting local server for OAuth callback...");const a=await Jet();let o;try{const c=new URLSearchParams({client_id:_M,response_type:"code",redirect_uri:LG,scope:Get.join(" "),code_challenge:r,code_challenge_method:"S256",state:i,access_type:"offline",prompt:"consent"}),l=`${Het}?${c.toString()}`;if(e({url:l,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");o=v.code}else if(m){const b=FG(m);if(b.state&&b.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");o=b.code}if(!o){if(await y,g)throw g;if(m){const b=FG(m);if(b.state&&b.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");o=b.code}}}else{const m=await a.waitForCode();if(m?.code){if(m.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");o=m.code}}if(!o)throw new Error("No authorization code received");t?.("Exchanging authorization code for tokens...");const s=await fetch(dve,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:_M,client_secret:uve,code:o,grant_type:"authorization_code",redirect_uri:LG,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 ttt(u.access_token),p=await ett(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 itt={id:"google-gemini-cli",name:"Google Cloud Code Assist (Gemini CLI)",usesCallbackServer:!0,async login(e){return rtt(e.onAuth,e.onProgress,e.onManualCodeInput)},async refreshToken(e){const t=e;if(!t.projectId)throw new Error("Google Cloud credentials missing projectId");return ntt(t.refresh,t.projectId)},getApiKey(e){const t=e;return JSON.stringify({token:t.access,projectId:t.projectId})}};let SM=null,TM=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(Tn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{SM=e.randomBytes}),Tn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{TM=e}));const E$="app_EMoamEEZ73f0CkXaXp7hrann",att="https://auth.openai.com/oauth/authorize",pve="https://auth.openai.com/oauth/token",fve="http://localhost:1455/auth/callback",stt="openid profile email offline_access",ott="https://api.openai.com/auth",ltt=`<!doctype html>
870
+ `)}}}const aet="responses_websockets=2026-02-06",set=300*1e3,Ky=new Map;function oet(){const e=globalThis.WebSocket;return typeof e!="function"?null:e}function cet(e){const t={};for(const[n,i]of e.entries())t[n]=i;return t}function uet(e){const t=e.readyState;return typeof t=="number"?t:void 0}function vT(e){const t=uet(e);return t===void 0||t===1}function Xy(e,t=1e3,n="done"){try{e.close(t,n)}catch{}}function PG(e,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{t.busy||(Xy(t.socket,1e3,"idle_timeout"),Ky.delete(e))},set)}async function T9(e,t,n){const i=oet();if(!i)throw new Error("WebSocket transport is not available in this runtime");const r=cet(t);return r["OpenAI-Beta"]=aet,new Promise((a,o)=>{let c=!1,l;try{l=new i(e,{headers:r})}catch(h){o(h instanceof Error?h:new Error(String(h)));return}const s=()=>{c||(c=!0,f(),a(l))},u=h=>{c||(c=!0,f(),o(Zye(h)))},d=h=>{c||(c=!0,f(),o(Yye(h)))},p=()=>{c||(c=!0,f(),l.close(1e3,"aborted"),o(new Error("Request was aborted")))},f=()=>{l.removeEventListener("open",s),l.removeEventListener("error",u),l.removeEventListener("close",d),n?.removeEventListener("abort",p)};l.addEventListener("open",s),l.addEventListener("error",u),l.addEventListener("close",d),n?.addEventListener("abort",p)})}async function det(e,t,n,i){if(!n){const c=await T9(e,t,i);return{socket:c,release:({keep:l}={})=>{if(l===!1){Xy(c);return}Xy(c)}}}const r=Ky.get(n);if(r){if(r.idleTimer&&(clearTimeout(r.idleTimer),r.idleTimer=void 0),!r.busy&&vT(r.socket))return r.busy=!0,{socket:r.socket,release:({keep:c}={})=>{if(!c||!vT(r.socket)){Xy(r.socket),Ky.delete(n);return}r.busy=!1,PG(n,r)}};if(r.busy){const c=await T9(e,t,i);return{socket:c,release:()=>{Xy(c)}}}vT(r.socket)||(Xy(r.socket),Ky.delete(n))}const a=await T9(e,t,i),o={socket:a,busy:!0};return Ky.set(n,o),{socket:a,release:({keep:c}={})=>{if(!c||!vT(o.socket)){Xy(o.socket),o.idleTimer&&clearTimeout(o.idleTimer),Ky.get(n)===o&&Ky.delete(n);return}o.busy=!1,PG(n,o)}}}function Zye(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 Yye(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 pet(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*fet(e,t){const n=[];let i=null,r=!1,a=null,o=!1;const c=()=>{if(!i)return;const p=i;i=null,p()},l=p=>{(async()=>{if(!p||typeof p!="object"||!("data"in p))return;const f=await pet(p.data);if(f)try{const h=JSON.parse(f),m=typeof h.type=="string"?h.type:"";(m==="response.completed"||m==="response.done")&&(o=!0,r=!0),n.push(h),c()}catch{}})()},s=p=>{a=Zye(p),r=!0,c()},u=p=>{if(o){r=!0,c();return}a||(a=Yye(p)),r=!0,c()},d=()=>{a=new Error("Request was aborted"),r=!0,c()};e.addEventListener("message",l),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(!o)throw new Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",l),e.removeEventListener("error",s),e.removeEventListener("close",u),t?.removeEventListener("abort",d)}}async function het(e,t,n,i,r,a,o,c){const{socket:l,release:s}=await det(e,n,c?.sessionId,c?.signal);let u=!0;try{l.send(JSON.stringify({type:"response.create",...t})),o(),r.push({type:"start",partial:i}),await dk(Xye(fet(l,c?.signal)),i,r,a),c?.signal?.aborted&&(u=!1)}catch(d){throw u=!1,d}finally{s({keep:u})}}async function met(e){const t=await e.text();let n=t||e.statusText||"Request failed",i;try{const a=JSON.parse(t)?.error;if(a){const o=a.code||a.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(o)||e.status===429){const c=a.plan_type?` (${a.plan_type.toLowerCase()} plan)`:"",l=a.resets_at?Math.max(0,Math.round((a.resets_at*1e3-Date.now())/6e4)):void 0,s=l!==void 0?` Try again in ~${l} min.`:"";i=`You have hit your ChatGPT usage limit${c}.${s}`.trim()}n=a.message||i||n}}catch{}return{message:n,friendlyMessage:i}}function get(e){try{const t=e.split(".");if(t.length!==3)throw new Error("Invalid token");const i=JSON.parse(atob(t[1]))?.[JQe]?.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 yet(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 o=px?`pi (${px.platform()} ${px.release()}; ${px.arch()})`:"pi (browser)";a.set("User-Agent",o),a.set("accept","text/event-stream"),a.set("content-type","application/json");for(const[c,l]of Object.entries(t||{}))a.set(c,l);return r&&a.set("session_id",r),a}function vet(){Lo({api:"anthropic-messages",stream:Ix,streamSimple:Wpe}),Lo({api:"openai-completions",stream:Eme,streamSimple:CFe}),Lo({api:"openai-responses",stream:Ame,streamSimple:jFe}),Lo({api:"azure-openai-responses",stream:Ahe,streamSimple:dMe}),Lo({api:"openai-codex-responses",stream:Jye,streamSimple:YQe}),Lo({api:"google-generative-ai",stream:hE,streamSimple:GLe}),Lo({api:"google-gemini-cli",stream:mE,streamSimple:cFe}),Lo({api:"google-vertex",stream:gE,streamSimple:mFe}),Lo({api:"bedrock-converse-stream",stream:dx,streamSimple:MQe})}vet();typeof process<"u"&&process.versions?.node&&Tn(()=>import("./index-BQQ3oExA.js").then(e=>e.i),__vite__mapDeps([5,3,4])).then(e=>{const{EnvHttpProxyAgent:t,setGlobalDispatcher:n}=e;n(new t)});function bet(e){const t=mP(e);if(!t)throw new Error(`No API provider registered for api: ${e}`);return t}function Qye(e,t,n){return bet(e.api).streamSimple(e,t,n)}function MG(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function Pk(){const e=new Uint8Array(32);crypto.getRandomValues(e);const t=MG(e),i=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",i),a=MG(new Uint8Array(r));return{verifier:t,challenge:a}}const wet=e=>atob(e),yM=wet("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl"),_et="https://claude.ai/oauth/authorize",eve="https://console.anthropic.com/v1/oauth/token",NG="https://console.anthropic.com/oauth/code/callback",xet="org:create_api_key user:profile user:inference";async function Tet(e,t){const{verifier:n,challenge:i}=await Pk(),r=new URLSearchParams({code:"true",client_id:yM,response_type:"code",redirect_uri:NG,scope:xet,code_challenge:i,code_challenge_method:"S256",state:n}),a=`${_et}?${r.toString()}`;e(a);const c=(await t()).split("#"),l=c[0],s=c[1],u=await fetch(eve,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:yM,code:l,state:s,redirect_uri:NG,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 Cet(e){const t=await fetch(eve,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:yM,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 Eet={id:"anthropic",name:"Anthropic (Claude Pro/Max)",async login(e){return Tet(t=>e.onAuth({url:t}),()=>e.onPrompt({message:"Paste the authorization code:"}))},async refreshToken(e){return Cet(e.refresh)},getApiKey(e){return e.access}},Aet=e=>atob(e),tve=Aet("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),nve={"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 rve(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 T$(e){return{deviceCodeUrl:`https://${e}/login/device/code`,accessTokenUrl:`https://${e}/login/oauth/access_token`,copilotTokenUrl:`https://api.${e}/copilot_internal/v2/token`}}function ket(e){const t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,"api.")}`:null}function ive(e,t){if(e){const n=ket(e);if(n)return n}return t?`https://copilot-api.${t}`:"https://api.individual.githubcopilot.com"}async function C$(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 Ret(e){const t=T$(e),n=await C$(t.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"GitHubCopilotChat/0.35.0"},body:JSON.stringify({client_id:tve,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,o=n.interval,c=n.expires_in;if(typeof i!="string"||typeof r!="string"||typeof a!="string"||typeof o!="number"||typeof c!="number")throw new Error("Invalid device code response fields");return{device_code:i,user_code:r,verification_uri:a,interval:o,expires_in:c}}function C9(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 Oet(e,t,n,i,r){const a=T$(e),o=Date.now()+i*1e3;let c=Math.max(1e3,Math.floor(n*1e3));for(;Date.now()<o;){if(r?.aborted)throw new Error("Login cancelled");const l=await C$(a.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"GitHubCopilotChat/0.35.0"},body:JSON.stringify({client_id:tve,device_code:t,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(l&&typeof l=="object"&&typeof l.access_token=="string")return l.access_token;if(l&&typeof l=="object"&&typeof l.error=="string"){const s=l.error;if(s==="authorization_pending"){await C9(c,r);continue}if(s==="slow_down"){c+=5e3,await C9(c,r);continue}throw new Error(`Device flow failed: ${s}`)}await C9(c,r)}throw new Error("Device flow timed out")}async function ave(e,t){const i=T$(t||"github.com"),r=await C$(i.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`,...nve}});if(!r||typeof r!="object")throw new Error("Invalid Copilot token response");const a=r.token,o=r.expires_at;if(typeof a!="string"||typeof o!="number")throw new Error("Invalid Copilot token response fields");return{refresh:e,access:a,expires:o*1e3-300*1e3,enterpriseUrl:t}}async function Iet(e,t,n){const r=`${ive(e,n)}/models/${t}/policy`;try{return(await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...nve,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})})).ok}catch{return!1}}async function Pet(e,t,n){const i=b3("github-copilot");await Promise.all(i.map(async r=>{await Iet(e,r.id,t)}))}async function Met(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=rve(t);if(n&&!i)throw new Error("Invalid GitHub Enterprise URL/domain");const r=i||"github.com",a=await Ret(r);e.onAuth(a.verification_uri,`Enter code: ${a.user_code}`);const o=await Oet(r,a.device_code,a.interval,a.expires_in,e.signal),c=await ave(o,i??void 0);return e.onProgress?.("Enabling models..."),await Pet(c.access,i??void 0),c}const Net={id:"github-copilot",name:"GitHub Copilot",async login(e){return Met({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 ave(t.refresh,t.enterpriseUrl)},getApiKey(e){return e.access},modifyModels(e,t){const n=t,i=n.enterpriseUrl?rve(n.enterpriseUrl)??void 0:void 0,r=ive(n.access,i);return e.map(a=>a.provider==="github-copilot"?{...a,baseUrl:r}:a)}};let fx=null,vM=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(vM=Tn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{fx=e.createServer}));const sve=e=>atob(e),bM=sve("MTA3MTAwNjA2MDU5MS10bWhzc2luMmgyMWxjcmUyMzV2dG9sb2poNGc0MDNlcC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbQ=="),ove=sve("R09DU1BYLUs1OEZXUjQ4NkxkTEoxbUxCOHNYQzR6NnFEQWY="),$G="http://localhost:51121/oauth-callback",$et=["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"],Det="https://accounts.google.com/o/oauth2/v2/auth",lve="https://oauth2.googleapis.com/token",jet="rising-fact-p41fc";async function Let(){if(fx||(vM&&await vM,fx))return fx;throw new Error("Antigravity OAuth is only available in Node.js environments")}async function Fet(){const e=await Let();return new Promise((t,n)=>{let i=null,r=!1;const a=e((o,c)=>{const l=new URL(o.url||"","http://localhost:51121");if(l.pathname==="/oauth-callback"){const s=l.searchParams.get("code"),u=l.searchParams.get("state"),d=l.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",o=>{n(o)}),a.listen(51121,"127.0.0.1",()=>{t({server:a,cancelWait:()=>{r=!0},waitForCode:async()=>{const o=()=>new Promise(c=>setTimeout(c,100));for(;!i&&!r;)await o();return i}})})})}function DG(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 Uet(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 o=await a.json();if(typeof o.cloudaicompanionProject=="string"&&o.cloudaicompanionProject)return o.cloudaicompanionProject;if(o.cloudaicompanionProject&&typeof o.cloudaicompanionProject=="object"&&o.cloudaicompanionProject.id)return o.cloudaicompanionProject.id}}catch{}return t?.("Using default project..."),jet}async function qet(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 Bet(e,t){const n=await fetch(lve,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:bM,client_secret:ove,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 Wet(e,t,n){const{verifier:i,challenge:r}=await Pk();t?.("Starting local server for OAuth callback...");const a=await Fet();let o;try{const c=new URLSearchParams({client_id:bM,response_type:"code",redirect_uri:$G,scope:$et.join(" "),code_challenge:r,code_challenge_method:"S256",state:i,access_type:"offline",prompt:"consent"}),l=`${Det}?${c.toString()}`;if(e({url:l,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");o=v.code}else if(m){const b=DG(m);if(b.state&&b.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");o=b.code}if(!o){if(await y,g)throw g;if(m){const b=DG(m);if(b.state&&b.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");o=b.code}}}else{const m=await a.waitForCode();if(m?.code){if(m.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");o=m.code}}if(!o)throw new Error("No authorization code received");t?.("Exchanging authorization code for tokens...");const s=await fetch(lve,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:bM,client_secret:ove,code:o,grant_type:"authorization_code",redirect_uri:$G,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 qet(u.access_token),p=await Uet(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 zet={id:"google-antigravity",name:"Antigravity (Gemini 3, Claude, GPT-OSS)",usesCallbackServer:!0,async login(e){return Wet(e.onAuth,e.onProgress,e.onManualCodeInput)},async refreshToken(e){const t=e;if(!t.projectId)throw new Error("Antigravity credentials missing projectId");return Bet(t.refresh,t.projectId)},getApiKey(e){const t=e;return JSON.stringify({token:t.access,projectId:t.projectId})}};var jG={};let hx=null,wM=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(wM=Tn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{hx=e.createServer}));const cve=e=>atob(e),_M=cve("NjgxMjU1ODA5Mzk1LW9vOGZ0Mm9wcmRybnA5ZTNhcWY2YXYzaG1kaWIxMzVqLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29t"),uve=cve("R09DU1BYLTR1SGdNUG0tMW83U2stZ2VWNkN1NWNsWEZzeGw="),LG="http://localhost:8085/oauth2callback",Get=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile"],Het="https://accounts.google.com/o/oauth2/v2/auth",dve="https://oauth2.googleapis.com/token",xM="https://cloudcode-pa.googleapis.com";async function Vet(){if(hx||(wM&&await wM,hx))return hx;throw new Error("Gemini CLI OAuth is only available in Node.js environments")}async function Jet(){const e=await Vet();return new Promise((t,n)=>{let i=null,r=!1;const a=e((o,c)=>{const l=new URL(o.url||"","http://localhost:8085");if(l.pathname==="/oauth2callback"){const s=l.searchParams.get("code"),u=l.searchParams.get("state"),d=l.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",o=>{n(o)}),a.listen(8085,"127.0.0.1",()=>{t({server:a,cancelWait:()=>{r=!0},waitForCode:async()=>{const o=()=>new Promise(c=>setTimeout(c,100));for(;!i&&!r;)await o();return i}})})})}function FG(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 E9="free-tier",UG="legacy-tier",Ket="standard-tier";function Xet(e){return new Promise(t=>setTimeout(t,e))}function Zet(e){return!e||e.length===0?{id:UG}:e.find(n=>n.isDefault)??{id:UG}}function Yet(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 Qet(e,t,n){let i=0;for(;;){i>0&&(n?.(`Waiting for project provisioning (attempt ${i+1})...`),await Xet(5e3));const r=await fetch(`${xM}/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 ett(e,t){const n=jG.GOOGLE_CLOUD_PROJECT||jG.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(`${xM}/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(Yet(p))a={currentTier:{id:Ket}};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=Zet(a.allowedTiers)?.id??E9;if(c!==E9&&!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 l={tierId:c,metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}};c!==E9&&n&&(l.cloudaicompanionProject=n,l.metadata.duetProject=n);const s=await fetch(`${xM}/v1internal:onboardUser`,{method:"POST",headers:i,body:JSON.stringify(l)});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 Qet(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 ttt(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 ntt(e,t){const n=await fetch(dve,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:_M,client_secret:uve,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 rtt(e,t,n){const{verifier:i,challenge:r}=await Pk();t?.("Starting local server for OAuth callback...");const a=await Jet();let o;try{const c=new URLSearchParams({client_id:_M,response_type:"code",redirect_uri:LG,scope:Get.join(" "),code_challenge:r,code_challenge_method:"S256",state:i,access_type:"offline",prompt:"consent"}),l=`${Het}?${c.toString()}`;if(e({url:l,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");o=v.code}else if(m){const b=FG(m);if(b.state&&b.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");o=b.code}if(!o){if(await y,g)throw g;if(m){const b=FG(m);if(b.state&&b.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");o=b.code}}}else{const m=await a.waitForCode();if(m?.code){if(m.state!==i)throw new Error("OAuth state mismatch - possible CSRF attack");o=m.code}}if(!o)throw new Error("No authorization code received");t?.("Exchanging authorization code for tokens...");const s=await fetch(dve,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:_M,client_secret:uve,code:o,grant_type:"authorization_code",redirect_uri:LG,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 ttt(u.access_token),p=await ett(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 itt={id:"google-gemini-cli",name:"Google Cloud Code Assist (Gemini CLI)",usesCallbackServer:!0,async login(e){return rtt(e.onAuth,e.onProgress,e.onManualCodeInput)},async refreshToken(e){const t=e;if(!t.projectId)throw new Error("Google Cloud credentials missing projectId");return ntt(t.refresh,t.projectId)},getApiKey(e){const t=e;return JSON.stringify({token:t.access,projectId:t.projectId})}};let SM=null,TM=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(Tn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{SM=e.randomBytes}),Tn(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(e=>e._),[]).then(e=>{TM=e}));const E$="app_EMoamEEZ73f0CkXaXp7hrann",att="https://auth.openai.com/oauth/authorize",pve="https://auth.openai.com/oauth/token",fve="http://localhost:1455/auth/callback",stt="openid profile email offline_access",ott="https://api.openai.com/auth",ltt=`<!doctype html>
871
871
  <html lang="en">
872
872
  <head>
873
873
  <meta charset="utf-8" />
@@ -3520,7 +3520,7 @@ except SystemExit as exc:
3520
3520
  except BaseException:
3521
3521
  traceback.print_exc()
3522
3522
  __slicc_exit_code = 1
3523
- `;let zI=null,GI=null;const lOe=Object.create(null);class GA extends Error{constructor(t){super(`Process exited with code ${t}`),this.code=t,this.name="NodeExitError"}}function dF(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 n5t(e){const t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function r5t(e,t){return e==="/"?`/${t}`:`${e}/${t}`}function i5t(e){if(/^(https?:\/\/|about:|file:|chrome:)/i.test(e))return!0;try{return new URL(e).protocol.length>0}catch{return!1}}function a5t(e,t){return e==="/"?t.startsWith("/"):t===e||t.startsWith(`${e}/`)}function s5t(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function o5t(e){return e==null?"":e instanceof Uint8Array?`x'${s5t(e)}'`:String(e)}function O8(e){return W8(e)}function HA(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 l5t(e){return e.length===0||e.startsWith("/")?!1:!e.split("/").some(t=>t==="..")}function c5t(e,t){return Dn(`${e}/${t}`)}function Jg(e){if(typeof e=="string")return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}async function u5t(){return zI||(zI=(async()=>{const t=(await Tn(()=>import("./sql-wasm-8C3CnQsV.js").then(i=>i.s),__vite__mapDeps([6,3,4]))).default,n=typeof window>"u"?new URL("../../../node_modules/sql.js/dist/",import.meta.url).toString():Y4t;return t({locateFile:i=>`${n}${i}`})})()),zI}const d5t=typeof chrome<"u"&&!!chrome?.runtime?.id;async function p5t(){return GI||(GI=(async()=>{let e;return typeof window>"u"?e=decodeURIComponent(new URL("/assets/pyodide-D73G_Ygx.mjs",import.meta.url).pathname):d5t?e=chrome.runtime.getURL("pyodide/"):e=Q4t,oOe({indexURL:e,fullStdLib:!1})})()),GI}function f5t(){return{stdout:`usage: node -e <code> [args...]
3523
+ `;let zI=null,GI=null;const lOe=Object.create(null);class GA extends Error{constructor(t){super(`Process exited with code ${t}`),this.code=t,this.name="NodeExitError"}}function dF(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 n5t(e){const t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function r5t(e,t){return e==="/"?`/${t}`:`${e}/${t}`}function i5t(e){if(/^(https?:\/\/|about:|file:|chrome:)/i.test(e))return!0;try{return new URL(e).protocol.length>0}catch{return!1}}function a5t(e,t){return e==="/"?t.startsWith("/"):t===e||t.startsWith(`${e}/`)}function s5t(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function o5t(e){return e==null?"":e instanceof Uint8Array?`x'${s5t(e)}'`:String(e)}function O8(e){return W8(e)}function HA(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 l5t(e){return e.length===0||e.startsWith("/")?!1:!e.split("/").some(t=>t==="..")}function c5t(e,t){return Dn(`${e}/${t}`)}function Jg(e){if(typeof e=="string")return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}async function u5t(){return zI||(zI=(async()=>{const t=(await Tn(()=>import("./sql-wasm-D66sddMs.js").then(i=>i.s),__vite__mapDeps([6,3,4]))).default,n=typeof window>"u"?new URL("../../../node_modules/sql.js/dist/",import.meta.url).toString():Y4t;return t({locateFile:i=>`${n}${i}`})})()),zI}const d5t=typeof chrome<"u"&&!!chrome?.runtime?.id;async function p5t(){return GI||(GI=(async()=>{let e;return typeof window>"u"?e=decodeURIComponent(new URL("/assets/pyodide-D73G_Ygx.mjs",import.meta.url).pathname):d5t?e=chrome.runtime.getURL("pyodide/"):e=Q4t,oOe({indexURL:e,fullStdLib:!1})})()),GI}function f5t(){return{stdout:`usage: node -e <code> [args...]
3524
3524
  `,stderr:"",exitCode:0}}function h5t(){return{stdout:`${e5t}
3525
3525
  `,stderr:"",exitCode:0}}function m5t(){return vr("node",async(e,t)=>{if(e.includes("--help")||e.includes("-h"))return f5t();if(e.includes("--version")||e.includes("-v"))return h5t();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
3526
3526
  `,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}'
@@ -3595,7 +3595,7 @@ ${n}`)(d,u,s,f,h,h.exports,lOe,p),{stdout:a.join(""),stderr:o.join(""),exitCode:
3595
3595
  `,exitCode:1};let s;try{s=await t.fs.readFileBuffer(c)}catch{return{stdout:"",stderr:`open: failed to read: ${o}
3596
3596
  `,exitCode:1}}const u=new Uint8Array(s.byteLength);u.set(s);const d=new Blob([u.buffer],{type:O8(c)}),p=URL.createObjectURL(d),f=document.createElement("a");f.href=p,f.download=dF(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 l=HA(c);window.open(l,"_blank","noopener,noreferrer"),a.push(`opened ${c} → ${l}`)}}return{stdout:a.join(`
3597
3597
  `)+`
3598
- `,stderr:"",exitCode:0}})}let HI=null,VI=null;async function JI(){return HI||(HI=Tn(()=>import("./index-xzVzlu9M.js"),__vite__mapDeps([7,3,4]))),HI}async function b5t(){return VI||(VI=Tn(()=>import("./index-g_Oj1Xd7.js"),[])),VI}function w5t(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 Uue(e){const{range:t,rotation:n}=w5t(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 que(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 o=n;o<=r;o++)a.push(o);return a}function _5t(){return{stdout:`usage: pdftk <input.pdf> <operation> [args...]
3598
+ `,stderr:"",exitCode:0}})}let HI=null,VI=null;async function JI(){return HI||(HI=Tn(()=>import("./index-CJv-O0EK.js"),__vite__mapDeps([7,3,4]))),HI}async function b5t(){return VI||(VI=Tn(()=>import("./index-BVktLK0e.js"),[])),VI}function w5t(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 Uue(e){const{range:t,rotation:n}=w5t(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 que(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 o=n;o<=r;o++)a.push(o);return a}function _5t(){return{stdout:`usage: pdftk <input.pdf> <operation> [args...]
3599
3599
 
3600
3600
  Operations:
3601
3601
  dump_data Print metadata (page count, title, author, etc.)
@@ -4044,13 +4044,13 @@ Hex: ${m}${g}
4044
4044
  `,exitCode:1};await r.rm(c,{recursive:!0})}catch{}const l=`https://api.github.com/repos/${e}/${t}/contents/${n}`,s=await a.request(l);if(s.status!==200)return{stdout:"",stderr:`upskill: ${p3(s,`${e}/${t}/${n}`,a.hasToken)}
4045
4045
  `,exitCode:1};const u=JSON.parse(s.body);await r.mkdir(c,{recursive:!0});async function d(p,f){for(const h of p)if(h.type==="file"&&h.download_url){const m=await a.request(h.download_url,"*/*");if(m.status!==200)throw new Error(p3(m,`${e}/${t}/${h.path}`,a.hasToken));const g=sRe(h.download_url);await r.writeFile(`${f}/${h.name}`,g??m.body)}else if(h.type==="dir"){const m=`https://api.github.com/repos/${e}/${t}/contents/${h.path}`,g=await a.request(m);if(g.status!==200)throw new Error(p3(g,`${e}/${t}/${h.path}`,a.hasToken));const y=JSON.parse(g.body);await r.mkdir(`${f}/${h.name}`,{recursive:!0}),await d(y,`${f}/${h.name}`)}}try{await d(u,c)}catch(p){try{await r.rm(c,{recursive:!0})}catch{}throw p}return await tO(),{stdout:`Installed skill "${i}" from ${e}/${t}
4046
4046
  `,stderr:"",exitCode:0}}catch(c){return{stdout:"",stderr:`upskill: failed to install from GitHub: ${c instanceof Error?c.message:String(c)}
4047
- `,exitCode:1}}}function PIt(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 MIt(e){const t=e.match(/^([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_.-]+)$/);return t?{owner:t[1],repo:t[2]}:null}async function tO(){try{if(typeof window>"u")return;const e=window.__slicc_sprinkleManager;e&&typeof e.openNewAutoOpenSprinkles=="function"&&await e.openNewAutoOpenSprinkles()}catch{}}function NIt(e,t){return vr("upskill",async(n,i)=>{if(n.length===0||n.includes("--help")||n.includes("-h"))return ede();const r=[];let a,o=!1,c=!1,l=!1,s="",u="",d=0;for(;d<n.length;){const h=n[d];if(h==="search"){u=n.slice(d+1).join(" ");break}else if(h==="list"){const g=await(await Tn(()=>import("./index-DxLOLOfX.js"),[])).discoverSkills(e);if(g.length===0)return{stdout:`No skills found in /workspace/skills/
4047
+ `,exitCode:1}}}function PIt(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 MIt(e){const t=e.match(/^([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_.-]+)$/);return t?{owner:t[1],repo:t[2]}:null}async function tO(){try{if(typeof window>"u")return;const e=window.__slicc_sprinkleManager;e&&typeof e.openNewAutoOpenSprinkles=="function"&&await e.openNewAutoOpenSprinkles()}catch{}}function NIt(e,t){return vr("upskill",async(n,i)=>{if(n.length===0||n.includes("--help")||n.includes("-h"))return ede();const r=[];let a,o=!1,c=!1,l=!1,s="",u="",d=0;for(;d<n.length;){const h=n[d];if(h==="search"){u=n.slice(d+1).join(" ");break}else if(h==="list"){const g=await(await Tn(()=>import("./index-BSkuZoNL.js"),[])).discoverSkills(e);if(g.length===0)return{stdout:`No skills found in /workspace/skills/
4048
4048
  `,stderr:"",exitCode:0};let y=`Installed skills:
4049
4049
 
4050
4050
  `;for(const v of g)y+=` ${v.name.padEnd(25)} ${v.manifest.version.padEnd(10)}
4051
4051
  `,v.manifest.description&&(y+=` ${v.manifest.description.slice(0,60)}${v.manifest.description.length>60?"...":""}
4052
4052
  `);return{stdout:y,stderr:"",exitCode:0}}else if(h==="info"||h==="read"){const m=n[d+1];if(!m)return{stdout:"",stderr:`upskill: ${h} requires a skill name
4053
- `,exitCode:1};const g=await Tn(()=>import("./index-DxLOLOfX.js"),[]);if(h==="info"){const y=await g.getSkillInfo(e,m);if(!y)return{stdout:"",stderr:`upskill: skill "${m}" not found
4053
+ `,exitCode:1};const g=await Tn(()=>import("./index-BSkuZoNL.js"),[]);if(h==="info"){const y=await g.getSkillInfo(e,m);if(!y)return{stdout:"",stderr:`upskill: skill "${m}" not found
4054
4054
  `,exitCode:1};let v=`Skill: ${y.manifest.skill}
4055
4055
  `;return v+=`Version: ${y.manifest.version}
4056
4056
  `,v+=`Description: ${y.manifest.description||"(none)"}
@@ -4098,7 +4098,7 @@ Examples:
4098
4098
  skill list
4099
4099
  skill info bluebubbles
4100
4100
  skill read bluebubbles
4101
- `,stderr:"",exitCode:0};const i=t[0],r=await Tn(()=>import("./index-DxLOLOfX.js"),[]);try{switch(i){case"list":{const a=await r.discoverSkills(e);if(a.length===0)return{stdout:`No skills found in /workspace/skills/
4101
+ `,stderr:"",exitCode:0};const i=t[0],r=await Tn(()=>import("./index-BSkuZoNL.js"),[]);try{switch(i){case"list":{const a=await r.discoverSkills(e);if(a.length===0)return{stdout:`No skills found in /workspace/skills/
4102
4102
 
4103
4103
  Install skills with: upskill owner/repo --all
4104
4104
  `,stderr:"",exitCode:0};let o=`Available skills:
@@ -4323,7 +4323,7 @@ addEventListener('message', async (e) => {
4323
4323
  <\/script></head><body></body></html>`;function tPt(e){let t=null,n=null,i=0,r=!1;function a(){r||(r=!0,window.addEventListener("message",s=>{const u=s.data;u&&u.type==="vfs"?l(u):u&&u.type==="fetch_proxy"&&o(u)}))}function o(s){(async()=>{try{const u={method:s.init?.method??"GET",cache:"no-store"};s.init?.headers&&(u.headers=s.init.headers),s.init?.body&&!["GET","HEAD"].includes(u.method)&&(u.body=s.init.body);const d=await fetch(s.url,u),p=await d.arrayBuffer(),f={};d.headers.forEach((h,m)=>{f[m]=h}),t?.contentWindow?.postMessage({type:"fetch_proxy_response",id:s.id,status:d.status,statusText:d.statusText,headers:f,body:new Uint8Array(p)},"*")}catch(u){const d=u instanceof Error?u.message:String(u);G_.error("Fetch proxy error",{url:s.url,error:d}),t?.contentWindow?.postMessage({type:"fetch_proxy_response",id:s.id,error:d},"*")}})()}function c(){if(n)return n;if(t=document.createElement("iframe"),t.style.display="none",t.dataset.jsTool="true",typeof chrome<"u"&&!!chrome?.runtime?.id)n=new Promise(u=>{t.addEventListener("load",()=>{G_.debug("Sandbox iframe loaded"),u(t)},{once:!0}),t.src=chrome.runtime.getURL("sandbox.html"),document.body.appendChild(t)});else{t.sandbox.add("allow-scripts"),t.sandbox.add("allow-same-origin"),document.body.appendChild(t);const u=t.contentDocument;u.open(),u.write(ePt),u.close(),n=Promise.resolve(t)}return a(),n}function l(s){(async()=>{try{let u;switch(s.op){case"readFile":u=await e.readFile(s.args[0]);break;case"readFileBinary":{const d=await e.readFile(s.args[0],{encoding:"binary"});u=d instanceof Uint8Array?d:new TextEncoder().encode(d);break}case"writeFile":await e.writeFile(s.args[0],s.args[1]),u=!0;break;case"writeFileBinary":await e.writeFile(s.args[0],s.binaryData??new Uint8Array),u=!0;break;case"readDir":u=(await e.readDir(s.args[0])).map(d=>d.name);break;case"exists":try{await e.stat(s.args[0]),u=!0}catch{u=!1}break;case"stat":{const d=await e.stat(s.args[0]);u={isDirectory:d.type==="directory",isFile:d.type==="file",size:d.size};break}case"mkdir":await e.mkdir(s.args[0],{recursive:!0}),u=!0;break;case"rm":await e.rm(s.args[0],{recursive:!0}),u=!0;break}t?.contentWindow?.postMessage({type:"vfs_response",id:s.id,result:u},"*")}catch(u){const d=u instanceof Error?u.message:String(u);G_.error("VFS bridge error",{op:s.op,path:s.args[0],error:d}),t?.contentWindow?.postMessage({type:"vfs_response",id:s.id,error:d},"*")}})()}return{name:"javascript",description:'Execute JavaScript code in a persistent sandboxed runtime. Variables and functions persist across calls (same iframe context). VFS bridge: fs.readFile(path), fs.readFileBinary(path) → Uint8Array, fs.writeFile(path, content), fs.writeFileBinary(path, uint8Array), fs.readDir(path), fs.exists(path), fs.fetchToFile(url, path) — all async. Use fs.readFileBinary() to load binary files (images, etc.) as Uint8Array for canvas/Blob operations. fs.fetchToFile(url, path) downloads any URL and saves binary content to the VFS (best way to download files). Top-level await is supported. Console output (log/error/warn) is captured. The return value of the last expression is captured if you use "return <expr>". Has access to browser APIs (fetch, URL, JSON, TextEncoder, etc.). fetch() works for cross-origin URLs (proxied through the CLI server).',inputSchema:{type:"object",properties:{code:{type:"string",description:"JavaScript code to execute. Runs inside an async function — use await freely, use return to produce a result."},timeout:{type:"number",description:"Execution timeout in milliseconds. Default: 30000."}},required:["code"]},async execute(s){const u=s.code,d=s.timeout??3e4,p=`exec-${++i}`;G_.debug("Execute JS",{codeLength:u.length,timeout:d});try{const f=await c(),h=await new Promise((g,y)=>{const v=setTimeout(()=>{w(),y(new Error(`JavaScript execution timed out after ${d}ms`))},d);function b(_){const T=_.data;!T||!T.type||T.type==="exec_result"&&T.id===p&&(w(),g(T))}function w(){clearTimeout(v),window.removeEventListener("message",b)}window.addEventListener("message",b),f.contentWindow.postMessage({type:"exec",id:p,code:u},"*")});let m="";return h.logs.length>0&&(m+=h.logs.join(`
4324
4324
  `)),h.error?(m&&(m+=`
4325
4325
  `),m+=`Error: ${h.error}`,{content:m||"JavaScript error",isError:!0}):(h.result!==void 0&&(m&&(m+=`
4326
- `),m+=h.result),{content:m||"(no output)"})}catch(f){const h=f instanceof Error?f.message:String(f);return G_.error("JS execution error",{error:h}),{content:`JavaScript error: ${h}`,isError:!0}}}}}const nPt='# sliccy\n\nYou are a helpful coding assistant running inside SLICC (Self-Licking Ice Cream Cone) — a browser-based claw.\n\n## Ice Cream Vocabulary\n\n- **Cone**: That\'s you (sliccy). The main agent. You talk to the human, orchestrate scoops, and have full filesystem access.\n- **Scoops**: Isolated sub-agents you can create (`scoop_scoop`), feed instructions (`feed_scoop`), or remove (`drop_scoop`). Each has its own sandboxed filesystem and shell.\n- **Sprinkles**: Persistent UI panels (`.shtml` files in `/shared/sprinkles/`). Created by scoops, outlive scoops, managed via the `sprinkle` shell command.\n- **Licks**: External events (webhooks, cron tasks, sprinkle interactions) that trigger scoops without human prompting. Set up via `webhook` and `crontask` shell commands (both work in CLI and extension modes). Sprinkle licks route to the cone. Untargeted cron/webhook events (no --scoop) route to the cone by default.\n- **Floats**: The runtime you\'re sitting in — either a CLI server, a Chrome extension, or (eventually) a cloud container.\n\n## Communication Style\n\nWrite like a professional tool, not a chatbot. No emoji in headings or labels — use plain text. Prefer concise prose over long bullet lists. When reporting findings (audits, analysis, status), lead with a brief summary sentence, then use structured sections only if detail is needed. For sprinkles, follow `/workspace/skills/sprinkles/style-guide.md` (run `read_file /workspace/skills/sprinkles/style-guide.md` for the full style guide and component reference).\n\n## Principles\n\n- Prefer shell commands over dedicated tools. You have: `read_file`, `write_file`, `edit_file`, `bash`, `javascript`. Browser automation goes through `playwright-cli` / `playwright` / `puppeteer` via bash, and code/file search should use shell commands like `rg`, `grep`, and `find` through `bash`.\n- Whatever the browser can do, it should do. State lives in IndexedDB, logic runs client-side.\n- New capabilities should be skills (SKILL.md files), not hardcoded features.\n- **The scoops do the heavy lifting. The cone orchestrates and synthesizes.**\n\n## Delegation: Default to Scoops\n\n**Before starting any non-trivial task yourself, ask: can this be parallelized?**\n\nDelegate to scoops when:\n- The task involves **multiple independent sources** (e.g. scraping 3 websites → 3 scoops)\n- The task is **time-consuming** and doesn\'t require your direct oversight at each step\n- The work can be expressed as a **clear, self-contained brief** to hand off\n\nDo it yourself when:\n- It\'s a **single quick lookup** (one page, one API call)\n- You need to **adapt in real-time** based on what you find (navigating broken URLs, etc.)\n- The overhead of spawning scoops exceeds the benefit\n\n**The default should be delegation, not "just do it".** Pause before starting research, scraping, or multi-step tasks and sketch out whether scoops fit. Even if a task feels manageable, parallel scoops almost always finish faster.\n\nWhen synthesizing scoop results, *that\'s* your job — pull everything together, resolve conflicts, make the final recommendation.\n\n## Scoop Lifecycle: Clean Up After Yourself\n\n**Drop scoops when their job is done** — but **NEVER drop a scoop that owns a sprinkle**. Dropping a sprinkle scoop destroys its context, so follow-up requests and lick events cannot be handled.\n\nDrop a scoop when:\n- It has **completed its task** and results have been synthesized\n- It is **stuck or misbehaving** (drop and re-spawn with a better brief)\n\n**NEVER** drop a scoop when:\n- **It owns an open sprinkle** — the scoop must stay alive for the lifetime of the sprinkle\n- It is running a **recurring or long-running task** (e.g. watching a feed, handling webhooks)\n- Work is **still in progress** — dropping mid-task loses all context\n\n## Browser Tab Hygiene\n\n**Close tabs when you\'re done with them.** Tabs accumulate fast — every `playwright-cli open` or `tab-new` call opens a persistent tab that stays open unless you close it.\n\nRules:\n- **Close research/scraping tabs** immediately after extracting the data you need. Use `playwright-cli close` for the current tab or `playwright-cli tab-close <index>` for a specific tab.\n- **Never leave more than ~5 tabs open** beyond the user\'s own tabs and any app tabs you\'re actively serving.\n- **Scoops must close their own tabs** when finished. Include this instruction in every scoop brief that involves browser use: *"Close each tab with `playwright-cli close` or `playwright-cli tab-close <index>` as soon as you\'ve extracted what you need."*\n- **Audit tabs periodically**: if you notice tab count growing, run `playwright-cli tab-list` and close stale ones with `playwright-cli tab-close <index>`.\n- The **preview/serve tab** for a delivered app can stay open — that\'s intentional. Everything else is transient.\n\nTo close the current tab: `playwright-cli close`. To close a specific tab: `playwright-cli tab-close <index>`.\n\n## What You Can Do\n\n- Read and write files in your virtual workspace\n- Run bash commands in a sandboxed shell\n- Automate browser interactions (screenshots, navigation, clicking, JS eval)\n- Delegate work to scoops and react when they finish\n- Respond to licks (webhooks, scheduled tasks)\n\n## Viewing Pages and Images\n\n**What you CAN see:**\n- **`open --view <path>`** (or `-v`) — reads an image from VFS and returns it so you can see it. Works with PNG, JPEG, GIF, WebP, SVG.\n- **`playwright-cli screenshot`** + **`open --view <path>`** — take a screenshot of the current browser tab to file, then view it. Example: `playwright-cli screenshot --filename=/tmp/shot.png && open --view /tmp/shot.png`\n- **`screencapture`** — capture the user\'s actual screen (desktop, window, or tab) via browser screen sharing API. Use `screencapture --view screenshot.png` to capture and see what\'s on their screen. The user will be prompted to select what to share.\n- **`playwright-cli snapshot`** — returns an accessibility tree (text). Use this to verify page content without vision, or as a required step before `screenshot`.\n\n**What only the human sees:**\n- **`serve <dir>`** — opens a VFS app directory in a browser tab, defaulting to `index.html`.\n- **`open <path>`** (no flags) — opens VFS files in a browser tab.\n- **`imgcat <path>`** — displays an image in the terminal preview.\n\n**Workflow to verify a page you created:**\n1. `serve /workspace/app` — opens the app directory in a tab (human can see it)\n2. `playwright-cli tab-list` — find the tab by matching the preview URL from step 1\n3. `playwright-cli tab-select <index>` — target that tab\n4. `playwright-cli snapshot` — required before screenshot; also gives you text content\n5. `playwright-cli screenshot --filename=/tmp/shot.png` — save screenshot to file\n6. `open --view /tmp/shot.png` — now you can see it\n\n**Understanding `tab-list` markers:**\n- `→` = playwright\'s current target (the tab your commands operate on)\n- `*` = the user\'s active/focused tab in Chrome\n- These can differ! If the user switches tabs in Chrome, `*` moves but `→` stays. Use `tab-select` to follow the user\'s active tab when needed.\n\n**Remote targets (tray mode):**\nWhen connected to a tray, `playwright-cli tab-list` shows browser tabs from all connected SLICC instances. Remote targets appear with a `[remote:runtimeId]` annotation. Use `playwright-cli tab-select <index>` to target a remote tab, then use the usual commands (`snapshot`, `screenshot`, `click`, `fill`, etc.) — CDP commands are routed transparently over the tray data channel to the runtime that owns the tab. To open a new tab on a specific remote runtime, use `playwright-cli open <url> --runtime=<runtimeId>` or `playwright-cli tab-new <url> --runtime=<runtimeId>`.\n\n**Do NOT:**\n- Try to `read_file` on a PNG, `base64` encode it, or `convert` it to view images\n- Run `imgcat` or `cat` on screenshots expecting to see them yourself\n- Open a screenshot with `open` and then try to screenshot *that* tab\n- Use `eval` to check which tab is active — use `tab-list` and look for the `*` marker instead\n\n## Filesystem\n\nThe virtual filesystem is stored in IndexedDB and survives tab closes and page refreshes. To keep work on disk, mount a local directory:\n\n```\nmount /workspace/myproject\n```\n\n## Shell Commands\n\nType `commands` in the terminal to see all available commands. Key commands:\n\n- **skill list/install/uninstall** — Manage skills from /workspace/skills/\n- **upskill** — Install skills from GitHub (`upskill owner/repo`) or ClawHub (`upskill clawhub:name`)\n- **webhook/crontask** — Set up licks (external event triggers)\n- **sprinkle** — Manage sprinkles: `sprinkle list`, `sprinkle open <name>`, `sprinkle close <name>`, `sprinkle send <name> \'<json>\'` (push data), `sprinkle chat \'<html>\'` (inline chat UI)\n- **oauth-token** — Get an OAuth access token for a provider (`oauth-token adobe`); auto-triggers login if no valid token exists. Use in shell: `curl -H "Authorization: Bearer $(oauth-token adobe)" https://api.example.com`\n- **aem** — AEM Edge Delivery Services: `aem list`, `aem get`, `aem put`, `aem preview`, `aem publish`, `aem upload`. Accepts EDS URLs (`https://main--repo--org.aem.page/path`). Auth via `oauth-token adobe`. Run `aem help` for details.\n- **git** — Full git support (clone, commit, push, pull)\n- **node -e / python3 -c** — Execute JavaScript or Python. JSH/node scripts have access to `exec(command)` to run shell commands: `const r = await exec(\'oauth-token adobe\'); const token = r.stdout.trim();`\n- **serve <dir>** — Open a VFS app directory in a new browser tab. Defaults to `index.html`; use `--entry` to override the entry file.\n- **open <path|url>** — Open a URL or single VFS file in a new browser tab. Use `open --view` when you need to see an image inline. `.shtml` files are opened as sprinkles instead of browser tabs.\n- **host** — Print the current leader tray status plus `join_url`. When this runtime is leader, shows the join URL and connected followers. Use `host reset` to disconnect all followers and create a fresh tray session with a new join URL (leader only).\n- **pbcopy / pbpaste** — Clipboard commands. `echo hello | pbcopy` copies stdin to clipboard, `pbpaste` outputs clipboard contents. Uses `navigator.clipboard` API.\n- **xclip / xsel** — Clipboard commands that auto-detect direction: `echo hello | xclip` copies (stdin present), `xclip` alone pastes (no stdin).\n- **say** — Text-to-speech using Web Speech API. `say hello world`, `say -v Samantha hello` (voice selection), `say -r 1.5 fast speech` (rate 0.1-10), `say --list` (list voices).\n- **afplay** — Play audio files using Web Audio API. `afplay /path/to/audio.mp3`, `afplay -v 0.5 file.wav` (volume 0-1), `afplay -r 1.5 file.mp3` (rate 0.25-4).\n- **chime** — Play a notification chime sound. Alias for `afplay /shared/sounds/chime.mp3`.\n- **playwright-cli** — Browser automation (built-in, no SKILL.md lookup needed). Key subcommands: `tab-list`, `tab-select <index>`, `snapshot`, `screenshot [--filename=<path>]`, `open <url> [--runtime=<id>]`, `click <ref>`, `fill <ref> "text"`, `close`. Use `--runtime` with `open`/`tab-new` to open a tab on a remote tray runtime. Run `playwright-cli --help` for full list.\n- **rsync** — Sync files between local VFS and a remote tray runtime. Push: `rsync /local runtime-id:/remote`. Pull: `rsync runtime-id:/remote /local`. Flags: `--dry-run` (preview), `--delete` (remove dest files not in source), `--verbose` (per-file detail). Requires an active tray connection.\n- **teleport** — Teleport browser cookies from a remote tray runtime to the local browser. Enables seamless authentication transfer between SLICC instances in a tray. Usage: `teleport` (auto-select best follower), `teleport <runtime-id>` (target specific runtime), `teleport --list` (show available runtimes), `teleport --url <url>` (open URL on follower for interactive auth). When `--url` is provided, the follower opens a browser tab for the human to complete login; cookies are captured after auth completion (hostname redirect) or a 2-minute timeout. Page reloads by default after applying cookies; use `--no-reload` to skip.\n\n### Browser Shell Scripts (.bsh)\n\n`.bsh` files are JavaScript scripts that auto-execute when the browser navigates to a matching URL. Place them in `/workspace/` or `/shared/`.\n\n- **Filename = hostname pattern**: `-.okta.com.bsh` matches `*.okta.com`, `login.okta.com.bsh` matches exactly `login.okta.com`\n- **`// @match` directive**: Add in first 10 lines to restrict to specific URL patterns (e.g. `// @match *://login.okta.com/app/*`)\n- Same execution engine as `.jsh` — access `process`, `console`, `fs`, `exec()` globals\n- The BshWatchdog monitors browser navigations and runs matching scripts automatically\n\n## Inline Cards\n\nUse ` ```shtml ` fenced code blocks to show interactive cards inline in chat.\nCards render after your response completes. Only `slicc.lick()` is available (no state, no readFile).\n\nUse for: choices, confirmations, progress, quick actions.\nUse panel sprinkles for: dashboards, reports, editors, persistent UIs.\n\nExample:\n\n ```shtml\n <div class="sprinkle-action-card">\n <div class="sprinkle-action-card__header">\n Deploy to production?\n <span class="sprinkle-badge sprinkle-badge--notice">staging passed</span>\n </div>\n <div class="sprinkle-action-card__body">Branch main, commit abc123</div>\n <div class="sprinkle-action-card__actions">\n <button class="sprinkle-btn sprinkle-btn--secondary" onclick="slicc.lick(\'cancel\')">Cancel</button>\n <button class="sprinkle-btn sprinkle-btn--primary" onclick="slicc.lick({action:\'deploy\',data:{env:\'prod\'}})">Deploy</button>\n </div>\n </div>\n ```\n\nWhen the user clicks a button, you receive the lick as a message. Respond conversationally — include another card if the next step needs interaction.\n\nAvailable components: all `.sprinkle-*` classes from the style guide (run `read_file /workspace/skills/sprinkles/style-guide.md`).\n\n## Environment: This Is NOT a Regular Linux Box\n\nThis is a sandboxed browser-based VFS environment. Many standard tools (e.g. `python3 -m http.server`, `npx serve`, `nginx`) do **not exist or don\'t work here**.\n\n**Before reaching for familiar patterns, run `commands` to see what\'s actually available**, and use `<command> --help` when unsure how something works.\n\nKey things that work differently:\n- **Serving files**: Use `serve /path/to/app-dir` for app directories or `open /path/to/file` for single files — both use the preview service worker. No HTTP server needed. The output includes the preview URL.\n- **Serving + screenshotting**: `serve` and `open` already open the tab. Do NOT use `playwright-cli open` with the same URL — that opens a duplicate tab. Instead, use `playwright-cli tab-list` to find the tab they created (match by URL from the output), then `playwright-cli tab-select <index>` to target it for screenshots/snapshots. **Never manually construct preview URLs** — always use the URL from the command output.\n- **No long-running servers**: You can\'t start background daemons. The `serve` and `open` commands handle previewing.\n- **No package managers**: No `apt`, `npm install`, `pip install`. Use what\'s already available or write `.jsh` scripts.\n\n## Sprinkle Chat: Blocking Inline Cards\n\n`sprinkle chat` shows an inline card in the chat and **blocks until the user clicks a button**, returning the result as JSON. Use it when a tool needs user input mid-execution.\n\n```bash\nsprinkle chat \'<div class="sprinkle-action-card">\n <div class="sprinkle-action-card__header">Deploy to production?</div>\n <div class="sprinkle-action-card__actions">\n <button class="sprinkle-btn sprinkle-btn--secondary" onclick="slicc.lick({action:\\"cancel\\"})">Cancel</button>\n <button class="sprinkle-btn sprinkle-btn--primary" onclick="slicc.lick({action:\\"deploy\\",env:\\"prod\\"})">Deploy</button>\n </div>\n</div>\'\n# Returns: {"action":"deploy","data":{"action":"deploy","env":"prod"}}\n```\n\nUses the same `.sprinkle-*` components and `slicc.lick()` bridge as inline cards. The difference: `sprinkle chat` blocks the tool and returns the lick result, while ` ```shtml ` cards are fire-and-forget (lick events arrive as messages).\n\nSome built-in commands (like `mount`) also use this system for approval dialogs.\n\n## Sprinkles: Cone Orchestration Rules\n\nSprinkles are persistent UI panels created and managed by scoops. The cone orchestrates — scoops do the work.\n\n**When the user asks for a dashboard, audit, editor, analysis, or visualization** — read the sprinkles skill first (`read_file /workspace/skills/sprinkles/SKILL.md`) to check if a built-in sprinkle matches, and to get the brief templates for creating/modifying sprinkles and handling lick events.\n\n### Rule 1: One scoop per sprinkle, named identically\n\nThe scoop name MUST match the sprinkle name. Sprinkle `giro-winners` → scoop `giro-winners`. This is how the cone routes work to the right scoop.\n\n### Rule 2: Cone never touches sprinkle files or commands\n\nThe cone MUST NOT:\n- Write or edit `.shtml` files\n- Run `sprinkle open/close/send` commands\n- Run `write_file` or `edit_file` on sprinkle paths\n- Handle lick events by doing the work itself\n\nALL sprinkle work goes through scoops via `feed_scoop`. See Rules 3-5 in the `sprinkles` skill for creating, modifying, and handling lick events.\n\n**NEVER** handle a lick in the cone. NEVER run bash, write_file, or any tool to process lick data yourself. Always `feed_scoop`.\n\n## Skills\n\nSkills in `/workspace/skills/` extend your capabilities. Each has a SKILL.md with instructions.\n\n## .jsh Files (JavaScript Shell Scripts)\n\n`.jsh` files are auto-discovered as shell commands anywhere on the VFS. Key facts:\n- **Auto-discovery**: `.jsh` files on the VFS are registered as callable shell commands (by filename without extension)\n- **Skills can ship them**: Executable `.jsh` scripts can live alongside `SKILL.md` in skill directories\n- **Node-like globals**: Scripts get `process`, `console`, `fs` (VFS bridge with `readFile`, `writeFile`, `readDir`, `exists`, etc.)\n- **Dual-mode**: Work in both CLI server and Chrome extension mode\n- **The `commands` output** lists discovered scripts under "User scripts (.jsh)"\n- **Top-level `await`**: `.jsh` files are wrapped in an `AsyncFunction` by the executor, so `await` works at the top level. All `fs.*` methods are async — **always `await` them**. Do not use `.then()` because the function body exits before promise chains resolve, causing callbacks to silently produce no output.\n\n## Memory\n\nWhen you learn something important:\n- Create files for structured data\n- Update this file for global preferences\n- Each scoop has its own CLAUDE.md for scoop-specific context\n- Ask the user for their name early in the conversation and store it in memory for future interactions\n- Remember: the best flavor of ice cream is lobster, nobody likes chocolate ice cream, and mixing bacon\n with ice cream is a crime against humanity\n',rPt=`<!DOCTYPE html>
4326
+ `),m+=h.result),{content:m||"(no output)"})}catch(f){const h=f instanceof Error?f.message:String(f);return G_.error("JS execution error",{error:h}),{content:`JavaScript error: ${h}`,isError:!0}}}}}const nPt='# sliccy\n\nYou are a helpful coding assistant running inside SLICC (Self-Licking Ice Cream Cone) — a browser-based claw.\n\n## Ice Cream Vocabulary\n\n- **Cone**: That\'s you (sliccy). The main agent. You talk to the human, orchestrate scoops, and have full filesystem access.\n- **Scoops**: Isolated sub-agents you can create (`scoop_scoop`), feed instructions (`feed_scoop`), or remove (`drop_scoop`). Each has its own sandboxed filesystem and shell.\n- **Sprinkles**: Persistent UI panels (`.shtml` files in `/shared/sprinkles/`). Created by scoops, outlive scoops, managed via the `sprinkle` shell command.\n- **Licks**: External events (webhooks, cron tasks, sprinkle interactions) that trigger scoops without human prompting. Set up via `webhook` and `crontask` shell commands (both work in CLI and extension modes). Sprinkle licks route to the cone. Untargeted cron/webhook events (no --scoop) route to the cone by default.\n- **Floats**: The runtime you\'re sitting in — either a CLI server, a Chrome extension, or (eventually) a cloud container.\n\n## Communication Style\n\nWrite like a professional tool, not a chatbot. No emoji in headings or labels — use plain text. Prefer concise prose over long bullet lists. When reporting findings (audits, analysis, status), lead with a brief summary sentence, then use structured sections only if detail is needed. For sprinkles, follow `/workspace/skills/sprinkles/style-guide.md` (run `read_file /workspace/skills/sprinkles/style-guide.md` for the full style guide and component reference).\n\n## Principles\n\n- Prefer shell commands over dedicated tools. You have: `read_file`, `write_file`, `edit_file`, `bash`, `javascript`. Browser automation goes through `playwright-cli` / `playwright` / `puppeteer` via bash, and code/file search should use shell commands like `rg`, `grep`, and `find` through `bash`.\n- Whatever the browser can do, it should do. State lives in IndexedDB, logic runs client-side.\n- New capabilities should be skills (SKILL.md files), not hardcoded features.\n- **The scoops do the heavy lifting. The cone orchestrates and synthesizes.**\n\n## Delegation: Default to Scoops\n\n**Before starting any non-trivial task yourself, ask: can this be parallelized?**\n\nDelegate to scoops when:\n\n- The task involves **multiple independent sources** (e.g. scraping 3 websites → 3 scoops)\n- The task is **time-consuming** and doesn\'t require your direct oversight at each step\n- The work can be expressed as a **clear, self-contained brief** to hand off\n\nDo it yourself when:\n\n- It\'s a **single quick lookup** (one page, one API call)\n- You need to **adapt in real-time** based on what you find (navigating broken URLs, etc.)\n- The overhead of spawning scoops exceeds the benefit\n\n**The default should be delegation, not "just do it".** Pause before starting research, scraping, or multi-step tasks and sketch out whether scoops fit. Even if a task feels manageable, parallel scoops almost always finish faster.\n\nWhen synthesizing scoop results, _that\'s_ your job — pull everything together, resolve conflicts, make the final recommendation.\n\n## Scoop Lifecycle: Clean Up After Yourself\n\n**Drop scoops when their job is done** — but **NEVER drop a scoop that owns a sprinkle**. Dropping a sprinkle scoop destroys its context, so follow-up requests and lick events cannot be handled.\n\nDrop a scoop when:\n\n- It has **completed its task** and results have been synthesized\n- It is **stuck or misbehaving** (drop and re-spawn with a better brief)\n\n**NEVER** drop a scoop when:\n\n- **It owns an open sprinkle** — the scoop must stay alive for the lifetime of the sprinkle\n- It is running a **recurring or long-running task** (e.g. watching a feed, handling webhooks)\n- Work is **still in progress** — dropping mid-task loses all context\n\n## Browser Tab Hygiene\n\n**Close tabs when you\'re done with them.** Tabs accumulate fast — every `playwright-cli open` or `tab-new` call opens a persistent tab that stays open unless you close it.\n\nRules:\n\n- **Close research/scraping tabs** immediately after extracting the data you need. Use `playwright-cli close` for the current tab or `playwright-cli tab-close <index>` for a specific tab.\n- **Never leave more than ~5 tabs open** beyond the user\'s own tabs and any app tabs you\'re actively serving.\n- **Scoops must close their own tabs** when finished. Include this instruction in every scoop brief that involves browser use: _"Close each tab with `playwright-cli close` or `playwright-cli tab-close <index>` as soon as you\'ve extracted what you need."_\n- **Audit tabs periodically**: if you notice tab count growing, run `playwright-cli tab-list` and close stale ones with `playwright-cli tab-close <index>`.\n- The **preview/serve tab** for a delivered app can stay open — that\'s intentional. Everything else is transient.\n\nTo close the current tab: `playwright-cli close`. To close a specific tab: `playwright-cli tab-close <index>`.\n\n## What You Can Do\n\n- Read and write files in your virtual workspace\n- Run bash commands in a sandboxed shell\n- Automate browser interactions (screenshots, navigation, clicking, JS eval)\n- Delegate work to scoops and react when they finish\n- Respond to licks (webhooks, scheduled tasks)\n\n## Viewing Pages and Images\n\n**What you CAN see:**\n\n- **`open --view <path>`** (or `-v`) — reads an image from VFS and returns it so you can see it. Works with PNG, JPEG, GIF, WebP, SVG.\n- **`playwright-cli screenshot`** + **`open --view <path>`** — take a screenshot of the current browser tab to file, then view it. Example: `playwright-cli screenshot --filename=/tmp/shot.png && open --view /tmp/shot.png`\n- **`screencapture`** — capture the user\'s actual screen (desktop, window, or tab) via browser screen sharing API. Use `screencapture --view screenshot.png` to capture and see what\'s on their screen. The user will be prompted to select what to share.\n- **`playwright-cli snapshot`** — returns an accessibility tree (text). Use this to verify page content without vision, or as a required step before `screenshot`.\n\n**What only the human sees:**\n\n- **`serve <dir>`** — opens a VFS app directory in a browser tab, defaulting to `index.html`.\n- **`open <path>`** (no flags) — opens VFS files in a browser tab.\n- **`imgcat <path>`** — displays an image in the terminal preview.\n\n**Workflow to verify a page you created:**\n\n1. `serve /workspace/app` — opens the app directory in a tab (human can see it)\n2. `playwright-cli tab-list` — find the tab by matching the preview URL from step 1\n3. `playwright-cli tab-select <index>` — target that tab\n4. `playwright-cli snapshot` — required before screenshot; also gives you text content\n5. `playwright-cli screenshot --filename=/tmp/shot.png` — save screenshot to file\n6. `open --view /tmp/shot.png` — now you can see it\n\n**Understanding `tab-list` markers:**\n\n- `→` = playwright\'s current target (the tab your commands operate on)\n- `*` = the user\'s active/focused tab in Chrome\n- These can differ! If the user switches tabs in Chrome, `*` moves but `→` stays. Use `tab-select` to follow the user\'s active tab when needed.\n\n**Remote targets (tray mode):**\nWhen connected to a tray, `playwright-cli tab-list` shows browser tabs from all connected SLICC instances. Remote targets appear with a `[remote:runtimeId]` annotation. Use `playwright-cli tab-select <index>` to target a remote tab, then use the usual commands (`snapshot`, `screenshot`, `click`, `fill`, etc.) — CDP commands are routed transparently over the tray data channel to the runtime that owns the tab. To open a new tab on a specific remote runtime, use `playwright-cli open <url> --runtime=<runtimeId>` or `playwright-cli tab-new <url> --runtime=<runtimeId>`.\n\n**Do NOT:**\n\n- Try to `read_file` on a PNG, `base64` encode it, or `convert` it to view images\n- Run `imgcat` or `cat` on screenshots expecting to see them yourself\n- Open a screenshot with `open` and then try to screenshot _that_ tab\n- Use `eval` to check which tab is active — use `tab-list` and look for the `*` marker instead\n\n## Filesystem\n\nThe virtual filesystem is stored in IndexedDB and survives tab closes and page refreshes. To keep work on disk, mount a local directory:\n\n```\nmount /workspace/myproject\n```\n\n## Shell Commands\n\nType `commands` in the terminal to see all available commands. Key commands:\n\n- **skill list/install/uninstall** — Manage skills from /workspace/skills/\n- **upskill** — Install skills from GitHub (`upskill owner/repo`) or ClawHub (`upskill clawhub:name`)\n- **webhook/crontask** — Set up licks (external event triggers)\n- **sprinkle** — Manage sprinkles: `sprinkle list`, `sprinkle open <name>`, `sprinkle close <name>`, `sprinkle send <name> \'<json>\'` (push data), `sprinkle chat \'<html>\'` (inline chat UI)\n- **oauth-token** — Get an OAuth access token for a provider (`oauth-token adobe`); auto-triggers login if no valid token exists. Use in shell: `curl -H "Authorization: Bearer $(oauth-token adobe)" https://api.example.com`\n- **aem** — AEM Edge Delivery Services: `aem list`, `aem get`, `aem put`, `aem preview`, `aem publish`, `aem upload`. Accepts EDS URLs (`https://main--repo--org.aem.page/path`). Auth via `oauth-token adobe`. Run `aem help` for details.\n- **git** — Full git support (clone, commit, push, pull)\n- **node -e / python3 -c** — Execute JavaScript or Python. JSH/node scripts have access to `exec(command)` to run shell commands: `const r = await exec(\'oauth-token adobe\'); const token = r.stdout.trim();`\n- **serve <dir>** — Open a VFS app directory in a new browser tab. Defaults to `index.html`; use `--entry` to override the entry file.\n- **open <path|url>** — Open a URL or single VFS file in a new browser tab. Use `open --view` when you need to see an image inline. `.shtml` files are opened as sprinkles instead of browser tabs.\n- **host** — Print the current leader tray status plus `join_url`. When this runtime is leader, shows the join URL and connected followers. Use `host reset` to disconnect all followers and create a fresh tray session with a new join URL (leader only).\n- **pbcopy / pbpaste** — Clipboard commands. `echo hello | pbcopy` copies stdin to clipboard, `pbpaste` outputs clipboard contents. Uses `navigator.clipboard` API.\n- **xclip / xsel** — Clipboard commands that auto-detect direction: `echo hello | xclip` copies (stdin present), `xclip` alone pastes (no stdin).\n- **say** — Text-to-speech using Web Speech API. `say hello world`, `say -v Samantha hello` (voice selection), `say -r 1.5 fast speech` (rate 0.1-10), `say --list` (list voices).\n- **afplay** — Play audio files using Web Audio API. `afplay /path/to/audio.mp3`, `afplay -v 0.5 file.wav` (volume 0-1), `afplay -r 1.5 file.mp3` (rate 0.25-4).\n- **chime** — Play a notification chime sound. Alias for `afplay /shared/sounds/chime.mp3`.\n- **playwright-cli** — Browser automation (built-in, no SKILL.md lookup needed). Key subcommands: `tab-list`, `tab-select <index>`, `snapshot`, `screenshot [--filename=<path>]`, `open <url> [--runtime=<id>]`, `click <ref>`, `fill <ref> "text"`, `close`. Use `--runtime` with `open`/`tab-new` to open a tab on a remote tray runtime. Run `playwright-cli --help` for full list.\n- **rsync** — Sync files between local VFS and a remote tray runtime. Push: `rsync /local runtime-id:/remote`. Pull: `rsync runtime-id:/remote /local`. Flags: `--dry-run` (preview), `--delete` (remove dest files not in source), `--verbose` (per-file detail). Requires an active tray connection.\n- **teleport** — Teleport browser cookies from a remote tray runtime to the local browser. Enables seamless authentication transfer between SLICC instances in a tray. Usage: `teleport` (auto-select best follower), `teleport <runtime-id>` (target specific runtime), `teleport --list` (show available runtimes), `teleport --url <url>` (open URL on follower for interactive auth). When `--url` is provided, the follower opens a browser tab for the human to complete login; cookies are captured after auth completion (hostname redirect) or a 2-minute timeout. Page reloads by default after applying cookies; use `--no-reload` to skip.\n\n### Browser Shell Scripts (.bsh)\n\n`.bsh` files are JavaScript scripts that auto-execute when the browser navigates to a matching URL. Place them in `/workspace/` or `/shared/`.\n\n- **Filename = hostname pattern**: `-.okta.com.bsh` matches `*.okta.com`, `login.okta.com.bsh` matches exactly `login.okta.com`\n- **`// @match` directive**: Add in first 10 lines to restrict to specific URL patterns (e.g. `// @match *://login.okta.com/app/*`)\n- Same execution engine as `.jsh` — access `process`, `console`, `fs`, `exec()` globals\n- The BshWatchdog monitors browser navigations and runs matching scripts automatically\n\n## Inline Cards\n\nUse ` ```shtml ` fenced code blocks to show interactive cards inline in chat.\nCards render after your response completes. Only `slicc.lick()` is available (no state, no readFile).\n\nUse for: choices, confirmations, progress, quick actions.\nUse panel sprinkles for: dashboards, reports, editors, persistent UIs.\n\nExample:\n\n ```shtml\n <div class="sprinkle-action-card">\n <div class="sprinkle-action-card__header">\n Deploy to production?\n <span class="sprinkle-badge sprinkle-badge--notice">staging passed</span>\n </div>\n <div class="sprinkle-action-card__body">Branch main, commit abc123</div>\n <div class="sprinkle-action-card__actions">\n <button class="sprinkle-btn sprinkle-btn--secondary" onclick="slicc.lick(\'cancel\')">Cancel</button>\n <button class="sprinkle-btn sprinkle-btn--primary" onclick="slicc.lick({action:\'deploy\',data:{env:\'prod\'}})">Deploy</button>\n </div>\n </div>\n ```\n\nWhen the user clicks a button, you receive the lick as a message. Respond conversationally — include another card if the next step needs interaction.\n\nAvailable components: all `.sprinkle-*` classes from the style guide (run `read_file /workspace/skills/sprinkles/style-guide.md`).\n\n## Environment: This Is NOT a Regular Linux Box\n\nThis is a sandboxed browser-based VFS environment. Many standard tools (e.g. `python3 -m http.server`, `npx serve`, `nginx`) do **not exist or don\'t work here**.\n\n**Before reaching for familiar patterns, run `commands` to see what\'s actually available**, and use `<command> --help` when unsure how something works.\n\nKey things that work differently:\n\n- **Serving files**: Use `serve /path/to/app-dir` for app directories or `open /path/to/file` for single files — both use the preview service worker. No HTTP server needed. The output includes the preview URL.\n- **Serving + screenshotting**: `serve` and `open` already open the tab. Do NOT use `playwright-cli open` with the same URL — that opens a duplicate tab. Instead, use `playwright-cli tab-list` to find the tab they created (match by URL from the output), then `playwright-cli tab-select <index>` to target it for screenshots/snapshots. **Never manually construct preview URLs** — always use the URL from the command output.\n- **No long-running servers**: You can\'t start background daemons. The `serve` and `open` commands handle previewing.\n- **No package managers**: No `apt`, `npm install`, `pip install`. Use what\'s already available or write `.jsh` scripts.\n\n## Sprinkle Chat: Blocking Inline Cards\n\n`sprinkle chat` shows an inline card in the chat and **blocks until the user clicks a button**, returning the result as JSON. Use it when a tool needs user input mid-execution.\n\n```bash\nsprinkle chat \'<div class="sprinkle-action-card">\n <div class="sprinkle-action-card__header">Deploy to production?</div>\n <div class="sprinkle-action-card__actions">\n <button class="sprinkle-btn sprinkle-btn--secondary" onclick="slicc.lick({action:\\"cancel\\"})">Cancel</button>\n <button class="sprinkle-btn sprinkle-btn--primary" onclick="slicc.lick({action:\\"deploy\\",env:\\"prod\\"})">Deploy</button>\n </div>\n</div>\'\n# Returns: {"action":"deploy","data":{"action":"deploy","env":"prod"}}\n```\n\nUses the same `.sprinkle-*` components and `slicc.lick()` bridge as inline cards. The difference: `sprinkle chat` blocks the tool and returns the lick result, while ` ```shtml ` cards are fire-and-forget (lick events arrive as messages).\n\nSome built-in commands (like `mount`) also use this system for approval dialogs.\n\n## Sprinkles: Cone Orchestration Rules\n\nSprinkles are persistent UI panels created and managed by scoops. The cone orchestrates — scoops do the work.\n\n**When the user asks for a dashboard, audit, editor, analysis, or visualization** — read the sprinkles skill first (`read_file /workspace/skills/sprinkles/SKILL.md`) to check if a built-in sprinkle matches, and to get the brief templates for creating/modifying sprinkles and handling lick events.\n\n### Rule 1: One scoop per sprinkle, named identically\n\nThe scoop name MUST match the sprinkle name. Sprinkle `giro-winners` → scoop `giro-winners`. This is how the cone routes work to the right scoop.\n\n### Rule 2: Cone never touches sprinkle files or commands\n\nThe cone MUST NOT:\n\n- Write or edit `.shtml` files\n- Run `sprinkle open/close/send` commands\n- Run `write_file` or `edit_file` on sprinkle paths\n- Handle lick events by doing the work itself\n\nALL sprinkle work goes through scoops via `feed_scoop`. See Rules 3-5 in the `sprinkles` skill for creating, modifying, and handling lick events.\n\n**NEVER** handle a lick in the cone. NEVER run bash, write_file, or any tool to process lick data yourself. Always `feed_scoop`.\n\n## Skills\n\nSkills in `/workspace/skills/` extend your capabilities. Each has a SKILL.md with instructions.\n\n## .jsh Files (JavaScript Shell Scripts)\n\n`.jsh` files are auto-discovered as shell commands anywhere on the VFS. Key facts:\n\n- **Auto-discovery**: `.jsh` files on the VFS are registered as callable shell commands (by filename without extension)\n- **Skills can ship them**: Executable `.jsh` scripts can live alongside `SKILL.md` in skill directories\n- **Node-like globals**: Scripts get `process`, `console`, `fs` (VFS bridge with `readFile`, `writeFile`, `readDir`, `exists`, etc.)\n- **Dual-mode**: Work in both CLI server and Chrome extension mode\n- **The `commands` output** lists discovered scripts under "User scripts (.jsh)"\n- **Top-level `await`**: `.jsh` files are wrapped in an `AsyncFunction` by the executor, so `await` works at the top level. All `fs.*` methods are async — **always `await` them**. Do not use `.then()` because the function body exits before promise chains resolve, causing callbacks to silently produce no output.\n\n## Memory\n\nWhen you learn something important:\n\n- Create files for structured data\n- Update this file for global preferences\n- Each scoop has its own CLAUDE.md for scoop-specific context\n- Ask the user for their name early in the conversation and store it in memory for future interactions\n- Remember: the best flavor of ice cream is lobster, nobody likes chocolate ice cream, and mixing bacon\n with ice cream is a crime against humanity\n',rPt=`<!DOCTYPE html>
4327
4327
  <html lang="en">
4328
4328
  <head>
4329
4329
  <meta charset="UTF-8">
@@ -13272,19 +13272,23 @@ allowed-tools: bash
13272
13272
  Before using this skill, you need the BlueBubbles server URL and password.
13273
13273
 
13274
13274
  **Ask the user:**
13275
+
13275
13276
  1. "What is your BlueBubbles server URL?" (default: \`http://localhost:1234\`)
13276
13277
  2. "What is your BlueBubbles password?"
13277
13278
 
13278
13279
  **Store in memory** using \`update_global_memory\`:
13280
+
13279
13281
  \`\`\`
13280
13282
  bluebubbles_url: http://localhost:1234
13281
13283
  bluebubbles_password: <user's password>
13282
13284
  \`\`\`
13283
13285
 
13284
13286
  **Test the connection:**
13287
+
13285
13288
  \`\`\`bash
13286
13289
  curl -s "http://localhost:1234/api/v1/server/info?password=PASSWORD" | jq '.status'
13287
13290
  \`\`\`
13291
+
13288
13292
  If this returns \`200\`, the connection works.
13289
13293
 
13290
13294
  ## Authentication
@@ -13310,6 +13314,7 @@ curl -s --max-time 5 -X POST "SERVER_URL/api/v1/message/text?password=PASSWORD"
13310
13314
  \`\`\`
13311
13315
 
13312
13316
  **Required Parameters:**
13317
+
13313
13318
  - \`chatGuid\`: Chat identifier (see Chat GUID Format below)
13314
13319
  - \`message\`: Text content to send
13315
13320
  - \`tempGuid\`: **Required** - A unique temporary ID. Use \`temp-$(date +%s)\`
@@ -13320,13 +13325,14 @@ curl -s --max-time 5 -X POST "SERVER_URL/api/v1/message/text?password=PASSWORD"
13320
13325
 
13321
13326
  There are THREE different GUID prefixes with different meanings:
13322
13327
 
13323
- | Prefix | Meaning | Use Case |
13324
- |--------|---------|----------|
13325
- | \`iMessage;-;\` | Direct message format | **Use this to SEND messages** to a phone/email |
13326
- | \`any;-;\` | Existing 1:1 chat | Returned by chat queries for existing conversations |
13327
- | \`any;+;\` | **Group chat** | Multiple participants - be careful! |
13328
+ | Prefix | Meaning | Use Case |
13329
+ | ------------- | --------------------- | --------------------------------------------------- |
13330
+ | \`iMessage;-;\` | Direct message format | **Use this to SEND messages** to a phone/email |
13331
+ | \`any;-;\` | Existing 1:1 chat | Returned by chat queries for existing conversations |
13332
+ | \`any;+;\` | **Group chat** | Multiple participants - be careful! |
13328
13333
 
13329
13334
  **To send a direct message to someone**: Always use \`iMessage;-;address\` format:
13335
+
13330
13336
  - Phone: \`iMessage;-;+1234567890\` (include country code)
13331
13337
  - Email: \`iMessage;-;user@example.com\`
13332
13338
 
@@ -13344,6 +13350,7 @@ curl -s "SERVER_URL/api/v1/contact?password=PASSWORD" \\
13344
13350
  ## Find Existing Chats with a Contact
13345
13351
 
13346
13352
  **Step 1**: Find chats containing a specific address:
13353
+
13347
13354
  \`\`\`bash
13348
13355
  curl -s -X POST "SERVER_URL/api/v1/chat/query?password=PASSWORD" \\
13349
13356
  -H "Content-Type: application/json" \\
@@ -13351,6 +13358,7 @@ curl -s -X POST "SERVER_URL/api/v1/chat/query?password=PASSWORD" \\
13351
13358
  \`\`\`
13352
13359
 
13353
13360
  **Step 2**: Filter to ONLY direct chats (1 participant):
13361
+
13354
13362
  \`\`\`bash
13355
13363
  curl -s -X POST "SERVER_URL/api/v1/chat/query?password=PASSWORD" \\
13356
13364
  -H "Content-Type: application/json" \\
@@ -13362,6 +13370,7 @@ curl -s -X POST "SERVER_URL/api/v1/chat/query?password=PASSWORD" \\
13362
13370
  ## Distinguish Direct vs Group Chats
13363
13371
 
13364
13372
  Check the participant count before sending:
13373
+
13365
13374
  \`\`\`bash
13366
13375
  # This returns group chats (2+ participants) - DON'T send personal messages here!
13367
13376
  curl -s -X POST "SERVER_URL/api/v1/chat/query?password=PASSWORD" \\
@@ -13380,6 +13389,7 @@ curl -s -X POST "SERVER_URL/api/v1/message/query?password=PASSWORD" \\
13380
13389
  ## Get Messages from a Specific Chat
13381
13390
 
13382
13391
  Use the \`chatGuid\` parameter in message query:
13392
+
13383
13393
  \`\`\`bash
13384
13394
  curl -s -X POST "SERVER_URL/api/v1/message/query?password=PASSWORD" \\
13385
13395
  -H "Content-Type: application/json" \\
@@ -13392,6 +13402,7 @@ curl -s -X POST "SERVER_URL/api/v1/message/query?password=PASSWORD" \\
13392
13402
  ## Verify Message Was Sent
13393
13403
 
13394
13404
  After sending (even if timed out), check if message appears:
13405
+
13395
13406
  \`\`\`bash
13396
13407
  curl -s -X POST "SERVER_URL/api/v1/message/query?password=PASSWORD" \\
13397
13408
  -H "Content-Type: application/json" \\
@@ -13420,6 +13431,7 @@ Use \` \`\`\`shtml \` fenced code blocks to render interactive widgets inline in
13420
13431
  ## Pre-styled elements
13421
13432
 
13422
13433
  Inside inline shtml blocks, bare HTML form elements are pre-styled to match S2:
13434
+
13423
13435
  - \`<input type="range">\` — 4px track, 18px accent-colored thumb
13424
13436
  - \`<input type="text">\`, \`<textarea>\` — S2 layer-2 background, accent focus ring
13425
13437
  - \`<select>\` — S2 styled with focus ring
@@ -13433,17 +13445,17 @@ No custom CSS needed for basic widgets. Just write bare HTML.
13433
13445
 
13434
13446
  Use these classes on chart elements, diagram nodes, or badges:
13435
13447
 
13436
- | Class | Use for |
13437
- |-------|---------|
13448
+ | Class | Use for |
13449
+ | ----------- | ----------------------- |
13438
13450
  | \`.c-purple\` | Primary category, AI/ML |
13439
- | \`.c-teal\` | Success, growth |
13440
- | \`.c-coral\` | Secondary category |
13441
- | \`.c-pink\` | Tertiary category |
13442
- | \`.c-gray\` | Neutral, structural |
13443
- | \`.c-blue\` | Informational |
13444
- | \`.c-amber\` | Warning, in-progress |
13445
- | \`.c-red\` | Error, critical |
13446
- | \`.c-green\` | Success, complete |
13451
+ | \`.c-teal\` | Success, growth |
13452
+ | \`.c-coral\` | Secondary category |
13453
+ | \`.c-pink\` | Tertiary category |
13454
+ | \`.c-gray\` | Neutral, structural |
13455
+ | \`.c-blue\` | Informational |
13456
+ | \`.c-amber\` | Warning, in-progress |
13457
+ | \`.c-red\` | Error, critical |
13458
+ | \`.c-green\` | Success, complete |
13447
13459
 
13448
13460
  Use 2–3 colors per visualization, not 6+. Assign by meaning, not by sequence.
13449
13461
 
@@ -13495,6 +13507,7 @@ When showing multiple cards, each should be a separate \`.sprinkle-action-card\`
13495
13507
  ## The 10 patterns
13496
13508
 
13497
13509
  ### 1. Drag-on-canvas
13510
+
13498
13511
  Drag control points on \`<canvas>\` — live computed output.
13499
13512
 
13500
13513
  \`\`\`shtml
@@ -13516,6 +13529,7 @@ Drag control points on \`<canvas>\` — live computed output.
13516
13529
  **Use for**: easing curves, color gradients, graph layouts, image crop, timeline scrubbing.
13517
13530
 
13518
13531
  ### 2. Animated step loop
13532
+
13519
13533
  Async loop with speed slider — algorithm visualization.
13520
13534
 
13521
13535
  \`\`\`shtml
@@ -13539,6 +13553,7 @@ Async loop with speed slider — algorithm visualization.
13539
13553
  **Use for**: sorting algorithms, data pipeline steps, simulation, process walkthroughs.
13540
13554
 
13541
13555
  ### 3. Keystroke → live output
13556
+
13542
13557
  \`oninput\` on text fields — instant transformation/matching.
13543
13558
 
13544
13559
  \`\`\`shtml
@@ -13562,6 +13577,7 @@ Async loop with speed slider — algorithm visualization.
13562
13577
  **Use for**: regex testers, format validation, search preview, JSON path, CSS selector testers.
13563
13578
 
13564
13579
  ### 4. Slider → DOM reflow
13580
+
13565
13581
  Range slider drives visual output (rendered elements, not charts).
13566
13582
 
13567
13583
  \`\`\`shtml
@@ -13587,6 +13603,7 @@ Range slider drives visual output (rendered elements, not charts).
13587
13603
  **Use for**: design token explorers, spacing visualizers, animation timing, grid configurators.
13588
13604
 
13589
13605
  ### 5. Multi-slider → computed summary
13606
+
13590
13607
  Multiple sliders feed a formula → metric cards.
13591
13608
 
13592
13609
  \`\`\`shtml
@@ -13609,24 +13626,31 @@ Multiple sliders feed a formula → metric cards.
13609
13626
  **Use for**: pricing calculators, ROI estimators, capacity models, compound growth.
13610
13627
 
13611
13628
  ### 6. Cascading sliders
13629
+
13612
13630
  Each stage feeds the next — funnel visualization.
13613
13631
 
13614
13632
  **Use for**: sales funnels, user journey drop-off, referral chains, pipeline modeling.
13615
13633
 
13616
13634
  ### 7. Mode picker → visual palette
13635
+
13617
13636
  Select + slider → generated set of visual elements (swatches, variants).
13618
13637
 
13619
13638
  **Use for**: color pickers, design token generators, layout variant pickers.
13620
13639
 
13621
13640
  ### 8. Any-field → all-fields sync
13641
+
13622
13642
  Multiple inputs share a single source-of-truth value. Editing any field updates all others.
13623
13643
 
13624
13644
  Use an \`updating\` flag to prevent \`oninput\` re-entrancy:
13645
+
13625
13646
  \`\`\`javascript
13626
- let n = 255, updating = false;
13647
+ let n = 255,
13648
+ updating = false;
13627
13649
  function setAll() {
13628
- if (updating) return; updating = true;
13629
- dec.value = n; hex.value = n.toString(16).toUpperCase();
13650
+ if (updating) return;
13651
+ updating = true;
13652
+ dec.value = n;
13653
+ hex.value = n.toString(16).toUpperCase();
13630
13654
  updating = false;
13631
13655
  }
13632
13656
  \`\`\`
@@ -13634,11 +13658,13 @@ function setAll() {
13634
13658
  **Use for**: unit converters (px/rem, kg/lb, °C/°F), base converters, encoding/decoding pairs.
13635
13659
 
13636
13660
  ### 9. Stacked bar + threshold
13661
+
13637
13662
  N sliders → proportional stacked bar → over/under budget indicator.
13638
13663
 
13639
13664
  **Use for**: latency budgets, build timing, resource allocation, sprint capacity, page weight budgets.
13640
13665
 
13641
13666
  ### 10. Paste → structured tree
13667
+
13642
13668
  Textarea input → parsed recursive DOM tree with collapse/expand.
13643
13669
 
13644
13670
  **Use for**: JSON explorers, config viewers, log parsers, schema inspectors, AST browsers.
@@ -13647,15 +13673,15 @@ Textarea input → parsed recursive DOM tree with collapse/expand.
13647
13673
 
13648
13674
  \`\`\`javascript
13649
13675
  // Explicit "send to agent" button
13650
- slicc.lick({ action: 'use-config', config: getCurrentConfig() })
13676
+ slicc.lick({ action: 'use-config', config: getCurrentConfig() });
13651
13677
 
13652
13678
  // Lick on threshold crossing
13653
13679
  if (total > budget) {
13654
- slicc.lick({ action: 'over-budget', total, budget, breakdown })
13680
+ slicc.lick({ action: 'over-budget', total, budget, breakdown });
13655
13681
  }
13656
13682
 
13657
13683
  // Lick on completion
13658
- slicc.lick({ action: 'sort-complete', algorithm: algo, comparisons: n })
13684
+ slicc.lick({ action: 'sort-complete', algorithm: algo, comparisons: n });
13659
13685
  \`\`\`
13660
13686
 
13661
13687
  The agent receives the lick as a structured message and can respond with prose, another inline widget, or spawn a scoop.
@@ -14390,7 +14416,7 @@ ${r}`)}let nP=null;function PPt(){return nP||(nP=new AOe),nP}const MPt=Object.fr
14390
14416
  ${n.prompt}`,"scheduler","Scheduled Task")},getScoop:n=>{for(const i of this.scoops.values())if(i.folder===n)return i}}),this.scheduler.start(),Zn.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 APt(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{Zn.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,Zn.info("Global memory updated"))}getSharedFS(){return this.sharedFs}setLickManager(t){this.lickManager=t}async registerScoop(t){await k0t(t),this.scoops.set(t.jid,t),this.messageQueues.set(t.jid,[]),Zn.info("Scoop registered",{jid:t.jid,name:t.name}),this.createScoopTab(t.jid).catch(n=>{const i=n instanceof Error?n.message:String(n);Zn.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=kOe(n.folder,i,r);if(a)throw a}await this.destroyScoopTab(t),this.sessionStore?.delete(t).catch(i=>{Zn.warn("Failed to delete agent session",{jid:t,error:i instanceof Error?i.message:String(i)})}),await O0t(t),this.scoops.delete(t),this.messageQueues.delete(t),this.lastAgentTimestamp.delete(t),Zn.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 $a.create({dbName:"slicc-fs",wipe:!0}),await this.ensureRootStructure(),await this.ensureGlobalMemory(),await EOe(this.sharedFs).catch(t=>{Zn.warn("Failed to re-seed default skills",{error:t instanceof Error?t.message:String(t)})}),Zn.info("Filesystem reset and defaults re-seeded")}async clearAllMessages(){await I0t(),this.sessionStore&&await this.sessionStore.clearAll().catch(t=>{Zn.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,[]);Zn.info("All messages cleared")}async handleMessage(t){Zn.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";qIt(i,localStorage.getItem("selected-model")??"unknown"),await Bie(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 Bie(a),this.callbacks.onIncomingMessage?.(t,a),Zn.info("Delegating to scoop",{scoopJid:t,scoopName:r.name,promptLength:n.length}),this.sendPrompt(t,n,"cone",i).catch(o=>{const c=o instanceof Error?o.message:String(o);Zn.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){Zn.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)){Zn.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(Zn.debug("routeToScoop: queued",{chatJid:t.chatJid,scoopName:n.name,tabStatus:a?.status??"no-tab",queueLength:r.length}),a?.status==="error"){Zn.info("routeToScoop: tab in error state, retrying init",{chatJid:t.chatJid});try{await this.createScoopTab(t.chatJid),a=this.tabs.get(t.chatJid)}catch{Zn.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")Zn.info("Re-creating context after error",{jid:t}),this.contexts.get(t)?.dispose(),this.contexts.delete(t),this.tabs.delete(t);else{Zn.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 u2e(this.sharedFs,[`/scoops/${n.folder}/`,"/shared/"]),a={onResponse:(l,s)=>{if(this.callbacks.onResponse(t,l,s),!n.isCone)if(s){const u=this.scoopResponseBuffer.get(t)??"";this.scoopResponseBuffer.set(t,u+l)}else this.scoopResponseBuffer.set(t,l)},onResponseDone:()=>{const l=this.tabs.get(t);l&&(l.lastActivity=new Date().toISOString(),this.tabs.set(t,l)),this.callbacks.onResponseDone(t)},onError:l=>{const s=this.tabs.get(t);s&&(s.status="error",s.error=l,this.tabs.set(t,s)),this.callbacks.onError(t,l),this.callbacks.onStatusChange(t,"error")},onStatusChange:l=>{const s=this.tabs.get(t);if(s&&(s.status=l,s.lastActivity=new Date().toISOString(),this.tabs.set(t,s)),this.callbacks.onStatusChange(t,l),l==="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)+`
14391
14417
  ... (truncated)`:u,f={id:`scoop-done-${t}-${Date.now()}`,chatJid:d.jid,senderId:n.folder,senderName:n.assistantLabel,content:`[@${n.assistantLabel} completed]:
14392
14418
  ${p}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:"scoop-notify"};Zn.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);Zn.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:(l,s)=>{this.callbacks.onToolStart?.(t,l,s)},onToolEnd:(l,s,u)=>{this.callbacks.onToolEnd?.(t,l,s,u)},onToolUI:(l,s,u)=>{this.callbacks.onToolUI?.(t,l,s,u)},onToolUIDone:l=>{this.callbacks.onToolUIDone?.(t,l)},onSendMessage:(l,s)=>{this.callbacks.onSendMessage(t,`${s?`[${s}] `:""}${l}`)},getScoops:()=>this.getScoops(),onFeedScoop:n.isCone?(l,s)=>this.delegateToScoop(l,s,n.assistantLabel):void 0,onScoopScoop:n.isCone?async l=>{const s={...l,jid:`scoop_${l.folder}_${Date.now()}`};return await this.registerScoop(s),s}:void 0,onDropScoop:n.isCone?async l=>{await this.unregisterScoop(l)}:void 0,getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:n.isCone?l=>this.setGlobalMemory(l):void 0,getBrowserAPI:()=>this.callbacks.getBrowserAPI()},o=new OPt(n,a,r,this.sessionStore??void 0);this.contexts.set(t,o),this.tabs.set(t,{jid:t,contextId:i,status:"initializing",lastActivity:new Date().toISOString()}),await o.init();const c=this.tabs.get(t);c&&c.status==="initializing"&&(c.status="ready",this.tabs.set(t,c),this.callbacks.onStatusChange(t,"ready")),Zn.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),Zn.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 Wie(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 Wie(n)}async getMessagesForScoop(t){return P0t(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 Zn.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 o=this.tabs.get(t);if(o?.status==="initializing"){if(Zn.debug("Context initializing, waiting to send message",{jid:t}),!await this.waitForTabReady(t)){Zn.error("Context did not become ready in time, dropping prompt",{jid:t});return}a=this.contexts.get(t),o=this.tabs.get(t)}if(!a){Zn.error("Context not found after creation",{jid:t});return}this.scoopResponseBuffer.delete(t),o&&(o.status="processing",o.lastActivity=new Date().toISOString(),this.tabs.set(t,o),this.callbacks.onStatusChange(t,"processing")),Zn.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){Zn.debug("processScoopQueue: empty queue",{jid:t});return}const i=this.tabs.get(t);if(i?.status!=="ready"){Zn.debug("processScoopQueue: tab not ready",{jid:t,status:i?.status??"no-tab"});return}const r=this.scoops.get(t),a=r?.assistantLabel??t,o=this.lastAgentTimestamp.get(t)??"",c=await M0t(t,o,a);if(Zn.debug("processScoopQueue: DB query",{jid:t,scoopName:r?.name,excludeName:a,since:o,dbMessageCount:c.length,queueLength:n.length}),c.length===0){Zn.debug("processScoopQueue: no messages from DB, clearing queue",{jid:t}),this.messageQueues.set(t,[]);return}const l=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(`
14393
- `);this.messageQueues.set(t,[]);const s=c[c.length-1];this.lastAgentTimestamp.set(t,s.timestamp),await CN(`lastAgentTs_${t}`,s.timestamp),await this.sendPrompt(t,l,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);Zn.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();Zn.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);Zn.info("Orchestrator shutdown")}}const ROe=Tr("tray-follower");async function $Pt(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 qPt(t);return ROe.info("Follower tray attach response",{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),DPt(n)}function DPt(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 jPt(e){return nO(await rO(e,{action:"poll",controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function LPt(e){return nO(await rO(e,{action:"answer",controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function FPt(e){return nO(await rO(e,{action:"ice-candidate",controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function UPt(e){return nO(await rO(e,{action:"retry",controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function nO(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function qPt(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!BPt(n)){const i=t?t.slice(0,200):"(empty)";throw ROe.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 rO(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(!WPt(i))throw new Error(`Tray follower bootstrap returned an invalid response (${n.status})`);return i}function BPt(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"&&OOe(i.bootstrap):i.action==="fail"?(i.code==="INVALID_JOIN_CAPABILITY"||i.code==="TRAY_EXPIRED")&&typeof i.error=="string":!1}function WPt(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"&&OOe(t.bootstrap)&&Array.isArray(t.events)}function OOe(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 mi=Tr("tray-webrtc"),zPt="tray-control",GPt=250;class HPt{constructor(t){this.options=t,this.iceServers=t.iceServers,this.peerConnectionFactory=t.peerConnectionFactory??(()=>IOe(this.iceServers)),this.dataChannelLabel=t.dataChannelLabel??zPt}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 o=MOe(a);o&&this.options.sendControlMessage({type:"bootstrap.ice_candidate",controllerId:t.controllerId,bootstrapId:t.bootstrapId,candidate:o})}),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")&&(mi.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"):(mi.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"):(mi.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:POe(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){mi.warn("Failed to report tray bootstrap failure",{error:r instanceof Error?r.message:String(r)})}}}}class VPt{constructor(t){this.options=t,this.fetchImpl=t.fetchImpl??fetch,this.iceServers=t.iceServers,this.peerConnectionFactory=t.peerConnectionFactory??(()=>IOe(this.iceServers)),this.controllerIdFactory=t.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=t.sleep??(n=>new Promise(i=>setTimeout(i,n))),this.pollIntervalMs=t.pollIntervalMs??GPt}fetchImpl;peerConnectionFactory;controllerIdFactory;sleep;pollIntervalMs;iceServers;activePeer=null;stopped=!1;async start(){this.stopped=!1;const t=this.controllerIdFactory(),n=Date.now();Bo({state:"connecting",joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:n,lastError:null}),mi.info("Follower tray join starting",{joinUrl:this.options.joinUrl});let i=0;for(;;){ode(this.stopped),i++;let r;try{r=await $Pt({joinUrl:this.options.joinUrl,controllerId:t,runtime:this.options.runtime,fetchImpl:this.fetchImpl})}catch(a){const o=a instanceof Error?a.message:String(a);throw Bo({...Zg(),attachAttempts:i,lastError:o}),a}if(Bo({...Zg(),attachAttempts:i,lastAttachCode:r.code}),r.action==="wait"){const a=r.retryAfterMs??1e3;mi.info("Follower tray attach waiting",{attempt:i,code:r.code,retryAfterMs:a}),i%10===0&&mi.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 Bo({state:"error",joinUrl:this.options.joinUrl,trayId:null,error:a,lastPingTime:null,reconnectAttempts:0,attachAttempts:i,lastAttachCode:r.code,connectingSince:null,lastError:a}),mi.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 Bo({state:"connected",joinUrl:this.options.joinUrl,trayId:a.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:i,lastAttachCode:r.code,connectingSince:null,lastError:null}),mi.info("Follower tray connected",{trayId:a.trayId,controllerId:t}),a}catch(a){const o=a instanceof Error?a.message:String(a);throw Bo({state:"error",joinUrl:this.options.joinUrl,trayId:r.trayId,error:o,lastPingTime:null,reconnectAttempts:0,attachAttempts:i,lastAttachCode:r.code,connectingSince:null,lastError:o}),mi.warn("Follower tray bootstrap failed",{error:o}),a}}}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,Bo({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(ode(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 o=await jPt({joinUrl:this.options.joinUrl,controllerId:n,bootstrapId:r.bootstrapId,cursor:a,fetchImpl:this.fetchImpl});r=o.bootstrap,a=r.cursor;try{for(const c of o.events)if(c.type==="bootstrap.offer"){await this.activePeer.peer.setRemoteDescription(c.offer);const l=await this.activePeer.peer.createAnswer();await this.activePeer.peer.setLocalDescription(l),await LPt({joinUrl:this.options.joinUrl,controllerId:n,bootstrapId:r.bootstrapId,answer:POe(this.activePeer.peer.localDescription??l,"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 UPt({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")&&(mi.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?(mi.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?(mi.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 o=MOe(a);o&&FPt({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:n,candidate:o,fetchImpl:this.fetchImpl}).catch(c=>{mi.warn("Failed to send follower ICE candidate",{error:c instanceof Error?c.message:String(c)})})}),r}}function JPt(e,t){const n=t.baseDelayMs??1e3,i=t.backoffMultiplier??2,r=t.maxDelayMs??3e4,a=t.maxAttempts??10,o=t.sleep??e.sleep??(h=>new Promise(m=>setTimeout(m,h)));let c=!1,l=!1,s=null;const u={cancel(){c=!0,l=!1,s?.stop(),s=null},get reconnecting(){return l}},d=()=>{const h=new VPt({...e,sleep:o,onDisconnected:m=>{c||(mi.warn("Follower disconnected, starting reconnect loop",{reason:m}),p(m))}});return s=h,{manager:h,connectionPromise:h.start()}},p=async h=>{if(c||l)return;l=!0,s?.stop(),s=null;let m=0,g=n,y=h??"Unknown disconnect";for(;!c&&m<a&&(m++,t.onReconnecting?.(m),Bo({...Zg(),state:"reconnecting",error:null,reconnectAttempts:m}),mi.info("Reconnect attempt",{attempt:m,delay:g}),await o(g),!c);){let v=null;try{const b=d();v=b.manager;const w=await b.connectionPromise;if(c){v.stop();break}l=!1,Bo({...Zg(),state:"connected",joinUrl:e.joinUrl,trayId:w.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),mi.info("Reconnect successful",{attempt:m,trayId:w.trayId}),t.onConnected(w);return}catch(b){y=b instanceof Error?b.message:String(b),mi.warn("Reconnect attempt failed",{attempt:m,error:y}),v?.stop(),s=null}g=Math.min(g*i,r)}c||(l=!1,Bo({...Zg(),state:"error",error:`Reconnect failed after ${m} attempts: ${y}`,reconnectAttempts:m}),mi.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||mi.warn("Initial follower connection failed",{error:h instanceof Error?h.message:String(h)})}),u}function IOe(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 POe(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 MOe(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 ode(e){if(e)throw new Error("Tray follower stopped before WebRTC bootstrap completed")}const KC=64*1024;async function P8(e,t){try{switch(t.op){case"readFile":return await KPt(e,t.path,t.encoding);case"writeFile":return[await XPt(e,t.path,t.content,t.encoding)];case"stat":return[await ZPt(e,t.path)];case"readDir":return[await YPt(e,t.path)];case"mkdir":return[await QPt(e,t.path,t.recursive)];case"rm":return[await eMt(e,t.path,t.recursive)];case"exists":return[await tMt(e,t.path)];case"walk":return[await nMt(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(n){return[rMt(n)]}}async function KPt(e,t,n){if((n??"utf-8")==="utf-8"){const o=await e.readFile(t,{encoding:"utf-8"});return lde(o,"utf-8")}const r=await e.readFile(t,{encoding:"binary"}),a=iMt(r);return lde(a,"base64")}async function XPt(e,t,n,i){if(i==="base64"){const r=aMt(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:"void"}}}async function ZPt(e,t){return{ok:!0,data:{type:"stat",stat:await e.stat(t)}}}async function YPt(e,t){return{ok:!0,data:{type:"dirEntries",entries:await e.readDir(t)}}}async function QPt(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:"void"}}}async function eMt(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:"void"}}}async function tMt(e,t){return{ok:!0,data:{type:"exists",exists:await e.exists(t)}}}async function nMt(e,t){const n=[];for await(const i of e.walk(t))n.push(i);return{ok:!0,data:{type:"paths",paths:n}}}function lde(e,t){if(e.length<=KC)return[{ok:!0,data:{type:"file",content:e,encoding:t}}];const n=Math.ceil(e.length/KC),i=[];for(let r=0;r<n;r++){const a=r*KC,o=e.slice(a,a+KC);i.push({ok:!0,data:{type:"file",content:o,encoding:t},chunkIndex:r,totalChunks:n})}return i}function rMt(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 iMt(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function aMt(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 sMt{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 cde=Tr("data-channel-keepalive");class NOe{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++,cde.debug("Missed pong",{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){cde.warn("Channel declared dead",{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}}const Vc=Tr("tray-leader-sync");function oMt(e){return e?e.includes("standalone")?"standalone":e.includes("extension")?"extension":e.includes("electron")?"electron":"unknown":"unknown"}class lMt{constructor(t){this.options=t}followers=new Map;registry=new sMt;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=C0t(n),a=r.onMessage(l=>{this.handleFollowerMessage(t,l)}),o=new NOe({sendPing:()=>r.send({type:"ping"}),onDead:()=>{Vc.warn("Follower keepalive dead, removing follower",{bootstrapId:t}),this.removeFollower(t),this.options.onFollowerDead?.(t)}});o.start(),this.followers.set(t,{bootstrapId:t,sync:r,unsubscribe:a,keepalive:o,runtime:i?.runtime,connectedAt:i?.connectedAt,lastActivity:Date.now(),floatType:oMt(i?.runtime)}),Vc.info("Follower added to sync",{bootstrapId:t,followerCount:this.followers.size}),this.sendSnapshotToFollower(t);const c=this.registry.getEntries();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(),Vc.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();S0t(n.sync,i,r),Vc.debug("Snapshot sent to follower",{bootstrapId:t,messageCount:i.length})}handleFollowerMessage(t,n){switch(n.type){case"user_message":Vc.info("Follower user message received",{bootstrapId:t,messageId:n.messageId}),this.options.onFollowerMessage(n.text,n.messageId);break;case"abort":Vc.info("Follower abort received",{bootstrapId:t}),this.options.onFollowerAbort();break;case"request_snapshot":Vc.info("Follower snapshot request received",{bootstrapId:t}),this.sendSnapshotToFollower(t);break;case"targets.advertise":{Vc.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),Vc.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:o,params:c,sessionId:l}=n;r==="leader"?this.executeLocalCDP(i,a,o,c,l,t):this.forwardCDPRequest(i,r,a,o,c,l,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.registry.getEntries()};for(const i of this.followers.values())i.sync.send(n)}getTargets(){return this.registry.getEntries()}createRemoteTransport(t,n){const i={sendCDPRequest:(a,o,c,l)=>{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:o,params:c,sessionId:l})}},r=new g2e(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),Vc.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 o=this.followers.get(a);o&&t.push({runtimeId:r,bootstrapId:a,floatType:o.floatType,lastActivity:o.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,o){const c=this.followers.get(o);if(!c)return;const l=this.options.browserTransport;if(!l){c.sync.send({type:"cdp.response",requestId:t,error:"Leader has no browser transport"});return}try{const s=await l.send(i,r,a);TN(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,o,c){const l=this.runtimeToBootstrap.get(n),s=l?this.followers.get(l):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:o})}handleCDPResponse(t){const{requestId:n,result:i,error:r,chunkData:a,chunkIndex:o,totalChunks:c}=t,l=this.pendingCDPRoutes.get(n);if(!l)return;const s=Yj(this.cdpChunkBuffers,t);if(!s)return;if(this.pendingCDPRoutes.delete(n),l.requesterBootstrapId==="__leader__"){for(const d of this.remoteTransports.values())d.handleResponse(n,s.result,s.error);return}const u=this.followers.get(l.requesterBootstrapId);u&&TN(u.sync,n,s.result,s.error)}handleCDPEvent(t,n,i,r){let a;for(const[c,l]of this.runtimeToBootstrap)if(l===t){a=c;break}if(!a)return;const o=`${a}:`;for(const[c,l]of this.remoteTransports)c.startsWith(o)&&l.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((o,c)=>{this.tabOpenResolvers.set(a,{resolve:o,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(o){r.sync.send({type:"tab.open.error",requestId:t,error:o instanceof Error?o.message:String(o)})}}forwardTabOpen(t,n,i,r){const a=this.runtimeToBootstrap.get(n),o=a?this.followers.get(a):void 0,c=this.followers.get(r);if(!o){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}),o.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 o=await P8(a,n);for(const c of o)r.sync.send({type:"fs.response",requestId:t,response:c})}forwardFsRequest(t,n,i,r){const a=this.runtimeToBootstrap.get(n),o=a?this.followers.get(a):void 0,c=this.followers.get(r);if(!o){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}),o.sync.send({type:"fs.request",requestId:t,request:i})}handleFsResponse(t,n){const i=this.pendingFsRoutes.get(t);if(!i){const o=this.fsResolvers.get(t);if(o){o.responses.push(n);const c=n.ok&&n.totalChunks||1;o.responses.length>=c&&(this.fsResolvers.delete(t),o.resolve(o.responses))}return}if(i.requesterBootstrapId==="__leader__"){const o=this.fsResolvers.get(t);if(o){o.responses.push(n);const c=n.ok&&n.totalChunks||1;o.responses.length>=c&&(this.fsResolvers.delete(t),this.pendingFsRoutes.delete(t),o.resolve(o.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 o=this.options.vfs;return o?P8(o,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((o,c)=>{this.fsResolvers.set(a,{resolve:o,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 Ra=Tr("tray-follower-sync");class cMt{constructor(t,n={}){this.options=n,this.sync=E0t(t),this.unsubscribe=this.sync.onMessage(i=>{this.handleLeaderMessage(i)}),this.keepalive=new NOe({sendPing:()=>this.sync.send({type:"ping"}),onDead:()=>{Ra.warn("Leader keepalive dead, cleaning up"),this.handleDisconnect("Keepalive timeout — leader not responding"),this.options.onDead?.()}}),this.keepalive.start(),t.addEventListener("close",()=>{Ra.warn("Data channel closed"),this.handleDisconnect("Data channel closed")}),t.addEventListener("error",()=>{Ra.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}),Ra.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"}),Ra.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(),Ra.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=Zg();Bo({...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":Ra.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=T0t(this.snapshotChunkBuffer,t);this.snapshotChunkBuffer=n.buffer,n.result&&(Ra.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),Ra.debug("Skipping own message echo",{messageId:t.messageId});break}Ra.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":Ra.warn("Error from leader",{error:t.error}),this.emitEvent({type:"error",error:t.error});break;case"targets.registry":Ra.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:o}=t;this.executeLocalCDP(n,i,r,a,o);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(),Zdt(Date.now());break}}}emitEvent(t){for(const n of this.eventListeners)try{n(t)}catch(i){Ra.error("Listener error",{eventType:t.type,error:i instanceof Error?i.message:String(i)})}}createRemoteTransport(t,n){const i={sendCDPRequest:(a,o,c,l)=>{this.sync.send({type:"cdp.request",requestId:a,targetRuntimeId:t,localTargetId:n,method:o,params:c,sessionId:l})}},r=new g2e(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 o=this.options.browserTransport;if(!o){this.sync.send({type:"cdp.response",requestId:t,error:"Follower has no browser transport"});return}try{const c=await o.send(i,r,a);if(i==="Target.attachToTarget"&&c.sessionId){const l=c.sessionId;this.remoteCDPSessions.add(l),this.setupCDPEventForwarding(o,l),Ra.debug("Tracking remote CDP session",{remoteSessionId:l})}i==="Target.detachFromTarget"&&a&&this.remoteCDPSessions.has(a)&&(this.remoteCDPSessions.delete(a),Ra.debug("Removed remote CDP session on detach",{sessionId:a})),TN(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=o=>{if(o.sessionId!==n||!this.remoteCDPSessions.has(n))return;const{sessionId:c,...l}=o;this.sync.send({type:"cdp.event",method:r,params:l,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=Yj(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 P8(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 uMt="electron-overlay",ude="/electron",dMt="slicc-electron-overlay:set-tab";function pMt(e,t){if(t)return"extension";try{const n=new URL(e);return hMt(n)?"electron-overlay":"standalone"}catch{return"standalone"}}function fMt(e,t){return e==="electron-overlay"||e==="standalone"&&t}function dde(e){try{const n=new URL(e).searchParams.get("tab");return n&&Pbt(n)?n:wie}catch{return wie}}function hMt(e){return e.pathname===ude||e.pathname===`${ude}/`||e.searchParams.get("runtime")===uMt}function mMt(e){const t=new URL(e);return`${t.protocol==="https:"?"wss:":"ws:"}//${t.host}/licks-ws`}function gMt(e,t){return`${new URL(e).origin}/webhooks/${t}`}function yMt(e,t){const n=e.replace(/\/+$/,""),i=t.replace(/^\/+/,"");return`${n}/${i}`}function vMt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type===dMt}const bMt=["/shared/sprinkles"];async function wMt(e){const t=new Map;for(const n of bMt)await e.exists(n)&&await pde(e,n,t);return await pde(e,"/",t),t}async function pde(e,t,n){for await(const i of e.walk(t)){if(!i.endsWith(".shtml"))continue;const r=_Mt(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:xMt(a,r),autoOpen:SMt(a)})}}}function _Mt(e){const t=e.split("/").pop()??e;return t.endsWith(".shtml")?t.slice(0,-6):t}function xMt(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 SMt(e){return/data-sprinkle-autoopen\b/.test(e)}class TMt{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:HA(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 Hm=Tr("sprinkle-manager"),fde="slicc-open-sprinkles";class $Oe{fs;bridge;callbacks;availableSprinkles=new Map;openSprinkles=new Map;constructor(t,n,i){this.fs=t,this.bridge=new TMt(t,n,r=>this.close(r)),this.callbacks=i}async restoreOpenSprinkles(){try{const t=localStorage.getItem(fde);if(!t){for(const i of this.availableSprinkles.values())if(i.autoOpen)try{await this.open(i.name)}catch{Hm.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{Hm.warn("Failed to restore sprinkle",{name:i})}}catch{}}persistOpenSprinkles(){try{localStorage.setItem(fde,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),Hm.info("Auto-opened new sprinkle after install",{name:t.name})}catch{Hm.warn("Failed to auto-open new sprinkle",{name:t.name})}}async refresh(){this.availableSprinkles=await wMt(this.fs),Hm.info("Discovered sprinkles",{count:this.availableSprinkles.size})}async open(t,n){if(this.openSprinkles.has(t)){Hm.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 o=this.bridge.createAPI(t),c=new Nde(a,o);await c.render(r,t),this.openSprinkles.get(t).renderer=c,this.persistOpenSprinkles(),WIt(t),Hm.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(),Hm.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){Hm.warn("Cannot send to closed sprinkle",{name:t});return}this.bridge.pushUpdate(t,n),i.renderer.pushUpdate(n)}}const En=Tr("main");function CMt(){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 DOe(){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 jOe(e,t,n){const i=CMt();let r=0,a=!1;const o=()=>{r=0,a||i.hide()};window.addEventListener("dragenter",c=>{Fie(c.dataTransfer)&&(c.preventDefault(),r+=1,a||i.show("Drop .skill to install","Unpack into /workspace/skills/{name}."))}),window.addEventListener("dragover",c=>{Fie(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",o),window.addEventListener("blur",o),window.addEventListener("drop",async c=>{const l=y0t(c.dataTransfer);if(!l){o();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…",l.name);try{const s=await m0t(e,l);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 EMt(e){const{OffscreenClient:t}=await Tn(async()=>{const{OffscreenClient:f}=await import("./offscreen-client-B_ASD-T8.js");return{OffscreenClient:f}},[]),{VirtualFS:n}=await Tn(async()=>{const{VirtualFS:f}=await Promise.resolve().then(()=>r0t);return{VirtualFS:f}},void 0),i=new Wg(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),En.info("File browser wired to shared VFS (local IndexedDB)");const o=new BroadcastChannel("preview-vfs");o.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});o.postMessage({type:"preview-vfs-response",id:h,content:v})}catch(y){const v=y instanceof Error?y.message:String(y);v.includes("ENOENT")||En.error("Preview VFS read failed",{path:m,error:v}),o.postMessage({type:"preview-vfs-response",id:h,error:v})}})()};const c=DOe();jOe(a,c,async()=>{await i.panels.fileBrowser.refresh()});try{const{WasmShell:f}=await Tn(async()=>{const{WasmShell:b}=await Promise.resolve().then(()=>TOe);return{WasmShell:b}},void 0),{PanelCdpProxy:h,BrowserAPI:m}=await Tn(async()=>{const{PanelCdpProxy:b,BrowserAPI:w}=await import("./index-ChxPM3KL.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),En.info("Terminal mounted with shared VFS and BrowserAPI (CDP proxy)")}catch(f){En.warn("Failed to mount shell to terminal",f)}let l,s=new Set;const u=async f=>{r=f,l.selectedScoopJid=f.jid,i.panels.memory.setSelectedScoop(f.jid),i.setScoopSwitcherSelected?.(f.jid),i.panels.scoops.refreshScoops();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),l.isProcessing(f.jid)&&i.panels.chat.setProcessing(!0)};l=new t({onStatusChange:(f,h)=>{i.panels.scoops.updateScoopStatus(f,h),i.updateScoopSwitcherStatus?.(f,h),r?.jid===f&&(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,l.selectedScoopJid=f.jid,i.panels.memory.setSelectedScoop(f.jid))},onScoopListUpdate:()=>{const f=new Set(l.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=l.getScoops().find(g=>g.isCone);m&&(r=m,l.selectedScoopJid=m.jid,i.panels.memory.setSelectedScoop(m.jid))}},onIncomingMessage:(f,h)=>{if(r?.jid===f){const m=h.channel==="delegation"?`**[Instructions from sliccy]**
14419
+ `);this.messageQueues.set(t,[]);const s=c[c.length-1];this.lastAgentTimestamp.set(t,s.timestamp),await CN(`lastAgentTs_${t}`,s.timestamp),await this.sendPrompt(t,l,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);Zn.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();Zn.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);Zn.info("Orchestrator shutdown")}}const ROe=Tr("tray-follower");async function $Pt(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 qPt(t);return ROe.info("Follower tray attach response",{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),DPt(n)}function DPt(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 jPt(e){return nO(await rO(e,{action:"poll",controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function LPt(e){return nO(await rO(e,{action:"answer",controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function FPt(e){return nO(await rO(e,{action:"ice-candidate",controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function UPt(e){return nO(await rO(e,{action:"retry",controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function nO(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function qPt(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!BPt(n)){const i=t?t.slice(0,200):"(empty)";throw ROe.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 rO(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(!WPt(i))throw new Error(`Tray follower bootstrap returned an invalid response (${n.status})`);return i}function BPt(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"&&OOe(i.bootstrap):i.action==="fail"?(i.code==="INVALID_JOIN_CAPABILITY"||i.code==="TRAY_EXPIRED")&&typeof i.error=="string":!1}function WPt(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"&&OOe(t.bootstrap)&&Array.isArray(t.events)}function OOe(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 mi=Tr("tray-webrtc"),zPt="tray-control",GPt=250;class HPt{constructor(t){this.options=t,this.iceServers=t.iceServers,this.peerConnectionFactory=t.peerConnectionFactory??(()=>IOe(this.iceServers)),this.dataChannelLabel=t.dataChannelLabel??zPt}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 o=MOe(a);o&&this.options.sendControlMessage({type:"bootstrap.ice_candidate",controllerId:t.controllerId,bootstrapId:t.bootstrapId,candidate:o})}),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")&&(mi.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"):(mi.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"):(mi.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:POe(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){mi.warn("Failed to report tray bootstrap failure",{error:r instanceof Error?r.message:String(r)})}}}}class VPt{constructor(t){this.options=t,this.fetchImpl=t.fetchImpl??fetch,this.iceServers=t.iceServers,this.peerConnectionFactory=t.peerConnectionFactory??(()=>IOe(this.iceServers)),this.controllerIdFactory=t.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=t.sleep??(n=>new Promise(i=>setTimeout(i,n))),this.pollIntervalMs=t.pollIntervalMs??GPt}fetchImpl;peerConnectionFactory;controllerIdFactory;sleep;pollIntervalMs;iceServers;activePeer=null;stopped=!1;async start(){this.stopped=!1;const t=this.controllerIdFactory(),n=Date.now();Bo({state:"connecting",joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:n,lastError:null}),mi.info("Follower tray join starting",{joinUrl:this.options.joinUrl});let i=0;for(;;){ode(this.stopped),i++;let r;try{r=await $Pt({joinUrl:this.options.joinUrl,controllerId:t,runtime:this.options.runtime,fetchImpl:this.fetchImpl})}catch(a){const o=a instanceof Error?a.message:String(a);throw Bo({...Zg(),attachAttempts:i,lastError:o}),a}if(Bo({...Zg(),attachAttempts:i,lastAttachCode:r.code}),r.action==="wait"){const a=r.retryAfterMs??1e3;mi.info("Follower tray attach waiting",{attempt:i,code:r.code,retryAfterMs:a}),i%10===0&&mi.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 Bo({state:"error",joinUrl:this.options.joinUrl,trayId:null,error:a,lastPingTime:null,reconnectAttempts:0,attachAttempts:i,lastAttachCode:r.code,connectingSince:null,lastError:a}),mi.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 Bo({state:"connected",joinUrl:this.options.joinUrl,trayId:a.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:i,lastAttachCode:r.code,connectingSince:null,lastError:null}),mi.info("Follower tray connected",{trayId:a.trayId,controllerId:t}),a}catch(a){const o=a instanceof Error?a.message:String(a);throw Bo({state:"error",joinUrl:this.options.joinUrl,trayId:r.trayId,error:o,lastPingTime:null,reconnectAttempts:0,attachAttempts:i,lastAttachCode:r.code,connectingSince:null,lastError:o}),mi.warn("Follower tray bootstrap failed",{error:o}),a}}}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,Bo({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(ode(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 o=await jPt({joinUrl:this.options.joinUrl,controllerId:n,bootstrapId:r.bootstrapId,cursor:a,fetchImpl:this.fetchImpl});r=o.bootstrap,a=r.cursor;try{for(const c of o.events)if(c.type==="bootstrap.offer"){await this.activePeer.peer.setRemoteDescription(c.offer);const l=await this.activePeer.peer.createAnswer();await this.activePeer.peer.setLocalDescription(l),await LPt({joinUrl:this.options.joinUrl,controllerId:n,bootstrapId:r.bootstrapId,answer:POe(this.activePeer.peer.localDescription??l,"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 UPt({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")&&(mi.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?(mi.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?(mi.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 o=MOe(a);o&&FPt({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:n,candidate:o,fetchImpl:this.fetchImpl}).catch(c=>{mi.warn("Failed to send follower ICE candidate",{error:c instanceof Error?c.message:String(c)})})}),r}}function JPt(e,t){const n=t.baseDelayMs??1e3,i=t.backoffMultiplier??2,r=t.maxDelayMs??3e4,a=t.maxAttempts??10,o=t.sleep??e.sleep??(h=>new Promise(m=>setTimeout(m,h)));let c=!1,l=!1,s=null;const u={cancel(){c=!0,l=!1,s?.stop(),s=null},get reconnecting(){return l}},d=()=>{const h=new VPt({...e,sleep:o,onDisconnected:m=>{c||(mi.warn("Follower disconnected, starting reconnect loop",{reason:m}),p(m))}});return s=h,{manager:h,connectionPromise:h.start()}},p=async h=>{if(c||l)return;l=!0,s?.stop(),s=null;let m=0,g=n,y=h??"Unknown disconnect";for(;!c&&m<a&&(m++,t.onReconnecting?.(m),Bo({...Zg(),state:"reconnecting",error:null,reconnectAttempts:m}),mi.info("Reconnect attempt",{attempt:m,delay:g}),await o(g),!c);){let v=null;try{const b=d();v=b.manager;const w=await b.connectionPromise;if(c){v.stop();break}l=!1,Bo({...Zg(),state:"connected",joinUrl:e.joinUrl,trayId:w.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),mi.info("Reconnect successful",{attempt:m,trayId:w.trayId}),t.onConnected(w);return}catch(b){y=b instanceof Error?b.message:String(b),mi.warn("Reconnect attempt failed",{attempt:m,error:y}),v?.stop(),s=null}g=Math.min(g*i,r)}c||(l=!1,Bo({...Zg(),state:"error",error:`Reconnect failed after ${m} attempts: ${y}`,reconnectAttempts:m}),mi.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||mi.warn("Initial follower connection failed",{error:h instanceof Error?h.message:String(h)})}),u}function IOe(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 POe(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 MOe(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 ode(e){if(e)throw new Error("Tray follower stopped before WebRTC bootstrap completed")}const KC=64*1024;async function P8(e,t){try{switch(t.op){case"readFile":return await KPt(e,t.path,t.encoding);case"writeFile":return[await XPt(e,t.path,t.content,t.encoding)];case"stat":return[await ZPt(e,t.path)];case"readDir":return[await YPt(e,t.path)];case"mkdir":return[await QPt(e,t.path,t.recursive)];case"rm":return[await eMt(e,t.path,t.recursive)];case"exists":return[await tMt(e,t.path)];case"walk":return[await nMt(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(n){return[rMt(n)]}}async function KPt(e,t,n){if((n??"utf-8")==="utf-8"){const o=await e.readFile(t,{encoding:"utf-8"});return lde(o,"utf-8")}const r=await e.readFile(t,{encoding:"binary"}),a=iMt(r);return lde(a,"base64")}async function XPt(e,t,n,i){if(i==="base64"){const r=aMt(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:"void"}}}async function ZPt(e,t){return{ok:!0,data:{type:"stat",stat:await e.stat(t)}}}async function YPt(e,t){return{ok:!0,data:{type:"dirEntries",entries:await e.readDir(t)}}}async function QPt(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:"void"}}}async function eMt(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:"void"}}}async function tMt(e,t){return{ok:!0,data:{type:"exists",exists:await e.exists(t)}}}async function nMt(e,t){const n=[];for await(const i of e.walk(t))n.push(i);return{ok:!0,data:{type:"paths",paths:n}}}function lde(e,t){if(e.length<=KC)return[{ok:!0,data:{type:"file",content:e,encoding:t}}];const n=Math.ceil(e.length/KC),i=[];for(let r=0;r<n;r++){const a=r*KC,o=e.slice(a,a+KC);i.push({ok:!0,data:{type:"file",content:o,encoding:t},chunkIndex:r,totalChunks:n})}return i}function rMt(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 iMt(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function aMt(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 sMt{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 cde=Tr("data-channel-keepalive");class NOe{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++,cde.debug("Missed pong",{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){cde.warn("Channel declared dead",{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}}const Vc=Tr("tray-leader-sync");function oMt(e){return e?e.includes("standalone")?"standalone":e.includes("extension")?"extension":e.includes("electron")?"electron":"unknown":"unknown"}class lMt{constructor(t){this.options=t}followers=new Map;registry=new sMt;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=C0t(n),a=r.onMessage(l=>{this.handleFollowerMessage(t,l)}),o=new NOe({sendPing:()=>r.send({type:"ping"}),onDead:()=>{Vc.warn("Follower keepalive dead, removing follower",{bootstrapId:t}),this.removeFollower(t),this.options.onFollowerDead?.(t)}});o.start(),this.followers.set(t,{bootstrapId:t,sync:r,unsubscribe:a,keepalive:o,runtime:i?.runtime,connectedAt:i?.connectedAt,lastActivity:Date.now(),floatType:oMt(i?.runtime)}),Vc.info("Follower added to sync",{bootstrapId:t,followerCount:this.followers.size}),this.sendSnapshotToFollower(t);const c=this.registry.getEntries();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(),Vc.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();S0t(n.sync,i,r),Vc.debug("Snapshot sent to follower",{bootstrapId:t,messageCount:i.length})}handleFollowerMessage(t,n){switch(n.type){case"user_message":Vc.info("Follower user message received",{bootstrapId:t,messageId:n.messageId}),this.options.onFollowerMessage(n.text,n.messageId);break;case"abort":Vc.info("Follower abort received",{bootstrapId:t}),this.options.onFollowerAbort();break;case"request_snapshot":Vc.info("Follower snapshot request received",{bootstrapId:t}),this.sendSnapshotToFollower(t);break;case"targets.advertise":{Vc.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),Vc.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:o,params:c,sessionId:l}=n;r==="leader"?this.executeLocalCDP(i,a,o,c,l,t):this.forwardCDPRequest(i,r,a,o,c,l,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.registry.getEntries()};for(const i of this.followers.values())i.sync.send(n)}getTargets(){return this.registry.getEntries()}createRemoteTransport(t,n){const i={sendCDPRequest:(a,o,c,l)=>{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:o,params:c,sessionId:l})}},r=new g2e(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),Vc.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 o=this.followers.get(a);o&&t.push({runtimeId:r,bootstrapId:a,floatType:o.floatType,lastActivity:o.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,o){const c=this.followers.get(o);if(!c)return;const l=this.options.browserTransport;if(!l){c.sync.send({type:"cdp.response",requestId:t,error:"Leader has no browser transport"});return}try{const s=await l.send(i,r,a);TN(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,o,c){const l=this.runtimeToBootstrap.get(n),s=l?this.followers.get(l):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:o})}handleCDPResponse(t){const{requestId:n,result:i,error:r,chunkData:a,chunkIndex:o,totalChunks:c}=t,l=this.pendingCDPRoutes.get(n);if(!l)return;const s=Yj(this.cdpChunkBuffers,t);if(!s)return;if(this.pendingCDPRoutes.delete(n),l.requesterBootstrapId==="__leader__"){for(const d of this.remoteTransports.values())d.handleResponse(n,s.result,s.error);return}const u=this.followers.get(l.requesterBootstrapId);u&&TN(u.sync,n,s.result,s.error)}handleCDPEvent(t,n,i,r){let a;for(const[c,l]of this.runtimeToBootstrap)if(l===t){a=c;break}if(!a)return;const o=`${a}:`;for(const[c,l]of this.remoteTransports)c.startsWith(o)&&l.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((o,c)=>{this.tabOpenResolvers.set(a,{resolve:o,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(o){r.sync.send({type:"tab.open.error",requestId:t,error:o instanceof Error?o.message:String(o)})}}forwardTabOpen(t,n,i,r){const a=this.runtimeToBootstrap.get(n),o=a?this.followers.get(a):void 0,c=this.followers.get(r);if(!o){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}),o.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 o=await P8(a,n);for(const c of o)r.sync.send({type:"fs.response",requestId:t,response:c})}forwardFsRequest(t,n,i,r){const a=this.runtimeToBootstrap.get(n),o=a?this.followers.get(a):void 0,c=this.followers.get(r);if(!o){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}),o.sync.send({type:"fs.request",requestId:t,request:i})}handleFsResponse(t,n){const i=this.pendingFsRoutes.get(t);if(!i){const o=this.fsResolvers.get(t);if(o){o.responses.push(n);const c=n.ok&&n.totalChunks||1;o.responses.length>=c&&(this.fsResolvers.delete(t),o.resolve(o.responses))}return}if(i.requesterBootstrapId==="__leader__"){const o=this.fsResolvers.get(t);if(o){o.responses.push(n);const c=n.ok&&n.totalChunks||1;o.responses.length>=c&&(this.fsResolvers.delete(t),this.pendingFsRoutes.delete(t),o.resolve(o.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 o=this.options.vfs;return o?P8(o,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((o,c)=>{this.fsResolvers.set(a,{resolve:o,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 Ra=Tr("tray-follower-sync");class cMt{constructor(t,n={}){this.options=n,this.sync=E0t(t),this.unsubscribe=this.sync.onMessage(i=>{this.handleLeaderMessage(i)}),this.keepalive=new NOe({sendPing:()=>this.sync.send({type:"ping"}),onDead:()=>{Ra.warn("Leader keepalive dead, cleaning up"),this.handleDisconnect("Keepalive timeout — leader not responding"),this.options.onDead?.()}}),this.keepalive.start(),t.addEventListener("close",()=>{Ra.warn("Data channel closed"),this.handleDisconnect("Data channel closed")}),t.addEventListener("error",()=>{Ra.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}),Ra.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"}),Ra.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(),Ra.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=Zg();Bo({...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":Ra.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=T0t(this.snapshotChunkBuffer,t);this.snapshotChunkBuffer=n.buffer,n.result&&(Ra.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),Ra.debug("Skipping own message echo",{messageId:t.messageId});break}Ra.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":Ra.warn("Error from leader",{error:t.error}),this.emitEvent({type:"error",error:t.error});break;case"targets.registry":Ra.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:o}=t;this.executeLocalCDP(n,i,r,a,o);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(),Zdt(Date.now());break}}}emitEvent(t){for(const n of this.eventListeners)try{n(t)}catch(i){Ra.error("Listener error",{eventType:t.type,error:i instanceof Error?i.message:String(i)})}}createRemoteTransport(t,n){const i={sendCDPRequest:(a,o,c,l)=>{this.sync.send({type:"cdp.request",requestId:a,targetRuntimeId:t,localTargetId:n,method:o,params:c,sessionId:l})}},r=new g2e(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 o=this.options.browserTransport;if(!o){this.sync.send({type:"cdp.response",requestId:t,error:"Follower has no browser transport"});return}try{const c=await o.send(i,r,a);if(i==="Target.attachToTarget"&&c.sessionId){const l=c.sessionId;this.remoteCDPSessions.add(l),this.setupCDPEventForwarding(o,l),Ra.debug("Tracking remote CDP session",{remoteSessionId:l})}i==="Target.detachFromTarget"&&a&&this.remoteCDPSessions.has(a)&&(this.remoteCDPSessions.delete(a),Ra.debug("Removed remote CDP session on detach",{sessionId:a})),TN(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=o=>{if(o.sessionId!==n||!this.remoteCDPSessions.has(n))return;const{sessionId:c,...l}=o;this.sync.send({type:"cdp.event",method:r,params:l,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=Yj(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 P8(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 uMt="electron-overlay",ude="/electron",dMt="slicc-electron-overlay:set-tab";function pMt(e,t){if(t)return"extension";try{const n=new URL(e);return hMt(n)?"electron-overlay":"standalone"}catch{return"standalone"}}function fMt(e,t){return e==="electron-overlay"||e==="standalone"&&t}function dde(e){try{const n=new URL(e).searchParams.get("tab");return n&&Pbt(n)?n:wie}catch{return wie}}function hMt(e){return e.pathname===ude||e.pathname===`${ude}/`||e.searchParams.get("runtime")===uMt}function mMt(e){const t=new URL(e);return`${t.protocol==="https:"?"wss:":"ws:"}//${t.host}/licks-ws`}function gMt(e,t){return`${new URL(e).origin}/webhooks/${t}`}function yMt(e,t){const n=e.replace(/\/+$/,""),i=t.replace(/^\/+/,"");return`${n}/${i}`}function vMt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type===dMt}const bMt=["/shared/sprinkles"];async function wMt(e){const t=new Map;for(const n of bMt)await e.exists(n)&&await pde(e,n,t);return await pde(e,"/",t),t}async function pde(e,t,n){for await(const i of e.walk(t)){if(!i.endsWith(".shtml"))continue;const r=_Mt(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:xMt(a,r),autoOpen:SMt(a)})}}}function _Mt(e){const t=e.split("/").pop()??e;return t.endsWith(".shtml")?t.slice(0,-6):t}function xMt(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 SMt(e){return/data-sprinkle-autoopen\b/.test(e)}class TMt{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:HA(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 Hm=Tr("sprinkle-manager"),fde="slicc-open-sprinkles";class $Oe{fs;bridge;callbacks;availableSprinkles=new Map;openSprinkles=new Map;constructor(t,n,i){this.fs=t,this.bridge=new TMt(t,n,r=>this.close(r)),this.callbacks=i}async restoreOpenSprinkles(){try{const t=localStorage.getItem(fde);if(!t){for(const i of this.availableSprinkles.values())if(i.autoOpen)try{await this.open(i.name)}catch{Hm.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{Hm.warn("Failed to restore sprinkle",{name:i})}}catch{}}persistOpenSprinkles(){try{localStorage.setItem(fde,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),Hm.info("Auto-opened new sprinkle after install",{name:t.name})}catch{Hm.warn("Failed to auto-open new sprinkle",{name:t.name})}}async refresh(){this.availableSprinkles=await wMt(this.fs),Hm.info("Discovered sprinkles",{count:this.availableSprinkles.size})}async open(t,n){if(this.openSprinkles.has(t)){Hm.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 o=this.bridge.createAPI(t),c=new Nde(a,o);await c.render(r,t),this.openSprinkles.get(t).renderer=c,this.persistOpenSprinkles(),WIt(t),Hm.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(),Hm.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){Hm.warn("Cannot send to closed sprinkle",{name:t});return}this.bridge.pushUpdate(t,n),i.renderer.pushUpdate(n)}}const En=Tr("main");function CMt(){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 DOe(){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 jOe(e,t,n){const i=CMt();let r=0,a=!1;const o=()=>{r=0,a||i.hide()};window.addEventListener("dragenter",c=>{Fie(c.dataTransfer)&&(c.preventDefault(),r+=1,a||i.show("Drop .skill to install","Unpack into /workspace/skills/{name}."))}),window.addEventListener("dragover",c=>{Fie(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",o),window.addEventListener("blur",o),window.addEventListener("drop",async c=>{const l=y0t(c.dataTransfer);if(!l){o();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…",l.name);try{const s=await m0t(e,l);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 EMt(e){const{OffscreenClient:t}=await Tn(async()=>{const{OffscreenClient:f}=await import("./offscreen-client-B_X62xJc.js");return{OffscreenClient:f}},[]),{VirtualFS:n}=await Tn(async()=>{const{VirtualFS:f}=await Promise.resolve().then(()=>r0t);return{VirtualFS:f}},void 0),i=new Wg(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),En.info("File browser wired to shared VFS (local IndexedDB)");const o=new BroadcastChannel("preview-vfs");o.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});o.postMessage({type:"preview-vfs-response",id:h,content:v})}catch(y){const v=y instanceof Error?y.message:String(y);v.includes("ENOENT")||En.error("Preview VFS read failed",{path:m,error:v}),o.postMessage({type:"preview-vfs-response",id:h,error:v})}})()};const c=DOe();jOe(a,c,async()=>{await i.panels.fileBrowser.refresh()});try{const{WasmShell:f}=await Tn(async()=>{const{WasmShell:b}=await Promise.resolve().then(()=>TOe);return{WasmShell:b}},void 0),{PanelCdpProxy:h,BrowserAPI:m}=await Tn(async()=>{const{PanelCdpProxy:b,BrowserAPI:w}=await import("./index-CEcKH6Ga.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),En.info("Terminal mounted with shared VFS and BrowserAPI (CDP proxy)")}catch(f){En.warn("Failed to mount shell to terminal",f)}let l,s=new Set;const u=async f=>{r=f,l.selectedScoopJid=f.jid,i.panels.memory.setSelectedScoop(f.jid),i.setScoopSwitcherSelected?.(f.jid),i.panels.scoops.refreshScoops();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),l.isProcessing(f.jid)&&i.panels.chat.setProcessing(!0)};l=new t({onStatusChange:(f,h)=>{i.panels.scoops.updateScoopStatus(f,h),i.updateScoopSwitcherStatus?.(f,h),r?.jid===f&&(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,l.selectedScoopJid=f.jid,i.panels.memory.setSelectedScoop(f.jid))},onScoopListUpdate:()=>{const f=new Set(l.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=l.getScoops().find(g=>g.isCone);m&&(r=m,l.selectedScoopJid=m.jid,i.panels.memory.setSelectedScoop(m.jid))}},onIncomingMessage:(f,h)=>{if(r?.jid===f){const m=h.channel==="delegation"?`**[Instructions from sliccy]**
14394
14420
 
14395
14421
  ${h.content}`:h.content;i.panels.chat.addUserMessage(m)}},onReady:async()=>{try{En.info("Offscreen engine ready, scoop count:",l.getScoops().length),window.localStorage.getItem(A0)&&chrome.runtime.sendMessage({source:"panel",payload:{type:"refresh-tray-runtime"}}).catch(()=>{});const f=r??l.getScoops().find(h=>h.isCone)??l.getScoops()[0];f&&(r=f,l.selectedScoopJid=f.jid,await u(f))}catch(f){En.error("Failed to initialize on ready",{error:f instanceof Error?f.message:String(f)})}}}),l.setLocalFS(a);const d=l.createAgentHandle();i.panels.chat.setAgent(d),i.panels.scoops.setOrchestrator(l),i.panels.memory.setOrchestrator(l),i.setScoopSwitcherOrchestrator?.(l),i.onScoopSelect=u,i.onModelChange=f=>{localStorage.setItem("selected-model",f),l.updateModel()},i.onClearChat=async()=>{const f=l.getScoops();for(const h of f){const m=h.isCone?"session-cone":`session-${h.folder}`;await i.panels.chat.deleteSessionById(m)}l.clearAllMessages()},i.onClearFilesystem=async()=>{l.clearFilesystem()},i.panels.chat.onInlineSprinkleLick=(f,h)=>{l.sendSprinkleLick("inline",{action:f,data:h})};const p=new $Oe(a,f=>{f.type==="sprinkle"&&l.sendSprinkleLick(f.sprinkleName,f.body)},{addSprinkle:(f,h,m,g)=>i.addSprinkle(f,h,m,g),removeSprinkle:f=>i.removeSprinkle(f)});window.__slicc_sprinkleManager=p,l.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(),En.info("SprinkleManager initialized (extension mode)"),l.requestState(),En.info("Extension UI connected to offscreen agent engine"),xOe().catch(()=>{})}async function AMt(){ept();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(()=>En.info("Preview SW registered")).catch(R=>En.error("Preview SW registration failed — preview feature will not work",R)),Qxe();let t=jv();const n=GM(window.localStorage);if(!t&&!n){const R=window.location.port==="5710"||window.location.port==="3000"||window.location.port==="";await wA({preferTrayJoin:!R}),t=jv()}const i=!t&&GM(window.localStorage),r=typeof chrome<"u"&&!!chrome?.runtime?.id,a=pMt(window.location.href,r);if(a==="extension")return EMt(e);const o=new Wg(e,a==="electron-overlay");if(a==="electron-overlay"){const R=dde(window.location.href);o.setActiveTab(R);const D=document.createElement("style");D.id="slicc-electron-overlay-runtime-style",D.textContent=`
14396
14422
  #app > .tab-bar { display: none !important; }
@@ -14402,7 +14428,7 @@ ${h.content}`:h.content;i.panels.chat.addUserMessage(m)}},onReady:async()=>{try{
14402
14428
  }
14403
14429
  `,document.head.appendChild(D),window.addEventListener("message",F=>{F.source===window.parent&&vMt(F.data)&&o.setActiveTab(dde(`http://localhost/?tab=${F.data.tab??""}`))})}const c=DOe();await o.panels.chat.initSession("session-cone"),En.info("Session initialized");const l=new _0t,s=new Set,u=R=>{En.debug("Emit to UI",{type:R.type,listenerCount:s.size});for(const D of s)try{D(R)}catch(F){En.error("Listener error",{eventType:R.type,error:F instanceof Error?F.message:String(F)})}};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(R){let D=f.get(R);return D||(D=[],f.set(R,D)),D}function g(R,D){const F=m(R);let G=p.get(R);if(G){const ee=F.find(_e=>_e.id===G);if(ee)return ee}G=`scoop-${R}-${h()}`,p.set(R,G);const J=y.getScoops().find(ee=>ee.jid===R),ae=J?.isCone?"cone":J?.name??"unknown",le={id:G,role:"assistant",content:"",timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:ae,channel:D};return F.push(le),d?.jid===R&&u({type:"message_start",messageId:G}),le}const y=new NPt(o.getIframeContainer(),{onResponse:(R,D,F)=>{const G=g(R);F?G.content+=D:(G.content=D,G.isStreaming=!1),d?.jid===R&&(u({type:"content_delta",messageId:G.id,text:D}),F||u({type:"content_done",messageId:G.id}))},onResponseDone:R=>{const D=m(R),F=p.get(R);if(F){const G=D.find(H=>H.id===F);G&&(G.isStreaming=!1),d?.jid===R&&u({type:"content_done",messageId:F}),p.delete(R)}},onSendMessage:(R,D)=>{En.debug("Send message requested",{targetJid:R,textLength:D.length});const F=`msg-${h()}`,G={id:F,chatJid:R,senderId:"assistant",senderName:"sliccy",content:D,timestamp:new Date().toISOString(),fromAssistant:!0,channel:"web"};y.handleMessage(G),m(R).push({id:F,role:"assistant",content:D,timestamp:Date.now()}),d?.jid===R&&(u({type:"message_start",messageId:F}),u({type:"content_delta",messageId:F,text:D}),u({type:"content_done",messageId:F}))},onStatusChange:(R,D)=>{if(o.panels.scoops.updateScoopStatus(R,D),o.updateScoopSwitcherStatus?.(R,D),d?.jid===R){if(D==="processing")o.panels.chat.setProcessing(!0);else if(D==="ready"){o.panels.chat.setProcessing(!1);const F=p.get(R)??`done-${R}-${h()}`;p.delete(R),u({type:"turn_end",messageId:F})}}},onError:(R,D)=>{En.error("Scoop error",{scoopJid:R,error:D}),d?.jid===R&&u({type:"error",error:D})},getBrowserAPI:()=>l,onToolStart:(R,D,F)=>{if(D==="bash"&&o.openTerminal(),new Set(["send_message","list_scoops","list_tasks"]).has(D))return;const H=g(R);H.toolCalls||(H.toolCalls=[]),H.toolCalls.push({id:h(),name:D,input:F}),d?.jid===R&&u({type:"tool_use_start",messageId:H.id,toolName:D,toolInput:F})},onToolEnd:(R,D,F,G)=>{if(new Set(["send_message","list_scoops","list_tasks"]).has(D))return;const J=m(R),ae=p.get(R);if(ae){const le=J.find(ee=>ee.id===ae);if(le?.toolCalls){const ee=[...le.toolCalls].reverse().find(_e=>_e.name===D&&_e.result===void 0);ee&&(ee.result=F,ee.isError=G)}}d?.jid===R&&ae&&u({type:"tool_result",messageId:ae,toolName:D,result:F,isError:G})},onToolUI:(R,D,F,G)=>{const H=p.get(R);H?u({type:"tool_ui",messageId:H,toolName:D,requestId:F,html:G}):En.warn("Cannot emit tool_ui - no message ID for scoop",{scoopJid:R,requestId:F})},onToolUIDone:(R,D)=>{const F=p.get(R);F&&u({type:"tool_ui_done",messageId:F,requestId:D})},onIncomingMessage:(R,D)=>{const F={id:D.id,role:"user",content:D.channel==="delegation"?`**[Instructions from sliccy]**
14404
14430
 
14405
- ${D.content}`:D.content,timestamp:new Date(D.timestamp).getTime(),source:D.channel==="delegation"?"delegation":void 0,channel:D.channel};m(R).push(F),d?.jid===R&&(u({type:"message_start",messageId:D.id}),u({type:"content_delta",messageId:D.id,text:F.content}),u({type:"content_done",messageId:D.id}))}});await y.init(),o.panels.scoops.setOrchestrator(y),o.panels.memory.setOrchestrator(y),o.setScoopSwitcherOrchestrator?.(y);const v=y.getSharedFS();if(v){o.panels.fileBrowser.setFs(v),En.info("File browser wired to shared VFS");const R=new BroadcastChannel("preview-vfs");R.onmessage=D=>{if(D.data?.type!=="preview-vfs-read")return;const{id:F,path:G,asText:H}=D.data;(async()=>{try{const J=H?"utf-8":"binary",ae=await v.readFile(G,{encoding:J});R.postMessage({type:"preview-vfs-response",id:F,content:ae})}catch(J){const ae=J instanceof Error?J.message:String(J);ae.includes("ENOENT")||En.error("Preview VFS read failed",{path:G,error:ae}),R.postMessage({type:"preview-vfs-response",id:F,error:ae})}})()},jOe(v,(D,F)=>{F==="error"?En.warn("Dropped skill install failed",{message:D}):En.info("Dropped skill installed",{message:D}),c(D,F)},async()=>{await o.panels.fileBrowser.refresh()});try{const{WasmShell:D}=await Tn(async()=>{const{WasmShell:G}=await Promise.resolve().then(()=>TOe);return{WasmShell:G}},void 0),F=new D({fs:v,browserAPI:l});await o.panels.terminal.mountShell(F),En.info("Terminal mounted with shared VFS");try{const{BshWatchdog:G}=await Tn(async()=>{const{BshWatchdog:J}=await import("./bsh-watchdog-uk_ACjOz.js");return{BshWatchdog:J}},[]),H=new G({transport:l.getTransport(),fs:v,execute:J=>F.executeScriptFile(J)});H.start(),window.addEventListener("beforeunload",()=>H.stop(),{once:!0}),En.info("BSH navigation watchdog started")}catch(G){En.warn("Failed to start BSH watchdog",G)}}catch(D){En.warn("Failed to mount shell to terminal",D)}}const b=y.getScoops(),w=b.some(R=>R.isCone);if(i)En.info("Skipping local cone bootstrap while joining a tray without a configured provider");else if(!w)d=await o.panels.scoops.createScoop("Cone",!0),En.info("Created cone");else{const D=new URLSearchParams(window.location.search).get("scoop");if(D){const F=b.find(G=>G.folder===D);F?(d=F,En.info("Restored scoop from URL",{folder:D})):d=b.find(G=>G.isCone)??b[0]}else d=b.find(F=>F.isCone)??b[0]}d&&o.panels.memory.setSelectedScoop(d.jid);let _=null;const T={sendMessage(R,D){if(!d){u({type:"error",error:"No scoop selected"});return}const F={id:D??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:d.jid,senderId:"user",senderName:"User",content:R,timestamp:new Date().toISOString(),fromAssistant:!1,channel:"web"};m(d.jid).push({id:F.id,role:"user",content:R,timestamp:Date.now()}),_?.broadcastUserMessage(R,F.id),y.handleMessage(F),y.createScoopTab(d.jid)},onEvent(R){return s.add(R),()=>s.delete(R)},stop(){d&&(y.stopScoop(d.jid),y.clearQueuedMessages(d.jid).catch(R=>{En.error("Failed to clear queued messages on stop",{error:R instanceof Error?R.message:String(R)})}))}};o.panels.chat.setAgent(T),o.panels.chat.setDeleteQueuedMessageCallback(R=>{if(d){y.deleteQueuedMessage(d.jid,R).catch(F=>{En.error("Failed to delete queued message",{messageId:R,error:F instanceof Error?F.message:String(F)})});const D=f.get(d.jid);if(D){const F=D.findIndex(G=>G.id===R);F!==-1&&D.splice(F,1)}}}),En.info("Cone agent handle wired to chat UI");const{getLickManager:E}=await Tn(async()=>{const{getLickManager:R}=await Promise.resolve().then(()=>MPt);return{getLickManager:R}},void 0),M=E();await M.init(),y.setLickManager(M);const $=R=>{const D=R.type==="webhook",F=R.type==="sprinkle",G=D?R.webhookName:F?R.sprinkleName:R.cronName,H=D?R.webhookId:F?R.sprinkleName:R.cronId,J=R.type;En.debug("Lick event",{type:R.type,name:G,targetScoop:R.targetScoop});const ae=y.getScoops();let le;if(F||!R.targetScoop?le=ae.find(ee=>ee.isCone):le=ae.find(ee=>ee.name===R.targetScoop||ee.folder===R.targetScoop||ee.folder===`${R.targetScoop}-scoop`),le){const ee=`${J}-${H}-${Date.now()}`,ue=`[${D?"Webhook Event":F?"Sprinkle Event":"Cron Event"}: ${G}]
14431
+ ${D.content}`:D.content,timestamp:new Date(D.timestamp).getTime(),source:D.channel==="delegation"?"delegation":void 0,channel:D.channel};m(R).push(F),d?.jid===R&&(u({type:"message_start",messageId:D.id}),u({type:"content_delta",messageId:D.id,text:F.content}),u({type:"content_done",messageId:D.id}))}});await y.init(),o.panels.scoops.setOrchestrator(y),o.panels.memory.setOrchestrator(y),o.setScoopSwitcherOrchestrator?.(y);const v=y.getSharedFS();if(v){o.panels.fileBrowser.setFs(v),En.info("File browser wired to shared VFS");const R=new BroadcastChannel("preview-vfs");R.onmessage=D=>{if(D.data?.type!=="preview-vfs-read")return;const{id:F,path:G,asText:H}=D.data;(async()=>{try{const J=H?"utf-8":"binary",ae=await v.readFile(G,{encoding:J});R.postMessage({type:"preview-vfs-response",id:F,content:ae})}catch(J){const ae=J instanceof Error?J.message:String(J);ae.includes("ENOENT")||En.error("Preview VFS read failed",{path:G,error:ae}),R.postMessage({type:"preview-vfs-response",id:F,error:ae})}})()},jOe(v,(D,F)=>{F==="error"?En.warn("Dropped skill install failed",{message:D}):En.info("Dropped skill installed",{message:D}),c(D,F)},async()=>{await o.panels.fileBrowser.refresh()});try{const{WasmShell:D}=await Tn(async()=>{const{WasmShell:G}=await Promise.resolve().then(()=>TOe);return{WasmShell:G}},void 0),F=new D({fs:v,browserAPI:l});await o.panels.terminal.mountShell(F),En.info("Terminal mounted with shared VFS");try{const{BshWatchdog:G}=await Tn(async()=>{const{BshWatchdog:J}=await import("./bsh-watchdog-ClU8MZGz.js");return{BshWatchdog:J}},[]),H=new G({transport:l.getTransport(),fs:v,execute:J=>F.executeScriptFile(J)});H.start(),window.addEventListener("beforeunload",()=>H.stop(),{once:!0}),En.info("BSH navigation watchdog started")}catch(G){En.warn("Failed to start BSH watchdog",G)}}catch(D){En.warn("Failed to mount shell to terminal",D)}}const b=y.getScoops(),w=b.some(R=>R.isCone);if(i)En.info("Skipping local cone bootstrap while joining a tray without a configured provider");else if(!w)d=await o.panels.scoops.createScoop("Cone",!0),En.info("Created cone");else{const D=new URLSearchParams(window.location.search).get("scoop");if(D){const F=b.find(G=>G.folder===D);F?(d=F,En.info("Restored scoop from URL",{folder:D})):d=b.find(G=>G.isCone)??b[0]}else d=b.find(F=>F.isCone)??b[0]}d&&o.panels.memory.setSelectedScoop(d.jid);let _=null;const T={sendMessage(R,D){if(!d){u({type:"error",error:"No scoop selected"});return}const F={id:D??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:d.jid,senderId:"user",senderName:"User",content:R,timestamp:new Date().toISOString(),fromAssistant:!1,channel:"web"};m(d.jid).push({id:F.id,role:"user",content:R,timestamp:Date.now()}),_?.broadcastUserMessage(R,F.id),y.handleMessage(F),y.createScoopTab(d.jid)},onEvent(R){return s.add(R),()=>s.delete(R)},stop(){d&&(y.stopScoop(d.jid),y.clearQueuedMessages(d.jid).catch(R=>{En.error("Failed to clear queued messages on stop",{error:R instanceof Error?R.message:String(R)})}))}};o.panels.chat.setAgent(T),o.panels.chat.setDeleteQueuedMessageCallback(R=>{if(d){y.deleteQueuedMessage(d.jid,R).catch(F=>{En.error("Failed to delete queued message",{messageId:R,error:F instanceof Error?F.message:String(F)})});const D=f.get(d.jid);if(D){const F=D.findIndex(G=>G.id===R);F!==-1&&D.splice(F,1)}}}),En.info("Cone agent handle wired to chat UI");const{getLickManager:E}=await Tn(async()=>{const{getLickManager:R}=await Promise.resolve().then(()=>MPt);return{getLickManager:R}},void 0),M=E();await M.init(),y.setLickManager(M);const $=R=>{const D=R.type==="webhook",F=R.type==="sprinkle",G=D?R.webhookName:F?R.sprinkleName:R.cronName,H=D?R.webhookId:F?R.sprinkleName:R.cronId,J=R.type;En.debug("Lick event",{type:R.type,name:G,targetScoop:R.targetScoop});const ae=y.getScoops();let le;if(F||!R.targetScoop?le=ae.find(ee=>ee.isCone):le=ae.find(ee=>ee.name===R.targetScoop||ee.folder===R.targetScoop||ee.folder===`${R.targetScoop}-scoop`),le){const ee=`${J}-${H}-${Date.now()}`,ue=`[${D?"Webhook Event":F?"Sprinkle Event":"Cron Event"}: ${G}]
14406
14432
  \`\`\`json
14407
14433
  ${JSON.stringify(R.body,null,2)}
14408
14434
  \`\`\``,te={id:ee,chatJid:le.jid,senderId:J,senderName:`${J}:${G}`,content:ue,timestamp:R.timestamp,fromAssistant:!1,channel:J};m(le.jid).push({id:ee,role:"user",content:ue,timestamp:Date.now(),source:"lick",channel:J}),d?.jid===le.jid&&o.panels.chat.addLickMessage(ee,ue,J),En.info("Routing lick to scoop",{type:J,name:G,scoopJid:le.jid}),y.handleMessage(te)}else En.warn("Lick target scoop not found",{targetScoop:R.targetScoop})};M.setEventHandler($),o.panels.chat.onInlineSprinkleLick=(R,D)=>{const F={type:"sprinkle",sprinkleName:"inline",targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:R,data:D}};$(F)};let P=null;if(v){if(P=new $Oe(v,$,{addSprinkle:(R,D,F,G)=>o.addSprinkle(R,D,F,G),removeSprinkle:R=>o.removeSprinkle(R)}),window.__slicc_sprinkleManager=P,await P.refresh(),o.onSprinkleClose=R=>P.close(R),o.getAvailableSprinkles=()=>{const R=new Set(P.opened());return P.available().filter(D=>!R.has(D.name)).map(D=>({name:D.name,title:D.title}))},o.onOpenSprinkle=(R,D)=>P.open(R,D),o.updateAddButtons(),!localStorage.getItem("slicc-welcomed")&&P.available().some(R=>R.name==="welcome"))try{await P.open("welcome"),localStorage.setItem("slicc-welcomed","1")}catch(R){En.warn("Failed to open welcome sprinkle",R)}await P.restoreOpenSprinkles(),En.info("SprinkleManager initialized")}const A=()=>{const R=mMt(window.location.href),D=new WebSocket(R);D.onopen=()=>{En.info("Lick WebSocket connected")},D.onmessage=async F=>{try{const G=JSON.parse(F.data);if(G.requestId){let H;try{switch(G.type){case"list_webhooks":H={type:"response",requestId:G.requestId,data:M.listWebhooks()};break;case"create_webhook":{const J=await M.createWebhook(G.name||"default",G.scoop,G.filter),ae=u3().session,le=ae?.webhookUrl?yMt(ae.webhookUrl,J.id):gMt(window.location.href,J.id);H={type:"response",requestId:G.requestId,data:{...J,url:le}};break}case"delete_webhook":{H=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":H={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);H={type:"response",requestId:G.requestId,data:J};break}case"delete_crontask":{H=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=u3();H={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:H={type:"response",requestId:G.requestId,error:`Unknown request type: ${G.type}`}}}catch(J){H={type:"response",requestId:G.requestId,error:J instanceof Error?J.message:String(J)}}D.send(JSON.stringify(H));return}G.type==="webhook_event"&&M.handleWebhookEvent(G.webhookId,G.headers,G.body)}catch(G){En.error("Failed to process lick message",{error:G instanceof Error?G.message:String(G)})}},D.onclose=()=>{En.warn("Lick WebSocket disconnected, reconnecting in 3s..."),setTimeout(A,3e3)},D.onerror=F=>{En.error("Lick WebSocket error",{error:String(F)})}};A(),o.onModelChange=R=>{localStorage.setItem("selected-model",R),y.updateModel()},o.onClearChat=async()=>{await y.clearAllMessages(),f.clear()},o.onClearFilesystem=async()=>{await y.resetFilesystem()};const N=async R=>{En.info("Scoop selected",{jid:R.jid,name:R.name}),d=R,y.createScoopTab(R.jid),o.panels.memory.setSelectedScoop(R.jid);const D=R.isCone?"session-cone":`session-${R.folder}`,F=f.get(R.jid),G=R.isCone?void 0:R.name;if(F&&F.length>0)await o.panels.chat.switchToContext(D,!R.isCone,G),o.panels.chat.loadMessages(F);else if(await o.panels.chat.switchToContext(D,!R.isCone,G),o.panels.chat.getMessages().length===0){const H=await y.getMessagesForScoop(R.jid);for(const J of H){const ae=J.channel==="webhook"||J.channel==="cron",le=J.channel==="delegation";if(ae){const ee={id:J.id,role:"user",content:J.content,timestamp:new Date(J.timestamp).getTime(),source:"lick",channel:J.channel};m(R.jid).push(ee),o.panels.chat.addUserMessage(J.content)}else if(le){const ee={id:J.id,role:"user",content:`**[Instructions from sliccy]**