sliccy 1.49.0 → 1.51.0
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.
- package/dist/ui/assets/{index-VksNau8J.js → index-BJhsq921.js} +21 -21
- package/dist/ui/assets/lick-manager-BYt1_XLw.js +1 -0
- package/dist/ui/assets/provider-settings-Aax0EzI-.js +1 -0
- package/dist/ui/assets/{provider-settings-B501vrrq.js → provider-settings-Cb1U9RA_.js} +1 -1
- package/dist/ui/assets/providers-43KOjQlK.js +1 -0
- package/dist/ui/assets/shell-xFrhOqcd.js +1 -0
- package/dist/ui/assets/sprinkle-renderer-DMzFY2-1.js +1 -0
- package/dist/ui/index.html +2 -2
- package/dist/ui/packages/webapp/index.html +2 -2
- package/package.json +1 -1
- package/dist/ui/assets/lick-manager-CMMQIB6z.js +0 -1
- package/dist/ui/assets/provider-settings-DS-KZ0__.js +0 -1
- package/dist/ui/assets/providers-V-_SBYNl.js +0 -1
- package/dist/ui/assets/shell-QbXxTSCK.js +0 -1
- package/dist/ui/assets/sprinkle-renderer-4aW_Vd0i.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/sql-wasm-CzNEXo5c.js","assets/chunk-zsgVPwQN.js","assets/__vite-browser-external-03xtmW8y.js","assets/pyodide-BnfPrtlN.js","assets/preload-helper-ca-nBW7U.js","assets/es--3J5TmQH.js","assets/pako-Bt_k3edT.js","assets/dist-D_HlTg57.js","assets/provider-settings-
|
|
2
|
-
import{o as e,t}from"./chunk-zsgVPwQN.js";import{t as n}from"./logger-B-No_qN_.js";import{c as r,f as i,h as a,i as o,l as s,m as c,n as l,o as u,p as d,r as f,s as p,t as m,u as h,v as g,y as _}from"./tray-follower-status-BlQSlF6m.js";import{t as v}from"./preload-helper-ca-nBW7U.js";import{A as y,
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/sql-wasm-CzNEXo5c.js","assets/chunk-zsgVPwQN.js","assets/__vite-browser-external-03xtmW8y.js","assets/pyodide-BnfPrtlN.js","assets/preload-helper-ca-nBW7U.js","assets/es--3J5TmQH.js","assets/pako-Bt_k3edT.js","assets/dist-D_HlTg57.js","assets/provider-settings-Aax0EzI-.js","assets/provider-settings-Cb1U9RA_.js","assets/env-api-keys-DlVZ9FrG.js","assets/simple-options-FPdEz6rB.js","assets/json-parse-JW3qhabb.js","assets/tray-follower-status-BlQSlF6m.js","assets/logger-B-No_qN_.js","assets/providers-43KOjQlK.js","assets/skills-B2ove-_7.js","assets/constants-DzDPiuHe.js","assets/skills-AKjvBI03.js","assets/fs-BQWb1K18.js","assets/xterm-BmfB5bmM.css","assets/offscreen-client-B8UaOgaJ.js","assets/cdp-Bzco6_uI.js","assets/cost-command-BK0NsK_J.js","assets/bsh-watchdog-2ucB7RyN.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{o as e,t}from"./chunk-zsgVPwQN.js";import{t as n}from"./logger-B-No_qN_.js";import{c as r,f as i,h as a,i as o,l as s,m as c,n as l,o as u,p as d,r as f,s as p,t as m,u as h,v as g,y as _}from"./tray-follower-status-BlQSlF6m.js";import{t as v}from"./preload-helper-ca-nBW7U.js";import{A as y,C as b,D as x,O as S,S as C,_ as w,b as T,c as E,g as D,j as O,k,m as A,n as ee,o as j,r as te,s as ne,v as re,y as ie}from"./provider-settings-Cb1U9RA_.js";import{f as M,l as N,p as P,s as ae,u as F}from"./constants-DzDPiuHe.js";import{a as I,i as L,n as R,r as z,s as oe}from"./fs-BQWb1K18.js";import{d as se,n as ce}from"./skills-AKjvBI03.js";import{a as le,c as ue,d as de,i as fe,l as pe,n as me,o as B,r as he,s as ge,u as _e}from"./cdp-Bzco6_uI.js";import{_ as ve,a as ye,b as be,c as xe,d as Se,f as Ce,g as we,h as Te,i as Ee,l as De,m as Oe,n as ke,o as Ae,p as je,r as Me,s as Ne,t as Pe,u as Fe,v as Ie,x as Le,y as V}from"./db-CogIG09c.js";import{a as Re,i as H,n as ze,o as Be,r as Ve,s as He}from"./cost-command-BK0NsK_J.js";import{t as Ue}from"./pako-Bt_k3edT.js";import{t as We}from"./__vite-browser-external-03xtmW8y.js";import{t as Ge}from"./magick-wasm-ChxbtGD8.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function Ke(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var qe=Ke();function Je(e){qe=e}var Ye={exec:()=>null};function U(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(Ze.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var Xe=(()=>{try{return!0}catch{return!1}})(),Ze={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=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,`i`),blockquoteBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}>`)},Qe=/^(?:[ \t]*(?:\n|$))+/,$e=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,et=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,tt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,nt=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,rt=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,it=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,at=U(it).replace(/bull/g,rt).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(),ot=U(it).replace(/bull/g,rt).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(),st=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ct=/^[^\n]+/,lt=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ut=U(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,lt).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),dt=U(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,rt).getRegex(),ft=`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`,pt=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,mt=U(`^ {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`,pt).replace(`tag`,ft).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),ht=U(st).replace(`hr`,tt).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`,ft).getRegex(),W={blockquote:U(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,ht).getRegex(),code:$e,def:ut,fences:et,heading:nt,hr:tt,html:mt,lheading:at,list:dt,newline:Qe,paragraph:ht,table:Ye,text:ct},gt=U(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,tt).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`,ft).getRegex(),_t={...W,lheading:ot,table:gt,paragraph:U(st).replace(`hr`,tt).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,gt).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`,ft).getRegex()},vt={...W,html:U(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,pt).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:Ye,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:U(st).replace(`hr`,tt).replace(`heading`,` *#{1,6} *[^
|
|
3
3
|
]`).replace(`lheading`,at).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},yt=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,bt=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,xt=/^( {2,}|\\)\n(?!\s*$)/,St=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ct=/[\p{P}\p{S}]/u,wt=/[\s\p{P}\p{S}]/u,Tt=/[^\s\p{P}\p{S}]/u,Et=U(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,wt).getRegex(),Dt=/(?!~)[\p{P}\p{S}]/u,Ot=/(?!~)[\s\p{P}\p{S}]/u,kt=/(?:[^\s\p{P}\p{S}]|~)/u,At=U(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,Xe?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),jt=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Mt=U(jt,`u`).replace(/punct/g,Ct).getRegex(),Nt=U(jt,`u`).replace(/punct/g,Dt).getRegex(),Pt=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,Ft=U(Pt,`gu`).replace(/notPunctSpace/g,Tt).replace(/punctSpace/g,wt).replace(/punct/g,Ct).getRegex(),It=U(Pt,`gu`).replace(/notPunctSpace/g,kt).replace(/punctSpace/g,Ot).replace(/punct/g,Dt).getRegex(),Lt=U(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,Tt).replace(/punctSpace/g,wt).replace(/punct/g,Ct).getRegex(),Rt=U(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,Ct).getRegex(),zt=U(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Tt).replace(/punctSpace/g,wt).replace(/punct/g,Ct).getRegex(),Bt=U(/\\(punct)/,`gu`).replace(/punct/g,Ct).getRegex(),Vt=U(/^<(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(),Ht=U(pt).replace(`(?:-->|$)`,`-->`).getRegex(),Ut=U(`^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`,Ht).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Wt=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Gt=U(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,Wt).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Kt=U(/^!?\[(label)\]\[(ref)\]/).replace(`label`,Wt).replace(`ref`,lt).getRegex(),qt=U(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,lt).getRegex(),Jt=U(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,Kt).replace(`nolink`,qt).getRegex(),Yt=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Xt={_backpedal:Ye,anyPunctuation:Bt,autolink:Vt,blockSkip:At,br:xt,code:bt,del:Ye,delLDelim:Ye,delRDelim:Ye,emStrongLDelim:Mt,emStrongRDelimAst:Ft,emStrongRDelimUnd:Lt,escape:yt,link:Gt,nolink:qt,punctuation:Et,reflink:Kt,reflinkSearch:Jt,tag:Ut,text:St,url:Ye},Zt={...Xt,link:U(/^!?\[(label)\]\((.*?)\)/).replace(`label`,Wt).getRegex(),reflink:U(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,Wt).getRegex()},Qt={...Xt,emStrongRDelimAst:It,emStrongLDelim:Nt,delLDelim:Rt,delRDelim:zt,url:U(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,Yt).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:U(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,Yt).getRegex()},$t={...Qt,br:U(xt).replace(`{2,}`,`*`).getRegex(),text:U(Qt.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},en={normal:W,gfm:_t,pedantic:vt},tn={normal:Xt,gfm:Qt,breaks:$t,pedantic:Zt},nn={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},rn=e=>nn[e];function an(e,t){if(t){if(Ze.escapeTest.test(e))return e.replace(Ze.escapeReplace,rn)}else if(Ze.escapeTestNoEncode.test(e))return e.replace(Ze.escapeReplaceNoEncode,rn);return e}function on(e){try{e=encodeURI(e).replace(Ze.percentDecode,`%`)}catch{return null}return e}function sn(e,t){let n=e.replace(Ze.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(Ze.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``);for(;r<n.length;r++)n[r]=n[r].trim().replace(Ze.slashPipe,`|`);return n}function cn(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function ln(e){let t=e.split(`
|
|
4
4
|
`),n=t.length-1;for(;n>=0&&!t[n].trim();)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
|
|
5
5
|
`)}function un(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function dn(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function fn(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function pn(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
@@ -62,8 +62,8 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
62
62
|
${e}</tr>
|
|
63
63
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
64
64
|
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${an(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=on(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+an(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=on(e);if(i===null)return an(n);e=i;let a=`<img src="${e}" alt="${an(n)}"`;return t&&(a+=` title="${an(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:an(e.text)}},_n=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},vn=class e{options;renderer;textRenderer;constructor(e){this.options=e||qe,this.options.renderer=this.options.renderer||new gn,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new _n}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},G=class{options;block;constructor(e){this.options=e||qe}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?hn.lex:hn.lexInline}provideParser(e=this.block){return e?vn.parse:vn.parseInline}},K=class{defaults=Ke();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=vn;Renderer=gn;TextRenderer=_n;Lexer=hn;Tokenizer=mn;Hooks=G;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new gn(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new mn(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new G;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];G.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&G.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:t[r]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return hn.lex(e,t??this.defaults)}parser(e,t){return vn.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?hn.lex:hn.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?vn.parse:vn.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?hn.lex:hn.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?vn.parse:vn.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
|
|
65
|
-
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+an(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}},yn=new K;function q(e,t){return yn.parse(e,t)}q.options=q.setOptions=function(e){return yn.setOptions(e),q.defaults=yn.defaults,Je(q.defaults),q},q.getDefaults=Ke,q.defaults=qe,q.use=function(...e){return yn.use(...e),q.defaults=yn.defaults,Je(q.defaults),q},q.walkTokens=function(e,t){return yn.walkTokens(e,t)},q.parseInline=yn.parseInline,q.Parser=vn,q.parser=vn.parse,q.Renderer=gn,q.TextRenderer=_n,q.Lexer=hn,q.lexer=hn.lex,q.Tokenizer=mn,q.Hooks=G,q.parse=q,q.options,q.setOptions,q.use,q.walkTokens,q.parseInline,vn.parse,hn.lex;var{entries:bn,setPrototypeOf:xn,isFrozen:Sn,getPrototypeOf:Cn,getOwnPropertyDescriptor:wn}=Object,{freeze:Tn,seal:En,create:Dn}=Object,{apply:On,construct:kn}=typeof Reflect<`u`&&Reflect;Tn||=function(e){return e},En||=function(e){return e},On||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},kn||=function(e){return new e(...[...arguments].slice(1))};var An=Wn(Array.prototype.forEach),jn=Wn(Array.prototype.lastIndexOf),Mn=Wn(Array.prototype.pop),Nn=Wn(Array.prototype.push),Pn=Wn(Array.prototype.splice),Fn=Wn(String.prototype.toLowerCase),In=Wn(String.prototype.toString),Ln=Wn(String.prototype.match),Rn=Wn(String.prototype.replace),zn=Wn(String.prototype.indexOf),Bn=Wn(String.prototype.trim),Vn=Wn(Object.prototype.hasOwnProperty),Hn=Wn(RegExp.prototype.test),Un=Gn(TypeError);function Wn(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return On(e,t,n)}}function Gn(e){return function(){return kn(e,[...arguments])}}function J(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Fn;xn&&xn(e,null);let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(Sn(t)||(t[r]=e),i=e)}e[i]=!0}return e}function Kn(e){for(let t=0;t<e.length;t++)Vn(e,t)||(e[t]=null);return e}function qn(e){let t=Dn(null);for(let[n,r]of bn(e))Vn(e,n)&&(Array.isArray(r)?t[n]=Kn(r):r&&typeof r==`object`&&r.constructor===Object?t[n]=qn(r):t[n]=r);return t}function Jn(e,t){for(;e!==null;){let n=wn(e,t);if(n){if(n.get)return Wn(n.get);if(typeof n.value==`function`)return Wn(n.value)}e=Cn(e)}function n(){return null}return n}var Yn=Tn(`a.abbr.acronym.address.area.article.aside.audio.b.bdi.bdo.big.blink.blockquote.body.br.button.canvas.caption.center.cite.code.col.colgroup.content.data.datalist.dd.decorator.del.details.dfn.dialog.dir.div.dl.dt.element.em.fieldset.figcaption.figure.font.footer.form.h1.h2.h3.h4.h5.h6.head.header.hgroup.hr.html.i.img.input.ins.kbd.label.legend.li.main.map.mark.marquee.menu.menuitem.meter.nav.nobr.ol.optgroup.option.output.p.picture.pre.progress.q.rp.rt.ruby.s.samp.search.section.select.shadow.slot.small.source.spacer.span.strike.strong.style.sub.summary.sup.table.tbody.td.template.textarea.tfoot.th.thead.time.tr.track.tt.u.ul.var.video.wbr`.split(`.`)),Xn=Tn(`svg.a.altglyph.altglyphdef.altglyphitem.animatecolor.animatemotion.animatetransform.circle.clippath.defs.desc.ellipse.enterkeyhint.exportparts.filter.font.g.glyph.glyphref.hkern.image.inputmode.line.lineargradient.marker.mask.metadata.mpath.part.path.pattern.polygon.polyline.radialgradient.rect.stop.style.switch.symbol.text.textpath.title.tref.tspan.view.vkern`.split(`.`)),Zn=Tn([`feBlend`,`feColorMatrix`,`feComponentTransfer`,`feComposite`,`feConvolveMatrix`,`feDiffuseLighting`,`feDisplacementMap`,`feDistantLight`,`feDropShadow`,`feFlood`,`feFuncA`,`feFuncB`,`feFuncG`,`feFuncR`,`feGaussianBlur`,`feImage`,`feMerge`,`feMergeNode`,`feMorphology`,`feOffset`,`fePointLight`,`feSpecularLighting`,`feSpotLight`,`feTile`,`feTurbulence`]),Qn=Tn([`animate`,`color-profile`,`cursor`,`discard`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`foreignobject`,`hatch`,`hatchpath`,`mesh`,`meshgradient`,`meshpatch`,`meshrow`,`missing-glyph`,`script`,`set`,`solidcolor`,`unknown`,`use`]),$n=Tn(`math.menclose.merror.mfenced.mfrac.mglyph.mi.mlabeledtr.mmultiscripts.mn.mo.mover.mpadded.mphantom.mroot.mrow.ms.mspace.msqrt.mstyle.msub.msup.msubsup.mtable.mtd.mtext.mtr.munder.munderover.mprescripts`.split(`.`)),er=Tn([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),tr=Tn([`#text`]),nr=Tn(`accept.action.align.alt.autocapitalize.autocomplete.autopictureinpicture.autoplay.background.bgcolor.border.capture.cellpadding.cellspacing.checked.cite.class.clear.color.cols.colspan.controls.controlslist.coords.crossorigin.datetime.decoding.default.dir.disabled.disablepictureinpicture.disableremoteplayback.download.draggable.enctype.enterkeyhint.exportparts.face.for.headers.height.hidden.high.href.hreflang.id.inert.inputmode.integrity.ismap.kind.label.lang.list.loading.loop.low.max.maxlength.media.method.min.minlength.multiple.muted.name.nonce.noshade.novalidate.nowrap.open.optimum.part.pattern.placeholder.playsinline.popover.popovertarget.popovertargetaction.poster.preload.pubdate.radiogroup.readonly.rel.required.rev.reversed.role.rows.rowspan.spellcheck.scope.selected.shape.size.sizes.slot.span.srclang.start.src.srcset.step.style.summary.tabindex.title.translate.type.usemap.valign.value.width.wrap.xmlns.slot`.split(`.`)),rr=Tn(`accent-height.accumulate.additive.alignment-baseline.amplitude.ascent.attributename.attributetype.azimuth.basefrequency.baseline-shift.begin.bias.by.class.clip.clippathunits.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.cx.cy.d.dx.dy.diffuseconstant.direction.display.divisor.dur.edgemode.elevation.end.exponent.fill.fill-opacity.fill-rule.filter.filterunits.flood-color.flood-opacity.font-family.font-size.font-size-adjust.font-stretch.font-style.font-variant.font-weight.fx.fy.g1.g2.glyph-name.glyphref.gradientunits.gradienttransform.height.href.id.image-rendering.in.in2.intercept.k.k1.k2.k3.k4.kerning.keypoints.keysplines.keytimes.lang.lengthadjust.letter-spacing.kernelmatrix.kernelunitlength.lighting-color.local.marker-end.marker-mid.marker-start.markerheight.markerunits.markerwidth.maskcontentunits.maskunits.max.mask.mask-type.media.method.mode.min.name.numoctaves.offset.operator.opacity.order.orient.orientation.origin.overflow.paint-order.path.pathlength.patterncontentunits.patterntransform.patternunits.points.preservealpha.preserveaspectratio.primitiveunits.r.rx.ry.radius.refx.refy.repeatcount.repeatdur.restart.result.rotate.scale.seed.shape-rendering.slope.specularconstant.specularexponent.spreadmethod.startoffset.stddeviation.stitchtiles.stop-color.stop-opacity.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke.stroke-width.style.surfacescale.systemlanguage.tabindex.tablevalues.targetx.targety.transform.transform-origin.text-anchor.text-decoration.text-rendering.textlength.type.u1.u2.unicode.values.viewbox.visibility.version.vert-adv-y.vert-origin-x.vert-origin-y.width.word-spacing.wrap.writing-mode.xchannelselector.ychannelselector.x.x1.x2.xmlns.y.y1.y2.z.zoomandpan`.split(`.`)),ir=Tn(`accent.accentunder.align.bevelled.close.columnsalign.columnlines.columnspan.denomalign.depth.dir.display.displaystyle.encoding.fence.frame.height.href.id.largeop.length.linethickness.lspace.lquote.mathbackground.mathcolor.mathsize.mathvariant.maxsize.minsize.movablelimits.notation.numalign.open.rowalign.rowlines.rowspacing.rowspan.rspace.rquote.scriptlevel.scriptminsize.scriptsizemultiplier.selection.separator.separators.stretchy.subscriptshift.supscriptshift.symmetric.voffset.width.xmlns`.split(`.`)),ar=Tn([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),or=En(/\{\{[\w\W]*|[\w\W]*\}\}/gm),sr=En(/<%[\w\W]*|[\w\W]*%>/gm),cr=En(/\$\{[\w\W]*/gm),lr=En(/^data-[\-\w.\u00B7-\uFFFF]+$/),ur=En(/^aria-[\-\w]+$/),dr=En(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),fr=En(/^(?:\w+script|data):/i),pr=En(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),mr=En(/^html$/i),hr=En(/^[a-z][.\w]*(-[.\w]+)+$/i),gr=Object.freeze({__proto__:null,ARIA_ATTR:ur,ATTR_WHITESPACE:pr,CUSTOM_ELEMENT:hr,DATA_ATTR:lr,DOCTYPE_NAME:mr,ERB_EXPR:sr,IS_ALLOWED_URI:dr,IS_SCRIPT_OR_DATA:fr,MUSTACHE_EXPR:or,TMPLIT_EXPR:cr}),_r={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},vr=function(){return typeof window>`u`?null:window},yr=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch{return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},br=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function xr(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:vr(),t=e=>xr(e);if(t.version=`3.3.3`,t.removed=[],!e||!e.document||e.document.nodeType!==_r.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e,r=n,i=r.currentScript,{DocumentFragment:a,HTMLTemplateElement:o,Node:s,Element:c,NodeFilter:l,NamedNodeMap:u=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:d,DOMParser:f,trustedTypes:p}=e,m=c.prototype,h=Jn(m,`cloneNode`),g=Jn(m,`remove`),_=Jn(m,`nextSibling`),v=Jn(m,`childNodes`),y=Jn(m,`parentNode`);if(typeof o==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let b,x=``,{implementation:S,createNodeIterator:C,createDocumentFragment:w,getElementsByTagName:T}=n,{importNode:E}=r,D=br();t.isSupported=typeof bn==`function`&&typeof y==`function`&&S&&S.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:O,ERB_EXPR:k,TMPLIT_EXPR:ee,DATA_ATTR:A,ARIA_ATTR:j,IS_SCRIPT_OR_DATA:te,ATTR_WHITESPACE:ne,CUSTOM_ELEMENT:re}=gr,{IS_ALLOWED_URI:ie}=gr,M=null,N=J({},[...Yn,...Xn,...Zn,...$n,...tr]),P=null,ae=J({},[...nr,...rr,...ir,...ar]),F=Object.seal(Dn(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),I=null,L=null,R=Object.seal(Dn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),z=!0,oe=!0,se=!1,ce=!0,le=!1,ue=!0,de=!1,fe=!1,pe=!1,me=!1,B=!1,he=!1,ge=!0,_e=!1,ve=!0,ye=!1,be={},xe=null,Se=J({},[`annotation-xml`,`audio`,`colgroup`,`desc`,`foreignobject`,`head`,`iframe`,`math`,`mi`,`mn`,`mo`,`ms`,`mtext`,`noembed`,`noframes`,`noscript`,`plaintext`,`script`,`style`,`svg`,`template`,`thead`,`title`,`video`,`xmp`]),Ce=null,we=J({},[`audio`,`video`,`img`,`source`,`image`,`track`]),Te=null,Ee=J({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),De=`http://www.w3.org/1998/Math/MathML`,Oe=`http://www.w3.org/2000/svg`,ke=`http://www.w3.org/1999/xhtml`,Ae=ke,je=!1,Me=null,Ne=J({},[De,Oe,ke],In),Pe=J({},[`mi`,`mo`,`mn`,`ms`,`mtext`]),Fe=J({},[`annotation-xml`]),Ie=J({},[`title`,`style`,`font`,`a`,`script`]),Le=null,V=[`application/xhtml+xml`,`text/html`],Re=null,H=null,ze=n.createElement(`form`),Be=function(e){return e instanceof RegExp||e instanceof Function},Ve=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(H&&H===e)){if((!e||typeof e!=`object`)&&(e={}),e=qn(e),Le=V.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,Re=Le===`application/xhtml+xml`?In:Fn,M=Vn(e,`ALLOWED_TAGS`)?J({},e.ALLOWED_TAGS,Re):N,P=Vn(e,`ALLOWED_ATTR`)?J({},e.ALLOWED_ATTR,Re):ae,Me=Vn(e,`ALLOWED_NAMESPACES`)?J({},e.ALLOWED_NAMESPACES,In):Ne,Te=Vn(e,`ADD_URI_SAFE_ATTR`)?J(qn(Ee),e.ADD_URI_SAFE_ATTR,Re):Ee,Ce=Vn(e,`ADD_DATA_URI_TAGS`)?J(qn(we),e.ADD_DATA_URI_TAGS,Re):we,xe=Vn(e,`FORBID_CONTENTS`)?J({},e.FORBID_CONTENTS,Re):Se,I=Vn(e,`FORBID_TAGS`)?J({},e.FORBID_TAGS,Re):qn({}),L=Vn(e,`FORBID_ATTR`)?J({},e.FORBID_ATTR,Re):qn({}),be=Vn(e,`USE_PROFILES`)?e.USE_PROFILES:!1,z=e.ALLOW_ARIA_ATTR!==!1,oe=e.ALLOW_DATA_ATTR!==!1,se=e.ALLOW_UNKNOWN_PROTOCOLS||!1,ce=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,le=e.SAFE_FOR_TEMPLATES||!1,ue=e.SAFE_FOR_XML!==!1,de=e.WHOLE_DOCUMENT||!1,me=e.RETURN_DOM||!1,B=e.RETURN_DOM_FRAGMENT||!1,he=e.RETURN_TRUSTED_TYPE||!1,pe=e.FORCE_BODY||!1,ge=e.SANITIZE_DOM!==!1,_e=e.SANITIZE_NAMED_PROPS||!1,ve=e.KEEP_CONTENT!==!1,ye=e.IN_PLACE||!1,ie=e.ALLOWED_URI_REGEXP||dr,Ae=e.NAMESPACE||ke,Pe=e.MATHML_TEXT_INTEGRATION_POINTS||Pe,Fe=e.HTML_INTEGRATION_POINTS||Fe,F=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&Be(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(F.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&Be(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(F.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements==`boolean`&&(F.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),le&&(oe=!1),B&&(me=!0),be&&(M=J({},tr),P=Dn(null),be.html===!0&&(J(M,Yn),J(P,nr)),be.svg===!0&&(J(M,Xn),J(P,rr),J(P,ar)),be.svgFilters===!0&&(J(M,Zn),J(P,rr),J(P,ar)),be.mathMl===!0&&(J(M,$n),J(P,ir),J(P,ar))),Vn(e,`ADD_TAGS`)||(R.tagCheck=null),Vn(e,`ADD_ATTR`)||(R.attributeCheck=null),e.ADD_TAGS&&(typeof e.ADD_TAGS==`function`?R.tagCheck=e.ADD_TAGS:(M===N&&(M=qn(M)),J(M,e.ADD_TAGS,Re))),e.ADD_ATTR&&(typeof e.ADD_ATTR==`function`?R.attributeCheck=e.ADD_ATTR:(P===ae&&(P=qn(P)),J(P,e.ADD_ATTR,Re))),e.ADD_URI_SAFE_ATTR&&J(Te,e.ADD_URI_SAFE_ATTR,Re),e.FORBID_CONTENTS&&(xe===Se&&(xe=qn(xe)),J(xe,e.FORBID_CONTENTS,Re)),e.ADD_FORBID_CONTENTS&&(xe===Se&&(xe=qn(xe)),J(xe,e.ADD_FORBID_CONTENTS,Re)),ve&&(M[`#text`]=!0),de&&J(M,[`html`,`head`,`body`]),M.table&&(J(M,[`tbody`]),delete I.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw Un(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw Un(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);b=e.TRUSTED_TYPES_POLICY,x=b.createHTML(``)}else b===void 0&&(b=yr(p,i)),b!==null&&typeof x==`string`&&(x=b.createHTML(``));Tn&&Tn(e),H=e}},He=J({},[...Xn,...Zn,...Qn]),Ue=J({},[...$n,...er]),We=function(e){let t=y(e);(!t||!t.tagName)&&(t={namespaceURI:Ae,tagName:`template`});let n=Fn(e.tagName),r=Fn(t.tagName);return Me[e.namespaceURI]?e.namespaceURI===Oe?t.namespaceURI===ke?n===`svg`:t.namespaceURI===De?n===`svg`&&(r===`annotation-xml`||Pe[r]):!!He[n]:e.namespaceURI===De?t.namespaceURI===ke?n===`math`:t.namespaceURI===Oe?n===`math`&&Fe[r]:!!Ue[n]:e.namespaceURI===ke?t.namespaceURI===Oe&&!Fe[r]||t.namespaceURI===De&&!Pe[r]?!1:!Ue[n]&&(Ie[n]||!He[n]):!!(Le===`application/xhtml+xml`&&Me[e.namespaceURI]):!1},Ge=function(e){Nn(t.removed,{element:e});try{y(e).removeChild(e)}catch{g(e)}},Ke=function(e,n){try{Nn(t.removed,{attribute:n.getAttributeNode(e),from:n})}catch{Nn(t.removed,{attribute:null,from:n})}if(n.removeAttribute(e),e===`is`)if(me||B)try{Ge(n)}catch{}else try{n.setAttribute(e,``)}catch{}},qe=function(e){let t=null,r=null;if(pe)e=`<remove></remove>`+e;else{let t=Ln(e,/^[\r\n\t ]+/);r=t&&t[0]}Le===`application/xhtml+xml`&&Ae===ke&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=b?b.createHTML(e):e;if(Ae===ke)try{t=new f().parseFromString(i,Le)}catch{}if(!t||!t.documentElement){t=S.createDocument(Ae,`template`,null);try{t.documentElement.innerHTML=je?x:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),Ae===ke?T.call(t,de?`html`:`body`)[0]:de?t.documentElement:a},Je=function(e){return C.call(e.ownerDocument||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Ye=function(e){return e instanceof d&&(typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||!(e.attributes instanceof u)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`)},U=function(e){return typeof s==`function`&&e instanceof s};function Xe(e,n,r){An(e,e=>{e.call(t,n,r,H)})}let Ze=function(e){let n=null;if(Xe(D.beforeSanitizeElements,e,null),Ye(e))return Ge(e),!0;let r=Re(e.nodeName);if(Xe(D.uponSanitizeElement,e,{tagName:r,allowedTags:M}),ue&&e.hasChildNodes()&&!U(e.firstElementChild)&&Hn(/<[/\w!]/g,e.innerHTML)&&Hn(/<[/\w!]/g,e.textContent)||e.nodeType===_r.progressingInstruction||ue&&e.nodeType===_r.comment&&Hn(/<[/\w]/g,e.data))return Ge(e),!0;if(!(R.tagCheck instanceof Function&&R.tagCheck(r))&&(!M[r]||I[r])){if(!I[r]&&$e(r)&&(F.tagNameCheck instanceof RegExp&&Hn(F.tagNameCheck,r)||F.tagNameCheck instanceof Function&&F.tagNameCheck(r)))return!1;if(ve&&!xe[r]){let t=y(e)||e.parentNode,n=v(e)||e.childNodes;if(n&&t){let r=n.length;for(let i=r-1;i>=0;--i){let r=h(n[i],!0);r.__removalCount=(e.__removalCount||0)+1,t.insertBefore(r,_(e))}}}return Ge(e),!0}return e instanceof c&&!We(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&Hn(/<\/no(script|embed|frames)/i,e.innerHTML)?(Ge(e),!0):(le&&e.nodeType===_r.text&&(n=e.textContent,An([O,k,ee],e=>{n=Rn(n,e,` `)}),e.textContent!==n&&(Nn(t.removed,{element:e.cloneNode()}),e.textContent=n)),Xe(D.afterSanitizeElements,e,null),!1)},Qe=function(e,t,r){if(L[t]||ge&&(t===`id`||t===`name`)&&(r in n||r in ze))return!1;if(!(oe&&!L[t]&&Hn(A,t))&&!(z&&Hn(j,t))&&!(R.attributeCheck instanceof Function&&R.attributeCheck(t,e))){if(!P[t]||L[t]){if(!($e(e)&&(F.tagNameCheck instanceof RegExp&&Hn(F.tagNameCheck,e)||F.tagNameCheck instanceof Function&&F.tagNameCheck(e))&&(F.attributeNameCheck instanceof RegExp&&Hn(F.attributeNameCheck,t)||F.attributeNameCheck instanceof Function&&F.attributeNameCheck(t,e))||t===`is`&&F.allowCustomizedBuiltInElements&&(F.tagNameCheck instanceof RegExp&&Hn(F.tagNameCheck,r)||F.tagNameCheck instanceof Function&&F.tagNameCheck(r))))return!1}else if(!Te[t]&&!Hn(ie,Rn(r,ne,``))&&!((t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&zn(r,`data:`)===0&&Ce[e])&&!(se&&!Hn(te,Rn(r,ne,``)))&&r)return!1}return!0},$e=function(e){return e!==`annotation-xml`&&Ln(e,re)},et=function(e){Xe(D.beforeSanitizeAttributes,e,null);let{attributes:n}=e;if(!n||Ye(e))return;let r={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:P,forceKeepAttr:void 0},i=n.length;for(;i--;){let{name:a,namespaceURI:o,value:s}=n[i],c=Re(a),l=s,u=a===`value`?l:Bn(l);if(r.attrName=c,r.attrValue=u,r.keepAttr=!0,r.forceKeepAttr=void 0,Xe(D.uponSanitizeAttribute,e,r),u=r.attrValue,_e&&(c===`id`||c===`name`)&&(Ke(a,e),u=`user-content-`+u),ue&&Hn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,u)){Ke(a,e);continue}if(c===`attributename`&&Ln(u,`href`)){Ke(a,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){Ke(a,e);continue}if(!ce&&Hn(/\/>/i,u)){Ke(a,e);continue}le&&An([O,k,ee],e=>{u=Rn(u,e,` `)});let d=Re(e.nodeName);if(!Qe(d,c,u)){Ke(a,e);continue}if(b&&typeof p==`object`&&typeof p.getAttributeType==`function`&&!o)switch(p.getAttributeType(d,c)){case`TrustedHTML`:u=b.createHTML(u);break;case`TrustedScriptURL`:u=b.createScriptURL(u);break}if(u!==l)try{o?e.setAttributeNS(o,a,u):e.setAttribute(a,u),Ye(e)?Ge(e):Mn(t.removed)}catch{Ke(a,e)}}Xe(D.afterSanitizeAttributes,e,null)},tt=function e(t){let n=null,r=Je(t);for(Xe(D.beforeSanitizeShadowDOM,t,null);n=r.nextNode();)Xe(D.uponSanitizeShadowNode,n,null),Ze(n),et(n),n.content instanceof a&&e(n.content);Xe(D.afterSanitizeShadowDOM,t,null)};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,o=null,c=null,l=null;if(je=!e,je&&(e=`<!-->`),typeof e!=`string`&&!U(e))if(typeof e.toString==`function`){if(e=e.toString(),typeof e!=`string`)throw Un(`dirty is not a string, aborting`)}else throw Un(`toString is not a function`);if(!t.isSupported)return e;if(fe||Ve(n),t.removed=[],typeof e==`string`&&(ye=!1),ye){if(e.nodeName){let t=Re(e.nodeName);if(!M[t]||I[t])throw Un(`root node is forbidden and cannot be sanitized in-place`)}}else if(e instanceof s)i=qe(`<!---->`),o=i.ownerDocument.importNode(e,!0),o.nodeType===_r.element&&o.nodeName===`BODY`||o.nodeName===`HTML`?i=o:i.appendChild(o);else{if(!me&&!le&&!de&&e.indexOf(`<`)===-1)return b&&he?b.createHTML(e):e;if(i=qe(e),!i)return me?null:he?x:``}i&&pe&&Ge(i.firstChild);let u=Je(ye?e:i);for(;c=u.nextNode();)Ze(c),et(c),c.content instanceof a&&tt(c.content);if(ye)return e;if(me){if(B)for(l=w.call(i.ownerDocument);i.firstChild;)l.appendChild(i.firstChild);else l=i;return(P.shadowroot||P.shadowrootmode)&&(l=E.call(r,l,!0)),l}let d=de?i.outerHTML:i.innerHTML;return de&&M[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&Hn(mr,i.ownerDocument.doctype.name)&&(d=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
|
|
66
|
-
`+d),le&&An([O,k,ee],e=>{d=Rn(d,e,` `)}),b&&he?b.createHTML(d):d},t.setConfig=function(){Ve(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),fe=!0},t.clearConfig=function(){H=null,fe=!1},t.isValidAttribute=function(e,t,n){return H||Ve({}),Qe(Re(e),Re(t),n)},t.addHook=function(e,t){typeof t==`function`&&Nn(D[e],t)},t.removeHook=function(e,t){if(t!==void 0){let n=jn(D[e],t);return n===-1?void 0:Pn(D[e],n,1)[0]}return Mn(D[e])},t.removeHooks=function(e){D[e]=[]},t.removeAllHooks=function(){D=br()},t}var Sr=xr(),Cr=Sr.sanitize.bind(Sr);Sr.isSupported,Sr.addHook.bind(Sr),Sr.removeHook.bind(Sr),Sr.removeHooks.bind(Sr),Sr.removeAllHooks.bind(Sr),Sr.setConfig.bind(Sr),Sr.clearConfig.bind(Sr),Sr.isValidAttribute.bind(Sr),Sr.version,Sr.removed;function wr(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function Tr(e,t){let n=wr(e);return t===`shtml`||([`js`,`javascript`,`ts`,`typescript`,`jsx`,`tsx`].includes(t)?n=Er(n):t===`json`?n=Dr(n):[`bash`,`sh`,`shell`,`zsh`].includes(t)&&(n=Or(n))),n}function Er(e){return e=e.replace(/(\/\/[^\n]*)/g,`<span class="tok-comment">$1</span>`),e=e.replace(/(\/\*[\s\S]*?\*\/)/g,`<span class="tok-comment">$1</span>`),e=e.replace(/("[^&]*?"|'[^&]*?'|`[^`]*?`)/g,`<span class="tok-string">$1</span>`),e=e.replace(RegExp(`\\b(${`const.let.var.function.return.if.else.for.while.class.extends.import.export.from.default.new.this.async.await.try.catch.throw.typeof.instanceof.interface.type.enum.implements.abstract.public.private.protected.readonly.static.void.null.undefined.true.false`.split(`.`).join(`|`)})\\b`,`g`),`<span class="tok-keyword">$1</span>`),e=e.replace(/\b(\d+\.?\d*)\b/g,`<span class="tok-number">$1</span>`),e=e.replace(/\b([a-zA-Z_$][\w$]*)\s*(?=\()/g,`<span class="tok-fn">$1</span>`),e}function Dr(e){return e=e.replace(/("[^&]*?")\s*:/g,`<span class="tok-keyword">$1</span>:`),e=e.replace(/:\s*("[^&]*?")/g,`: <span class="tok-string">$1</span>`),e=e.replace(/\b(\d+\.?\d*)\b/g,`<span class="tok-number">$1</span>`),e=e.replace(/\b(true|false|null)\b/g,`<span class="tok-keyword">$1</span>`),e}function Or(e){return e=e.replace(/(#[^\n]*)/g,`<span class="tok-comment">$1</span>`),e=e.replace(/("[^&]*?"|'[^&]*?')/g,`<span class="tok-string">$1</span>`),e=e.replace(RegExp(`\\b(${[`if`,`then`,`else`,`fi`,`for`,`do`,`done`,`while`,`case`,`esac`,`echo`,`export`,`cd`,`ls`,`mkdir`,`rm`,`cp`,`mv`,`cat`,`grep`,`npm`,`node`,`git`].join(`|`)})\\b`,`g`),`<span class="tok-keyword">$1</span>`),e}var kr=new K({gfm:!0,breaks:!0,async:!1,renderer:{code({text:e,lang:t}){let n=t??``,r=Tr(e,n);return`<pre><code${n?` class="language-${wr(n)}"`:``}>${r}</code></pre>\n`},link({href:e,title:t,tokens:n}){let r=e??``;if(r.startsWith(`javascript:`))return this.parser.parseInline(n);let i=t?` title="${wr(t)}"`:``,a=this.parser.parseInline(n);return`<a href="${wr(r)}"${i} target="_blank" rel="noopener noreferrer">${a}</a>`}}}),Ar={ALLOWED_TAGS:`a.b.i.em.strong.p.br.code.pre.ul.ol.li.h1.h2.h3.h4.h5.h6.table.thead.tbody.tr.th.td.del.blockquote.hr.img.span.div.details.summary.input`.split(`.`),ALLOWED_ATTR:[`href`,`src`,`alt`,`title`,`class`,`target`,`rel`,`type`,`checked`,`disabled`],ALLOW_DATA_ATTR:!1};function jr(e){return Cr(e,Ar)}function Mr(e){return e.replace(/<a\s([^>]*?)>/g,(e,t)=>{let n=t;return/(^|\s)target\s*=/i.test(n)?n=n.replace(/(^|\s)target\s*=\s*(['"])[^'"]*\2/gi,`$1target="_blank"`):n+=` target="_blank"`,/(^|\s)rel\s*=/i.test(n)?n=n.replace(/(^|\s)rel\s*=\s*(['"])[^'"]*\2/gi,`$1rel="noopener noreferrer"`):n+=` rel="noopener noreferrer"`,`<a ${n}>`})}var Nr=/<p><strong>Error:<\/strong>\s*([\s\S]*?)<\/p>/g;function Pr(e){return Mr(jr(kr.parse(e)))}function Fr(e){return e.replace(Nr,(e,t)=>`<div class="msg__error" role="alert"><div class="msg__error-label">Error</div><div class="msg__error-body">${t}</div></div>`)}function Ir(e){return Pr(e)}function Lr(e){return Fr(Pr(e))}function Rr(e){if(typeof e==`string`)return wr(e);try{return wr(JSON.stringify(e,null,2))}catch{return wr(String(e))}}var zr=`browser-coding-agent`,Br=1,Vr=`sessions`;function Hr(){return new Promise((e,t)=>{let n=indexedDB.open(zr,Br);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Vr)||e.createObjectStore(Vr,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var Ur=class{db=null;async init(){this.db=await Hr()}ensureDb(){if(!this.db)throw Error(`SessionStore not initialized. Call init() first.`);return this.db}async save(e){let t=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(Vr,`readwrite`);i.objectStore(Vr).put(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(Vr,`readonly`).objectStore(Vr).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async list(){let e=this.ensureDb();return new Promise((t,n)=>{let r=e.transaction(Vr,`readonly`).objectStore(Vr).getAll();r.onsuccess=()=>{t(r.result.sort((e,t)=>t.updatedAt-e.updatedAt).map(e=>e.id))},r.onerror=()=>n(r.error)})}async delete(e){let t=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(Vr,`readwrite`);i.objectStore(Vr).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async saveMessages(e,t){let n=await this.load(e),r=n?{...n,messages:t,updatedAt:Date.now()}:{id:e,messages:t,createdAt:Date.now(),updatedAt:Date.now()};await this.save(r)}},Wr={"not-allowed":`Microphone access denied. Check Chrome site permissions.`,"no-speech":`No speech detected. Try again.`,"audio-capture":`No microphone found. Check your audio input device.`,network:`Voice input requires an internet connection.`,aborted:`Voice input was interrupted.`,"service-not-available":`Speech recognition service unavailable. Try again later.`,"start-failed":`Failed to start speech recognition.`,"not-supported":`Speech recognition is not supported in this browser.`};function Gr(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function Kr(){return typeof window>`u`?null:window.SpeechRecognition||window.webkitSpeechRecognition||null}var qr=class e{recognition=null;_isListening=!1;shouldBeListening=!1;options;debounceTimer=null;autoSendTimer=null;pendingTranscript=``;consecutiveRestarts=0;inactivityTimer=null;messageListener=null;popupWindowId=null;constructor(e){this.options=e}start(){if(this._isListening)return;this.debounceTimer&&=(clearTimeout(this.debounceTimer),null);let e=Kr();if(!e){this.options.onError(`Speech recognition is not supported in this browser.`),this.options.onStateChange(`error`);return}this.shouldBeListening=!0,this.pendingTranscript=``,this.consecutiveRestarts=0,this.cancelAutoSend(),this.resetInactivityTimer(),navigator.mediaDevices?.getUserMedia?navigator.mediaDevices.getUserMedia({audio:!0}).then(t=>{for(let e of t.getTracks())e.stop();this.shouldBeListening&&this.startRecognition(new e)}).catch(e=>{if(this.shouldBeListening)if(Gr())this.startExtensionPopup();else{this.shouldBeListening=!1;let t=e?.name,n=Wr[`not-allowed`];t===`NotFoundError`?n=Wr[`audio-capture`]:t===`NotReadableError`&&(n=`Microphone is in use by another app. Try again.`),this.options.onError(n),this.options.onStateChange(`error`)}}):this.startRecognition(new e)}startExtensionPopup(){let e=this.options.lang??`en-US`,t=chrome.runtime.getURL(`voice-popup.html?lang=${encodeURIComponent(e)}`);chrome.windows.create({url:t,type:`popup`,width:300,height:68,focused:!0}).then(e=>{this.shouldBeListening&&(this.setupExtensionListener(),e?.id&&(this.popupWindowId=e.id))}).catch(()=>{this.shouldBeListening=!1,this.options.onError(`Failed to open voice input window.`),this.options.onStateChange(`error`)})}setupExtensionListener(){this.messageListener||(this.messageListener=e=>{if(e.source===`voice-popup`)switch(e.type){case`speech-result`:if(e.isFinal)this.pendingTranscript+=(this.pendingTranscript?` `:``)+e.text,this.options.onTranscript(this.pendingTranscript,!0),this.scheduleAutoSend();else{let t=this.pendingTranscript?this.pendingTranscript+` `+e.text:e.text;this.options.onTranscript(t,!1),this.cancelAutoSend()}break;case`speech-error`:{let t=Wr[e.error]??`Speech recognition error: ${e.error}`;this.options.onError(t),e.fatal&&(this._isListening=!1,this.shouldBeListening=!1,this.popupWindowId=null,this.options.onStateChange(`error`));break}case`speech-state`:e.state===`listening`&&(this._isListening=!0,this.options.onStateChange(`listening`));break;case`speech-end`:this._isListening=!1,this.shouldBeListening=!1,this.popupWindowId=null,this.options.onStateChange(`idle`);break}},chrome.runtime.onMessage.addListener(this.messageListener))}removeExtensionListener(){this.messageListener&&=(chrome.runtime.onMessage.removeListener(this.messageListener),null)}startRecognition(e){this.recognition=e,this.recognition.continuous=!0,this.recognition.interimResults=!0,this.recognition.lang=this.options.lang??`en-US`,this.recognition.onresult=e=>{this.consecutiveRestarts=0,this.resetInactivityTimer();let t=``,n=``;for(let r=e.resultIndex;r<e.results.length;r++){let i=e.results[r];i.isFinal?n+=i[0].transcript:t+=i[0].transcript}if(n)this.pendingTranscript+=(this.pendingTranscript?` `:``)+n,this.options.onTranscript(this.pendingTranscript,!0),this.scheduleAutoSend();else if(t){let e=this.pendingTranscript?this.pendingTranscript+` `+t:t;this.options.onTranscript(e,!1),this.cancelAutoSend()}},this.recognition.onerror=e=>{let t=e.error,n=Wr[t]??`Speech recognition error: ${t}`;if(t===`no-speech`){this.options.onError(n);return}t!==`aborted`&&(this._isListening=!1,this.shouldBeListening=!1,this.options.onError(n),this.options.onStateChange(`error`))},this.recognition.onend=()=>{if(this._isListening=!1,this.recognition&&=(this.recognition.onresult=null,this.recognition.onerror=null,this.recognition.onend=null,null),this.shouldBeListening){this.consecutiveRestarts++;let e=Math.min(300*2**(this.consecutiveRestarts-1),5e3),t=Kr();this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.shouldBeListening&&t?this.startRecognition(new t):this.shouldBeListening&&(this.shouldBeListening=!1,this.options.onStateChange(`idle`))},e);return}this.options.onStateChange(`idle`)};try{this.recognition.start(),this._isListening=!0,this.options.onStateChange(`listening`)}catch{this.shouldBeListening=!1,this.options.onError(`Failed to start speech recognition.`),this.options.onStateChange(`error`)}}static SEND_DELAY_MS=2500;static INACTIVITY_TIMEOUT_MS=12e4;scheduleAutoSend(){this.cancelAutoSend(),this.options.autoSend&&(this.autoSendTimer=setTimeout(()=>{this.autoSendTimer=null;let e=this.pendingTranscript.trim();e&&(this.pendingTranscript=``,this.options.onAutoSend(e))},e.SEND_DELAY_MS))}cancelAutoSend(){this.autoSendTimer&&=(clearTimeout(this.autoSendTimer),null)}resetInactivityTimer(){this.clearInactivityTimer(),this.options.onAutoDisable&&(this.inactivityTimer=setTimeout(()=>{this.inactivityTimer=null,this.stop(),this.options.onAutoDisable?.()},e.INACTIVITY_TIMEOUT_MS))}clearInactivityTimer(){this.inactivityTimer&&=(clearTimeout(this.inactivityTimer),null)}stop(){if(this.shouldBeListening=!1,this.cancelAutoSend(),this.clearInactivityTimer(),this.pendingTranscript=``,this.debounceTimer&&=(clearTimeout(this.debounceTimer),null),this.popupWindowId!=null){try{chrome.runtime.sendMessage({target:`voice-popup`,type:`voice-stop`})}catch{}chrome.windows.remove(this.popupWindowId).catch(()=>{}),this.popupWindowId=null}else if(this.recognition){this.recognition.onresult=null,this.recognition.onerror=null,this.recognition.onend=null;try{this.recognition.stop()}catch{}this.recognition=null}this._isListening=!1,this.options.onStateChange(`idle`)}toggle(){this._isListening||this.shouldBeListening?this.stop():this.start()}isListening(){return this._isListening||this.shouldBeListening}setAutoSend(e){this.options.autoSend=e}destroy(){this.stop(),this.removeExtensionListener(),this.recognition=null}},Jr={autoSend:`voice-auto-send`,lang:`voice-lang`};function Yr(){return localStorage.getItem(Jr.lang)||`en-US`}var Xr=typeof chrome<`u`&&!!chrome?.runtime?.id;function Zr(e){let t=e.trimStart().toLowerCase();return t.startsWith(`<!doctype`)||t.startsWith(`<html`)}var Qr=class{container;bridge;scripts=[];iframe=null;messageHandler=null;constructor(e,t){this.container=e,this.bridge=t}async render(e,t){this.dispose(),Xr?await this.renderInSandbox(e,t,Zr(e)):Zr(e)?await this.renderFullDoc(e,t):this.renderInline(e,t)}async renderInSandbox(e,t,n=!1){let r=document.createElement(`iframe`);r.src=chrome.runtime.getURL(`sprinkle-sandbox.html`),r.style.cssText=`width: 100%; flex: 1; border: none; min-height: 0;`,this.iframe=r,console.log(`[sprinkle-renderer] creating sandbox iframe`,r.src),await new Promise((e,t)=>{let n=setTimeout(()=>{console.error(`[sprinkle-renderer] iframe load timed out after 5s`),t(Error(`sprinkle sandbox iframe load timed out`))},5e3);r.addEventListener(`load`,()=>{clearTimeout(n),console.log(`[sprinkle-renderer] iframe loaded, contentWindow:`,!!r.contentWindow),e()},{once:!0}),r.addEventListener(`error`,e=>{clearTimeout(n),console.error(`[sprinkle-renderer] iframe error:`,e),t(Error(`sprinkle sandbox iframe failed to load`))},{once:!0}),this.container.appendChild(r)}),this.messageHandler=e=>{if(e.source!==r.contentWindow)return;let n=e.data;if(n?.type)if(n.type===`sprinkle-lick`)this.bridge.lick({action:n.action,data:n.data});else if(n.type===`sprinkle-set-state`)this.bridge.setState(n.data);else if(n.type===`sprinkle-close`)this.bridge.close();else if(n.type===`sprinkle-storage-set`)try{localStorage.setItem(`slicc-sprinkle-ls:${t}:${n.key}`,n.value)}catch(e){console.warn(`[sprinkle-renderer] localStorage setItem failed:`,n.key,e)}else if(n.type===`sprinkle-storage-remove`)try{localStorage.removeItem(`slicc-sprinkle-ls:${t}:${n.key}`)}catch(e){console.warn(`[sprinkle-renderer] localStorage removeItem failed:`,n.key,e)}else if(n.type===`sprinkle-storage-clear`){let e=`slicc-sprinkle-ls:${t}:`;for(let t=localStorage.length-1;t>=0;t--){let n=localStorage.key(t);n?.startsWith(e)&&localStorage.removeItem(n)}}else n.type===`sprinkle-open`?this.bridge.open(n.path,n.projectRoot?{projectRoot:n.projectRoot}:void 0):n.type===`sprinkle-readfile`?this.bridge.readFile(n.path).then(e=>r.contentWindow?.postMessage({type:`sprinkle-readfile-response`,id:n.id,content:e},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-readfile-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`)):n.type===`sprinkle-writefile`?this.bridge.writeFile(n.path,n.content).then(()=>r.contentWindow?.postMessage({type:`sprinkle-writefile-response`,id:n.id},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-writefile-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`)):n.type===`sprinkle-readdir`?this.bridge.readDir(n.path).then(e=>r.contentWindow?.postMessage({type:`sprinkle-readdir-response`,id:n.id,entries:e},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-readdir-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`)):n.type===`sprinkle-exists`?this.bridge.exists(n.path).then(e=>r.contentWindow?.postMessage({type:`sprinkle-exists-response`,id:n.id,exists:e},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-exists-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`)):n.type===`sprinkle-stat`?this.bridge.stat(n.path).then(e=>r.contentWindow?.postMessage({type:`sprinkle-stat-response`,id:n.id,stat:e},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-stat-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`)):n.type===`sprinkle-mkdir`?this.bridge.mkdir(n.path).then(()=>r.contentWindow?.postMessage({type:`sprinkle-mkdir-response`,id:n.id},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-mkdir-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`)):n.type===`sprinkle-rm`&&this.bridge.rm(n.path).then(()=>r.contentWindow?.postMessage({type:`sprinkle-rm-response`,id:n.id},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-rm-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`))},window.addEventListener(`message`,this.messageHandler);let i=this.collectThemeCSS(),a={},o=`slicc-sprinkle-ls:${t}:`;for(let e=0;e<localStorage.length;e++){let t=localStorage.key(e);t?.startsWith(o)&&(a[t.slice(o.length)]=localStorage.getItem(t)??``)}let s=this.bridge.getState();r.contentWindow.postMessage({type:`sprinkle-render`,content:e,name:t,themeCSS:i,savedState:s,savedStorage:a,fullDoc:n},`*`)}pushUpdate(e){this.iframe?.contentWindow&&this.iframe.contentWindow.postMessage({type:`sprinkle-update`,data:e},`*`)}collectThemeCSS(){return ei()}generateBridgeScript(){return`(function() {
|
|
65
|
+
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+an(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}},yn=new K;function q(e,t){return yn.parse(e,t)}q.options=q.setOptions=function(e){return yn.setOptions(e),q.defaults=yn.defaults,Je(q.defaults),q},q.getDefaults=Ke,q.defaults=qe,q.use=function(...e){return yn.use(...e),q.defaults=yn.defaults,Je(q.defaults),q},q.walkTokens=function(e,t){return yn.walkTokens(e,t)},q.parseInline=yn.parseInline,q.Parser=vn,q.parser=vn.parse,q.Renderer=gn,q.TextRenderer=_n,q.Lexer=hn,q.lexer=hn.lex,q.Tokenizer=mn,q.Hooks=G,q.parse=q,q.options,q.setOptions,q.use,q.walkTokens,q.parseInline,vn.parse,hn.lex;var{entries:bn,setPrototypeOf:xn,isFrozen:Sn,getPrototypeOf:Cn,getOwnPropertyDescriptor:wn}=Object,{freeze:Tn,seal:En,create:Dn}=Object,{apply:On,construct:kn}=typeof Reflect<`u`&&Reflect;Tn||=function(e){return e},En||=function(e){return e},On||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},kn||=function(e){return new e(...[...arguments].slice(1))};var An=Wn(Array.prototype.forEach),jn=Wn(Array.prototype.lastIndexOf),Mn=Wn(Array.prototype.pop),Nn=Wn(Array.prototype.push),Pn=Wn(Array.prototype.splice),Fn=Wn(String.prototype.toLowerCase),In=Wn(String.prototype.toString),Ln=Wn(String.prototype.match),Rn=Wn(String.prototype.replace),zn=Wn(String.prototype.indexOf),Bn=Wn(String.prototype.trim),Vn=Wn(Object.prototype.hasOwnProperty),Hn=Wn(RegExp.prototype.test),Un=Gn(TypeError);function Wn(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return On(e,t,n)}}function Gn(e){return function(){return kn(e,[...arguments])}}function J(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Fn;xn&&xn(e,null);let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(Sn(t)||(t[r]=e),i=e)}e[i]=!0}return e}function Kn(e){for(let t=0;t<e.length;t++)Vn(e,t)||(e[t]=null);return e}function qn(e){let t=Dn(null);for(let[n,r]of bn(e))Vn(e,n)&&(Array.isArray(r)?t[n]=Kn(r):r&&typeof r==`object`&&r.constructor===Object?t[n]=qn(r):t[n]=r);return t}function Jn(e,t){for(;e!==null;){let n=wn(e,t);if(n){if(n.get)return Wn(n.get);if(typeof n.value==`function`)return Wn(n.value)}e=Cn(e)}function n(){return null}return n}var Yn=Tn(`a.abbr.acronym.address.area.article.aside.audio.b.bdi.bdo.big.blink.blockquote.body.br.button.canvas.caption.center.cite.code.col.colgroup.content.data.datalist.dd.decorator.del.details.dfn.dialog.dir.div.dl.dt.element.em.fieldset.figcaption.figure.font.footer.form.h1.h2.h3.h4.h5.h6.head.header.hgroup.hr.html.i.img.input.ins.kbd.label.legend.li.main.map.mark.marquee.menu.menuitem.meter.nav.nobr.ol.optgroup.option.output.p.picture.pre.progress.q.rp.rt.ruby.s.samp.search.section.select.shadow.slot.small.source.spacer.span.strike.strong.style.sub.summary.sup.table.tbody.td.template.textarea.tfoot.th.thead.time.tr.track.tt.u.ul.var.video.wbr`.split(`.`)),Xn=Tn(`svg.a.altglyph.altglyphdef.altglyphitem.animatecolor.animatemotion.animatetransform.circle.clippath.defs.desc.ellipse.enterkeyhint.exportparts.filter.font.g.glyph.glyphref.hkern.image.inputmode.line.lineargradient.marker.mask.metadata.mpath.part.path.pattern.polygon.polyline.radialgradient.rect.stop.style.switch.symbol.text.textpath.title.tref.tspan.view.vkern`.split(`.`)),Zn=Tn([`feBlend`,`feColorMatrix`,`feComponentTransfer`,`feComposite`,`feConvolveMatrix`,`feDiffuseLighting`,`feDisplacementMap`,`feDistantLight`,`feDropShadow`,`feFlood`,`feFuncA`,`feFuncB`,`feFuncG`,`feFuncR`,`feGaussianBlur`,`feImage`,`feMerge`,`feMergeNode`,`feMorphology`,`feOffset`,`fePointLight`,`feSpecularLighting`,`feSpotLight`,`feTile`,`feTurbulence`]),Qn=Tn([`animate`,`color-profile`,`cursor`,`discard`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`foreignobject`,`hatch`,`hatchpath`,`mesh`,`meshgradient`,`meshpatch`,`meshrow`,`missing-glyph`,`script`,`set`,`solidcolor`,`unknown`,`use`]),$n=Tn(`math.menclose.merror.mfenced.mfrac.mglyph.mi.mlabeledtr.mmultiscripts.mn.mo.mover.mpadded.mphantom.mroot.mrow.ms.mspace.msqrt.mstyle.msub.msup.msubsup.mtable.mtd.mtext.mtr.munder.munderover.mprescripts`.split(`.`)),er=Tn([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),tr=Tn([`#text`]),nr=Tn(`accept.action.align.alt.autocapitalize.autocomplete.autopictureinpicture.autoplay.background.bgcolor.border.capture.cellpadding.cellspacing.checked.cite.class.clear.color.cols.colspan.controls.controlslist.coords.crossorigin.datetime.decoding.default.dir.disabled.disablepictureinpicture.disableremoteplayback.download.draggable.enctype.enterkeyhint.exportparts.face.for.headers.height.hidden.high.href.hreflang.id.inert.inputmode.integrity.ismap.kind.label.lang.list.loading.loop.low.max.maxlength.media.method.min.minlength.multiple.muted.name.nonce.noshade.novalidate.nowrap.open.optimum.part.pattern.placeholder.playsinline.popover.popovertarget.popovertargetaction.poster.preload.pubdate.radiogroup.readonly.rel.required.rev.reversed.role.rows.rowspan.spellcheck.scope.selected.shape.size.sizes.slot.span.srclang.start.src.srcset.step.style.summary.tabindex.title.translate.type.usemap.valign.value.width.wrap.xmlns.slot`.split(`.`)),rr=Tn(`accent-height.accumulate.additive.alignment-baseline.amplitude.ascent.attributename.attributetype.azimuth.basefrequency.baseline-shift.begin.bias.by.class.clip.clippathunits.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.cx.cy.d.dx.dy.diffuseconstant.direction.display.divisor.dur.edgemode.elevation.end.exponent.fill.fill-opacity.fill-rule.filter.filterunits.flood-color.flood-opacity.font-family.font-size.font-size-adjust.font-stretch.font-style.font-variant.font-weight.fx.fy.g1.g2.glyph-name.glyphref.gradientunits.gradienttransform.height.href.id.image-rendering.in.in2.intercept.k.k1.k2.k3.k4.kerning.keypoints.keysplines.keytimes.lang.lengthadjust.letter-spacing.kernelmatrix.kernelunitlength.lighting-color.local.marker-end.marker-mid.marker-start.markerheight.markerunits.markerwidth.maskcontentunits.maskunits.max.mask.mask-type.media.method.mode.min.name.numoctaves.offset.operator.opacity.order.orient.orientation.origin.overflow.paint-order.path.pathlength.patterncontentunits.patterntransform.patternunits.points.preservealpha.preserveaspectratio.primitiveunits.r.rx.ry.radius.refx.refy.repeatcount.repeatdur.restart.result.rotate.scale.seed.shape-rendering.slope.specularconstant.specularexponent.spreadmethod.startoffset.stddeviation.stitchtiles.stop-color.stop-opacity.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke.stroke-width.style.surfacescale.systemlanguage.tabindex.tablevalues.targetx.targety.transform.transform-origin.text-anchor.text-decoration.text-rendering.textlength.type.u1.u2.unicode.values.viewbox.visibility.version.vert-adv-y.vert-origin-x.vert-origin-y.width.word-spacing.wrap.writing-mode.xchannelselector.ychannelselector.x.x1.x2.xmlns.y.y1.y2.z.zoomandpan`.split(`.`)),ir=Tn(`accent.accentunder.align.bevelled.close.columnsalign.columnlines.columnspan.denomalign.depth.dir.display.displaystyle.encoding.fence.frame.height.href.id.largeop.length.linethickness.lspace.lquote.mathbackground.mathcolor.mathsize.mathvariant.maxsize.minsize.movablelimits.notation.numalign.open.rowalign.rowlines.rowspacing.rowspan.rspace.rquote.scriptlevel.scriptminsize.scriptsizemultiplier.selection.separator.separators.stretchy.subscriptshift.supscriptshift.symmetric.voffset.width.xmlns`.split(`.`)),ar=Tn([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),or=En(/\{\{[\w\W]*|[\w\W]*\}\}/gm),sr=En(/<%[\w\W]*|[\w\W]*%>/gm),cr=En(/\$\{[\w\W]*/gm),lr=En(/^data-[\-\w.\u00B7-\uFFFF]+$/),ur=En(/^aria-[\-\w]+$/),dr=En(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),fr=En(/^(?:\w+script|data):/i),pr=En(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),mr=En(/^html$/i),hr=En(/^[a-z][.\w]*(-[.\w]+)+$/i),gr=Object.freeze({__proto__:null,ARIA_ATTR:ur,ATTR_WHITESPACE:pr,CUSTOM_ELEMENT:hr,DATA_ATTR:lr,DOCTYPE_NAME:mr,ERB_EXPR:sr,IS_ALLOWED_URI:dr,IS_SCRIPT_OR_DATA:fr,MUSTACHE_EXPR:or,TMPLIT_EXPR:cr}),_r={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},vr=function(){return typeof window>`u`?null:window},yr=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch{return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},br=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function xr(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:vr(),t=e=>xr(e);if(t.version=`3.3.3`,t.removed=[],!e||!e.document||e.document.nodeType!==_r.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e,r=n,i=r.currentScript,{DocumentFragment:a,HTMLTemplateElement:o,Node:s,Element:c,NodeFilter:l,NamedNodeMap:u=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:d,DOMParser:f,trustedTypes:p}=e,m=c.prototype,h=Jn(m,`cloneNode`),g=Jn(m,`remove`),_=Jn(m,`nextSibling`),v=Jn(m,`childNodes`),y=Jn(m,`parentNode`);if(typeof o==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let b,x=``,{implementation:S,createNodeIterator:C,createDocumentFragment:w,getElementsByTagName:T}=n,{importNode:E}=r,D=br();t.isSupported=typeof bn==`function`&&typeof y==`function`&&S&&S.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:O,ERB_EXPR:k,TMPLIT_EXPR:A,DATA_ATTR:ee,ARIA_ATTR:j,IS_SCRIPT_OR_DATA:te,ATTR_WHITESPACE:ne,CUSTOM_ELEMENT:re}=gr,{IS_ALLOWED_URI:ie}=gr,M=null,N=J({},[...Yn,...Xn,...Zn,...$n,...tr]),P=null,ae=J({},[...nr,...rr,...ir,...ar]),F=Object.seal(Dn(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),I=null,L=null,R=Object.seal(Dn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),z=!0,oe=!0,se=!1,ce=!0,le=!1,ue=!0,de=!1,fe=!1,pe=!1,me=!1,B=!1,he=!1,ge=!0,_e=!1,ve=!0,ye=!1,be={},xe=null,Se=J({},[`annotation-xml`,`audio`,`colgroup`,`desc`,`foreignobject`,`head`,`iframe`,`math`,`mi`,`mn`,`mo`,`ms`,`mtext`,`noembed`,`noframes`,`noscript`,`plaintext`,`script`,`style`,`svg`,`template`,`thead`,`title`,`video`,`xmp`]),Ce=null,we=J({},[`audio`,`video`,`img`,`source`,`image`,`track`]),Te=null,Ee=J({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),De=`http://www.w3.org/1998/Math/MathML`,Oe=`http://www.w3.org/2000/svg`,ke=`http://www.w3.org/1999/xhtml`,Ae=ke,je=!1,Me=null,Ne=J({},[De,Oe,ke],In),Pe=J({},[`mi`,`mo`,`mn`,`ms`,`mtext`]),Fe=J({},[`annotation-xml`]),Ie=J({},[`title`,`style`,`font`,`a`,`script`]),Le=null,V=[`application/xhtml+xml`,`text/html`],Re=null,H=null,ze=n.createElement(`form`),Be=function(e){return e instanceof RegExp||e instanceof Function},Ve=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(H&&H===e)){if((!e||typeof e!=`object`)&&(e={}),e=qn(e),Le=V.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,Re=Le===`application/xhtml+xml`?In:Fn,M=Vn(e,`ALLOWED_TAGS`)?J({},e.ALLOWED_TAGS,Re):N,P=Vn(e,`ALLOWED_ATTR`)?J({},e.ALLOWED_ATTR,Re):ae,Me=Vn(e,`ALLOWED_NAMESPACES`)?J({},e.ALLOWED_NAMESPACES,In):Ne,Te=Vn(e,`ADD_URI_SAFE_ATTR`)?J(qn(Ee),e.ADD_URI_SAFE_ATTR,Re):Ee,Ce=Vn(e,`ADD_DATA_URI_TAGS`)?J(qn(we),e.ADD_DATA_URI_TAGS,Re):we,xe=Vn(e,`FORBID_CONTENTS`)?J({},e.FORBID_CONTENTS,Re):Se,I=Vn(e,`FORBID_TAGS`)?J({},e.FORBID_TAGS,Re):qn({}),L=Vn(e,`FORBID_ATTR`)?J({},e.FORBID_ATTR,Re):qn({}),be=Vn(e,`USE_PROFILES`)?e.USE_PROFILES:!1,z=e.ALLOW_ARIA_ATTR!==!1,oe=e.ALLOW_DATA_ATTR!==!1,se=e.ALLOW_UNKNOWN_PROTOCOLS||!1,ce=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,le=e.SAFE_FOR_TEMPLATES||!1,ue=e.SAFE_FOR_XML!==!1,de=e.WHOLE_DOCUMENT||!1,me=e.RETURN_DOM||!1,B=e.RETURN_DOM_FRAGMENT||!1,he=e.RETURN_TRUSTED_TYPE||!1,pe=e.FORCE_BODY||!1,ge=e.SANITIZE_DOM!==!1,_e=e.SANITIZE_NAMED_PROPS||!1,ve=e.KEEP_CONTENT!==!1,ye=e.IN_PLACE||!1,ie=e.ALLOWED_URI_REGEXP||dr,Ae=e.NAMESPACE||ke,Pe=e.MATHML_TEXT_INTEGRATION_POINTS||Pe,Fe=e.HTML_INTEGRATION_POINTS||Fe,F=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&Be(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(F.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&Be(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(F.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements==`boolean`&&(F.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),le&&(oe=!1),B&&(me=!0),be&&(M=J({},tr),P=Dn(null),be.html===!0&&(J(M,Yn),J(P,nr)),be.svg===!0&&(J(M,Xn),J(P,rr),J(P,ar)),be.svgFilters===!0&&(J(M,Zn),J(P,rr),J(P,ar)),be.mathMl===!0&&(J(M,$n),J(P,ir),J(P,ar))),Vn(e,`ADD_TAGS`)||(R.tagCheck=null),Vn(e,`ADD_ATTR`)||(R.attributeCheck=null),e.ADD_TAGS&&(typeof e.ADD_TAGS==`function`?R.tagCheck=e.ADD_TAGS:(M===N&&(M=qn(M)),J(M,e.ADD_TAGS,Re))),e.ADD_ATTR&&(typeof e.ADD_ATTR==`function`?R.attributeCheck=e.ADD_ATTR:(P===ae&&(P=qn(P)),J(P,e.ADD_ATTR,Re))),e.ADD_URI_SAFE_ATTR&&J(Te,e.ADD_URI_SAFE_ATTR,Re),e.FORBID_CONTENTS&&(xe===Se&&(xe=qn(xe)),J(xe,e.FORBID_CONTENTS,Re)),e.ADD_FORBID_CONTENTS&&(xe===Se&&(xe=qn(xe)),J(xe,e.ADD_FORBID_CONTENTS,Re)),ve&&(M[`#text`]=!0),de&&J(M,[`html`,`head`,`body`]),M.table&&(J(M,[`tbody`]),delete I.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw Un(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw Un(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);b=e.TRUSTED_TYPES_POLICY,x=b.createHTML(``)}else b===void 0&&(b=yr(p,i)),b!==null&&typeof x==`string`&&(x=b.createHTML(``));Tn&&Tn(e),H=e}},He=J({},[...Xn,...Zn,...Qn]),Ue=J({},[...$n,...er]),We=function(e){let t=y(e);(!t||!t.tagName)&&(t={namespaceURI:Ae,tagName:`template`});let n=Fn(e.tagName),r=Fn(t.tagName);return Me[e.namespaceURI]?e.namespaceURI===Oe?t.namespaceURI===ke?n===`svg`:t.namespaceURI===De?n===`svg`&&(r===`annotation-xml`||Pe[r]):!!He[n]:e.namespaceURI===De?t.namespaceURI===ke?n===`math`:t.namespaceURI===Oe?n===`math`&&Fe[r]:!!Ue[n]:e.namespaceURI===ke?t.namespaceURI===Oe&&!Fe[r]||t.namespaceURI===De&&!Pe[r]?!1:!Ue[n]&&(Ie[n]||!He[n]):!!(Le===`application/xhtml+xml`&&Me[e.namespaceURI]):!1},Ge=function(e){Nn(t.removed,{element:e});try{y(e).removeChild(e)}catch{g(e)}},Ke=function(e,n){try{Nn(t.removed,{attribute:n.getAttributeNode(e),from:n})}catch{Nn(t.removed,{attribute:null,from:n})}if(n.removeAttribute(e),e===`is`)if(me||B)try{Ge(n)}catch{}else try{n.setAttribute(e,``)}catch{}},qe=function(e){let t=null,r=null;if(pe)e=`<remove></remove>`+e;else{let t=Ln(e,/^[\r\n\t ]+/);r=t&&t[0]}Le===`application/xhtml+xml`&&Ae===ke&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=b?b.createHTML(e):e;if(Ae===ke)try{t=new f().parseFromString(i,Le)}catch{}if(!t||!t.documentElement){t=S.createDocument(Ae,`template`,null);try{t.documentElement.innerHTML=je?x:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),Ae===ke?T.call(t,de?`html`:`body`)[0]:de?t.documentElement:a},Je=function(e){return C.call(e.ownerDocument||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Ye=function(e){return e instanceof d&&(typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||!(e.attributes instanceof u)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`)},U=function(e){return typeof s==`function`&&e instanceof s};function Xe(e,n,r){An(e,e=>{e.call(t,n,r,H)})}let Ze=function(e){let n=null;if(Xe(D.beforeSanitizeElements,e,null),Ye(e))return Ge(e),!0;let r=Re(e.nodeName);if(Xe(D.uponSanitizeElement,e,{tagName:r,allowedTags:M}),ue&&e.hasChildNodes()&&!U(e.firstElementChild)&&Hn(/<[/\w!]/g,e.innerHTML)&&Hn(/<[/\w!]/g,e.textContent)||e.nodeType===_r.progressingInstruction||ue&&e.nodeType===_r.comment&&Hn(/<[/\w]/g,e.data))return Ge(e),!0;if(!(R.tagCheck instanceof Function&&R.tagCheck(r))&&(!M[r]||I[r])){if(!I[r]&&$e(r)&&(F.tagNameCheck instanceof RegExp&&Hn(F.tagNameCheck,r)||F.tagNameCheck instanceof Function&&F.tagNameCheck(r)))return!1;if(ve&&!xe[r]){let t=y(e)||e.parentNode,n=v(e)||e.childNodes;if(n&&t){let r=n.length;for(let i=r-1;i>=0;--i){let r=h(n[i],!0);r.__removalCount=(e.__removalCount||0)+1,t.insertBefore(r,_(e))}}}return Ge(e),!0}return e instanceof c&&!We(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&Hn(/<\/no(script|embed|frames)/i,e.innerHTML)?(Ge(e),!0):(le&&e.nodeType===_r.text&&(n=e.textContent,An([O,k,A],e=>{n=Rn(n,e,` `)}),e.textContent!==n&&(Nn(t.removed,{element:e.cloneNode()}),e.textContent=n)),Xe(D.afterSanitizeElements,e,null),!1)},Qe=function(e,t,r){if(L[t]||ge&&(t===`id`||t===`name`)&&(r in n||r in ze))return!1;if(!(oe&&!L[t]&&Hn(ee,t))&&!(z&&Hn(j,t))&&!(R.attributeCheck instanceof Function&&R.attributeCheck(t,e))){if(!P[t]||L[t]){if(!($e(e)&&(F.tagNameCheck instanceof RegExp&&Hn(F.tagNameCheck,e)||F.tagNameCheck instanceof Function&&F.tagNameCheck(e))&&(F.attributeNameCheck instanceof RegExp&&Hn(F.attributeNameCheck,t)||F.attributeNameCheck instanceof Function&&F.attributeNameCheck(t,e))||t===`is`&&F.allowCustomizedBuiltInElements&&(F.tagNameCheck instanceof RegExp&&Hn(F.tagNameCheck,r)||F.tagNameCheck instanceof Function&&F.tagNameCheck(r))))return!1}else if(!Te[t]&&!Hn(ie,Rn(r,ne,``))&&!((t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&zn(r,`data:`)===0&&Ce[e])&&!(se&&!Hn(te,Rn(r,ne,``)))&&r)return!1}return!0},$e=function(e){return e!==`annotation-xml`&&Ln(e,re)},et=function(e){Xe(D.beforeSanitizeAttributes,e,null);let{attributes:n}=e;if(!n||Ye(e))return;let r={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:P,forceKeepAttr:void 0},i=n.length;for(;i--;){let{name:a,namespaceURI:o,value:s}=n[i],c=Re(a),l=s,u=a===`value`?l:Bn(l);if(r.attrName=c,r.attrValue=u,r.keepAttr=!0,r.forceKeepAttr=void 0,Xe(D.uponSanitizeAttribute,e,r),u=r.attrValue,_e&&(c===`id`||c===`name`)&&(Ke(a,e),u=`user-content-`+u),ue&&Hn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,u)){Ke(a,e);continue}if(c===`attributename`&&Ln(u,`href`)){Ke(a,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){Ke(a,e);continue}if(!ce&&Hn(/\/>/i,u)){Ke(a,e);continue}le&&An([O,k,A],e=>{u=Rn(u,e,` `)});let d=Re(e.nodeName);if(!Qe(d,c,u)){Ke(a,e);continue}if(b&&typeof p==`object`&&typeof p.getAttributeType==`function`&&!o)switch(p.getAttributeType(d,c)){case`TrustedHTML`:u=b.createHTML(u);break;case`TrustedScriptURL`:u=b.createScriptURL(u);break}if(u!==l)try{o?e.setAttributeNS(o,a,u):e.setAttribute(a,u),Ye(e)?Ge(e):Mn(t.removed)}catch{Ke(a,e)}}Xe(D.afterSanitizeAttributes,e,null)},tt=function e(t){let n=null,r=Je(t);for(Xe(D.beforeSanitizeShadowDOM,t,null);n=r.nextNode();)Xe(D.uponSanitizeShadowNode,n,null),Ze(n),et(n),n.content instanceof a&&e(n.content);Xe(D.afterSanitizeShadowDOM,t,null)};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,o=null,c=null,l=null;if(je=!e,je&&(e=`<!-->`),typeof e!=`string`&&!U(e))if(typeof e.toString==`function`){if(e=e.toString(),typeof e!=`string`)throw Un(`dirty is not a string, aborting`)}else throw Un(`toString is not a function`);if(!t.isSupported)return e;if(fe||Ve(n),t.removed=[],typeof e==`string`&&(ye=!1),ye){if(e.nodeName){let t=Re(e.nodeName);if(!M[t]||I[t])throw Un(`root node is forbidden and cannot be sanitized in-place`)}}else if(e instanceof s)i=qe(`<!---->`),o=i.ownerDocument.importNode(e,!0),o.nodeType===_r.element&&o.nodeName===`BODY`||o.nodeName===`HTML`?i=o:i.appendChild(o);else{if(!me&&!le&&!de&&e.indexOf(`<`)===-1)return b&&he?b.createHTML(e):e;if(i=qe(e),!i)return me?null:he?x:``}i&&pe&&Ge(i.firstChild);let u=Je(ye?e:i);for(;c=u.nextNode();)Ze(c),et(c),c.content instanceof a&&tt(c.content);if(ye)return e;if(me){if(B)for(l=w.call(i.ownerDocument);i.firstChild;)l.appendChild(i.firstChild);else l=i;return(P.shadowroot||P.shadowrootmode)&&(l=E.call(r,l,!0)),l}let d=de?i.outerHTML:i.innerHTML;return de&&M[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&Hn(mr,i.ownerDocument.doctype.name)&&(d=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
|
|
66
|
+
`+d),le&&An([O,k,A],e=>{d=Rn(d,e,` `)}),b&&he?b.createHTML(d):d},t.setConfig=function(){Ve(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),fe=!0},t.clearConfig=function(){H=null,fe=!1},t.isValidAttribute=function(e,t,n){return H||Ve({}),Qe(Re(e),Re(t),n)},t.addHook=function(e,t){typeof t==`function`&&Nn(D[e],t)},t.removeHook=function(e,t){if(t!==void 0){let n=jn(D[e],t);return n===-1?void 0:Pn(D[e],n,1)[0]}return Mn(D[e])},t.removeHooks=function(e){D[e]=[]},t.removeAllHooks=function(){D=br()},t}var Sr=xr(),Cr=Sr.sanitize.bind(Sr);Sr.isSupported,Sr.addHook.bind(Sr),Sr.removeHook.bind(Sr),Sr.removeHooks.bind(Sr),Sr.removeAllHooks.bind(Sr),Sr.setConfig.bind(Sr),Sr.clearConfig.bind(Sr),Sr.isValidAttribute.bind(Sr),Sr.version,Sr.removed;function wr(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function Tr(e,t){let n=wr(e);return t===`shtml`||([`js`,`javascript`,`ts`,`typescript`,`jsx`,`tsx`].includes(t)?n=Er(n):t===`json`?n=Dr(n):[`bash`,`sh`,`shell`,`zsh`].includes(t)&&(n=Or(n))),n}function Er(e){return e=e.replace(/(\/\/[^\n]*)/g,`<span class="tok-comment">$1</span>`),e=e.replace(/(\/\*[\s\S]*?\*\/)/g,`<span class="tok-comment">$1</span>`),e=e.replace(/("[^&]*?"|'[^&]*?'|`[^`]*?`)/g,`<span class="tok-string">$1</span>`),e=e.replace(RegExp(`\\b(${`const.let.var.function.return.if.else.for.while.class.extends.import.export.from.default.new.this.async.await.try.catch.throw.typeof.instanceof.interface.type.enum.implements.abstract.public.private.protected.readonly.static.void.null.undefined.true.false`.split(`.`).join(`|`)})\\b`,`g`),`<span class="tok-keyword">$1</span>`),e=e.replace(/\b(\d+\.?\d*)\b/g,`<span class="tok-number">$1</span>`),e=e.replace(/\b([a-zA-Z_$][\w$]*)\s*(?=\()/g,`<span class="tok-fn">$1</span>`),e}function Dr(e){return e=e.replace(/("[^&]*?")\s*:/g,`<span class="tok-keyword">$1</span>:`),e=e.replace(/:\s*("[^&]*?")/g,`: <span class="tok-string">$1</span>`),e=e.replace(/\b(\d+\.?\d*)\b/g,`<span class="tok-number">$1</span>`),e=e.replace(/\b(true|false|null)\b/g,`<span class="tok-keyword">$1</span>`),e}function Or(e){return e=e.replace(/(#[^\n]*)/g,`<span class="tok-comment">$1</span>`),e=e.replace(/("[^&]*?"|'[^&]*?')/g,`<span class="tok-string">$1</span>`),e=e.replace(RegExp(`\\b(${[`if`,`then`,`else`,`fi`,`for`,`do`,`done`,`while`,`case`,`esac`,`echo`,`export`,`cd`,`ls`,`mkdir`,`rm`,`cp`,`mv`,`cat`,`grep`,`npm`,`node`,`git`].join(`|`)})\\b`,`g`),`<span class="tok-keyword">$1</span>`),e}var kr=new K({gfm:!0,breaks:!0,async:!1,renderer:{code({text:e,lang:t}){let n=t??``,r=Tr(e,n);return`<pre><code${n?` class="language-${wr(n)}"`:``}>${r}</code></pre>\n`},link({href:e,title:t,tokens:n}){let r=e??``;if(r.startsWith(`javascript:`))return this.parser.parseInline(n);let i=t?` title="${wr(t)}"`:``,a=this.parser.parseInline(n);return`<a href="${wr(r)}"${i} target="_blank" rel="noopener noreferrer">${a}</a>`}}}),Ar={ALLOWED_TAGS:`a.b.i.em.strong.p.br.code.pre.ul.ol.li.h1.h2.h3.h4.h5.h6.table.thead.tbody.tr.th.td.del.blockquote.hr.img.span.div.details.summary.input`.split(`.`),ALLOWED_ATTR:[`href`,`src`,`alt`,`title`,`class`,`target`,`rel`,`type`,`checked`,`disabled`],ALLOW_DATA_ATTR:!1};function jr(e){return Cr(e,Ar)}function Mr(e){return e.replace(/<a\s([^>]*?)>/g,(e,t)=>{let n=t;return/(^|\s)target\s*=/i.test(n)?n=n.replace(/(^|\s)target\s*=\s*(['"])[^'"]*\2/gi,`$1target="_blank"`):n+=` target="_blank"`,/(^|\s)rel\s*=/i.test(n)?n=n.replace(/(^|\s)rel\s*=\s*(['"])[^'"]*\2/gi,`$1rel="noopener noreferrer"`):n+=` rel="noopener noreferrer"`,`<a ${n}>`})}var Nr=/<p><strong>Error:<\/strong>\s*([\s\S]*?)<\/p>/g;function Pr(e){return Mr(jr(kr.parse(e)))}function Fr(e){return e.replace(Nr,(e,t)=>`<div class="msg__error" role="alert"><div class="msg__error-label">Error</div><div class="msg__error-body">${t}</div></div>`)}function Ir(e){return Pr(e)}function Lr(e){return Fr(Pr(e))}function Rr(e){if(typeof e==`string`)return wr(e);try{return wr(JSON.stringify(e,null,2))}catch{return wr(String(e))}}var zr=`browser-coding-agent`,Br=1,Vr=`sessions`;function Hr(){return new Promise((e,t)=>{let n=indexedDB.open(zr,Br);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Vr)||e.createObjectStore(Vr,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var Ur=class{db=null;async init(){this.db=await Hr()}ensureDb(){if(!this.db)throw Error(`SessionStore not initialized. Call init() first.`);return this.db}async save(e){let t=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(Vr,`readwrite`);i.objectStore(Vr).put(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(Vr,`readonly`).objectStore(Vr).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async list(){let e=this.ensureDb();return new Promise((t,n)=>{let r=e.transaction(Vr,`readonly`).objectStore(Vr).getAll();r.onsuccess=()=>{t(r.result.sort((e,t)=>t.updatedAt-e.updatedAt).map(e=>e.id))},r.onerror=()=>n(r.error)})}async delete(e){let t=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(Vr,`readwrite`);i.objectStore(Vr).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async saveMessages(e,t){let n=await this.load(e),r=n?{...n,messages:t,updatedAt:Date.now()}:{id:e,messages:t,createdAt:Date.now(),updatedAt:Date.now()};await this.save(r)}},Wr={"not-allowed":`Microphone access denied. Check Chrome site permissions.`,"no-speech":`No speech detected. Try again.`,"audio-capture":`No microphone found. Check your audio input device.`,network:`Voice input requires an internet connection.`,aborted:`Voice input was interrupted.`,"service-not-available":`Speech recognition service unavailable. Try again later.`,"start-failed":`Failed to start speech recognition.`,"not-supported":`Speech recognition is not supported in this browser.`};function Gr(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function Kr(){return typeof window>`u`?null:window.SpeechRecognition||window.webkitSpeechRecognition||null}var qr=class e{recognition=null;_isListening=!1;shouldBeListening=!1;options;debounceTimer=null;autoSendTimer=null;pendingTranscript=``;consecutiveRestarts=0;inactivityTimer=null;messageListener=null;popupWindowId=null;constructor(e){this.options=e}start(){if(this._isListening)return;this.debounceTimer&&=(clearTimeout(this.debounceTimer),null);let e=Kr();if(!e){this.options.onError(`Speech recognition is not supported in this browser.`),this.options.onStateChange(`error`);return}this.shouldBeListening=!0,this.pendingTranscript=``,this.consecutiveRestarts=0,this.cancelAutoSend(),this.resetInactivityTimer(),navigator.mediaDevices?.getUserMedia?navigator.mediaDevices.getUserMedia({audio:!0}).then(t=>{for(let e of t.getTracks())e.stop();this.shouldBeListening&&this.startRecognition(new e)}).catch(e=>{if(this.shouldBeListening)if(Gr())this.startExtensionPopup();else{this.shouldBeListening=!1;let t=e?.name,n=Wr[`not-allowed`];t===`NotFoundError`?n=Wr[`audio-capture`]:t===`NotReadableError`&&(n=`Microphone is in use by another app. Try again.`),this.options.onError(n),this.options.onStateChange(`error`)}}):this.startRecognition(new e)}startExtensionPopup(){let e=this.options.lang??`en-US`,t=chrome.runtime.getURL(`voice-popup.html?lang=${encodeURIComponent(e)}`);chrome.windows.create({url:t,type:`popup`,width:300,height:68,focused:!0}).then(e=>{this.shouldBeListening&&(this.setupExtensionListener(),e?.id&&(this.popupWindowId=e.id))}).catch(()=>{this.shouldBeListening=!1,this.options.onError(`Failed to open voice input window.`),this.options.onStateChange(`error`)})}setupExtensionListener(){this.messageListener||(this.messageListener=e=>{if(e.source===`voice-popup`)switch(e.type){case`speech-result`:if(e.isFinal)this.pendingTranscript+=(this.pendingTranscript?` `:``)+e.text,this.options.onTranscript(this.pendingTranscript,!0),this.scheduleAutoSend();else{let t=this.pendingTranscript?this.pendingTranscript+` `+e.text:e.text;this.options.onTranscript(t,!1),this.cancelAutoSend()}break;case`speech-error`:{let t=Wr[e.error]??`Speech recognition error: ${e.error}`;this.options.onError(t),e.fatal&&(this._isListening=!1,this.shouldBeListening=!1,this.popupWindowId=null,this.options.onStateChange(`error`));break}case`speech-state`:e.state===`listening`&&(this._isListening=!0,this.options.onStateChange(`listening`));break;case`speech-end`:this._isListening=!1,this.shouldBeListening=!1,this.popupWindowId=null,this.options.onStateChange(`idle`);break}},chrome.runtime.onMessage.addListener(this.messageListener))}removeExtensionListener(){this.messageListener&&=(chrome.runtime.onMessage.removeListener(this.messageListener),null)}startRecognition(e){this.recognition=e,this.recognition.continuous=!0,this.recognition.interimResults=!0,this.recognition.lang=this.options.lang??`en-US`,this.recognition.onresult=e=>{this.consecutiveRestarts=0,this.resetInactivityTimer();let t=``,n=``;for(let r=e.resultIndex;r<e.results.length;r++){let i=e.results[r];i.isFinal?n+=i[0].transcript:t+=i[0].transcript}if(n)this.pendingTranscript+=(this.pendingTranscript?` `:``)+n,this.options.onTranscript(this.pendingTranscript,!0),this.scheduleAutoSend();else if(t){let e=this.pendingTranscript?this.pendingTranscript+` `+t:t;this.options.onTranscript(e,!1),this.cancelAutoSend()}},this.recognition.onerror=e=>{let t=e.error,n=Wr[t]??`Speech recognition error: ${t}`;if(t===`no-speech`){this.options.onError(n);return}t!==`aborted`&&(this._isListening=!1,this.shouldBeListening=!1,this.options.onError(n),this.options.onStateChange(`error`))},this.recognition.onend=()=>{if(this._isListening=!1,this.recognition&&=(this.recognition.onresult=null,this.recognition.onerror=null,this.recognition.onend=null,null),this.shouldBeListening){this.consecutiveRestarts++;let e=Math.min(300*2**(this.consecutiveRestarts-1),5e3),t=Kr();this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.shouldBeListening&&t?this.startRecognition(new t):this.shouldBeListening&&(this.shouldBeListening=!1,this.options.onStateChange(`idle`))},e);return}this.options.onStateChange(`idle`)};try{this.recognition.start(),this._isListening=!0,this.options.onStateChange(`listening`)}catch{this.shouldBeListening=!1,this.options.onError(`Failed to start speech recognition.`),this.options.onStateChange(`error`)}}static SEND_DELAY_MS=2500;static INACTIVITY_TIMEOUT_MS=12e4;scheduleAutoSend(){this.cancelAutoSend(),this.options.autoSend&&(this.autoSendTimer=setTimeout(()=>{this.autoSendTimer=null;let e=this.pendingTranscript.trim();e&&(this.pendingTranscript=``,this.options.onAutoSend(e))},e.SEND_DELAY_MS))}cancelAutoSend(){this.autoSendTimer&&=(clearTimeout(this.autoSendTimer),null)}resetInactivityTimer(){this.clearInactivityTimer(),this.options.onAutoDisable&&(this.inactivityTimer=setTimeout(()=>{this.inactivityTimer=null,this.stop(),this.options.onAutoDisable?.()},e.INACTIVITY_TIMEOUT_MS))}clearInactivityTimer(){this.inactivityTimer&&=(clearTimeout(this.inactivityTimer),null)}stop(){if(this.shouldBeListening=!1,this.cancelAutoSend(),this.clearInactivityTimer(),this.pendingTranscript=``,this.debounceTimer&&=(clearTimeout(this.debounceTimer),null),this.popupWindowId!=null){try{chrome.runtime.sendMessage({target:`voice-popup`,type:`voice-stop`})}catch{}chrome.windows.remove(this.popupWindowId).catch(()=>{}),this.popupWindowId=null}else if(this.recognition){this.recognition.onresult=null,this.recognition.onerror=null,this.recognition.onend=null;try{this.recognition.stop()}catch{}this.recognition=null}this._isListening=!1,this.options.onStateChange(`idle`)}toggle(){this._isListening||this.shouldBeListening?this.stop():this.start()}isListening(){return this._isListening||this.shouldBeListening}setAutoSend(e){this.options.autoSend=e}destroy(){this.stop(),this.removeExtensionListener(),this.recognition=null}},Jr={autoSend:`voice-auto-send`,lang:`voice-lang`};function Yr(){return localStorage.getItem(Jr.lang)||`en-US`}var Xr=typeof chrome<`u`&&!!chrome?.runtime?.id;function Zr(e){let t=e.trimStart().toLowerCase();return t.startsWith(`<!doctype`)||t.startsWith(`<html`)}var Qr=class{container;bridge;scripts=[];iframe=null;messageHandler=null;constructor(e,t){this.container=e,this.bridge=t}async render(e,t){this.dispose(),Xr?await this.renderInSandbox(e,t,Zr(e)):Zr(e)?await this.renderFullDoc(e,t):this.renderInline(e,t)}async renderInSandbox(e,t,n=!1){let r=document.createElement(`iframe`);r.src=chrome.runtime.getURL(`sprinkle-sandbox.html`),r.style.cssText=`width: 100%; flex: 1; border: none; min-height: 0;`,this.iframe=r,console.log(`[sprinkle-renderer] creating sandbox iframe`,r.src),await new Promise((e,t)=>{let n=setTimeout(()=>{console.error(`[sprinkle-renderer] iframe load timed out after 5s`),t(Error(`sprinkle sandbox iframe load timed out`))},5e3);r.addEventListener(`load`,()=>{clearTimeout(n),console.log(`[sprinkle-renderer] iframe loaded, contentWindow:`,!!r.contentWindow),e()},{once:!0}),r.addEventListener(`error`,e=>{clearTimeout(n),console.error(`[sprinkle-renderer] iframe error:`,e),t(Error(`sprinkle sandbox iframe failed to load`))},{once:!0}),this.container.appendChild(r)}),this.messageHandler=e=>{if(e.source!==r.contentWindow)return;let n=e.data;if(n?.type)if(n.type===`sprinkle-lick`)this.bridge.lick({action:n.action,data:n.data});else if(n.type===`sprinkle-set-state`)this.bridge.setState(n.data);else if(n.type===`sprinkle-close`)this.bridge.close();else if(n.type===`sprinkle-storage-set`)try{localStorage.setItem(`slicc-sprinkle-ls:${t}:${n.key}`,n.value)}catch(e){console.warn(`[sprinkle-renderer] localStorage setItem failed:`,n.key,e)}else if(n.type===`sprinkle-storage-remove`)try{localStorage.removeItem(`slicc-sprinkle-ls:${t}:${n.key}`)}catch(e){console.warn(`[sprinkle-renderer] localStorage removeItem failed:`,n.key,e)}else if(n.type===`sprinkle-storage-clear`){let e=`slicc-sprinkle-ls:${t}:`;for(let t=localStorage.length-1;t>=0;t--){let n=localStorage.key(t);n?.startsWith(e)&&localStorage.removeItem(n)}}else n.type===`sprinkle-open`?this.bridge.open(n.path,n.projectRoot?{projectRoot:n.projectRoot}:void 0):n.type===`sprinkle-readfile`?this.bridge.readFile(n.path).then(e=>r.contentWindow?.postMessage({type:`sprinkle-readfile-response`,id:n.id,content:e},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-readfile-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`)):n.type===`sprinkle-writefile`?this.bridge.writeFile(n.path,n.content).then(()=>r.contentWindow?.postMessage({type:`sprinkle-writefile-response`,id:n.id},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-writefile-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`)):n.type===`sprinkle-readdir`?this.bridge.readDir(n.path).then(e=>r.contentWindow?.postMessage({type:`sprinkle-readdir-response`,id:n.id,entries:e},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-readdir-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`)):n.type===`sprinkle-exists`?this.bridge.exists(n.path).then(e=>r.contentWindow?.postMessage({type:`sprinkle-exists-response`,id:n.id,exists:e},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-exists-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`)):n.type===`sprinkle-stat`?this.bridge.stat(n.path).then(e=>r.contentWindow?.postMessage({type:`sprinkle-stat-response`,id:n.id,stat:e},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-stat-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`)):n.type===`sprinkle-mkdir`?this.bridge.mkdir(n.path).then(()=>r.contentWindow?.postMessage({type:`sprinkle-mkdir-response`,id:n.id},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-mkdir-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`)):n.type===`sprinkle-rm`&&this.bridge.rm(n.path).then(()=>r.contentWindow?.postMessage({type:`sprinkle-rm-response`,id:n.id},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-rm-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`))},window.addEventListener(`message`,this.messageHandler);let i=this.collectThemeCSS(),a={},o=`slicc-sprinkle-ls:${t}:`;for(let e=0;e<localStorage.length;e++){let t=localStorage.key(e);t?.startsWith(o)&&(a[t.slice(o.length)]=localStorage.getItem(t)??``)}let s=this.bridge.getState();r.contentWindow.postMessage({type:`sprinkle-render`,content:e,name:t,themeCSS:i,savedState:s,savedStorage:a,fullDoc:n},`*`)}pushUpdate(e){this.iframe?.contentWindow&&this.iframe.contentWindow.postMessage({type:`sprinkle-update`,data:e},`*`)}collectThemeCSS(){return ei()}generateBridgeScript(){return`(function() {
|
|
67
67
|
var _updateListeners = new Set();
|
|
68
68
|
var _sprinkleName = '';
|
|
69
69
|
var _state = null;
|
|
@@ -235,7 +235,7 @@ mark{background:color-mix(in srgb,var(--s2-accent) 25%,transparent);color:inheri
|
|
|
235
235
|
</style>
|
|
236
236
|
<script>${ni}<\/script>
|
|
237
237
|
</head>
|
|
238
|
-
<body class="sprinkle-inline">${t}</body></html>`;if(ti)return oi(e,r,n);let i=document.createElement(`iframe`);i.setAttribute(`sandbox`,`allow-scripts allow-same-origin`),i.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,i.srcdoc=r,e.appendChild(i);let a=e=>{if(e.source!==i.contentWindow)return;let t=e.data;t?.type&&(t.type===`inline-sprinkle-lick`?n(t.action,t.data):t.type===`inline-sprinkle-height`&&(i.style.height=t.height+`px`))};return window.addEventListener(`message`,a),{dispose(){window.removeEventListener(`message`,a),i.remove()}}}function ii(e,t){let n=e.querySelectorAll(`pre > code.language-shtml`);if(n.length===0)return[];let r=[];for(let e of n){let n=e.parentElement,i=e.textContent??``,a=document.createElement(`div`);a.className=`msg__inline-sprinkle`,n.replaceWith(a),r.push(ri(a,i,t))}return r}function ai(e){for(let t of e)try{t.dispose()}catch{}e.length=0}function oi(e,t,n){let r=document.createElement(`iframe`);r.src=chrome.runtime.getURL(`sprinkle-sandbox.html`),r.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,e.appendChild(r);let i=e=>{if(e.source!==r.contentWindow)return;let t=e.data;t?.type&&(t.type===`inline-sprinkle-lick`?n(t.action,t.data):t.type===`inline-sprinkle-height`&&(r.style.height=t.height+`px`))};return window.addEventListener(`message`,i),r.addEventListener(`load`,()=>{r.contentWindow?.postMessage({type:`inline-sprinkle-render`,srcdoc:t},`*`)},{once:!0}),{dispose(){window.removeEventListener(`message`,i),r.remove()}}}var si=n(`tool-ui-renderer`),ci=typeof chrome<`u`&&!!chrome?.runtime?.id,li=class{container;iframe=null;inlineSprinkle=null;messageHandler=null;requestId;nonce;constructor(e,t){this.container=e,this.requestId=t,this.nonce=crypto.randomUUID()}async render(e){ci?await this.renderInSandbox(e):this.renderWithInlineSprinkle(e)}async renderInSandbox(e){let t=document.createElement(`iframe`);t.src=chrome.runtime.getURL(`tool-ui-sandbox.html`),t.style.cssText=`width: 100%; border: none; min-height: 60px;`,this.iframe=t,await new Promise((e,n)=>{let r=setTimeout(()=>{si.error(`Tool UI iframe load timed out`),t.remove(),this.iframe=null,n(Error(`tool-ui sandbox iframe load timed out`))},5e3);t.addEventListener(`load`,()=>{clearTimeout(r),e()},{once:!0}),t.addEventListener(`error`,()=>{clearTimeout(r),t.remove(),this.iframe=null,n(Error(`tool-ui sandbox iframe failed to load`))},{once:!0}),this.container.appendChild(t)}),this.messageHandler=e=>{if(e.source!==t.contentWindow)return;let n=e.data;if(n?.type){if(n.nonce!==this.nonce){si.warn(`Tool UI message nonce mismatch`,{expected:this.nonce,received:n.nonce});return}n.type===`tool-ui-action`&&n.id===this.requestId?(si.info(`Tool UI action received`,{id:n.id,action:n.action}),_.handleAction(n.id,{action:n.action,data:n.data})):n.type===`tool-ui-rendered`&&n.id===this.requestId?n.height&&this.iframe&&(this.iframe.style.height=`${Math.max(60,n.height)}px`):n.type===`tool-ui-resize`&&n.id===this.requestId&&n.height&&this.iframe&&(this.iframe.style.height=`${Math.max(60,n.height)}px`)}},window.addEventListener(`message`,this.messageHandler);let{collectThemeCSS:n}=await v(async()=>{let{collectThemeCSS:e}=await import(`./sprinkle-renderer-4aW_Vd0i.js`);return{collectThemeCSS:e}},[]),r=n();t.contentWindow.postMessage({type:`tool-ui-render`,id:this.requestId,nonce:this.nonce,html:e,themeCSS:r},`*`)}renderWithInlineSprinkle(e){let t=document.createElement(`div`);t.className=`msg__inline-sprinkle`,this.container.appendChild(t),this.inlineSprinkle=ri(t,e,(e,t)=>{si.info(`Tool UI action (inline sprinkle)`,{id:this.requestId,action:e}),_.handleAction(this.requestId,{action:e,data:t})})}dispose(){this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.iframe&&=(this.iframe.remove(),null),this.inlineSprinkle&&=(this.inlineSprinkle.dispose(),null)}},ui=new Map;function di(e,t,n){let r=ui.get(t);r&&r.dispose();let i=new li(e,t);return ui.set(t,i),i.render(n).catch(e=>{si.error(`Failed to render tool UI`,{requestId:t,error:e.message})}),i}function fi(e){let t=ui.get(e);t&&(t.dispose(),ui.delete(e))}var pi=n(`chat-panel`);function mi(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var hi={bash:`$`,browser:`B`,read_file:`R`,write_file:`W`,edit_file:`E`,javascript:`JS`,delegate_to_scoop:`D`,send_message:`M`,schedule_task:`T`,list_scoops:`LS`,list_tasks:`LT`,register_scoop:`RS`,update_global_memory:`GM`};function gi(e){return hi[e]??`?`}function _i(e){return e.role===`assistant`?Lr(e.content):Ir(e.content)}var vi=class{container;messagesEl;messagesInner;inputArea;textarea;sendBtn;stopBtn;micBtn;voiceInput=null;voiceMode=!1;keydownListener=null;messages=[];agent=null;unsubscribe=null;isStreaming=!1;currentStreamId=null;sessionStore;sessionId;readOnly=!1;terminalOutputCallback=null;currentScoopName=null;autoScrollAttached=!0;lastScrollTop=0;jumpPill;onDeleteQueuedMessage=null;pendingDeltaText=``;streamingRafId=null;inlineSprinkles=new Map;onInlineSprinkleLick;modelSelectorEl;handoffsEl;pendingHandoffs=[];onAcceptPendingHandoff=null;onDismissPendingHandoff=null;onModelChange;constructor(e){this.container=e,this.sessionStore=new Ur,this.sessionId=`default`,this.render()}setAgent(e){this.unsubscribe?.(),this.agent=e,this.unsubscribe=e.onEvent(e=>this.handleAgentEvent(e))}onTerminalOutput(e){this.terminalOutputCallback=e}setDeleteQueuedMessageCallback(e){this.onDeleteQueuedMessage=e}async initSession(e){await this.sessionStore.init(),this.sessionId=e??`default`;let t=await this.sessionStore.load(this.sessionId);t&&t.messages.length>0&&(this.messages=t.messages.map(e=>({...e,isStreaming:!1})),this.renderMessages())}async clearSession(){this.messages=[],this.renderMessages(),await this.sessionStore.delete(this.sessionId)}async deleteSessionById(e){await this.sessionStore.delete(e)}async switchToContext(e,t,n){await this.persistSessionAsync(),this.setStreamingState(!1),this.currentStreamId=null,this.cancelPendingDelta(),this.sessionId=e,this.currentScoopName=n??null,this.setReadOnly(t);let r=await this.sessionStore.load(this.sessionId);r&&r.messages.length>0?this.messages=r.messages.map(e=>({...e,isStreaming:!1})):this.messages=[],this.renderMessages()}setReadOnly(e){this.readOnly=e,this.inputArea&&(this.inputArea.style.display=e?`none`:``)}async persistSessionAsync(){try{await this.sessionStore.saveMessages(this.sessionId,this.messages)}catch{}}setProcessing(e){e?this.setStreamingState(!0):this.setStreamingState(!1)}addSystemMessage(e){let t={id:mi(),role:`assistant`,content:e,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t),this.persistSession()}addLickMessage(e,t,n){let r={id:e,role:`user`,content:t,timestamp:Date.now(),source:`lick`,channel:n};this.messages.push(r),this.appendMessageEl(r),this.persistSession()}getMessages(){return[...this.messages]}loadMessages(e){this.messages=e.map(e=>({...e,isStreaming:!1})),this.renderMessages(),this.persistSession(),this.renderModelSelector()}clear(){this.messages=[],this.renderMessages(),this.renderModelSelector()}setPendingHandoffs(e){this.pendingHandoffs=[...e],this.renderPendingHandoffs()}setPendingHandoffActions(e){this.onAcceptPendingHandoff=e.onAccept,this.onDismissPendingHandoff=e.onDismiss,this.renderPendingHandoffs()}addUserMessage(e){let t={id:mi(),role:`user`,content:e,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t)}deleteQueuedMessage(e){let t=this.messages.findIndex(t=>t.id===e);if(t===-1)return;this.messages.splice(t,1);let n=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);n&&n.remove(),this.persistSession(),this.onDeleteQueuedMessage?.(e)}render(){this.container.innerHTML=``,this.container.classList.add(`chat`),this.messagesEl=document.createElement(`div`),this.messagesEl.className=`chat__messages`,this.messagesInner=document.createElement(`div`),this.messagesInner.className=`chat__messages-inner`,this.messagesEl.appendChild(this.messagesInner),this.handoffsEl=document.createElement(`div`),this.handoffsEl.className=`chat__handoffs`,this.handoffsEl.hidden=!0,this.messagesEl.appendChild(this.handoffsEl),this.container.appendChild(this.messagesEl),this.renderPendingHandoffs(),this.messagesEl.addEventListener(`scroll`,()=>{let{scrollTop:e,scrollHeight:t,clientHeight:n}=this.messagesEl;t-e-n<=250?(this.autoScrollAttached=!0,this.hideJumpPill()):e<this.lastScrollTop&&(this.autoScrollAttached=!1),this.lastScrollTop=e},{passive:!0}),this.inputArea=document.createElement(`div`);let e=this.inputArea;e.className=`chat__input-area`;let t=document.createElement(`div`);t.className=`chat__input-area-inner`,this.textarea=document.createElement(`textarea`),this.textarea.className=`chat__textarea`,this.textarea.placeholder=`What shall we build?`,this.textarea.rows=1,this.sendBtn=document.createElement(`button`),this.sendBtn.className=`chat__send-btn`,this.sendBtn.innerHTML=`<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M10 1.25C5.167 1.25 1.25 5.167 1.25 10s3.917 8.75 8.75 8.75 8.75-3.918 8.75-8.75S14.833 1.25 10 1.25zm3.527 8.284a.75.75 0 0 1-1.06 0L10.75 7.82v6.172a.75.75 0 0 1-1.5 0V7.812L7.527 9.534a.75.75 0 1 1-1.06-1.06l2.998-2.998a.75.75 0 0 1 1.06-.001l3.002 2.998a.75.75 0 0 1 0 1.061z"/></svg>`,this.sendBtn.dataset.tooltip=`Send message`,this.sendBtn.dataset.tooltipPos=`top`,this.stopBtn=document.createElement(`button`),this.stopBtn.className=`chat__stop-btn`,this.stopBtn.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M13.75 4H6.25A2.25 2.25 0 0 0 4 6.25v7.5A2.25 2.25 0 0 0 6.25 16h7.5A2.25 2.25 0 0 0 16 13.75v-7.5A2.25 2.25 0 0 0 13.75 4z"/></svg>`,this.stopBtn.dataset.tooltip=`Stop generation`,this.stopBtn.style.display=`none`,this.micBtn=document.createElement(`button`),this.micBtn.className=`chat__mic-btn`;let n=`http://www.w3.org/2000/svg`,r=document.createElementNS(n,`svg`);r.setAttribute(`width`,`16`),r.setAttribute(`height`,`16`),r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`2`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`);let i=document.createElementNS(n,`path`);i.setAttribute(`d`,`M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z`);let a=document.createElementNS(n,`path`);a.setAttribute(`d`,`M19 10v2a7 7 0 0 1-14 0v-2`);let o=document.createElementNS(n,`line`);o.setAttribute(`x1`,`12`),o.setAttribute(`y1`,`19`),o.setAttribute(`x2`,`12`),o.setAttribute(`y2`,`23`);let s=document.createElementNS(n,`line`);s.setAttribute(`x1`,`8`),s.setAttribute(`y1`,`23`),s.setAttribute(`x2`,`16`),s.setAttribute(`y2`,`23`),r.append(i,a,o,s),this.micBtn.appendChild(r),this.micBtn.dataset.tooltip=`Voice (Ctrl+Shift+V)`;let c=document.createElement(`div`);c.className=`chat__input-wrapper`,c.appendChild(this.textarea);let l=document.createElement(`div`);l.className=`chat__action-bar`;let u=document.createElement(`div`);u.className=`chat__action-bar-left`,u.appendChild(this.micBtn),l.appendChild(u),this.modelSelectorEl=document.createElement(`div`),this.modelSelectorEl.className=`chat__model-selector`,this.renderModelSelector(),l.appendChild(this.modelSelectorEl);let d=document.createElement(`div`);d.className=`chat__action-bar-right`,d.appendChild(this.sendBtn),d.appendChild(this.stopBtn),l.appendChild(d),c.appendChild(l),t.appendChild(c),e.appendChild(t),this.container.appendChild(e),this.jumpPill=document.createElement(`button`),this.jumpPill.className=`chat__jump-pill`,this.jumpPill.textContent=`↓ New activity`,this.jumpPill.addEventListener(`click`,()=>{this.autoScrollAttached=!0,this.hideJumpPill(),this.scrollToBottom(!0)}),this.container.appendChild(this.jumpPill),this.textarea.addEventListener(`keydown`,e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.sendMessage())}),this.textarea.addEventListener(`input`,()=>{this.textarea.style.height=`auto`,this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+`px`}),this.sendBtn.addEventListener(`click`,()=>this.sendMessage()),this.stopBtn.addEventListener(`click`,()=>{this.agent?.stop();for(let e of this.messages)e.queued&&(e.queued=!1,this.updateMessageEl(e.id));this.setStreamingState(!1)}),this.voiceInput=new qr({onTranscript:(e,t)=>{this.textarea.value=e,this.textarea.style.height=`auto`,this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+`px`},onStateChange:e=>{e===`error`?(this.voiceMode=!1,this.micBtn.classList.remove(`chat__mic-btn--active`,`chat__mic-btn--listening`)):this.voiceMode?e===`listening`&&this.micBtn.classList.add(`chat__mic-btn--listening`):this.micBtn.classList.toggle(`chat__mic-btn--listening`,e===`listening`)},onError:e=>{pi.debug(`Voice input error`,{error:e}),!(this.voiceMode&&e.includes(`No speech detected`))&&this.addSystemMessage(e)},autoSend:!0,onAutoSend:e=>{this.textarea.value=e,this.sendMessage()},onAutoDisable:()=>{this.voiceMode=!1,this.micBtn.classList.remove(`chat__mic-btn--active`,`chat__mic-btn--listening`),this.addSystemMessage(`Voice mode disabled after 2 minutes of inactivity.`)},lang:Yr()}),this.micBtn.addEventListener(`click`,()=>{this.toggleVoiceMode()}),this.keydownListener=e=>{e.shiftKey&&(e.ctrlKey||e.metaKey)&&e.key===`V`&&(e.preventDefault(),this.toggleVoiceMode())},document.addEventListener(`keydown`,this.keydownListener)}renderPendingHandoffs(){if(!this.handoffsEl)return;if(this.pendingHandoffs.length===0){this.handoffsEl.hidden=!0,this.handoffsEl.innerHTML=``;return}let e=this.pendingHandoffs.length===1?`1 pending handoff`:`${this.pendingHandoffs.length} pending handoffs`;this.handoffsEl.hidden=!1,this.handoffsEl.innerHTML=`
|
|
238
|
+
<body class="sprinkle-inline">${t}</body></html>`;if(ti)return oi(e,r,n);let i=document.createElement(`iframe`);i.setAttribute(`sandbox`,`allow-scripts allow-same-origin`),i.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,i.srcdoc=r,e.appendChild(i);let a=e=>{if(e.source!==i.contentWindow)return;let t=e.data;t?.type&&(t.type===`inline-sprinkle-lick`?n(t.action,t.data):t.type===`inline-sprinkle-height`&&(i.style.height=t.height+`px`))};return window.addEventListener(`message`,a),{dispose(){window.removeEventListener(`message`,a),i.remove()}}}function ii(e,t){let n=e.querySelectorAll(`pre > code.language-shtml`);if(n.length===0)return[];let r=[];for(let e of n){let n=e.parentElement,i=e.textContent??``,a=document.createElement(`div`);a.className=`msg__inline-sprinkle`,n.replaceWith(a),r.push(ri(a,i,t))}return r}function ai(e){for(let t of e)try{t.dispose()}catch{}e.length=0}function oi(e,t,n){let r=document.createElement(`iframe`);r.src=chrome.runtime.getURL(`sprinkle-sandbox.html`),r.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,e.appendChild(r);let i=e=>{if(e.source!==r.contentWindow)return;let t=e.data;t?.type&&(t.type===`inline-sprinkle-lick`?n(t.action,t.data):t.type===`inline-sprinkle-height`&&(r.style.height=t.height+`px`))};return window.addEventListener(`message`,i),r.addEventListener(`load`,()=>{r.contentWindow?.postMessage({type:`inline-sprinkle-render`,srcdoc:t},`*`)},{once:!0}),{dispose(){window.removeEventListener(`message`,i),r.remove()}}}var si=n(`tool-ui-renderer`),ci=typeof chrome<`u`&&!!chrome?.runtime?.id,li=class{container;iframe=null;inlineSprinkle=null;messageHandler=null;requestId;nonce;constructor(e,t){this.container=e,this.requestId=t,this.nonce=crypto.randomUUID()}async render(e){ci?await this.renderInSandbox(e):this.renderWithInlineSprinkle(e)}async renderInSandbox(e){let t=document.createElement(`iframe`);t.src=chrome.runtime.getURL(`tool-ui-sandbox.html`),t.style.cssText=`width: 100%; border: none; min-height: 60px;`,this.iframe=t,await new Promise((e,n)=>{let r=setTimeout(()=>{si.error(`Tool UI iframe load timed out`),t.remove(),this.iframe=null,n(Error(`tool-ui sandbox iframe load timed out`))},5e3);t.addEventListener(`load`,()=>{clearTimeout(r),e()},{once:!0}),t.addEventListener(`error`,()=>{clearTimeout(r),t.remove(),this.iframe=null,n(Error(`tool-ui sandbox iframe failed to load`))},{once:!0}),this.container.appendChild(t)}),this.messageHandler=e=>{if(e.source!==t.contentWindow)return;let n=e.data;if(n?.type){if(n.nonce!==this.nonce){si.warn(`Tool UI message nonce mismatch`,{expected:this.nonce,received:n.nonce});return}n.type===`tool-ui-action`&&n.id===this.requestId?(si.info(`Tool UI action received`,{id:n.id,action:n.action}),_.handleAction(n.id,{action:n.action,data:n.data})):n.type===`tool-ui-rendered`&&n.id===this.requestId?n.height&&this.iframe&&(this.iframe.style.height=`${Math.max(60,n.height)}px`):n.type===`tool-ui-resize`&&n.id===this.requestId&&n.height&&this.iframe&&(this.iframe.style.height=`${Math.max(60,n.height)}px`)}},window.addEventListener(`message`,this.messageHandler);let{collectThemeCSS:n}=await v(async()=>{let{collectThemeCSS:e}=await import(`./sprinkle-renderer-DMzFY2-1.js`);return{collectThemeCSS:e}},[]),r=n();t.contentWindow.postMessage({type:`tool-ui-render`,id:this.requestId,nonce:this.nonce,html:e,themeCSS:r},`*`)}renderWithInlineSprinkle(e){let t=document.createElement(`div`);t.className=`msg__inline-sprinkle`,this.container.appendChild(t),this.inlineSprinkle=ri(t,e,(e,t)=>{si.info(`Tool UI action (inline sprinkle)`,{id:this.requestId,action:e}),_.handleAction(this.requestId,{action:e,data:t})})}dispose(){this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.iframe&&=(this.iframe.remove(),null),this.inlineSprinkle&&=(this.inlineSprinkle.dispose(),null)}},ui=new Map;function di(e,t,n){let r=ui.get(t);r&&r.dispose();let i=new li(e,t);return ui.set(t,i),i.render(n).catch(e=>{si.error(`Failed to render tool UI`,{requestId:t,error:e.message})}),i}function fi(e){let t=ui.get(e);t&&(t.dispose(),ui.delete(e))}var pi=n(`chat-panel`);function mi(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var hi={bash:`$`,browser:`B`,read_file:`R`,write_file:`W`,edit_file:`E`,javascript:`JS`,delegate_to_scoop:`D`,send_message:`M`,schedule_task:`T`,list_scoops:`LS`,list_tasks:`LT`,register_scoop:`RS`,update_global_memory:`GM`};function gi(e){return hi[e]??`?`}function _i(e){return e.role===`assistant`?Lr(e.content):Ir(e.content)}var vi=class{container;messagesEl;messagesInner;inputArea;textarea;sendBtn;stopBtn;micBtn;voiceInput=null;voiceMode=!1;keydownListener=null;messages=[];agent=null;unsubscribe=null;isStreaming=!1;currentStreamId=null;sessionStore;sessionId;readOnly=!1;terminalOutputCallback=null;currentScoopName=null;autoScrollAttached=!0;lastScrollTop=0;jumpPill;onDeleteQueuedMessage=null;pendingDeltaText=``;streamingRafId=null;inlineSprinkles=new Map;onInlineSprinkleLick;modelSelectorEl;handoffsEl;pendingHandoffs=[];onAcceptPendingHandoff=null;onDismissPendingHandoff=null;onModelChange;constructor(e){this.container=e,this.sessionStore=new Ur,this.sessionId=`default`,this.render()}setAgent(e){this.unsubscribe?.(),this.agent=e,this.unsubscribe=e.onEvent(e=>this.handleAgentEvent(e))}onTerminalOutput(e){this.terminalOutputCallback=e}setDeleteQueuedMessageCallback(e){this.onDeleteQueuedMessage=e}async initSession(e){await this.sessionStore.init(),this.sessionId=e??`default`;let t=await this.sessionStore.load(this.sessionId);t&&t.messages.length>0&&(this.messages=t.messages.map(e=>({...e,isStreaming:!1})),this.renderMessages())}async clearSession(){this.messages=[],this.renderMessages(),await this.sessionStore.delete(this.sessionId)}async deleteSessionById(e){await this.sessionStore.delete(e)}async switchToContext(e,t,n){await this.persistSessionAsync(),this.setStreamingState(!1),this.currentStreamId=null,this.cancelPendingDelta(),this.sessionId=e,this.currentScoopName=n??null,this.setReadOnly(t);let r=await this.sessionStore.load(this.sessionId);r&&r.messages.length>0?this.messages=r.messages.map(e=>({...e,isStreaming:!1})):this.messages=[],this.renderMessages()}setReadOnly(e){this.readOnly=e,this.inputArea&&(this.inputArea.style.display=e?`none`:``)}async persistSessionAsync(){try{await this.sessionStore.saveMessages(this.sessionId,this.messages)}catch{}}setProcessing(e){e?this.setStreamingState(!0):this.setStreamingState(!1)}addSystemMessage(e){let t={id:mi(),role:`assistant`,content:e,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t),this.persistSession()}addLickMessage(e,t,n){let r={id:e,role:`user`,content:t,timestamp:Date.now(),source:`lick`,channel:n};this.messages.push(r),this.appendMessageEl(r),this.persistSession()}getMessages(){return[...this.messages]}loadMessages(e){this.messages=e.map(e=>({...e,isStreaming:!1})),this.renderMessages(),this.persistSession(),this.renderModelSelector()}clear(){this.messages=[],this.renderMessages(),this.renderModelSelector()}setPendingHandoffs(e){this.pendingHandoffs=[...e],this.renderPendingHandoffs()}setPendingHandoffActions(e){this.onAcceptPendingHandoff=e.onAccept,this.onDismissPendingHandoff=e.onDismiss,this.renderPendingHandoffs()}addUserMessage(e){let t={id:mi(),role:`user`,content:e,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t)}deleteQueuedMessage(e){let t=this.messages.findIndex(t=>t.id===e);if(t===-1)return;this.messages.splice(t,1);let n=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);n&&n.remove(),this.persistSession(),this.onDeleteQueuedMessage?.(e)}render(){this.container.innerHTML=``,this.container.classList.add(`chat`),this.messagesEl=document.createElement(`div`),this.messagesEl.className=`chat__messages`,this.messagesInner=document.createElement(`div`),this.messagesInner.className=`chat__messages-inner`,this.messagesEl.appendChild(this.messagesInner),this.handoffsEl=document.createElement(`div`),this.handoffsEl.className=`chat__handoffs`,this.handoffsEl.hidden=!0,this.messagesEl.appendChild(this.handoffsEl),this.container.appendChild(this.messagesEl),this.renderPendingHandoffs(),this.messagesEl.addEventListener(`scroll`,()=>{let{scrollTop:e,scrollHeight:t,clientHeight:n}=this.messagesEl;t-e-n<=250?(this.autoScrollAttached=!0,this.hideJumpPill()):e<this.lastScrollTop&&(this.autoScrollAttached=!1),this.lastScrollTop=e},{passive:!0}),this.inputArea=document.createElement(`div`);let e=this.inputArea;e.className=`chat__input-area`;let t=document.createElement(`div`);t.className=`chat__input-area-inner`,this.textarea=document.createElement(`textarea`),this.textarea.className=`chat__textarea`,this.textarea.placeholder=`What shall we build?`,this.textarea.rows=1,this.sendBtn=document.createElement(`button`),this.sendBtn.className=`chat__send-btn`,this.sendBtn.innerHTML=`<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M10 1.25C5.167 1.25 1.25 5.167 1.25 10s3.917 8.75 8.75 8.75 8.75-3.918 8.75-8.75S14.833 1.25 10 1.25zm3.527 8.284a.75.75 0 0 1-1.06 0L10.75 7.82v6.172a.75.75 0 0 1-1.5 0V7.812L7.527 9.534a.75.75 0 1 1-1.06-1.06l2.998-2.998a.75.75 0 0 1 1.06-.001l3.002 2.998a.75.75 0 0 1 0 1.061z"/></svg>`,this.sendBtn.dataset.tooltip=`Send message`,this.sendBtn.dataset.tooltipPos=`top`,this.stopBtn=document.createElement(`button`),this.stopBtn.className=`chat__stop-btn`,this.stopBtn.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M13.75 4H6.25A2.25 2.25 0 0 0 4 6.25v7.5A2.25 2.25 0 0 0 6.25 16h7.5A2.25 2.25 0 0 0 16 13.75v-7.5A2.25 2.25 0 0 0 13.75 4z"/></svg>`,this.stopBtn.dataset.tooltip=`Stop generation`,this.stopBtn.style.display=`none`,this.micBtn=document.createElement(`button`),this.micBtn.className=`chat__mic-btn`;let n=`http://www.w3.org/2000/svg`,r=document.createElementNS(n,`svg`);r.setAttribute(`width`,`16`),r.setAttribute(`height`,`16`),r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`2`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`);let i=document.createElementNS(n,`path`);i.setAttribute(`d`,`M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z`);let a=document.createElementNS(n,`path`);a.setAttribute(`d`,`M19 10v2a7 7 0 0 1-14 0v-2`);let o=document.createElementNS(n,`line`);o.setAttribute(`x1`,`12`),o.setAttribute(`y1`,`19`),o.setAttribute(`x2`,`12`),o.setAttribute(`y2`,`23`);let s=document.createElementNS(n,`line`);s.setAttribute(`x1`,`8`),s.setAttribute(`y1`,`23`),s.setAttribute(`x2`,`16`),s.setAttribute(`y2`,`23`),r.append(i,a,o,s),this.micBtn.appendChild(r),this.micBtn.dataset.tooltip=`Voice (Ctrl+Shift+V)`;let c=document.createElement(`div`);c.className=`chat__input-wrapper`,c.appendChild(this.textarea);let l=document.createElement(`div`);l.className=`chat__action-bar`;let u=document.createElement(`div`);u.className=`chat__action-bar-left`,u.appendChild(this.micBtn),l.appendChild(u),this.modelSelectorEl=document.createElement(`div`),this.modelSelectorEl.className=`chat__model-selector`,this.renderModelSelector(),l.appendChild(this.modelSelectorEl);let d=document.createElement(`div`);d.className=`chat__action-bar-right`,d.appendChild(this.sendBtn),d.appendChild(this.stopBtn),l.appendChild(d),c.appendChild(l),t.appendChild(c),e.appendChild(t),this.container.appendChild(e),this.jumpPill=document.createElement(`button`),this.jumpPill.className=`chat__jump-pill`,this.jumpPill.textContent=`↓ New activity`,this.jumpPill.addEventListener(`click`,()=>{this.autoScrollAttached=!0,this.hideJumpPill(),this.scrollToBottom(!0)}),this.container.appendChild(this.jumpPill),this.textarea.addEventListener(`keydown`,e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.sendMessage())}),this.textarea.addEventListener(`input`,()=>{this.textarea.style.height=`auto`,this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+`px`}),this.sendBtn.addEventListener(`click`,()=>this.sendMessage()),this.stopBtn.addEventListener(`click`,()=>{this.agent?.stop();for(let e of this.messages)e.queued&&(e.queued=!1,this.updateMessageEl(e.id));this.setStreamingState(!1)}),this.voiceInput=new qr({onTranscript:(e,t)=>{this.textarea.value=e,this.textarea.style.height=`auto`,this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+`px`},onStateChange:e=>{e===`error`?(this.voiceMode=!1,this.micBtn.classList.remove(`chat__mic-btn--active`,`chat__mic-btn--listening`)):this.voiceMode?e===`listening`&&this.micBtn.classList.add(`chat__mic-btn--listening`):this.micBtn.classList.toggle(`chat__mic-btn--listening`,e===`listening`)},onError:e=>{pi.debug(`Voice input error`,{error:e}),!(this.voiceMode&&e.includes(`No speech detected`))&&this.addSystemMessage(e)},autoSend:!0,onAutoSend:e=>{this.textarea.value=e,this.sendMessage()},onAutoDisable:()=>{this.voiceMode=!1,this.micBtn.classList.remove(`chat__mic-btn--active`,`chat__mic-btn--listening`),this.addSystemMessage(`Voice mode disabled after 2 minutes of inactivity.`)},lang:Yr()}),this.micBtn.addEventListener(`click`,()=>{this.toggleVoiceMode()}),this.keydownListener=e=>{e.shiftKey&&(e.ctrlKey||e.metaKey)&&e.key===`V`&&(e.preventDefault(),this.toggleVoiceMode())},document.addEventListener(`keydown`,this.keydownListener)}renderPendingHandoffs(){if(!this.handoffsEl)return;if(this.pendingHandoffs.length===0){this.handoffsEl.hidden=!0,this.handoffsEl.innerHTML=``;return}let e=this.pendingHandoffs.length===1?`1 pending handoff`:`${this.pendingHandoffs.length} pending handoffs`;this.handoffsEl.hidden=!1,this.handoffsEl.innerHTML=`
|
|
239
239
|
<div class="chat__handoffs-inner">
|
|
240
240
|
<div class="chat__handoffs-header">${wr(e)}</div>
|
|
241
241
|
${this.pendingHandoffs.map(e=>this.renderPendingHandoffCard(e)).join(``)}
|
|
@@ -249,7 +249,7 @@ mark{background:color-mix(in srgb,var(--s2-accent) 25%,transparent);color:inheri
|
|
|
249
249
|
<button class="chat__handoff-btn" data-action="dismiss" data-handoff-id="${wr(e.handoffId)}" type="button">Dismiss</button>
|
|
250
250
|
</div>
|
|
251
251
|
</section>
|
|
252
|
-
`}toggleVoiceMode(){this.voiceMode=!this.voiceMode,this.micBtn.classList.toggle(`chat__mic-btn--active`,this.voiceMode),this.voiceMode?this.voiceInput?.start():this.voiceInput?.stop()}sendMessage(){let e=this.textarea.value.trim();if(!e)return;this.autoScrollAttached=!0,this.hideJumpPill();let t=this.isStreaming,n={id:mi(),role:`user`,content:e,timestamp:Date.now(),queued:t||void 0};this.messages.push(n),this.appendMessageEl(n),this.persistSession(),this.textarea.value=``,this.textarea.style.height=`auto`,this.isStreaming||this.setStreamingState(!0),this.agent?.sendMessage(e,n.id)}handleAgentEvent(e){switch(pi.debug(`Agent event`,{type:e.type}),e.type){case`message_start`:this.handleMessageStart(e.messageId);break;case`content_delta`:this.handleContentDelta(e.messageId,e.text);break;case`content_done`:this.handleContentDone(e.messageId);break;case`tool_use_start`:this.handleToolUseStart(e.messageId,e.toolName,e.toolInput);break;case`tool_result`:this.handleToolResult(e.messageId,e.toolName,e.result,e.isError);break;case`tool_ui`:this.handleToolUI(e.messageId,e.toolName,e.requestId,e.html);break;case`tool_ui_done`:this.handleToolUIDone(e.messageId,e.requestId);break;case`turn_end`:this.handleTurnEnd(e.messageId);break;case`error`:this.handleError(e.error);break;case`screenshot`:break;case`terminal_output`:this.terminalOutputCallback?.(e.text);break}}handleMessageStart(e){this.setStreamingState(!0),this.currentStreamId=e;let t={id:e,role:`assistant`,content:``,timestamp:Date.now(),isStreaming:!0,toolCalls:[]};this.messages.push(t),this.appendMessageEl(t)}handleContentDelta(e,t){this.findMessage(e)&&(this.pendingDeltaText+=t,this.streamingRafId===null&&(this.streamingRafId=requestAnimationFrame(()=>this.flushPendingDelta())))}handleContentDone(e){if(this.pendingDeltaText&&this.currentStreamId===e){let t=this.findMessage(e);t&&(t.content+=this.pendingDeltaText)}this.cancelPendingDelta();let t=this.findMessage(e);t&&(t.isStreaming=!1,this.updateMessageEl(e))}handleToolUseStart(e,t,n){let r=this.findMessage(e);r&&(r.toolCalls||=[],r.toolCalls.push({id:mi(),name:t,input:n}),this.updateMessageEl(e))}handleToolResult(e,t,n,r){let i=this.findMessage(e);if(!i||!i.toolCalls)return;let a=[...i.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);if(a){let e=n.match(/<img:(data:image\/[^>]+)>/);a.result=n.replace(/<img:data:image\/[^>]+>/g,``).trim(),e&&(a._screenshotDataUrl=e[1]),a.isError=r}this.updateMessageEl(e)}handleToolUI(e,t,n,r,i=0){let a=this.findMessage(e);if(!a||!a.toolCalls){if(i<10){setTimeout(()=>this.handleToolUI(e,t,n,r,i+1),100);return}pi.warn(`handleToolUI: message or toolCalls not found after retries`,{messageId:e});return}let o=[...a.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);if(!o){pi.warn(`handleToolUI: no matching tool call found`,{messageId:e,toolName:t});return}o._toolUIRequestId=n;let s=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);if(!s){if(i<10){setTimeout(()=>this.handleToolUI(e,t,n,r,i+1),100);return}pi.warn(`handleToolUI: wrapper element not found after retries`,{messageId:e});return}let c=[...s.querySelectorAll(`.tool-call`)].reverse().find(e=>e.querySelector(`.tool-call__name`)?.textContent===t);if(c){c instanceof HTMLDetailsElement&&(c.open=!0);let e=c.querySelector(`.tool-call__ui`);e||(e=document.createElement(`div`),e.className=`tool-call__ui`,c.appendChild(e)),di(e,n,r)}else i<10?setTimeout(()=>this.handleToolUI(e,t,n,r,i+1),100):pi.warn(`handleToolUI: tool call element not found in DOM after retries`,{toolName:t})}handleToolUIDone(e,t){fi(t)}handleTurnEnd(e){this.setStreamingState(!1),this.currentStreamId=null,this.persistSession()}handleError(e){this.setStreamingState(!1),this.currentStreamId=null;let t=this.messages[this.messages.length-1];if(t?.role===`assistant`&&t.isStreaming)t.isStreaming=!1,t.content+=`\n\n**Error:** ${e}`,this.updateMessageEl(t.id);else{let t={id:mi(),role:`assistant`,content:`**Error:** ${e}`,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t)}this.persistSession()}setStreamingState(e){this.isStreaming=e;try{this.renderModelSelector()}catch{}if(this.stopBtn.style.display=e?`flex`:`none`,this.sendBtn.style.display=e?`none`:`flex`,this.textarea.disabled=!1,e){this.voiceInput?.isListening()&&this.voiceInput.stop(),this.micBtn.classList.remove(`chat__mic-btn--listening`);let e=this.messages.find(e=>e.queued);e&&(e.queued=!1,this.updateMessageEl(e.id))}e||(this.voiceMode?(this.micBtn.classList.add(`chat__mic-btn--listening`),this.voiceInput?.start()):this.textarea.focus())}renderModelSelector(){let e=this.modelSelectorEl;if(!e)return;for(;e.firstChild;)e.removeChild(e.firstChild);let t=te(),n=D(),r=E(),i=[];for(let e of t)for(let t of e.models)i.push({providerId:e.providerId,id:t.id,name:t.name,reasoning:t.reasoning});i.sort((e,t)=>e.reasoning===t.reasoning?e.name.localeCompare(t.name):e.reasoning?-1:1);let a=i.find(e=>e.id===n&&e.providerId===r)||i[0];if(!a)return;let o=this.isStreaming,s=document.createElement(`button`);if(s.className=`chat__model-btn chat__model-btn--compact`,o&&s.classList.add(`chat__model-btn--disabled`),s.textContent=a.name,!o){let e=document.createElement(`span`);e.className=`chat__model-chevron`,e.innerHTML=`<svg width="12" height="12" viewBox="0 0 16 16" fill="currentColor"><path d="M4.5 6l3.5 4 3.5-4z"/></svg>`,s.appendChild(e)}if(o)e.appendChild(s);else{let t=!1,a=document.createElement(`div`);a.className=`chat__model-menu`;let o=()=>{for(a.style.display=t?`block`:`none`;a.firstChild;)a.removeChild(a.firstChild);if(t)for(let e of i){let i=document.createElement(`div`);i.className=`chat__model-menu-item`;let o=e.id===n&&e.providerId===r;o&&i.classList.add(`chat__model-menu-item--active`);let s=document.createElement(`span`);if(s.textContent=e.name,i.appendChild(s),o){let e=document.createElement(`span`);e.className=`chat__model-check`,e.innerHTML=`<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M6.5 12.5l-4-4 1.4-1.4 2.6 2.6 5.6-5.6 1.4 1.4z"/></svg>`,i.appendChild(e)}i.addEventListener(`click`,()=>{let n=`${e.providerId}:${e.id}`;re(n),this.onModelChange?.(n),t=!1,this.renderModelSelector()}),a.appendChild(i)}};s.addEventListener(`click`,e=>{e.stopPropagation(),t=!t,o()}),document.addEventListener(`click`,()=>{t=!1,o()},{once:!0}),e.appendChild(s),e.appendChild(a),o()}}refreshModelSelector(){this.renderModelSelector()}findMessage(e){return this.messages.find(t=>t.id===e)}flushPendingDelta(){if(this.streamingRafId=null,!this.pendingDeltaText||!this.currentStreamId)return;let e=this.findMessage(this.currentStreamId);if(!e){this.pendingDeltaText=``;return}e.content+=this.pendingDeltaText,this.pendingDeltaText=``,this.updateStreamingContent(this.currentStreamId)}cancelPendingDelta(){this.streamingRafId!==null&&(cancelAnimationFrame(this.streamingRafId),this.streamingRafId=null),this.pendingDeltaText=``}updateStreamingContent(e){let t=this.findMessage(e);if(!t)return;let n=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);if(!n)return;let r=n.querySelector(`.msg__content`);if(r){if(r.innerHTML=_i(t),t.isStreaming){let e=document.createElement(`span`);e.className=`streaming-cursor`,r.appendChild(e)}}else if(t.content.trim().length>0){this.updateMessageEl(e);return}this.scrollToBottom()}renderMessages(){this.disposeAllInlineSprinkles(),this.messagesInner.innerHTML=``;let e=null,t=0,n=-1;for(let e=this.messages.length-1;e>=0;e--)if(this.messages[e].role===`assistant`){n=e;break}for(let r=0;r<this.messages.length;r++){let i=this.messages[r],a=this.shouldShowLabel(i,e,t),o=this.createMessageEl(i,a,r===n);this.messagesInner.appendChild(o),e=i.role,t=i.timestamp}this.autoScrollAttached=!0,this.hideJumpPill(),this.scrollToBottom(!0)}appendMessageEl(e){let t=this.messagesInner.querySelector(`.msg__feedback`);t&&t.remove();let n=this.messages.length>=2?this.messages[this.messages.length-2]:null,r=this.shouldShowLabel(e,n?.role??null,n?.timestamp??0),i=e.role===`assistant`,a=this.createMessageEl(e,r,i);this.messagesInner.appendChild(a),this.scrollToBottom()}shouldShowLabel(e,t,n){return e.source===`lick`||e.channel===`webhook`||e.channel===`cron`||e.role!==t||e.timestamp-n>12e4}updateMessageEl(e){let t=this.findMessage(e);if(!t)return;let n=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);if(n){this.disposeInlineSprinklesForMessage(e);let r=this.messages.indexOf(t),i=r>0?this.messages[r-1]:null,a=this.shouldShowLabel(t,i?.role??null,i?.timestamp??0),o=!1;if(t.role===`assistant`){let e=-1;for(let t=this.messages.length-1;t>=0;t--)if(this.messages[t].role===`assistant`){e=t;break}o=r===e}let s=this.createMessageEl(t,a,o);n.replaceWith(s)}this.scrollToBottom()}createMessageEl(e,t=!0,n=!1){if(e.source===`lick`||e.channel===`webhook`||e.channel===`cron`){let t=document.createElement(`div`);return t.className=`msg-group`,t.setAttribute(`data-msg-id`,e.id),t.appendChild(this.createLickEl(e)),t}let r=document.createElement(`div`);r.className=`msg-group${t?``:` msg-group--continuation`}`,r.setAttribute(`data-msg-id`,e.id);let i=document.createElement(`div`);if(i.className=`msg msg--${e.role}${e.queued?` msg--queued`:``}`,t){let t,n,r=this.currentScoopName!==null;e.role===`user`?e.source===`delegation`||e.channel===`delegation`?(t=`S`,n=`sliccy`):(t=`U`,n=`You`):r?(t=(this.currentScoopName||`S`).charAt(0).toUpperCase(),n=`@${this.currentScoopName}`):e.source&&e.source!==`cone`?(t=e.source.charAt(0).toUpperCase(),n=e.source):(t=`S`,n=`sliccy`);let a=document.createElement(`div`);a.className=`msg__role`;let o=document.createElement(`span`);if(o.className=`msg__icon`,o.textContent=t,a.appendChild(o),a.appendChild(document.createTextNode(` ${n}`)),e.queued){let t=document.createElement(`span`);t.className=`msg__queued-badge`,t.textContent=`queued`,a.appendChild(t);let n=document.createElement(`button`);n.className=`msg__queued-delete`,n.textContent=`×`,n.title=`Remove queued message`,n.addEventListener(`click`,t=>{t.stopPropagation(),this.deleteQueuedMessage(e.id)}),a.appendChild(n)}i.appendChild(a)}let a=(e.source===`lick`||e.channel===`webhook`||e.channel===`cron`)&&this.sessionId===`session-cone`,o=e.source&&e.source!==`cone`&&e.source!==`lick`&&e.role===`assistant`&&this.sessionId===`session-cone`;if(a||o){let t=document.createElement(`details`);t.className=`msg__collapsible`;let n=document.createElement(`summary`);n.className=`msg__summary`,n.textContent=e.content.slice(0,60).replace(/\n/g,` `)+(e.content.length>60?`...`:``),t.appendChild(n);let r=document.createElement(`div`);r.className=`msg__content`,r.innerHTML=_i(e),e.isStreaming||this.hydrateInlineSprinklesInEl(r,e.id),t.appendChild(r),i.appendChild(t)}else{let t=document.createElement(`div`);if(t.className=`msg__content`,t.innerHTML=_i(e),e.isStreaming){let e=document.createElement(`span`);e.className=`streaming-cursor`,t.appendChild(e)}else this.hydrateInlineSprinklesInEl(t,e.id);i.appendChild(t)}let s=e.content.trim().length>0;if(s&&r.appendChild(i),e.toolCalls)for(let t of e.toolCalls)r.appendChild(this.createToolCallEl(t));return e.role===`assistant`&&!e.isStreaming&&!e.queued&&s&&n&&r.appendChild(this.createFeedbackRow()),r}createFeedbackRow(){let e=document.createElement(`div`);e.className=`msg__feedback`;let t=document.createElement(`button`);return t.className=`msg__feedback-btn`,t.dataset.tooltip=`Copy chat`,t.setAttribute(`aria-label`,`Copy chat`),t.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="m11.75,18h-7.5c-1.24,0-2.25-1.01-2.25-2.25v-7.5c0-1.24,1.01-2.25,2.25-2.25.41,0,.75.34.75.75s-.34.75-.75.75c-.41,0-.75.34-.75.75v7.5c0,.41.34.75.75.75h7.5c.41,0,.75-.34.75-.75,0-.41.34-.75.75-.75s.75.34.75.75c0,1.24-1.01,2.25-2.25,2.25Z"/><path d="m6.75,5c-.41,0-.75-.34-.75-.75,0-1.24,1.01-2.25,2.25-2.25.41,0,.75.34.75.75s-.34.75-.75.75c-.41,0-.75.34-.75.75,0,.41-.34.75-.75.75Z"/><path d="m13,3.5h-2c-.41,0-.75-.34-.75-.75s.34-.75.75-.75h2c.41,0,.75.34.75.75s-.34.75-.75.75Z"/><path d="m13,14h-2c-.41,0-.75-.34-.75-.75s.34-.75.75-.75h2c.41,0,.75.34.75.75s-.34.75-.75.75Z"/><path d="m15.75,14c-.41,0-.75-.34-.75-.75s.34-.75.75-.75c.41,0,.75-.34.75-.75,0-.41.34-.75.75-.75s.75.34.75.75c0,1.24-1.01,2.25-2.25,2.25Z"/><path d="m17.25,5c-.41,0-.75-.34-.75-.75,0-.41-.34-.75-.75-.75-.41,0-.75-.34-.75-.75s.34-.75.75-.75c1.24,0,2.25,1.01,2.25,2.25,0,.41-.34.75-.75.75Z"/><path d="m17.25,9.75c-.41,0-.75-.34-.75-.75v-2c0-.41.34-.75.75-.75s.75.34.75.75v2c0,.41-.34.75-.75.75Z"/><path d="m6.75,9.75c-.41,0-.75-.34-.75-.75v-2c0-.41.34-.75.75-.75s.75.34.75.75v2c0,.41-.34.75-.75.75Z"/><path d="m8.25,14c-1.24,0-2.25-1.01-2.25-2.25,0-.41.34-.75.75-.75s.75.34.75.75c0,.41.34.75.75.75.41,0,.75.34.75.75s-.34.75-.75.75Z"/></svg>`,t.addEventListener(`click`,async()=>{let e=this.getMessages(),n=``;for(let t of e){let e=t.role===`user`?`User`:`Assistant`;if(n+=`## ${e}\n${t.content}\n\n`,t.toolCalls)for(let e of t.toolCalls)n+=`### Tool: ${e.name}\nInput: ${JSON.stringify(e.input,null,2)}\nResult: ${e.result??``}\n\n`}await navigator.clipboard.writeText(n),t.style.color=`var(--s2-positive)`,setTimeout(()=>{t.style.color=``},1500)}),e.appendChild(t),e}createLickEl(e){let t=document.createElement(`details`);t.className=`lick`;let n=e.channel===`webhook`?`Webhook`:e.channel===`cron`?`Cron`:`Event`,r=document.createElement(`summary`);r.className=`lick__header`,r.innerHTML=`<span class="lick__icon">E</span> <span class="lick__type">${n}</span>`;let i=document.createElement(`span`);i.className=`lick__preview`;let a=e.content.replace(/\[Webhook Event:.*?\]\n```json\n?/s,``).slice(0,50);i.textContent=a.replace(/\n/g,` `)+(a.length>=50?`...`:``),r.appendChild(i),t.appendChild(r);let o=document.createElement(`div`);return o.className=`lick__details`,o.innerHTML=Ir(e.content),t.appendChild(o),t}createToolCallEl(e){gi(e.name);let t=document.createElement(`details`);t.className=`tool-call`;let n=document.createElement(`summary`);if(n.className=`tool-call__header`,n.innerHTML=`<span class="tool-call__icon"><svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor"><path d="M2 3.5L5 6.5L8 3.5" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg></span> <span class="tool-call__name">${wr(e.name)}</span>`,e.input!==void 0){let t=document.createElement(`span`);t.className=`tool-call__preview`;let r=typeof e.input==`string`?e.input:JSON.stringify(e.input);t.textContent=r.slice(0,40)+(r.length>40?`...`:``),n.appendChild(t)}let r=document.createElement(`span`);e.result===void 0?r.className=`tool-call__status tool-call__status--running`:e.isError?(r.className=`tool-call__status tool-call__status--error`,r.textContent=`failed`):(r.className=`tool-call__status tool-call__status--success`,r.textContent=`✓`),n.appendChild(r),t.appendChild(n);let i=document.createElement(`div`);if(i.className=`tool-call__details`,e.input!==void 0){let t=document.createElement(`div`);t.className=`tool-call__input`;let n=document.createElement(`div`);n.className=`tool-call__label`,n.textContent=`Input:`,t.appendChild(n);let r=document.createElement(`pre`);r.innerHTML=Rr(e.input),t.appendChild(r),i.appendChild(t)}if(e.result!==void 0){let t=document.createElement(`div`);t.className=`tool-call__result${e.isError?` tool-call__result--error`:``}`;let n=document.createElement(`div`);n.className=`tool-call__label`,n.textContent=e.isError?`Error:`:`Result:`,t.appendChild(n);let r=document.createElement(`pre`);r.textContent=e.result,t.appendChild(r),i.appendChild(t)}let a=e._screenshotDataUrl;if(a){let e=document.createElement(`img`);e.src=a,e.className=`tool-call__screenshot`,e.title=`Click to view full size`,e.addEventListener(`click`,e=>{e.stopPropagation();let t=window.open(`about:blank`);if(t){let e=t.document.createElement(`img`);e.src=a,t.document.title=`Screenshot`,t.document.body.style.margin=`0`,t.document.body.style.background=document.documentElement.classList.contains(`theme-light`)?`#f0f0f0`:`#141414`,t.document.body.appendChild(e)}}),i.appendChild(e)}return t.appendChild(i),t}scrollToBottom(e=!1){if(!e&&!this.autoScrollAttached){this.showJumpPill();return}requestAnimationFrame(()=>{this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this.lastScrollTop=this.messagesEl.scrollTop})}showJumpPill(){this.jumpPill.classList.add(`chat__jump-pill--visible`)}hideJumpPill(){this.jumpPill.classList.remove(`chat__jump-pill--visible`)}persistSession(){this.sessionStore.saveMessages(this.sessionId,this.messages).catch(()=>{})}disposeInlineSprinklesForMessage(e){let t=this.inlineSprinkles.get(e);t&&(ai(t),this.inlineSprinkles.delete(e))}disposeAllInlineSprinkles(){for(let[,e]of this.inlineSprinkles)ai(e);this.inlineSprinkles.clear()}hydrateInlineSprinklesInEl(e,t){let n=ii(e,(e,t)=>this.onInlineSprinkleLick?.(e,t));n.length&&this.inlineSprinkles.set(t,n)}dispose(){this.cancelPendingDelta(),this.disposeAllInlineSprinkles(),this.unsubscribe?.(),this.voiceInput?.destroy(),this.keydownListener&&=(document.removeEventListener(`keydown`,this.keydownListener),null),this.container.innerHTML=``}},yi=class{container;terminalViewEl;previewViewEl;previewEmptyEl;previewBtn;shell=null;activeView=`terminal`;onClearTerminal;constructor(e,t={}){this.container=e,this.onClearTerminal=t.onClearTerminal??null,this.render()}async mountShell(e){this.shell?.setPreviewStateListener(null),this.shell=e;let t=document.createElement(`div`);t.className=`terminal-panel__mount`,this.terminalViewEl.appendChild(t),await e.mount(t);let n=t.querySelector(`.terminal-panel__terminal-host`),r=t.querySelector(`.terminal-panel__preview`);if(!n||!r)throw Error(`terminal mount did not create expected hosts`);this.terminalViewEl.replaceChildren(n),this.previewViewEl.replaceChildren(this.previewEmptyEl),this.previewViewEl.appendChild(r),e.setPreviewStateListener(e=>this.handlePreviewStateChange(e))}clearTerminal(){this.shell?.clearTerminal()}async runCommand(e){return this.shell?(/^\s*imgcat(?:\s|$)/.test(e)||this.setActiveView(`terminal`),this.shell.executeCommandInTerminal(e)):{stdout:``,stderr:`terminal is unavailable
|
|
252
|
+
`}toggleVoiceMode(){this.voiceMode=!this.voiceMode,this.micBtn.classList.toggle(`chat__mic-btn--active`,this.voiceMode),this.voiceMode?this.voiceInput?.start():this.voiceInput?.stop()}sendMessage(){let e=this.textarea.value.trim();if(!e)return;this.autoScrollAttached=!0,this.hideJumpPill();let t=this.isStreaming,n={id:mi(),role:`user`,content:e,timestamp:Date.now(),queued:t||void 0};this.messages.push(n),this.appendMessageEl(n),this.persistSession(),this.textarea.value=``,this.textarea.style.height=`auto`,this.isStreaming||this.setStreamingState(!0),this.agent?.sendMessage(e,n.id)}handleAgentEvent(e){switch(pi.debug(`Agent event`,{type:e.type}),e.type){case`message_start`:this.handleMessageStart(e.messageId);break;case`content_delta`:this.handleContentDelta(e.messageId,e.text);break;case`content_done`:this.handleContentDone(e.messageId);break;case`tool_use_start`:this.handleToolUseStart(e.messageId,e.toolName,e.toolInput);break;case`tool_result`:this.handleToolResult(e.messageId,e.toolName,e.result,e.isError);break;case`tool_ui`:this.handleToolUI(e.messageId,e.toolName,e.requestId,e.html);break;case`tool_ui_done`:this.handleToolUIDone(e.messageId,e.requestId);break;case`turn_end`:this.handleTurnEnd(e.messageId);break;case`error`:this.handleError(e.error);break;case`screenshot`:break;case`terminal_output`:this.terminalOutputCallback?.(e.text);break}}handleMessageStart(e){this.setStreamingState(!0),this.currentStreamId=e;let t={id:e,role:`assistant`,content:``,timestamp:Date.now(),isStreaming:!0,toolCalls:[]};this.messages.push(t),this.appendMessageEl(t)}handleContentDelta(e,t){this.findMessage(e)&&(this.pendingDeltaText+=t,this.streamingRafId===null&&(this.streamingRafId=requestAnimationFrame(()=>this.flushPendingDelta())))}handleContentDone(e){if(this.pendingDeltaText&&this.currentStreamId===e){let t=this.findMessage(e);t&&(t.content+=this.pendingDeltaText)}this.cancelPendingDelta();let t=this.findMessage(e);t&&(t.isStreaming=!1,this.updateMessageEl(e))}handleToolUseStart(e,t,n){let r=this.findMessage(e);r&&(r.toolCalls||=[],r.toolCalls.push({id:mi(),name:t,input:n}),this.updateMessageEl(e))}handleToolResult(e,t,n,r){let i=this.findMessage(e);if(!i||!i.toolCalls)return;let a=[...i.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);if(a){let e=n.match(/<img:(data:image\/[^>]+)>/);a.result=n.replace(/<img:data:image\/[^>]+>/g,``).trim(),e&&(a._screenshotDataUrl=e[1]),a.isError=r}this.updateMessageEl(e)}handleToolUI(e,t,n,r,i=0){let a=this.findMessage(e);if(!a||!a.toolCalls){if(i<10){setTimeout(()=>this.handleToolUI(e,t,n,r,i+1),100);return}pi.warn(`handleToolUI: message or toolCalls not found after retries`,{messageId:e});return}let o=[...a.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);if(!o){pi.warn(`handleToolUI: no matching tool call found`,{messageId:e,toolName:t});return}o._toolUIRequestId=n;let s=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);if(!s){if(i<10){setTimeout(()=>this.handleToolUI(e,t,n,r,i+1),100);return}pi.warn(`handleToolUI: wrapper element not found after retries`,{messageId:e});return}let c=[...s.querySelectorAll(`.tool-call`)].reverse().find(e=>e.querySelector(`.tool-call__name`)?.textContent===t);if(c){c instanceof HTMLDetailsElement&&(c.open=!0);let e=c.querySelector(`.tool-call__ui`);e||(e=document.createElement(`div`),e.className=`tool-call__ui`,c.appendChild(e)),di(e,n,r)}else i<10?setTimeout(()=>this.handleToolUI(e,t,n,r,i+1),100):pi.warn(`handleToolUI: tool call element not found in DOM after retries`,{toolName:t})}handleToolUIDone(e,t){fi(t)}handleTurnEnd(e){this.setStreamingState(!1),this.currentStreamId=null,this.persistSession()}handleError(e){this.setStreamingState(!1),this.currentStreamId=null;let t=this.messages[this.messages.length-1];if(t?.role===`assistant`&&t.isStreaming)t.isStreaming=!1,t.content+=`\n\n**Error:** ${e}`,this.updateMessageEl(t.id);else{let t={id:mi(),role:`assistant`,content:`**Error:** ${e}`,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t)}this.persistSession()}setStreamingState(e){this.isStreaming=e;try{this.renderModelSelector()}catch{}if(this.stopBtn.style.display=e?`flex`:`none`,this.sendBtn.style.display=e?`none`:`flex`,this.textarea.disabled=!1,e){this.voiceInput?.isListening()&&this.voiceInput.stop(),this.micBtn.classList.remove(`chat__mic-btn--listening`);let e=this.messages.find(e=>e.queued);e&&(e.queued=!1,this.updateMessageEl(e.id))}e||(this.voiceMode?(this.micBtn.classList.add(`chat__mic-btn--listening`),this.voiceInput?.start()):this.textarea.focus())}renderModelSelector(){let e=this.modelSelectorEl;if(!e)return;for(;e.firstChild;)e.removeChild(e.firstChild);let t=ne(),n=D(),r=w(),i=[];for(let e of t)for(let t of e.models)i.push({providerId:e.providerId,id:t.id,name:t.name,reasoning:t.reasoning});i.sort((e,t)=>e.reasoning===t.reasoning?e.name.localeCompare(t.name):e.reasoning?-1:1);let a=i.find(e=>e.id===n&&e.providerId===r)||i[0];if(!a)return;let o=this.isStreaming,s=document.createElement(`button`);if(s.className=`chat__model-btn chat__model-btn--compact`,o&&s.classList.add(`chat__model-btn--disabled`),s.textContent=a.name,!o){let e=document.createElement(`span`);e.className=`chat__model-chevron`,e.innerHTML=`<svg width="12" height="12" viewBox="0 0 16 16" fill="currentColor"><path d="M4.5 6l3.5 4 3.5-4z"/></svg>`,s.appendChild(e)}if(o)e.appendChild(s);else{let t=!1,a=document.createElement(`div`);a.className=`chat__model-menu`;let o=()=>{for(a.style.display=t?`block`:`none`;a.firstChild;)a.removeChild(a.firstChild);if(t)for(let e of i){let i=document.createElement(`div`);i.className=`chat__model-menu-item`;let o=e.id===n&&e.providerId===r;o&&i.classList.add(`chat__model-menu-item--active`);let s=document.createElement(`span`);if(s.textContent=e.name,i.appendChild(s),o){let e=document.createElement(`span`);e.className=`chat__model-check`,e.innerHTML=`<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M6.5 12.5l-4-4 1.4-1.4 2.6 2.6 5.6-5.6 1.4 1.4z"/></svg>`,i.appendChild(e)}i.addEventListener(`click`,()=>{let n=`${e.providerId}:${e.id}`;C(n),this.onModelChange?.(n),t=!1,this.renderModelSelector()}),a.appendChild(i)}};s.addEventListener(`click`,e=>{e.stopPropagation(),t=!t,o()}),document.addEventListener(`click`,()=>{t=!1,o()},{once:!0}),e.appendChild(s),e.appendChild(a),o()}}refreshModelSelector(){this.renderModelSelector()}findMessage(e){return this.messages.find(t=>t.id===e)}flushPendingDelta(){if(this.streamingRafId=null,!this.pendingDeltaText||!this.currentStreamId)return;let e=this.findMessage(this.currentStreamId);if(!e){this.pendingDeltaText=``;return}e.content+=this.pendingDeltaText,this.pendingDeltaText=``,this.updateStreamingContent(this.currentStreamId)}cancelPendingDelta(){this.streamingRafId!==null&&(cancelAnimationFrame(this.streamingRafId),this.streamingRafId=null),this.pendingDeltaText=``}updateStreamingContent(e){let t=this.findMessage(e);if(!t)return;let n=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);if(!n)return;let r=n.querySelector(`.msg__content`);if(r){if(r.innerHTML=_i(t),t.isStreaming){let e=document.createElement(`span`);e.className=`streaming-cursor`,r.appendChild(e)}}else if(t.content.trim().length>0){this.updateMessageEl(e);return}this.scrollToBottom()}renderMessages(){this.disposeAllInlineSprinkles(),this.messagesInner.innerHTML=``;let e=null,t=0,n=-1;for(let e=this.messages.length-1;e>=0;e--)if(this.messages[e].role===`assistant`){n=e;break}for(let r=0;r<this.messages.length;r++){let i=this.messages[r],a=this.shouldShowLabel(i,e,t),o=this.createMessageEl(i,a,r===n);this.messagesInner.appendChild(o),e=i.role,t=i.timestamp}this.autoScrollAttached=!0,this.hideJumpPill(),this.scrollToBottom(!0)}appendMessageEl(e){let t=this.messagesInner.querySelector(`.msg__feedback`);t&&t.remove();let n=this.messages.length>=2?this.messages[this.messages.length-2]:null,r=this.shouldShowLabel(e,n?.role??null,n?.timestamp??0),i=e.role===`assistant`,a=this.createMessageEl(e,r,i);this.messagesInner.appendChild(a),this.scrollToBottom()}shouldShowLabel(e,t,n){return e.source===`lick`||e.channel===`webhook`||e.channel===`cron`||e.role!==t||e.timestamp-n>12e4}updateMessageEl(e){let t=this.findMessage(e);if(!t)return;let n=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);if(n){this.disposeInlineSprinklesForMessage(e);let r=this.messages.indexOf(t),i=r>0?this.messages[r-1]:null,a=this.shouldShowLabel(t,i?.role??null,i?.timestamp??0),o=!1;if(t.role===`assistant`){let e=-1;for(let t=this.messages.length-1;t>=0;t--)if(this.messages[t].role===`assistant`){e=t;break}o=r===e}let s=this.createMessageEl(t,a,o);n.replaceWith(s)}this.scrollToBottom()}createMessageEl(e,t=!0,n=!1){if(e.source===`lick`||e.channel===`webhook`||e.channel===`cron`){let t=document.createElement(`div`);return t.className=`msg-group`,t.setAttribute(`data-msg-id`,e.id),t.appendChild(this.createLickEl(e)),t}let r=document.createElement(`div`);r.className=`msg-group${t?``:` msg-group--continuation`}`,r.setAttribute(`data-msg-id`,e.id);let i=document.createElement(`div`);if(i.className=`msg msg--${e.role}${e.queued?` msg--queued`:``}`,t){let t,n,r=this.currentScoopName!==null;e.role===`user`?e.source===`delegation`||e.channel===`delegation`?(t=`S`,n=`sliccy`):(t=`U`,n=`You`):r?(t=(this.currentScoopName||`S`).charAt(0).toUpperCase(),n=`@${this.currentScoopName}`):e.source&&e.source!==`cone`?(t=e.source.charAt(0).toUpperCase(),n=e.source):(t=`S`,n=`sliccy`);let a=document.createElement(`div`);a.className=`msg__role`;let o=document.createElement(`span`);if(o.className=`msg__icon`,o.textContent=t,a.appendChild(o),a.appendChild(document.createTextNode(` ${n}`)),e.queued){let t=document.createElement(`span`);t.className=`msg__queued-badge`,t.textContent=`queued`,a.appendChild(t);let n=document.createElement(`button`);n.className=`msg__queued-delete`,n.textContent=`×`,n.title=`Remove queued message`,n.addEventListener(`click`,t=>{t.stopPropagation(),this.deleteQueuedMessage(e.id)}),a.appendChild(n)}i.appendChild(a)}let a=(e.source===`lick`||e.channel===`webhook`||e.channel===`cron`)&&this.sessionId===`session-cone`,o=e.source&&e.source!==`cone`&&e.source!==`lick`&&e.role===`assistant`&&this.sessionId===`session-cone`;if(a||o){let t=document.createElement(`details`);t.className=`msg__collapsible`;let n=document.createElement(`summary`);n.className=`msg__summary`,n.textContent=e.content.slice(0,60).replace(/\n/g,` `)+(e.content.length>60?`...`:``),t.appendChild(n);let r=document.createElement(`div`);r.className=`msg__content`,r.innerHTML=_i(e),e.isStreaming||this.hydrateInlineSprinklesInEl(r,e.id),t.appendChild(r),i.appendChild(t)}else{let t=document.createElement(`div`);if(t.className=`msg__content`,t.innerHTML=_i(e),e.isStreaming){let e=document.createElement(`span`);e.className=`streaming-cursor`,t.appendChild(e)}else this.hydrateInlineSprinklesInEl(t,e.id);i.appendChild(t)}let s=e.content.trim().length>0;if(s&&r.appendChild(i),e.toolCalls)for(let t of e.toolCalls)r.appendChild(this.createToolCallEl(t));return e.role===`assistant`&&!e.isStreaming&&!e.queued&&s&&n&&r.appendChild(this.createFeedbackRow()),r}createFeedbackRow(){let e=document.createElement(`div`);e.className=`msg__feedback`;let t=document.createElement(`button`);return t.className=`msg__feedback-btn`,t.dataset.tooltip=`Copy chat`,t.setAttribute(`aria-label`,`Copy chat`),t.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="m11.75,18h-7.5c-1.24,0-2.25-1.01-2.25-2.25v-7.5c0-1.24,1.01-2.25,2.25-2.25.41,0,.75.34.75.75s-.34.75-.75.75c-.41,0-.75.34-.75.75v7.5c0,.41.34.75.75.75h7.5c.41,0,.75-.34.75-.75,0-.41.34-.75.75-.75s.75.34.75.75c0,1.24-1.01,2.25-2.25,2.25Z"/><path d="m6.75,5c-.41,0-.75-.34-.75-.75,0-1.24,1.01-2.25,2.25-2.25.41,0,.75.34.75.75s-.34.75-.75.75c-.41,0-.75.34-.75.75,0,.41-.34.75-.75.75Z"/><path d="m13,3.5h-2c-.41,0-.75-.34-.75-.75s.34-.75.75-.75h2c.41,0,.75.34.75.75s-.34.75-.75.75Z"/><path d="m13,14h-2c-.41,0-.75-.34-.75-.75s.34-.75.75-.75h2c.41,0,.75.34.75.75s-.34.75-.75.75Z"/><path d="m15.75,14c-.41,0-.75-.34-.75-.75s.34-.75.75-.75c.41,0,.75-.34.75-.75,0-.41.34-.75.75-.75s.75.34.75.75c0,1.24-1.01,2.25-2.25,2.25Z"/><path d="m17.25,5c-.41,0-.75-.34-.75-.75,0-.41-.34-.75-.75-.75-.41,0-.75-.34-.75-.75s.34-.75.75-.75c1.24,0,2.25,1.01,2.25,2.25,0,.41-.34.75-.75.75Z"/><path d="m17.25,9.75c-.41,0-.75-.34-.75-.75v-2c0-.41.34-.75.75-.75s.75.34.75.75v2c0,.41-.34.75-.75.75Z"/><path d="m6.75,9.75c-.41,0-.75-.34-.75-.75v-2c0-.41.34-.75.75-.75s.75.34.75.75v2c0,.41-.34.75-.75.75Z"/><path d="m8.25,14c-1.24,0-2.25-1.01-2.25-2.25,0-.41.34-.75.75-.75s.75.34.75.75c0,.41.34.75.75.75.41,0,.75.34.75.75s-.34.75-.75.75Z"/></svg>`,t.addEventListener(`click`,async()=>{let e=this.getMessages(),n=``;for(let t of e){let e=t.role===`user`?`User`:`Assistant`;if(n+=`## ${e}\n${t.content}\n\n`,t.toolCalls)for(let e of t.toolCalls)n+=`### Tool: ${e.name}\nInput: ${JSON.stringify(e.input,null,2)}\nResult: ${e.result??``}\n\n`}await navigator.clipboard.writeText(n),t.style.color=`var(--s2-positive)`,setTimeout(()=>{t.style.color=``},1500)}),e.appendChild(t),e}createLickEl(e){let t=document.createElement(`details`);t.className=`lick`;let n=e.channel===`webhook`?`Webhook`:e.channel===`cron`?`Cron`:`Event`,r=document.createElement(`summary`);r.className=`lick__header`,r.innerHTML=`<span class="lick__icon">E</span> <span class="lick__type">${n}</span>`;let i=document.createElement(`span`);i.className=`lick__preview`;let a=e.content.replace(/\[Webhook Event:.*?\]\n```json\n?/s,``).slice(0,50);i.textContent=a.replace(/\n/g,` `)+(a.length>=50?`...`:``),r.appendChild(i),t.appendChild(r);let o=document.createElement(`div`);return o.className=`lick__details`,o.innerHTML=Ir(e.content),t.appendChild(o),t}createToolCallEl(e){gi(e.name);let t=document.createElement(`details`);t.className=`tool-call`;let n=document.createElement(`summary`);if(n.className=`tool-call__header`,n.innerHTML=`<span class="tool-call__icon"><svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor"><path d="M2 3.5L5 6.5L8 3.5" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg></span> <span class="tool-call__name">${wr(e.name)}</span>`,e.input!==void 0){let t=document.createElement(`span`);t.className=`tool-call__preview`;let r=typeof e.input==`string`?e.input:JSON.stringify(e.input);t.textContent=r.slice(0,40)+(r.length>40?`...`:``),n.appendChild(t)}let r=document.createElement(`span`);e.result===void 0?r.className=`tool-call__status tool-call__status--running`:e.isError?(r.className=`tool-call__status tool-call__status--error`,r.textContent=`failed`):(r.className=`tool-call__status tool-call__status--success`,r.textContent=`✓`),n.appendChild(r),t.appendChild(n);let i=document.createElement(`div`);if(i.className=`tool-call__details`,e.input!==void 0){let t=document.createElement(`div`);t.className=`tool-call__input`;let n=document.createElement(`div`);n.className=`tool-call__label`,n.textContent=`Input:`,t.appendChild(n);let r=document.createElement(`pre`);r.innerHTML=Rr(e.input),t.appendChild(r),i.appendChild(t)}if(e.result!==void 0){let t=document.createElement(`div`);t.className=`tool-call__result${e.isError?` tool-call__result--error`:``}`;let n=document.createElement(`div`);n.className=`tool-call__label`,n.textContent=e.isError?`Error:`:`Result:`,t.appendChild(n);let r=document.createElement(`pre`);r.textContent=e.result,t.appendChild(r),i.appendChild(t)}let a=e._screenshotDataUrl;if(a){let e=document.createElement(`img`);e.src=a,e.className=`tool-call__screenshot`,e.title=`Click to view full size`,e.addEventListener(`click`,e=>{e.stopPropagation();let t=window.open(`about:blank`);if(t){let e=t.document.createElement(`img`);e.src=a,t.document.title=`Screenshot`,t.document.body.style.margin=`0`,t.document.body.style.background=document.documentElement.classList.contains(`theme-light`)?`#f0f0f0`:`#141414`,t.document.body.appendChild(e)}}),i.appendChild(e)}return t.appendChild(i),t}scrollToBottom(e=!1){if(!e&&!this.autoScrollAttached){this.showJumpPill();return}requestAnimationFrame(()=>{this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this.lastScrollTop=this.messagesEl.scrollTop})}showJumpPill(){this.jumpPill.classList.add(`chat__jump-pill--visible`)}hideJumpPill(){this.jumpPill.classList.remove(`chat__jump-pill--visible`)}persistSession(){this.sessionStore.saveMessages(this.sessionId,this.messages).catch(()=>{})}disposeInlineSprinklesForMessage(e){let t=this.inlineSprinkles.get(e);t&&(ai(t),this.inlineSprinkles.delete(e))}disposeAllInlineSprinkles(){for(let[,e]of this.inlineSprinkles)ai(e);this.inlineSprinkles.clear()}hydrateInlineSprinklesInEl(e,t){let n=ii(e,(e,t)=>this.onInlineSprinkleLick?.(e,t));n.length&&this.inlineSprinkles.set(t,n)}dispose(){this.cancelPendingDelta(),this.disposeAllInlineSprinkles(),this.unsubscribe?.(),this.voiceInput?.destroy(),this.keydownListener&&=(document.removeEventListener(`keydown`,this.keydownListener),null),this.container.innerHTML=``}},yi=class{container;terminalViewEl;previewViewEl;previewEmptyEl;previewBtn;shell=null;activeView=`terminal`;onClearTerminal;constructor(e,t={}){this.container=e,this.onClearTerminal=t.onClearTerminal??null,this.render()}async mountShell(e){this.shell?.setPreviewStateListener(null),this.shell=e;let t=document.createElement(`div`);t.className=`terminal-panel__mount`,this.terminalViewEl.appendChild(t),await e.mount(t);let n=t.querySelector(`.terminal-panel__terminal-host`),r=t.querySelector(`.terminal-panel__preview`);if(!n||!r)throw Error(`terminal mount did not create expected hosts`);this.terminalViewEl.replaceChildren(n),this.previewViewEl.replaceChildren(this.previewEmptyEl),this.previewViewEl.appendChild(r),e.setPreviewStateListener(e=>this.handlePreviewStateChange(e))}clearTerminal(){this.shell?.clearTerminal()}async runCommand(e){return this.shell?(/^\s*imgcat(?:\s|$)/.test(e)||this.setActiveView(`terminal`),this.shell.executeCommandInTerminal(e)):{stdout:``,stderr:`terminal is unavailable
|
|
253
253
|
`,exitCode:1}}refit(){this.shell?.refit()}getBodyElement(){return this.container}render(){this.container.innerHTML=``,this.container.classList.add(`terminal-panel`);let e=document.createElement(`div`);e.className=`file-browser__header`;let t=document.createElement(`span`);if(t.className=`file-browser__header-title`,t.textContent=`Terminal`,e.appendChild(t),this.onClearTerminal){let t=document.createElement(`button`);t.className=`file-browser__header-btn`,t.dataset.tooltip=`Clear Terminal`,t.setAttribute(`aria-label`,`Clear Terminal`),t.innerHTML=`<svg width="14" height="14" viewBox="0 0 20 20" fill="none"><path d="m8.249,15.021c-.4,0-.733-.317-.748-.72l-.25-6.5c-.017-.414.307-.763.72-.778.01-.001.021-.001.03-.001.4,0,.733.317.748.72l.25,6.5c.017.414-.307.763-.72.778-.01.001-.021.001-.03.001Z" fill="currentColor"/><path d="m11.751,15.021c-.01,0-.02,0-.03-.001-.413-.016-.736-.364-.72-.778l.25-6.5c.015-.403.348-.72.748-.72.01,0,.02,0,.03.001.413.016.736.364.72.778l-.25,6.5c-.015.403-.348.72-.748.72Z" fill="currentColor"/><path d="m17,4h-3.5v-.75c0-1.24-1.01-2.25-2.25-2.25h-2.5c-1.24,0-2.25,1.01-2.25,2.25v.75h-3.5c-.414,0-.75.336-.75.75s.336.75.75.75h.52l.422,10.342c.048,1.21,1.036,2.158,2.248,2.158h7.619c1.212,0,2.2-.948,2.248-2.158l.422-10.342h.52c.414,0,.75-.336.75-.75s-.336-.75-.75-.75Zm-9-.75c0-.413.337-.75.75-.75h2.5c.413,0,.75.337.75.75v.75h-4v-.75Zm6.56,12.531c-.017.403-.346.719-.75.719h-7.619c-.404,0-.733-.316-.75-.719l-.42-10.281h9.959l-.42,10.281Z" fill="currentColor"/></svg>`,t.addEventListener(`click`,()=>this.onClearTerminal()),e.appendChild(t)}this.previewBtn=document.createElement(`button`),this.previewBtn.className=`file-browser__header-btn`,this.previewBtn.setAttribute(`aria-label`,`Toggle preview`),this.previewBtn.dataset.tooltip=`Preview`,this.previewBtn.disabled=!0;let n=`http://www.w3.org/2000/svg`,r=document.createElementNS(n,`svg`);r.setAttribute(`width`,`16`),r.setAttribute(`height`,`16`),r.setAttribute(`viewBox`,`0 0 20 20`),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`1.5`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`);let i=document.createElementNS(n,`path`);i.setAttribute(`d`,`M2 10s3-6 8-6 8 6 8 6-3 6-8 6-8-6-8-6z`),r.appendChild(i);let a=document.createElementNS(n,`circle`);a.setAttribute(`cx`,`10`),a.setAttribute(`cy`,`10`),a.setAttribute(`r`,`2.5`),r.appendChild(a),this.previewBtn.appendChild(r),this.previewBtn.addEventListener(`click`,()=>{this.previewBtn.disabled||this.setActiveView(this.activeView===`preview`?`terminal`:`preview`)}),e.appendChild(this.previewBtn),this.container.appendChild(e),this.terminalViewEl=document.createElement(`div`),this.terminalViewEl.className=`terminal-panel__view`,this.container.appendChild(this.terminalViewEl),this.previewViewEl=document.createElement(`div`),this.previewViewEl.className=`terminal-panel__view`,this.container.appendChild(this.previewViewEl),this.previewEmptyEl=document.createElement(`div`),this.previewEmptyEl.className=`terminal-panel__empty-state`,this.previewEmptyEl.textContent=`Run imgcat to preview media here.`,this.previewViewEl.appendChild(this.previewEmptyEl),this.setActiveView(`terminal`)}dispose(){this.shell?.setPreviewStateListener(null),this.shell?.dispose(),this.container.innerHTML=``}setActiveView(e){this.activeView=e,this.previewBtn.classList.toggle(`file-browser__header-btn--active`,e===`preview`),this.terminalViewEl.style.display=e===`terminal`?`flex`:`none`,this.previewViewEl.style.display=e===`preview`?`flex`:`none`,e===`terminal`&&this.refit()}handlePreviewStateChange(e){this.previewBtn.disabled=!e,this.previewEmptyEl.style.display=e?`none`:`flex`,e?this.setActiveView(`preview`):this.activeView===`preview`&&this.setActiveView(`terminal`)}};function bi(e){return e<1024?e+` B`:e<1024*1024?(e/1024).toFixed(1)+`K`:e<1024*1024*1024?(e/(1024*1024)).toFixed(1)+`M`:(e/(1024*1024*1024)).toFixed(1)+`G`}function xi(e){let t=`http://www.w3.org/2000/svg`,n=document.createElementNS(t,`svg`);n.setAttribute(`width`,`14`),n.setAttribute(`height`,`14`),n.setAttribute(`viewBox`,`0 0 20 20`),n.setAttribute(`fill`,`none`),n.setAttribute(`stroke`,`currentColor`),n.setAttribute(`stroke-width`,`1.5`),n.setAttribute(`stroke-linecap`,`round`),n.setAttribute(`stroke-linejoin`,`round`),n.style.flexShrink=`0`;for(let r of e){let e=document.createElementNS(t,`path`);e.setAttribute(`d`,r),n.appendChild(e)}return n}function Si(){return xi([`M2 6V5a1 1 0 0 1 1-1h4l2 2h8a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V6z`])}function Ci(){return xi([`M6 2h5l5 5v9a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1z`,`M11 2v5h5`])}function wi(e){let t=`http://www.w3.org/2000/svg`,n=document.createElementNS(t,`svg`);n.setAttribute(`width`,`10`),n.setAttribute(`height`,`10`),n.setAttribute(`viewBox`,`0 0 20 20`),n.setAttribute(`fill`,`none`),n.setAttribute(`stroke`,`currentColor`),n.setAttribute(`stroke-width`,`2`),n.setAttribute(`stroke-linecap`,`round`),n.setAttribute(`stroke-linejoin`,`round`),n.style.flexShrink=`0`,n.style.transition=`transform 130ms ease`,e&&(n.style.transform=`rotate(90deg)`);let r=document.createElementNS(t,`path`);return r.setAttribute(`d`,`M7 5l5 5-5 5`),n.appendChild(r),n}function Ti(e){return`'${e.replace(/'/g,`'\\''`)}'`}function Ei(e){return`${d(e)?`imgcat`:`cat`} ${Ti(e)}`}var Di=class{container;bodyEl;fs=null;expandedDirs=new Set([`/`]);refreshTimer=null;onRunCommand;selectedPath=null;keydownHandler=null;constructor(e,t={}){this.container=e,this.onRunCommand=t.onRunCommand??null,this.render()}setFs(e){this.fs=e,this.refresh(),this.refreshTimer=setInterval(()=>this.refresh(),3e3)}async refresh(){if(!this.fs)return;let e=document.createElement(`div`);try{await this.renderDir(`/`,e,0)}catch(e){console.warn(`[FileBrowser] Refresh failed:`,e instanceof Error?e.message:String(e));return}if(e.innerHTML===this.bodyEl.innerHTML){this.applySelection();return}let t=this.container.contains(document.activeElement);for(;this.bodyEl.firstChild;)this.bodyEl.removeChild(this.bodyEl.firstChild);for(;e.firstChild;)this.bodyEl.appendChild(e.firstChild);this.applySelection(),t&&this.selectedPath&&this.bodyEl.querySelector(`.file-browser__item--selected`)?.focus()}render(){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.container.classList.add(`file-browser`);let e=document.createElement(`div`);e.className=`file-browser__header`;let t=document.createElement(`span`);t.className=`file-browser__header-title`,t.textContent=`Files`,e.appendChild(t),this.container.appendChild(e),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`file-browser__body`,this.container.appendChild(this.bodyEl),this.setupKeydown()}async renderDir(e,t,n){if(!this.fs)return;let r;try{r=await this.fs.readDir(e)}catch(t){console.warn(`[FileBrowser] readDir failed:`,e,t instanceof Error?t.message:String(t));return}let i=r.filter(e=>e.type===`directory`).sort((e,t)=>e.name.localeCompare(t.name)),a=r.filter(e=>e.type===`file`).sort((e,t)=>e.name.localeCompare(t.name));for(let r of[...i,...a]){let i=e===`/`?`/`+r.name:e+`/`+r.name,a=document.createElement(`div`);if(a.className=`file-browser__item`,a.style.paddingLeft=12+n*16+`px`,a.dataset.path=r.type===`directory`&&!i.endsWith(`/`)?i+`/`:i,r.type===`directory`){let e=this.expandedDirs.has(i),o=document.createElement(`span`);o.className=`file-browser__arrow`,o.appendChild(wi(e)),a.appendChild(o);let s=document.createElement(`span`);s.className=`file-browser__icon`,s.appendChild(Si()),a.appendChild(s);let c=document.createElement(`span`);c.className=`file-browser__name`,c.textContent=r.name,a.appendChild(c);let l=document.createElement(`button`);l.className=`file-browser__action-btn`,l.style.marginLeft=`auto`,l.textContent=`ZIP`,l.title=`Download as ZIP`,l.addEventListener(`click`,e=>{e.stopPropagation(),this.downloadDirAsZip(i,r.name)}),a.appendChild(l),a.style.cursor=`pointer`,a.addEventListener(`click`,()=>{this.selectPath(i,`directory`),this.expandedDirs.has(i)?this.expandedDirs.delete(i):this.expandedDirs.add(i),this.refresh()}),t.appendChild(a),e&&await this.renderDir(i,t,n+1)}else{let e=document.createElement(`span`);e.className=`file-browser__arrow`,a.appendChild(e);let n=document.createElement(`span`);n.className=`file-browser__icon`,n.appendChild(Ci()),a.appendChild(n);let o=document.createElement(`span`);o.className=`file-browser__name`,o.textContent=r.name,a.appendChild(o);try{let e=await this.fs.stat(i),t=document.createElement(`span`);t.className=`file-browser__size`,t.textContent=bi(e.size),a.appendChild(t)}catch(e){console.warn(`[FileBrowser] stat failed:`,i,e instanceof Error?e.message:String(e))}let s=document.createElement(`button`);s.className=`file-browser__action-btn`,s.style.marginLeft=`8px`,s.textContent=`CAT`,s.title=this.onRunCommand?d(i)?`Preview media in terminal`:`Preview in terminal`:`Terminal unavailable`,s.disabled=!this.onRunCommand,s.addEventListener(`click`,e=>{e.stopPropagation(),this.previewFile(i)}),a.appendChild(s),a.addEventListener(`click`,()=>{this.selectPath(i,`file`)}),t.appendChild(a)}}}async collectFiles(e,t){if(!this.fs)return{};let n={},r=await this.fs.readDir(e);for(let i of r){let r=e===`/`?`/`+i.name:e+`/`+i.name,a=t?t+`/`+i.name:i.name;if(i.type===`directory`){let e=await this.collectFiles(r,a);Object.assign(n,e)}else{let e=await this.fs.readFile(r,{encoding:`binary`});n[a]=e instanceof Uint8Array?e:new TextEncoder().encode(e)}}return n}async downloadDirAsZip(e,t){if(this.fs)try{let n=P(await this.collectFiles(e,``)),r=new Blob([n.buffer],{type:`application/zip`}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=t+`.zip`,a.click(),URL.revokeObjectURL(i)}catch(t){console.error(`[FileBrowser] ZIP download failed:`,e,t instanceof Error?t.message:String(t))}}previewFile(e){if(!this.onRunCommand)return;let t=Ei(e);Promise.resolve(this.onRunCommand(t)).catch(t=>{console.error(`[FileBrowser] Preview command failed:`,e,t instanceof Error?t.message:String(t))})}selectPath(e,t){this.selectedPath=t===`directory`&&!e.endsWith(`/`)?e+`/`:e,this.applySelection(),this.bodyEl.querySelector(`.file-browser__item--selected`)?.focus()}applySelection(){let e=this.bodyEl.querySelector(`.file-browser__item--selected`);if(e&&(e.classList.remove(`file-browser__item--selected`),e.removeAttribute(`tabindex`)),!this.selectedPath)return;let t=this.bodyEl.querySelectorAll(`.file-browser__item`);for(let e of t)if(e.dataset.path===this.selectedPath){e.classList.add(`file-browser__item--selected`),e.tabIndex=0;break}}setupKeydown(){this.keydownHandler=e=>{!(e.metaKey||e.ctrlKey)||e.key!==`c`||this.selectedPath&&window.getSelection()?.isCollapsed!==!1&&(e.preventDefault(),navigator.clipboard.writeText(this.selectedPath).then(()=>{this.flashCopyFeedback()}).catch(e=>{console.warn(`[FileBrowser] Clipboard write failed:`,e instanceof Error?e.message:String(e))}))},this.container.addEventListener(`keydown`,this.keydownHandler)}flashCopyFeedback(){let e=this.bodyEl.querySelector(`.file-browser__item--selected`);e&&(e.classList.add(`file-browser__item--copy-flash`),setTimeout(()=>{e.classList.remove(`file-browser__item--copy-flash`)},300))}dispose(){for(this.keydownHandler&&=(this.container.removeEventListener(`keydown`,this.keydownHandler),null),this.refreshTimer&&=(clearInterval(this.refreshTimer),null);this.container.firstChild;)this.container.removeChild(this.container.firstChild)}},Oi=class{container;bodyEl;orchestrator=null;selectedScoopJid=null;refreshTimer=null;constructor(e){this.container=e,this.render()}setOrchestrator(e){this.orchestrator=e,this.refresh(),this.refreshTimer=setInterval(()=>this.refresh(),5e3)}setSelectedScoop(e){this.selectedScoopJid=e,this.refresh()}async refresh(){if(!this.orchestrator)return;let e=document.createElement(`div`);e.className=`memory-panel__content`;let t=document.createElement(`div`);t.className=`memory-panel__section`;let n=document.createElement(`div`);n.className=`memory-panel__section-header`,n.textContent=`Global Memory (/shared/CLAUDE.md)`,t.appendChild(n);let r=document.createElement(`div`);r.className=`memory-panel__memory-content`;try{r.textContent=await this.orchestrator.getGlobalMemory()||`(empty)`}catch{r.textContent=`(not available)`}if(t.appendChild(r),e.appendChild(t),this.selectedScoopJid){let t=this.orchestrator.getScoopContext(this.selectedScoopJid),n=this.orchestrator.getScoop(this.selectedScoopJid);if(t&&n){let r=document.createElement(`div`);r.className=`memory-panel__section`;let i=document.createElement(`div`);i.className=`memory-panel__section-header`,i.textContent=`${n.isCone?`Cone`:`Scoop`}: ${n.assistantLabel}`,r.appendChild(i);let a=document.createElement(`div`);a.className=`memory-panel__memory-content`;try{let e=t.getFS();if(e){let t=n.isCone?`/workspace/CLAUDE.md`:`/scoops/${n.folder}/CLAUDE.md`,r=await e.readFile(t,{encoding:`utf-8`});a.textContent=typeof r==`string`?r:new TextDecoder().decode(r)}else a.textContent=`(filesystem not ready)`}catch{a.textContent=`(no memory file yet)`}r.appendChild(a),e.appendChild(r)}}if(e.innerHTML!==this.bodyEl.innerHTML){for(;this.bodyEl.firstChild;)this.bodyEl.removeChild(this.bodyEl.firstChild);for(;e.firstChild;)this.bodyEl.appendChild(e.firstChild)}}render(){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.container.classList.add(`memory-panel`),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`memory-panel__body`,this.container.appendChild(this.bodyEl)}dispose(){this.refreshTimer&&=(clearInterval(this.refreshTimer),null)}},ki=n(`scoops-panel`),Ai=class{container;orchestrator=null;callbacks;selectedScoopJid=null;scoopStatuses=new Map;expanded=!1;constructor(e,t){this.container=e,this.callbacks=t,this.render()}toggleExpanded(){this.expanded=!this.expanded,this.container.classList.toggle(`layout__scoops--expanded`,this.expanded);let e=this.container.querySelector(`.scoops-hamburger`);e&&(e.innerHTML=this.expanded?`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M9.86241 16.4551C9.66612 16.4551 9.46886 16.3779 9.32237 16.2246L3.83507 10.5215C3.5548 10.2315 3.5548 9.77247 3.83507 9.48243L9.33507 3.76563C9.62218 3.4668 10.0978 3.45801 10.3946 3.74512C10.6935 4.03223 10.7032 4.50684 10.4151 4.80469L5.41613 10.002L10.4025 15.1855C10.6906 15.4834 10.6808 15.958 10.382 16.2451C10.2374 16.3857 10.0499 16.4551 9.86241 16.4551Z"/><path d="M15.6124 16.4551C15.4161 16.4551 15.2189 16.3779 15.0724 16.2246L9.58507 10.5215C9.3048 10.2315 9.3048 9.77247 9.58507 9.48243L15.0851 3.76563C15.3722 3.4668 15.8478 3.45801 16.1446 3.74512C16.4435 4.03223 16.4532 4.50684 16.1652 4.80469L11.1661 10.002L16.1525 15.1855C16.4406 15.4834 16.4308 15.958 16.132 16.2451C15.9874 16.3857 15.7999 16.4551 15.6124 16.4551Z"/></svg>`:`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M9.61805 16.2451C9.31922 15.958 9.30945 15.4834 9.59754 15.1855L14.5839 10.002L9.58485 4.80469C9.29677 4.50684 9.30653 4.03223 9.60536 3.74512C9.90223 3.45801 10.3778 3.4668 10.6649 3.76563L16.1649 9.48243C16.4452 9.77247 16.4452 10.2315 16.1649 10.5215L10.6776 16.2246C10.5311 16.3779 10.3339 16.4551 10.1376 16.4551C9.95008 16.4551 9.76258 16.3857 9.61805 16.2451Z"/><path d="M3.86805 16.2451C3.56922 15.958 3.55945 15.4834 3.84754 15.1855L8.83387 10.002L3.83485 4.80469C3.54677 4.50684 3.55653 4.03223 3.85536 3.74512C4.15223 3.45801 4.62782 3.4668 4.91493 3.76563L10.4149 9.48243C10.6952 9.77247 10.6952 10.2315 10.4149 10.5215L4.92763 16.2246C4.78114 16.3779 4.58388 16.4551 4.38759 16.4551C4.20008 16.4551 4.01258 16.3857 3.86805 16.2451Z"/></svg>`)}setOrchestrator(e){this.orchestrator=e,this.refreshScoops()}updateScoopStatus(e,t){this.scoopStatuses.set(e,t),this.refreshScoops()}refreshScoops(){if(!this.orchestrator)return;document.querySelectorAll(`.scoop-fixed-tooltip`).forEach(e=>e.remove());let e=this.orchestrator.getScoops(),t=e.find(e=>e.isCone),n=e.filter(e=>!e.isCone),r=`http://www.w3.org/2000/svg`,i=[`#e8457a`,`#f08c5a`,`#9b6dd7`,`#42b8a0`,`#d4953e`],a=[`#fde4ec`,`#fef0e4`,`#efe4f8`,`#e0f5ef`,`#fef3e0`],o=this.container.querySelector(`.scoop-cone-header`);if(o){for(;o.firstChild;)o.removeChild(o.firstChild);if(t){let e=this.scoopStatuses.get(t.jid)??`inactive`,n=t.jid===this.selectedScoopJid,i=`#e07030`,a=`#fef0e0`,s=document.createElement(`div`);s.className=`scoop-item scoop-item--cone ${n?`selected`:``} status-${e}`,s.dataset.jid=t.jid,s.setAttribute(`aria-label`,t.assistantLabel),s.style.setProperty(`--scoop-accent`,i),s.style.setProperty(`--scoop-accent-bg`,a);let c=document.createElement(`div`);c.className=`scoop-icon-wrap scoop-icon-wrap--cone`,c.style.background=a,c.style.width=`40px`,c.style.height=`40px`;let l=document.createElementNS(r,`svg`);l.setAttribute(`width`,`24`),l.setAttribute(`height`,`24`),l.setAttribute(`fill`,i),l.setAttribute(`viewBox`,`100 195 230 235`);let u=document.createElementNS(r,`path`);if(u.setAttribute(`d`,`M331.2,128.8c1.6-4.8,2.4-11.2,2.4-16.8c0-20.8-12.8-40-31.2-48.8c-8-36-47.2-63.2-92.8-63.2c-48,0-88,29.6-93.6,68.8C102.4,79.2,94.4,95.2,94.4,112c0,4.8,0.8,9.6,1.6,13.6c-7.2,9.6-10.4,20.8-10.4,32C85.6,180,100,200,120,208l85.6,212.8c1.6,3.2,4,4.8,7.2,4.8s6.4-1.6,7.2-4.8L305.6,208c20-8,34.4-27.2,34.4-50.4C340,147.2,336.8,136.8,331.2,128.8z M139.2,216l-1.6-3.2h0.8c1.6,0,2.4,0,4,0L139.2,216z M145.6,232.8l23.2-24.8c4.8,6.4,11.2,11.2,18.4,14.4l12,12l-28.8,30.4l-20.8-22.4L145.6,232.8z M210.4,246.4l28.8,30.4L210.4,308l-28.8-31.2L210.4,246.4z M168.8,289.6l1.6-1.6l28.8,32l-12.8,13.6L168.8,289.6z M212,396.8l-18.4-46.4l16.8-18.4l19.2,21.6L212,396.8z M236.8,336l-15.2-16.8l28.8-31.2l4,4L236.8,336z M250.4,264.8l-28.8-30.4l11.2-12c8-3.2,14.4-8,19.2-14.4l25.6,27.2L250.4,264.8z M284,218.4l-6.4-6.4c2.4,0,4.8,0.8,8,0.8h0.8L284,218.4z M285.6,196c-9.6,0-19.2-4-26.4-11.2c-1.6-1.6-4.8-2.4-7.2-2.4c-2.4,0.8-4.8,2.4-5.6,4.8c-6.4,13.6-20,23.2-35.2,23.2c-14.4,0-28-8.8-34.4-21.6c-0.8-2.4-3.2-4-5.6-4.8c-0.8,0-0.8,0-1.6,0c-1.6,0-4,0.8-5.6,2.4c-7.2,6.4-16,9.6-25.6,9.6c-20.8,0-38.4-16.8-38.4-38.4c0-9.6,3.2-18.4,9.6-24.8c1.6-2.4,2.4-5.6,1.6-8c-1.6-4-2.4-8.8-2.4-12.8c0-12.8,6.4-24.8,17.6-32c2.4-1.6,3.2-4,4-6.4c2.4-32,36.8-57.6,78.4-57.6c39.2,0,72.8,23.2,77.6,54.4c0.8,3.2,2.4,5.6,4.8,6.4c15.2,5.6,24.8,20,24.8,36c0,4.8-0.8,10.4-3.2,15.2c-0.8,2.4-0.8,5.6,0.8,8c4.8,6.4,8,14.4,8,23.2C323.2,179.2,306.4,196,285.6,196z`),l.appendChild(u),c.appendChild(l),e===`processing`||e===`ready`||e===`error`){let t=document.createElement(`span`);t.className=`scoop-dot scoop-dot--${e}`,c.appendChild(t)}s.appendChild(c);let d=document.createElement(`div`);d.className=`scoop-info`;let f=document.createElement(`div`);if(f.className=`scoop-name`,f.textContent=t.assistantLabel,d.appendChild(f),e===`processing`||e===`error`){let t=document.createElement(`div`);t.className=`scoop-subtitle`,t.textContent=e===`processing`?`Working…`:`Error`,d.appendChild(t)}s.appendChild(d);let p=document.createElement(`div`);if(p.className=`scoop-actions`,e===`processing`){let e=document.createElement(`span`);e.className=`scoop-spin-dot`,p.appendChild(e)}else if(e===`error`){let e=document.createElement(`span`);e.className=`scoop-err-dot`,p.appendChild(e)}s.appendChild(p),s.addEventListener(`click`,()=>this.selectScoop(t));let m=t.assistantLabel;s.addEventListener(`mouseenter`,()=>{if(this.expanded)return;let e=document.createElement(`div`);e.className=`scoop-fixed-tooltip`,e.textContent=m,document.body.appendChild(e);let t=s.getBoundingClientRect();e.style.top=`${t.top+t.height/2}px`,e.style.left=`${t.right+8}px`,s.__tip=e}),s.addEventListener(`mouseleave`,()=>{let e=s.__tip;e&&(e.remove(),s.__tip=null)}),o.appendChild(s)}}let s=this.container.querySelector(`.scoops-list`);if(s){for(;s.firstChild;)s.removeChild(s.firstChild);if(n.length===0){this.callbacks.onScoopsChanged?.(e);return}for(let e=0;e<n.length;e++){let t=n[e],o=this.scoopStatuses.get(t.jid)??`inactive`,c=t.jid===this.selectedScoopJid,l=i[e%i.length],u=a[e%a.length],d=document.createElement(`div`);d.className=`scoop-item ${c?`selected`:``} status-${o}`,d.dataset.jid=t.jid;let f=t.assistantLabel.replace(/-scoop$/,``);d.setAttribute(`aria-label`,f),d.style.setProperty(`--scoop-accent`,l),d.style.setProperty(`--scoop-accent-bg`,u);let p=document.createElement(`div`);p.className=`scoop-icon-wrap`,p.style.background=u;let m=document.createElementNS(r,`svg`);m.setAttribute(`width`,`20`),m.setAttribute(`height`,`20`),m.setAttribute(`fill`,l),m.setAttribute(`viewBox`,`70 0 290 210`);let h=document.createElementNS(r,`path`);if(h.setAttribute(`d`,`M331.2,128.8c1.6-4.8,2.4-11.2,2.4-16.8c0-20.8-12.8-40-31.2-48.8c-8-36-47.2-63.2-92.8-63.2c-48,0-88,29.6-93.6,68.8C102.4,79.2,94.4,95.2,94.4,112c0,4.8,0.8,9.6,1.6,13.6c-7.2,9.6-10.4,20.8-10.4,32C85.6,180,100,200,120,208l85.6,212.8c1.6,3.2,4,4.8,7.2,4.8s6.4-1.6,7.2-4.8L305.6,208c20-8,34.4-27.2,34.4-50.4C340,147.2,336.8,136.8,331.2,128.8z M285.6,196c-9.6,0-19.2-4-26.4-11.2c-1.6-1.6-4.8-2.4-7.2-2.4c-2.4,0.8-4.8,2.4-5.6,4.8c-6.4,13.6-20,23.2-35.2,23.2c-14.4,0-28-8.8-34.4-21.6c-0.8-2.4-3.2-4-5.6-4.8c-0.8,0-0.8,0-1.6,0c-1.6,0-4,0.8-5.6,2.4c-7.2,6.4-16,9.6-25.6,9.6c-20.8,0-38.4-16.8-38.4-38.4c0-9.6,3.2-18.4,9.6-24.8c1.6-2.4,2.4-5.6,1.6-8c-1.6-4-2.4-8.8-2.4-12.8c0-12.8,6.4-24.8,17.6-32c2.4-1.6,3.2-4,4-6.4c2.4-32,36.8-57.6,78.4-57.6c39.2,0,72.8,23.2,77.6,54.4c0.8,3.2,2.4,5.6,4.8,6.4c15.2,5.6,24.8,20,24.8,36c0,4.8-0.8,10.4-3.2,15.2c-0.8,2.4-0.8,5.6,0.8,8c4.8,6.4,8,14.4,8,23.2C323.2,179.2,306.4,196,285.6,196z`),m.appendChild(h),p.appendChild(m),o===`processing`||o===`ready`||o===`error`){let e=document.createElement(`span`);e.className=`scoop-dot scoop-dot--${o}`,p.appendChild(e)}d.appendChild(p);let g=document.createElement(`div`);g.className=`scoop-info`;let _=document.createElement(`div`);if(_.className=`scoop-name`,_.textContent=f,g.appendChild(_),o===`processing`||o===`error`){let e=document.createElement(`div`);e.className=`scoop-subtitle`,e.textContent=o===`processing`?`Working…`:`Error`,g.appendChild(e)}d.appendChild(g);let v=document.createElement(`div`);if(v.className=`scoop-actions`,o===`processing`){let e=document.createElement(`span`);e.className=`scoop-spin-dot`,v.appendChild(e)}else if(o===`error`){let e=document.createElement(`span`);e.className=`scoop-err-dot`,v.appendChild(e)}d.appendChild(v),d.addEventListener(`click`,()=>{this.selectScoop(t)}),d.addEventListener(`mouseenter`,()=>{if(this.expanded)return;let e=document.createElement(`div`);e.className=`scoop-fixed-tooltip`,e.textContent=f,document.body.appendChild(e);let t=d.getBoundingClientRect();e.style.top=`${t.top+t.height/2}px`,e.style.left=`${t.right+8}px`,d.__tip=e}),d.addEventListener(`mouseleave`,()=>{let e=d.__tip;e&&(e.remove(),d.__tip=null)}),s.appendChild(d)}this.callbacks.onScoopsChanged?.(e)}}selectScoop(e){this.selectedScoopJid=e.jid,this.refreshScoops(),this.callbacks.onScoopSelect(e);let t=new URL(window.location.href);e.isCone?t.searchParams.delete(`scoop`):t.searchParams.set(`scoop`,e.folder),history.replaceState(null,``,t.toString())}selectScoopByFolder(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.folder===e);t&&this.selectScoop(t)}setSelectedJid(e){this.selectedScoopJid=e,this.refreshScoops()}getSelectedScoopJid(){return this.selectedScoopJid}async deleteScoop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoop(e);if(t){if(t.isCone){alert(`Cannot delete the cone`);return}if(confirm(`Delete scoop "${t.name}"? This cannot be undone.`)){try{await this.orchestrator.unregisterScoop(e)}catch(e){let t=e instanceof Error?e.message:String(e);alert(t);return}this.selectedScoopJid===e&&(this.selectedScoopJid=null),this.refreshScoops(),ki.info(`Scoop deleted`,{jid:e,name:t.name})}}}async createScoop(e,t=!1){if(!this.orchestrator)throw Error(`Orchestrator not set`);let n=t?`cone`:this.sanitizeFolderName(e)+`-scoop`,r=t?`cone_${Date.now()}`:`scoop_${n}_${Date.now()}`,i={jid:r,name:e,folder:n,trigger:t?void 0:`@${n}`,requiresTrigger:!t,isCone:t,type:t?`cone`:`scoop`,assistantLabel:t?`sliccy`:n,addedAt:new Date().toISOString()};return await this.orchestrator.registerScoop(i),this.refreshScoops(),ki.info(`Scoop created`,{jid:r,name:e,isCone:t}),i}sanitizeFolderName(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,50)||`scoop`}render(){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);let e=document.createElement(`div`);e.className=`scoops-panel`;let t=document.createElement(`button`);t.className=`scoops-hamburger`,t.dataset.tooltip=`Toggle navigation`,t.dataset.tooltipPos=`right`,t.setAttribute(`aria-label`,`Toggle navigation`),t.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M9.61805 16.2451C9.31922 15.958 9.30945 15.4834 9.59754 15.1855L14.5839 10.002L9.58485 4.80469C9.29677 4.50684 9.30653 4.03223 9.60536 3.74512C9.90223 3.45801 10.3778 3.4668 10.6649 3.76563L16.1649 9.48243C16.4452 9.77247 16.4452 10.2315 16.1649 10.5215L10.6776 16.2246C10.5311 16.3779 10.3339 16.4551 10.1376 16.4551C9.95008 16.4551 9.76258 16.3857 9.61805 16.2451Z"/><path d="M3.86805 16.2451C3.56922 15.958 3.55945 15.4834 3.84754 15.1855L8.83387 10.002L3.83485 4.80469C3.54677 4.50684 3.55653 4.03223 3.85536 3.74512C4.15223 3.45801 4.62782 3.4668 4.91493 3.76563L10.4149 9.48243C10.6952 9.77247 10.6952 10.2315 10.4149 10.5215L4.92763 16.2246C4.78114 16.3779 4.58388 16.4551 4.38759 16.4551C4.20008 16.4551 4.01258 16.3857 3.86805 16.2451Z"/></svg>`,t.addEventListener(`click`,()=>this.toggleExpanded()),e.appendChild(t);let n=document.createElement(`div`);n.className=`scoop-cone-header`,e.appendChild(n);let r=document.createElement(`div`);r.className=`scoops-list`,e.appendChild(r),this.container.appendChild(e);let i=document.createElement(`style`);i.textContent=`
|
|
254
254
|
.scoops-panel {
|
|
255
255
|
display: flex;
|
|
@@ -722,8 +722,8 @@ mark{background:color-mix(in srgb,var(--s2-accent) 25%,transparent);color:inheri
|
|
|
722
722
|
50% { transform: scale(1.3); }
|
|
723
723
|
100% { transform: scale(1); }
|
|
724
724
|
}
|
|
725
|
-
`,document.head.appendChild(e)}},Mi=[{id:`chat`,label:`Chat`},{id:`terminal`,label:`Terminal`},{id:`files`,label:`Files`},{id:`memory`,label:`Memory`}],Ni=`slicc-hidden-tabs`,Pi=[`terminal`,`memory`];function Fi(){try{let e=localStorage.getItem(Ni);return e?new Set(JSON.parse(e)):new Set(Pi)}catch{return new Set(Pi)}}function Ii(e){let t=e.filter(e=>e!==`chat`);localStorage.setItem(Ni,JSON.stringify(t))}var Li=Mi.filter(e=>!Fi().has(e.id)),Ri=`chat`,zi=new Set(Mi.map(e=>e.id));function Bi(e){return zi.has(e)}var Vi=class{zoneId;tabBar;contentArea;tabs=new Map;activeTabId=null;callbacks;addBtn=null;fullpageBtn=null;isFullpage=!1;separator=null;scrollArea=null;storageKey;classPrefix;constructor(e,t,n,r={},i={}){this.tabBar=e,this.contentArea=t,this.zoneId=n,this.callbacks=r,this.storageKey=`slicc-${n}-tab`,this.classPrefix=i.classPrefix??`mini-tabs`}addTab(e){if(this.tabs.has(e.id))return;let t=document.createElement(`button`);if(t.dataset.tabId=e.id,e.pinned&&e.icon){t.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--icon ${this.classPrefix}__tab--dimmed`,t.innerHTML=e.icon,t.setAttribute(`aria-label`,e.label),t.dataset.tooltip=e.label,t.dataset.tooltipPos=`top`;let n=this.separator||this.findFirstNonPinnedBtn()||this.addBtn;if(n?this.tabBar.insertBefore(t,n):this.tabBar.appendChild(t),!this.separator){this.separator=document.createElement(`div`),this.separator.className=`${this.classPrefix}__separator`,this.scrollArea=document.createElement(`div`),this.scrollArea.className=`${this.classPrefix}__scroll`;let e=this.addBtn||this.fullpageBtn;e?(this.tabBar.insertBefore(this.separator,e),this.tabBar.insertBefore(this.scrollArea,e)):(this.tabBar.appendChild(this.separator),this.tabBar.appendChild(this.scrollArea))}t.addEventListener(`click`,()=>{let t=this.tabs.get(e.id);t&&!t.mounted&&this.enablePinnedTab(e.id),this.activateTab(e.id)}),this.tabs.set(e.id,{btn:t,container:e.element,tab:e,mounted:!1})}else{if(t.className=`${this.classPrefix}__tab`,t.appendChild(document.createTextNode(e.label)),e.closable){let n=document.createElement(`span`);n.className=`${this.classPrefix}__tab-close`,n.title=`Close panel`,n.textContent=`×`,n.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onTabClose?.(e.id)}),t.appendChild(n)}t.addEventListener(`click`,()=>this.activateTab(e.id)),this.scrollArea?this.scrollArea.appendChild(t):this.addBtn?this.tabBar.insertBefore(t,this.addBtn):this.tabBar.appendChild(t);let n=e.element;n.style.display=`none`,this.contentArea.appendChild(n),this.tabs.set(e.id,{btn:t,container:n,tab:e,mounted:!0}),(!this.activeTabId||!this.tabs.get(this.activeTabId)?.mounted)&&this.activateTab(e.id)}}removeTab(e){let t=this.tabs.get(e);if(t&&(t.btn.remove(),t.mounted&&t.container.remove(),this.tabs.delete(e),this.activeTabId===e)){let e=Array.from(this.tabs.entries()).find(([,e])=>e.mounted);e?this.activateTab(e[0]):this.activeTabId=null}}enablePinnedTab(e){let t=this.tabs.get(e);!t||t.mounted||(t.mounted=!0,t.btn.classList.remove(`${this.classPrefix}__tab--dimmed`),t.container.style.display=`none`,this.contentArea.appendChild(t.container))}isPinnedTabEnabled(e){return this.tabs.get(e)?.mounted??!1}activateTab(e){let t=this.tabs.get(e);if(!(!t||!t.mounted)){this.activeTabId=e;for(let[t,{btn:n,container:r,mounted:i}]of this.tabs){let a=t===e;n.classList.toggle(`${this.classPrefix}__tab--active`,a),i&&(r.style.display=a?`flex`:`none`)}try{localStorage.setItem(this.storageKey,e)}catch{}t.tab.onActivate?.(),this.callbacks.onTabActivate?.(e)}}getActiveTabId(){return this.activeTabId}getTabIds(){return Array.from(this.tabs.keys())}hasTab(e){return this.tabs.has(e)}setTabBadge(e,t){let n=this.tabs.get(e);if(!n)return;let r=n.btn.querySelector(`.${this.classPrefix}__tab-badge`);if(!t||t<=0){r?.remove();return}let i=r instanceof HTMLSpanElement?r:document.createElement(`span`);if(i.className=`${this.classPrefix}__tab-badge`,i.textContent=t>99?`99+`:String(t),i.setAttribute(`aria-label`,`${t} notifications`),!r){let e=n.btn.querySelector(`.${this.classPrefix}__tab-close`);e?n.btn.insertBefore(i,e):n.btn.appendChild(i)}}get tabCount(){return this.tabs.size}enableAddButton(){this.addBtn||(this.addBtn=document.createElement(`button`),this.addBtn.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--add`,this.addBtn.textContent=`+`,this.addBtn.dataset.tooltip=`Open panel`,this.addBtn.dataset.tooltipPos=`top`,this.addBtn.setAttribute(`aria-label`,`Open panel`),this.addBtn.addEventListener(`click`,()=>this.callbacks.onAddClick?.()),this.tabBar.appendChild(this.addBtn))}setAddButtonEnabled(e){this.addBtn&&(this.addBtn.disabled=!e)}enableFullpageButton(){this.fullpageBtn||(this.fullpageBtn=document.createElement(`button`),this.fullpageBtn.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--fullpage`,this.fullpageBtn.dataset.tooltip=`Full page`,this.fullpageBtn.dataset.tooltipPos=`top`,this.fullpageBtn.setAttribute(`aria-label`,`Toggle full page`),this.fullpageBtn.innerHTML=`<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2h4v4"/><path d="M6 14H2v-4"/><path d="M14 2L9.5 6.5"/><path d="M2 14l4.5-4.5"/></svg>`,this.fullpageBtn.addEventListener(`click`,()=>{this.isFullpage=!this.isFullpage,this.fullpageBtn.classList.toggle(`${this.classPrefix}__tab--active`,this.isFullpage),this.fullpageBtn.innerHTML=this.isFullpage?`<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14 6h-4V2"/><path d="M2 10h4v4"/><path d="M10 6l4.5-4.5"/><path d="M6 10L1.5 14.5"/></svg>`:`<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2h4v4"/><path d="M6 14H2v-4"/><path d="M14 2L9.5 6.5"/><path d="M2 14l4.5-4.5"/></svg>`,this.fullpageBtn.dataset.tooltip=this.isFullpage?`Exit full page`:`Full page`,this.callbacks.onFullpageToggle?.(this.isFullpage)}),this.tabBar.appendChild(this.fullpageBtn))}restoreActiveTab(){try{let e=localStorage.getItem(this.storageKey);if(e&&this.tabs.has(e)&&this.tabs.get(e).mounted)return this.activateTab(e),e}catch{}return null}findFirstNonPinnedBtn(){for(let[,e]of this.tabs)if(!e.tab.pinned)return e.btn;return null}},Hi=class{entries=new Map;listeners=new Set;register(e){this.entries.set(e.id,{descriptor:e}),this.notify()}unregister(e){this.entries.delete(e),this.notify()}get(e){return this.entries.get(e)}getByZone(e){let t=[];for(let n of this.entries.values())n.descriptor.zone===e&&t.push(n.descriptor);return t}getClosed(){let e=[];for(let t of this.entries.values())t.descriptor.zone===null&&e.push(t.descriptor);return e}setZone(e,t){let n=this.entries.get(e);n&&(n.descriptor.zone=t,this.notify())}ids(){return Array.from(this.entries.keys())}has(e){return this.entries.has(e)}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(){for(let e of this.listeners)e()}};function Ui(e,t,n){let r=document.querySelector(`.sprinkle-picker`);if(r){r.remove();return}let{registry:i,callbacks:a,getAvailableSprinkles:o}=n,s=i.getClosed(),c=o?.()??[];if(s.length===0&&c.length===0)return;let l=document.createElement(`div`);l.className=`sprinkle-picker`,l.style.cssText=`position: absolute; min-width: 160px; max-height: 300px; overflow-y: auto; background: var(--s2-bg-layer-2); border: 1px solid var(--s2-border-default); border-radius: var(--s2-radius-l); padding: 4px 0; box-shadow: var(--s2-shadow-elevated); z-index: 1000;`;let u=()=>{l.remove(),document.removeEventListener(`pointerdown`,f,!0),document.removeEventListener(`keydown`,p,!0)};for(let e of s){let n=Wi(e.label,()=>{a.onSelectPanel(e.id,t),u()});l.appendChild(n)}if(s.length>0&&c.length>0){let e=document.createElement(`div`);e.style.cssText=`height: 1px; background: var(--s2-border-default); margin: 4px 0;`,l.appendChild(e)}for(let e of c){let n=Wi(e.title,()=>{a.onSelectSprinkle(e.name,t),u()});l.appendChild(n)}let d=e.getBoundingClientRect();l.style.top=`${d.bottom+4}px`,l.style.left=`${d.left}px`,document.body.appendChild(l);let f=e=>{l.contains(e.target)||u()},p=e=>{e.key===`Escape`&&u()};requestAnimationFrame(()=>{document.addEventListener(`pointerdown`,f,!0),document.addEventListener(`keydown`,p,!0)})}function Wi(e,t){let n=document.createElement(`div`);return n.className=`sprinkle-picker__item`,n.style.cssText=`padding: 6px 12px; cursor: pointer; font-size: 12px; color: var(--s2-content-default); border-radius: var(--s2-radius-s); margin: 0 4px; transition: background 130ms ease;`,n.textContent=e,n.addEventListener(`mouseenter`,()=>{n.style.background=`var(--s2-bg-elevated)`}),n.addEventListener(`mouseleave`,()=>{n.style.background=``}),n.addEventListener(`click`,t),n}var Gi=class e{root;isExtension;scoopsEl;leftEl;rightEl;verticalDivider;terminalContainer;iframeContainer;threadHeaderEl;threadHeaderName;primaryZoneEl;primaryZone;get drawerZone(){return this.primaryZone}get drawerZoneEl(){return this.primaryZoneEl}tabContainers=new Map;activeTab=`chat`;debugTabContainers=null;scoopSwitcher=null;scoopSwitcherEl=null;avatarEl;logoSvg=null;logoImg=null;logoScoopCount=-1;panels;registry=new Hi;onModelChange;refreshModels;onScoopSelect;onClearChat;onClearFilesystem;onSprinkleClose;getAvailableSprinkles;onOpenSprinkle;constructor(e,t=!1){this.root=e,this.isExtension=t,t?this.buildTabbedLayout():this.buildSplitLayout()}setScoopSwitcherOrchestrator(e){this.scoopSwitcher?.setOrchestrator(e)}updateScoopSwitcherStatus(e,t){this.scoopSwitcher?.updateStatus(e,t)}setScoopSwitcherSelected(e){this.scoopSwitcher?.setSelected(e)}refreshScoopSwitcher(){this.scoopSwitcher?.refresh()}setActiveTab(e){this.isExtension&&this.extensionZone?.activateTab(e)}getActiveTab(){return this.activeTab}setPendingHandoffCount(e){this.isExtension&&this.extensionZone.setTabBadge(`chat`,e>0?e:null)}isTerminalOpen(){return this.isExtension?!0:this.primaryZone.isPinnedTabEnabled(`terminal`)}setAgentProcessing(e){this.threadHeaderEl?.classList.toggle(`thread-header--processing`,e)}openTerminal(){if(this.isExtension)return;this.primaryZone.isPinnedTabEnabled(`terminal`)||this.primaryZone.enablePinnedTab(`terminal`);let e=this.primaryZone.getActiveTabId();e&&e.startsWith(`sprinkle-`)||this.primaryZone.activateTab(`terminal`)}setDebugTabs(e){if(!this.isExtension||!this.debugTabContainers)return;let t=[{id:`terminal`,label:`Terminal`,container:this.debugTabContainers.terminal,onActivate:()=>this.panels?.terminal?.refit?.()},{id:`memory`,label:`Memory`,container:this.debugTabContainers.memory,onActivate:()=>this.panels?.memory?.refresh()}];for(let{id:n,label:r,container:i,onActivate:a}of t)e&&!this.extensionZone.hasTab(n)?(this.extensionZone.addTab({id:n,label:r,closable:!1,element:i,onActivate:a}),this.tabContainers.set(n,i)):!e&&this.extensionZone.hasTab(n)&&(this.extensionZone.removeTab(n),this.tabContainers.delete(n));Ii(e?[]:[`terminal`,`memory`])}buildHeader(e){let t=document.createElement(`div`);t.className=`header`;let n=()=>{if(D())return;let e=te();for(let t of e)if(t.models.length>0){let{defaultModelId:e}=A(t.providerId),n=(e?t.models.find(t=>t.id.toLowerCase().includes(e.toLowerCase())):void 0)??t.models[0];re(`${t.providerId}:${n.id}`);return}};n(),this.refreshModels=()=>{n(),this.panels?.chat?.refreshModelSelector(),this.refreshAvatar()};let r=document.createElement(`div`);r.className=`header__row`;let i=document.createElement(`div`);i.className=`header__brand`;let a=this.isExtension?24:28,o=this.sliccLogo(a);i.appendChild(o);let s=document.createElement(`div`);s.className=`header__title`,s.textContent=`slicc`,i.appendChild(s),r.appendChild(i),this.isExtension&&(this.scoopSwitcherEl=document.createElement(`div`),this.scoopSwitcherEl.className=`scoop-switcher`,this.scoopSwitcher=new ji(this.scoopSwitcherEl,{onScoopSelect:e=>this.onScoopSelect?.(e),onDeleteScoop:e=>{this.panels?.scoops?.deleteScoop?.(e)}}),r.appendChild(this.scoopSwitcherEl));let c=document.createElement(`div`);c.className=`header__spacer`,r.appendChild(c),this.avatarEl=this.buildUserAvatar(),r.appendChild(this.avatarEl),t.appendChild(r),e.appendChild(t)}static SCOOP_COLORS=[`#f000a0`,`#00f0f0`,`#90f000`,`#15d675`,`#e68619`];sliccLogo(e=22){let t=document.createElement(`img`);return t.width=e,t.height=e,t.src=`/logos/sliccy-color-0scoops-128x128.png`,t.alt=`slicc`,t.classList.add(`header__logo`),t.style.objectFit=`contain`,this.logoImg=t,t}static SCOOP_R=5;static SCOOP_SPACING=8.5;static ROW_STEP=7.5;pyramidLayout(t){if(t===0)return[];let{SCOOP_SPACING:n,ROW_STEP:r}=e,i=1;for(;i*(i+1)/2<t;)i++;let a=[],o=t,s=i;for(;o>0;){let e=Math.min(o,s);a.push(e),o-=e,s--}let c=[],l=19-e.SCOOP_R;for(let e of a){let t=16-(e-1)*n/2;for(let r=0;r<e;r++)c.push({cx:t+r*n,cy:l});l-=r}return c}updateLogoScoops(e){let t=e.filter(e=>!e.isCone),n=this.logoScoopCount;if(n===t.length&&n>=0)return;this.logoScoopCount=t.length;let r=Math.min(Math.max(t.length,0),10);this.logoImg&&(this.logoImg.src=`/logos/sliccy-color-${r}scoops-128x128.png`),this.updateFaviconForScoops(t.length)}updateFaviconForScoops(e){let t=Math.min(Math.max(e,0),10),n=document.querySelector(`link[rel="icon"]`);n&&(n.href=`/logos/sliccy-color-${t}scoops-32x32.png`);let r=typeof chrome<`u`?chrome:null;r?.action?.setIcon&&r.action.setIcon({path:{16:`logos/sliccy-color-${t}scoops-16x16.png`,32:`logos/sliccy-color-${t}scoops-32x32.png`,48:`logos/sliccy-color-${t}scoops-48x48.png`,128:`logos/sliccy-color-${t}scoops-128x128.png`}}).catch(()=>{})}getInitials(e){let t=e.trim().split(/\s+/);return t.length>=2?(t[0][0]+t[t.length-1][0]).toUpperCase():e.slice(0,2).toUpperCase()}buildUserAvatar(){let e=document.createElement(`div`);e.className=`header__avatar`,e.setAttribute(`aria-label`,`Account`),e.dataset.tooltip=`Account`;let t=ee().find(e=>e.userName||e.userAvatar);if(t?.userAvatar){let n=document.createElement(`img`);n.src=t.userAvatar,n.alt=t.userName??`User`,n.addEventListener(`error`,()=>{e.removeChild(n),t.userName&&(e.classList.add(`header__avatar--initials`),e.textContent=this.getInitials(t.userName))}),e.appendChild(n)}else t?.userName?(e.classList.add(`header__avatar--initials`),e.textContent=this.getInitials(t.userName)):(e.classList.add(`header__avatar--placeholder`),e.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M10 10c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v1c0 .55.45 1 1 1h14c.55 0 1-.45 1-1v-1c0-2.66-5.33-4-8-4z"/></svg>`);return e.addEventListener(`click`,()=>this.showAvatarPopover()),e}refreshAvatar(){if(!this.avatarEl)return;let e=this.avatarEl.parentElement;if(!e)return;let t=this.buildUserAvatar();e.replaceChild(t,this.avatarEl),this.avatarEl=t}showAvatarPopover(){let e=document.querySelector(`.avatar-popover`);if(e){e.remove();return}let t=document.createElement(`div`);t.className=`avatar-popover`;let n=ee(),r=n.find(e=>e.userName||e.accessToken||e.apiKey);if(r){let e=document.createElement(`div`);e.className=`avatar-popover__user`;let n=document.createElement(`div`);n.className=`avatar-popover__name`,n.textContent=r.userName||`Logged in`,e.appendChild(n);let i=document.createElement(`div`);i.className=`avatar-popover__provider`,i.textContent=A(r.providerId).name,e.appendChild(i),t.appendChild(e);let a=document.createElement(`button`);a.className=`avatar-popover__item`,a.textContent=`Sign out`,a.addEventListener(`click`,()=>{w(r.providerId),t.remove(),this.refreshAvatar(),this.refreshModels?.()}),t.appendChild(a)}if(n.length>0){let e=document.createElement(`div`);e.className=`avatar-popover__separator`,t.appendChild(e);let n=document.createElement(`button`);n.className=`avatar-popover__item avatar-popover__item--danger`,n.textContent=`Clear all accounts`,n.addEventListener(`click`,()=>{j(),t.remove(),this.refreshAvatar(),this.refreshModels?.()}),t.appendChild(n)}let i=document.createElement(`div`);i.className=`avatar-popover__separator`,t.appendChild(i);let a=document.createElement(`button`);a.className=`avatar-popover__item avatar-popover__item--danger`,a.textContent=`Clear chat`,a.addEventListener(`click`,async()=>{t.remove(),await this.panels?.chat?.clearSession(),await this.onClearChat?.(),location.reload()}),t.appendChild(a);let o=document.createElement(`div`);o.className=`avatar-popover__separator`,t.appendChild(o);let s=document.createElement(`button`);s.className=`avatar-popover__item`,s.textContent=`Account settings…`,s.addEventListener(`click`,async()=>{t.remove(),T()||j(),await C()&&(this.refreshAvatar(),this.refreshModels?.())}),t.appendChild(s),document.body.appendChild(t);let c=this.avatarEl.getBoundingClientRect();t.style.top=`${c.bottom+4}px`,t.style.right=`${window.innerWidth-c.right}px`;let l=e=>{if(e instanceof KeyboardEvent){if(e.key!==`Escape`)return}else if(t.contains(e.target)||this.avatarEl.contains(e.target))return;t.remove(),document.removeEventListener(`mousedown`,l),document.removeEventListener(`keydown`,l)};requestAnimationFrame(()=>{document.addEventListener(`mousedown`,l),document.addEventListener(`keydown`,l)})}extensionZone;buildTabbedLayout(){for(;this.root.firstChild;)this.root.removeChild(this.root.firstChild);this.buildHeader(this.root);let e=document.createElement(`div`);e.className=`tab-bar`,this.root.appendChild(e);let t=document.createElement(`div`);t.className=`tab-content`,this.root.appendChild(t),this.extensionZone=new Vi(e,t,`primary`,{onTabActivate:e=>{this.activeTab=e,e===`terminal`&&this.panels?.terminal?.refit?.(),e===`memory`&&this.panels?.memory?.refresh()},onTabClose:e=>{let t=e.startsWith(`sprinkle-`)?e.slice(9):e;this.onSprinkleClose?.(t)},onAddClick:()=>this.showExtensionPicker(e)},{classPrefix:`tab-bar`});let n=document.createElement(`div`);n.className=`tab-content__panel`;let r=document.createElement(`div`);r.className=`tab-content__panel`;let i=document.createElement(`div`);i.className=`tab-content__panel`;let a=document.createElement(`div`);a.className=`tab-content__panel`;for(let{id:e,label:t}of Li){let o=e===`chat`?n:e===`terminal`?r:e===`files`?i:a;this.extensionZone.addTab({id:e,label:t,closable:!1,element:o,onActivate:e===`terminal`?()=>this.panels?.terminal?.refit?.():e===`memory`?()=>this.panels?.memory?.refresh():void 0}),this.tabContainers.set(e,o)}this.debugTabContainers={terminal:r,memory:a},this.extensionZone.enableAddButton(),this.iframeContainer=document.createElement(`div`),this.iframeContainer.id=`scoop-iframes`,this.iframeContainer.style.display=`none`,this.root.appendChild(this.iframeContainer),this.scoopsEl=document.createElement(`div`),this.scoopsEl.style.display=`none`,this.root.appendChild(this.scoopsEl),this.panels={chat:new vi(n),terminal:new yi(r,{onClearTerminal:()=>{this.panels.terminal.clearTerminal()}}),fileBrowser:new Di(i,{onRunCommand:async e=>{await this.runFileBrowserCommand(e),this.extensionZone.activateTab(`terminal`)}}),memory:new Oi(a),scoops:new Ai(this.scoopsEl,{onScoopSelect:e=>this.onScoopSelect?.(e),onSendMessage:()=>{},onScoopsChanged:e=>this.updateLogoScoops(e)})},this.panels.chat.onModelChange=e=>this.onModelChange?.(e)}showExtensionPicker(e){let t=this.getAvailableSprinkles?.()??[],n=new Set(this.extensionZone.getTabIds()),r=t.filter(e=>!n.has(`sprinkle-${e.name}`));r.length!==0&&Ui(e,`primary`,{registry:this.registry,callbacks:{onSelectPanel:()=>{},onSelectSprinkle:e=>{this.onOpenSprinkle?.(e)}},getAvailableSprinkles:()=>r})}switchTab(e){this.extensionZone&&this.extensionZone.activateTab(e)}buildSplitLayout(){for(;this.root.firstChild;)this.root.removeChild(this.root.firstChild);this.buildHeader(this.root);let e=document.createElement(`div`);e.className=`layout`,this.scoopsEl=document.createElement(`div`),this.scoopsEl.className=`layout__scoops`,e.appendChild(this.scoopsEl),this.leftEl=document.createElement(`div`),this.leftEl.className=`layout__left`,this.threadHeaderEl=document.createElement(`div`),this.threadHeaderEl.className=`thread-header`;let t=document.createElement(`div`);t.className=`thread-header__title`;let n=document.createElement(`span`);n.className=`thread-header__icon`,n.innerHTML=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 4h14a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H7l-4 3V5a1 1 0 0 1 1-1z"/><path d="M7 8h6"/><path d="M7 11h3"/></svg>`,t.appendChild(n),this.threadHeaderName=document.createElement(`span`),this.threadHeaderName.className=`thread-header__name`,this.threadHeaderName.textContent=`sliccy`,t.appendChild(this.threadHeaderName),this.threadHeaderEl.appendChild(t);let r=document.createElement(`button`);r.className=`thread-header__panel-toggle thread-header__panel-toggle--right`,r.dataset.tooltip=`Toggle panel`,r.setAttribute(`aria-label`,`Toggle panel`),r.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3h14a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/><path d="M12 3v14"/></svg>`,r.addEventListener(`click`,()=>{this.rightEl.classList.toggle(`layout__right--open`)});let i=document.createElement(`button`);i.className=`thread-header__panel-toggle`,i.dataset.tooltip=`Clear Chat`,i.setAttribute(`aria-label`,`Clear Chat`),i.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="none"><path d="m8.249,15.021c-.4,0-.733-.317-.748-.72l-.25-6.5c-.017-.414.307-.763.72-.778.01-.001.021-.001.03-.001.4,0,.733.317.748.72l.25,6.5c.017.414-.307.763-.72.778-.01.001-.021.001-.03.001Z" fill="currentColor"/><path d="m11.751,15.021c-.01,0-.02,0-.03-.001-.413-.016-.736-.364-.72-.778l.25-6.5c.015-.403.348-.72.748-.72.01,0,.02,0,.03.001.413.016.736.364.72.778l-.25,6.5c-.015.403-.348.72-.748.72Z" fill="currentColor"/><path d="m17,4h-3.5v-.75c0-1.24-1.01-2.25-2.25-2.25h-2.5c-1.24,0-2.25,1.01-2.25,2.25v.75h-3.5c-.414,0-.75.336-.75.75s.336.75.75.75h.52l.422,10.342c.048,1.21,1.036,2.158,2.248,2.158h7.619c1.212,0,2.2-.948,2.248-2.158l.422-10.342h.52c.414,0,.75-.336.75-.75s-.336-.75-.75-.75Zm-9-.75c0-.413.337-.75.75-.75h2.5c.413,0,.75.337.75.75v.75h-4v-.75Zm6.56,12.531c-.017.403-.346.719-.75.719h-7.619c-.404,0-.733-.316-.75-.719l-.42-10.281h9.959l-.42,10.281Z" fill="currentColor"/></svg>`,i.addEventListener(`click`,async()=>{await this.panels.chat.clearSession(),await this.onClearChat?.(),location.reload()});let a=document.createElement(`div`);a.className=`thread-header__actions`,a.appendChild(i),a.appendChild(r),this.threadHeaderEl.appendChild(a),this.leftEl.appendChild(this.threadHeaderEl);let o=document.createElement(`div`);o.style.cssText=`display: flex; flex-direction: column; flex: 1; min-height: 0;`,this.leftEl.appendChild(o),e.appendChild(this.leftEl),this.verticalDivider=document.createElement(`div`),this.verticalDivider.className=`layout__divider layout__divider--vertical`,e.appendChild(this.verticalDivider),this.rightEl=document.createElement(`div`),this.rightEl.className=`layout__right`,this.primaryZoneEl=document.createElement(`div`),this.primaryZoneEl.style.cssText=`display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;`;let s=document.createElement(`div`);s.className=`mini-tabs`;let c=document.createElement(`button`);c.className=`thread-header__panel-toggle thread-header__panel-toggle--right`,c.dataset.tooltip=`Close panel`,c.setAttribute(`aria-label`,`Close panel`),c.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v14"/><path d="M3 3h14a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/></svg>`,c.addEventListener(`click`,()=>{this.rightEl.classList.remove(`layout__right--open`)}),s.appendChild(c),this.primaryZoneEl.appendChild(s);let l=document.createElement(`div`);l.style.cssText=`flex: 1; min-height: 0; display: flex; flex-direction: column; overflow: hidden;`,this.primaryZoneEl.appendChild(l),this.primaryZone=new Vi(s,l,`primary`,{onTabActivate:e=>{e===`terminal`&&this.panels?.terminal?.refit(),e===`memory`&&this.panels?.memory?.refresh()},onTabClose:e=>{let t=e.startsWith(`sprinkle-`)?e.slice(9):e;this.onSprinkleClose?.(t)},onAddClick:()=>this.showPickerForZone(`primary`,s),onFullpageToggle:e=>{this.leftEl.classList.toggle(`layout__left--fullpage-hidden`,e),this.verticalDivider.classList.toggle(`layout__divider--fullpage-hidden`,e),this.scoopsEl.classList.toggle(`layout__scoops--fullpage-hidden`,e),this.rightEl.classList.toggle(`layout__right--fullpage`,e)}}),this.terminalContainer=document.createElement(`div`),this.terminalContainer.style.cssText=`display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;`;let u=document.createElement(`div`);u.style.cssText=`display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;`;let d=document.createElement(`div`);d.style.cssText=`display: flex; flex-direction: column; min-height: 0; flex: 1;`;let f=e=>`<svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">${e}</svg>`;this.primaryZone.addTab({id:`terminal`,label:`Terminal`,closable:!1,element:this.terminalContainer,pinned:!0,icon:f(`<path d="M5.5 14.5C5.30762 14.5 5.11621 14.4268 4.96973 14.2803L1.21973 10.5303C0.92676 10.2373 0.92676 9.76269 1.21973 9.46972L4.96973 5.71972C5.2627 5.42675 5.73731 5.42675 6.03028 5.71972C6.32325 6.01269 6.32325 6.4873 6.03028 6.78027L2.81055 10L6.03028 13.2197C6.32325 13.5127 6.32325 13.9873 6.03028 14.2803C5.8838 14.4268 5.69238 14.5 5.5 14.5Z" fill="currentColor"/><path d="M14.5 14.5C14.3076 14.5 14.1162 14.4268 13.9697 14.2803C13.6768 13.9873 13.6768 13.5127 13.9697 13.2197L17.1895 9.99999L13.9697 6.78026C13.6768 6.48729 13.6768 6.01268 13.9697 5.71971C14.2627 5.42674 14.7373 5.42674 15.0303 5.71971L18.7803 9.46971C19.0732 9.76268 19.0732 10.2373 18.7803 10.5303L15.0303 14.2803C14.8838 14.4267 14.6924 14.5 14.5 14.5Z" fill="currentColor"/><path d="M8.22852 18C8.16993 18 8.11036 17.9932 8.05176 17.9795C7.64844 17.8818 7.40137 17.4766 7.49805 17.0742L10.998 2.57422C11.0957 2.1709 11.5078 1.92871 11.9033 2.02051C12.3066 2.11817 12.5537 2.52344 12.457 2.92578L8.95703 17.4258C8.87402 17.7695 8.56642 18 8.22852 18Z" fill="currentColor"/>`),onActivate:()=>this.panels?.terminal?.refit()}),this.primaryZone.addTab({id:`files`,label:`Files`,closable:!1,element:u,pinned:!0,icon:f(`<path d="M18 4.75C18 2.61621 13.9756 1.5 10 1.5C6.02441 1.5 2 2.61621 2 4.75C2 4.81714 2.01538 4.88037 2.02325 4.94556C2.01696 4.98462 2 5.01978 2 5.06055V15C2 17.0615 6.14697 18 10 18C13.853 18 18 17.0615 18 15V5.06055C18 5.01978 17.983 4.98462 17.9767 4.94556C17.9846 4.88037 18 4.81714 18 4.75ZM16.5002 9.99451C16.4084 10.4097 14.2719 11.5 10 11.5C5.72705 11.5 3.59033 10.4092 3.5 10V6.72449C5.02985 7.56665 7.52393 8 10 8C12.4761 8 14.9701 7.56665 16.5001 6.72437L16.5002 9.99451ZM10 3C14.2886 3 16.5 4.22656 16.5 4.75C16.5 5.27344 14.2886 6.5 10 6.5C5.71143 6.5 3.5 5.27344 3.5 4.75C3.5 4.22656 5.71143 3 10 3ZM10 16.5C5.72705 16.5 3.59033 15.4092 3.5 15V11.8464C5.05219 12.6304 7.58337 13 10 13C12.4168 13 14.9482 12.6304 16.5003 11.8463L16.5005 14.9941C16.4097 15.4092 14.273 16.5 10 16.5Z" fill="currentColor"/>`)}),this.primaryZone.addTab({id:`memory`,label:`Memory`,closable:!1,element:d,pinned:!0,icon:f(`<path d="M10.0039 12.5889C9.11573 12.5889 8.25098 12.1289 7.77588 11.3057C7.06787 10.0781 7.48975 8.50489 8.71582 7.79688C9.30908 7.45313 10.001 7.36329 10.665 7.54004C11.3276 7.71777 11.8814 8.14356 12.2241 8.73731C12.5674 9.33106 12.6582 10.0234 12.481 10.6855C12.3032 11.3486 11.8784 11.9024 11.2842 12.2451C10.8809 12.4785 10.4395 12.5889 10.0039 12.5889ZM9.07471 10.5557C9.36914 11.0645 10.0229 11.2392 10.5342 10.9463C10.7812 10.8037 10.958 10.5732 11.0317 10.2978C11.1055 10.0225 11.0679 9.73436 10.9253 9.48729C10.7822 9.24022 10.5522 9.06346 10.2764 8.98924C10.0015 8.916 9.71337 8.95408 9.46581 9.09569C8.95556 9.39061 8.78027 10.0449 9.07471 10.5557Z" fill="currentColor"/><path d="M6.90674 18.3184C6.56738 18.3184 6.22461 18.2334 5.91455 18.0537L5.09473 17.5811C4.20166 17.0674 3.84473 15.9316 4.28369 14.998L4.86377 13.7646C4.59863 13.4014 4.37402 13.0137 4.19189 12.6035L2.83496 12.4912C1.80615 12.4063 1.00049 11.5313 1.00049 10.5L0.99951 9.55371C0.99951 8.52051 1.80469 7.64453 2.83301 7.55957L4.1875 7.44531C4.2793 7.23633 4.37988 7.03613 4.48926 6.8457C4.59912 6.65429 4.72266 6.46679 4.8584 6.28125L4.27783 5.05176C3.83691 4.11914 4.1914 2.9834 5.08496 2.4668L5.90527 1.99317C6.79785 1.47657 7.95898 1.73438 8.54785 2.58301L9.32519 3.70117C9.76904 3.65137 10.2173 3.65332 10.666 3.70117L11.4414 2.58203C12.0303 1.73242 13.1924 1.47265 14.085 1.98828L14.9048 2.46094C15.7988 2.97656 16.1543 4.11231 15.7153 5.04492L15.1352 6.27734C15.4009 6.6416 15.6255 7.02929 15.8071 7.43847L17.164 7.55077C18.1924 7.63573 18.998 8.51073 18.999 9.54198L18.9995 10.4893C19.0005 11.5205 18.1958 12.3965 17.1675 12.4834L15.812 12.5976C15.7207 12.8066 15.6201 13.0059 15.5093 13.1973C15.3999 13.3867 15.2769 13.5752 15.1411 13.7607L15.7217 14.9902C16.1621 15.9219 15.8081 17.0576 14.915 17.5752L14.0942 18.0498C13.2007 18.5684 12.0405 18.3076 11.4517 17.459L10.6743 16.3408C10.2285 16.3897 9.78028 16.3887 9.3335 16.3418L8.55713 17.4619C8.17334 18.0156 7.54541 18.3184 6.90674 18.3184ZM6.9043 3.22461C6.81934 3.22461 6.73389 3.24609 6.65625 3.29102L5.83545 3.76563C5.61279 3.89454 5.52393 4.17774 5.63428 4.41114L6.41309 6.06153C6.53907 6.32813 6.49707 6.64356 6.30567 6.86817C6.10157 7.10743 5.93262 7.34473 5.78907 7.59376C5.64796 7.83985 5.52393 8.11231 5.42091 8.40333C5.32277 8.68165 5.07081 8.87599 4.77687 8.9004L2.95802 9.05372C2.6963 9.07618 2.49952 9.29005 2.49952 9.55274L2.5005 10.499C2.5005 10.7568 2.70167 10.9756 2.959 10.9971L4.77834 11.1475C5.07229 11.1719 5.32473 11.3662 5.42336 11.6445C5.62209 12.2051 5.92043 12.7207 6.31008 13.1768C6.50197 13.4004 6.54446 13.7168 6.41897 13.9834L5.64114 15.6358C5.53176 15.8692 5.62014 16.1533 5.84378 16.2813L6.66409 16.7549C6.88821 16.8848 7.17825 16.8184 7.32425 16.6074L8.36527 15.1055C8.53275 14.8633 8.82425 14.7363 9.11771 14.7959C9.70609 14.9033 10.3023 14.9043 10.8877 14.7949C11.1773 14.7402 11.4727 14.8613 11.6412 15.1045L12.6831 16.6035C12.8296 16.8135 13.1216 16.8799 13.3438 16.751L14.1641 16.2773C14.3902 16.1465 14.4776 15.8682 14.3653 15.6309L13.5864 13.9805C13.4605 13.7139 13.5025 13.3984 13.6939 13.1738C13.898 12.9336 14.0669 12.6973 14.2095 12.4492L14.21 12.4483C14.3526 12.2012 14.4732 11.9365 14.5786 11.6387C14.6773 11.3604 14.9292 11.166 15.2232 11.1416L17.042 10.9893C17.2984 10.9668 17.4995 10.7481 17.4995 10.4902L17.499 9.54298C17.499 9.28126 17.3018 9.06739 17.0401 9.04493L15.2212 8.89454C14.9273 8.87013 14.6748 8.67579 14.5762 8.39747C14.3784 7.8379 14.0796 7.32227 13.689 6.86524C13.4976 6.64063 13.4551 6.3252 13.5806 6.0586L14.3579 4.40626C14.4678 4.17286 14.3789 3.88868 14.1553 3.75978L13.3355 3.28712C13.1108 3.16017 12.8213 3.2256 12.6743 3.43653L11.6348 4.93653C11.4668 5.17969 11.1758 5.30469 10.8819 5.24708C10.2905 5.1377 9.69435 5.1377 9.11183 5.24708C8.81984 5.29884 8.52638 5.1797 8.35841 4.93751L7.31642 3.43849C7.22023 3.30079 7.06348 3.22461 6.9043 3.22461Z" fill="currentColor"/>`),onActivate:()=>this.panels?.memory?.refresh()}),this.primaryZone.enableAddButton(),this.primaryZone.enableFullpageButton(),this.rightEl.appendChild(this.primaryZoneEl),e.appendChild(this.rightEl),this.iframeContainer=document.createElement(`div`),this.iframeContainer.id=`scoop-iframes`,this.iframeContainer.style.display=`none`,e.appendChild(this.iframeContainer),this.root.appendChild(e),this.panels={chat:new vi(o),terminal:new yi(this.terminalContainer,{onClearTerminal:()=>{this.panels.terminal.clearTerminal(),this.openTerminal()}}),fileBrowser:new Di(u,{onRunCommand:async e=>{await this.runFileBrowserCommand(e),this.openTerminal()}}),memory:new Oi(d),scoops:new Ai(this.scoopsEl,{onScoopSelect:e=>{this.onScoopSelect?.(e),this.threadHeaderName.textContent=e.assistantLabel},onSendMessage:()=>{},onScoopsChanged:e=>this.updateLogoScoops(e)})},this.panels.chat.onModelChange=e=>this.onModelChange?.(e),this.setupVerticalDrag(),window.addEventListener(`resize`,()=>{})}getIframeContainer(){return this.iframeContainer}async runFileBrowserCommand(e){let t=await this.panels.terminal.runCommand(e);t.exitCode!==0&&t.stderr&&console.warn(`[Layout] File browser command failed:`,t.stderr.trim())}setupVerticalDrag(){if(!this.verticalDivider)return;let e=!1,t=t=>{if(!e)return;let n=this.root.querySelector(`.layout`)?.getBoundingClientRect();if(!n)return;let r=t.clientX-n.left-58,i=n.width-58,a=Math.max(.3,Math.min(.7,r/i));this.leftEl.style.flex=`${a*100} 0 0`,this.rightEl.style.flex=`${(1-a)*100} 0 0`},n=()=>{e=!1,this.verticalDivider.classList.remove(`active`),document.body.style.cursor=``,document.body.style.userSelect=``,window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n),this.panels?.terminal?.refit()};this.verticalDivider.addEventListener(`mousedown`,r=>{r.preventDefault(),e=!0,this.verticalDivider.classList.add(`active`),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`,window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)})}updateAddButtons(){let e=this.registry.getClosed().length,t=this.getAvailableSprinkles?.()??[],n=new Set;for(let e of this.registry.ids())e.startsWith(`sprinkle-`)&&this.registry.get(e)?.descriptor.zone!==null&&n.add(e.slice(9));let r=e+t.filter(e=>!n.has(e.name)).length>0;this.primaryZone?.setAddButtonEnabled(r)}showPickerForZone(e,t){let n=new Set;for(let e of this.registry.ids())e.startsWith(`sprinkle-`)&&this.registry.get(e)?.descriptor.zone!==null&&n.add(e.slice(9));let r=(this.getAvailableSprinkles?.()??[]).filter(e=>!n.has(e.name));Ui(t,e,{registry:this.registry,callbacks:{onSelectPanel:(e,t)=>{this.openPanelInZone(e,t)},onSelectSprinkle:(e,t)=>{this.onOpenSprinkle?.(e,t)}},getAvailableSprinkles:()=>r})}openPanelInZone(e,t){let n=this.registry.get(e);if(!n)return;let r=this.primaryZone;this.registry.setZone(e,t),r.addTab({id:n.descriptor.id,label:n.descriptor.label,closable:n.descriptor.closable,element:n.descriptor.element,onActivate:n.descriptor.onActivate}),r.activateTab(e)}dynamicSprinkles=new Map;addSprinkle(e,t,n,r){if(this.isExtension){let r=`sprinkle-${e}`,i=document.createElement(`div`);i.className=`tab-content__panel`,i.appendChild(n),this.extensionZone.addTab({id:r,label:t,closable:!0,element:i}),this.tabContainers.set(r,i),this.dynamicSprinkles.set(e,i),this.extensionZone.activateTab(r)}else{let i=r??`primary`,a=this.primaryZone,o=`sprinkle-${e}`,s=document.createElement(`div`);s.style.cssText=`display: flex; flex-direction: column; min-height: 0; overflow: auto; flex: 1;`,s.appendChild(n),this.registry.register({id:o,label:t,zone:i,closable:!0,element:s,onClose:()=>this.onSprinkleClose?.(e)}),a.addTab({id:o,label:t,closable:!0,element:s}),this.dynamicSprinkles.set(e,s),a.activateTab(o),this.updateAddButtons()}}removeSprinkle(e){if(this.isExtension){let t=`sprinkle-${e}`;this.extensionZone.removeTab(t),this.tabContainers.delete(t),this.dynamicSprinkles.delete(e)}else{let t=`sprinkle-${e}`;this.primaryZone.removeTab(t),this.registry.unregister(t),this.dynamicSprinkles.delete(e),this.updateAddButtons()}}dispose(){for(this.panels.chat.dispose(),this.panels.terminal.dispose(),this.panels.fileBrowser.dispose(),this.panels.memory.dispose();this.root.firstChild;)this.root.removeChild(this.root.firstChild)}},Ki=`slicc-theme`,qi=new Set([`dark`,`light`,`system`]);function Ji(){let e=localStorage.getItem(Ki);return e&&qi.has(e)?e:`system`}function Yi(){let e=Ji(),t=e===`light`;e===`system`&&(t=window.matchMedia?.(`(prefers-color-scheme: light)`).matches??!1),document.documentElement.classList.toggle(`theme-light`,t)}var Xi;function Zi(){Yi(),Xi=window.matchMedia?.(`(prefers-color-scheme: light)`),Xi?.addEventListener?.(`change`,()=>{Ji()===`system`&&Yi()})}var Qi=300,$i=6,ea=null,ta=null;function na(){return ea||(ea=document.createElement(`div`),ea.className=`s2-tooltip`,document.body.appendChild(ea)),ea}function ra(e){let t=e.getAttribute(`data-tooltip`);if(!t)return;let n=na();n.textContent=t,n.classList.remove(`s2-tooltip--visible`),n.style.left=`0`,n.style.top=`0`;let r=e.getBoundingClientRect(),i=n.getBoundingClientRect(),a=e.getAttribute(`data-tooltip-pos`)||`bottom`,o,s;a===`top`?(o=r.top-i.height-$i,s=r.left+r.width/2-i.width/2):a===`right`?(o=r.top+r.height/2-i.height/2,s=r.right+$i):(o=r.bottom+$i,s=r.left+r.width/2-i.width/2),a===`bottom`&&o+i.height>window.innerHeight-4?o=r.top-i.height-$i:a===`top`&&o<4&&(o=r.bottom+$i),s<4&&(s=4),s+i.width>window.innerWidth-4&&(s=window.innerWidth-i.width-4),n.style.top=`${o}px`,n.style.left=`${s}px`,n.classList.add(`s2-tooltip--visible`)}function ia(){ta&&=(clearTimeout(ta),null),ea?.classList.remove(`s2-tooltip--visible`)}function aa(){document.addEventListener(`pointerenter`,e=>{let t=e.target.closest?.(`[data-tooltip]`);t&&(ia(),ta=setTimeout(()=>ra(t),Qi))},!0),document.addEventListener(`pointerleave`,e=>{e.target.closest?.(`[data-tooltip]`)&&ia()},!0),document.addEventListener(`pointerdown`,ia,!0)}function oa(e){return e.toLowerCase().endsWith(ae)}function sa(e){return Array.from(e).find(e=>oa(e.name))??null}function ca(e){if(!e)return!1;if(e.items){for(let t of Array.from(e.items))if(t.kind===`file`)return!0}return!1}function la(e){if(!e)return null;if(e.files){let t=sa(e.files);if(t)return t}if(!e.items)return null;for(let t of Array.from(e.items)){if(t.kind&&t.kind!==`file`)continue;let e=t.getAsFile?.();if(e&&oa(e.name))return e}return null}var ua=new Map,da=new Map;function fa(e){let t=e.length;return t===0?`0`:`${t}:${e.charCodeAt(0)}:${t>1?e.charCodeAt(1):0}:${t>2?e.charCodeAt(2):0}:${t>3?e.charCodeAt(3):0}:${t>4?e.charCodeAt(Math.floor(t/4)):0}:${t>4?e.charCodeAt(Math.floor(t/2)):0}:${t>4?e.charCodeAt(Math.floor(3*t/4)):0}:${e.charCodeAt(t-1)}`}function pa(e,t){let n=fa(e);ua.set(n,t),setTimeout(()=>ua.delete(n),1e4)}function ma(e,t){da.set(e,t),setTimeout(()=>da.delete(e),1e4)}function ha(e){let t=da.get(e);return t?(da.delete(e),t):null}function ga(e){let t=fa(e),n=ua.get(t);return n?(ua.delete(t),n):null}var _a=class{registeredCommandsFn=null;constructor(e){this.vfs=e}setRegisteredCommandsFn(e){this.registeredCommandsFn=e}getVirtualBinCommands(){return this.registeredCommandsFn?.()??[]}async readFile(e,t){let n=I(e),r=await this.vfs.readFile(n,{encoding:`binary`}),i=r instanceof Uint8Array?r:new TextEncoder().encode(r);try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(i)}catch{let e=Array(i.length);for(let t=0;t<i.length;t++)e[t]=String.fromCharCode(i[t]);return e.join(``)}}async readFileBuffer(e){let t=I(e),n=await this.vfs.readFile(t,{encoding:`binary`});return n instanceof Uint8Array?n:new TextEncoder().encode(n)}async writeFile(e,t,n){let r=I(e);if(typeof t==`string`){let e=ga(t);if(e){await this.vfs.writeFile(r,e);return}let n=!1;for(let e=0;e<t.length;e++)if(t.charCodeAt(e)>255){n=!0;break}if(n)await this.vfs.writeFile(r,new TextEncoder().encode(t));else{let e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);await this.vfs.writeFile(r,e)}}else await this.vfs.writeFile(r,t)}async appendFile(e,t,n){let r=I(e),i=new Uint8Array;try{let e=await this.vfs.readFile(r,{encoding:`binary`});i=e instanceof Uint8Array?new Uint8Array(e):new TextEncoder().encode(e)}catch(e){if(!(e instanceof oe&&e.code===`ENOENT`))throw e}let a;if(typeof t==`string`){a=new Uint8Array(t.length);for(let e=0;e<t.length;e++)a[e]=t.charCodeAt(e)&255}else a=t instanceof Uint8Array?t:new Uint8Array(t);let o=new Uint8Array(i.length+a.length);o.set(i),o.set(a,i.length),await this.vfs.writeFile(r,o)}async exists(e){let t=I(e);if(t===`/usr`||t===`/usr/bin`)return!0;if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);return e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e)}return this.vfs.exists(t)}async stat(e){let t=I(e);if(t===`/usr`||t===`/usr/bin`)return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)};if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);if(e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e))return{isFile:!0,isDirectory:!1,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)}}let n=await this.vfs.stat(t);return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!1,mode:n.type===`directory`?493:420,size:n.size,mtime:new Date(n.mtime)}}async lstat(e){return this.stat(e)}async mkdir(e,t){await this.vfs.mkdir(I(e),t)}async readdir(e){let t=I(e);return t===`/usr`?[`bin`]:t===`/usr/bin`?this.getVirtualBinCommands().slice().sort():(await this.vfs.readDir(t)).map(e=>e.name)}async readdirWithFileTypes(e){let t=I(e);return t===`/usr`?[{name:`bin`,isFile:!1,isDirectory:!0,isSymbolicLink:!1}]:t===`/usr/bin`?this.getVirtualBinCommands().slice().sort().map(e=>({name:e,isFile:!0,isDirectory:!1,isSymbolicLink:!1})):(await this.vfs.readDir(t)).map(e=>({name:e.name,isFile:e.type===`file`,isDirectory:e.type===`directory`,isSymbolicLink:!1}))}async rm(e,t){await this.vfs.rm(I(e),t)}async cp(e,t,n){let r=I(e),i=I(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new oe(`EISDIR`,`is a directory`,r);await this.cpDir(r,i)}else await this.vfs.copyFile(r,i)}async cpDir(e,t){await this.vfs.mkdir(t,{recursive:!0});let n=await this.vfs.readDir(e);for(let r of n){let n=L(e,r.name),i=L(t,r.name);r.type===`directory`?await this.cpDir(n,i):await this.vfs.copyFile(n,i)}}async mv(e,t){await this.vfs.rename(I(e),I(t))}resolvePath(e,t){return t.startsWith(`/`)?I(t):I(L(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){throw Error(`Symlinks not supported in VirtualFS`)}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){throw Error(`Symlinks not supported in VirtualFS`)}async realpath(e){return I(e)}async utimes(e,t,n){}},va=t((e=>{e.byteLength=c,e.toByteArray=u,e.fromByteArray=p;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a<o;++a)t[a]=i[a],n[i.charCodeAt(a)]=a;n[45]=62,n[95]=63;function s(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e){var t=s(e),n=t[0],r=t[1];return(n+r)*3/4-r}function l(e,t,n){return(t+n)*3/4-n}function u(e){var t,i=s(e),a=i[0],o=i[1],c=new r(l(e,a,o)),u=0,d=o>0?a-4:a,f;for(f=0;f<d;f+=4)t=n[e.charCodeAt(f)]<<18|n[e.charCodeAt(f+1)]<<12|n[e.charCodeAt(f+2)]<<6|n[e.charCodeAt(f+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,c[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,c[u++]=t>>8&255,c[u++]=t&255),c}function d(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[e&63]}function f(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(d(r));return i.join(``)}function p(e){for(var n,r=e.length,i=r%3,a=[],o=16383,s=0,c=r-i;s<c;s+=o)a.push(f(e,s,s+o>c?c:s+o));return i===1?(n=e[r-1],a.push(t[n>>2]+t[n<<4&63]+`==`)):i===2&&(n=(e[r-2]<<8)+e[r-1],a.push(t[n>>10]+t[n>>4&63]+t[n<<2&63]+`=`)),a.join(``)}})),ya=t((e=>{e.read=function(e,t,n,r,i){var a,o,s=i*8-r-1,c=(1<<s)-1,l=c>>1,u=-7,d=n?i-1:0,f=n?-1:1,p=e[t+d];for(d+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=a*256+e[t+d],d+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=f,u-=8);if(a===0)a=1-l;else if(a===c)return o?NaN:(p?-1:1)*(1/0);else o+=2**r,a-=l;return(p?-1:1)*o*2**(a-r)},e.write=function(e,t,n,r,i,a){var o,s,c,l=a*8-i-1,u=(1<<l)-1,d=u>>1,f=i===23?2**-24-2**-77:0,p=r?0:a-1,m=r?1:-1,h=+(t<0||t===0&&1/t<0);for(t=Math.abs(t),isNaN(t)||t===1/0?(s=+!!isNaN(t),o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=2**-o)<1&&(o--,c*=2),o+d>=1?t+=f/c:t+=f*2**(1-d),t*c>=2&&(o++,c/=2),o+d>=u?(s=0,o=u):o+d>=1?(s=(t*c-1)*2**i,o+=d):(s=t*2**(d-1)*2**i,o=0));i>=8;e[n+p]=s&255,p+=m,s/=256,i-=8);for(o=o<<i|s,l+=i;l>0;e[n+p]=o&255,p+=m,o/=256,l-=8);e[n+p-m]|=h*128}})),ba=t((e=>{var t=va(),n=ya(),r=typeof Symbol==`function`&&typeof Symbol.for==`function`?Symbol.for(`nodejs.util.inspect.custom`):null;e.Buffer=s,e.SlowBuffer=v,e.INSPECT_MAX_BYTES=50;var i=2147483647;e.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=a(),!s.TYPED_ARRAY_SUPPORT&&typeof console<`u`&&typeof console.error==`function`&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),e.foo()===42}catch{return!1}}Object.defineProperty(s.prototype,`parent`,{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,`offset`,{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}});function o(e){if(e>i)throw RangeError(`The value "`+e+`" is invalid for option "size"`);let t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if(typeof e==`number`){if(typeof t==`string`)throw TypeError(`The "string" argument must be of type string. Received type number`);return d(e)}return c(e,t,n)}s.poolSize=8192;function c(e,t,n){if(typeof e==`string`)return f(e,t);if(ArrayBuffer.isView(e))return m(e);if(e==null)throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e);if(_e(e,ArrayBuffer)||e&&_e(e.buffer,ArrayBuffer)||typeof SharedArrayBuffer<`u`&&(_e(e,SharedArrayBuffer)||e&&_e(e.buffer,SharedArrayBuffer)))return h(e,t,n);if(typeof e==`number`)throw TypeError(`The "value" argument must not be of type number. Received type number`);let r=e.valueOf&&e.valueOf();if(r!=null&&r!==e)return s.from(r,t,n);let i=g(e);if(i)return i;if(typeof Symbol<`u`&&Symbol.toPrimitive!=null&&typeof e[Symbol.toPrimitive]==`function`)return s.from(e[Symbol.toPrimitive](`string`),t,n);throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e)}s.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array);function l(e){if(typeof e!=`number`)throw TypeError(`"size" argument must be of type number`);if(e<0)throw RangeError(`The value "`+e+`" is invalid for option "size"`)}function u(e,t,n){return l(e),e<=0||t===void 0?o(e):typeof n==`string`?o(e).fill(t,n):o(e).fill(t)}s.alloc=function(e,t,n){return u(e,t,n)};function d(e){return l(e),o(e<0?0:_(e)|0)}s.allocUnsafe=function(e){return d(e)},s.allocUnsafeSlow=function(e){return d(e)};function f(e,t){if((typeof t!=`string`||t===``)&&(t=`utf8`),!s.isEncoding(t))throw TypeError(`Unknown encoding: `+t);let n=y(e,t)|0,r=o(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}function p(e){let t=e.length<0?0:_(e.length)|0,n=o(t);for(let r=0;r<t;r+=1)n[r]=e[r]&255;return n}function m(e){if(_e(e,Uint8Array)){let t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return p(e)}function h(e,t,n){if(t<0||e.byteLength<t)throw RangeError(`"offset" is outside of buffer bounds`);if(e.byteLength<t+(n||0))throw RangeError(`"length" is outside of buffer bounds`);let r;return r=t===void 0&&n===void 0?new Uint8Array(e):n===void 0?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,s.prototype),r}function g(e){if(s.isBuffer(e)){let t=_(e.length)|0,n=o(t);return n.length===0||e.copy(n,0,0,t),n}if(e.length!==void 0)return typeof e.length!=`number`||ve(e.length)?o(0):p(e);if(e.type===`Buffer`&&Array.isArray(e.data))return p(e.data)}function _(e){if(e>=i)throw RangeError(`Attempt to allocate Buffer larger than maximum size: 0x`+i.toString(16)+` bytes`);return e|0}function v(e){return+e!=e&&(e=0),s.alloc(+e)}s.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==s.prototype},s.compare=function(e,t){if(_e(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),_e(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw TypeError(`The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array`);if(e===t)return 0;let n=e.length,r=t.length;for(let i=0,a=Math.min(n,r);i<a;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:+(r<n)},s.isEncoding=function(e){switch(String(e).toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`latin1`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw TypeError(`"list" argument must be an Array of Buffers`);if(e.length===0)return s.alloc(0);let n;if(t===void 0)for(t=0,n=0;n<e.length;++n)t+=e[n].length;let r=s.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){let t=e[n];if(_e(t,Uint8Array))i+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,i)):Uint8Array.prototype.set.call(r,t,i);else if(s.isBuffer(t))t.copy(r,i);else throw TypeError(`"list" argument must be an Array of Buffers`);i+=t.length}return r};function y(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||_e(e,ArrayBuffer))return e.byteLength;if(typeof e!=`string`)throw TypeError(`The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type `+typeof e);let n=e.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&n===0)return 0;let i=!1;for(;;)switch(t){case`ascii`:case`latin1`:case`binary`:return n;case`utf8`:case`utf-8`:return pe(e).length;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return n*2;case`hex`:return n>>>1;case`base64`:return he(e).length;default:if(i)return r?-1:pe(e).length;t=(``+t).toLowerCase(),i=!0}}s.byteLength=y;function b(e,t,n){let r=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((n===void 0||n>this.length)&&(n=this.length),n<=0)||(n>>>=0,t>>>=0,n<=t))return``;for(e||=`utf8`;;)switch(e){case`hex`:return re(this,t,n);case`utf8`:case`utf-8`:return ee(this,t,n);case`ascii`:return te(this,t,n);case`latin1`:case`binary`:return ne(this,t,n);case`base64`:return k(this,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return ie(this,t,n);default:if(r)throw TypeError(`Unknown encoding: `+e);e=(e+``).toLowerCase(),r=!0}}s.prototype._isBuffer=!0;function x(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}s.prototype.swap16=function(){let e=this.length;if(e%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(let t=0;t<e;t+=2)x(this,t,t+1);return this},s.prototype.swap32=function(){let e=this.length;if(e%4!=0)throw RangeError(`Buffer size must be a multiple of 32-bits`);for(let t=0;t<e;t+=4)x(this,t,t+3),x(this,t+1,t+2);return this},s.prototype.swap64=function(){let e=this.length;if(e%8!=0)throw RangeError(`Buffer size must be a multiple of 64-bits`);for(let t=0;t<e;t+=8)x(this,t,t+7),x(this,t+1,t+6),x(this,t+2,t+5),x(this,t+3,t+4);return this},s.prototype.toString=function(){let e=this.length;return e===0?``:arguments.length===0?ee(this,0,e):b.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw TypeError(`Argument must be a Buffer`);return this===e?!0:s.compare(this,e)===0},s.prototype.inspect=function(){let t=``,n=e.INSPECT_MAX_BYTES;return t=this.toString(`hex`,0,n).replace(/(.{2})/g,`$1 `).trim(),this.length>n&&(t+=` ... `),`<Buffer `+t+`>`},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(_e(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw TypeError(`The "target" argument must be one of type Buffer or Uint8Array. Received type `+typeof e);if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),r===void 0&&(r=0),i===void 0&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw RangeError(`out of range index`);if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;let a=i-r,o=n-t,c=Math.min(a,o),l=this.slice(r,i),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){a=l[e],o=u[e];break}return a<o?-1:+(o<a)};function S(e,t,n,r,i){if(e.length===0)return-1;if(typeof n==`string`?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,ve(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0)if(i)n=0;else return-1;if(typeof t==`string`&&(t=s.from(t,r)),s.isBuffer(t))return t.length===0?-1:C(e,t,n,r,i);if(typeof t==`number`)return t&=255,typeof Uint8Array.prototype.indexOf==`function`?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):C(e,[t],n,r,i);throw TypeError(`val must be string, number or Buffer`)}function C(e,t,n,r,i){let a=1,o=e.length,s=t.length;if(r!==void 0&&(r=String(r).toLowerCase(),r===`ucs2`||r===`ucs-2`||r===`utf16le`||r===`utf-16le`)){if(e.length<2||t.length<2)return-1;a=2,o/=2,s/=2,n/=2}function c(e,t){return a===1?e[t]:e.readUInt16BE(t*a)}let l;if(i){let r=-1;for(l=n;l<o;l++)if(c(e,l)===c(t,r===-1?0:l-r)){if(r===-1&&(r=l),l-r+1===s)return r*a}else r!==-1&&(l-=l-r),r=-1}else for(n+s>o&&(n=o-s),l=n;l>=0;l--){let n=!0;for(let r=0;r<s;r++)if(c(e,l+r)!==c(t,r)){n=!1;break}if(n)return l}return-1}s.prototype.includes=function(e,t,n){return this.indexOf(e,t,n)!==-1},s.prototype.indexOf=function(e,t,n){return S(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return S(this,e,t,n,!1)};function w(e,t,n,r){n=Number(n)||0;let i=e.length-n;r?(r=Number(r),r>i&&(r=i)):r=i;let a=t.length;r>a/2&&(r=a/2);let o;for(o=0;o<r;++o){let r=parseInt(t.substr(o*2,2),16);if(ve(r))return o;e[n+o]=r}return o}function T(e,t,n,r){return ge(pe(t,e.length-n),e,n,r)}function E(e,t,n,r){return ge(me(t),e,n,r)}function D(e,t,n,r){return ge(he(t),e,n,r)}function O(e,t,n,r){return ge(B(t,e.length-n),e,n,r)}s.prototype.write=function(e,t,n,r){if(t===void 0)r=`utf8`,n=this.length,t=0;else if(n===void 0&&typeof t==`string`)r=t,n=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(n)?(n>>>=0,r===void 0&&(r=`utf8`)):(r=n,n=void 0);else throw Error(`Buffer.write(string, encoding, offset[, length]) is no longer supported`);let i=this.length-t;if((n===void 0||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw RangeError(`Attempt to write outside buffer bounds`);r||=`utf8`;let a=!1;for(;;)switch(r){case`hex`:return w(this,e,t,n);case`utf8`:case`utf-8`:return T(this,e,t,n);case`ascii`:case`latin1`:case`binary`:return E(this,e,t,n);case`base64`:return D(this,e,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return O(this,e,t,n);default:if(a)throw TypeError(`Unknown encoding: `+r);r=(``+r).toLowerCase(),a=!0}},s.prototype.toJSON=function(){return{type:`Buffer`,data:Array.prototype.slice.call(this._arr||this,0)}};function k(e,n,r){return n===0&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function ee(e,t,n){n=Math.min(e.length,n);let r=[],i=t;for(;i<n;){let t=e[i],a=null,o=t>239?4:t>223?3:t>191?2:1;if(i+o<=n){let n,r,s,c;switch(o){case 1:t<128&&(a=t);break;case 2:n=e[i+1],(n&192)==128&&(c=(t&31)<<6|n&63,c>127&&(a=c));break;case 3:n=e[i+1],r=e[i+2],(n&192)==128&&(r&192)==128&&(c=(t&15)<<12|(n&63)<<6|r&63,c>2047&&(c<55296||c>57343)&&(a=c));break;case 4:n=e[i+1],r=e[i+2],s=e[i+3],(n&192)==128&&(r&192)==128&&(s&192)==128&&(c=(t&15)<<18|(n&63)<<12|(r&63)<<6|s&63,c>65535&&c<1114112&&(a=c))}}a===null?(a=65533,o=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|a&1023),r.push(a),i+=o}return j(r)}var A=4096;function j(e){let t=e.length;if(t<=A)return String.fromCharCode.apply(String,e);let n=``,r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=A));return n}function te(e,t,n){let r=``;n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]&127);return r}function ne(e,t,n){let r=``;n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function re(e,t,n){let r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let i=``;for(let r=t;r<n;++r)i+=ye[e[r]];return i}function ie(e,t,n){let r=e.slice(t,n),i=``;for(let e=0;e<r.length-1;e+=2)i+=String.fromCharCode(r[e]+r[e+1]*256);return i}s.prototype.slice=function(e,t){let n=this.length;e=~~e,t=t===void 0?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t<e&&(t=e);let r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r};function M(e,t,n){if(e%1!=0||e<0)throw RangeError(`offset is not uint`);if(e+t>n)throw RangeError(`Trying to access beyond buffer length`)}s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e],i=1,a=0;for(;++a<t&&(i*=256);)r+=this[e+a]*i;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=be(function(e){e>>>=0,le(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&ue(e,this.length-8);let r=t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,i=this[++e]+this[++e]*2**8+this[++e]*2**16+n*2**24;return BigInt(r)+(BigInt(i)<<BigInt(32))}),s.prototype.readBigUInt64BE=be(function(e){e>>>=0,le(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&ue(e,this.length-8);let r=t*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],i=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n;return(BigInt(r)<<BigInt(32))+BigInt(i)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e],i=1,a=0;for(;++a<t&&(i*=256);)r+=this[e+a]*i;return i*=128,r>=i&&(r-=2**(8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=t,i=1,a=this[e+--r];for(;r>0&&(i*=256);)a+=this[e+--r]*i;return i*=128,a>=i&&(a-=2**(8*t)),a},s.prototype.readInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||M(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||M(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=be(function(e){e>>>=0,le(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&ue(e,this.length-8);let r=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24)}),s.prototype.readBigInt64BE=be(function(e){e>>>=0,le(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&ue(e,this.length-8);let r=(t<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||M(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||M(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||M(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||M(e,8,this.length),n.read(this,e,!1,52,8)};function N(e,t,n,r,i,a){if(!s.isBuffer(e))throw TypeError(`"buffer" argument must be a Buffer instance`);if(t>i||t<a)throw RangeError(`"value" argument is out of bounds`);if(n+r>e.length)throw RangeError(`Index out of range`)}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;N(this,e,t,n,r,0)}let i=1,a=0;for(this[t]=e&255;++a<n&&(i*=256);)this[t+a]=e/i&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;N(this,e,t,n,r,0)}let i=n-1,a=1;for(this[t+i]=e&255;--i>=0&&(a*=256);)this[t+i]=e/a&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,255,0),this[t]=e&255,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function P(e,t,n,r,i){ce(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function ae(e,t,n,r,i){ce(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n+7]=a,a>>=8,e[n+6]=a,a>>=8,e[n+5]=a,a>>=8,e[n+4]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}s.prototype.writeBigUInt64LE=be(function(e,t=0){return P(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeBigUInt64BE=be(function(e,t=0){return ae(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);N(this,e,t,n,r-1,-r)}let i=0,a=1,o=0;for(this[t]=e&255;++i<n&&(a*=256);)e<0&&o===0&&this[t+i-1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);N(this,e,t,n,r-1,-r)}let i=n-1,a=1,o=0;for(this[t+i]=e&255;--i>=0&&(a*=256);)e<0&&o===0&&this[t+i+1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4},s.prototype.writeBigInt64LE=be(function(e,t=0){return P(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))}),s.prototype.writeBigInt64BE=be(function(e,t=0){return ae(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))});function F(e,t,n,r,i,a){if(n+r>e.length||n<0)throw RangeError(`Index out of range`)}function I(e,t,r,i,a){return t=+t,r>>>=0,a||F(e,t,r,4,34028234663852886e22,-34028234663852886e22),n.write(e,t,r,i,23,4),r+4}s.prototype.writeFloatLE=function(e,t,n){return I(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return I(this,e,t,!1,n)};function L(e,t,r,i,a){return t=+t,r>>>=0,a||F(e,t,r,8,17976931348623157e292,-17976931348623157e292),n.write(e,t,r,i,52,8),r+8}s.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw TypeError(`argument should be a Buffer`);if(n||=0,!r&&r!==0&&(r=this.length),t>=e.length&&(t=e.length),t||=0,r>0&&r<n&&(r=n),r===n||e.length===0||this.length===0)return 0;if(t<0)throw RangeError(`targetStart out of bounds`);if(n<0||n>=this.length)throw RangeError(`Index out of range`);if(r<0)throw RangeError(`sourceEnd out of bounds`);r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);let i=r-n;return this===e&&typeof Uint8Array.prototype.copyWithin==`function`?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),i},s.prototype.fill=function(e,t,n,r){if(typeof e==`string`){if(typeof t==`string`?(r=t,t=0,n=this.length):typeof n==`string`&&(r=n,n=this.length),r!==void 0&&typeof r!=`string`)throw TypeError(`encoding must be a string`);if(typeof r==`string`&&!s.isEncoding(r))throw TypeError(`Unknown encoding: `+r);if(e.length===1){let t=e.charCodeAt(0);(r===`utf8`&&t<128||r===`latin1`)&&(e=t)}}else typeof e==`number`?e&=255:typeof e==`boolean`&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw RangeError(`Out of range index`);if(n<=t)return this;t>>>=0,n=n===void 0?this.length:n>>>0,e||=0;let i;if(typeof e==`number`)for(i=t;i<n;++i)this[i]=e;else{let a=s.isBuffer(e)?e:s.from(e,r),o=a.length;if(o===0)throw TypeError(`The value "`+e+`" is invalid for argument "value"`);for(i=0;i<n-t;++i)this[i+t]=a[i%o]}return this};var R={};function z(e,t,n){R[e]=class extends n{constructor(){super(),Object.defineProperty(this,`message`,{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,`code`,{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}z(`ERR_BUFFER_OUT_OF_BOUNDS`,function(e){return e?`${e} is outside of buffer bounds`:`Attempt to access memory outside buffer bounds`},RangeError),z(`ERR_INVALID_ARG_TYPE`,function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),z(`ERR_OUT_OF_RANGE`,function(e,t,n){let r=`The value of "${e}" is out of range.`,i=n;return Number.isInteger(n)&&Math.abs(n)>2**32?i=oe(String(n)):typeof n==`bigint`&&(i=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(i=oe(i)),i+=`n`),r+=` It must be ${t}. Received ${i}`,r},RangeError);function oe(e){let t=``,n=e.length,r=+(e[0]===`-`);for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function se(e,t,n){le(t,`offset`),(e[t]===void 0||e[t+n]===void 0)&&ue(t,e.length-(n+1))}function ce(e,t,n,r,i,a){if(e>n||e<t){let r=typeof t==`bigint`?`n`:``,i;throw i=a>3?t===0||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${(a+1)*8}${r}`:`>= -(2${r} ** ${(a+1)*8-1}${r}) and < 2 ** ${(a+1)*8-1}${r}`:`>= ${t}${r} and <= ${n}${r}`,new R.ERR_OUT_OF_RANGE(`value`,i,e)}se(r,i,a)}function le(e,t){if(typeof e!=`number`)throw new R.ERR_INVALID_ARG_TYPE(t,`number`,e)}function ue(e,t,n){throw Math.floor(e)===e?t<0?new R.ERR_BUFFER_OUT_OF_BOUNDS:new R.ERR_OUT_OF_RANGE(n||`offset`,`>= ${+!!n} and <= ${t}`,e):(le(e,n),new R.ERR_OUT_OF_RANGE(n||`offset`,`an integer`,e))}var de=/[^+/0-9A-Za-z-_]/g;function fe(e){if(e=e.split(`=`)[0],e=e.trim().replace(de,``),e.length<2)return``;for(;e.length%4!=0;)e+=`=`;return e}function pe(e,t){t||=1/0;let n,r=e.length,i=null,a=[];for(let o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}else if(o+1===r){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if(--t<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,n&63|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,n&63|128)}else if(n<1114112){if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,n&63|128)}else throw Error(`Invalid code point`)}return a}function me(e){let t=[];for(let n=0;n<e.length;++n)t.push(e.charCodeAt(n)&255);return t}function B(e,t){let n,r,i,a=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,i=n%256,a.push(i),a.push(r);return a}function he(e){return t.toByteArray(fe(e))}function ge(e,t,n,r){let i;for(i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function _e(e,t){return e instanceof t||e!=null&&e.constructor!=null&&e.constructor.name!=null&&e.constructor.name===t.name}function ve(e){return e!==e}var ye=(function(){let e=`0123456789abcdef`,t=Array(256);for(let n=0;n<16;++n){let r=n*16;for(let i=0;i<16;++i)t[r+i]=e[n]+e[i]}return t})();function be(e){return typeof BigInt>`u`?xe:e}function xe(){throw Error(`BigInt not supported`)}})),xa=ba();globalThis.Buffer===void 0&&(globalThis.Buffer=xa.Buffer);var Sa=t(((e,t)=>{var n=function(e){if(e||={},this.Promise=e.Promise||Promise,this.queues=Object.create(null),this.domainReentrant=e.domainReentrant||!1,this.domainReentrant){if(typeof process>`u`||process.domain===void 0)throw Error("Domain-reentrant locks require `process.domain` to exist. Please flip `opts.domainReentrant = false`, use a NodeJS version that still implements Domain, or install a browser polyfill.");this.domains=Object.create(null)}this.timeout=e.timeout||n.DEFAULT_TIMEOUT,this.maxOccupationTime=e.maxOccupationTime||n.DEFAULT_MAX_OCCUPATION_TIME,this.maxExecutionTime=e.maxExecutionTime||n.DEFAULT_MAX_EXECUTION_TIME,e.maxPending===1/0||Number.isInteger(e.maxPending)&&e.maxPending>=0?this.maxPending=e.maxPending:this.maxPending=n.DEFAULT_MAX_PENDING};n.DEFAULT_TIMEOUT=0,n.DEFAULT_MAX_OCCUPATION_TIME=0,n.DEFAULT_MAX_EXECUTION_TIME=0,n.DEFAULT_MAX_PENDING=1e3,n.prototype.acquire=function(e,t,n,r){if(Array.isArray(e))return this._acquireBatch(e,t,n,r);if(typeof t!=`function`)throw Error(`You must pass a function to execute`);var i=null,a=null,o=null;typeof n!=`function`&&(r=n,n=null,o=new this.Promise(function(e,t){i=e,a=t})),r||={};var s=!1,c=null,l=null,u=null,d=this,f=function(t,r,c){l&&=(clearTimeout(l),null),u&&=(clearTimeout(u),null),t&&(d.queues[e]&&d.queues[e].length===0&&delete d.queues[e],d.domainReentrant&&delete d.domains[e]),s||=(o?r?a(r):i(c):typeof n==`function`&&n(r,c),!0),t&&d.queues[e]&&d.queues[e].length>0&&d.queues[e].shift()()},p=function(n){if(s)return f(n);c&&=(clearTimeout(c),null),d.domainReentrant&&n&&(d.domains[e]=process.domain);var i=r.maxExecutionTime||d.maxExecutionTime;if(i&&(u=setTimeout(function(){d.queues[e]&&f(n,Error(`Maximum execution time is exceeded `+e))},i)),t.length===1){var a=!1;try{t(function(e,t){a||(a=!0,f(n,e,t))})}catch(e){a||(a=!0,f(n,e))}}else d._promiseTry(function(){return t()}).then(function(e){f(n,void 0,e)},function(e){f(n,e)})};d.domainReentrant&&process.domain&&(p=process.domain.bind(p));var m=r.maxPending||d.maxPending;if(!d.queues[e])d.queues[e]=[],p(!0);else if(d.domainReentrant&&process.domain&&process.domain===d.domains[e])p(!1);else if(d.queues[e].length>=m)f(!1,Error(`Too many pending tasks in queue `+e));else{var h=function(){p(!0)};r.skipQueue?d.queues[e].unshift(h):d.queues[e].push(h);var g=r.timeout||d.timeout;g&&(c=setTimeout(function(){c=null,f(!1,Error(`async-lock timed out in queue `+e))},g))}var _=r.maxOccupationTime||d.maxOccupationTime;if(_&&(l=setTimeout(function(){d.queues[e]&&f(!1,Error(`Maximum occupation time is exceeded in queue `+e))},_)),o)return o},n.prototype._acquireBatch=function(e,t,n,r){typeof n!=`function`&&(r=n,n=null);var i=this,a=function(e,t){return function(n){i.acquire(e,t,n,r)}},o=e.reduceRight(function(e,t){return a(t,e)},t);if(typeof n==`function`)o(n);else return new this.Promise(function(e,t){o.length===1?o(function(n,r){n?t(n):e(r)}):e(o())})},n.prototype.isBusy=function(e){return e?!!this.queues[e]:Object.keys(this.queues).length>0},n.prototype._promiseTry=function(e){try{return this.Promise.resolve(e())}catch(e){return this.Promise.reject(e)}},t.exports=n})),Ca=t(((e,t)=>{t.exports=Sa()})),wa=t(((e,t)=>{typeof Object.create==`function`?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}})),Ta=t(((e,t)=>{var n=ba(),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=n:(i(n,e),e.Buffer=a);function a(e,t,n){return r(e,t,n)}a.prototype=Object.create(r.prototype),i(r,a),a.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return r(e,t,n)},a.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var i=r(e);return t===void 0?i.fill(0):typeof n==`string`?i.fill(t,n):i.fill(t),i},a.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r(e)},a.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return n.SlowBuffer(e)}})),Ea=t(((e,t)=>{var n={}.toString;t.exports=Array.isArray||function(e){return n.call(e)==`[object Array]`}})),Da=t(((e,t)=>{t.exports=TypeError})),Oa=t(((e,t)=>{t.exports=Object})),ka=t(((e,t)=>{t.exports=Error})),Aa=t(((e,t)=>{t.exports=EvalError})),ja=t(((e,t)=>{t.exports=RangeError})),Ma=t(((e,t)=>{t.exports=ReferenceError})),Na=t(((e,t)=>{t.exports=SyntaxError})),Pa=t(((e,t)=>{t.exports=URIError})),Fa=t(((e,t)=>{t.exports=Math.abs})),Ia=t(((e,t)=>{t.exports=Math.floor})),La=t(((e,t)=>{t.exports=Math.max})),Ra=t(((e,t)=>{t.exports=Math.min})),za=t(((e,t)=>{t.exports=Math.pow})),Ba=t(((e,t)=>{t.exports=Math.round})),Va=t(((e,t)=>{t.exports=Number.isNaN||function(e){return e!==e}})),Ha=t(((e,t)=>{var n=Va();t.exports=function(e){return n(e)||e===0?e:e<0?-1:1}})),Ua=t(((e,t)=>{t.exports=Object.getOwnPropertyDescriptor})),Wa=t(((e,t)=>{var n=Ua();if(n)try{n([],`length`)}catch{n=null}t.exports=n})),Ga=t(((e,t)=>{var n=Object.defineProperty||!1;if(n)try{n({},`a`,{value:1})}catch{n=!1}t.exports=n})),Ka=t(((e,t)=>{t.exports=function(){if(typeof Symbol!=`function`||typeof Object.getOwnPropertySymbols!=`function`)return!1;if(typeof Symbol.iterator==`symbol`)return!0;var e={},t=Symbol(`test`),n=Object(t);if(typeof t==`string`||Object.prototype.toString.call(t)!==`[object Symbol]`||Object.prototype.toString.call(n)!==`[object Symbol]`)return!1;var r=42;for(var i in e[t]=r,e)return!1;if(typeof Object.keys==`function`&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames==`function`&&Object.getOwnPropertyNames(e).length!==0)return!1;var a=Object.getOwnPropertySymbols(e);if(a.length!==1||a[0]!==t||!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if(typeof Object.getOwnPropertyDescriptor==`function`){var o=Object.getOwnPropertyDescriptor(e,t);if(o.value!==r||o.enumerable!==!0)return!1}return!0}})),qa=t(((e,t)=>{var n=typeof Symbol<`u`&&Symbol,r=Ka();t.exports=function(){return typeof n!=`function`||typeof Symbol!=`function`||typeof n(`foo`)!=`symbol`||typeof Symbol(`bar`)!=`symbol`?!1:r()}})),Ja=t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect.getPrototypeOf||null})),Ya=t(((e,t)=>{t.exports=Oa().getPrototypeOf||null})),Xa=t(((e,t)=>{var n=`Function.prototype.bind called on incompatible `,r=Object.prototype.toString,i=Math.max,a=`[object Function]`,o=function(e,t){for(var n=[],r=0;r<e.length;r+=1)n[r]=e[r];for(var i=0;i<t.length;i+=1)n[i+e.length]=t[i];return n},s=function(e,t){for(var n=[],r=t||0,i=0;r<e.length;r+=1,i+=1)n[i]=e[r];return n},c=function(e,t){for(var n=``,r=0;r<e.length;r+=1)n+=e[r],r+1<e.length&&(n+=t);return n};t.exports=function(e){var t=this;if(typeof t!=`function`||r.apply(t)!==a)throw TypeError(n+t);for(var l=s(arguments,1),u,d=function(){if(this instanceof u){var n=t.apply(this,o(l,arguments));return Object(n)===n?n:this}return t.apply(e,o(l,arguments))},f=i(0,t.length-l.length),p=[],m=0;m<f;m++)p[m]=`$`+m;if(u=Function(`binder`,`return function (`+c(p,`,`)+`){ return binder.apply(this,arguments); }`)(d),t.prototype){var h=function(){};h.prototype=t.prototype,u.prototype=new h,h.prototype=null}return u}})),Za=t(((e,t)=>{var n=Xa();t.exports=Function.prototype.bind||n})),Qa=t(((e,t)=>{t.exports=Function.prototype.call})),$a=t(((e,t)=>{t.exports=Function.prototype.apply})),eo=t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect&&Reflect.apply})),to=t(((e,t)=>{var n=Za(),r=$a(),i=Qa();t.exports=eo()||n.call(i,r)})),no=t(((e,t)=>{var n=Za(),r=Da(),i=Qa(),a=to();t.exports=function(e){if(e.length<1||typeof e[0]!=`function`)throw new r(`a function is required`);return a(n,i,e)}})),ro=t(((e,t)=>{var n=no(),r=Wa(),i;try{i=[].__proto__===Array.prototype}catch(e){if(!e||typeof e!=`object`||!(`code`in e)||e.code!==`ERR_PROTO_ACCESS`)throw e}var a=!!i&&r&&r(Object.prototype,`__proto__`),o=Object,s=o.getPrototypeOf;t.exports=a&&typeof a.get==`function`?n([a.get]):typeof s==`function`?function(e){return s(e==null?e:o(e))}:!1})),io=t(((e,t)=>{var n=Ja(),r=Ya(),i=ro();t.exports=n?function(e){return n(e)}:r?function(e){if(!e||typeof e!=`object`&&typeof e!=`function`)throw TypeError(`getProto: not an object`);return r(e)}:i?function(e){return i(e)}:null})),ao=t(((e,t)=>{var n=Function.prototype.call,r=Object.prototype.hasOwnProperty;t.exports=Za().call(n,r)})),oo=t(((e,t)=>{var n,r=Oa(),i=ka(),a=Aa(),o=ja(),s=Ma(),c=Na(),l=Da(),u=Pa(),d=Fa(),f=Ia(),p=La(),m=Ra(),h=za(),g=Ba(),_=Ha(),v=Function,y=function(e){try{return v(`"use strict"; return (`+e+`).constructor;`)()}catch{}},b=Wa(),x=Ga(),S=function(){throw new l},C=b?function(){try{return arguments.callee,S}catch{try{return b(arguments,`callee`).get}catch{return S}}}():S,w=qa()(),T=io(),E=Ya(),D=Ja(),O=$a(),k=Qa(),ee={},A=typeof Uint8Array>`u`||!T?n:T(Uint8Array),j={__proto__:null,"%AggregateError%":typeof AggregateError>`u`?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>`u`?n:ArrayBuffer,"%ArrayIteratorPrototype%":w&&T?T([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":ee,"%AsyncGenerator%":ee,"%AsyncGeneratorFunction%":ee,"%AsyncIteratorPrototype%":ee,"%Atomics%":typeof Atomics>`u`?n:Atomics,"%BigInt%":typeof BigInt>`u`?n:BigInt,"%BigInt64Array%":typeof BigInt64Array>`u`?n:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>`u`?n:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>`u`?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":i,"%eval%":eval,"%EvalError%":a,"%Float16Array%":typeof Float16Array>`u`?n:Float16Array,"%Float32Array%":typeof Float32Array>`u`?n:Float32Array,"%Float64Array%":typeof Float64Array>`u`?n:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>`u`?n:FinalizationRegistry,"%Function%":v,"%GeneratorFunction%":ee,"%Int8Array%":typeof Int8Array>`u`?n:Int8Array,"%Int16Array%":typeof Int16Array>`u`?n:Int16Array,"%Int32Array%":typeof Int32Array>`u`?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":w&&T?T(T([][Symbol.iterator]())):n,"%JSON%":typeof JSON==`object`?JSON:n,"%Map%":typeof Map>`u`?n:Map,"%MapIteratorPrototype%":typeof Map>`u`||!w||!T?n:T(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":r,"%Object.getOwnPropertyDescriptor%":b,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>`u`?n:Promise,"%Proxy%":typeof Proxy>`u`?n:Proxy,"%RangeError%":o,"%ReferenceError%":s,"%Reflect%":typeof Reflect>`u`?n:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>`u`?n:Set,"%SetIteratorPrototype%":typeof Set>`u`||!w||!T?n:T(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>`u`?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":w&&T?T(``[Symbol.iterator]()):n,"%Symbol%":w?Symbol:n,"%SyntaxError%":c,"%ThrowTypeError%":C,"%TypedArray%":A,"%TypeError%":l,"%Uint8Array%":typeof Uint8Array>`u`?n:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>`u`?n:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>`u`?n:Uint16Array,"%Uint32Array%":typeof Uint32Array>`u`?n:Uint32Array,"%URIError%":u,"%WeakMap%":typeof WeakMap>`u`?n:WeakMap,"%WeakRef%":typeof WeakRef>`u`?n:WeakRef,"%WeakSet%":typeof WeakSet>`u`?n:WeakSet,"%Function.prototype.call%":k,"%Function.prototype.apply%":O,"%Object.defineProperty%":x,"%Object.getPrototypeOf%":E,"%Math.abs%":d,"%Math.floor%":f,"%Math.max%":p,"%Math.min%":m,"%Math.pow%":h,"%Math.round%":g,"%Math.sign%":_,"%Reflect.getPrototypeOf%":D};if(T)try{null.error}catch(e){j[`%Error.prototype%`]=T(T(e))}var te=function e(t){var n;if(t===`%AsyncFunction%`)n=y(`async function () {}`);else if(t===`%GeneratorFunction%`)n=y(`function* () {}`);else if(t===`%AsyncGeneratorFunction%`)n=y(`async function* () {}`);else if(t===`%AsyncGenerator%`){var r=e(`%AsyncGeneratorFunction%`);r&&(n=r.prototype)}else if(t===`%AsyncIteratorPrototype%`){var i=e(`%AsyncGenerator%`);i&&T&&(n=T(i.prototype))}return j[t]=n,n},ne={__proto__:null,"%ArrayBufferPrototype%":[`ArrayBuffer`,`prototype`],"%ArrayPrototype%":[`Array`,`prototype`],"%ArrayProto_entries%":[`Array`,`prototype`,`entries`],"%ArrayProto_forEach%":[`Array`,`prototype`,`forEach`],"%ArrayProto_keys%":[`Array`,`prototype`,`keys`],"%ArrayProto_values%":[`Array`,`prototype`,`values`],"%AsyncFunctionPrototype%":[`AsyncFunction`,`prototype`],"%AsyncGenerator%":[`AsyncGeneratorFunction`,`prototype`],"%AsyncGeneratorPrototype%":[`AsyncGeneratorFunction`,`prototype`,`prototype`],"%BooleanPrototype%":[`Boolean`,`prototype`],"%DataViewPrototype%":[`DataView`,`prototype`],"%DatePrototype%":[`Date`,`prototype`],"%ErrorPrototype%":[`Error`,`prototype`],"%EvalErrorPrototype%":[`EvalError`,`prototype`],"%Float32ArrayPrototype%":[`Float32Array`,`prototype`],"%Float64ArrayPrototype%":[`Float64Array`,`prototype`],"%FunctionPrototype%":[`Function`,`prototype`],"%Generator%":[`GeneratorFunction`,`prototype`],"%GeneratorPrototype%":[`GeneratorFunction`,`prototype`,`prototype`],"%Int8ArrayPrototype%":[`Int8Array`,`prototype`],"%Int16ArrayPrototype%":[`Int16Array`,`prototype`],"%Int32ArrayPrototype%":[`Int32Array`,`prototype`],"%JSONParse%":[`JSON`,`parse`],"%JSONStringify%":[`JSON`,`stringify`],"%MapPrototype%":[`Map`,`prototype`],"%NumberPrototype%":[`Number`,`prototype`],"%ObjectPrototype%":[`Object`,`prototype`],"%ObjProto_toString%":[`Object`,`prototype`,`toString`],"%ObjProto_valueOf%":[`Object`,`prototype`,`valueOf`],"%PromisePrototype%":[`Promise`,`prototype`],"%PromiseProto_then%":[`Promise`,`prototype`,`then`],"%Promise_all%":[`Promise`,`all`],"%Promise_reject%":[`Promise`,`reject`],"%Promise_resolve%":[`Promise`,`resolve`],"%RangeErrorPrototype%":[`RangeError`,`prototype`],"%ReferenceErrorPrototype%":[`ReferenceError`,`prototype`],"%RegExpPrototype%":[`RegExp`,`prototype`],"%SetPrototype%":[`Set`,`prototype`],"%SharedArrayBufferPrototype%":[`SharedArrayBuffer`,`prototype`],"%StringPrototype%":[`String`,`prototype`],"%SymbolPrototype%":[`Symbol`,`prototype`],"%SyntaxErrorPrototype%":[`SyntaxError`,`prototype`],"%TypedArrayPrototype%":[`TypedArray`,`prototype`],"%TypeErrorPrototype%":[`TypeError`,`prototype`],"%Uint8ArrayPrototype%":[`Uint8Array`,`prototype`],"%Uint8ClampedArrayPrototype%":[`Uint8ClampedArray`,`prototype`],"%Uint16ArrayPrototype%":[`Uint16Array`,`prototype`],"%Uint32ArrayPrototype%":[`Uint32Array`,`prototype`],"%URIErrorPrototype%":[`URIError`,`prototype`],"%WeakMapPrototype%":[`WeakMap`,`prototype`],"%WeakSetPrototype%":[`WeakSet`,`prototype`]},re=Za(),ie=ao(),M=re.call(k,Array.prototype.concat),N=re.call(O,Array.prototype.splice),P=re.call(k,String.prototype.replace),ae=re.call(k,String.prototype.slice),F=re.call(k,RegExp.prototype.exec),I=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,L=/\\(\\)?/g,R=function(e){var t=ae(e,0,1),n=ae(e,-1);if(t===`%`&&n!==`%`)throw new c("invalid intrinsic syntax, expected closing `%`");if(n===`%`&&t!==`%`)throw new c("invalid intrinsic syntax, expected opening `%`");var r=[];return P(e,I,function(e,t,n,i){r[r.length]=n?P(i,L,`$1`):t||e}),r},z=function(e,t){var n=e,r;if(ie(ne,n)&&(r=ne[n],n=`%`+r[0]+`%`),ie(j,n)){var i=j[n];if(i===ee&&(i=te(n)),i===void 0&&!t)throw new l(`intrinsic `+e+` exists, but is not available. Please file an issue!`);return{alias:r,name:n,value:i}}throw new c(`intrinsic `+e+` does not exist!`)};t.exports=function(e,t){if(typeof e!=`string`||e.length===0)throw new l(`intrinsic name must be a non-empty string`);if(arguments.length>1&&typeof t!=`boolean`)throw new l(`"allowMissing" argument must be a boolean`);if(F(/^%?[^%]*%?$/,e)===null)throw new c("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=R(e),r=n.length>0?n[0]:``,i=z(`%`+r+`%`,t),a=i.name,o=i.value,s=!1,u=i.alias;u&&(r=u[0],N(n,M([0,1],u)));for(var d=1,f=!0;d<n.length;d+=1){var p=n[d],m=ae(p,0,1),h=ae(p,-1);if((m===`"`||m===`'`||m==="`"||h===`"`||h===`'`||h==="`")&&m!==h)throw new c(`property names with quotes must have matching quotes`);if((p===`constructor`||!f)&&(s=!0),r+=`.`+p,a=`%`+r+`%`,ie(j,a))o=j[a];else if(o!=null){if(!(p in o)){if(!t)throw new l(`base intrinsic for `+e+` exists, but the property is not available.`);return}if(b&&d+1>=n.length){var g=b(o,p);f=!!g,o=f&&`get`in g&&!(`originalValue`in g.get)?g.get:o[p]}else f=ie(o,p),o=o[p];f&&!s&&(j[a]=o)}}return o}})),so=t(((e,t)=>{var n=oo(),r=no(),i=r([n(`%String.prototype.indexOf%`)]);t.exports=function(e,t){var a=n(e,!!t);return typeof a==`function`&&i(e,`.prototype.`)>-1?r([a]):a}})),co=t(((e,t)=>{var n=Function.prototype.toString,r=typeof Reflect==`object`&&Reflect!==null&&Reflect.apply,i,a;if(typeof r==`function`&&typeof Object.defineProperty==`function`)try{i=Object.defineProperty({},`length`,{get:function(){throw a}}),a={},r(function(){throw 42},null,i)}catch(e){e!==a&&(r=null)}else r=null;var o=/^\s*class\b/,s=function(e){try{var t=n.call(e);return o.test(t)}catch{return!1}},c=function(e){try{return s(e)?!1:(n.call(e),!0)}catch{return!1}},l=Object.prototype.toString,u=`[object Object]`,d=`[object Function]`,f=`[object GeneratorFunction]`,p=`[object HTMLAllCollection]`,m=`[object HTML document.all class]`,h=`[object HTMLCollection]`,g=typeof Symbol==`function`&&!!Symbol.toStringTag,_=!(0 in[,]),v=function(){return!1};if(typeof document==`object`){var y=document.all;l.call(y)===l.call(document.all)&&(v=function(e){if((_||!e)&&(e===void 0||typeof e==`object`))try{var t=l.call(e);return(t===p||t===m||t===h||t===u)&&e(``)==null}catch{}return!1})}t.exports=r?function(e){if(v(e))return!0;if(!e||typeof e!=`function`&&typeof e!=`object`)return!1;try{r(e,null,i)}catch(e){if(e!==a)return!1}return!s(e)&&c(e)}:function(e){if(v(e))return!0;if(!e||typeof e!=`function`&&typeof e!=`object`)return!1;if(g)return c(e);if(s(e))return!1;var t=l.call(e);return t!==d&&t!==f&&!/^\[object HTML/.test(t)?!1:c(e)}})),lo=t(((e,t)=>{var n=co(),r=Object.prototype.toString,i=Object.prototype.hasOwnProperty,a=function(e,t,n){for(var r=0,a=e.length;r<a;r++)i.call(e,r)&&(n==null?t(e[r],r,e):t.call(n,e[r],r,e))},o=function(e,t,n){for(var r=0,i=e.length;r<i;r++)n==null?t(e.charAt(r),r,e):t.call(n,e.charAt(r),r,e)},s=function(e,t,n){for(var r in e)i.call(e,r)&&(n==null?t(e[r],r,e):t.call(n,e[r],r,e))};function c(e){return r.call(e)===`[object Array]`}t.exports=function(e,t,r){if(!n(t))throw TypeError(`iterator must be a function`);var i;arguments.length>=3&&(i=r),c(e)?a(e,t,i):typeof e==`string`?o(e,t,i):s(e,t,i)}})),uo=t(((e,t)=>{t.exports=[`Float16Array`,`Float32Array`,`Float64Array`,`Int8Array`,`Int16Array`,`Int32Array`,`Uint8Array`,`Uint8ClampedArray`,`Uint16Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`]})),fo=t(((e,t)=>{var n=uo(),r=globalThis;t.exports=function(){for(var e=[],t=0;t<n.length;t++)typeof r[n[t]]==`function`&&(e[e.length]=n[t]);return e}})),po=t(((e,t)=>{var n=Ga(),r=Na(),i=Da(),a=Wa();t.exports=function(e,t,o){if(!e||typeof e!=`object`&&typeof e!=`function`)throw new i("`obj` must be an object or a function`");if(typeof t!=`string`&&typeof t!=`symbol`)throw new i("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!=`boolean`&&arguments[3]!==null)throw new i("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!=`boolean`&&arguments[4]!==null)throw new i("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!=`boolean`&&arguments[5]!==null)throw new i("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!=`boolean`)throw new i("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,d=!!a&&a(e,t);if(n)n(e,t,{configurable:l===null&&d?d.configurable:!l,enumerable:s===null&&d?d.enumerable:!s,value:o,writable:c===null&&d?d.writable:!c});else if(u||!s&&!c&&!l)e[t]=o;else throw new r(`This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.`)}})),mo=t(((e,t)=>{var n=Ga(),r=function(){return!!n};r.hasArrayLengthDefineBug=function(){if(!n)return null;try{return n([],`length`,{value:1}).length!==1}catch{return!0}},t.exports=r})),ho=t(((e,t)=>{var n=oo(),r=po(),i=mo()(),a=Wa(),o=Da(),s=n(`%Math.floor%`);t.exports=function(e,t){if(typeof e!=`function`)throw new o("`fn` is not a function");if(typeof t!=`number`||t<0||t>4294967295||s(t)!==t)throw new o("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],c=!0,l=!0;if(`length`in e&&a){var u=a(e,`length`);u&&!u.configurable&&(c=!1),u&&!u.writable&&(l=!1)}return(c||l||!n)&&(i?r(e,`length`,t,!0,!0):r(e,`length`,t)),e}})),go=t(((e,t)=>{var n=Za(),r=$a(),i=to();t.exports=function(){return i(n,r,arguments)}})),_o=t(((e,t)=>{var n=ho(),r=Ga(),i=no(),a=go();t.exports=function(e){var t=i(arguments),r=e.length-(arguments.length-1);return n(t,1+(r>0?r:0),!0)},r?r(t.exports,`apply`,{value:a}):t.exports.apply=a})),vo=t(((e,t)=>{var n=Ka();t.exports=function(){return n()&&!!Symbol.toStringTag}})),yo=t(((e,t)=>{var n=lo(),r=fo(),i=_o(),a=so(),o=Wa(),s=io(),c=a(`Object.prototype.toString`),l=vo()(),u=globalThis,d=r(),f=a(`String.prototype.slice`),p=a(`Array.prototype.indexOf`,!0)||function(e,t){for(var n=0;n<e.length;n+=1)if(e[n]===t)return n;return-1},m={__proto__:null};l&&o&&s?n(d,function(e){var t=new u[e];if(Symbol.toStringTag in t&&s){var n=s(t),r=o(n,Symbol.toStringTag);if(!r&&n&&(r=o(s(n),Symbol.toStringTag)),r&&r.get){var a=i(r.get);m[`$`+e]=a}}}):n(d,function(e){var t=new u[e],n=t.slice||t.set;if(n){var r=i(n);m[`$`+e]=r}});var h=function(e){var t=!1;return n(m,function(n,r){if(!t)try{`$`+n(e)===r&&(t=f(r,1))}catch{}}),t},g=function(e){var t=!1;return n(m,function(n,r){if(!t)try{n(e),t=f(r,1)}catch{}}),t};t.exports=function(e){if(!e||typeof e!=`object`)return!1;if(!l){var t=f(c(e),8,-1);return p(d,t)>-1?t:t===`Object`?g(e):!1}return o?h(e):null}})),bo=t(((e,t)=>{var n=yo();t.exports=function(e){return!!n(e)}})),xo=t(((e,t)=>{var n=Da(),r=so()(`TypedArray.prototype.buffer`,!0),i=bo();t.exports=r||function(e){if(!i(e))throw new n(`Not a Typed Array`);return e.buffer}})),So=t(((e,t)=>{var n=Ta().Buffer,r=Ea(),i=xo(),a=ArrayBuffer.isView||function(e){try{return i(e),!0}catch{return!1}},o=typeof Uint8Array<`u`,s=typeof ArrayBuffer<`u`&&typeof Uint8Array<`u`,c=s&&(n.prototype instanceof Uint8Array||n.TYPED_ARRAY_SUPPORT);t.exports=function(e,t){if(n.isBuffer(e))return e.constructor&&!(`isBuffer`in e)?n.from(e):e;if(typeof e==`string`)return n.from(e,t);if(s&&a(e)){if(e.byteLength===0)return n.alloc(0);if(c){var i=n.from(e.buffer,e.byteOffset,e.byteLength);if(i.byteLength===e.byteLength)return i}var l=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),u=n.from(l);if(u.length===e.byteLength)return u}if(o&&e instanceof Uint8Array)return n.from(e);var d=r(e);if(d)for(var f=0;f<e.length;f+=1){var p=e[f];if(typeof p!=`number`||p<0||p>255||~~p!==p)throw RangeError(`Array items must be numbers in the range 0-255.`)}if(d||n.isBuffer(e)&&e.constructor&&typeof e.constructor.isBuffer==`function`&&e.constructor.isBuffer(e))return n.from(e);throw TypeError(`The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.`)}})),Co=t(((e,t)=>{var n=Ta().Buffer,r=So();function i(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}i.prototype.update=function(e,t){e=r(e,t||`utf8`);for(var n=this._block,i=this._blockSize,a=e.length,o=this._len,s=0;s<a;){for(var c=o%i,l=Math.min(a-s,i-c),u=0;u<l;u++)n[c+u]=e[s+u];o+=l,s+=l,o%i===0&&this._update(n)}return this._len+=a,this},i.prototype.digest=function(e){var t=this._len%this._blockSize;this._block[t]=128,this._block.fill(0,t+1),t>=this._finalSize&&(this._update(this._block),this._block.fill(0));var n=this._len*8;if(n<=4294967295)this._block.writeUInt32BE(n,this._blockSize-4);else{var r=(n&4294967295)>>>0,i=(n-r)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(r,this._blockSize-4)}this._update(this._block);var a=this._hash();return e?a.toString(e):a},i.prototype._update=function(){throw Error(`_update must be implemented by subclass`)},t.exports=i})),wo=t(((e,t)=>{var n=wa(),r=Co(),i=Ta().Buffer,a=[1518500249,1859775393,-1894007588,-899497514],o=Array(80);function s(){this.init(),this._w=o,r.call(this,64,56)}n(s,r),s.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function c(e){return e<<1|e>>>31}function l(e){return e<<5|e>>>27}function u(e){return e<<30|e>>>2}function d(e,t,n,r){return e===0?t&n|~t&r:e===2?t&n|t&r|n&r:t^n^r}s.prototype._update=function(e){for(var t=this._w,n=this._a|0,r=this._b|0,i=this._c|0,o=this._d|0,s=this._e|0,f=0;f<16;++f)t[f]=e.readInt32BE(f*4);for(;f<80;++f)t[f]=c(t[f-3]^t[f-8]^t[f-14]^t[f-16]);for(var p=0;p<80;++p){var m=~~(p/20),h=l(n)+d(m,r,i,o)+s+t[p]+a[m]|0;s=o,o=i,i=u(r),r=n,n=h}this._a=n+this._a|0,this._b=r+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0},s.prototype._hash=function(){var e=i.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e},t.exports=s})),To=t((e=>{(function(t){typeof DO_NOT_EXPORT_CRC>`u`?typeof e==`object`?t(e):typeof define==`function`&&define.amd?define(function(){var e={};return t(e),e}):t({}):t({})})(function(e){e.version=`1.2.2`;function t(){for(var e=0,t=Array(256),n=0;n!=256;++n)e=n,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,t[n]=e;return typeof Int32Array<`u`?new Int32Array(t):t}var n=t();function r(e){var t=0,n=0,r=0,i=typeof Int32Array<`u`?new Int32Array(4096):Array(4096);for(r=0;r!=256;++r)i[r]=e[r];for(r=0;r!=256;++r)for(n=e[r],t=256+r;t<4096;t+=256)n=i[t]=n>>>8^e[n&255];var a=[];for(r=1;r!=16;++r)a[r-1]=typeof Int32Array<`u`?i.subarray(r*256,r*256+256):i.slice(r*256,r*256+256);return a}var i=r(n),a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14];function b(e,t){for(var r=t^-1,i=0,a=e.length;i<a;)r=r>>>8^n[(r^e.charCodeAt(i++))&255];return~r}function x(e,t){for(var r=t^-1,i=e.length-15,b=0;b<i;)r=y[e[b++]^r&255]^v[e[b++]^r>>8&255]^_[e[b++]^r>>16&255]^g[e[b++]^r>>>24]^h[e[b++]]^m[e[b++]]^p[e[b++]]^f[e[b++]]^d[e[b++]]^u[e[b++]]^l[e[b++]]^c[e[b++]]^s[e[b++]]^o[e[b++]]^a[e[b++]]^n[e[b++]];for(i+=15;b<i;)r=r>>>8^n[(r^e[b++])&255];return~r}function S(e,t){for(var r=t^-1,i=0,a=e.length,o=0,s=0;i<a;)o=e.charCodeAt(i++),o<128?r=r>>>8^n[(r^o)&255]:o<2048?(r=r>>>8^n[(r^(192|o>>6&31))&255],r=r>>>8^n[(r^(128|o&63))&255]):o>=55296&&o<57344?(o=(o&1023)+64,s=e.charCodeAt(i++)&1023,r=r>>>8^n[(r^(240|o>>8&7))&255],r=r>>>8^n[(r^(128|o>>2&63))&255],r=r>>>8^n[(r^(128|s>>6&15|(o&3)<<4))&255],r=r>>>8^n[(r^(128|s&63))&255]):(r=r>>>8^n[(r^(224|o>>12&15))&255],r=r>>>8^n[(r^(128|o>>6&63))&255],r=r>>>8^n[(r^(128|o&63))&255]);return~r}e.table=n,e.bstr=b,e.buf=x,e.str=S})})),Eo=t(((e,t)=>{var n=(e,t)=>function(...n){let r=t.promiseModule;return new r((r,i)=>{t.multiArgs?n.push((...e)=>{t.errorFirst?e[0]?i(e):(e.shift(),r(e)):r(e)}):t.errorFirst?n.push((e,t)=>{e?i(e):r(t)}):n.push(r),e.apply(this,n)})};t.exports=(e,t)=>{t=Object.assign({exclude:[/.+(Sync|Stream)$/],errorFirst:!0,promiseModule:Promise},t);let r=typeof e;if(!(e!==null&&(r===`object`||r===`function`)))throw TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${e===null?`null`:r}\``);let i=e=>{let n=t=>typeof t==`string`?e===t:t.test(e);return t.include?t.include.some(n):!t.exclude.some(n)},a;a=r===`function`?function(...r){return t.excludeMain?e(...r):n(e,t).apply(this,r)}:Object.create(Object.getPrototypeOf(e));for(let r in e){let o=e[r];a[r]=typeof o==`function`&&i(r)?n(o,t):o}return a}})),Do=t(((e,t)=>{function n(e){return Array.isArray(e)?e:[e]}var r=``,i=` `,a=`\\`,o=/^\s+$/,s=/(?:[^\\]|^)\\$/,c=/^\\!/,l=/^\\#/,u=/\r?\n/g,d=/^\.*\/|^\.+$/,f=`/`,p=`node-ignore`;typeof Symbol<`u`&&(p=Symbol.for(`node-ignore`));var m=p,h=(e,t,n)=>Object.defineProperty(e,t,{value:n}),g=/([0-z])-([0-z])/g,_=()=>!1,v=e=>e.replace(g,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:r),y=e=>{let{length:t}=e;return e.slice(0,t-t%2)},b=[[/^\uFEFF/,()=>r],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf(`\\`)===0?i:r)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+i}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>t+n.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>a],[/\\\\/g,()=>a],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,i)=>t===a?`\\[${n}${y(r)}${i}`:i===`]`&&r.length%2==0?`[${v(n)}${r}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`]],x=Object.create(null),S=(e,t)=>{let n=x[e];return n||(n=b.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),x[e]=n),t?new RegExp(n,`i`):new RegExp(n)},C=e=>typeof e==`string`,w=e=>e&&C(e)&&!o.test(e)&&!s.test(e)&&e.indexOf(`#`)!==0,T=e=>e.split(u),E=class{constructor(e,t,n,r){this.origin=e,this.pattern=t,this.negative=n,this.regex=r}},D=(e,t)=>{let n=e,r=!1;e.indexOf(`!`)===0&&(r=!0,e=e.substr(1)),e=e.replace(c,`!`).replace(l,`#`);let i=S(e,t);return new E(n,e,r,i)},O=(e,t)=>{throw new t(e)},k=(e,t,n)=>C(e)?e?k.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n(`path must not be empty`,TypeError):n(`path must be a string, but got \`${t}\``,TypeError),ee=e=>d.test(e);k.isNotRelative=ee,k.convert=e=>e;var A=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){h(this,m,!0),this._rules=[],this._ignoreCase=t,this._allowRelativePaths=n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[m]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(w(e)){let t=D(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,n(C(e)?T(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,t){let n=!1,r=!1;return this._rules.forEach(i=>{let{negative:a}=i;r===a&&n!==r||a&&!n&&!r&&!t||i.regex.test(e)&&(n=!a,r=a)}),{ignored:n,unignored:r}}_test(e,t,n,r){let i=e&&k.convert(e);return k(i,e,this._allowRelativePaths?_:O),this._t(i,t,n,r)}_t(e,t,n,r){if(e in t)return t[e];if(r||=e.split(f),r.pop(),!r.length)return t[e]=this._testOne(e,n);let i=this._t(r.join(f)+f,t,n,r);return t[e]=i.ignored?i:this._testOne(e,n)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return n(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},j=e=>new A(e);if(j.isPathValid=e=>k(e&&k.convert(e),e,_),j.default=j,t.exports=j,typeof process<`u`&&({}.IGNORE_TEST_WIN32||process.platform===`win32`)){k.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;k.isNotRelative=t=>e.test(t)||ee(t)}})),Oo=t(((e,t)=>{function n(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function r(e,t,r){return t=t instanceof RegExp?t:new RegExp(n(t),`g`),e.replace(t,r)}t.exports={clean:function(e){if(typeof e!=`string`)throw Error(`Expected a string, received: `+e);return e=r(e,`./`,`/`),e=r(e,`..`,`.`),e=r(e,` `,`-`),e=r(e,/^[~^:?*\\\-]/g,``),e=r(e,/[~^:?*\\]/g,`-`),e=r(e,/[~^:?*\\\-]$/g,``),e=r(e,`@{`,`-`),e=r(e,/\.$/g,``),e=r(e,/\/$/g,``),e=r(e,/\.lock$/g,``),e}}})),ko=t(((e,t)=>{t.exports=function(e,t){var n=e,r=t,i=n.length,a=r.length,o=!1,s=null,c=i+1,l=[],u=[],d=[],f=``,p=-1,m=0,h=1,g,_,v=function(){i>=a&&(g=n,_=i,n=r,r=g,i=a,a=_,o=!0,c=i+1)},y=function(e,t,n){return{x:e,y:t,k:n}},b=function(e,t){return{elem:e,t}},x=function(e,t,o){var s=t>o?l[e-1+c]:l[e+1+c],d,f=Math.max(t,o);for(d=f-e;d<i&&f<a&&n[d]===r[f];)++d,++f;return l[e+c]=u.length,u[u.length]=new y(d,f,s),f},S=function(e){var t=i=1,i,a=s=0,s,c;for(c=e.length-1;c>=0;--c)for(;a<e[c].x||s<e[c].y;)e[c].y-e[c].x>s-a?(o?d[d.length]=new b(r[s],p):d[d.length]=new b(r[s],h),++i,++s):e[c].y-e[c].x<s-a?(o?d[d.length]=new b(n[a],h):d[d.length]=new b(n[a],p),++t,++a):(d[d.length]=new b(n[a],m),f+=n[a],++t,++i,++a,++s)};return v(),{SES_DELETE:-1,SES_COMMON:0,SES_ADD:1,editdistance:function(){return s},getlcs:function(){return f},getses:function(){return d},compose:function(){var e=a-i,t=i+a+3,n={},r,o,d,f,p;for(f=0;f<t;++f)n[f]=-1,l[f]=-1;r=-1;do{for(++r,p=-r;p<=e-1;++p)n[p+c]=x(p,n[p-1+c]+1,n[p+1+c]);for(p=e+r;p>=e+1;--p)n[p+c]=x(p,n[p-1+c]+1,n[p+1+c]);n[e+c]=x(e,n[e-1+c]+1,n[e+1+c])}while(n[e+c]!==a);for(s=e+2*r,o=l[e+c],d=[];o!==-1;)d[d.length]=new y(u[o].x,u[o].y,null),o=u[o].k;S(d)}}}})),Ao=t(((e,t)=>{var n=ko();function r(e,t){var r=new n(e,t);r.compose();for(var i=r.getses(),a,o,s=e.length-1,c=t.length-1,l=i.length-1;l>=0;--l)i[l].t===r.SES_COMMON?(o?(o.chain={file1index:s,file2index:c,chain:null},o=o.chain):(a={file1index:s,file2index:c,chain:null},o=a),s--,c--):i[l].t===r.SES_DELETE?s--:i[l].t===r.SES_ADD&&c--;var u={file1index:-1,file2index:-1,chain:null};return o?(o.chain=u,a):u}function i(e,t){for(var n=[],i=e.length,a=t.length,o=r(e,t);o!==null;o=o.chain){var s=i-o.file1index-1,c=a-o.file2index-1;i=o.file1index,a=o.file2index,(s||c)&&n.push({file1:[i+1,s],file2:[a+1,c]})}return n.reverse(),n}function a(e,t,n){var r,a=i(t,e),o=i(t,n),s=[];function c(e,t){s.push([e.file1[0],t,e.file1[1],e.file2[0],e.file2[1]])}for(r=0;r<a.length;r++)c(a[r],0);for(r=0;r<o.length;r++)c(o[r],2);s.sort(function(e,t){return e[0]-t[0]});var l=[],u=0;function d(e){e>u&&(l.push([1,u,e-u]),u=e)}for(var f=0;f<s.length;f++){for(var p=f,m=s[f],h=m[0],g=h+m[2];f<s.length-1;){var _=s[f+1],v=_[0];if(v>g)break;g=Math.max(g,v+_[2]),f++}if(d(h),p==f)m[4]>0&&l.push([m[1],m[3],m[4]]);else{var y={0:[e.length,-1,t.length,-1],2:[n.length,-1,t.length,-1]};for(r=p;r<=f;r++){m=s[r];var b=y[m[1]],x=m[0],S=x+m[2],C=m[3],w=C+m[4];b[0]=Math.min(C,b[0]),b[1]=Math.max(w,b[1]),b[2]=Math.min(x,b[2]),b[3]=Math.max(S,b[3])}var T=y[0][0]+(h-y[0][2]),E=y[0][1]+(g-y[0][3]),D=y[2][0]+(h-y[2][2]),O=y[2][1]+(g-y[2][3]);l.push([-1,T,E-T,h,g-h,D,O-D])}u=g}return d(t.length),l}function o(e,t,n){var r=[],i=[e,t,n],o=a(e,t,n),s=[];function c(){s.length&&r.push({ok:s}),s=[]}function l(e){for(var t=0;t<e.length;t++)s.push(e[t])}function u(t){if(t[2]!=t[6])return!0;for(var r=t[1],i=t[5],a=0;a<t[2];a++)if(e[a+r]!=n[a+i])return!0;return!1}for(var d=0;d<o.length;d++){var f=o[d],p=f[0];p==-1?u(f)?(c(),r.push({conflict:{a:e.slice(f[1],f[1]+f[2]),aIndex:f[1],o:t.slice(f[3],f[3]+f[4]),oIndex:f[3],b:n.slice(f[5],f[5]+f[6]),bIndex:f[5]}})):l(i[0].slice(f[1],f[1]+f[2])):l(i[p].slice(f[1],f[1]+f[2]))}return c(),r}t.exports=o})),Y=e(t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e){return e&&typeof e==`object`&&`default`in e?e.default:e}var n=t(Ca()),r=t(wo()),i=t(To()),a=t(Ue()),o=We(),s=t(Eo()),c=t(Do()),l=t(Oo()),u=t(Ao()),d=class e extends Error{constructor(e){super(e),this.caller=``}toJSON(){return{code:this.code,data:this.data,caller:this.caller,message:this.message,stack:this.stack}}fromJSON(t){let n=new e(t.message);return n.code=t.code,n.data=t.data,n.caller=t.caller,n.stack=t.stack,n}get isIsomorphicGitError(){return!0}},f=class e extends d{constructor(t){super(`Modifying the index is not possible because you have unmerged files: ${t.toString}. Fix them up in the work tree, and then use 'git add/rm as appropriate to mark resolution and make a commit.`),this.code=this.name=e.code,this.data={filepaths:t}}};f.code=`UnmergedPathsError`;var p=class e extends d{constructor(t){super(`An internal error caused this command to fail.\n\nIf you're not a developer, report the bug to the developers of the application you're using. If this is a bug in isomorphic-git then you should create a proper bug yourselves. The bug should include a minimal reproduction and details about the version and environment.\n\nPlease file a bug report at https://github.com/isomorphic-git/isomorphic-git/issues with this error message: ${t}`),this.code=this.name=e.code,this.data={message:t}}};p.code=`InternalError`;var m=class e extends d{constructor(t){super(`The filepath "${t}" contains unsafe character sequences`),this.code=this.name=e.code,this.data={filepath:t}}};m.code=`UnsafeFilepathError`;var h=class{constructor(e){this.buffer=e,this._start=0}eof(){return this._start>=this.buffer.length}tell(){return this._start}seek(e){this._start=e}slice(e){let t=this.buffer.slice(this._start,this._start+e);return this._start+=e,t}toString(e,t){let n=this.buffer.toString(e,this._start,this._start+t);return this._start+=t,n}write(e,t,n){let r=this.buffer.write(e,this._start,t,n);return this._start+=t,r}copy(e,t,n){let r=e.copy(this.buffer,this._start,t,n);return this._start+=r,r}readUInt8(){let e=this.buffer.readUInt8(this._start);return this._start+=1,e}writeUInt8(e){let t=this.buffer.writeUInt8(e,this._start);return this._start+=1,t}readUInt16BE(){let e=this.buffer.readUInt16BE(this._start);return this._start+=2,e}writeUInt16BE(e){let t=this.buffer.writeUInt16BE(e,this._start);return this._start+=2,t}readUInt32BE(){let e=this.buffer.readUInt32BE(this._start);return this._start+=4,e}writeUInt32BE(e){let t=this.buffer.writeUInt32BE(e,this._start);return this._start+=4,t}};function g(e,t){return-(e<t)||+(e>t)}function _(e,t){return g(e.path,t.path)}function v(e){let t=e>0?e>>12:0;t!==4&&t!==8&&t!==10&&t!==14&&(t=8);let n=e&511;return n=n&73?493:420,t!==8&&(n=0),(t<<12)+n}var y=2**32;function b(e,t,n,r){if(e!==void 0&&t!==void 0)return[e,t];n===void 0&&(n=r.valueOf());let i=Math.floor(n/1e3);return[i,(n-i*1e3)*1e6]}function x(e){let[t,n]=b(e.ctimeSeconds,e.ctimeNanoseconds,e.ctimeMs,e.ctime),[r,i]=b(e.mtimeSeconds,e.mtimeNanoseconds,e.mtimeMs,e.mtime);return{ctimeSeconds:t%y,ctimeNanoseconds:n%y,mtimeSeconds:r%y,mtimeNanoseconds:i%y,dev:e.dev%y,ino:e.ino%y,mode:v(e.mode%y),uid:e.uid%y,gid:e.gid%y,size:e.size>-1?e.size%y:0}}function S(e){let t=``;for(let n of new Uint8Array(e))n<16&&(t+=`0`),t+=n.toString(16);return t}var C=null;async function w(e){return C===null&&(C=await D()),C?E(e):T(e)}function T(e){return new r().update(e).digest(`hex`)}async function E(e){return S(await crypto.subtle.digest(`SHA-1`,e))}async function D(){try{return await E(new Uint8Array([]))===`da39a3ee5e6b4b0d3255bfef95601890afd80709`}catch{}return!1}function O(e){return{assumeValid:!!(e&32768),extended:!!(e&16384),stage:(e&12288)>>12,nameLength:e&4095}}function k(e){let t=e.flags;return t.extended=!1,t.nameLength=Math.min(Buffer.from(e.path).length,4095),(t.assumeValid?32768:0)+(t.extended?16384:0)+((t.stage&3)<<12)+(t.nameLength&4095)}var ee=class e{constructor(e,t){this._dirty=!1,this._unmergedPaths=t||new Set,this._entries=e||new Map}_addEntry(e){if(e.flags.stage===0)e.stages=[e],this._entries.set(e.path,e),this._unmergedPaths.delete(e.path);else{let t=this._entries.get(e.path);t||=(this._entries.set(e.path,e),e),t.stages[e.flags.stage]=e,this._unmergedPaths.add(e.path)}}static async from(t){if(Buffer.isBuffer(t))return e.fromBuffer(t);if(t===null)return new e(null);throw new p(`invalid type passed to GitIndex.from`)}static async fromBuffer(t){if(t.length===0)throw new p(`Index file is empty (.git/index)`);let n=new e,r=new h(t),i=r.toString(`utf8`,4);if(i!==`DIRC`)throw new p(`Invalid dircache magic file number: ${i}`);let a=await w(t.slice(0,-20)),o=t.slice(-20).toString(`hex`);if(o!==a)throw new p(`Invalid checksum in GitIndex buffer: expected ${o} but saw ${a}`);let s=r.readUInt32BE();if(s!==2)throw new p(`Unsupported dircache version: ${s}`);let c=r.readUInt32BE(),l=0;for(;!r.eof()&&l<c;){let e={};e.ctimeSeconds=r.readUInt32BE(),e.ctimeNanoseconds=r.readUInt32BE(),e.mtimeSeconds=r.readUInt32BE(),e.mtimeNanoseconds=r.readUInt32BE(),e.dev=r.readUInt32BE(),e.ino=r.readUInt32BE(),e.mode=r.readUInt32BE(),e.uid=r.readUInt32BE(),e.gid=r.readUInt32BE(),e.size=r.readUInt32BE(),e.oid=r.slice(20).toString(`hex`),e.flags=O(r.readUInt16BE());let i=t.indexOf(0,r.tell()+1)-r.tell();if(i<1)throw new p(`Got a path length of: ${i}`);if(e.path=r.toString(`utf8`,i),e.path.includes(`..\\`)||e.path.includes(`../`))throw new m(e.path);let a=8-(r.tell()-12)%8;for(a===0&&(a=8);a--;){let t=r.readUInt8();if(t!==0)throw new p(`Expected 1-8 null characters but got '${t}' after ${e.path}`);if(r.eof())throw new p(`Unexpected end of file`)}e.stages=[],n._addEntry(e),l++}return n}get unmergedPaths(){return[...this._unmergedPaths]}get entries(){return[...this._entries.values()].sort(_)}get entriesMap(){return this._entries}get entriesFlat(){return[...this.entries].flatMap(e=>e.stages.length>1?e.stages.filter(e=>e):e)}*[Symbol.iterator](){for(let e of this.entries)yield e}insert({filepath:e,stats:t,oid:n,stage:r=0}){t||={ctimeSeconds:0,ctimeNanoseconds:0,mtimeSeconds:0,mtimeNanoseconds:0,dev:0,ino:0,mode:0,uid:0,gid:0,size:0},t=x(t);let i=Buffer.from(e),a={ctimeSeconds:t.ctimeSeconds,ctimeNanoseconds:t.ctimeNanoseconds,mtimeSeconds:t.mtimeSeconds,mtimeNanoseconds:t.mtimeNanoseconds,dev:t.dev,ino:t.ino,mode:t.mode||33188,uid:t.uid,gid:t.gid,size:t.size,path:e,oid:n,flags:{assumeValid:!1,extended:!1,stage:r,nameLength:i.length<4095?i.length:4095},stages:[]};this._addEntry(a),this._dirty=!0}delete({filepath:e}){if(this._entries.has(e))this._entries.delete(e);else for(let t of this._entries.keys())t.startsWith(e+`/`)&&this._entries.delete(t);this._unmergedPaths.has(e)&&this._unmergedPaths.delete(e),this._dirty=!0}clear(){this._entries.clear(),this._dirty=!0}has({filepath:e}){return this._entries.has(e)}render(){return this.entries.map(e=>`${e.mode.toString(8)} ${e.oid} ${e.path}`).join(`
|
|
726
|
-
`)}static async _entryToBuffer(e){let t=Buffer.from(e.path),n=Math.ceil((62+t.length+1)/8)*8,r=Buffer.alloc(n),i=new h(r),a=x(e);return i.writeUInt32BE(a.ctimeSeconds),i.writeUInt32BE(a.ctimeNanoseconds),i.writeUInt32BE(a.mtimeSeconds),i.writeUInt32BE(a.mtimeNanoseconds),i.writeUInt32BE(a.dev),i.writeUInt32BE(a.ino),i.writeUInt32BE(a.mode),i.writeUInt32BE(a.uid),i.writeUInt32BE(a.gid),i.writeUInt32BE(a.size),i.write(e.oid,20,`hex`),i.writeUInt16BE(k(e)),i.write(e.path,t.length,`utf8`),r}async toObject(){let t=Buffer.alloc(12),n=new h(t);n.write(`DIRC`,4,`utf8`),n.writeUInt32BE(2),n.writeUInt32BE(this.entriesFlat.length);let r=[];for(let t of this.entries)if(r.push(e._entryToBuffer(t)),t.stages.length>1)for(let n of t.stages)n&&n!==t&&r.push(e._entryToBuffer(n));r=await Promise.all(r);let i=Buffer.concat(r),a=Buffer.concat([t,i]),o=await w(a);return Buffer.concat([a,Buffer.from(o,`hex`)])}};function
|
|
725
|
+
`,document.head.appendChild(e)}},Mi=[{id:`chat`,label:`Chat`},{id:`terminal`,label:`Terminal`},{id:`files`,label:`Files`},{id:`memory`,label:`Memory`}],Ni=`slicc-hidden-tabs`,Pi=[`terminal`,`memory`];function Fi(){try{let e=localStorage.getItem(Ni);return e?new Set(JSON.parse(e)):new Set(Pi)}catch{return new Set(Pi)}}function Ii(e){let t=e.filter(e=>e!==`chat`);localStorage.setItem(Ni,JSON.stringify(t))}var Li=Mi.filter(e=>!Fi().has(e.id)),Ri=`chat`,zi=new Set(Mi.map(e=>e.id));function Bi(e){return zi.has(e)}var Vi=class{zoneId;tabBar;contentArea;tabs=new Map;activeTabId=null;callbacks;addBtn=null;fullpageBtn=null;isFullpage=!1;separator=null;scrollArea=null;storageKey;classPrefix;constructor(e,t,n,r={},i={}){this.tabBar=e,this.contentArea=t,this.zoneId=n,this.callbacks=r,this.storageKey=`slicc-${n}-tab`,this.classPrefix=i.classPrefix??`mini-tabs`}addTab(e){if(this.tabs.has(e.id))return;let t=document.createElement(`button`);if(t.dataset.tabId=e.id,e.pinned&&e.icon){t.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--icon ${this.classPrefix}__tab--dimmed`,t.innerHTML=e.icon,t.setAttribute(`aria-label`,e.label),t.dataset.tooltip=e.label,t.dataset.tooltipPos=`top`;let n=this.separator||this.findFirstNonPinnedBtn()||this.addBtn;if(n?this.tabBar.insertBefore(t,n):this.tabBar.appendChild(t),!this.separator){this.separator=document.createElement(`div`),this.separator.className=`${this.classPrefix}__separator`,this.scrollArea=document.createElement(`div`),this.scrollArea.className=`${this.classPrefix}__scroll`;let e=this.addBtn||this.fullpageBtn;e?(this.tabBar.insertBefore(this.separator,e),this.tabBar.insertBefore(this.scrollArea,e)):(this.tabBar.appendChild(this.separator),this.tabBar.appendChild(this.scrollArea))}t.addEventListener(`click`,()=>{let t=this.tabs.get(e.id);t&&!t.mounted&&this.enablePinnedTab(e.id),this.activateTab(e.id)}),this.tabs.set(e.id,{btn:t,container:e.element,tab:e,mounted:!1})}else{if(t.className=`${this.classPrefix}__tab`,t.appendChild(document.createTextNode(e.label)),e.closable){let n=document.createElement(`span`);n.className=`${this.classPrefix}__tab-close`,n.title=`Close panel`,n.textContent=`×`,n.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onTabClose?.(e.id)}),t.appendChild(n)}t.addEventListener(`click`,()=>this.activateTab(e.id)),this.scrollArea?this.scrollArea.appendChild(t):this.addBtn?this.tabBar.insertBefore(t,this.addBtn):this.tabBar.appendChild(t);let n=e.element;n.style.display=`none`,this.contentArea.appendChild(n),this.tabs.set(e.id,{btn:t,container:n,tab:e,mounted:!0}),(!this.activeTabId||!this.tabs.get(this.activeTabId)?.mounted)&&this.activateTab(e.id)}}removeTab(e){let t=this.tabs.get(e);if(t&&(t.btn.remove(),t.mounted&&t.container.remove(),this.tabs.delete(e),this.activeTabId===e)){let e=Array.from(this.tabs.entries()).find(([,e])=>e.mounted);e?this.activateTab(e[0]):this.activeTabId=null}}enablePinnedTab(e){let t=this.tabs.get(e);!t||t.mounted||(t.mounted=!0,t.btn.classList.remove(`${this.classPrefix}__tab--dimmed`),t.container.style.display=`none`,this.contentArea.appendChild(t.container))}isPinnedTabEnabled(e){return this.tabs.get(e)?.mounted??!1}activateTab(e){let t=this.tabs.get(e);if(!(!t||!t.mounted)){this.activeTabId=e;for(let[t,{btn:n,container:r,mounted:i}]of this.tabs){let a=t===e;n.classList.toggle(`${this.classPrefix}__tab--active`,a),i&&(r.style.display=a?`flex`:`none`)}try{localStorage.setItem(this.storageKey,e)}catch{}t.tab.onActivate?.(),this.callbacks.onTabActivate?.(e)}}getActiveTabId(){return this.activeTabId}getTabIds(){return Array.from(this.tabs.keys())}hasTab(e){return this.tabs.has(e)}setTabBadge(e,t){let n=this.tabs.get(e);if(!n)return;let r=n.btn.querySelector(`.${this.classPrefix}__tab-badge`);if(!t||t<=0){r?.remove();return}let i=r instanceof HTMLSpanElement?r:document.createElement(`span`);if(i.className=`${this.classPrefix}__tab-badge`,i.textContent=t>99?`99+`:String(t),i.setAttribute(`aria-label`,`${t} notifications`),!r){let e=n.btn.querySelector(`.${this.classPrefix}__tab-close`);e?n.btn.insertBefore(i,e):n.btn.appendChild(i)}}get tabCount(){return this.tabs.size}enableAddButton(){this.addBtn||(this.addBtn=document.createElement(`button`),this.addBtn.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--add`,this.addBtn.textContent=`+`,this.addBtn.dataset.tooltip=`Open panel`,this.addBtn.dataset.tooltipPos=`top`,this.addBtn.setAttribute(`aria-label`,`Open panel`),this.addBtn.addEventListener(`click`,()=>this.callbacks.onAddClick?.()),this.tabBar.appendChild(this.addBtn))}setAddButtonEnabled(e){this.addBtn&&(this.addBtn.disabled=!e)}enableFullpageButton(){this.fullpageBtn||(this.fullpageBtn=document.createElement(`button`),this.fullpageBtn.className=`${this.classPrefix}__tab ${this.classPrefix}__tab--fullpage`,this.fullpageBtn.dataset.tooltip=`Full page`,this.fullpageBtn.dataset.tooltipPos=`top`,this.fullpageBtn.setAttribute(`aria-label`,`Toggle full page`),this.fullpageBtn.innerHTML=`<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2h4v4"/><path d="M6 14H2v-4"/><path d="M14 2L9.5 6.5"/><path d="M2 14l4.5-4.5"/></svg>`,this.fullpageBtn.addEventListener(`click`,()=>{this.isFullpage=!this.isFullpage,this.fullpageBtn.classList.toggle(`${this.classPrefix}__tab--active`,this.isFullpage),this.fullpageBtn.innerHTML=this.isFullpage?`<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14 6h-4V2"/><path d="M2 10h4v4"/><path d="M10 6l4.5-4.5"/><path d="M6 10L1.5 14.5"/></svg>`:`<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2h4v4"/><path d="M6 14H2v-4"/><path d="M14 2L9.5 6.5"/><path d="M2 14l4.5-4.5"/></svg>`,this.fullpageBtn.dataset.tooltip=this.isFullpage?`Exit full page`:`Full page`,this.callbacks.onFullpageToggle?.(this.isFullpage)}),this.tabBar.appendChild(this.fullpageBtn))}restoreActiveTab(){try{let e=localStorage.getItem(this.storageKey);if(e&&this.tabs.has(e)&&this.tabs.get(e).mounted)return this.activateTab(e),e}catch{}return null}findFirstNonPinnedBtn(){for(let[,e]of this.tabs)if(!e.tab.pinned)return e.btn;return null}},Hi=class{entries=new Map;listeners=new Set;register(e){this.entries.set(e.id,{descriptor:e}),this.notify()}unregister(e){this.entries.delete(e),this.notify()}get(e){return this.entries.get(e)}getByZone(e){let t=[];for(let n of this.entries.values())n.descriptor.zone===e&&t.push(n.descriptor);return t}getClosed(){let e=[];for(let t of this.entries.values())t.descriptor.zone===null&&e.push(t.descriptor);return e}setZone(e,t){let n=this.entries.get(e);n&&(n.descriptor.zone=t,this.notify())}ids(){return Array.from(this.entries.keys())}has(e){return this.entries.has(e)}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(){for(let e of this.listeners)e()}};function Ui(e,t,n){let r=document.querySelector(`.sprinkle-picker`);if(r){r.remove();return}let{registry:i,callbacks:a,getAvailableSprinkles:o}=n,s=i.getClosed(),c=o?.()??[];if(s.length===0&&c.length===0)return;let l=document.createElement(`div`);l.className=`sprinkle-picker`,l.style.cssText=`position: absolute; min-width: 160px; max-height: 300px; overflow-y: auto; background: var(--s2-bg-layer-2); border: 1px solid var(--s2-border-default); border-radius: var(--s2-radius-l); padding: 4px 0; box-shadow: var(--s2-shadow-elevated); z-index: 1000;`;let u=()=>{l.remove(),document.removeEventListener(`pointerdown`,f,!0),document.removeEventListener(`keydown`,p,!0)};for(let e of s){let n=Wi(e.label,()=>{a.onSelectPanel(e.id,t),u()});l.appendChild(n)}if(s.length>0&&c.length>0){let e=document.createElement(`div`);e.style.cssText=`height: 1px; background: var(--s2-border-default); margin: 4px 0;`,l.appendChild(e)}for(let e of c){let n=Wi(e.title,()=>{a.onSelectSprinkle(e.name,t),u()});l.appendChild(n)}let d=e.getBoundingClientRect();l.style.top=`${d.bottom+4}px`,l.style.left=`${d.left}px`,document.body.appendChild(l);let f=e=>{l.contains(e.target)||u()},p=e=>{e.key===`Escape`&&u()};requestAnimationFrame(()=>{document.addEventListener(`pointerdown`,f,!0),document.addEventListener(`keydown`,p,!0)})}function Wi(e,t){let n=document.createElement(`div`);return n.className=`sprinkle-picker__item`,n.style.cssText=`padding: 6px 12px; cursor: pointer; font-size: 12px; color: var(--s2-content-default); border-radius: var(--s2-radius-s); margin: 0 4px; transition: background 130ms ease;`,n.textContent=e,n.addEventListener(`mouseenter`,()=>{n.style.background=`var(--s2-bg-elevated)`}),n.addEventListener(`mouseleave`,()=>{n.style.background=``}),n.addEventListener(`click`,t),n}var Gi=class e{root;isExtension;scoopsEl;leftEl;rightEl;verticalDivider;terminalContainer;iframeContainer;threadHeaderEl;threadHeaderName;primaryZoneEl;primaryZone;get drawerZone(){return this.primaryZone}get drawerZoneEl(){return this.primaryZoneEl}tabContainers=new Map;activeTab=`chat`;debugTabContainers=null;scoopSwitcher=null;scoopSwitcherEl=null;avatarEl;logoSvg=null;logoImg=null;logoScoopCount=-1;panels;registry=new Hi;onModelChange;refreshModels;onScoopSelect;onClearChat;onClearFilesystem;onSprinkleClose;getAvailableSprinkles;onOpenSprinkle;constructor(e,t=!1){this.root=e,this.isExtension=t,t?this.buildTabbedLayout():this.buildSplitLayout()}setScoopSwitcherOrchestrator(e){this.scoopSwitcher?.setOrchestrator(e)}updateScoopSwitcherStatus(e,t){this.scoopSwitcher?.updateStatus(e,t)}setScoopSwitcherSelected(e){this.scoopSwitcher?.setSelected(e)}refreshScoopSwitcher(){this.scoopSwitcher?.refresh()}setActiveTab(e){this.isExtension&&this.extensionZone?.activateTab(e)}getActiveTab(){return this.activeTab}setPendingHandoffCount(e){this.isExtension&&this.extensionZone.setTabBadge(`chat`,e>0?e:null)}isTerminalOpen(){return this.isExtension?!0:this.primaryZone.isPinnedTabEnabled(`terminal`)}setAgentProcessing(e){this.threadHeaderEl?.classList.toggle(`thread-header--processing`,e)}openTerminal(){if(this.isExtension)return;this.primaryZone.isPinnedTabEnabled(`terminal`)||this.primaryZone.enablePinnedTab(`terminal`);let e=this.primaryZone.getActiveTabId();e&&e.startsWith(`sprinkle-`)||this.primaryZone.activateTab(`terminal`)}setDebugTabs(e){if(!this.isExtension||!this.debugTabContainers)return;let t=[{id:`terminal`,label:`Terminal`,container:this.debugTabContainers.terminal,onActivate:()=>this.panels?.terminal?.refit?.()},{id:`memory`,label:`Memory`,container:this.debugTabContainers.memory,onActivate:()=>this.panels?.memory?.refresh()}];for(let{id:n,label:r,container:i,onActivate:a}of t)e&&!this.extensionZone.hasTab(n)?(this.extensionZone.addTab({id:n,label:r,closable:!1,element:i,onActivate:a}),this.tabContainers.set(n,i)):!e&&this.extensionZone.hasTab(n)&&(this.extensionZone.removeTab(n),this.tabContainers.delete(n));Ii(e?[]:[`terminal`,`memory`])}buildHeader(e){let t=document.createElement(`div`);t.className=`header`;let n=()=>{if(D())return;let e=ne();for(let t of e)if(t.models.length>0){let{defaultModelId:e}=A(t.providerId),n=(e?t.models.find(t=>t.id.toLowerCase().includes(e.toLowerCase())):void 0)??t.models[0];C(`${t.providerId}:${n.id}`);return}};n(),this.refreshModels=()=>{n(),this.panels?.chat?.refreshModelSelector(),this.refreshAvatar()};let r=document.createElement(`div`);r.className=`header__row`;let i=document.createElement(`div`);i.className=`header__brand`;let a=this.isExtension?24:28,o=this.sliccLogo(a);i.appendChild(o);let s=document.createElement(`div`);s.className=`header__title`,s.textContent=`slicc`,i.appendChild(s),r.appendChild(i),this.isExtension&&(this.scoopSwitcherEl=document.createElement(`div`),this.scoopSwitcherEl.className=`scoop-switcher`,this.scoopSwitcher=new ji(this.scoopSwitcherEl,{onScoopSelect:e=>this.onScoopSelect?.(e),onDeleteScoop:e=>{this.panels?.scoops?.deleteScoop?.(e)}}),r.appendChild(this.scoopSwitcherEl));let c=document.createElement(`div`);c.className=`header__spacer`,r.appendChild(c),this.avatarEl=this.buildUserAvatar(),r.appendChild(this.avatarEl),t.appendChild(r),e.appendChild(t)}static SCOOP_COLORS=[`#f000a0`,`#00f0f0`,`#90f000`,`#15d675`,`#e68619`];sliccLogo(e=22){let t=document.createElement(`img`);return t.width=e,t.height=e,t.src=`/logos/sliccy-color-0scoops-128x128.png`,t.alt=`slicc`,t.classList.add(`header__logo`),t.style.objectFit=`contain`,this.logoImg=t,t}static SCOOP_R=5;static SCOOP_SPACING=8.5;static ROW_STEP=7.5;pyramidLayout(t){if(t===0)return[];let{SCOOP_SPACING:n,ROW_STEP:r}=e,i=1;for(;i*(i+1)/2<t;)i++;let a=[],o=t,s=i;for(;o>0;){let e=Math.min(o,s);a.push(e),o-=e,s--}let c=[],l=19-e.SCOOP_R;for(let e of a){let t=16-(e-1)*n/2;for(let r=0;r<e;r++)c.push({cx:t+r*n,cy:l});l-=r}return c}updateLogoScoops(e){let t=e.filter(e=>!e.isCone),n=this.logoScoopCount;if(n===t.length&&n>=0)return;this.logoScoopCount=t.length;let r=Math.min(Math.max(t.length,0),10);this.logoImg&&(this.logoImg.src=`/logos/sliccy-color-${r}scoops-128x128.png`),this.updateFaviconForScoops(t.length)}updateFaviconForScoops(e){let t=Math.min(Math.max(e,0),10),n=document.querySelector(`link[rel="icon"]`);n&&(n.href=`/logos/sliccy-color-${t}scoops-32x32.png`);let r=typeof chrome<`u`?chrome:null;r?.action?.setIcon&&r.action.setIcon({path:{16:`logos/sliccy-color-${t}scoops-16x16.png`,32:`logos/sliccy-color-${t}scoops-32x32.png`,48:`logos/sliccy-color-${t}scoops-48x48.png`,128:`logos/sliccy-color-${t}scoops-128x128.png`}}).catch(()=>{})}getInitials(e){let t=e.trim().split(/\s+/);return t.length>=2?(t[0][0]+t[t.length-1][0]).toUpperCase():e.slice(0,2).toUpperCase()}buildUserAvatar(){let e=document.createElement(`div`);e.className=`header__avatar`,e.setAttribute(`aria-label`,`Account`),e.dataset.tooltip=`Account`;let t=j().find(e=>e.userName||e.userAvatar);if(t?.userAvatar){let n=document.createElement(`img`);n.src=t.userAvatar,n.alt=t.userName??`User`,n.addEventListener(`error`,()=>{e.removeChild(n),t.userName&&(e.classList.add(`header__avatar--initials`),e.textContent=this.getInitials(t.userName))}),e.appendChild(n)}else t?.userName?(e.classList.add(`header__avatar--initials`),e.textContent=this.getInitials(t.userName)):(e.classList.add(`header__avatar--placeholder`),e.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M10 10c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v1c0 .55.45 1 1 1h14c.55 0 1-.45 1-1v-1c0-2.66-5.33-4-8-4z"/></svg>`);return e.addEventListener(`click`,()=>this.showAvatarPopover()),e}refreshAvatar(){if(!this.avatarEl)return;let e=this.avatarEl.parentElement;if(!e)return;let t=this.buildUserAvatar();e.replaceChild(t,this.avatarEl),this.avatarEl=t}showAvatarPopover(){let e=document.querySelector(`.avatar-popover`);if(e){e.remove();return}let t=document.createElement(`div`);t.className=`avatar-popover`;let n=j(),r=n.find(e=>e.userName||e.accessToken||e.apiKey);if(r){let e=document.createElement(`div`);e.className=`avatar-popover__user`;let n=document.createElement(`div`);n.className=`avatar-popover__name`,n.textContent=r.userName||`Logged in`,e.appendChild(n);let i=document.createElement(`div`);i.className=`avatar-popover__provider`,i.textContent=A(r.providerId).name,e.appendChild(i),t.appendChild(e);let a=document.createElement(`button`);a.className=`avatar-popover__item`,a.textContent=`Sign out`,a.addEventListener(`click`,()=>{re(r.providerId),t.remove(),this.refreshAvatar(),this.refreshModels?.()}),t.appendChild(a)}if(n.length>0){let e=document.createElement(`div`);e.className=`avatar-popover__separator`,t.appendChild(e);let n=document.createElement(`button`);n.className=`avatar-popover__item avatar-popover__item--danger`,n.textContent=`Clear all accounts`,n.addEventListener(`click`,()=>{te(),t.remove(),this.refreshAvatar(),this.refreshModels?.()}),t.appendChild(n)}let i=document.createElement(`div`);i.className=`avatar-popover__separator`,t.appendChild(i);let a=document.createElement(`button`);a.className=`avatar-popover__item avatar-popover__item--danger`,a.textContent=`Clear chat`,a.addEventListener(`click`,async()=>{t.remove(),await this.panels?.chat?.clearSession(),await this.onClearChat?.(),location.reload()}),t.appendChild(a);let o=document.createElement(`div`);o.className=`avatar-popover__separator`,t.appendChild(o);let s=document.createElement(`button`);s.className=`avatar-popover__item`,s.textContent=`Account settings…`,s.addEventListener(`click`,async()=>{t.remove(),E()||te(),await b()&&(this.refreshAvatar(),this.refreshModels?.())}),t.appendChild(s),document.body.appendChild(t);let c=this.avatarEl.getBoundingClientRect();t.style.top=`${c.bottom+4}px`,t.style.right=`${window.innerWidth-c.right}px`;let l=e=>{if(e instanceof KeyboardEvent){if(e.key!==`Escape`)return}else if(t.contains(e.target)||this.avatarEl.contains(e.target))return;t.remove(),document.removeEventListener(`mousedown`,l),document.removeEventListener(`keydown`,l)};requestAnimationFrame(()=>{document.addEventListener(`mousedown`,l),document.addEventListener(`keydown`,l)})}extensionZone;buildTabbedLayout(){for(;this.root.firstChild;)this.root.removeChild(this.root.firstChild);this.buildHeader(this.root);let e=document.createElement(`div`);e.className=`tab-bar`,this.root.appendChild(e);let t=document.createElement(`div`);t.className=`tab-content`,this.root.appendChild(t),this.extensionZone=new Vi(e,t,`primary`,{onTabActivate:e=>{this.activeTab=e,e===`terminal`&&this.panels?.terminal?.refit?.(),e===`memory`&&this.panels?.memory?.refresh()},onTabClose:e=>{let t=e.startsWith(`sprinkle-`)?e.slice(9):e;this.onSprinkleClose?.(t)},onAddClick:()=>this.showExtensionPicker(e)},{classPrefix:`tab-bar`});let n=document.createElement(`div`);n.className=`tab-content__panel`;let r=document.createElement(`div`);r.className=`tab-content__panel`;let i=document.createElement(`div`);i.className=`tab-content__panel`;let a=document.createElement(`div`);a.className=`tab-content__panel`;for(let{id:e,label:t}of Li){let o=e===`chat`?n:e===`terminal`?r:e===`files`?i:a;this.extensionZone.addTab({id:e,label:t,closable:!1,element:o,onActivate:e===`terminal`?()=>this.panels?.terminal?.refit?.():e===`memory`?()=>this.panels?.memory?.refresh():void 0}),this.tabContainers.set(e,o)}this.debugTabContainers={terminal:r,memory:a},this.extensionZone.enableAddButton(),this.iframeContainer=document.createElement(`div`),this.iframeContainer.id=`scoop-iframes`,this.iframeContainer.style.display=`none`,this.root.appendChild(this.iframeContainer),this.scoopsEl=document.createElement(`div`),this.scoopsEl.style.display=`none`,this.root.appendChild(this.scoopsEl),this.panels={chat:new vi(n),terminal:new yi(r,{onClearTerminal:()=>{this.panels.terminal.clearTerminal()}}),fileBrowser:new Di(i,{onRunCommand:async e=>{await this.runFileBrowserCommand(e),this.extensionZone.activateTab(`terminal`)}}),memory:new Oi(a),scoops:new Ai(this.scoopsEl,{onScoopSelect:e=>this.onScoopSelect?.(e),onSendMessage:()=>{},onScoopsChanged:e=>this.updateLogoScoops(e)})},this.panels.chat.onModelChange=e=>this.onModelChange?.(e)}showExtensionPicker(e){let t=this.getAvailableSprinkles?.()??[],n=new Set(this.extensionZone.getTabIds()),r=t.filter(e=>!n.has(`sprinkle-${e.name}`));r.length!==0&&Ui(e,`primary`,{registry:this.registry,callbacks:{onSelectPanel:()=>{},onSelectSprinkle:e=>{this.onOpenSprinkle?.(e)}},getAvailableSprinkles:()=>r})}switchTab(e){this.extensionZone&&this.extensionZone.activateTab(e)}buildSplitLayout(){for(;this.root.firstChild;)this.root.removeChild(this.root.firstChild);this.buildHeader(this.root);let e=document.createElement(`div`);e.className=`layout`,this.scoopsEl=document.createElement(`div`),this.scoopsEl.className=`layout__scoops`,e.appendChild(this.scoopsEl),this.leftEl=document.createElement(`div`),this.leftEl.className=`layout__left`,this.threadHeaderEl=document.createElement(`div`),this.threadHeaderEl.className=`thread-header`;let t=document.createElement(`div`);t.className=`thread-header__title`;let n=document.createElement(`span`);n.className=`thread-header__icon`,n.innerHTML=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 4h14a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H7l-4 3V5a1 1 0 0 1 1-1z"/><path d="M7 8h6"/><path d="M7 11h3"/></svg>`,t.appendChild(n),this.threadHeaderName=document.createElement(`span`),this.threadHeaderName.className=`thread-header__name`,this.threadHeaderName.textContent=`sliccy`,t.appendChild(this.threadHeaderName),this.threadHeaderEl.appendChild(t);let r=document.createElement(`button`);r.className=`thread-header__panel-toggle thread-header__panel-toggle--right`,r.dataset.tooltip=`Toggle panel`,r.setAttribute(`aria-label`,`Toggle panel`),r.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3h14a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/><path d="M12 3v14"/></svg>`,r.addEventListener(`click`,()=>{this.rightEl.classList.toggle(`layout__right--open`)});let i=document.createElement(`button`);i.className=`thread-header__panel-toggle`,i.dataset.tooltip=`Clear Chat`,i.setAttribute(`aria-label`,`Clear Chat`),i.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="none"><path d="m8.249,15.021c-.4,0-.733-.317-.748-.72l-.25-6.5c-.017-.414.307-.763.72-.778.01-.001.021-.001.03-.001.4,0,.733.317.748.72l.25,6.5c.017.414-.307.763-.72.778-.01.001-.021.001-.03.001Z" fill="currentColor"/><path d="m11.751,15.021c-.01,0-.02,0-.03-.001-.413-.016-.736-.364-.72-.778l.25-6.5c.015-.403.348-.72.748-.72.01,0,.02,0,.03.001.413.016.736.364.72.778l-.25,6.5c-.015.403-.348.72-.748.72Z" fill="currentColor"/><path d="m17,4h-3.5v-.75c0-1.24-1.01-2.25-2.25-2.25h-2.5c-1.24,0-2.25,1.01-2.25,2.25v.75h-3.5c-.414,0-.75.336-.75.75s.336.75.75.75h.52l.422,10.342c.048,1.21,1.036,2.158,2.248,2.158h7.619c1.212,0,2.2-.948,2.248-2.158l.422-10.342h.52c.414,0,.75-.336.75-.75s-.336-.75-.75-.75Zm-9-.75c0-.413.337-.75.75-.75h2.5c.413,0,.75.337.75.75v.75h-4v-.75Zm6.56,12.531c-.017.403-.346.719-.75.719h-7.619c-.404,0-.733-.316-.75-.719l-.42-10.281h9.959l-.42,10.281Z" fill="currentColor"/></svg>`,i.addEventListener(`click`,async()=>{await this.panels.chat.clearSession(),await this.onClearChat?.(),location.reload()});let a=document.createElement(`div`);a.className=`thread-header__actions`,a.appendChild(i),a.appendChild(r),this.threadHeaderEl.appendChild(a),this.leftEl.appendChild(this.threadHeaderEl);let o=document.createElement(`div`);o.style.cssText=`display: flex; flex-direction: column; flex: 1; min-height: 0;`,this.leftEl.appendChild(o),e.appendChild(this.leftEl),this.verticalDivider=document.createElement(`div`),this.verticalDivider.className=`layout__divider layout__divider--vertical`,e.appendChild(this.verticalDivider),this.rightEl=document.createElement(`div`),this.rightEl.className=`layout__right`,this.primaryZoneEl=document.createElement(`div`),this.primaryZoneEl.style.cssText=`display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;`;let s=document.createElement(`div`);s.className=`mini-tabs`;let c=document.createElement(`button`);c.className=`thread-header__panel-toggle thread-header__panel-toggle--right`,c.dataset.tooltip=`Close panel`,c.setAttribute(`aria-label`,`Close panel`),c.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v14"/><path d="M3 3h14a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/></svg>`,c.addEventListener(`click`,()=>{this.rightEl.classList.remove(`layout__right--open`)}),s.appendChild(c),this.primaryZoneEl.appendChild(s);let l=document.createElement(`div`);l.style.cssText=`flex: 1; min-height: 0; display: flex; flex-direction: column; overflow: hidden;`,this.primaryZoneEl.appendChild(l),this.primaryZone=new Vi(s,l,`primary`,{onTabActivate:e=>{e===`terminal`&&this.panels?.terminal?.refit(),e===`memory`&&this.panels?.memory?.refresh()},onTabClose:e=>{let t=e.startsWith(`sprinkle-`)?e.slice(9):e;this.onSprinkleClose?.(t)},onAddClick:()=>this.showPickerForZone(`primary`,s),onFullpageToggle:e=>{this.leftEl.classList.toggle(`layout__left--fullpage-hidden`,e),this.verticalDivider.classList.toggle(`layout__divider--fullpage-hidden`,e),this.scoopsEl.classList.toggle(`layout__scoops--fullpage-hidden`,e),this.rightEl.classList.toggle(`layout__right--fullpage`,e)}}),this.terminalContainer=document.createElement(`div`),this.terminalContainer.style.cssText=`display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;`;let u=document.createElement(`div`);u.style.cssText=`display: flex; flex-direction: column; min-height: 0; overflow: hidden; flex: 1;`;let d=document.createElement(`div`);d.style.cssText=`display: flex; flex-direction: column; min-height: 0; flex: 1;`;let f=e=>`<svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">${e}</svg>`;this.primaryZone.addTab({id:`terminal`,label:`Terminal`,closable:!1,element:this.terminalContainer,pinned:!0,icon:f(`<path d="M5.5 14.5C5.30762 14.5 5.11621 14.4268 4.96973 14.2803L1.21973 10.5303C0.92676 10.2373 0.92676 9.76269 1.21973 9.46972L4.96973 5.71972C5.2627 5.42675 5.73731 5.42675 6.03028 5.71972C6.32325 6.01269 6.32325 6.4873 6.03028 6.78027L2.81055 10L6.03028 13.2197C6.32325 13.5127 6.32325 13.9873 6.03028 14.2803C5.8838 14.4268 5.69238 14.5 5.5 14.5Z" fill="currentColor"/><path d="M14.5 14.5C14.3076 14.5 14.1162 14.4268 13.9697 14.2803C13.6768 13.9873 13.6768 13.5127 13.9697 13.2197L17.1895 9.99999L13.9697 6.78026C13.6768 6.48729 13.6768 6.01268 13.9697 5.71971C14.2627 5.42674 14.7373 5.42674 15.0303 5.71971L18.7803 9.46971C19.0732 9.76268 19.0732 10.2373 18.7803 10.5303L15.0303 14.2803C14.8838 14.4267 14.6924 14.5 14.5 14.5Z" fill="currentColor"/><path d="M8.22852 18C8.16993 18 8.11036 17.9932 8.05176 17.9795C7.64844 17.8818 7.40137 17.4766 7.49805 17.0742L10.998 2.57422C11.0957 2.1709 11.5078 1.92871 11.9033 2.02051C12.3066 2.11817 12.5537 2.52344 12.457 2.92578L8.95703 17.4258C8.87402 17.7695 8.56642 18 8.22852 18Z" fill="currentColor"/>`),onActivate:()=>this.panels?.terminal?.refit()}),this.primaryZone.addTab({id:`files`,label:`Files`,closable:!1,element:u,pinned:!0,icon:f(`<path d="M18 4.75C18 2.61621 13.9756 1.5 10 1.5C6.02441 1.5 2 2.61621 2 4.75C2 4.81714 2.01538 4.88037 2.02325 4.94556C2.01696 4.98462 2 5.01978 2 5.06055V15C2 17.0615 6.14697 18 10 18C13.853 18 18 17.0615 18 15V5.06055C18 5.01978 17.983 4.98462 17.9767 4.94556C17.9846 4.88037 18 4.81714 18 4.75ZM16.5002 9.99451C16.4084 10.4097 14.2719 11.5 10 11.5C5.72705 11.5 3.59033 10.4092 3.5 10V6.72449C5.02985 7.56665 7.52393 8 10 8C12.4761 8 14.9701 7.56665 16.5001 6.72437L16.5002 9.99451ZM10 3C14.2886 3 16.5 4.22656 16.5 4.75C16.5 5.27344 14.2886 6.5 10 6.5C5.71143 6.5 3.5 5.27344 3.5 4.75C3.5 4.22656 5.71143 3 10 3ZM10 16.5C5.72705 16.5 3.59033 15.4092 3.5 15V11.8464C5.05219 12.6304 7.58337 13 10 13C12.4168 13 14.9482 12.6304 16.5003 11.8463L16.5005 14.9941C16.4097 15.4092 14.273 16.5 10 16.5Z" fill="currentColor"/>`)}),this.primaryZone.addTab({id:`memory`,label:`Memory`,closable:!1,element:d,pinned:!0,icon:f(`<path d="M10.0039 12.5889C9.11573 12.5889 8.25098 12.1289 7.77588 11.3057C7.06787 10.0781 7.48975 8.50489 8.71582 7.79688C9.30908 7.45313 10.001 7.36329 10.665 7.54004C11.3276 7.71777 11.8814 8.14356 12.2241 8.73731C12.5674 9.33106 12.6582 10.0234 12.481 10.6855C12.3032 11.3486 11.8784 11.9024 11.2842 12.2451C10.8809 12.4785 10.4395 12.5889 10.0039 12.5889ZM9.07471 10.5557C9.36914 11.0645 10.0229 11.2392 10.5342 10.9463C10.7812 10.8037 10.958 10.5732 11.0317 10.2978C11.1055 10.0225 11.0679 9.73436 10.9253 9.48729C10.7822 9.24022 10.5522 9.06346 10.2764 8.98924C10.0015 8.916 9.71337 8.95408 9.46581 9.09569C8.95556 9.39061 8.78027 10.0449 9.07471 10.5557Z" fill="currentColor"/><path d="M6.90674 18.3184C6.56738 18.3184 6.22461 18.2334 5.91455 18.0537L5.09473 17.5811C4.20166 17.0674 3.84473 15.9316 4.28369 14.998L4.86377 13.7646C4.59863 13.4014 4.37402 13.0137 4.19189 12.6035L2.83496 12.4912C1.80615 12.4063 1.00049 11.5313 1.00049 10.5L0.99951 9.55371C0.99951 8.52051 1.80469 7.64453 2.83301 7.55957L4.1875 7.44531C4.2793 7.23633 4.37988 7.03613 4.48926 6.8457C4.59912 6.65429 4.72266 6.46679 4.8584 6.28125L4.27783 5.05176C3.83691 4.11914 4.1914 2.9834 5.08496 2.4668L5.90527 1.99317C6.79785 1.47657 7.95898 1.73438 8.54785 2.58301L9.32519 3.70117C9.76904 3.65137 10.2173 3.65332 10.666 3.70117L11.4414 2.58203C12.0303 1.73242 13.1924 1.47265 14.085 1.98828L14.9048 2.46094C15.7988 2.97656 16.1543 4.11231 15.7153 5.04492L15.1352 6.27734C15.4009 6.6416 15.6255 7.02929 15.8071 7.43847L17.164 7.55077C18.1924 7.63573 18.998 8.51073 18.999 9.54198L18.9995 10.4893C19.0005 11.5205 18.1958 12.3965 17.1675 12.4834L15.812 12.5976C15.7207 12.8066 15.6201 13.0059 15.5093 13.1973C15.3999 13.3867 15.2769 13.5752 15.1411 13.7607L15.7217 14.9902C16.1621 15.9219 15.8081 17.0576 14.915 17.5752L14.0942 18.0498C13.2007 18.5684 12.0405 18.3076 11.4517 17.459L10.6743 16.3408C10.2285 16.3897 9.78028 16.3887 9.3335 16.3418L8.55713 17.4619C8.17334 18.0156 7.54541 18.3184 6.90674 18.3184ZM6.9043 3.22461C6.81934 3.22461 6.73389 3.24609 6.65625 3.29102L5.83545 3.76563C5.61279 3.89454 5.52393 4.17774 5.63428 4.41114L6.41309 6.06153C6.53907 6.32813 6.49707 6.64356 6.30567 6.86817C6.10157 7.10743 5.93262 7.34473 5.78907 7.59376C5.64796 7.83985 5.52393 8.11231 5.42091 8.40333C5.32277 8.68165 5.07081 8.87599 4.77687 8.9004L2.95802 9.05372C2.6963 9.07618 2.49952 9.29005 2.49952 9.55274L2.5005 10.499C2.5005 10.7568 2.70167 10.9756 2.959 10.9971L4.77834 11.1475C5.07229 11.1719 5.32473 11.3662 5.42336 11.6445C5.62209 12.2051 5.92043 12.7207 6.31008 13.1768C6.50197 13.4004 6.54446 13.7168 6.41897 13.9834L5.64114 15.6358C5.53176 15.8692 5.62014 16.1533 5.84378 16.2813L6.66409 16.7549C6.88821 16.8848 7.17825 16.8184 7.32425 16.6074L8.36527 15.1055C8.53275 14.8633 8.82425 14.7363 9.11771 14.7959C9.70609 14.9033 10.3023 14.9043 10.8877 14.7949C11.1773 14.7402 11.4727 14.8613 11.6412 15.1045L12.6831 16.6035C12.8296 16.8135 13.1216 16.8799 13.3438 16.751L14.1641 16.2773C14.3902 16.1465 14.4776 15.8682 14.3653 15.6309L13.5864 13.9805C13.4605 13.7139 13.5025 13.3984 13.6939 13.1738C13.898 12.9336 14.0669 12.6973 14.2095 12.4492L14.21 12.4483C14.3526 12.2012 14.4732 11.9365 14.5786 11.6387C14.6773 11.3604 14.9292 11.166 15.2232 11.1416L17.042 10.9893C17.2984 10.9668 17.4995 10.7481 17.4995 10.4902L17.499 9.54298C17.499 9.28126 17.3018 9.06739 17.0401 9.04493L15.2212 8.89454C14.9273 8.87013 14.6748 8.67579 14.5762 8.39747C14.3784 7.8379 14.0796 7.32227 13.689 6.86524C13.4976 6.64063 13.4551 6.3252 13.5806 6.0586L14.3579 4.40626C14.4678 4.17286 14.3789 3.88868 14.1553 3.75978L13.3355 3.28712C13.1108 3.16017 12.8213 3.2256 12.6743 3.43653L11.6348 4.93653C11.4668 5.17969 11.1758 5.30469 10.8819 5.24708C10.2905 5.1377 9.69435 5.1377 9.11183 5.24708C8.81984 5.29884 8.52638 5.1797 8.35841 4.93751L7.31642 3.43849C7.22023 3.30079 7.06348 3.22461 6.9043 3.22461Z" fill="currentColor"/>`),onActivate:()=>this.panels?.memory?.refresh()}),this.primaryZone.enableAddButton(),this.primaryZone.enableFullpageButton(),this.rightEl.appendChild(this.primaryZoneEl),e.appendChild(this.rightEl),this.iframeContainer=document.createElement(`div`),this.iframeContainer.id=`scoop-iframes`,this.iframeContainer.style.display=`none`,e.appendChild(this.iframeContainer),this.root.appendChild(e),this.panels={chat:new vi(o),terminal:new yi(this.terminalContainer,{onClearTerminal:()=>{this.panels.terminal.clearTerminal(),this.openTerminal()}}),fileBrowser:new Di(u,{onRunCommand:async e=>{await this.runFileBrowserCommand(e),this.openTerminal()}}),memory:new Oi(d),scoops:new Ai(this.scoopsEl,{onScoopSelect:e=>{this.onScoopSelect?.(e),this.threadHeaderName.textContent=e.assistantLabel},onSendMessage:()=>{},onScoopsChanged:e=>this.updateLogoScoops(e)})},this.panels.chat.onModelChange=e=>this.onModelChange?.(e),this.setupVerticalDrag(),window.addEventListener(`resize`,()=>{})}getIframeContainer(){return this.iframeContainer}async runFileBrowserCommand(e){let t=await this.panels.terminal.runCommand(e);t.exitCode!==0&&t.stderr&&console.warn(`[Layout] File browser command failed:`,t.stderr.trim())}setupVerticalDrag(){if(!this.verticalDivider)return;let e=!1,t=t=>{if(!e)return;let n=this.root.querySelector(`.layout`)?.getBoundingClientRect();if(!n)return;let r=t.clientX-n.left-58,i=n.width-58,a=Math.max(.3,Math.min(.7,r/i));this.leftEl.style.flex=`${a*100} 0 0`,this.rightEl.style.flex=`${(1-a)*100} 0 0`},n=()=>{e=!1,this.verticalDivider.classList.remove(`active`),document.body.style.cursor=``,document.body.style.userSelect=``,window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n),this.panels?.terminal?.refit()};this.verticalDivider.addEventListener(`mousedown`,r=>{r.preventDefault(),e=!0,this.verticalDivider.classList.add(`active`),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`,window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)})}updateAddButtons(){let e=this.registry.getClosed().length,t=this.getAvailableSprinkles?.()??[],n=new Set;for(let e of this.registry.ids())e.startsWith(`sprinkle-`)&&this.registry.get(e)?.descriptor.zone!==null&&n.add(e.slice(9));let r=e+t.filter(e=>!n.has(e.name)).length>0;this.primaryZone?.setAddButtonEnabled(r)}showPickerForZone(e,t){let n=new Set;for(let e of this.registry.ids())e.startsWith(`sprinkle-`)&&this.registry.get(e)?.descriptor.zone!==null&&n.add(e.slice(9));let r=(this.getAvailableSprinkles?.()??[]).filter(e=>!n.has(e.name));Ui(t,e,{registry:this.registry,callbacks:{onSelectPanel:(e,t)=>{this.openPanelInZone(e,t)},onSelectSprinkle:(e,t)=>{this.onOpenSprinkle?.(e,t)}},getAvailableSprinkles:()=>r})}openPanelInZone(e,t){let n=this.registry.get(e);if(!n)return;let r=this.primaryZone;this.registry.setZone(e,t),r.addTab({id:n.descriptor.id,label:n.descriptor.label,closable:n.descriptor.closable,element:n.descriptor.element,onActivate:n.descriptor.onActivate}),r.activateTab(e)}dynamicSprinkles=new Map;addSprinkle(e,t,n,r){if(this.isExtension){let r=`sprinkle-${e}`,i=document.createElement(`div`);i.className=`tab-content__panel`,i.appendChild(n),this.extensionZone.addTab({id:r,label:t,closable:!0,element:i}),this.tabContainers.set(r,i),this.dynamicSprinkles.set(e,i),this.extensionZone.activateTab(r)}else{let i=r??`primary`,a=this.primaryZone,o=`sprinkle-${e}`,s=document.createElement(`div`);s.style.cssText=`display: flex; flex-direction: column; min-height: 0; overflow: auto; flex: 1;`,s.appendChild(n),this.registry.register({id:o,label:t,zone:i,closable:!0,element:s,onClose:()=>this.onSprinkleClose?.(e)}),a.addTab({id:o,label:t,closable:!0,element:s}),this.dynamicSprinkles.set(e,s),a.activateTab(o),this.updateAddButtons()}}removeSprinkle(e){if(this.isExtension){let t=`sprinkle-${e}`;this.extensionZone.removeTab(t),this.tabContainers.delete(t),this.dynamicSprinkles.delete(e)}else{let t=`sprinkle-${e}`;this.primaryZone.removeTab(t),this.registry.unregister(t),this.dynamicSprinkles.delete(e),this.updateAddButtons()}}dispose(){for(this.panels.chat.dispose(),this.panels.terminal.dispose(),this.panels.fileBrowser.dispose(),this.panels.memory.dispose();this.root.firstChild;)this.root.removeChild(this.root.firstChild)}},Ki=`slicc-theme`,qi=new Set([`dark`,`light`,`system`]);function Ji(){let e=localStorage.getItem(Ki);return e&&qi.has(e)?e:`system`}function Yi(){let e=Ji(),t=e===`light`;e===`system`&&(t=window.matchMedia?.(`(prefers-color-scheme: light)`).matches??!1),document.documentElement.classList.toggle(`theme-light`,t)}var Xi;function Zi(){Yi(),Xi=window.matchMedia?.(`(prefers-color-scheme: light)`),Xi?.addEventListener?.(`change`,()=>{Ji()===`system`&&Yi()})}var Qi=300,$i=6,ea=null,ta=null;function na(){return ea||(ea=document.createElement(`div`),ea.className=`s2-tooltip`,document.body.appendChild(ea)),ea}function ra(e){let t=e.getAttribute(`data-tooltip`);if(!t)return;let n=na();n.textContent=t,n.classList.remove(`s2-tooltip--visible`),n.style.left=`0`,n.style.top=`0`;let r=e.getBoundingClientRect(),i=n.getBoundingClientRect(),a=e.getAttribute(`data-tooltip-pos`)||`bottom`,o,s;a===`top`?(o=r.top-i.height-$i,s=r.left+r.width/2-i.width/2):a===`right`?(o=r.top+r.height/2-i.height/2,s=r.right+$i):(o=r.bottom+$i,s=r.left+r.width/2-i.width/2),a===`bottom`&&o+i.height>window.innerHeight-4?o=r.top-i.height-$i:a===`top`&&o<4&&(o=r.bottom+$i),s<4&&(s=4),s+i.width>window.innerWidth-4&&(s=window.innerWidth-i.width-4),n.style.top=`${o}px`,n.style.left=`${s}px`,n.classList.add(`s2-tooltip--visible`)}function ia(){ta&&=(clearTimeout(ta),null),ea?.classList.remove(`s2-tooltip--visible`)}function aa(){document.addEventListener(`pointerenter`,e=>{let t=e.target.closest?.(`[data-tooltip]`);t&&(ia(),ta=setTimeout(()=>ra(t),Qi))},!0),document.addEventListener(`pointerleave`,e=>{e.target.closest?.(`[data-tooltip]`)&&ia()},!0),document.addEventListener(`pointerdown`,ia,!0)}function oa(e){return e.toLowerCase().endsWith(ae)}function sa(e){return Array.from(e).find(e=>oa(e.name))??null}function ca(e){if(!e)return!1;if(e.items){for(let t of Array.from(e.items))if(t.kind===`file`)return!0}return!1}function la(e){if(!e)return null;if(e.files){let t=sa(e.files);if(t)return t}if(!e.items)return null;for(let t of Array.from(e.items)){if(t.kind&&t.kind!==`file`)continue;let e=t.getAsFile?.();if(e&&oa(e.name))return e}return null}var ua=new Map,da=new Map;function fa(e){let t=e.length;return t===0?`0`:`${t}:${e.charCodeAt(0)}:${t>1?e.charCodeAt(1):0}:${t>2?e.charCodeAt(2):0}:${t>3?e.charCodeAt(3):0}:${t>4?e.charCodeAt(Math.floor(t/4)):0}:${t>4?e.charCodeAt(Math.floor(t/2)):0}:${t>4?e.charCodeAt(Math.floor(3*t/4)):0}:${e.charCodeAt(t-1)}`}function pa(e,t){let n=fa(e);ua.set(n,t),setTimeout(()=>ua.delete(n),1e4)}function ma(e,t){da.set(e,t),setTimeout(()=>da.delete(e),1e4)}function ha(e){let t=da.get(e);return t?(da.delete(e),t):null}function ga(e){let t=fa(e),n=ua.get(t);return n?(ua.delete(t),n):null}var _a=class{registeredCommandsFn=null;constructor(e){this.vfs=e}setRegisteredCommandsFn(e){this.registeredCommandsFn=e}getVirtualBinCommands(){return this.registeredCommandsFn?.()??[]}async readFile(e,t){let n=I(e),r=await this.vfs.readFile(n,{encoding:`binary`}),i=r instanceof Uint8Array?r:new TextEncoder().encode(r);try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(i)}catch{let e=Array(i.length);for(let t=0;t<i.length;t++)e[t]=String.fromCharCode(i[t]);return e.join(``)}}async readFileBuffer(e){let t=I(e),n=await this.vfs.readFile(t,{encoding:`binary`});return n instanceof Uint8Array?n:new TextEncoder().encode(n)}async writeFile(e,t,n){let r=I(e);if(typeof t==`string`){let e=ga(t);if(e){await this.vfs.writeFile(r,e);return}let n=!1;for(let e=0;e<t.length;e++)if(t.charCodeAt(e)>255){n=!0;break}if(n)await this.vfs.writeFile(r,new TextEncoder().encode(t));else{let e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);await this.vfs.writeFile(r,e)}}else await this.vfs.writeFile(r,t)}async appendFile(e,t,n){let r=I(e),i=new Uint8Array;try{let e=await this.vfs.readFile(r,{encoding:`binary`});i=e instanceof Uint8Array?new Uint8Array(e):new TextEncoder().encode(e)}catch(e){if(!(e instanceof oe&&e.code===`ENOENT`))throw e}let a;if(typeof t==`string`){a=new Uint8Array(t.length);for(let e=0;e<t.length;e++)a[e]=t.charCodeAt(e)&255}else a=t instanceof Uint8Array?t:new Uint8Array(t);let o=new Uint8Array(i.length+a.length);o.set(i),o.set(a,i.length),await this.vfs.writeFile(r,o)}async exists(e){let t=I(e);if(t===`/usr`||t===`/usr/bin`)return!0;if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);return e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e)}return this.vfs.exists(t)}async stat(e){let t=I(e);if(t===`/usr`||t===`/usr/bin`)return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)};if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);if(e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e))return{isFile:!0,isDirectory:!1,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)}}let n=await this.vfs.stat(t);return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!1,mode:n.type===`directory`?493:420,size:n.size,mtime:new Date(n.mtime)}}async lstat(e){return this.stat(e)}async mkdir(e,t){await this.vfs.mkdir(I(e),t)}async readdir(e){let t=I(e);return t===`/usr`?[`bin`]:t===`/usr/bin`?this.getVirtualBinCommands().slice().sort():(await this.vfs.readDir(t)).map(e=>e.name)}async readdirWithFileTypes(e){let t=I(e);return t===`/usr`?[{name:`bin`,isFile:!1,isDirectory:!0,isSymbolicLink:!1}]:t===`/usr/bin`?this.getVirtualBinCommands().slice().sort().map(e=>({name:e,isFile:!0,isDirectory:!1,isSymbolicLink:!1})):(await this.vfs.readDir(t)).map(e=>({name:e.name,isFile:e.type===`file`,isDirectory:e.type===`directory`,isSymbolicLink:!1}))}async rm(e,t){await this.vfs.rm(I(e),t)}async cp(e,t,n){let r=I(e),i=I(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new oe(`EISDIR`,`is a directory`,r);await this.cpDir(r,i)}else await this.vfs.copyFile(r,i)}async cpDir(e,t){await this.vfs.mkdir(t,{recursive:!0});let n=await this.vfs.readDir(e);for(let r of n){let n=L(e,r.name),i=L(t,r.name);r.type===`directory`?await this.cpDir(n,i):await this.vfs.copyFile(n,i)}}async mv(e,t){await this.vfs.rename(I(e),I(t))}resolvePath(e,t){return t.startsWith(`/`)?I(t):I(L(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){throw Error(`Symlinks not supported in VirtualFS`)}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){throw Error(`Symlinks not supported in VirtualFS`)}async realpath(e){return I(e)}async utimes(e,t,n){}},va=t((e=>{e.byteLength=c,e.toByteArray=u,e.fromByteArray=p;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a<o;++a)t[a]=i[a],n[i.charCodeAt(a)]=a;n[45]=62,n[95]=63;function s(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e){var t=s(e),n=t[0],r=t[1];return(n+r)*3/4-r}function l(e,t,n){return(t+n)*3/4-n}function u(e){var t,i=s(e),a=i[0],o=i[1],c=new r(l(e,a,o)),u=0,d=o>0?a-4:a,f;for(f=0;f<d;f+=4)t=n[e.charCodeAt(f)]<<18|n[e.charCodeAt(f+1)]<<12|n[e.charCodeAt(f+2)]<<6|n[e.charCodeAt(f+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,c[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,c[u++]=t>>8&255,c[u++]=t&255),c}function d(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[e&63]}function f(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(d(r));return i.join(``)}function p(e){for(var n,r=e.length,i=r%3,a=[],o=16383,s=0,c=r-i;s<c;s+=o)a.push(f(e,s,s+o>c?c:s+o));return i===1?(n=e[r-1],a.push(t[n>>2]+t[n<<4&63]+`==`)):i===2&&(n=(e[r-2]<<8)+e[r-1],a.push(t[n>>10]+t[n>>4&63]+t[n<<2&63]+`=`)),a.join(``)}})),ya=t((e=>{e.read=function(e,t,n,r,i){var a,o,s=i*8-r-1,c=(1<<s)-1,l=c>>1,u=-7,d=n?i-1:0,f=n?-1:1,p=e[t+d];for(d+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=a*256+e[t+d],d+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=f,u-=8);if(a===0)a=1-l;else if(a===c)return o?NaN:(p?-1:1)*(1/0);else o+=2**r,a-=l;return(p?-1:1)*o*2**(a-r)},e.write=function(e,t,n,r,i,a){var o,s,c,l=a*8-i-1,u=(1<<l)-1,d=u>>1,f=i===23?2**-24-2**-77:0,p=r?0:a-1,m=r?1:-1,h=+(t<0||t===0&&1/t<0);for(t=Math.abs(t),isNaN(t)||t===1/0?(s=+!!isNaN(t),o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=2**-o)<1&&(o--,c*=2),o+d>=1?t+=f/c:t+=f*2**(1-d),t*c>=2&&(o++,c/=2),o+d>=u?(s=0,o=u):o+d>=1?(s=(t*c-1)*2**i,o+=d):(s=t*2**(d-1)*2**i,o=0));i>=8;e[n+p]=s&255,p+=m,s/=256,i-=8);for(o=o<<i|s,l+=i;l>0;e[n+p]=o&255,p+=m,o/=256,l-=8);e[n+p-m]|=h*128}})),ba=t((e=>{var t=va(),n=ya(),r=typeof Symbol==`function`&&typeof Symbol.for==`function`?Symbol.for(`nodejs.util.inspect.custom`):null;e.Buffer=s,e.SlowBuffer=v,e.INSPECT_MAX_BYTES=50;var i=2147483647;e.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=a(),!s.TYPED_ARRAY_SUPPORT&&typeof console<`u`&&typeof console.error==`function`&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),e.foo()===42}catch{return!1}}Object.defineProperty(s.prototype,`parent`,{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,`offset`,{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}});function o(e){if(e>i)throw RangeError(`The value "`+e+`" is invalid for option "size"`);let t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if(typeof e==`number`){if(typeof t==`string`)throw TypeError(`The "string" argument must be of type string. Received type number`);return d(e)}return c(e,t,n)}s.poolSize=8192;function c(e,t,n){if(typeof e==`string`)return f(e,t);if(ArrayBuffer.isView(e))return m(e);if(e==null)throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e);if(_e(e,ArrayBuffer)||e&&_e(e.buffer,ArrayBuffer)||typeof SharedArrayBuffer<`u`&&(_e(e,SharedArrayBuffer)||e&&_e(e.buffer,SharedArrayBuffer)))return h(e,t,n);if(typeof e==`number`)throw TypeError(`The "value" argument must not be of type number. Received type number`);let r=e.valueOf&&e.valueOf();if(r!=null&&r!==e)return s.from(r,t,n);let i=g(e);if(i)return i;if(typeof Symbol<`u`&&Symbol.toPrimitive!=null&&typeof e[Symbol.toPrimitive]==`function`)return s.from(e[Symbol.toPrimitive](`string`),t,n);throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e)}s.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array);function l(e){if(typeof e!=`number`)throw TypeError(`"size" argument must be of type number`);if(e<0)throw RangeError(`The value "`+e+`" is invalid for option "size"`)}function u(e,t,n){return l(e),e<=0||t===void 0?o(e):typeof n==`string`?o(e).fill(t,n):o(e).fill(t)}s.alloc=function(e,t,n){return u(e,t,n)};function d(e){return l(e),o(e<0?0:_(e)|0)}s.allocUnsafe=function(e){return d(e)},s.allocUnsafeSlow=function(e){return d(e)};function f(e,t){if((typeof t!=`string`||t===``)&&(t=`utf8`),!s.isEncoding(t))throw TypeError(`Unknown encoding: `+t);let n=y(e,t)|0,r=o(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}function p(e){let t=e.length<0?0:_(e.length)|0,n=o(t);for(let r=0;r<t;r+=1)n[r]=e[r]&255;return n}function m(e){if(_e(e,Uint8Array)){let t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return p(e)}function h(e,t,n){if(t<0||e.byteLength<t)throw RangeError(`"offset" is outside of buffer bounds`);if(e.byteLength<t+(n||0))throw RangeError(`"length" is outside of buffer bounds`);let r;return r=t===void 0&&n===void 0?new Uint8Array(e):n===void 0?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,s.prototype),r}function g(e){if(s.isBuffer(e)){let t=_(e.length)|0,n=o(t);return n.length===0||e.copy(n,0,0,t),n}if(e.length!==void 0)return typeof e.length!=`number`||ve(e.length)?o(0):p(e);if(e.type===`Buffer`&&Array.isArray(e.data))return p(e.data)}function _(e){if(e>=i)throw RangeError(`Attempt to allocate Buffer larger than maximum size: 0x`+i.toString(16)+` bytes`);return e|0}function v(e){return+e!=e&&(e=0),s.alloc(+e)}s.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==s.prototype},s.compare=function(e,t){if(_e(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),_e(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw TypeError(`The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array`);if(e===t)return 0;let n=e.length,r=t.length;for(let i=0,a=Math.min(n,r);i<a;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:+(r<n)},s.isEncoding=function(e){switch(String(e).toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`latin1`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw TypeError(`"list" argument must be an Array of Buffers`);if(e.length===0)return s.alloc(0);let n;if(t===void 0)for(t=0,n=0;n<e.length;++n)t+=e[n].length;let r=s.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){let t=e[n];if(_e(t,Uint8Array))i+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,i)):Uint8Array.prototype.set.call(r,t,i);else if(s.isBuffer(t))t.copy(r,i);else throw TypeError(`"list" argument must be an Array of Buffers`);i+=t.length}return r};function y(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||_e(e,ArrayBuffer))return e.byteLength;if(typeof e!=`string`)throw TypeError(`The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type `+typeof e);let n=e.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&n===0)return 0;let i=!1;for(;;)switch(t){case`ascii`:case`latin1`:case`binary`:return n;case`utf8`:case`utf-8`:return pe(e).length;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return n*2;case`hex`:return n>>>1;case`base64`:return he(e).length;default:if(i)return r?-1:pe(e).length;t=(``+t).toLowerCase(),i=!0}}s.byteLength=y;function b(e,t,n){let r=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((n===void 0||n>this.length)&&(n=this.length),n<=0)||(n>>>=0,t>>>=0,n<=t))return``;for(e||=`utf8`;;)switch(e){case`hex`:return re(this,t,n);case`utf8`:case`utf-8`:return A(this,t,n);case`ascii`:return te(this,t,n);case`latin1`:case`binary`:return ne(this,t,n);case`base64`:return k(this,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return ie(this,t,n);default:if(r)throw TypeError(`Unknown encoding: `+e);e=(e+``).toLowerCase(),r=!0}}s.prototype._isBuffer=!0;function x(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}s.prototype.swap16=function(){let e=this.length;if(e%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(let t=0;t<e;t+=2)x(this,t,t+1);return this},s.prototype.swap32=function(){let e=this.length;if(e%4!=0)throw RangeError(`Buffer size must be a multiple of 32-bits`);for(let t=0;t<e;t+=4)x(this,t,t+3),x(this,t+1,t+2);return this},s.prototype.swap64=function(){let e=this.length;if(e%8!=0)throw RangeError(`Buffer size must be a multiple of 64-bits`);for(let t=0;t<e;t+=8)x(this,t,t+7),x(this,t+1,t+6),x(this,t+2,t+5),x(this,t+3,t+4);return this},s.prototype.toString=function(){let e=this.length;return e===0?``:arguments.length===0?A(this,0,e):b.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw TypeError(`Argument must be a Buffer`);return this===e?!0:s.compare(this,e)===0},s.prototype.inspect=function(){let t=``,n=e.INSPECT_MAX_BYTES;return t=this.toString(`hex`,0,n).replace(/(.{2})/g,`$1 `).trim(),this.length>n&&(t+=` ... `),`<Buffer `+t+`>`},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(_e(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw TypeError(`The "target" argument must be one of type Buffer or Uint8Array. Received type `+typeof e);if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),r===void 0&&(r=0),i===void 0&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw RangeError(`out of range index`);if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;let a=i-r,o=n-t,c=Math.min(a,o),l=this.slice(r,i),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){a=l[e],o=u[e];break}return a<o?-1:+(o<a)};function S(e,t,n,r,i){if(e.length===0)return-1;if(typeof n==`string`?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,ve(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0)if(i)n=0;else return-1;if(typeof t==`string`&&(t=s.from(t,r)),s.isBuffer(t))return t.length===0?-1:C(e,t,n,r,i);if(typeof t==`number`)return t&=255,typeof Uint8Array.prototype.indexOf==`function`?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):C(e,[t],n,r,i);throw TypeError(`val must be string, number or Buffer`)}function C(e,t,n,r,i){let a=1,o=e.length,s=t.length;if(r!==void 0&&(r=String(r).toLowerCase(),r===`ucs2`||r===`ucs-2`||r===`utf16le`||r===`utf-16le`)){if(e.length<2||t.length<2)return-1;a=2,o/=2,s/=2,n/=2}function c(e,t){return a===1?e[t]:e.readUInt16BE(t*a)}let l;if(i){let r=-1;for(l=n;l<o;l++)if(c(e,l)===c(t,r===-1?0:l-r)){if(r===-1&&(r=l),l-r+1===s)return r*a}else r!==-1&&(l-=l-r),r=-1}else for(n+s>o&&(n=o-s),l=n;l>=0;l--){let n=!0;for(let r=0;r<s;r++)if(c(e,l+r)!==c(t,r)){n=!1;break}if(n)return l}return-1}s.prototype.includes=function(e,t,n){return this.indexOf(e,t,n)!==-1},s.prototype.indexOf=function(e,t,n){return S(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return S(this,e,t,n,!1)};function w(e,t,n,r){n=Number(n)||0;let i=e.length-n;r?(r=Number(r),r>i&&(r=i)):r=i;let a=t.length;r>a/2&&(r=a/2);let o;for(o=0;o<r;++o){let r=parseInt(t.substr(o*2,2),16);if(ve(r))return o;e[n+o]=r}return o}function T(e,t,n,r){return ge(pe(t,e.length-n),e,n,r)}function E(e,t,n,r){return ge(me(t),e,n,r)}function D(e,t,n,r){return ge(he(t),e,n,r)}function O(e,t,n,r){return ge(B(t,e.length-n),e,n,r)}s.prototype.write=function(e,t,n,r){if(t===void 0)r=`utf8`,n=this.length,t=0;else if(n===void 0&&typeof t==`string`)r=t,n=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(n)?(n>>>=0,r===void 0&&(r=`utf8`)):(r=n,n=void 0);else throw Error(`Buffer.write(string, encoding, offset[, length]) is no longer supported`);let i=this.length-t;if((n===void 0||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw RangeError(`Attempt to write outside buffer bounds`);r||=`utf8`;let a=!1;for(;;)switch(r){case`hex`:return w(this,e,t,n);case`utf8`:case`utf-8`:return T(this,e,t,n);case`ascii`:case`latin1`:case`binary`:return E(this,e,t,n);case`base64`:return D(this,e,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return O(this,e,t,n);default:if(a)throw TypeError(`Unknown encoding: `+r);r=(``+r).toLowerCase(),a=!0}},s.prototype.toJSON=function(){return{type:`Buffer`,data:Array.prototype.slice.call(this._arr||this,0)}};function k(e,n,r){return n===0&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function A(e,t,n){n=Math.min(e.length,n);let r=[],i=t;for(;i<n;){let t=e[i],a=null,o=t>239?4:t>223?3:t>191?2:1;if(i+o<=n){let n,r,s,c;switch(o){case 1:t<128&&(a=t);break;case 2:n=e[i+1],(n&192)==128&&(c=(t&31)<<6|n&63,c>127&&(a=c));break;case 3:n=e[i+1],r=e[i+2],(n&192)==128&&(r&192)==128&&(c=(t&15)<<12|(n&63)<<6|r&63,c>2047&&(c<55296||c>57343)&&(a=c));break;case 4:n=e[i+1],r=e[i+2],s=e[i+3],(n&192)==128&&(r&192)==128&&(s&192)==128&&(c=(t&15)<<18|(n&63)<<12|(r&63)<<6|s&63,c>65535&&c<1114112&&(a=c))}}a===null?(a=65533,o=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|a&1023),r.push(a),i+=o}return j(r)}var ee=4096;function j(e){let t=e.length;if(t<=ee)return String.fromCharCode.apply(String,e);let n=``,r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=ee));return n}function te(e,t,n){let r=``;n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]&127);return r}function ne(e,t,n){let r=``;n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function re(e,t,n){let r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let i=``;for(let r=t;r<n;++r)i+=ye[e[r]];return i}function ie(e,t,n){let r=e.slice(t,n),i=``;for(let e=0;e<r.length-1;e+=2)i+=String.fromCharCode(r[e]+r[e+1]*256);return i}s.prototype.slice=function(e,t){let n=this.length;e=~~e,t=t===void 0?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t<e&&(t=e);let r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r};function M(e,t,n){if(e%1!=0||e<0)throw RangeError(`offset is not uint`);if(e+t>n)throw RangeError(`Trying to access beyond buffer length`)}s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e],i=1,a=0;for(;++a<t&&(i*=256);)r+=this[e+a]*i;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=be(function(e){e>>>=0,le(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&ue(e,this.length-8);let r=t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,i=this[++e]+this[++e]*2**8+this[++e]*2**16+n*2**24;return BigInt(r)+(BigInt(i)<<BigInt(32))}),s.prototype.readBigUInt64BE=be(function(e){e>>>=0,le(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&ue(e,this.length-8);let r=t*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],i=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n;return(BigInt(r)<<BigInt(32))+BigInt(i)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e],i=1,a=0;for(;++a<t&&(i*=256);)r+=this[e+a]*i;return i*=128,r>=i&&(r-=2**(8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=t,i=1,a=this[e+--r];for(;r>0&&(i*=256);)a+=this[e+--r]*i;return i*=128,a>=i&&(a-=2**(8*t)),a},s.prototype.readInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||M(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||M(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=be(function(e){e>>>=0,le(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&ue(e,this.length-8);let r=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24)}),s.prototype.readBigInt64BE=be(function(e){e>>>=0,le(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&ue(e,this.length-8);let r=(t<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||M(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||M(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||M(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||M(e,8,this.length),n.read(this,e,!1,52,8)};function N(e,t,n,r,i,a){if(!s.isBuffer(e))throw TypeError(`"buffer" argument must be a Buffer instance`);if(t>i||t<a)throw RangeError(`"value" argument is out of bounds`);if(n+r>e.length)throw RangeError(`Index out of range`)}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;N(this,e,t,n,r,0)}let i=1,a=0;for(this[t]=e&255;++a<n&&(i*=256);)this[t+a]=e/i&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;N(this,e,t,n,r,0)}let i=n-1,a=1;for(this[t+i]=e&255;--i>=0&&(a*=256);)this[t+i]=e/a&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,255,0),this[t]=e&255,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function P(e,t,n,r,i){ce(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function ae(e,t,n,r,i){ce(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n+7]=a,a>>=8,e[n+6]=a,a>>=8,e[n+5]=a,a>>=8,e[n+4]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}s.prototype.writeBigUInt64LE=be(function(e,t=0){return P(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeBigUInt64BE=be(function(e,t=0){return ae(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);N(this,e,t,n,r-1,-r)}let i=0,a=1,o=0;for(this[t]=e&255;++i<n&&(a*=256);)e<0&&o===0&&this[t+i-1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);N(this,e,t,n,r-1,-r)}let i=n-1,a=1,o=0;for(this[t+i]=e&255;--i>=0&&(a*=256);)e<0&&o===0&&this[t+i+1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4},s.prototype.writeBigInt64LE=be(function(e,t=0){return P(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))}),s.prototype.writeBigInt64BE=be(function(e,t=0){return ae(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))});function F(e,t,n,r,i,a){if(n+r>e.length||n<0)throw RangeError(`Index out of range`)}function I(e,t,r,i,a){return t=+t,r>>>=0,a||F(e,t,r,4,34028234663852886e22,-34028234663852886e22),n.write(e,t,r,i,23,4),r+4}s.prototype.writeFloatLE=function(e,t,n){return I(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return I(this,e,t,!1,n)};function L(e,t,r,i,a){return t=+t,r>>>=0,a||F(e,t,r,8,17976931348623157e292,-17976931348623157e292),n.write(e,t,r,i,52,8),r+8}s.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw TypeError(`argument should be a Buffer`);if(n||=0,!r&&r!==0&&(r=this.length),t>=e.length&&(t=e.length),t||=0,r>0&&r<n&&(r=n),r===n||e.length===0||this.length===0)return 0;if(t<0)throw RangeError(`targetStart out of bounds`);if(n<0||n>=this.length)throw RangeError(`Index out of range`);if(r<0)throw RangeError(`sourceEnd out of bounds`);r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);let i=r-n;return this===e&&typeof Uint8Array.prototype.copyWithin==`function`?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),i},s.prototype.fill=function(e,t,n,r){if(typeof e==`string`){if(typeof t==`string`?(r=t,t=0,n=this.length):typeof n==`string`&&(r=n,n=this.length),r!==void 0&&typeof r!=`string`)throw TypeError(`encoding must be a string`);if(typeof r==`string`&&!s.isEncoding(r))throw TypeError(`Unknown encoding: `+r);if(e.length===1){let t=e.charCodeAt(0);(r===`utf8`&&t<128||r===`latin1`)&&(e=t)}}else typeof e==`number`?e&=255:typeof e==`boolean`&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw RangeError(`Out of range index`);if(n<=t)return this;t>>>=0,n=n===void 0?this.length:n>>>0,e||=0;let i;if(typeof e==`number`)for(i=t;i<n;++i)this[i]=e;else{let a=s.isBuffer(e)?e:s.from(e,r),o=a.length;if(o===0)throw TypeError(`The value "`+e+`" is invalid for argument "value"`);for(i=0;i<n-t;++i)this[i+t]=a[i%o]}return this};var R={};function z(e,t,n){R[e]=class extends n{constructor(){super(),Object.defineProperty(this,`message`,{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,`code`,{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}z(`ERR_BUFFER_OUT_OF_BOUNDS`,function(e){return e?`${e} is outside of buffer bounds`:`Attempt to access memory outside buffer bounds`},RangeError),z(`ERR_INVALID_ARG_TYPE`,function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),z(`ERR_OUT_OF_RANGE`,function(e,t,n){let r=`The value of "${e}" is out of range.`,i=n;return Number.isInteger(n)&&Math.abs(n)>2**32?i=oe(String(n)):typeof n==`bigint`&&(i=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(i=oe(i)),i+=`n`),r+=` It must be ${t}. Received ${i}`,r},RangeError);function oe(e){let t=``,n=e.length,r=+(e[0]===`-`);for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function se(e,t,n){le(t,`offset`),(e[t]===void 0||e[t+n]===void 0)&&ue(t,e.length-(n+1))}function ce(e,t,n,r,i,a){if(e>n||e<t){let r=typeof t==`bigint`?`n`:``,i;throw i=a>3?t===0||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${(a+1)*8}${r}`:`>= -(2${r} ** ${(a+1)*8-1}${r}) and < 2 ** ${(a+1)*8-1}${r}`:`>= ${t}${r} and <= ${n}${r}`,new R.ERR_OUT_OF_RANGE(`value`,i,e)}se(r,i,a)}function le(e,t){if(typeof e!=`number`)throw new R.ERR_INVALID_ARG_TYPE(t,`number`,e)}function ue(e,t,n){throw Math.floor(e)===e?t<0?new R.ERR_BUFFER_OUT_OF_BOUNDS:new R.ERR_OUT_OF_RANGE(n||`offset`,`>= ${+!!n} and <= ${t}`,e):(le(e,n),new R.ERR_OUT_OF_RANGE(n||`offset`,`an integer`,e))}var de=/[^+/0-9A-Za-z-_]/g;function fe(e){if(e=e.split(`=`)[0],e=e.trim().replace(de,``),e.length<2)return``;for(;e.length%4!=0;)e+=`=`;return e}function pe(e,t){t||=1/0;let n,r=e.length,i=null,a=[];for(let o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}else if(o+1===r){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if(--t<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,n&63|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,n&63|128)}else if(n<1114112){if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,n&63|128)}else throw Error(`Invalid code point`)}return a}function me(e){let t=[];for(let n=0;n<e.length;++n)t.push(e.charCodeAt(n)&255);return t}function B(e,t){let n,r,i,a=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,i=n%256,a.push(i),a.push(r);return a}function he(e){return t.toByteArray(fe(e))}function ge(e,t,n,r){let i;for(i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function _e(e,t){return e instanceof t||e!=null&&e.constructor!=null&&e.constructor.name!=null&&e.constructor.name===t.name}function ve(e){return e!==e}var ye=(function(){let e=`0123456789abcdef`,t=Array(256);for(let n=0;n<16;++n){let r=n*16;for(let i=0;i<16;++i)t[r+i]=e[n]+e[i]}return t})();function be(e){return typeof BigInt>`u`?xe:e}function xe(){throw Error(`BigInt not supported`)}})),xa=ba();globalThis.Buffer===void 0&&(globalThis.Buffer=xa.Buffer);var Sa=t(((e,t)=>{var n=function(e){if(e||={},this.Promise=e.Promise||Promise,this.queues=Object.create(null),this.domainReentrant=e.domainReentrant||!1,this.domainReentrant){if(typeof process>`u`||process.domain===void 0)throw Error("Domain-reentrant locks require `process.domain` to exist. Please flip `opts.domainReentrant = false`, use a NodeJS version that still implements Domain, or install a browser polyfill.");this.domains=Object.create(null)}this.timeout=e.timeout||n.DEFAULT_TIMEOUT,this.maxOccupationTime=e.maxOccupationTime||n.DEFAULT_MAX_OCCUPATION_TIME,this.maxExecutionTime=e.maxExecutionTime||n.DEFAULT_MAX_EXECUTION_TIME,e.maxPending===1/0||Number.isInteger(e.maxPending)&&e.maxPending>=0?this.maxPending=e.maxPending:this.maxPending=n.DEFAULT_MAX_PENDING};n.DEFAULT_TIMEOUT=0,n.DEFAULT_MAX_OCCUPATION_TIME=0,n.DEFAULT_MAX_EXECUTION_TIME=0,n.DEFAULT_MAX_PENDING=1e3,n.prototype.acquire=function(e,t,n,r){if(Array.isArray(e))return this._acquireBatch(e,t,n,r);if(typeof t!=`function`)throw Error(`You must pass a function to execute`);var i=null,a=null,o=null;typeof n!=`function`&&(r=n,n=null,o=new this.Promise(function(e,t){i=e,a=t})),r||={};var s=!1,c=null,l=null,u=null,d=this,f=function(t,r,c){l&&=(clearTimeout(l),null),u&&=(clearTimeout(u),null),t&&(d.queues[e]&&d.queues[e].length===0&&delete d.queues[e],d.domainReentrant&&delete d.domains[e]),s||=(o?r?a(r):i(c):typeof n==`function`&&n(r,c),!0),t&&d.queues[e]&&d.queues[e].length>0&&d.queues[e].shift()()},p=function(n){if(s)return f(n);c&&=(clearTimeout(c),null),d.domainReentrant&&n&&(d.domains[e]=process.domain);var i=r.maxExecutionTime||d.maxExecutionTime;if(i&&(u=setTimeout(function(){d.queues[e]&&f(n,Error(`Maximum execution time is exceeded `+e))},i)),t.length===1){var a=!1;try{t(function(e,t){a||(a=!0,f(n,e,t))})}catch(e){a||(a=!0,f(n,e))}}else d._promiseTry(function(){return t()}).then(function(e){f(n,void 0,e)},function(e){f(n,e)})};d.domainReentrant&&process.domain&&(p=process.domain.bind(p));var m=r.maxPending||d.maxPending;if(!d.queues[e])d.queues[e]=[],p(!0);else if(d.domainReentrant&&process.domain&&process.domain===d.domains[e])p(!1);else if(d.queues[e].length>=m)f(!1,Error(`Too many pending tasks in queue `+e));else{var h=function(){p(!0)};r.skipQueue?d.queues[e].unshift(h):d.queues[e].push(h);var g=r.timeout||d.timeout;g&&(c=setTimeout(function(){c=null,f(!1,Error(`async-lock timed out in queue `+e))},g))}var _=r.maxOccupationTime||d.maxOccupationTime;if(_&&(l=setTimeout(function(){d.queues[e]&&f(!1,Error(`Maximum occupation time is exceeded in queue `+e))},_)),o)return o},n.prototype._acquireBatch=function(e,t,n,r){typeof n!=`function`&&(r=n,n=null);var i=this,a=function(e,t){return function(n){i.acquire(e,t,n,r)}},o=e.reduceRight(function(e,t){return a(t,e)},t);if(typeof n==`function`)o(n);else return new this.Promise(function(e,t){o.length===1?o(function(n,r){n?t(n):e(r)}):e(o())})},n.prototype.isBusy=function(e){return e?!!this.queues[e]:Object.keys(this.queues).length>0},n.prototype._promiseTry=function(e){try{return this.Promise.resolve(e())}catch(e){return this.Promise.reject(e)}},t.exports=n})),Ca=t(((e,t)=>{t.exports=Sa()})),wa=t(((e,t)=>{typeof Object.create==`function`?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}})),Ta=t(((e,t)=>{var n=ba(),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=n:(i(n,e),e.Buffer=a);function a(e,t,n){return r(e,t,n)}a.prototype=Object.create(r.prototype),i(r,a),a.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return r(e,t,n)},a.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var i=r(e);return t===void 0?i.fill(0):typeof n==`string`?i.fill(t,n):i.fill(t),i},a.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r(e)},a.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return n.SlowBuffer(e)}})),Ea=t(((e,t)=>{var n={}.toString;t.exports=Array.isArray||function(e){return n.call(e)==`[object Array]`}})),Da=t(((e,t)=>{t.exports=TypeError})),Oa=t(((e,t)=>{t.exports=Object})),ka=t(((e,t)=>{t.exports=Error})),Aa=t(((e,t)=>{t.exports=EvalError})),ja=t(((e,t)=>{t.exports=RangeError})),Ma=t(((e,t)=>{t.exports=ReferenceError})),Na=t(((e,t)=>{t.exports=SyntaxError})),Pa=t(((e,t)=>{t.exports=URIError})),Fa=t(((e,t)=>{t.exports=Math.abs})),Ia=t(((e,t)=>{t.exports=Math.floor})),La=t(((e,t)=>{t.exports=Math.max})),Ra=t(((e,t)=>{t.exports=Math.min})),za=t(((e,t)=>{t.exports=Math.pow})),Ba=t(((e,t)=>{t.exports=Math.round})),Va=t(((e,t)=>{t.exports=Number.isNaN||function(e){return e!==e}})),Ha=t(((e,t)=>{var n=Va();t.exports=function(e){return n(e)||e===0?e:e<0?-1:1}})),Ua=t(((e,t)=>{t.exports=Object.getOwnPropertyDescriptor})),Wa=t(((e,t)=>{var n=Ua();if(n)try{n([],`length`)}catch{n=null}t.exports=n})),Ga=t(((e,t)=>{var n=Object.defineProperty||!1;if(n)try{n({},`a`,{value:1})}catch{n=!1}t.exports=n})),Ka=t(((e,t)=>{t.exports=function(){if(typeof Symbol!=`function`||typeof Object.getOwnPropertySymbols!=`function`)return!1;if(typeof Symbol.iterator==`symbol`)return!0;var e={},t=Symbol(`test`),n=Object(t);if(typeof t==`string`||Object.prototype.toString.call(t)!==`[object Symbol]`||Object.prototype.toString.call(n)!==`[object Symbol]`)return!1;var r=42;for(var i in e[t]=r,e)return!1;if(typeof Object.keys==`function`&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames==`function`&&Object.getOwnPropertyNames(e).length!==0)return!1;var a=Object.getOwnPropertySymbols(e);if(a.length!==1||a[0]!==t||!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if(typeof Object.getOwnPropertyDescriptor==`function`){var o=Object.getOwnPropertyDescriptor(e,t);if(o.value!==r||o.enumerable!==!0)return!1}return!0}})),qa=t(((e,t)=>{var n=typeof Symbol<`u`&&Symbol,r=Ka();t.exports=function(){return typeof n!=`function`||typeof Symbol!=`function`||typeof n(`foo`)!=`symbol`||typeof Symbol(`bar`)!=`symbol`?!1:r()}})),Ja=t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect.getPrototypeOf||null})),Ya=t(((e,t)=>{t.exports=Oa().getPrototypeOf||null})),Xa=t(((e,t)=>{var n=`Function.prototype.bind called on incompatible `,r=Object.prototype.toString,i=Math.max,a=`[object Function]`,o=function(e,t){for(var n=[],r=0;r<e.length;r+=1)n[r]=e[r];for(var i=0;i<t.length;i+=1)n[i+e.length]=t[i];return n},s=function(e,t){for(var n=[],r=t||0,i=0;r<e.length;r+=1,i+=1)n[i]=e[r];return n},c=function(e,t){for(var n=``,r=0;r<e.length;r+=1)n+=e[r],r+1<e.length&&(n+=t);return n};t.exports=function(e){var t=this;if(typeof t!=`function`||r.apply(t)!==a)throw TypeError(n+t);for(var l=s(arguments,1),u,d=function(){if(this instanceof u){var n=t.apply(this,o(l,arguments));return Object(n)===n?n:this}return t.apply(e,o(l,arguments))},f=i(0,t.length-l.length),p=[],m=0;m<f;m++)p[m]=`$`+m;if(u=Function(`binder`,`return function (`+c(p,`,`)+`){ return binder.apply(this,arguments); }`)(d),t.prototype){var h=function(){};h.prototype=t.prototype,u.prototype=new h,h.prototype=null}return u}})),Za=t(((e,t)=>{var n=Xa();t.exports=Function.prototype.bind||n})),Qa=t(((e,t)=>{t.exports=Function.prototype.call})),$a=t(((e,t)=>{t.exports=Function.prototype.apply})),eo=t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect&&Reflect.apply})),to=t(((e,t)=>{var n=Za(),r=$a(),i=Qa();t.exports=eo()||n.call(i,r)})),no=t(((e,t)=>{var n=Za(),r=Da(),i=Qa(),a=to();t.exports=function(e){if(e.length<1||typeof e[0]!=`function`)throw new r(`a function is required`);return a(n,i,e)}})),ro=t(((e,t)=>{var n=no(),r=Wa(),i;try{i=[].__proto__===Array.prototype}catch(e){if(!e||typeof e!=`object`||!(`code`in e)||e.code!==`ERR_PROTO_ACCESS`)throw e}var a=!!i&&r&&r(Object.prototype,`__proto__`),o=Object,s=o.getPrototypeOf;t.exports=a&&typeof a.get==`function`?n([a.get]):typeof s==`function`?function(e){return s(e==null?e:o(e))}:!1})),io=t(((e,t)=>{var n=Ja(),r=Ya(),i=ro();t.exports=n?function(e){return n(e)}:r?function(e){if(!e||typeof e!=`object`&&typeof e!=`function`)throw TypeError(`getProto: not an object`);return r(e)}:i?function(e){return i(e)}:null})),ao=t(((e,t)=>{var n=Function.prototype.call,r=Object.prototype.hasOwnProperty;t.exports=Za().call(n,r)})),oo=t(((e,t)=>{var n,r=Oa(),i=ka(),a=Aa(),o=ja(),s=Ma(),c=Na(),l=Da(),u=Pa(),d=Fa(),f=Ia(),p=La(),m=Ra(),h=za(),g=Ba(),_=Ha(),v=Function,y=function(e){try{return v(`"use strict"; return (`+e+`).constructor;`)()}catch{}},b=Wa(),x=Ga(),S=function(){throw new l},C=b?function(){try{return arguments.callee,S}catch{try{return b(arguments,`callee`).get}catch{return S}}}():S,w=qa()(),T=io(),E=Ya(),D=Ja(),O=$a(),k=Qa(),A={},ee=typeof Uint8Array>`u`||!T?n:T(Uint8Array),j={__proto__:null,"%AggregateError%":typeof AggregateError>`u`?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>`u`?n:ArrayBuffer,"%ArrayIteratorPrototype%":w&&T?T([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":A,"%AsyncGenerator%":A,"%AsyncGeneratorFunction%":A,"%AsyncIteratorPrototype%":A,"%Atomics%":typeof Atomics>`u`?n:Atomics,"%BigInt%":typeof BigInt>`u`?n:BigInt,"%BigInt64Array%":typeof BigInt64Array>`u`?n:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>`u`?n:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>`u`?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":i,"%eval%":eval,"%EvalError%":a,"%Float16Array%":typeof Float16Array>`u`?n:Float16Array,"%Float32Array%":typeof Float32Array>`u`?n:Float32Array,"%Float64Array%":typeof Float64Array>`u`?n:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>`u`?n:FinalizationRegistry,"%Function%":v,"%GeneratorFunction%":A,"%Int8Array%":typeof Int8Array>`u`?n:Int8Array,"%Int16Array%":typeof Int16Array>`u`?n:Int16Array,"%Int32Array%":typeof Int32Array>`u`?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":w&&T?T(T([][Symbol.iterator]())):n,"%JSON%":typeof JSON==`object`?JSON:n,"%Map%":typeof Map>`u`?n:Map,"%MapIteratorPrototype%":typeof Map>`u`||!w||!T?n:T(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":r,"%Object.getOwnPropertyDescriptor%":b,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>`u`?n:Promise,"%Proxy%":typeof Proxy>`u`?n:Proxy,"%RangeError%":o,"%ReferenceError%":s,"%Reflect%":typeof Reflect>`u`?n:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>`u`?n:Set,"%SetIteratorPrototype%":typeof Set>`u`||!w||!T?n:T(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>`u`?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":w&&T?T(``[Symbol.iterator]()):n,"%Symbol%":w?Symbol:n,"%SyntaxError%":c,"%ThrowTypeError%":C,"%TypedArray%":ee,"%TypeError%":l,"%Uint8Array%":typeof Uint8Array>`u`?n:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>`u`?n:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>`u`?n:Uint16Array,"%Uint32Array%":typeof Uint32Array>`u`?n:Uint32Array,"%URIError%":u,"%WeakMap%":typeof WeakMap>`u`?n:WeakMap,"%WeakRef%":typeof WeakRef>`u`?n:WeakRef,"%WeakSet%":typeof WeakSet>`u`?n:WeakSet,"%Function.prototype.call%":k,"%Function.prototype.apply%":O,"%Object.defineProperty%":x,"%Object.getPrototypeOf%":E,"%Math.abs%":d,"%Math.floor%":f,"%Math.max%":p,"%Math.min%":m,"%Math.pow%":h,"%Math.round%":g,"%Math.sign%":_,"%Reflect.getPrototypeOf%":D};if(T)try{null.error}catch(e){j[`%Error.prototype%`]=T(T(e))}var te=function e(t){var n;if(t===`%AsyncFunction%`)n=y(`async function () {}`);else if(t===`%GeneratorFunction%`)n=y(`function* () {}`);else if(t===`%AsyncGeneratorFunction%`)n=y(`async function* () {}`);else if(t===`%AsyncGenerator%`){var r=e(`%AsyncGeneratorFunction%`);r&&(n=r.prototype)}else if(t===`%AsyncIteratorPrototype%`){var i=e(`%AsyncGenerator%`);i&&T&&(n=T(i.prototype))}return j[t]=n,n},ne={__proto__:null,"%ArrayBufferPrototype%":[`ArrayBuffer`,`prototype`],"%ArrayPrototype%":[`Array`,`prototype`],"%ArrayProto_entries%":[`Array`,`prototype`,`entries`],"%ArrayProto_forEach%":[`Array`,`prototype`,`forEach`],"%ArrayProto_keys%":[`Array`,`prototype`,`keys`],"%ArrayProto_values%":[`Array`,`prototype`,`values`],"%AsyncFunctionPrototype%":[`AsyncFunction`,`prototype`],"%AsyncGenerator%":[`AsyncGeneratorFunction`,`prototype`],"%AsyncGeneratorPrototype%":[`AsyncGeneratorFunction`,`prototype`,`prototype`],"%BooleanPrototype%":[`Boolean`,`prototype`],"%DataViewPrototype%":[`DataView`,`prototype`],"%DatePrototype%":[`Date`,`prototype`],"%ErrorPrototype%":[`Error`,`prototype`],"%EvalErrorPrototype%":[`EvalError`,`prototype`],"%Float32ArrayPrototype%":[`Float32Array`,`prototype`],"%Float64ArrayPrototype%":[`Float64Array`,`prototype`],"%FunctionPrototype%":[`Function`,`prototype`],"%Generator%":[`GeneratorFunction`,`prototype`],"%GeneratorPrototype%":[`GeneratorFunction`,`prototype`,`prototype`],"%Int8ArrayPrototype%":[`Int8Array`,`prototype`],"%Int16ArrayPrototype%":[`Int16Array`,`prototype`],"%Int32ArrayPrototype%":[`Int32Array`,`prototype`],"%JSONParse%":[`JSON`,`parse`],"%JSONStringify%":[`JSON`,`stringify`],"%MapPrototype%":[`Map`,`prototype`],"%NumberPrototype%":[`Number`,`prototype`],"%ObjectPrototype%":[`Object`,`prototype`],"%ObjProto_toString%":[`Object`,`prototype`,`toString`],"%ObjProto_valueOf%":[`Object`,`prototype`,`valueOf`],"%PromisePrototype%":[`Promise`,`prototype`],"%PromiseProto_then%":[`Promise`,`prototype`,`then`],"%Promise_all%":[`Promise`,`all`],"%Promise_reject%":[`Promise`,`reject`],"%Promise_resolve%":[`Promise`,`resolve`],"%RangeErrorPrototype%":[`RangeError`,`prototype`],"%ReferenceErrorPrototype%":[`ReferenceError`,`prototype`],"%RegExpPrototype%":[`RegExp`,`prototype`],"%SetPrototype%":[`Set`,`prototype`],"%SharedArrayBufferPrototype%":[`SharedArrayBuffer`,`prototype`],"%StringPrototype%":[`String`,`prototype`],"%SymbolPrototype%":[`Symbol`,`prototype`],"%SyntaxErrorPrototype%":[`SyntaxError`,`prototype`],"%TypedArrayPrototype%":[`TypedArray`,`prototype`],"%TypeErrorPrototype%":[`TypeError`,`prototype`],"%Uint8ArrayPrototype%":[`Uint8Array`,`prototype`],"%Uint8ClampedArrayPrototype%":[`Uint8ClampedArray`,`prototype`],"%Uint16ArrayPrototype%":[`Uint16Array`,`prototype`],"%Uint32ArrayPrototype%":[`Uint32Array`,`prototype`],"%URIErrorPrototype%":[`URIError`,`prototype`],"%WeakMapPrototype%":[`WeakMap`,`prototype`],"%WeakSetPrototype%":[`WeakSet`,`prototype`]},re=Za(),ie=ao(),M=re.call(k,Array.prototype.concat),N=re.call(O,Array.prototype.splice),P=re.call(k,String.prototype.replace),ae=re.call(k,String.prototype.slice),F=re.call(k,RegExp.prototype.exec),I=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,L=/\\(\\)?/g,R=function(e){var t=ae(e,0,1),n=ae(e,-1);if(t===`%`&&n!==`%`)throw new c("invalid intrinsic syntax, expected closing `%`");if(n===`%`&&t!==`%`)throw new c("invalid intrinsic syntax, expected opening `%`");var r=[];return P(e,I,function(e,t,n,i){r[r.length]=n?P(i,L,`$1`):t||e}),r},z=function(e,t){var n=e,r;if(ie(ne,n)&&(r=ne[n],n=`%`+r[0]+`%`),ie(j,n)){var i=j[n];if(i===A&&(i=te(n)),i===void 0&&!t)throw new l(`intrinsic `+e+` exists, but is not available. Please file an issue!`);return{alias:r,name:n,value:i}}throw new c(`intrinsic `+e+` does not exist!`)};t.exports=function(e,t){if(typeof e!=`string`||e.length===0)throw new l(`intrinsic name must be a non-empty string`);if(arguments.length>1&&typeof t!=`boolean`)throw new l(`"allowMissing" argument must be a boolean`);if(F(/^%?[^%]*%?$/,e)===null)throw new c("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=R(e),r=n.length>0?n[0]:``,i=z(`%`+r+`%`,t),a=i.name,o=i.value,s=!1,u=i.alias;u&&(r=u[0],N(n,M([0,1],u)));for(var d=1,f=!0;d<n.length;d+=1){var p=n[d],m=ae(p,0,1),h=ae(p,-1);if((m===`"`||m===`'`||m==="`"||h===`"`||h===`'`||h==="`")&&m!==h)throw new c(`property names with quotes must have matching quotes`);if((p===`constructor`||!f)&&(s=!0),r+=`.`+p,a=`%`+r+`%`,ie(j,a))o=j[a];else if(o!=null){if(!(p in o)){if(!t)throw new l(`base intrinsic for `+e+` exists, but the property is not available.`);return}if(b&&d+1>=n.length){var g=b(o,p);f=!!g,o=f&&`get`in g&&!(`originalValue`in g.get)?g.get:o[p]}else f=ie(o,p),o=o[p];f&&!s&&(j[a]=o)}}return o}})),so=t(((e,t)=>{var n=oo(),r=no(),i=r([n(`%String.prototype.indexOf%`)]);t.exports=function(e,t){var a=n(e,!!t);return typeof a==`function`&&i(e,`.prototype.`)>-1?r([a]):a}})),co=t(((e,t)=>{var n=Function.prototype.toString,r=typeof Reflect==`object`&&Reflect!==null&&Reflect.apply,i,a;if(typeof r==`function`&&typeof Object.defineProperty==`function`)try{i=Object.defineProperty({},`length`,{get:function(){throw a}}),a={},r(function(){throw 42},null,i)}catch(e){e!==a&&(r=null)}else r=null;var o=/^\s*class\b/,s=function(e){try{var t=n.call(e);return o.test(t)}catch{return!1}},c=function(e){try{return s(e)?!1:(n.call(e),!0)}catch{return!1}},l=Object.prototype.toString,u=`[object Object]`,d=`[object Function]`,f=`[object GeneratorFunction]`,p=`[object HTMLAllCollection]`,m=`[object HTML document.all class]`,h=`[object HTMLCollection]`,g=typeof Symbol==`function`&&!!Symbol.toStringTag,_=!(0 in[,]),v=function(){return!1};if(typeof document==`object`){var y=document.all;l.call(y)===l.call(document.all)&&(v=function(e){if((_||!e)&&(e===void 0||typeof e==`object`))try{var t=l.call(e);return(t===p||t===m||t===h||t===u)&&e(``)==null}catch{}return!1})}t.exports=r?function(e){if(v(e))return!0;if(!e||typeof e!=`function`&&typeof e!=`object`)return!1;try{r(e,null,i)}catch(e){if(e!==a)return!1}return!s(e)&&c(e)}:function(e){if(v(e))return!0;if(!e||typeof e!=`function`&&typeof e!=`object`)return!1;if(g)return c(e);if(s(e))return!1;var t=l.call(e);return t!==d&&t!==f&&!/^\[object HTML/.test(t)?!1:c(e)}})),lo=t(((e,t)=>{var n=co(),r=Object.prototype.toString,i=Object.prototype.hasOwnProperty,a=function(e,t,n){for(var r=0,a=e.length;r<a;r++)i.call(e,r)&&(n==null?t(e[r],r,e):t.call(n,e[r],r,e))},o=function(e,t,n){for(var r=0,i=e.length;r<i;r++)n==null?t(e.charAt(r),r,e):t.call(n,e.charAt(r),r,e)},s=function(e,t,n){for(var r in e)i.call(e,r)&&(n==null?t(e[r],r,e):t.call(n,e[r],r,e))};function c(e){return r.call(e)===`[object Array]`}t.exports=function(e,t,r){if(!n(t))throw TypeError(`iterator must be a function`);var i;arguments.length>=3&&(i=r),c(e)?a(e,t,i):typeof e==`string`?o(e,t,i):s(e,t,i)}})),uo=t(((e,t)=>{t.exports=[`Float16Array`,`Float32Array`,`Float64Array`,`Int8Array`,`Int16Array`,`Int32Array`,`Uint8Array`,`Uint8ClampedArray`,`Uint16Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`]})),fo=t(((e,t)=>{var n=uo(),r=globalThis;t.exports=function(){for(var e=[],t=0;t<n.length;t++)typeof r[n[t]]==`function`&&(e[e.length]=n[t]);return e}})),po=t(((e,t)=>{var n=Ga(),r=Na(),i=Da(),a=Wa();t.exports=function(e,t,o){if(!e||typeof e!=`object`&&typeof e!=`function`)throw new i("`obj` must be an object or a function`");if(typeof t!=`string`&&typeof t!=`symbol`)throw new i("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!=`boolean`&&arguments[3]!==null)throw new i("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!=`boolean`&&arguments[4]!==null)throw new i("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!=`boolean`&&arguments[5]!==null)throw new i("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!=`boolean`)throw new i("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,d=!!a&&a(e,t);if(n)n(e,t,{configurable:l===null&&d?d.configurable:!l,enumerable:s===null&&d?d.enumerable:!s,value:o,writable:c===null&&d?d.writable:!c});else if(u||!s&&!c&&!l)e[t]=o;else throw new r(`This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.`)}})),mo=t(((e,t)=>{var n=Ga(),r=function(){return!!n};r.hasArrayLengthDefineBug=function(){if(!n)return null;try{return n([],`length`,{value:1}).length!==1}catch{return!0}},t.exports=r})),ho=t(((e,t)=>{var n=oo(),r=po(),i=mo()(),a=Wa(),o=Da(),s=n(`%Math.floor%`);t.exports=function(e,t){if(typeof e!=`function`)throw new o("`fn` is not a function");if(typeof t!=`number`||t<0||t>4294967295||s(t)!==t)throw new o("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],c=!0,l=!0;if(`length`in e&&a){var u=a(e,`length`);u&&!u.configurable&&(c=!1),u&&!u.writable&&(l=!1)}return(c||l||!n)&&(i?r(e,`length`,t,!0,!0):r(e,`length`,t)),e}})),go=t(((e,t)=>{var n=Za(),r=$a(),i=to();t.exports=function(){return i(n,r,arguments)}})),_o=t(((e,t)=>{var n=ho(),r=Ga(),i=no(),a=go();t.exports=function(e){var t=i(arguments),r=e.length-(arguments.length-1);return n(t,1+(r>0?r:0),!0)},r?r(t.exports,`apply`,{value:a}):t.exports.apply=a})),vo=t(((e,t)=>{var n=Ka();t.exports=function(){return n()&&!!Symbol.toStringTag}})),yo=t(((e,t)=>{var n=lo(),r=fo(),i=_o(),a=so(),o=Wa(),s=io(),c=a(`Object.prototype.toString`),l=vo()(),u=globalThis,d=r(),f=a(`String.prototype.slice`),p=a(`Array.prototype.indexOf`,!0)||function(e,t){for(var n=0;n<e.length;n+=1)if(e[n]===t)return n;return-1},m={__proto__:null};l&&o&&s?n(d,function(e){var t=new u[e];if(Symbol.toStringTag in t&&s){var n=s(t),r=o(n,Symbol.toStringTag);if(!r&&n&&(r=o(s(n),Symbol.toStringTag)),r&&r.get){var a=i(r.get);m[`$`+e]=a}}}):n(d,function(e){var t=new u[e],n=t.slice||t.set;if(n){var r=i(n);m[`$`+e]=r}});var h=function(e){var t=!1;return n(m,function(n,r){if(!t)try{`$`+n(e)===r&&(t=f(r,1))}catch{}}),t},g=function(e){var t=!1;return n(m,function(n,r){if(!t)try{n(e),t=f(r,1)}catch{}}),t};t.exports=function(e){if(!e||typeof e!=`object`)return!1;if(!l){var t=f(c(e),8,-1);return p(d,t)>-1?t:t===`Object`?g(e):!1}return o?h(e):null}})),bo=t(((e,t)=>{var n=yo();t.exports=function(e){return!!n(e)}})),xo=t(((e,t)=>{var n=Da(),r=so()(`TypedArray.prototype.buffer`,!0),i=bo();t.exports=r||function(e){if(!i(e))throw new n(`Not a Typed Array`);return e.buffer}})),So=t(((e,t)=>{var n=Ta().Buffer,r=Ea(),i=xo(),a=ArrayBuffer.isView||function(e){try{return i(e),!0}catch{return!1}},o=typeof Uint8Array<`u`,s=typeof ArrayBuffer<`u`&&typeof Uint8Array<`u`,c=s&&(n.prototype instanceof Uint8Array||n.TYPED_ARRAY_SUPPORT);t.exports=function(e,t){if(n.isBuffer(e))return e.constructor&&!(`isBuffer`in e)?n.from(e):e;if(typeof e==`string`)return n.from(e,t);if(s&&a(e)){if(e.byteLength===0)return n.alloc(0);if(c){var i=n.from(e.buffer,e.byteOffset,e.byteLength);if(i.byteLength===e.byteLength)return i}var l=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),u=n.from(l);if(u.length===e.byteLength)return u}if(o&&e instanceof Uint8Array)return n.from(e);var d=r(e);if(d)for(var f=0;f<e.length;f+=1){var p=e[f];if(typeof p!=`number`||p<0||p>255||~~p!==p)throw RangeError(`Array items must be numbers in the range 0-255.`)}if(d||n.isBuffer(e)&&e.constructor&&typeof e.constructor.isBuffer==`function`&&e.constructor.isBuffer(e))return n.from(e);throw TypeError(`The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.`)}})),Co=t(((e,t)=>{var n=Ta().Buffer,r=So();function i(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}i.prototype.update=function(e,t){e=r(e,t||`utf8`);for(var n=this._block,i=this._blockSize,a=e.length,o=this._len,s=0;s<a;){for(var c=o%i,l=Math.min(a-s,i-c),u=0;u<l;u++)n[c+u]=e[s+u];o+=l,s+=l,o%i===0&&this._update(n)}return this._len+=a,this},i.prototype.digest=function(e){var t=this._len%this._blockSize;this._block[t]=128,this._block.fill(0,t+1),t>=this._finalSize&&(this._update(this._block),this._block.fill(0));var n=this._len*8;if(n<=4294967295)this._block.writeUInt32BE(n,this._blockSize-4);else{var r=(n&4294967295)>>>0,i=(n-r)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(r,this._blockSize-4)}this._update(this._block);var a=this._hash();return e?a.toString(e):a},i.prototype._update=function(){throw Error(`_update must be implemented by subclass`)},t.exports=i})),wo=t(((e,t)=>{var n=wa(),r=Co(),i=Ta().Buffer,a=[1518500249,1859775393,-1894007588,-899497514],o=Array(80);function s(){this.init(),this._w=o,r.call(this,64,56)}n(s,r),s.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function c(e){return e<<1|e>>>31}function l(e){return e<<5|e>>>27}function u(e){return e<<30|e>>>2}function d(e,t,n,r){return e===0?t&n|~t&r:e===2?t&n|t&r|n&r:t^n^r}s.prototype._update=function(e){for(var t=this._w,n=this._a|0,r=this._b|0,i=this._c|0,o=this._d|0,s=this._e|0,f=0;f<16;++f)t[f]=e.readInt32BE(f*4);for(;f<80;++f)t[f]=c(t[f-3]^t[f-8]^t[f-14]^t[f-16]);for(var p=0;p<80;++p){var m=~~(p/20),h=l(n)+d(m,r,i,o)+s+t[p]+a[m]|0;s=o,o=i,i=u(r),r=n,n=h}this._a=n+this._a|0,this._b=r+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0},s.prototype._hash=function(){var e=i.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e},t.exports=s})),To=t((e=>{(function(t){typeof DO_NOT_EXPORT_CRC>`u`?typeof e==`object`?t(e):typeof define==`function`&&define.amd?define(function(){var e={};return t(e),e}):t({}):t({})})(function(e){e.version=`1.2.2`;function t(){for(var e=0,t=Array(256),n=0;n!=256;++n)e=n,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,t[n]=e;return typeof Int32Array<`u`?new Int32Array(t):t}var n=t();function r(e){var t=0,n=0,r=0,i=typeof Int32Array<`u`?new Int32Array(4096):Array(4096);for(r=0;r!=256;++r)i[r]=e[r];for(r=0;r!=256;++r)for(n=e[r],t=256+r;t<4096;t+=256)n=i[t]=n>>>8^e[n&255];var a=[];for(r=1;r!=16;++r)a[r-1]=typeof Int32Array<`u`?i.subarray(r*256,r*256+256):i.slice(r*256,r*256+256);return a}var i=r(n),a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14];function b(e,t){for(var r=t^-1,i=0,a=e.length;i<a;)r=r>>>8^n[(r^e.charCodeAt(i++))&255];return~r}function x(e,t){for(var r=t^-1,i=e.length-15,b=0;b<i;)r=y[e[b++]^r&255]^v[e[b++]^r>>8&255]^_[e[b++]^r>>16&255]^g[e[b++]^r>>>24]^h[e[b++]]^m[e[b++]]^p[e[b++]]^f[e[b++]]^d[e[b++]]^u[e[b++]]^l[e[b++]]^c[e[b++]]^s[e[b++]]^o[e[b++]]^a[e[b++]]^n[e[b++]];for(i+=15;b<i;)r=r>>>8^n[(r^e[b++])&255];return~r}function S(e,t){for(var r=t^-1,i=0,a=e.length,o=0,s=0;i<a;)o=e.charCodeAt(i++),o<128?r=r>>>8^n[(r^o)&255]:o<2048?(r=r>>>8^n[(r^(192|o>>6&31))&255],r=r>>>8^n[(r^(128|o&63))&255]):o>=55296&&o<57344?(o=(o&1023)+64,s=e.charCodeAt(i++)&1023,r=r>>>8^n[(r^(240|o>>8&7))&255],r=r>>>8^n[(r^(128|o>>2&63))&255],r=r>>>8^n[(r^(128|s>>6&15|(o&3)<<4))&255],r=r>>>8^n[(r^(128|s&63))&255]):(r=r>>>8^n[(r^(224|o>>12&15))&255],r=r>>>8^n[(r^(128|o>>6&63))&255],r=r>>>8^n[(r^(128|o&63))&255]);return~r}e.table=n,e.bstr=b,e.buf=x,e.str=S})})),Eo=t(((e,t)=>{var n=(e,t)=>function(...n){let r=t.promiseModule;return new r((r,i)=>{t.multiArgs?n.push((...e)=>{t.errorFirst?e[0]?i(e):(e.shift(),r(e)):r(e)}):t.errorFirst?n.push((e,t)=>{e?i(e):r(t)}):n.push(r),e.apply(this,n)})};t.exports=(e,t)=>{t=Object.assign({exclude:[/.+(Sync|Stream)$/],errorFirst:!0,promiseModule:Promise},t);let r=typeof e;if(!(e!==null&&(r===`object`||r===`function`)))throw TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${e===null?`null`:r}\``);let i=e=>{let n=t=>typeof t==`string`?e===t:t.test(e);return t.include?t.include.some(n):!t.exclude.some(n)},a;a=r===`function`?function(...r){return t.excludeMain?e(...r):n(e,t).apply(this,r)}:Object.create(Object.getPrototypeOf(e));for(let r in e){let o=e[r];a[r]=typeof o==`function`&&i(r)?n(o,t):o}return a}})),Do=t(((e,t)=>{function n(e){return Array.isArray(e)?e:[e]}var r=``,i=` `,a=`\\`,o=/^\s+$/,s=/(?:[^\\]|^)\\$/,c=/^\\!/,l=/^\\#/,u=/\r?\n/g,d=/^\.*\/|^\.+$/,f=`/`,p=`node-ignore`;typeof Symbol<`u`&&(p=Symbol.for(`node-ignore`));var m=p,h=(e,t,n)=>Object.defineProperty(e,t,{value:n}),g=/([0-z])-([0-z])/g,_=()=>!1,v=e=>e.replace(g,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:r),y=e=>{let{length:t}=e;return e.slice(0,t-t%2)},b=[[/^\uFEFF/,()=>r],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf(`\\`)===0?i:r)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+i}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>t+n.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>a],[/\\\\/g,()=>a],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,i)=>t===a?`\\[${n}${y(r)}${i}`:i===`]`&&r.length%2==0?`[${v(n)}${r}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`]],x=Object.create(null),S=(e,t)=>{let n=x[e];return n||(n=b.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),x[e]=n),t?new RegExp(n,`i`):new RegExp(n)},C=e=>typeof e==`string`,w=e=>e&&C(e)&&!o.test(e)&&!s.test(e)&&e.indexOf(`#`)!==0,T=e=>e.split(u),E=class{constructor(e,t,n,r){this.origin=e,this.pattern=t,this.negative=n,this.regex=r}},D=(e,t)=>{let n=e,r=!1;e.indexOf(`!`)===0&&(r=!0,e=e.substr(1)),e=e.replace(c,`!`).replace(l,`#`);let i=S(e,t);return new E(n,e,r,i)},O=(e,t)=>{throw new t(e)},k=(e,t,n)=>C(e)?e?k.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n(`path must not be empty`,TypeError):n(`path must be a string, but got \`${t}\``,TypeError),A=e=>d.test(e);k.isNotRelative=A,k.convert=e=>e;var ee=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){h(this,m,!0),this._rules=[],this._ignoreCase=t,this._allowRelativePaths=n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[m]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(w(e)){let t=D(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,n(C(e)?T(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,t){let n=!1,r=!1;return this._rules.forEach(i=>{let{negative:a}=i;r===a&&n!==r||a&&!n&&!r&&!t||i.regex.test(e)&&(n=!a,r=a)}),{ignored:n,unignored:r}}_test(e,t,n,r){let i=e&&k.convert(e);return k(i,e,this._allowRelativePaths?_:O),this._t(i,t,n,r)}_t(e,t,n,r){if(e in t)return t[e];if(r||=e.split(f),r.pop(),!r.length)return t[e]=this._testOne(e,n);let i=this._t(r.join(f)+f,t,n,r);return t[e]=i.ignored?i:this._testOne(e,n)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return n(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},j=e=>new ee(e);if(j.isPathValid=e=>k(e&&k.convert(e),e,_),j.default=j,t.exports=j,typeof process<`u`&&({}.IGNORE_TEST_WIN32||process.platform===`win32`)){k.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;k.isNotRelative=t=>e.test(t)||A(t)}})),Oo=t(((e,t)=>{function n(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function r(e,t,r){return t=t instanceof RegExp?t:new RegExp(n(t),`g`),e.replace(t,r)}t.exports={clean:function(e){if(typeof e!=`string`)throw Error(`Expected a string, received: `+e);return e=r(e,`./`,`/`),e=r(e,`..`,`.`),e=r(e,` `,`-`),e=r(e,/^[~^:?*\\\-]/g,``),e=r(e,/[~^:?*\\]/g,`-`),e=r(e,/[~^:?*\\\-]$/g,``),e=r(e,`@{`,`-`),e=r(e,/\.$/g,``),e=r(e,/\/$/g,``),e=r(e,/\.lock$/g,``),e}}})),ko=t(((e,t)=>{t.exports=function(e,t){var n=e,r=t,i=n.length,a=r.length,o=!1,s=null,c=i+1,l=[],u=[],d=[],f=``,p=-1,m=0,h=1,g,_,v=function(){i>=a&&(g=n,_=i,n=r,r=g,i=a,a=_,o=!0,c=i+1)},y=function(e,t,n){return{x:e,y:t,k:n}},b=function(e,t){return{elem:e,t}},x=function(e,t,o){var s=t>o?l[e-1+c]:l[e+1+c],d,f=Math.max(t,o);for(d=f-e;d<i&&f<a&&n[d]===r[f];)++d,++f;return l[e+c]=u.length,u[u.length]=new y(d,f,s),f},S=function(e){var t=i=1,i,a=s=0,s,c;for(c=e.length-1;c>=0;--c)for(;a<e[c].x||s<e[c].y;)e[c].y-e[c].x>s-a?(o?d[d.length]=new b(r[s],p):d[d.length]=new b(r[s],h),++i,++s):e[c].y-e[c].x<s-a?(o?d[d.length]=new b(n[a],h):d[d.length]=new b(n[a],p),++t,++a):(d[d.length]=new b(n[a],m),f+=n[a],++t,++i,++a,++s)};return v(),{SES_DELETE:-1,SES_COMMON:0,SES_ADD:1,editdistance:function(){return s},getlcs:function(){return f},getses:function(){return d},compose:function(){var e=a-i,t=i+a+3,n={},r,o,d,f,p;for(f=0;f<t;++f)n[f]=-1,l[f]=-1;r=-1;do{for(++r,p=-r;p<=e-1;++p)n[p+c]=x(p,n[p-1+c]+1,n[p+1+c]);for(p=e+r;p>=e+1;--p)n[p+c]=x(p,n[p-1+c]+1,n[p+1+c]);n[e+c]=x(e,n[e-1+c]+1,n[e+1+c])}while(n[e+c]!==a);for(s=e+2*r,o=l[e+c],d=[];o!==-1;)d[d.length]=new y(u[o].x,u[o].y,null),o=u[o].k;S(d)}}}})),Ao=t(((e,t)=>{var n=ko();function r(e,t){var r=new n(e,t);r.compose();for(var i=r.getses(),a,o,s=e.length-1,c=t.length-1,l=i.length-1;l>=0;--l)i[l].t===r.SES_COMMON?(o?(o.chain={file1index:s,file2index:c,chain:null},o=o.chain):(a={file1index:s,file2index:c,chain:null},o=a),s--,c--):i[l].t===r.SES_DELETE?s--:i[l].t===r.SES_ADD&&c--;var u={file1index:-1,file2index:-1,chain:null};return o?(o.chain=u,a):u}function i(e,t){for(var n=[],i=e.length,a=t.length,o=r(e,t);o!==null;o=o.chain){var s=i-o.file1index-1,c=a-o.file2index-1;i=o.file1index,a=o.file2index,(s||c)&&n.push({file1:[i+1,s],file2:[a+1,c]})}return n.reverse(),n}function a(e,t,n){var r,a=i(t,e),o=i(t,n),s=[];function c(e,t){s.push([e.file1[0],t,e.file1[1],e.file2[0],e.file2[1]])}for(r=0;r<a.length;r++)c(a[r],0);for(r=0;r<o.length;r++)c(o[r],2);s.sort(function(e,t){return e[0]-t[0]});var l=[],u=0;function d(e){e>u&&(l.push([1,u,e-u]),u=e)}for(var f=0;f<s.length;f++){for(var p=f,m=s[f],h=m[0],g=h+m[2];f<s.length-1;){var _=s[f+1],v=_[0];if(v>g)break;g=Math.max(g,v+_[2]),f++}if(d(h),p==f)m[4]>0&&l.push([m[1],m[3],m[4]]);else{var y={0:[e.length,-1,t.length,-1],2:[n.length,-1,t.length,-1]};for(r=p;r<=f;r++){m=s[r];var b=y[m[1]],x=m[0],S=x+m[2],C=m[3],w=C+m[4];b[0]=Math.min(C,b[0]),b[1]=Math.max(w,b[1]),b[2]=Math.min(x,b[2]),b[3]=Math.max(S,b[3])}var T=y[0][0]+(h-y[0][2]),E=y[0][1]+(g-y[0][3]),D=y[2][0]+(h-y[2][2]),O=y[2][1]+(g-y[2][3]);l.push([-1,T,E-T,h,g-h,D,O-D])}u=g}return d(t.length),l}function o(e,t,n){var r=[],i=[e,t,n],o=a(e,t,n),s=[];function c(){s.length&&r.push({ok:s}),s=[]}function l(e){for(var t=0;t<e.length;t++)s.push(e[t])}function u(t){if(t[2]!=t[6])return!0;for(var r=t[1],i=t[5],a=0;a<t[2];a++)if(e[a+r]!=n[a+i])return!0;return!1}for(var d=0;d<o.length;d++){var f=o[d],p=f[0];p==-1?u(f)?(c(),r.push({conflict:{a:e.slice(f[1],f[1]+f[2]),aIndex:f[1],o:t.slice(f[3],f[3]+f[4]),oIndex:f[3],b:n.slice(f[5],f[5]+f[6]),bIndex:f[5]}})):l(i[0].slice(f[1],f[1]+f[2])):l(i[p].slice(f[1],f[1]+f[2]))}return c(),r}t.exports=o})),Y=e(t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e){return e&&typeof e==`object`&&`default`in e?e.default:e}var n=t(Ca()),r=t(wo()),i=t(To()),a=t(Ue()),o=We(),s=t(Eo()),c=t(Do()),l=t(Oo()),u=t(Ao()),d=class e extends Error{constructor(e){super(e),this.caller=``}toJSON(){return{code:this.code,data:this.data,caller:this.caller,message:this.message,stack:this.stack}}fromJSON(t){let n=new e(t.message);return n.code=t.code,n.data=t.data,n.caller=t.caller,n.stack=t.stack,n}get isIsomorphicGitError(){return!0}},f=class e extends d{constructor(t){super(`Modifying the index is not possible because you have unmerged files: ${t.toString}. Fix them up in the work tree, and then use 'git add/rm as appropriate to mark resolution and make a commit.`),this.code=this.name=e.code,this.data={filepaths:t}}};f.code=`UnmergedPathsError`;var p=class e extends d{constructor(t){super(`An internal error caused this command to fail.\n\nIf you're not a developer, report the bug to the developers of the application you're using. If this is a bug in isomorphic-git then you should create a proper bug yourselves. The bug should include a minimal reproduction and details about the version and environment.\n\nPlease file a bug report at https://github.com/isomorphic-git/isomorphic-git/issues with this error message: ${t}`),this.code=this.name=e.code,this.data={message:t}}};p.code=`InternalError`;var m=class e extends d{constructor(t){super(`The filepath "${t}" contains unsafe character sequences`),this.code=this.name=e.code,this.data={filepath:t}}};m.code=`UnsafeFilepathError`;var h=class{constructor(e){this.buffer=e,this._start=0}eof(){return this._start>=this.buffer.length}tell(){return this._start}seek(e){this._start=e}slice(e){let t=this.buffer.slice(this._start,this._start+e);return this._start+=e,t}toString(e,t){let n=this.buffer.toString(e,this._start,this._start+t);return this._start+=t,n}write(e,t,n){let r=this.buffer.write(e,this._start,t,n);return this._start+=t,r}copy(e,t,n){let r=e.copy(this.buffer,this._start,t,n);return this._start+=r,r}readUInt8(){let e=this.buffer.readUInt8(this._start);return this._start+=1,e}writeUInt8(e){let t=this.buffer.writeUInt8(e,this._start);return this._start+=1,t}readUInt16BE(){let e=this.buffer.readUInt16BE(this._start);return this._start+=2,e}writeUInt16BE(e){let t=this.buffer.writeUInt16BE(e,this._start);return this._start+=2,t}readUInt32BE(){let e=this.buffer.readUInt32BE(this._start);return this._start+=4,e}writeUInt32BE(e){let t=this.buffer.writeUInt32BE(e,this._start);return this._start+=4,t}};function g(e,t){return-(e<t)||+(e>t)}function _(e,t){return g(e.path,t.path)}function v(e){let t=e>0?e>>12:0;t!==4&&t!==8&&t!==10&&t!==14&&(t=8);let n=e&511;return n=n&73?493:420,t!==8&&(n=0),(t<<12)+n}var y=2**32;function b(e,t,n,r){if(e!==void 0&&t!==void 0)return[e,t];n===void 0&&(n=r.valueOf());let i=Math.floor(n/1e3);return[i,(n-i*1e3)*1e6]}function x(e){let[t,n]=b(e.ctimeSeconds,e.ctimeNanoseconds,e.ctimeMs,e.ctime),[r,i]=b(e.mtimeSeconds,e.mtimeNanoseconds,e.mtimeMs,e.mtime);return{ctimeSeconds:t%y,ctimeNanoseconds:n%y,mtimeSeconds:r%y,mtimeNanoseconds:i%y,dev:e.dev%y,ino:e.ino%y,mode:v(e.mode%y),uid:e.uid%y,gid:e.gid%y,size:e.size>-1?e.size%y:0}}function S(e){let t=``;for(let n of new Uint8Array(e))n<16&&(t+=`0`),t+=n.toString(16);return t}var C=null;async function w(e){return C===null&&(C=await D()),C?E(e):T(e)}function T(e){return new r().update(e).digest(`hex`)}async function E(e){return S(await crypto.subtle.digest(`SHA-1`,e))}async function D(){try{return await E(new Uint8Array([]))===`da39a3ee5e6b4b0d3255bfef95601890afd80709`}catch{}return!1}function O(e){return{assumeValid:!!(e&32768),extended:!!(e&16384),stage:(e&12288)>>12,nameLength:e&4095}}function k(e){let t=e.flags;return t.extended=!1,t.nameLength=Math.min(Buffer.from(e.path).length,4095),(t.assumeValid?32768:0)+(t.extended?16384:0)+((t.stage&3)<<12)+(t.nameLength&4095)}var A=class e{constructor(e,t){this._dirty=!1,this._unmergedPaths=t||new Set,this._entries=e||new Map}_addEntry(e){if(e.flags.stage===0)e.stages=[e],this._entries.set(e.path,e),this._unmergedPaths.delete(e.path);else{let t=this._entries.get(e.path);t||=(this._entries.set(e.path,e),e),t.stages[e.flags.stage]=e,this._unmergedPaths.add(e.path)}}static async from(t){if(Buffer.isBuffer(t))return e.fromBuffer(t);if(t===null)return new e(null);throw new p(`invalid type passed to GitIndex.from`)}static async fromBuffer(t){if(t.length===0)throw new p(`Index file is empty (.git/index)`);let n=new e,r=new h(t),i=r.toString(`utf8`,4);if(i!==`DIRC`)throw new p(`Invalid dircache magic file number: ${i}`);let a=await w(t.slice(0,-20)),o=t.slice(-20).toString(`hex`);if(o!==a)throw new p(`Invalid checksum in GitIndex buffer: expected ${o} but saw ${a}`);let s=r.readUInt32BE();if(s!==2)throw new p(`Unsupported dircache version: ${s}`);let c=r.readUInt32BE(),l=0;for(;!r.eof()&&l<c;){let e={};e.ctimeSeconds=r.readUInt32BE(),e.ctimeNanoseconds=r.readUInt32BE(),e.mtimeSeconds=r.readUInt32BE(),e.mtimeNanoseconds=r.readUInt32BE(),e.dev=r.readUInt32BE(),e.ino=r.readUInt32BE(),e.mode=r.readUInt32BE(),e.uid=r.readUInt32BE(),e.gid=r.readUInt32BE(),e.size=r.readUInt32BE(),e.oid=r.slice(20).toString(`hex`),e.flags=O(r.readUInt16BE());let i=t.indexOf(0,r.tell()+1)-r.tell();if(i<1)throw new p(`Got a path length of: ${i}`);if(e.path=r.toString(`utf8`,i),e.path.includes(`..\\`)||e.path.includes(`../`))throw new m(e.path);let a=8-(r.tell()-12)%8;for(a===0&&(a=8);a--;){let t=r.readUInt8();if(t!==0)throw new p(`Expected 1-8 null characters but got '${t}' after ${e.path}`);if(r.eof())throw new p(`Unexpected end of file`)}e.stages=[],n._addEntry(e),l++}return n}get unmergedPaths(){return[...this._unmergedPaths]}get entries(){return[...this._entries.values()].sort(_)}get entriesMap(){return this._entries}get entriesFlat(){return[...this.entries].flatMap(e=>e.stages.length>1?e.stages.filter(e=>e):e)}*[Symbol.iterator](){for(let e of this.entries)yield e}insert({filepath:e,stats:t,oid:n,stage:r=0}){t||={ctimeSeconds:0,ctimeNanoseconds:0,mtimeSeconds:0,mtimeNanoseconds:0,dev:0,ino:0,mode:0,uid:0,gid:0,size:0},t=x(t);let i=Buffer.from(e),a={ctimeSeconds:t.ctimeSeconds,ctimeNanoseconds:t.ctimeNanoseconds,mtimeSeconds:t.mtimeSeconds,mtimeNanoseconds:t.mtimeNanoseconds,dev:t.dev,ino:t.ino,mode:t.mode||33188,uid:t.uid,gid:t.gid,size:t.size,path:e,oid:n,flags:{assumeValid:!1,extended:!1,stage:r,nameLength:i.length<4095?i.length:4095},stages:[]};this._addEntry(a),this._dirty=!0}delete({filepath:e}){if(this._entries.has(e))this._entries.delete(e);else for(let t of this._entries.keys())t.startsWith(e+`/`)&&this._entries.delete(t);this._unmergedPaths.has(e)&&this._unmergedPaths.delete(e),this._dirty=!0}clear(){this._entries.clear(),this._dirty=!0}has({filepath:e}){return this._entries.has(e)}render(){return this.entries.map(e=>`${e.mode.toString(8)} ${e.oid} ${e.path}`).join(`
|
|
726
|
+
`)}static async _entryToBuffer(e){let t=Buffer.from(e.path),n=Math.ceil((62+t.length+1)/8)*8,r=Buffer.alloc(n),i=new h(r),a=x(e);return i.writeUInt32BE(a.ctimeSeconds),i.writeUInt32BE(a.ctimeNanoseconds),i.writeUInt32BE(a.mtimeSeconds),i.writeUInt32BE(a.mtimeNanoseconds),i.writeUInt32BE(a.dev),i.writeUInt32BE(a.ino),i.writeUInt32BE(a.mode),i.writeUInt32BE(a.uid),i.writeUInt32BE(a.gid),i.writeUInt32BE(a.size),i.write(e.oid,20,`hex`),i.writeUInt16BE(k(e)),i.write(e.path,t.length,`utf8`),r}async toObject(){let t=Buffer.alloc(12),n=new h(t);n.write(`DIRC`,4,`utf8`),n.writeUInt32BE(2),n.writeUInt32BE(this.entriesFlat.length);let r=[];for(let t of this.entries)if(r.push(e._entryToBuffer(t)),t.stages.length>1)for(let n of t.stages)n&&n!==t&&r.push(e._entryToBuffer(n));r=await Promise.all(r);let i=Buffer.concat(r),a=Buffer.concat([t,i]),o=await w(a);return Buffer.concat([a,Buffer.from(o,`hex`)])}};function ee(e,t,n=!0,r=!0){let i=x(e),a=x(t);return n&&i.mode!==a.mode||i.mtimeSeconds!==a.mtimeSeconds||i.ctimeSeconds!==a.ctimeSeconds||i.uid!==a.uid||i.gid!==a.gid||r&&i.ino!==a.ino||i.size!==a.size}var j=null,te=Symbol(`IndexCache`);function ne(){return{map:new Map,stats:new Map}}async function re(e,t,n){let[r,i]=await Promise.all([e.lstat(t),e.read(t)]),a=await A.from(i);n.map.set(t,a),n.stats.set(t,r)}async function ie(e,t,n){let r=n.stats.get(t);if(r===void 0)return!0;if(r===null)return!1;let i=await e.lstat(t);return i===null?!1:ee(r,i)}var M=class{static async acquire({fs:e,gitdir:t,cache:r,allowUnmerged:i=!0},a){r[te]||(r[te]=ne());let o=`${t}/index`;j===null&&(j=new n({maxPending:1/0}));let s,c=[];return await j.acquire(o,async()=>{let t=r[te];await ie(e,o,t)&&await re(e,o,t);let n=t.map.get(o);if(c=n.unmergedPaths,c.length&&!i)throw new f(c);if(s=await a(n),n._dirty){let r=await n.toObject();await e.write(o,r),t.stats.set(o,await e.lstat(o)),n._dirty=!1}}),s}};function N(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t>-1&&(e=e.slice(t+1)),e}function P(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t===-1?`.`:t===0?`/`:e.slice(0,t)}function ae(e){let t=new Map,n=function(e){if(!t.has(e)){let r={type:`tree`,fullpath:e,basename:N(e),metadata:{},children:[]};t.set(e,r),r.parent=n(P(e)),r.parent&&r.parent!==r&&r.parent.children.push(r)}return t.get(e)},r=function(e,r){if(!t.has(e)){let i={type:`blob`,fullpath:e,basename:N(e),metadata:r,parent:n(P(e)),children:[]};i.parent&&i.parent.children.push(i),t.set(e,i)}return t.get(e)};n(`.`);for(let t of e)r(t.path,t);return t}function F(e){switch(e){case 16384:return`tree`;case 33188:return`blob`;case 33261:return`blob`;case 40960:return`blob`;case 57344:return`commit`}throw new p(`Unexpected GitTree entry mode: ${e.toString(8)}`)}var I=class{constructor({fs:e,gitdir:t,cache:n}){this.treePromise=M.acquire({fs:e,gitdir:t,cache:n},async function(e){return ae(e.entries)});let r=this;this.ConstructEntry=class{constructor(e){this._fullpath=e,this._type=!1,this._mode=!1,this._stat=!1,this._oid=!1}async type(){return r.type(this)}async mode(){return r.mode(this)}async stat(){return r.stat(this)}async content(){return r.content(this)}async oid(){return r.oid(this)}}}async readdir(e){let t=e._fullpath,n=(await this.treePromise).get(t);if(!n||n.type===`blob`)return null;if(n.type!==`tree`)throw Error(`ENOTDIR: not a directory, scandir '${t}'`);let r=n.children.map(e=>e.fullpath);return r.sort(g),r}async type(e){return e._type===!1&&await e.stat(),e._type}async mode(e){return e._mode===!1&&await e.stat(),e._mode}async stat(e){if(e._stat===!1){let t=(await this.treePromise).get(e._fullpath);if(!t)throw Error(`ENOENT: no such file or directory, lstat '${e._fullpath}'`);let n=t.type===`tree`?{}:x(t.metadata);e._type=t.type===`tree`?`tree`:F(n.mode),e._mode=n.mode,t.type===`tree`?e._stat=void 0:e._stat=n}return e._stat}async content(e){}async oid(e){return e._oid===!1&&(e._oid=(await this.treePromise).get(e._fullpath).metadata.oid),e._oid}},L=Symbol(`GitWalkSymbol`);function R(){let e=Object.create(null);return Object.defineProperty(e,L,{value:function({fs:e,gitdir:t,cache:n}){return new I({fs:e,gitdir:t,cache:n})}}),Object.freeze(e),e}var z=class e extends d{constructor(t){super(`Could not find ${t}.`),this.code=this.name=e.code,this.data={what:t}}};z.code=`NotFoundError`;var oe=class e extends d{constructor(t,n,r,i){super(`Object ${t} ${i?`at ${i}`:``}was anticipated to be a ${r} but it is a ${n}.`),this.code=this.name=e.code,this.data={oid:t,actual:n,expected:r,filepath:i}}};oe.code=`ObjectTypeError`;var se=class e extends d{constructor(t){super(`Expected a 40-char hex object id but saw "${t}".`),this.code=this.name=e.code,this.data={value:t}}};se.code=`InvalidOidError`;var ce=class e extends d{constructor(t){super(`Could not find a fetch refspec for remote "${t}". Make sure the config file has an entry like the following:
|
|
727
727
|
[remote "${t}"]
|
|
728
728
|
\tfetch = +refs/heads/*:refs/remotes/origin/*
|
|
729
729
|
`),this.code=this.name=e.code,this.data={remote:t}}};ce.code=`NoRefspecError`;var le=class e{constructor(e){if(this.refs=new Map,this.parsedConfig=[],e){let t=null;this.parsedConfig=e.trim().split(`
|
|
@@ -770,13 +770,13 @@ gpgsig`)),n=e.slice(e.indexOf(`-----END PGP SIGNATURE-----
|
|
|
770
770
|
`)+28);return qt(t+`
|
|
771
771
|
`+n)}isolateSignature(){return $t(this._commit.slice(this._commit.indexOf(`-----BEGIN PGP SIGNATURE-----`),this._commit.indexOf(`-----END PGP SIGNATURE-----`)+27))}static async sign(t,n,r){let i=t.withoutSignature(),a=e.justMessage(t._commit),{signature:o}=await n({payload:i,secretKey:r});o=qt(o);let s=e.justHeaders(t._commit)+`
|
|
772
772
|
gpgsig`+Qt(o)+`
|
|
773
|
-
`+a;return e.from(s)}};async function tn({fs:e,cache:t,gitdir:n,oid:r}){if(r===`4b825dc642cb6eb9a060e54bf8d69288fbee4904`)return{tree:Ge.from([]),oid:r};let{type:i,object:a}=await W({fs:e,cache:t,gitdir:n,oid:r});if(i===`tag`)return r=Zt.from(a).parse().object,tn({fs:e,cache:t,gitdir:n,oid:r});if(i===`commit`)return r=en.from(a).parse().tree,tn({fs:e,cache:t,gitdir:n,oid:r});if(i!==`tree`)throw new oe(r,i,`tree`);return{tree:Ge.from(a),oid:r}}var nn=class{constructor({fs:e,gitdir:t,ref:n,cache:r}){this.fs=e,this.cache=r,this.gitdir=t,this.mapPromise=(async()=>{let r=new Map,i;try{i=await V.resolve({fs:e,gitdir:t,ref:n})}catch(e){e instanceof z&&(i=`4b825dc642cb6eb9a060e54bf8d69288fbee4904`)}let a=await tn({fs:e,cache:this.cache,gitdir:t,oid:i});return a.type=`tree`,a.mode=`40000`,r.set(`.`,a),r})();let i=this;this.ConstructEntry=class{constructor(e){this._fullpath=e,this._type=!1,this._mode=!1,this._stat=!1,this._content=!1,this._oid=!1}async type(){return i.type(this)}async mode(){return i.mode(this)}async stat(){return i.stat(this)}async content(){return i.content(this)}async oid(){return i.oid(this)}}}async readdir(e){let t=e._fullpath,{fs:n,cache:r,gitdir:i}=this,a=await this.mapPromise,o=a.get(t);if(!o)throw Error(`No obj for ${t}`);let s=o.oid;if(!s)throw Error(`No oid for obj ${JSON.stringify(o)}`);if(o.type!==`tree`)return null;let{type:c,object:l}=await W({fs:n,cache:r,gitdir:i,oid:s});if(c!==o.type)throw new oe(s,c,o.type);let u=Ge.from(l);for(let e of u)a.set(B(t,e.path),e);return u.entries().map(e=>B(t,e.path))}async type(e){if(e._type===!1){let{type:t}=(await this.mapPromise).get(e._fullpath);e._type=t}return e._type}async mode(e){if(e._mode===!1){let{mode:t}=(await this.mapPromise).get(e._fullpath);e._mode=v(parseInt(t,8))}return e._mode}async stat(e){}async content(e){if(e._content===!1){let t=await this.mapPromise,{fs:n,cache:r,gitdir:i}=this,a=t.get(e._fullpath).oid,{type:o,object:s}=await W({fs:n,cache:r,gitdir:i,oid:a});o===`blob`?e._content=new Uint8Array(s):e._content=void 0}return e._content}async oid(e){return e._oid===!1&&(e._oid=(await this.mapPromise).get(e._fullpath).oid),e._oid}};function rn({ref:e=`HEAD`}={}){let t=Object.create(null);return Object.defineProperty(t,L,{value:function({fs:t,gitdir:n,cache:r}){return new nn({fs:t,gitdir:n,ref:e,cache:r})}}),Object.freeze(t),t}var an=class{constructor({fs:e,dir:t,gitdir:n,cache:r}){this.fs=e,this.cache=r,this.dir=t,this.gitdir=n,this.config=null;let i=this;this.ConstructEntry=class{constructor(e){this._fullpath=e,this._type=!1,this._mode=!1,this._stat=!1,this._content=!1,this._oid=!1}async type(){return i.type(this)}async mode(){return i.mode(this)}async stat(){return i.stat(this)}async content(){return i.content(this)}async oid(){return i.oid(this)}}}async readdir(e){let t=e._fullpath,{fs:n,dir:r}=this,i=await n.readdir(B(r,t));return i===null?null:i.map(e=>B(t,e))}async type(e){return e._type===!1&&await e.stat(),e._type}async mode(e){return e._mode===!1&&await e.stat(),e._mode}async stat(e){if(e._stat===!1){let{fs:t,dir:n}=this,r=await t.lstat(`${n}/${e._fullpath}`);if(!r)throw Error(`ENOENT: no such file or directory, lstat '${e._fullpath}'`);let i=r.isDirectory()?`tree`:`blob`;i===`blob`&&!r.isFile()&&!r.isSymbolicLink()&&(i=`special`),e._type=i,r=x(r),e._mode=r.mode,r.size===-1&&e._actualSize&&(r.size=e._actualSize),e._stat=r}return e._stat}async content(e){if(e._content===!1){let{fs:t,dir:n,gitdir:r}=this;if(await e.type()===`tree`)e._content=void 0;else{let i;if(await e.mode()>>12==10)i=await t.readlink(`${n}/${e._fullpath}`);else{let a=await(await this._getGitConfig(t,r)).get(`core.autocrlf`);i=await t.read(`${n}/${e._fullpath}`,{autocrlf:a})}e._actualSize=i.length,e._stat&&e._stat.size===-1&&(e._stat.size=e._actualSize),e._content=new Uint8Array(i)}}return e._content}async oid(e){if(e._oid===!1){let t=this,{fs:n,gitdir:r,cache:i}=this,a;await M.acquire({fs:n,gitdir:r,cache:i},async function(i){let o=i.entriesMap.get(e._fullpath),s=await e.stat(),c=await(await t._getGitConfig(n,r)).get(`core.filemode`),l=typeof process<`u`?process.platform!==`win32`:!0;if(!o||
|
|
773
|
+
`+a;return e.from(s)}};async function tn({fs:e,cache:t,gitdir:n,oid:r}){if(r===`4b825dc642cb6eb9a060e54bf8d69288fbee4904`)return{tree:Ge.from([]),oid:r};let{type:i,object:a}=await W({fs:e,cache:t,gitdir:n,oid:r});if(i===`tag`)return r=Zt.from(a).parse().object,tn({fs:e,cache:t,gitdir:n,oid:r});if(i===`commit`)return r=en.from(a).parse().tree,tn({fs:e,cache:t,gitdir:n,oid:r});if(i!==`tree`)throw new oe(r,i,`tree`);return{tree:Ge.from(a),oid:r}}var nn=class{constructor({fs:e,gitdir:t,ref:n,cache:r}){this.fs=e,this.cache=r,this.gitdir=t,this.mapPromise=(async()=>{let r=new Map,i;try{i=await V.resolve({fs:e,gitdir:t,ref:n})}catch(e){e instanceof z&&(i=`4b825dc642cb6eb9a060e54bf8d69288fbee4904`)}let a=await tn({fs:e,cache:this.cache,gitdir:t,oid:i});return a.type=`tree`,a.mode=`40000`,r.set(`.`,a),r})();let i=this;this.ConstructEntry=class{constructor(e){this._fullpath=e,this._type=!1,this._mode=!1,this._stat=!1,this._content=!1,this._oid=!1}async type(){return i.type(this)}async mode(){return i.mode(this)}async stat(){return i.stat(this)}async content(){return i.content(this)}async oid(){return i.oid(this)}}}async readdir(e){let t=e._fullpath,{fs:n,cache:r,gitdir:i}=this,a=await this.mapPromise,o=a.get(t);if(!o)throw Error(`No obj for ${t}`);let s=o.oid;if(!s)throw Error(`No oid for obj ${JSON.stringify(o)}`);if(o.type!==`tree`)return null;let{type:c,object:l}=await W({fs:n,cache:r,gitdir:i,oid:s});if(c!==o.type)throw new oe(s,c,o.type);let u=Ge.from(l);for(let e of u)a.set(B(t,e.path),e);return u.entries().map(e=>B(t,e.path))}async type(e){if(e._type===!1){let{type:t}=(await this.mapPromise).get(e._fullpath);e._type=t}return e._type}async mode(e){if(e._mode===!1){let{mode:t}=(await this.mapPromise).get(e._fullpath);e._mode=v(parseInt(t,8))}return e._mode}async stat(e){}async content(e){if(e._content===!1){let t=await this.mapPromise,{fs:n,cache:r,gitdir:i}=this,a=t.get(e._fullpath).oid,{type:o,object:s}=await W({fs:n,cache:r,gitdir:i,oid:a});o===`blob`?e._content=new Uint8Array(s):e._content=void 0}return e._content}async oid(e){return e._oid===!1&&(e._oid=(await this.mapPromise).get(e._fullpath).oid),e._oid}};function rn({ref:e=`HEAD`}={}){let t=Object.create(null);return Object.defineProperty(t,L,{value:function({fs:t,gitdir:n,cache:r}){return new nn({fs:t,gitdir:n,ref:e,cache:r})}}),Object.freeze(t),t}var an=class{constructor({fs:e,dir:t,gitdir:n,cache:r}){this.fs=e,this.cache=r,this.dir=t,this.gitdir=n,this.config=null;let i=this;this.ConstructEntry=class{constructor(e){this._fullpath=e,this._type=!1,this._mode=!1,this._stat=!1,this._content=!1,this._oid=!1}async type(){return i.type(this)}async mode(){return i.mode(this)}async stat(){return i.stat(this)}async content(){return i.content(this)}async oid(){return i.oid(this)}}}async readdir(e){let t=e._fullpath,{fs:n,dir:r}=this,i=await n.readdir(B(r,t));return i===null?null:i.map(e=>B(t,e))}async type(e){return e._type===!1&&await e.stat(),e._type}async mode(e){return e._mode===!1&&await e.stat(),e._mode}async stat(e){if(e._stat===!1){let{fs:t,dir:n}=this,r=await t.lstat(`${n}/${e._fullpath}`);if(!r)throw Error(`ENOENT: no such file or directory, lstat '${e._fullpath}'`);let i=r.isDirectory()?`tree`:`blob`;i===`blob`&&!r.isFile()&&!r.isSymbolicLink()&&(i=`special`),e._type=i,r=x(r),e._mode=r.mode,r.size===-1&&e._actualSize&&(r.size=e._actualSize),e._stat=r}return e._stat}async content(e){if(e._content===!1){let{fs:t,dir:n,gitdir:r}=this;if(await e.type()===`tree`)e._content=void 0;else{let i;if(await e.mode()>>12==10)i=await t.readlink(`${n}/${e._fullpath}`);else{let a=await(await this._getGitConfig(t,r)).get(`core.autocrlf`);i=await t.read(`${n}/${e._fullpath}`,{autocrlf:a})}e._actualSize=i.length,e._stat&&e._stat.size===-1&&(e._stat.size=e._actualSize),e._content=new Uint8Array(i)}}return e._content}async oid(e){if(e._oid===!1){let t=this,{fs:n,gitdir:r,cache:i}=this,a;await M.acquire({fs:n,gitdir:r,cache:i},async function(i){let o=i.entriesMap.get(e._fullpath),s=await e.stat(),c=await(await t._getGitConfig(n,r)).get(`core.filemode`),l=typeof process<`u`?process.platform!==`win32`:!0;if(!o||ee(s,o,c,l)){let t=await e.content();t===void 0?a=void 0:(a=await w(Ke.wrap({type:`blob`,object:t})),o&&a===o.oid&&(!c||s.mode===o.mode)&&ee(s,o,c,l)&&i.insert({filepath:e._fullpath,stats:s,oid:a}))}else a=o.oid}),e._oid=a}return e._oid}async _getGitConfig(e,t){return this.config||=await Ne.get({fs:e,gitdir:t}),this.config}};function on(){let e=Object.create(null);return Object.defineProperty(e,L,{value:function({fs:e,dir:t,gitdir:n,cache:r}){return new an({fs:e,dir:t,gitdir:n,cache:r})}}),Object.freeze(e),e}function sn(e,t){let n=t-e;return Array.from({length:n},(t,n)=>e+n)}var cn=Array.prototype.flat===void 0?e=>e.reduce((e,t)=>e.concat(t),[]):e=>e.flat(),ln=class{constructor(){this.value=null}consider(e){e!=null&&(this.value===null||e<this.value)&&(this.value=e)}reset(){this.value=null}};function*un(e){let t=new ln,n,r=[],i=e.length;for(let n=0;n<i;n++)r[n]=e[n].next().value,r[n]!==void 0&&t.consider(r[n]);if(t.value!==null)for(;;){let a=[];n=t.value,t.reset();for(let o=0;o<i;o++)r[o]!==void 0&&r[o]===n?(a[o]=r[o],r[o]=e[o].next().value):a[o]=null,r[o]!==void 0&&t.consider(r[o]);if(yield a,t.value===null)return}}async function dn({fs:e,cache:t,dir:n,gitdir:r,trees:i,map:a=async(e,t)=>t,reduce:o=async(e,t)=>{let n=cn(t);return e!==void 0&&n.unshift(e),n},iterate:s=(e,t)=>Promise.all([...t].map(e))}){let c=i.map(i=>i[L]({fs:e,dir:n,gitdir:r,cache:t})),l=Array(c.length).fill(`.`),u=sn(0,c.length),d=async e=>(u.forEach(t=>{let n=e[t];e[t]=n&&new c[t].ConstructEntry(n)}),{entries:e,children:un((await Promise.all(u.map(t=>{let n=e[t];return n?c[t].readdir(n):[]}))).map(e=>(e===null?[]:e)[Symbol.iterator]()))}),f=async e=>{let{entries:t,children:n}=await d(e),r=t.find(e=>e&&e._fullpath)._fullpath,i=await a(r,t);if(i!==null){let e=await s(f,n);return e=e.filter(e=>e!==void 0),o(i,e)}};return f(l)}async function fn(e,t){let n=await e.readdir(t);n==null?await e.rm(t):n.length?await Promise.all(n.map(n=>{let r=B(t,n);return e.lstat(r).then(t=>{if(t)return t.isDirectory()?fn(e,r):e.rm(r)})})).then(()=>e.rmdir(t)):await e.rmdir(t)}function pn(e){return mn(e)&&hn(e.then)&&hn(e.catch)}function mn(e){return e&&typeof e==`object`}function hn(e){return typeof e==`function`}function gn(e){return pn((e=>{try{return e.readFile().catch(e=>e)}catch(e){return e}})(e))}var _n=[`readFile`,`writeFile`,`mkdir`,`rmdir`,`unlink`,`stat`,`lstat`,`readdir`,`readlink`,`symlink`];function vn(e,t){if(gn(t))for(let n of _n)e[`_${n}`]=t[n].bind(t);else for(let n of _n)e[`_${n}`]=s(t[n].bind(t));gn(t)?(t.cp&&(e._cp=t.cp.bind(t)),t.rm?e._rm=t.rm.bind(t):t.rmdir.length>1?e._rm=t.rmdir.bind(t):e._rm=fn.bind(null,e)):(t.cp&&(e._cp=s(t.cp.bind(t))),t.rm?e._rm=s(t.rm.bind(t)):t.rmdir.length>2?e._rm=s(t.rmdir.bind(t)):e._rm=fn.bind(null,e))}var G=class{constructor(e){if(e._original_unwrapped_fs!==void 0)return e;let t=Object.getOwnPropertyDescriptor(e,`promises`);t&&t.enumerable?vn(this,e.promises):vn(this,e),this._original_unwrapped_fs=e}async exists(e,t={}){try{return await this._stat(e),!0}catch(e){if(e.code===`ENOENT`||e.code===`ENOTDIR`||(e.code||``).includes(`ENS`))return!1;throw console.log(`Unhandled error in "FileSystem.exists()" function`,e),e}}async read(e,t={}){try{let n=await this._readFile(e,t);if(t.autocrlf===`true`)try{n=new TextDecoder(`utf8`,{fatal:!0}).decode(n),n=n.replace(/\r\n/g,`
|
|
774
774
|
`),n=new TextEncoder().encode(n)}catch{}return typeof n!=`string`&&(n=Buffer.from(n)),n}catch{return null}}async write(e,t,n={}){try{await this._writeFile(e,t,n)}catch{await this.mkdir(P(e)),await this._writeFile(e,t,n)}}async mkdir(e,t=!1){try{await this._mkdir(e)}catch(n){if(n===null||n.code===`EEXIST`)return;if(t)throw n;if(n.code===`ENOENT`){let t=P(e);if(t===`.`||t===`/`||t===e)throw n;await this.mkdir(t),await this.mkdir(e,!0)}}}async rm(e){try{await this._unlink(e)}catch(e){if(e.code!==`ENOENT`)throw e}}async rmdir(e,t){try{t&&t.recursive?await this._rm(e,t):await this._rmdir(e)}catch(e){if(e.code!==`ENOENT`)throw e}}async readdir(e){try{let t=await this._readdir(e);return t.sort(g),t}catch(e){return e.code===`ENOTDIR`?null:[]}}async readdirDeep(e){let t=await this._readdir(e);return(await Promise.all(t.map(async t=>{let n=e+`/`+t;return(await this._stat(n)).isDirectory()?this.readdirDeep(n):n}))).reduce((e,t)=>e.concat(t),[])}async lstat(e){try{return await this._lstat(e)}catch(e){if(e.code===`ENOENT`||(e.code||``).includes(`ENS`))return null;throw e}}async readlink(e,t={encoding:`buffer`}){try{let n=await this._readlink(e,t);return Buffer.isBuffer(n)?n:Buffer.from(n)}catch(e){if(e.code===`ENOENT`||(e.code||``).includes(`ENS`))return null;throw e}}async writelink(e,t){return this._symlink(t.toString(`utf8`),e)}};function K(e,t){if(t===void 0)throw new Mt(e)}function yn(e){return e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)}async function q({fsp:e,dotgit:t}){K(`fsp`,e),K(`dotgit`,t);let n=await e._stat(t).catch(()=>({isFile:()=>!1,isDirectory:()=>!1}));return n.isDirectory()?t:n.isFile()?e._readFile(t,`utf8`).then(e=>e.trimRight().substr(8)).then(e=>yn(e)?e:B(P(t),e)):t}async function bn(e,t){return!e&&!t?!1:e&&!t||!e&&t?!0:!(await e.type()===`tree`&&await t.type()===`tree`||await e.type()===await t.type()&&await e.mode()===await t.mode()&&await e.oid()===await t.oid())}var xn=class{static async isIgnored({fs:e,dir:t,gitdir:n=B(t,`.git`),filepath:r}){if(N(r)===`.git`)return!0;if(r===`.`)return!1;let i=``,a=B(n,`info`,`exclude`);await e.exists(a)&&(i=await e.read(a,`utf8`));let o=[{gitignore:B(t,`.gitignore`),filepath:r}],s=r.split(`/`).filter(Boolean);for(let e=1;e<s.length;e++){let n=s.slice(0,e).join(`/`),r=s.slice(e).join(`/`);o.push({gitignore:B(t,n,`.gitignore`),filepath:r})}let l=!1;for(let t of o){let n;try{n=await e.read(t.gitignore,`utf8`)}catch(e){if(e.code===`NOENT`)continue}let r=c().add(i);r.add(n);let a=P(t.filepath);if(a!==`.`&&r.ignores(a))return!0;l=l?!r.test(t.filepath).unignored:r.test(t.filepath).ignored}return l}};async function Sn({fs:e,gitdir:t,object:n,format:r,oid:i}){if(r!==`deflated`)throw new p(`GitObjectStoreLoose expects objects to write to be in deflated format`);let a=`${t}/${`objects/${i.slice(0,2)}/${i.slice(2)}`}`;await e.exists(a)||await e.write(a,n)}var Cn=null;async function wn(e){return Cn===null&&(Cn=En()),Cn?Tn(e):a.deflate(e)}async function Tn(e){let t=new CompressionStream(`deflate`),n=new Blob([e]).stream().pipeThrough(t);return new Uint8Array(await new Response(n).arrayBuffer())}function En(){try{return new CompressionStream(`deflate`).writable.close(),new Blob([]).stream().cancel(),!0}catch{return!1}}async function Dn({fs:e,gitdir:t,type:n,object:r,format:i=`content`,oid:a=void 0,dryRun:o=!1}){return i!==`deflated`&&(i!==`wrapped`&&(r=Ke.wrap({type:n,object:r})),a=await w(r),r=Buffer.from(await wn(r))),o||await Sn({fs:e,gitdir:t,object:r,format:`deflated`,oid:a}),a}function On(e){let t;for(;~(t=e.indexOf(92));)e[t]=47;return e}async function kn({fs:e,dir:t,gitdir:n=B(t,`.git`),filepath:r,cache:i={},force:a=!1,parallel:o=!0}){try{K(`fs`,e),K(`dir`,t),K(`gitdir`,n),K(`filepath`,r);let s=new G(e),c=await q({fsp:s,dotgit:n});await M.acquire({fs:s,gitdir:c,cache:i},async e=>An({dir:t,gitdir:c,fs:s,filepath:r,index:e,force:a,parallel:o,autocrlf:await(await Ne.get({fs:s,gitdir:c})).get(`core.autocrlf`)}))}catch(e){throw e.caller=`git.add`,e}}async function An({dir:e,gitdir:t,fs:n,filepath:r,index:i,force:a,parallel:o,autocrlf:s}){r=Array.isArray(r)?r:[r];let c=r.map(async r=>{if(!a&&await xn.isIgnored({fs:n,dir:e,gitdir:t,filepath:r}))return;let c=await n.lstat(B(e,r));if(!c)throw new z(r);if(c.isDirectory()){let c=await n.readdir(B(e,r));if(o){let l=c.map(c=>An({dir:e,gitdir:t,fs:n,filepath:[B(r,c)],index:i,force:a,parallel:o,autocrlf:s}));await Promise.all(l)}else for(let l of c)await An({dir:e,gitdir:t,fs:n,filepath:[B(r,l)],index:i,force:a,parallel:o,autocrlf:s})}else{let a=c.isSymbolicLink()?await n.readlink(B(e,r)).then(On):await n.read(B(e,r),{autocrlf:s});if(a===null)throw new z(r);let o=await Dn({fs:n,gitdir:t,type:`blob`,object:a});i.insert({filepath:r,stats:c,oid:o})}}),l=await Promise.allSettled(c),u=l.filter(e=>e.status===`rejected`).map(e=>e.reason);if(u.length>1)throw new Nt(u);if(u.length===1)throw u[0];return l.filter(e=>e.status===`fulfilled`&&e.value).map(e=>e.value)}async function jn({fs:e,gitdir:t,path:n}){return(await Ne.get({fs:e,gitdir:t})).get(n)}function Mn(e,...t){for(let n of t)if(n)for(let t of Object.keys(n)){let r=n[t];r!==void 0&&(e[t]=r)}return e}async function Nn({fs:e,gitdir:t,author:n,commit:r}){let i=Math.floor(Date.now()/1e3),a=Mn({},{name:await jn({fs:e,gitdir:t,path:`user.name`}),email:await jn({fs:e,gitdir:t,path:`user.email`})||``,timestamp:i,timezoneOffset:new Date(i*1e3).getTimezoneOffset()},r?r.author:void 0,n);if(a.name!==void 0)return a}async function Pn({fs:e,gitdir:t,author:n,committer:r,commit:i}){let a=Math.floor(Date.now()/1e3),o=Mn({},{name:await jn({fs:e,gitdir:t,path:`user.name`}),email:await jn({fs:e,gitdir:t,path:`user.email`})||``,timestamp:a,timezoneOffset:new Date(a*1e3).getTimezoneOffset()},i?i.committer:void 0,n,r);if(o.name!==void 0)return o}async function Fn({fs:e,cache:t,gitdir:n,oid:r}){let{type:i,object:a}=await W({fs:e,cache:t,gitdir:n,oid:r});if(i===`tag`)return r=Zt.from(a).parse().object,Fn({fs:e,cache:t,gitdir:n,oid:r});if(i!==`commit`)throw new oe(r,i,`commit`);return{commit:en.from(a),oid:r}}async function In({fs:e,cache:t,gitdir:n,oid:r}){let{commit:i,oid:a}=await Fn({fs:e,cache:t,gitdir:n,oid:r});return{oid:a,commit:i.parse(),payload:i.withoutSignature()}}async function Ln({fs:e,cache:t,onSign:n,gitdir:r,message:i,author:a,committer:o,signingKey:s,amend:c=!1,dryRun:l=!1,noUpdateBranch:u=!1,ref:d,parent:f,tree:p}){let m=!1,h=!1;d||=(h=!(await e.read(`${r}/HEAD`,{encoding:`utf8`})).startsWith(`ref:`),await V.resolve({fs:e,gitdir:r,ref:`HEAD`,depth:2}));let g,_;try{g=await V.resolve({fs:e,gitdir:r,ref:d}),_=await In({fs:e,gitdir:r,oid:g,cache:{}})}catch{m=!0}if(c&&m)throw new Ht(d);let v=c?await Nn({fs:e,gitdir:r,author:a,commit:_.commit}):await Nn({fs:e,gitdir:r,author:a});if(!v)throw new jt(`author`);let y=c?await Pn({fs:e,gitdir:r,author:v,committer:o,commit:_.commit}):await Pn({fs:e,gitdir:r,author:v,committer:o});if(!y)throw new jt(`committer`);return M.acquire({fs:e,gitdir:r,cache:t,allowUnmerged:!1},async function(t){let a=ae(t.entries).get(`.`);if(p||=await Rn({fs:e,gitdir:r,inode:a,dryRun:l}),f=f?await Promise.all(f.map(t=>V.resolve({fs:e,gitdir:r,ref:t}))):c?_.commit.parent:g?[g]:[],!i)if(c)i=_.commit.message;else throw new Mt(`message`);let o=en.from({tree:p,parent:f,author:v,committer:y,message:i});s&&(o=await en.sign(o,n,s));let m=await Dn({fs:e,gitdir:r,type:`commit`,object:o.toObject(),dryRun:l});return!u&&!l&&await V.writeRef({fs:e,gitdir:r,ref:h?`HEAD`:d,value:m}),m})}async function Rn({fs:e,gitdir:t,inode:n,dryRun:r}){let i=n.children;for(let n of i)n.type===`tree`&&(n.metadata.mode=`040000`,n.metadata.oid=await Rn({fs:e,gitdir:t,inode:n,dryRun:r}));let a=i.map(e=>({mode:e.metadata.mode,path:e.basename,oid:e.metadata.oid,type:e.type}));return await Dn({fs:e,gitdir:t,type:`tree`,object:Ge.from(a).toObject(),dryRun:r})}async function zn({fs:e,cache:t,gitdir:n,oid:r,filepath:i}){if(i.startsWith(`/`))throw new Et(`leading-slash`);if(i.endsWith(`/`))throw new Et(`trailing-slash`);let a=r,o=await tn({fs:e,cache:t,gitdir:n,oid:r}),s=o.tree;return r=i===``?o.oid:await Bn({fs:e,cache:t,gitdir:n,tree:s,pathArray:i.split(`/`),oid:a,filepath:i}),r}async function Bn({fs:e,cache:t,gitdir:n,tree:r,pathArray:i,oid:a,filepath:o}){let s=i.shift();for(let c of r)if(c.path===s){if(i.length===0)return c.oid;{let{type:s,object:l}=await W({fs:e,cache:t,gitdir:n,oid:c.oid});if(s!==`tree`)throw new oe(a,s,`tree`,o);return r=Ge.from(l),Bn({fs:e,cache:t,gitdir:n,tree:r,pathArray:i,oid:a,filepath:o})}}throw new z(`file or directory found at "${a}:${o}"`)}async function Vn({fs:e,cache:t,gitdir:n,oid:r,filepath:i=void 0}){i!==void 0&&(r=await zn({fs:e,cache:t,gitdir:n,oid:r,filepath:i}));let{tree:a,oid:o}=await tn({fs:e,cache:t,gitdir:n,oid:r});return{oid:o,tree:a.entries()}}async function Hn({fs:e,gitdir:t,tree:n}){return await Dn({fs:e,gitdir:t,type:`tree`,object:Ge.from(n).toObject(),format:`content`})}var Un=/(^|[/.])([/.]|$)|^@$|@{|[\x00-\x20\x7f~^:?*[\\]|\.lock(\/|$)/;function Wn(e,t){if(typeof e!=`string`)throw TypeError(`Reference name must be a string`);return!Un.test(e)&&(!!t||e.includes(`/`))}async function Gn({fs:e,gitdir:t,remote:n,url:r,force:i}){if(!Wn(n,!0))throw new Dt(n,l.clean(n));let a=await Ne.get({fs:e,gitdir:t});if(!i&&(await a.getSubsections(`remote`)).includes(n)&&r!==await a.get(`remote.${n}.url`))throw new gt(`remote`,n);await a.set(`remote.${n}.url`,r),await a.set(`remote.${n}.fetch`,`+refs/heads/*:refs/remotes/${n}/*`),await Ne.save({fs:e,gitdir:t,config:a})}async function J({fs:e,dir:t,gitdir:n=B(t,`.git`),remote:r,url:i,force:a=!1}){try{K(`fs`,e),K(`gitdir`,n),K(`remote`,r),K(`url`,i);let t=new G(e);return await Gn({fs:t,gitdir:await q({fsp:t,dotgit:n}),remote:r,url:i,force:a})}catch(e){throw e.caller=`git.addRemote`,e}}async function Kn({fs:e,cache:t,onSign:n,gitdir:r,ref:i,tagger:a,message:o=i,gpgsig:s,object:c,signingKey:l,force:u=!1}){if(i=i.startsWith(`refs/tags/`)?i:`refs/tags/${i}`,!u&&await V.exists({fs:e,gitdir:r,ref:i}))throw new gt(`tag`,i);let d=await V.resolve({fs:e,gitdir:r,ref:c||`HEAD`}),{type:f}=await W({fs:e,cache:t,gitdir:r,oid:d}),p=Zt.from({object:d,type:f,tag:i.replace(`refs/tags/`,``),tagger:a,message:o,gpgsig:s});l&&(p=await Zt.sign(p,n,l));let m=await Dn({fs:e,gitdir:r,type:`tag`,object:p.toObject()});await V.writeRef({fs:e,gitdir:r,ref:i,value:m})}async function qn({fs:e,onSign:t,dir:n,gitdir:r=B(n,`.git`),ref:i,tagger:a,message:o=i,gpgsig:s,object:c,signingKey:l,force:u=!1,cache:d={}}){try{K(`fs`,e),K(`gitdir`,r),K(`ref`,i),l&&K(`onSign`,t);let n=new G(e),f=await q({fsp:n,dotgit:r}),p=await Nn({fs:n,gitdir:f,author:a});if(!p)throw new jt(`tagger`);return await Kn({fs:n,cache:d,onSign:t,gitdir:f,ref:i,tagger:p,message:o,gpgsig:s,object:c,signingKey:l,force:u})}catch(e){throw e.caller=`git.annotatedTag`,e}}async function Jn({fs:e,gitdir:t,ref:n,object:r,checkout:i=!1,force:a=!1}){if(!Wn(n,!0))throw new Dt(n,l.clean(n));let o=`refs/heads/${n}`;if(!a&&await V.exists({fs:e,gitdir:t,ref:o}))throw new gt(`branch`,n,!1);let s;try{s=await V.resolve({fs:e,gitdir:t,ref:r||`HEAD`})}catch{}s&&await V.writeRef({fs:e,gitdir:t,ref:o,value:s}),i&&await V.writeSymbolicRef({fs:e,gitdir:t,ref:`HEAD`,value:o})}async function Yn({fs:e,dir:t,gitdir:n=B(t,`.git`),ref:r,object:i,checkout:a=!1,force:o=!1}){try{K(`fs`,e),K(`gitdir`,n),K(`ref`,r);let t=new G(e);return await Jn({fs:t,gitdir:await q({fsp:t,dotgit:n}),ref:r,object:i,checkout:a,force:o})}catch(e){throw e.caller=`git.branch`,e}}var Xn=(e,t)=>e===`.`||t==null||t.length===0||t===`.`?!0:t.length>=e.length?t.startsWith(e):e.startsWith(t);async function Zn({fs:e,cache:t,onProgress:n,onPostCheckout:r,dir:i,gitdir:a,remote:o,ref:s,filepaths:c,noCheckout:l,noUpdateHead:u,dryRun:d,force:f,track:m=!0,nonBlocking:h=!1,batchSize:g=100}){let _;if(r)try{_=await V.resolve({fs:e,gitdir:a,ref:`HEAD`})}catch{_=`0000000000000000000000000000000000000000`}let v;try{v=await V.resolve({fs:e,gitdir:a,ref:s})}catch(t){if(s===`HEAD`)throw t;let n=`${o}/${s}`;if(v=await V.resolve({fs:e,gitdir:a,ref:n}),m){let t=await Ne.get({fs:e,gitdir:a});await t.set(`branch.${s}.remote`,o),await t.set(`branch.${s}.merge`,`refs/heads/${s}`),await Ne.save({fs:e,gitdir:a,config:t})}await V.writeRef({fs:e,gitdir:a,ref:`refs/heads/${s}`,value:v})}if(!l){let o;try{o=await Qn({fs:e,cache:t,onProgress:n,dir:i,gitdir:a,ref:s,force:f,filepaths:c})}catch(e){throw e instanceof z&&e.data.what===v?new xt(s,v):e}let l=o.filter(([e])=>e===`conflict`).map(([e,t])=>t);if(l.length>0)throw new vt(l);let u=o.filter(([e])=>e===`error`).map(([e,t])=>t);if(u.length>0)throw new p(u.join(`, `));if(d){r&&await r({previousHead:_,newHead:v,type:c!=null&&c.length>0?`file`:`branch`});return}let m=0,y=o.length;if(await M.acquire({fs:e,gitdir:a,cache:t},async function(t){await Promise.all(o.filter(([e])=>e===`delete`||e===`delete-index`).map(async function([r,a]){let o=`${i}/${a}`;r===`delete`&&await e.rm(o),t.delete({filepath:a}),n&&await n({phase:`Updating workdir`,loaded:++m,total:y})}))}),await M.acquire({fs:e,gitdir:a,cache:t},async function(t){for(let[r,a]of o)if(r===`rmdir`||r===`rmdir-index`){let o=`${i}/${a}`;try{r===`rmdir`&&await e.rmdir(o),t.delete({filepath:a}),n&&await n({phase:`Updating workdir`,loaded:++m,total:y})}catch(e){if(e.code===`ENOTEMPTY`)console.log(`Did not delete ${a} because directory is not empty`);else throw e}}}),await Promise.all(o.filter(([e])=>e===`mkdir`||e===`mkdir-index`).map(async function([t,r]){let a=`${i}/${r}`;await e.mkdir(a),n&&await n({phase:`Updating workdir`,loaded:++m,total:y})})),h){let r=await tr(`Update Working Dir`,o.filter(([e])=>e===`create`||e===`create-index`||e===`update`||e===`mkdir-index`).map(([n,r,o,s,c])=>()=>er({fs:e,cache:t,gitdir:a,dir:i},[n,r,o,s,c])),n,g);await M.acquire({fs:e,gitdir:a,cache:t,allowUnmerged:!0},async function(e){await tr(`Update Index`,r.map(([t,n,r])=>()=>$n({index:e,fullpath:t,oid:n,stats:r})),n,g)})}else await M.acquire({fs:e,gitdir:a,cache:t,allowUnmerged:!0},async function(r){await Promise.all(o.filter(([e])=>e===`create`||e===`create-index`||e===`update`||e===`mkdir-index`).map(async function([o,s,c,l,u]){let d=`${i}/${s}`;try{if(o!==`create-index`&&o!==`mkdir-index`){let{object:n}=await W({fs:e,cache:t,gitdir:a,oid:c});if(u&&await e.rm(d),l===33188)await e.write(d,n);else if(l===33261)await e.write(d,n,{mode:511});else if(l===40960)await e.writelink(d,n);else throw new p(`Invalid mode 0o${l.toString(8)} detected in blob ${c}`)}let i=await e.lstat(d);l===33261&&(i.mode=493),o===`mkdir-index`&&(i.mode=57344),r.insert({filepath:s,stats:i,oid:c}),n&&await n({phase:`Updating workdir`,loaded:++m,total:y})}catch(e){console.log(e)}}))});r&&await r({previousHead:_,newHead:v,type:c!=null&&c.length>0?`file`:`branch`})}if(!u){let t=await V.expand({fs:e,gitdir:a,ref:s});t.startsWith(`refs/heads`)?await V.writeSymbolicRef({fs:e,gitdir:a,ref:`HEAD`,value:t}):await V.writeRef({fs:e,gitdir:a,ref:`HEAD`,value:v})}}async function Qn({fs:e,cache:t,onProgress:n,dir:r,gitdir:i,ref:a,force:o,filepaths:s}){let c=0;return dn({fs:e,cache:t,dir:r,gitdir:i,trees:[rn({ref:a}),on(),R()],map:async function(e,[t,r,i]){if(e!==`.`){if(s&&!s.some(t=>Xn(e,t)))return null;switch(n&&await n({phase:`Analyzing workdir`,loaded:++c}),[!!i,!!t,!!r].map(Number).join(``)){case`000`:return;case`001`:return o&&s&&s.includes(e)?[`delete`,e]:void 0;case`010`:switch(await t.type()){case`tree`:return[`mkdir`,e];case`blob`:return[`create`,e,await t.oid(),await t.mode()];case`commit`:return[`mkdir-index`,e,await t.oid(),await t.mode()];default:return[`error`,`new entry Unhandled type ${await t.type()}`]}case`011`:switch(`${await t.type()}-${await r.type()}`){case`tree-tree`:return;case`tree-blob`:case`blob-tree`:return[`conflict`,e];case`blob-blob`:return await t.oid()===await r.oid()?await t.mode()===await r.mode()?[`create-index`,e,await t.oid(),await t.mode()]:o?[`update`,e,await t.oid(),await t.mode(),!0]:[`conflict`,e]:o?[`update`,e,await t.oid(),await t.mode(),await t.mode()!==await r.mode()]:[`conflict`,e];case`commit-tree`:return;case`commit-blob`:return[`conflict`,e];default:return[`error`,`new entry Unhandled type ${t.type}`]}case`100`:return[`delete-index`,e];case`101`:switch(await i.type()){case`tree`:return[`rmdir-index`,e];case`blob`:return await i.oid()===await r.oid()||o?[`delete`,e]:[`conflict`,e];case`commit`:return[`rmdir-index`,e];default:return[`error`,`delete entry Unhandled type ${await i.type()}`]}case`110`:case`111`:switch(`${await i.type()}-${await t.type()}`){case`tree-tree`:return;case`blob-blob`:if(await i.oid()===await t.oid()&&await i.mode()===await t.mode()&&!o)return;if(r){if(await r.oid()!==await i.oid()&&await r.oid()!==await t.oid())return o?[`update`,e,await t.oid(),await t.mode(),await t.mode()!==await r.mode()]:[`conflict`,e]}else if(o)return[`update`,e,await t.oid(),await t.mode(),await t.mode()!==await i.mode()];return await t.mode()===await i.mode()?await t.oid()===await i.oid()?void 0:[`update`,e,await t.oid(),await t.mode(),!1]:[`update`,e,await t.oid(),await t.mode(),!0];case`tree-blob`:return[`update-dir-to-blob`,e,await t.oid()];case`blob-tree`:return[`update-blob-to-tree`,e];case`commit-commit`:return[`mkdir-index`,e,await t.oid(),await t.mode()];default:return[`error`,`update entry Unhandled type ${await i.type()}-${await t.type()}`]}}}},reduce:async function(e,t){return t=cn(t),e?e&&e[0]===`rmdir`?(t.push(e),t):(t.unshift(e),t):t}})}async function $n({index:e,fullpath:t,stats:n,oid:r}){try{e.insert({filepath:t,stats:n,oid:r})}catch(e){console.warn(`Error inserting ${t} into index:`,e)}}async function er({fs:e,cache:t,gitdir:n,dir:r},[i,a,o,s,c]){let l=`${r}/${a}`;if(i!==`create-index`&&i!==`mkdir-index`){let{object:r}=await W({fs:e,cache:t,gitdir:n,oid:o});if(c&&await e.rm(l),s===33188)await e.write(l,r);else if(s===33261)await e.write(l,r,{mode:511});else if(s===40960)await e.writelink(l,r);else throw new p(`Invalid mode 0o${s.toString(8)} detected in blob ${o}`)}let u=await e.lstat(l);return s===33261&&(u.mode=493),i===`mkdir-index`&&(u.mode=57344),[a,o,u]}async function tr(e,t,n,r){let i=[];try{for(let e=0;e<t.length;e+=r){let a=t.slice(e,e+r).map(e=>e());(await Promise.allSettled(a)).forEach(e=>{e.status===`fulfilled`&&i.push(e.value)}),n&&await n({phase:`Updating workdir`,loaded:e+a.length,total:t.length})}return i}catch(t){console.error(`Error during ${e}: ${t}`)}return i}async function nr({fs:e,onProgress:t,onPostCheckout:n,dir:r,gitdir:i=B(r,`.git`),remote:a=`origin`,ref:o,filepaths:s,noCheckout:c=!1,noUpdateHead:l=o===void 0,dryRun:u=!1,force:d=!1,track:f=!0,cache:p={},nonBlocking:m=!1,batchSize:h=100}){try{K(`fs`,e),K(`dir`,r),K(`gitdir`,i);let g=o||`HEAD`,_=new G(e);return await Zn({fs:_,cache:p,onProgress:t,onPostCheckout:n,dir:r,gitdir:await q({fsp:_,dotgit:i}),remote:a,ref:g,filepaths:s,noCheckout:c,noUpdateHead:l,dryRun:u,force:d,track:f,nonBlocking:m,batchSize:h})}catch(e){throw e.caller=`git.checkout`,e}}var rr=/^.*(\r?\n|$)/gm;function ir({branches:e,contents:t}){let n=e[1],r=e[2],i=t[0],a=t[1],o=t[2],s=u(a.match(rr),i.match(rr),o.match(rr)),c=``,l=!0;for(let e of s)e.ok&&(c+=e.ok.join(``)),e.conflict&&(l=!1,c+=`${`<`.repeat(7)} ${n}\n`,c+=e.conflict.a.join(``),c+=`${`=`.repeat(7)}\n`,c+=e.conflict.b.join(``),c+=`${`>`.repeat(7)} ${r}\n`);return{cleanMerge:l,mergedText:c}}async function ar({fs:e,cache:t,dir:n,gitdir:r=B(n,`.git`),index:i,ourOid:a,baseOid:o,theirOid:s,ourName:c=`ours`,baseName:l=`base`,theirName:u=`theirs`,dryRun:d=!1,abortOnConflict:f=!0,mergeDriver:p}){let m=rn({ref:a}),h=rn({ref:o}),g=rn({ref:s}),_=[],v=[],y=[],b=[],x=await dn({fs:e,cache:t,dir:n,gitdir:r,trees:[m,h,g],map:async function(t,[n,a,o]){let s=N(t);switch(`${await bn(n,a)}-${await bn(o,a)}`){case`false-false`:return{mode:await a.mode(),path:s,oid:await a.oid(),type:await a.type()};case`false-true`:return!o&&await n.type()===`tree`?{mode:await n.mode(),path:s,oid:await n.oid(),type:await n.type()}:o?{mode:await o.mode(),path:s,oid:await o.oid(),type:await o.type()}:void 0;case`true-false`:return!n&&await o.type()===`tree`?{mode:await o.mode(),path:s,oid:await o.oid(),type:await o.type()}:n?{mode:await n.mode(),path:s,oid:await n.oid(),type:await n.type()}:void 0;case`true-true`:if(n&&o&&await n.type()===`tree`&&await o.type()===`tree`)return{mode:await n.mode(),path:s,oid:await n.oid(),type:`tree`};if(n&&o&&await n.type()===`blob`&&await o.type()===`blob`)return or({fs:e,gitdir:r,path:s,ours:n,base:a,theirs:o,ourName:c,baseName:l,theirName:u,mergeDriver:p}).then(async e=>{if(e.cleanMerge)f||i.insert({filepath:t,oid:e.mergeResult.oid,stage:0});else if(_.push(t),v.push(t),!f){let e=``;a&&await a.type()===`blob`&&(e=await a.oid());let r=await n.oid(),s=await o.oid();i.delete({filepath:t}),e&&i.insert({filepath:t,oid:e,stage:1}),i.insert({filepath:t,oid:r,stage:2}),i.insert({filepath:t,oid:s,stage:3})}return e.mergeResult});if(a&&!n&&o&&await a.type()===`blob`&&await o.type()===`blob`){if(_.push(t),y.push(t),!f){let e=await a.oid(),n=await o.oid();i.delete({filepath:t}),i.insert({filepath:t,oid:e,stage:1}),i.insert({filepath:t,oid:n,stage:3})}return{mode:await o.mode(),oid:await o.oid(),type:`blob`,path:s}}if(a&&n&&!o&&await a.type()===`blob`&&await n.type()===`blob`){if(_.push(t),b.push(t),!f){let e=await a.oid(),r=await n.oid();i.delete({filepath:t}),i.insert({filepath:t,oid:e,stage:1}),i.insert({filepath:t,oid:r,stage:2})}return{mode:await n.mode(),oid:await n.oid(),type:`blob`,path:s}}if(a&&!n&&!o&&(await a.type()===`blob`||await a.type()===`tree`))return;throw new kt}},reduce:_.length!==0&&(!n||f)?void 0:async(t,n)=>{let i=n.filter(Boolean);if(t&&!(t&&t.type===`tree`&&i.length===0&&t.path!==`.`))return(i.length>0||t.path===`.`&&i.length===0)&&(t.oid=await Dn({fs:e,gitdir:r,type:`tree`,object:new Ge(i).toObject(),dryRun:d})),t}});return _.length===0?x.oid:(n&&!f&&await dn({fs:e,cache:t,dir:n,gitdir:r,trees:[rn({ref:x.oid})],map:async function(t,[r]){let i=`${n}/${t}`;if(await r.type()===`blob`){let t=await r.mode(),n=new TextDecoder().decode(await r.content());await e.write(i,n,{mode:t})}return!0}}),new At(_,v,y,b))}async function or({fs:e,gitdir:t,path:n,ours:r,base:i,theirs:a,ourName:o,theirName:s,baseName:c,dryRun:l,mergeDriver:u=ir}){let d=`blob`,f=`100755`,p=``,m=``;i&&await i.type()===`blob`&&(f=await i.mode(),p=await i.oid(),m=Buffer.from(await i.content()).toString(`utf8`));let h=f===await r.mode()?await a.mode():await r.mode();if(await r.oid()===await a.oid())return{cleanMerge:!0,mergeResult:{mode:h,path:n,oid:await r.oid(),type:d}};if(await r.oid()===p)return{cleanMerge:!0,mergeResult:{mode:h,path:n,oid:await a.oid(),type:d}};if(await a.oid()===p)return{cleanMerge:!0,mergeResult:{mode:h,path:n,oid:await r.oid(),type:d}};let g=Buffer.from(await r.content()).toString(`utf8`),_=Buffer.from(await a.content()).toString(`utf8`),{mergedText:v,cleanMerge:y}=await u({branches:[c,o,s],contents:[m,g,_],path:n});return{cleanMerge:y,mergeResult:{mode:h,path:n,oid:await Dn({fs:e,gitdir:t,type:`blob`,object:Buffer.from(v,`utf8`),dryRun:l}),type:d}}}var sr=/^refs\/(heads\/|tags\/|remotes\/)?(.*)/;function cr(e){let t=sr.exec(e);return t?t[1]===`remotes/`&&e.endsWith(`/HEAD`)?t[2].slice(0,-5):t[2]:e}async function lr({fs:e,gitdir:t,fullname:n=!1,test:r=!1}){let i=await V.resolve({fs:e,gitdir:t,ref:`HEAD`,depth:2});if(r)try{await V.resolve({fs:e,gitdir:t,ref:i})}catch{return}if(i.startsWith(`refs/`))return n?i:cr(i)}function ur(e){return e=e.replace(/^git@([^:]+):/,`https://$1/`),e=e.replace(/^ssh:\/\//,`https://`),e}function dr({username:e=``,password:t=``}){return`Basic ${Buffer.from(`${e}:${t}`).toString(`base64`)}`}async function fr(e,t){let n=Qe(e);for(;;){let{value:e,done:r}=await n.next();if(e&&await t(e),r)break}n.return&&n.return()}async function pr(e){let t=0,n=[];await fr(e,e=>{n.push(e),t+=e.byteLength});let r=new Uint8Array(t),i=0;for(let e of n)r.set(e,i),i+=e.byteLength;return r}function mr(e){let t=e.match(/^https?:\/\/([^/]+)@/);if(t==null)return{url:e,auth:{}};t=t[1];let[n,r]=t.split(`:`);return e=e.replace(`${t}@`,``),{url:e,auth:{username:n,password:r}}}function hr(e,t){let n=t.toString(16);return`0`.repeat(e-n.length)+n}var gr=class{static flush(){return Buffer.from(`0000`,`utf8`)}static delim(){return Buffer.from(`0001`,`utf8`)}static encode(e){typeof e==`string`&&(e=Buffer.from(e));let t=hr(4,e.length+4);return Buffer.concat([Buffer.from(t,`utf8`),e])}static streamReader(e){let t=new $e(e);return async function(){try{let e=await t.read(4);return e==null?!0:(e=parseInt(e.toString(`utf8`),16),e===0||e===1?null:await t.read(e-4)??!0)}catch(t){return e.error=t,!0}}}};async function _r(e){let t={},n;for(;n=await e(),n!==!0;){if(n===null)continue;n=n.toString(`utf8`).replace(/\n$/,``);let e=n.indexOf(`=`);if(e>-1){let r=n.slice(0,e);t[r]=n.slice(e+1)}else t[n]=!0}return{protocolVersion:2,capabilities2:t}}async function vr(e,{service:t}){let n=new Set,r=new Map,i=new Map,a=gr.streamReader(e),o=await a();for(;o===null;)o=await a();if(o===!0)throw new St;if(o.includes(`version 2`))return _r(a);if(o.toString(`utf8`).replace(/\n$/,``)!==`# service=${t}`)throw new Pt(`# service=${t}\\n`,o.toString(`utf8`));let s=await a();for(;s===null;)s=await a();if(s===!0)return{capabilities:n,refs:r,symrefs:i};if(s=s.toString(`utf8`),s.includes(`version 2`))return _r(a);let[c,l]=yr(s,`\0`,`\\x00`);if(l.split(` `).map(e=>n.add(e)),c!==`0000000000000000000000000000000000000000 capabilities^{}`){let[e,t]=yr(c,` `,` `);for(r.set(t,e);;){let e=await a();if(e===!0)break;if(e!==null){let[t,n]=yr(e.toString(`utf8`),` `,` `);r.set(n,t)}}}for(let e of n)if(e.startsWith(`symref=`)){let t=e.match(/symref=([^:]+):(.*)/);t.length===3&&i.set(t[1],t[2])}return{protocolVersion:1,capabilities:n,refs:r,symrefs:i}}function yr(e,t,n){let r=e.trim().split(t);if(r.length!==2)throw new Pt(`Two strings separated by '${n}'`,e.toString(`utf8`));return r}var br=(e,t)=>e.endsWith(`?`)?`${e}${t}`:`${e}/${t.replace(/^https?:\/\//,``)}`,xr=(e,t)=>{(t.username||t.password)&&(e.Authorization=dr(t)),t.headers&&Object.assign(e,t.headers)},Sr=async e=>{try{let t=Buffer.from(await pr(e.body)),n=t.toString(`utf8`);return{preview:n.length<256?n:n.slice(0,256)+`...`,response:n,data:t}}catch{return{}}},Cr=class{static async capabilities(){return[`discover`,`connect`]}static async discover({http:e,onProgress:t,onAuth:n,onAuthSuccess:r,onAuthFailure:i,corsProxy:a,service:o,url:s,headers:c,protocolVersion:l}){let{url:u,auth:d}=mr(s),f=a?br(a,u):u;(d.username||d.password)&&(c.Authorization=dr(d)),l===2&&(c[`Git-Protocol`]=`version=2`);let p,m,h=!1;do if(p=await e.request({onProgress:t,method:`GET`,url:`${f}/info/refs?service=${o}`,headers:c}),m=!1,p.statusCode===401||p.statusCode===203){let e=h?i:n;if(e){if(d=await e(u,{...d,headers:{...c}}),d&&d.cancel)throw new Bt;d&&(xr(c,d),h=!0,m=!0)}}else p.statusCode===200&&h&&r&&await r(u,d);while(m);if(p.statusCode!==200){let{response:e}=await Sr(p);throw new Tt(p.statusCode,p.statusMessage,e)}if(p.headers[`content-type`]===`application/x-${o}-advertisement`){let e=await vr(p.body,{service:o});return e.auth=d,e}else{let{preview:e,response:t,data:n}=await Sr(p);try{let e=await vr([n],{service:o});return e.auth=d,e}catch{throw new Lt(e,t)}}}static async connect({http:e,onProgress:t,corsProxy:n,service:r,url:i,auth:a,body:o,headers:s}){let c=mr(i);c&&(i=c.url),n&&(i=br(n,i)),s[`content-type`]=`application/x-${r}-request`,s.accept=`application/x-${r}-result`,xr(s,a);let l=await e.request({onProgress:t,method:`POST`,url:`${i}/${r}`,body:o,headers:s});if(l.statusCode!==200){let{response:e}=Sr(l);throw new Tt(l.statusCode,l.statusMessage,e)}return l}},wr=class{static getRemoteHelperFor({url:e}){let t=new Map;t.set(`http`,Cr),t.set(`https`,Cr);let n=Tr({url:e});if(!n)throw new zt(e);if(t.has(n.transport))return t.get(n.transport);throw new Rt(e,n.transport,n.transport===`ssh`?ur(e):void 0)}};function Tr({url:e}){if(e.startsWith(`git@`))return{transport:`ssh`,address:e};let t=e.match(/(\w+)(:\/\/|::)(.*)/);if(t!==null){if(t[2]===`://`)return{transport:t[1],address:t[0]};if(t[2]===`::`)return{transport:t[1],address:t[3]}}}var Er=null,Dr=class{static async read({fs:e,gitdir:t}){Er===null&&(Er=new n);let r=B(t,`shallow`),i=new Set;return await Er.acquire(r,async function(){let t=await e.read(r,{encoding:`utf8`});if(t===null||t.trim()===``)return i;t.trim().split(`
|
|
775
775
|
`).map(e=>i.add(e))}),i}static async write({fs:e,gitdir:t,oids:r}){Er===null&&(Er=new n);let i=B(t,`shallow`);if(r.size>0){let t=[...r].join(`
|
|
776
776
|
`)+`
|
|
777
777
|
`;await Er.acquire(i,async function(){await e.write(i,t,{encoding:`utf8`})})}else await Er.acquire(i,async function(){await e.rm(i)})}};async function Or({fs:e,gitdir:t,oid:n}){let r=`objects/${n.slice(0,2)}/${n.slice(2)}`;return e.exists(`${t}/${r}`)}async function kr({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:i}){let a=await e.readdir(B(n,`objects/pack`));a=a.filter(e=>e.endsWith(`.idx`));for(let o of a){let a=await ft({fs:e,cache:t,filename:`${n}/objects/pack/${o}`,getExternalRefDelta:i});if(a.error)throw new p(a.error);if(a.offsets.has(r))return!0}return!1}async function Ar({fs:e,cache:t,gitdir:n,oid:r,format:i=`content`}){let a=r=>W({fs:e,cache:t,gitdir:n,oid:r}),o=await Or({fs:e,gitdir:n,oid:r});return o||=await kr({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:a}),o}function jr(e){return e.slice(0,12).toString(`hex`)===`5041434b0000000200000000`}function Mr(e,t){let n=e.map(e=>e.split(`=`,1)[0]);return t.filter(e=>{let t=e.split(`=`,1)[0];return n.includes(t)})}var Nr={name:`isomorphic-git`,version:`1.37.5`,agent:`git/isomorphic-git@1.37.5`},Pr=class{constructor(){this._queue=[]}write(e){if(this._ended)throw Error(`You cannot write to a FIFO that has already been ended!`);if(this._waiting){let t=this._waiting;this._waiting=null,t({value:e})}else this._queue.push(e)}end(){if(this._ended=!0,this._waiting){let e=this._waiting;this._waiting=null,e({done:!0})}}destroy(e){this.error=e,this.end()}async next(){if(this._queue.length>0)return{value:this._queue.shift()};if(this._ended)return{done:!0};if(this._waiting)throw Error(`You cannot call read until the previous call to read has returned!`);return new Promise(e=>{this._waiting=e})}};function Fr(e){let t=e.indexOf(`\r`),n=e.indexOf(`
|
|
778
778
|
`);return t===-1&&n===-1?-1:t===-1?n+1:n===-1?t+1:n===t+1?n+1:Math.min(t,n)+1}function Ir(e){let t=new Pr,n=``;return(async()=>{await fr(e,e=>{for(e=e.toString(`utf8`),n+=e;;){let e=Fr(n);if(e===-1)break;t.write(n.slice(0,e)),n=n.slice(e)}}),n.length>0&&t.write(n),t.end()})(),t}var Lr=class{static demux(e){let t=gr.streamReader(e),n=new Pr,r=new Pr,i=new Pr,a=async function(){let o=await t();if(o===null)return a();if(o===!0){n.end(),i.end(),e.error?r.destroy(e.error):r.end();return}switch(o[0]){case 1:r.write(o.slice(1));break;case 2:i.write(o.slice(1));break;case 3:{let e=o.slice(1);i.write(e),n.end(),i.end(),r.destroy(Error(e.toString(`utf8`)));return}default:n.write(o)}a()};return a(),{packetlines:n,packfile:r,progress:i}}};async function Rr(e){let{packetlines:t,packfile:n,progress:r}=Lr.demux(e),i=[],a=[],o=[],s=!1,c=!1;return new Promise((l,u)=>{fr(t,t=>{let d=t.toString(`utf8`).trim();if(d.startsWith(`shallow`)){let e=d.slice(-41).trim();e.length!==40&&u(new se(e)),i.push(e)}else if(d.startsWith(`unshallow`)){let e=d.slice(-41).trim();e.length!==40&&u(new se(e)),a.push(e)}else if(d.startsWith(`ACK`)){let[,e,t]=d.split(` `);o.push({oid:e,status:t}),t||(c=!0)}else d.startsWith(`NAK`)?(s=!0,c=!0):(c=!0,s=!0);c&&(e.error?u(e.error):l({shallows:i,unshallows:a,acks:o,nak:s,packfile:n,progress:r}))}).finally(()=>{c||(e.error?u(e.error):l({shallows:i,unshallows:a,acks:o,nak:s,packfile:n,progress:r}))})})}function zr({capabilities:e=[],wants:t=[],haves:n=[],shallows:r=[],depth:i=null,since:a=null,exclude:o=[]}){let s=[];t=[...new Set(t)];let c=` ${e.join(` `)}`;for(let e of t)s.push(gr.encode(`want ${e}${c}\n`)),c=``;for(let e of r)s.push(gr.encode(`shallow ${e}\n`));i!==null&&s.push(gr.encode(`deepen ${i}\n`)),a!==null&&s.push(gr.encode(`deepen-since ${Math.floor(a.valueOf()/1e3)}\n`));for(let e of o)s.push(gr.encode(`deepen-not ${e}\n`));s.push(gr.flush());for(let e of n)s.push(gr.encode(`have ${e}\n`));return s.push(gr.encode(`done
|
|
779
|
-
`)),s}async function Br({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,gitdir:c,ref:l,remoteRef:u,remote:d,url:f,corsProxy:p,depth:m=null,since:h=null,exclude:g=[],relative:_=!1,tags:v=!1,singleBranch:y=!1,headers:b={},prune:x=!1,pruneTags:S=!1}){let C=l||await lr({fs:e,gitdir:c,test:!0}),w=await Ne.get({fs:e,gitdir:c}),T=d||C&&await w.get(`branch.${C}.remote`)||`origin`,E=f||await w.get(`remote.${T}.url`);if(E===void 0)throw new Mt(`remote OR url`);let D=u||C&&await w.get(`branch.${C}.merge`)||l||`HEAD`;p===void 0&&(p=await w.get(`http.corsProxy`));let O=wr.getRemoteHelperFor({url:E}),k=await O.discover({http:n,onAuth:a,onAuthSuccess:o,onAuthFailure:s,corsProxy:p,service:`git-upload-pack`,url:E,headers:b,protocolVersion:1}),
|
|
779
|
+
`)),s}async function Br({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,gitdir:c,ref:l,remoteRef:u,remote:d,url:f,corsProxy:p,depth:m=null,since:h=null,exclude:g=[],relative:_=!1,tags:v=!1,singleBranch:y=!1,headers:b={},prune:x=!1,pruneTags:S=!1}){let C=l||await lr({fs:e,gitdir:c,test:!0}),w=await Ne.get({fs:e,gitdir:c}),T=d||C&&await w.get(`branch.${C}.remote`)||`origin`,E=f||await w.get(`remote.${T}.url`);if(E===void 0)throw new Mt(`remote OR url`);let D=u||C&&await w.get(`branch.${C}.merge`)||l||`HEAD`;p===void 0&&(p=await w.get(`http.corsProxy`));let O=wr.getRemoteHelperFor({url:E}),k=await O.discover({http:n,onAuth:a,onAuthSuccess:o,onAuthFailure:s,corsProxy:p,service:`git-upload-pack`,url:E,headers:b,protocolVersion:1}),A=k.auth,ee=k.refs;if(ee.size===0)return{defaultBranch:null,fetchHead:null,fetchHeadDescription:null};if(m!==null&&!k.capabilities.has(`shallow`))throw new It(`shallow`,`depth`);if(h!==null&&!k.capabilities.has(`deepen-since`))throw new It(`deepen-since`,`since`);if(g.length>0&&!k.capabilities.has(`deepen-not`))throw new It(`deepen-not`,`exclude`);if(_===!0&&!k.capabilities.has(`deepen-relative`))throw new It(`deepen-relative`,`relative`);let{oid:j,fullref:te}=V.resolveAgainstMap({ref:D,map:ee});for(let e of ee.keys())e===te||e===`HEAD`||e.startsWith(`refs/heads/`)||v&&e.startsWith(`refs/tags/`)||ee.delete(e);let ne=Mr([...k.capabilities],[`multi_ack_detailed`,`no-done`,`side-band-64k`,`ofs-delta`,`agent=${Nr.agent}`]);_&&ne.push(`deepen-relative`);let re=y?[j]:ee.values(),ie=y?[C]:await V.listRefs({fs:e,gitdir:c,filepath:`refs`}),M=[];for(let n of ie)try{n=await V.expand({fs:e,gitdir:c,ref:n});let r=await V.resolve({fs:e,gitdir:c,ref:n});await Ar({fs:e,cache:t,gitdir:c,oid:r})&&M.push(r)}catch{}M=[...new Set(M)];let N=await Dr.read({fs:e,gitdir:c}),P=k.capabilities.has(`shallow`)?[...N]:[],ae=zr({capabilities:ne,wants:re,haves:M,shallows:P,depth:m,since:h,exclude:g}),F=Buffer.from(await pr(ae)),I=await O.connect({http:n,onProgress:r,corsProxy:p,service:`git-upload-pack`,url:E,auth:A,body:[F],headers:b}),L=await Rr(I.body);I.headers&&(L.headers=I.headers);for(let n of L.shallows)if(!N.has(n))try{let{object:r}=await W({fs:e,cache:t,gitdir:c,oid:n}),i=new en(r),a=await Promise.all(i.headers().parent.map(n=>Ar({fs:e,cache:t,gitdir:c,oid:n})));a.length===0||a.every(e=>e)||N.add(n)}catch{N.add(n)}for(let e of L.unshallows)N.delete(e);if(await Dr.write({fs:e,gitdir:c,oids:N}),y){let t=new Map([[te,j]]),n=new Map,r=10,i=te;for(;r--;){let e=k.symrefs.get(i);if(e===void 0)break;n.set(i,e),i=e}let a=ee.get(i);a&&t.set(i,a);let{pruned:o}=await V.updateRemoteRefs({fs:e,gitdir:c,remote:T,refs:t,symrefs:n,tags:v,prune:x});x&&(L.pruned=o)}else{let{pruned:t}=await V.updateRemoteRefs({fs:e,gitdir:c,remote:T,refs:ee,symrefs:k.symrefs,tags:v,prune:x,pruneTags:S});x&&(L.pruned=t)}if(L.HEAD=k.symrefs.get(`HEAD`),L.HEAD===void 0){let{oid:e}=V.resolveAgainstMap({ref:`HEAD`,map:ee});for(let[t,n]of ee.entries())if(t!==`HEAD`&&n===e){L.HEAD=t;break}}L.FETCH_HEAD={oid:j,description:`${te.startsWith(`refs/tags`)?`tag`:`branch`} '${cr(te)}' of ${E}`},(r||i)&&fr(Ir(L.progress),async e=>{if(i&&await i(e),r){let t=e.match(/([^:]*).*\((\d+?)\/(\d+?)\)/);t&&await r({phase:t[1].trim(),loaded:parseInt(t[2],10),total:parseInt(t[3],10)})}});let R=Buffer.from(await pr(L.packfile));if(I.body.error)throw I.body.error;let z=R.slice(-20).toString(`hex`),oe={defaultBranch:L.HEAD,fetchHead:L.FETCH_HEAD.oid,fetchHeadDescription:L.FETCH_HEAD.description};if(L.headers&&(oe.headers=L.headers),x&&(oe.pruned=L.pruned),z!==``&&!jr(R)){oe.packfile=`objects/pack/pack-${z}.pack`;let n=B(c,oe.packfile);await e.write(n,R);let i=await lt.fromPack({pack:R,getExternalRefDelta:n=>W({fs:e,cache:t,gitdir:c,oid:n}),onProgress:r});await e.write(n.replace(/\.pack$/,`.idx`),await i.toBuffer())}return oe}async function Vr({fs:e,bare:t=!1,dir:n,gitdir:r=t?n:B(n,`.git`),defaultBranch:i=`master`}){if(await e.exists(r+`/config`))return;let a=[`hooks`,`info`,`objects/info`,`objects/pack`,`refs/heads`,`refs/tags`];a=a.map(e=>r+`/`+e);for(let t of a)await e.mkdir(t);await e.write(r+`/config`,`[core]
|
|
780
780
|
repositoryformatversion = 0
|
|
781
781
|
filemode = false
|
|
782
782
|
\tbare = ${t}\n`+(t?``:` logallrefupdates = true
|
|
@@ -784,7 +784,7 @@ gpgsig`+Qt(o)+`
|
|
|
784
784
|
ignorecase = true
|
|
785
785
|
`),await e.write(r+`/HEAD`,`ref: refs/heads/${i}\n`)}async function Hr({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,onPostCheckout:c,dir:l,gitdir:u,url:d,corsProxy:f,ref:p,remote:m,depth:h,since:g,exclude:_,relative:v,singleBranch:y,noCheckout:b,noTags:x,headers:S,nonBlocking:C,batchSize:w=100}){try{if(await Vr({fs:e,gitdir:u}),await Gn({fs:e,gitdir:u,remote:m,url:d,force:!1}),f){let t=await Ne.get({fs:e,gitdir:u});await t.set(`http.corsProxy`,f),await Ne.save({fs:e,gitdir:u,config:t})}let{defaultBranch:T,fetchHead:E}=await Br({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,gitdir:u,ref:p,remote:m,corsProxy:f,depth:h,since:g,exclude:_,relative:v,singleBranch:y,headers:S,tags:!x});if(E===null)return;p||=T,p=p.replace(`refs/heads/`,``),await Zn({fs:e,cache:t,onProgress:r,onPostCheckout:c,dir:l,gitdir:u,ref:p,remote:m,noCheckout:b,nonBlocking:C,batchSize:w})}catch(t){throw await e.rmdir(u,{recursive:!0,maxRetries:10}).catch(()=>void 0),t}}async function Ur({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPostCheckout:s,dir:c,gitdir:l=B(c,`.git`),url:u,corsProxy:d=void 0,ref:f=void 0,remote:p=`origin`,depth:m=void 0,since:h=void 0,exclude:g=[],relative:_=!1,singleBranch:v=!1,noCheckout:y=!1,noTags:b=!1,headers:x={},cache:S={},nonBlocking:C=!1,batchSize:w=100}){try{K(`fs`,e),K(`http`,t),K(`gitdir`,l),y||K(`dir`,c),K(`url`,u);let T=new G(e);return await Hr({fs:T,cache:S,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPostCheckout:s,dir:c,gitdir:await q({fsp:T,dotgit:l}),url:u,corsProxy:d,ref:f,remote:p,depth:m,since:h,exclude:g,relative:_,singleBranch:v,noCheckout:y,noTags:b,headers:x,nonBlocking:C,batchSize:w})}catch(e){throw e.caller=`git.clone`,e}}async function Wr({fs:e,onSign:t,dir:n,gitdir:r=B(n,`.git`),message:i,author:a,committer:o,signingKey:s,amend:c=!1,dryRun:l=!1,noUpdateBranch:u=!1,ref:d,parent:f,tree:p,cache:m={}}){try{K(`fs`,e),c||K(`message`,i),s&&K(`onSign`,t);let n=new G(e);return await Ln({fs:n,cache:m,onSign:t,gitdir:await q({fsp:n,dotgit:r}),message:i,author:a,committer:o,signingKey:s,amend:c,dryRun:l,noUpdateBranch:u,ref:d,parent:f,tree:p})}catch(e){throw e.caller=`git.commit`,e}}async function Gr({fs:e,dir:t,gitdir:n=B(t,`.git`),fullname:r=!1,test:i=!1}){try{K(`fs`,e),K(`gitdir`,n);let t=new G(e);return await lr({fs:t,gitdir:await q({fsp:t,dotgit:n}),fullname:r,test:i})}catch(e){throw e.caller=`git.currentBranch`,e}}async function Kr({fs:e,gitdir:t,ref:n}){if(n=n.startsWith(`refs/heads/`)?n:`refs/heads/${n}`,!await V.exists({fs:e,gitdir:t,ref:n}))throw new z(n);let r=await V.expand({fs:e,gitdir:t,ref:n});if(r===await lr({fs:e,gitdir:t,fullname:!0})){let n=await V.resolve({fs:e,gitdir:t,ref:r});await V.writeRef({fs:e,gitdir:t,ref:`HEAD`,value:n})}await V.deleteRef({fs:e,gitdir:t,ref:r});let i=cr(n),a=await Ne.get({fs:e,gitdir:t});await a.deleteSection(`branch`,i),await Ne.save({fs:e,gitdir:t,config:a})}async function qr({fs:e,dir:t,gitdir:n=B(t,`.git`),ref:r}){try{K(`fs`,e),K(`ref`,r);let t=new G(e);return await Kr({fs:t,gitdir:await q({fsp:t,dotgit:n}),ref:r})}catch(e){throw e.caller=`git.deleteBranch`,e}}async function Jr({fs:e,gitdir:t,remote:n}){let r=await Ne.get({fs:e,gitdir:t});await r.deleteSection(`remote`,n),await Ne.save({fs:e,gitdir:t,config:r})}async function Yr({fs:e,dir:t,gitdir:n=B(t,`.git`),remote:r}){try{K(`fs`,e),K(`remote`,r);let t=new G(e);return await Jr({fs:t,gitdir:await q({fsp:t,dotgit:n}),remote:r})}catch(e){throw e.caller=`git.deleteRemote`,e}}async function Xr({fs:e,gitdir:t,ref:n}){n=n.startsWith(`refs/tags/`)?n:`refs/tags/${n}`,await V.deleteRef({fs:e,gitdir:t,ref:n})}async function Zr({fs:e,dir:t,gitdir:n=B(t,`.git`),ref:r}){try{K(`fs`,e),K(`ref`,r);let t=new G(e);return await Xr({fs:t,gitdir:await q({fsp:t,dotgit:n}),ref:r})}catch(e){throw e.caller=`git.deleteTag`,e}}async function Qr({fs:e,gitdir:t,oid:n}){let r=n.slice(0,2);return(await e.readdir(`${t}/objects/${r}`)).map(e=>`${r}${e}`).filter(e=>e.startsWith(n))}async function $r({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:i}){let a=[],o=await e.readdir(B(n,`objects/pack`));o=o.filter(e=>e.endsWith(`.idx`));for(let s of o){let o=await ft({fs:e,cache:t,filename:`${n}/objects/pack/${s}`,getExternalRefDelta:i});if(o.error)throw new p(o.error);for(let e of o.offsets.keys())e.startsWith(r)&&a.push(e)}return a}async function ei({fs:e,cache:t,gitdir:n,oid:r}){let i=r=>W({fs:e,cache:t,gitdir:n,oid:r}),a=await Qr({fs:e,gitdir:n,oid:r}),o=await $r({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:i});for(let e of o)a.indexOf(e)===-1&&a.push(e);if(a.length===1)return a[0];throw a.length>1?new _t(`oids`,r,a):new z(`an object matching "${r}"`)}async function ti({fs:e,dir:t,gitdir:n=B(t,`.git`),oid:r,cache:i={}}){try{K(`fs`,e),K(`gitdir`,n),K(`oid`,r);let t=new G(e);return await ei({fs:t,cache:i,gitdir:await q({fsp:t,dotgit:n}),oid:r})}catch(e){throw e.caller=`git.expandOid`,e}}async function ni({fs:e,cache:t,gitdir:n,oids:r}){let i={},a=r.length,o=r.map((e,t)=>({index:t,oid:e}));for(;o.length;){let r=new Set;for(let{oid:e,index:t}of o)i[e]||(i[e]=new Set),i[e].add(t),i[e].size===a&&r.add(e);if(r.size>0)return[...r];let s=new Map;for(let{oid:r,index:a}of o)try{let{object:o}=await W({fs:e,cache:t,gitdir:n,oid:r}),{parent:c}=en.from(o).parseHeaders();for(let e of c)(!i[e]||!i[e].has(a))&&s.set(e+`:`+a,{oid:e,index:a})}catch{}o=Array.from(s.values())}return[]}async function ri({fs:e,cache:t,dir:n,gitdir:r,ours:i,theirs:a,fastForward:o=!0,fastForwardOnly:s=!1,dryRun:c=!1,noUpdateBranch:l=!1,abortOnConflict:u=!0,message:d,author:f,committer:p,signingKey:m,onSign:h,mergeDriver:g,allowUnrelatedHistories:_=!1}){i===void 0&&(i=await lr({fs:e,gitdir:r,fullname:!0})),i=await V.expand({fs:e,gitdir:r,ref:i}),a=await V.expand({fs:e,gitdir:r,ref:a});let v=await V.resolve({fs:e,gitdir:r,ref:i}),y=await V.resolve({fs:e,gitdir:r,ref:a}),b=await ni({fs:e,cache:t,gitdir:r,oids:[v,y]});if(b.length!==1)if(b.length===0&&_)b.push(`4b825dc642cb6eb9a060e54bf8d69288fbee4904`);else throw new kt;let x=b[0];if(x===y)return{oid:v,alreadyMerged:!0};if(o&&x===v)return!c&&!l&&await V.writeRef({fs:e,gitdir:r,ref:i,value:y}),{oid:y,fastForward:!0};{if(s)throw new Ct;let o=await M.acquire({fs:e,gitdir:r,cache:t,allowUnmerged:!1},async o=>ar({fs:e,cache:t,dir:n,gitdir:r,index:o,ourOid:v,theirOid:y,baseOid:x,ourName:cr(i),baseName:`base`,theirName:cr(a),dryRun:c,abortOnConflict:u,mergeDriver:g}));if(o instanceof At)throw o;return d||=`Merge branch '${cr(a)}' into ${cr(i)}`,{oid:await Ln({fs:e,cache:t,gitdir:r,message:d,ref:i,tree:o,parent:[v,y],author:f,committer:p,signingKey:m,onSign:h,dryRun:c,noUpdateBranch:l}),tree:o,mergeCommit:!0}}}async function ii({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,dir:c,gitdir:l,ref:u,url:d,remote:f,remoteRef:p,prune:m,pruneTags:h,fastForward:g,fastForwardOnly:_,corsProxy:v,singleBranch:y,headers:b,author:x,committer:S,signingKey:C}){try{if(!u){let t=await lr({fs:e,gitdir:l});if(!t)throw new Mt(`ref`);u=t}let{fetchHead:w,fetchHeadDescription:T}=await Br({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,gitdir:l,corsProxy:v,ref:u,url:d,remote:f,remoteRef:p,singleBranch:y,headers:b,prune:m,pruneTags:h});await ri({fs:e,cache:t,gitdir:l,ours:u,theirs:w,fastForward:g,fastForwardOnly:_,message:`Merge ${T}`,author:x,committer:S,signingKey:C,dryRun:!1,noUpdateBranch:!1}),await Zn({fs:e,cache:t,onProgress:r,dir:c,gitdir:l,ref:u,remote:f,noCheckout:!1})}catch(e){throw e.caller=`git.pull`,e}}async function ai({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,dir:s,gitdir:c=B(s,`.git`),ref:l,remote:u,remoteRef:d,url:f,corsProxy:p,depth:m=null,since:h=null,exclude:g=[],relative:_=!1,tags:v=!1,singleBranch:y=!1,headers:b={},prune:x=!1,pruneTags:S=!1,cache:C={}}){try{K(`fs`,e),K(`http`,t),K(`gitdir`,c);let s=new G(e);return await Br({fs:s,cache:C,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,gitdir:await q({fsp:s,dotgit:c}),ref:l,remote:u,remoteRef:d,url:f,corsProxy:p,depth:m,since:h,exclude:g,relative:_,tags:v,singleBranch:y,headers:b,prune:x,pruneTags:S})}catch(e){throw e.caller=`git.fetch`,e}}async function oi({fs:e,filepath:t}){if(await e.exists(B(t,`.git`)))return t;{let n=P(t);if(n===t)throw new z(`git root for ${t}`);return oi({fs:e,filepath:n})}}async function si({fs:e,filepath:t}){try{return K(`fs`,e),K(`filepath`,t),await oi({fs:new G(e),filepath:t})}catch(e){throw e.caller=`git.findRoot`,e}}async function ci({fs:e,dir:t,gitdir:n=B(t,`.git`),path:r}){try{K(`fs`,e),K(`gitdir`,n),K(`path`,r);let t=new G(e);return await jn({fs:t,gitdir:await q({fsp:t,dotgit:n}),path:r})}catch(e){throw e.caller=`git.getConfig`,e}}async function li({fs:e,bare:t=!1,dir:n,gitdir:r=t?n:B(n,`.git`),defaultBranch:i=`master`}){try{K(`fs`,e),K(`gitdir`,r),t||K(`dir`,n);let a=new G(e);return await Vr({fs:a,bare:t,dir:n,gitdir:await q({fsp:a,dotgit:r}),defaultBranch:i})}catch(e){throw e.caller=`git.init`,e}}async function ui({fs:e,cache:t,gitdir:n,oid:r,ancestor:i,depth:a}){let o=await Dr.read({fs:e,gitdir:n});if(!r)throw new Mt(`oid`);if(!i)throw new Mt(`ancestor`);if(r===i)return!1;let s=[r],c=new Set,l=0;for(;s.length;){if(l++===a)throw new Ot(a);let r=s.shift(),{type:u,object:d}=await W({fs:e,cache:t,gitdir:n,oid:r});if(u!==`commit`)throw new oe(r,u,`commit`);let f=en.from(d).parse();for(let e of f.parent)if(e===i)return!0;if(!o.has(r))for(let e of f.parent)c.has(e)||(s.push(e),c.add(e))}return!1}async function di({fs:e,dir:t,gitdir:n=B(t,`.git`),remote:r}){try{K(`fs`,e),K(`gitdir`,n);let t=new G(e),i=await q({fsp:t,dotgit:n});return V.listBranches({fs:t,gitdir:i,remote:r})}catch(e){throw e.caller=`git.listBranches`,e}}async function fi({fs:e,gitdir:t,ref:n,cache:r}){if(n){let i=await V.resolve({gitdir:t,fs:e,ref:n}),a=[];return await pi({fs:e,cache:r,gitdir:t,oid:i,filenames:a,prefix:``}),a}else return M.acquire({fs:e,gitdir:t,cache:r},async function(e){return e.entries.map(e=>e.path)})}async function pi({fs:e,cache:t,gitdir:n,oid:r,filenames:i,prefix:a}){let{tree:o}=await Vn({fs:e,cache:t,gitdir:n,oid:r});for(let r of o)r.type===`tree`?await pi({fs:e,cache:t,gitdir:n,oid:r.oid,filenames:i,prefix:B(a,r.path)}):i.push(B(a,r.path))}async function mi({fs:e,dir:t,gitdir:n=B(t,`.git`),ref:r,cache:i={}}){try{K(`fs`,e),K(`gitdir`,n);let t=new G(e);return await fi({fs:t,cache:i,gitdir:await q({fsp:t,dotgit:n}),ref:r})}catch(e){throw e.caller=`git.listFiles`,e}}async function hi({fs:e,gitdir:t}){let n=await Ne.get({fs:e,gitdir:t}),r=await n.getSubsections(`remote`);return Promise.all(r.map(async e=>({remote:e,url:await n.get(`remote.${e}.url`)})))}async function gi({fs:e,dir:t,gitdir:n=B(t,`.git`)}){try{K(`fs`,e),K(`gitdir`,n);let t=new G(e);return await hi({fs:t,gitdir:await q({fsp:t,dotgit:n})})}catch(e){throw e.caller=`git.listRemotes`,e}}async function _i({fs:e,dir:t,gitdir:n=B(t,`.git`)}){try{K(`fs`,e),K(`gitdir`,n);let t=new G(e),r=await q({fsp:t,dotgit:n});return V.listTags({fs:t,gitdir:r})}catch(e){throw e.caller=`git.listTags`,e}}function vi(e,t){return e.committer.timestamp-t.committer.timestamp}var yi=`e69de29bb2d1d6434b8b29ae775ad8c2e48c5391`;async function bi({fs:e,cache:t,gitdir:n,oid:r,fileId:i}){if(i===yi)return;let a=r,o,s=await tn({fs:e,cache:t,gitdir:n,oid:r}),c=s.tree;return i===s.oid?o=s.path:(o=await xi({fs:e,cache:t,gitdir:n,tree:c,fileId:i,oid:a}),Array.isArray(o)&&(o.length===0?o=void 0:o.length===1&&(o=o[0]))),o}async function xi({fs:e,cache:t,gitdir:n,tree:r,fileId:i,oid:a,filepaths:o=[],parentPath:s=``}){let c=r.entries().map(function(r){let c;return r.oid===i?(c=B(s,r.path),o.push(c)):r.type===`tree`&&(c=W({fs:e,cache:t,gitdir:n,oid:r.oid}).then(function({object:c}){return xi({fs:e,cache:t,gitdir:n,tree:Ge.from(c),fileId:i,oid:a,filepaths:o,parentPath:B(s,r.path)})})),c});return await Promise.all(c),o}async function Si({fs:e,cache:t,gitdir:n,filepath:r,ref:i,depth:a,since:o,force:s,follow:c}){let l=o===void 0?void 0:Math.floor(o.valueOf()/1e3),u=[],d=await Dr.read({fs:e,gitdir:n}),f=[await In({fs:e,cache:t,gitdir:n,oid:await V.resolve({fs:e,gitdir:n,ref:i})})],p,m,h;function g(e){h&&r&&u.push(e)}for(;f.length>0;){let i=f.pop();if(l!==void 0&&i.commit.committer.timestamp<=l)break;if(r){let a;try{a=await zn({fs:e,cache:t,gitdir:n,oid:i.commit.tree,filepath:r}),m&&p!==a&&u.push(m),p=a,m=i,h=!0}catch(a){if(a instanceof z){let o=c&&p;if(o&&(o=await bi({fs:e,cache:t,gitdir:n,oid:i.commit.tree,fileId:p}),o))if(Array.isArray(o)){if(m){let i=await bi({fs:e,cache:t,gitdir:n,oid:m.commit.tree,fileId:p});if(Array.isArray(i))if(o=o.filter(e=>i.indexOf(e)===-1),o.length===1)o=o[0],r=o,m&&u.push(m);else{o=!1,m&&u.push(m);break}}}else r=o,m&&u.push(m);if(!o){if(h&&p&&(u.push(m),!s))break;if(!s&&!c)throw a}m=i,h=!1}else throw a}}else u.push(i);if(a!==void 0&&u.length===a){g(i);break}if(!d.has(i.oid))for(let r of i.commit.parent){let i=await In({fs:e,cache:t,gitdir:n,oid:r});f.map(e=>e.oid).includes(i.oid)||f.push(i)}f.length===0&&g(i),f.sort((e,t)=>vi(e.commit,t.commit))}return u}async function Ci({fs:e,dir:t,gitdir:n=B(t,`.git`),filepath:r,ref:i=`HEAD`,depth:a,since:o,force:s,follow:c,cache:l={}}){try{K(`fs`,e),K(`gitdir`,n),K(`ref`,i);let t=new G(e);return await Si({fs:t,cache:l,gitdir:await q({fsp:t,dotgit:n}),filepath:r,ref:i,depth:a,since:o,force:s,follow:c})}catch(e){throw e.caller=`git.log`,e}}async function wi({fs:e,onSign:t,dir:n,gitdir:r=B(n,`.git`),ours:i,theirs:a,fastForward:o=!0,fastForwardOnly:s=!1,dryRun:c=!1,noUpdateBranch:l=!1,abortOnConflict:u=!0,message:d,author:f,committer:p,signingKey:m,cache:h={},mergeDriver:g,allowUnrelatedHistories:_=!1}){try{K(`fs`,e),m&&K(`onSign`,t);let v=new G(e),y=await q({fsp:v,dotgit:r}),b=await Nn({fs:v,gitdir:y,author:f});if(!b&&(!s||!o))throw new jt(`author`);let x=await Pn({fs:v,gitdir:y,author:b,committer:p});if(!x&&(!s||!o))throw new jt(`committer`);return await ri({fs:v,cache:h,dir:n,gitdir:y,ours:i,theirs:a,fastForward:o,fastForwardOnly:s,dryRun:c,noUpdateBranch:l,abortOnConflict:u,message:d,author:b,committer:x,signingKey:m,onSign:t,mergeDriver:g,allowUnrelatedHistories:_})}catch(e){throw e.caller=`git.merge`,e}}var Ti={commit:16,tree:32,blob:48,tag:64,ofs_delta:96,ref_delta:112};async function Ei({fs:e,cache:t,dir:n,gitdir:i=B(n,`.git`),oids:a}){let o=new r,s=[];function c(e,t){let n=Buffer.from(e,t);s.push(n),o.update(n)}async function l({stype:e,object:t}){let n=Ti[e],r=t.length,i=r>15?128:0,a=r&15;r>>>=4;let o=(i|n|a).toString(16);for(c(o,`hex`);i;)i=r>127?128:0,o=i|r&127,c(hr(2,o),`hex`),r>>>=7;c(Buffer.from(await wn(t)))}c(`PACK`),c(`00000002`,`hex`),c(hr(8,a.length),`hex`);for(let n of a){let{type:r,object:a}=await W({fs:e,cache:t,gitdir:i,oid:n});await l({write:c,object:a,stype:r})}let u=o.digest();return s.push(u),s}async function Di({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,dir:s,gitdir:c=B(s,`.git`),ref:l,url:u,remote:d,remoteRef:f,prune:p=!1,pruneTags:m=!1,fastForward:h=!0,fastForwardOnly:g=!1,corsProxy:_,singleBranch:v,headers:y={},author:b,committer:x,signingKey:S,cache:C={}}){try{K(`fs`,e),K(`gitdir`,c);let w=new G(e),T=await q({fsp:w,dotgit:c}),E=await Nn({fs:w,gitdir:T,author:b});if(!E)throw new jt(`author`);let D=await Pn({fs:w,gitdir:T,author:E,committer:x});if(!D)throw new jt(`committer`);return await ii({fs:w,cache:C,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,dir:s,gitdir:T,ref:l,url:u,remote:d,remoteRef:f,fastForward:h,fastForwardOnly:g,corsProxy:_,singleBranch:v,headers:y,author:E,committer:D,signingKey:S,prune:p,pruneTags:m})}catch(e){throw e.caller=`git.pull`,e}}async function Oi({fs:e,cache:t,dir:n,gitdir:r=B(n,`.git`),start:i,finish:a}){let o=await Dr.read({fs:e,gitdir:r}),s=new Set,c=new Set;for(let t of i)s.add(await V.resolve({fs:e,gitdir:r,ref:t}));for(let t of a)try{let n=await V.resolve({fs:e,gitdir:r,ref:t});c.add(n)}catch{}let l=new Set;async function u(n){l.add(n);let{type:i,object:a}=await W({fs:e,cache:t,gitdir:r,oid:n});if(i===`tag`){let e=Zt.from(a).headers().object;return u(e)}if(i!==`commit`)throw new oe(n,i,`commit`);if(!o.has(n))for(n of en.from(a).headers().parent)!c.has(n)&&!l.has(n)&&await u(n)}for(let e of s)await u(e);return l}async function ki({fs:e,cache:t,dir:n,gitdir:r=B(n,`.git`),oids:i}){let a=new Set;async function o(n){if(a.has(n))return;a.add(n);let{type:i,object:s}=await W({fs:e,cache:t,gitdir:r,oid:n});if(i===`tag`){let e=Zt.from(s).headers().object;await o(e)}else if(i===`commit`){let e=en.from(s).headers().tree;await o(e)}else if(i===`tree`){let e=Ge.from(s);for(let t of e)t.type===`blob`&&a.add(t.oid),t.type===`tree`&&await o(t.oid)}}for(let e of i)await o(e);return a}async function Ai(e){let t={},n=``,r=gr.streamReader(e),i=await r();for(;i!==!0;)i!==null&&(n+=i.toString(`utf8`)+`
|
|
786
786
|
`),i=await r();let a=n.toString(`utf8`).split(`
|
|
787
|
-
`);if(i=a.shift(),!i.startsWith(`unpack `))throw new Pt(`unpack ok" or "unpack [error message]`,i);t.ok=i===`unpack ok`,t.ok||(t.error=i.slice(7)),t.refs={};for(let e of a){if(e.trim()===``)continue;let n=e.slice(0,2),r=e.slice(3),i=r.indexOf(` `);i===-1&&(i=r.length);let a=r.slice(0,i),o=r.slice(i+1);t.refs[a]={ok:n===`ok`,error:o}}return t}async function ji({capabilities:e=[],triplets:t=[]}){let n=[],r=`\x00 ${e.join(` `)}`;for(let e of t)n.push(gr.encode(`${e.oldoid} ${e.oid} ${e.fullRef}${r}\n`)),r=``;return n.push(gr.flush()),n}async function Mi({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,onPrePush:c,gitdir:l,ref:u,remoteRef:d,remote:f,url:p,force:m=!1,delete:h=!1,corsProxy:g,headers:_={}}){let v=u||await lr({fs:e,gitdir:l});if(v===void 0)throw new Mt(`ref`);let y=await Ne.get({fs:e,gitdir:l});f=f||await y.get(`branch.${v}.pushRemote`)||await y.get(`remote.pushDefault`)||await y.get(`branch.${v}.remote`)||`origin`;let b=p||await y.get(`remote.${f}.pushurl`)||await y.get(`remote.${f}.url`);if(b===void 0)throw new Mt(`remote OR url`);let x=d||await y.get(`branch.${v}.merge`);if(b===void 0)throw new Mt(`remoteRef`);g===void 0&&(g=await y.get(`http.corsProxy`));let S=await V.expand({fs:e,gitdir:l,ref:v}),C=h?`0000000000000000000000000000000000000000`:await V.resolve({fs:e,gitdir:l,ref:S}),w=wr.getRemoteHelperFor({url:b}),T=await w.discover({http:n,onAuth:a,onAuthSuccess:o,onAuthFailure:s,corsProxy:g,service:`git-receive-pack`,url:b,headers:_,protocolVersion:1}),E=T.auth,D;if(!x)D=S;else try{D=await V.expandAgainstMap({ref:x,map:T.refs})}catch(e){if(e instanceof z)D=x.startsWith(`refs/`)?x:`refs/heads/${x}`;else throw e}let O=T.refs.get(D)||`0000000000000000000000000000000000000000`;if(c&&!await c({remote:f,url:b,localRef:{ref:h?`(delete)`:S,oid:C},remoteRef:{ref:D,oid:O}}))throw new Bt;let k=!T.capabilities.has(`no-thin`),ee=new Set;if(!h){let n=[...T.refs.values()],r=new Set;if(O!==`0000000000000000000000000000000000000000`){let i=await ni({fs:e,cache:t,gitdir:l,oids:[C,O]});for(let e of i)n.push(e);k&&(r=await ki({fs:e,cache:t,gitdir:l,oids:i}))}if(n.includes(C)||(ee=await ki({fs:e,cache:t,gitdir:l,oids:await Oi({fs:e,cache:t,gitdir:l,start:[C],finish:n})})),k){try{let n=await V.resolve({fs:e,gitdir:l,ref:`refs/remotes/${f}/HEAD`,depth:2}),{oid:i}=await V.resolveAgainstMap({ref:n.replace(`refs/remotes/${f}/`,``),fullref:n,map:T.refs}),a=[i];for(let n of await ki({fs:e,cache:t,gitdir:l,oids:a}))r.add(n)}catch{}for(let e of r)ee.delete(e)}if(C===O&&(m=!0),!m){if(S.startsWith(`refs/tags`)&&O!==`0000000000000000000000000000000000000000`)throw new Ft(`tag-exists`);if(C!==`0000000000000000000000000000000000000000`&&O!==`0000000000000000000000000000000000000000`&&!await ui({fs:e,cache:t,gitdir:l,oid:C,ancestor:O,depth:-1}))throw new Ft(`not-fast-forward`)}}let A=await ji({capabilities:Mr([...T.capabilities],[`report-status`,`side-band-64k`,`agent=${Nr.agent}`]),triplets:[{oldoid:O,oid:C,fullRef:D}]}),j=h?[]:await Ei({fs:e,cache:t,gitdir:l,oids:[...ee]}),te=await w.connect({http:n,onProgress:r,corsProxy:g,service:`git-receive-pack`,url:b,auth:E,headers:_,body:[...A,...j]}),{packfile:ne,progress:re}=await Lr.demux(te.body);i&&fr(Ir(re),async e=>{await i(e)});let ie=await Ai(ne);if(te.headers&&(ie.headers=te.headers),f&&ie.ok&&ie.refs[D].ok&&!S.startsWith(`refs/tags`)){let t=`refs/remotes/${f}/${D.replace(`refs/heads`,``)}`;h?await V.deleteRef({fs:e,gitdir:l,ref:t}):await V.writeRef({fs:e,gitdir:l,ref:t,value:C})}if(ie.ok&&Object.values(ie.refs).every(e=>e.ok))return ie;throw new wt(Object.entries(ie.refs).filter(([e,t])=>!t.ok).map(([e,t])=>`\n - ${e}: ${t.error}`).join(``),ie)}async function Ni({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPrePush:s,dir:c,gitdir:l=B(c,`.git`),ref:u,remoteRef:d,remote:f=`origin`,url:p,force:m=!1,delete:h=!1,corsProxy:g,headers:_={},cache:v={}}){try{K(`fs`,e),K(`http`,t),K(`gitdir`,l);let c=new G(e);return await Mi({fs:c,cache:v,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPrePush:s,gitdir:await q({fsp:c,dotgit:l}),ref:u,remoteRef:d,remote:f,url:p,force:m,delete:h,corsProxy:g,headers:_})}catch(e){throw e.caller=`git.push`,e}}async function Pi({fs:e,cache:t,gitdir:n,oid:r}){let{type:i,object:a}=await W({fs:e,cache:t,gitdir:n,oid:r});if(i===`tag`)return r=Zt.from(a).parse().object,Pi({fs:e,cache:t,gitdir:n,oid:r});if(i!==`blob`)throw new oe(r,i,`blob`);return{oid:r,blob:new Uint8Array(a)}}async function Fi({fs:e,cache:t,gitdir:n,oid:r,filepath:i=void 0}){return i!==void 0&&(r=await zn({fs:e,cache:t,gitdir:n,oid:r,filepath:i})),await Pi({fs:e,cache:t,gitdir:n,oid:r})}async function Ii({fs:e,dir:t,gitdir:n=B(t,`.git`),oid:r,filepath:i,cache:a={}}){try{K(`fs`,e),K(`gitdir`,n),K(`oid`,r);let t=new G(e);return await Fi({fs:t,cache:a,gitdir:await q({fsp:t,dotgit:n}),oid:r,filepath:i})}catch(e){throw e.caller=`git.readBlob`,e}}async function Li({fs:e,dir:t,gitdir:n=B(t,`.git`),oid:r,cache:i={}}){try{K(`fs`,e),K(`gitdir`,n),K(`oid`,r);let t=new G(e);return await In({fs:t,cache:i,gitdir:await q({fsp:t,dotgit:n}),oid:r})}catch(e){throw e.caller=`git.readCommit`,e}}async function Ri({fs:e,dir:t,gitdir:n=B(t,`.git`),oid:r,filepath:i=void 0,cache:a={}}){try{K(`fs`,e),K(`gitdir`,n),K(`oid`,r);let t=new G(e);return await Vn({fs:t,cache:a,gitdir:await q({fsp:t,dotgit:n}),oid:r,filepath:i})}catch(e){throw e.caller=`git.readTree`,e}}async function zi({fs:e,dir:t,gitdir:n=B(t,`.git`),filepath:r,cache:i={}}){try{K(`fs`,e),K(`gitdir`,n),K(`filepath`,r);let t=new G(e),a=await q({fsp:t,dotgit:n});await M.acquire({fs:t,gitdir:a,cache:i},async function(e){e.delete({filepath:r})})}catch(e){throw e.caller=`git.remove`,e}}async function Bi({gitdir:e,type:t,object:n}){return w(Ke.wrap({type:t,object:n}))}async function Vi({fs:e,dir:t,gitdir:n=B(t,`.git`),filepath:r,ref:i,cache:a={}}){try{K(`fs`,e),K(`gitdir`,n),K(`filepath`,r);let o=new G(e),s=await q({fsp:o,dotgit:n}),c,l;try{c=await V.resolve({fs:o,gitdir:s,ref:i||`HEAD`})}catch(e){if(i)throw e}if(c)try{c=await zn({fs:o,cache:a,gitdir:s,oid:c,filepath:r})}catch{c=null}let u={ctime:new Date(0),mtime:new Date(0),dev:0,ino:0,mode:0,uid:0,gid:0,size:0},d=t&&await o.read(B(t,r));d&&(l=await Bi({gitdir:s,type:`blob`,object:d}),c===l&&(u=await o.lstat(B(t,r)))),await M.acquire({fs:o,gitdir:s,cache:a},async function(e){e.delete({filepath:r}),c&&e.insert({filepath:r,stats:u,oid:c})})}catch(e){throw e.caller=`git.reset`,e}}async function Hi({fs:e,dir:t,gitdir:n=B(t,`.git`),ref:r,depth:i}){try{K(`fs`,e),K(`gitdir`,n),K(`ref`,r);let t=new G(e),a=await q({fsp:t,dotgit:n});return await V.resolve({fs:t,gitdir:a,ref:r,depth:i})}catch(e){throw e.caller=`git.resolveRef`,e}}async function Ui({fs:e,dir:t,gitdir:n=B(t,`.git`),path:r,value:i,append:a=!1}){try{K(`fs`,e),K(`gitdir`,n),K(`path`,r);let t=new G(e),o=await q({fsp:t,dotgit:n}),s=await Ne.get({fs:t,gitdir:o});a?await s.append(r,i):await s.set(r,i),await Ne.save({fs:t,gitdir:o,config:s})}catch(e){throw e.caller=`git.setConfig`,e}}async function Wi({fs:e,gitdir:t,commit:n}){return await Dn({fs:e,gitdir:t,type:`commit`,object:en.from(n).toObject(),format:`content`})}async function Gi({fs:e,dir:t,gitdir:n=B(t,`.git`),ref:r=`HEAD`,filepaths:i=[`.`],filter:a,cache:o={},ignored:s=!1}){try{K(`fs`,e),K(`gitdir`,n),K(`ref`,r);let c=new G(e);return await dn({fs:c,cache:o,dir:t,gitdir:await q({fsp:c,dotgit:n}),trees:[rn({ref:r}),on(),R()],map:async function(e,[n,r,o]){if(!n&&!o&&r&&!s&&await xn.isIgnored({fs:c,dir:t,filepath:e})||!i.some(t=>Xn(e,t)))return null;if(a&&!a(e))return;let[l,u,d]=await Promise.all([n&&n.type(),r&&r.type(),o&&o.type()]),f=[l,u,d].includes(`blob`);if((l===`tree`||l===`special`)&&!f)return;if(l===`commit`)return null;if((u===`tree`||u===`special`)&&!f)return;if(d===`commit`)return null;if((d===`tree`||d===`special`)&&!f)return;let p=l===`blob`?await n.oid():void 0,m=d===`blob`?await o.oid():void 0,h;l!==`blob`&&u===`blob`&&d!==`blob`?h=`42`:u===`blob`&&(h=await r.oid());let g=[void 0,p,h,m],_=g.map(e=>g.indexOf(e));return _.shift(),[e,..._]}})}catch(e){throw e.caller=`git.statusMatrix`,e}}async function Ki({fs:e,dir:t,gitdir:n=B(t,`.git`),ref:r,object:i,force:a=!1}){try{K(`fs`,e),K(`gitdir`,n),K(`ref`,r);let t=new G(e);if(r===void 0)throw new Mt(`ref`);r=r.startsWith(`refs/tags/`)?r:`refs/tags/${r}`;let o=await q({fsp:t,dotgit:n}),s=await V.resolve({fs:t,gitdir:o,ref:i||`HEAD`});if(!a&&await V.exists({fs:t,gitdir:o,ref:r}))throw new gt(`tag`,r);await V.writeRef({fs:t,gitdir:o,ref:r,value:s})}catch(e){throw e.caller=`git.tag`,e}}function qi(){try{return Nr.version}catch(e){throw e.caller=`git.version`,e}}async function Ji({fs:e,dir:t,gitdir:n=B(t,`.git`),trees:r,map:i,reduce:a,iterate:o,cache:s={}}){try{K(`fs`,e),K(`gitdir`,n),K(`trees`,r);let c=new G(e);return await dn({fs:c,cache:s,dir:t,gitdir:await q({fsp:c,dotgit:n}),trees:r,map:i,reduce:a,iterate:o})}catch(e){throw e.caller=`git.walk`,e}}async function Yi({fs:e,dir:t,gitdir:n=B(t,`.git`),blob:r}){try{K(`fs`,e),K(`gitdir`,n),K(`blob`,r);let t=new G(e);return await Dn({fs:t,gitdir:await q({fsp:t,dotgit:n}),type:`blob`,object:r,format:`content`})}catch(e){throw e.caller=`git.writeBlob`,e}}async function Xi({fs:e,dir:t,gitdir:n=B(t,`.git`),commit:r}){try{K(`fs`,e),K(`gitdir`,n),K(`commit`,r);let t=new G(e);return await Wi({fs:t,gitdir:await q({fsp:t,dotgit:n}),commit:r})}catch(e){throw e.caller=`git.writeCommit`,e}}async function Zi({fs:e,dir:t,gitdir:n=B(t,`.git`),ref:r,value:i,force:a=!1,symbolic:o=!1}){try{K(`fs`,e),K(`gitdir`,n),K(`ref`,r),K(`value`,i);let t=new G(e);if(!Wn(r,!0))throw new Dt(r,l.clean(r));let s=await q({fsp:t,dotgit:n});if(!a&&await V.exists({fs:t,gitdir:s,ref:r}))throw new gt(`ref`,r);o?await V.writeSymbolicRef({fs:t,gitdir:s,ref:r,value:i}):(i=await V.resolve({fs:t,gitdir:s,ref:i}),await V.writeRef({fs:t,gitdir:s,ref:r,value:i}))}catch(e){throw e.caller=`git.writeRef`,e}}async function Qi({fs:e,dir:t,gitdir:n=B(t,`.git`),tree:r}){try{K(`fs`,e),K(`gitdir`,n),K(`tree`,r);let t=new G(e);return await Hn({fs:t,gitdir:await q({fsp:t,dotgit:n}),tree:r})}catch(e){throw e.caller=`git.writeTree`,e}}e.STAGE=R,e.TREE=rn,e.add=kn,e.addRemote=J,e.annotatedTag=qn,e.branch=Yn,e.checkout=nr,e.clone=Ur,e.commit=Wr,e.currentBranch=Gr,e.deleteBranch=qr,e.deleteRemote=Yr,e.deleteTag=Zr,e.expandOid=ti,e.fetch=ai,e.findRoot=si,e.getConfig=ci,e.init=li,e.listBranches=di,e.listFiles=mi,e.listRemotes=gi,e.listTags=_i,e.log=Ci,e.merge=wi,e.pull=Di,e.push=Ni,e.readBlob=Ii,e.readCommit=Li,e.readTree=Ri,e.remove=zi,e.resetIndex=Vi,e.resolveRef=Hi,e.setConfig=Ui,e.statusMatrix=Gi,e.tag=Ki,e.version=qi,e.walk=Ji,e.writeBlob=Yi,e.writeCommit=Xi,e.writeRef=Zi,e.writeTree=Qi}))(),1);function jo(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function Mo(){return{request:async e=>{let{url:t,method:n=`GET`,headers:r={},body:i,onProgress:a}=e,o;if(i){let e=[];for await(let t of i)e.push(t);let t=e.reduce((e,t)=>e+t.length,0);o=new Uint8Array(t);let n=0;for(let t of e)o.set(t,n),n+=t.length}let s,c=r[`content-type`]??`application/octet-stream`,l=o?new Blob([o.buffer],{type:c}):void 0;if(jo())s=await fetch(t,{method:n,headers:r,body:l});else{let e={...r,"X-Target-URL":t};if(r[`content-type`]&&(e[`Content-Type`]=r[`content-type`]),s=await fetch(`/api/fetch-proxy`,{method:n,headers:e,body:l}),s.status===502||s.status===400){let e=await s.text(),t=`Proxy error ${s.status}`;try{t=JSON.parse(e).error??t}catch{}throw Error(t)}}let u={};s.headers.forEach((e,t)=>{u[t]=e});let d=s.body,f;if(d){let e=d.getReader(),t=0;f={[Symbol.asyncIterator](){return this},async next(){let{done:n,value:r}=await e.read();return n?{done:!0,value:void 0}:(t+=r.length,a&&a({phase:`Receiving`,loaded:t,total:parseInt(u[`content-length`]??`0`,10)||t}),{done:!1,value:r})}}}return{url:s.url||t,method:n,headers:u,body:f,statusCode:s.status,statusMessage:s.statusText}}}}var No=Mo();function Po(e,t){let n=e.length,r=t.length;if(n===0&&r===0)return[];if(n===0)return t.map(e=>({type:`insert`,line:e}));if(r===0)return e.map(e=>({type:`delete`,line:e}));let i=n+r,a=i,o=2*i+1,s=[],c=Array(o).fill(0),l=-1;outer:for(let o=0;o<=i;o++){s.push(c.slice());for(let i=-o;i<=o;i+=2){let s;s=i===-o||i!==o&&c[i-1+a]<c[i+1+a]?c[i+1+a]:c[i-1+a]+1;let u=s-i;for(;s<n&&u<r&&e[s]===t[u];)s++,u++;if(c[i+a]=s,s>=n&&u>=r){l=o;break outer}}}l===-1&&(l=i);let u=[],d=n,f=r;for(let n=l;n>0;n--){let r=s[n],i=d-f,o;o=i===-n||i!==n&&r[i-1+a]<r[i+1+a]?i+1:i-1;let c=r[o+a],l=c-o;for(;d>c&&f>l;)d--,f--,u.push({type:`equal`,line:e[d]});d===c&&f>l?(f--,u.push({type:`insert`,line:t[f]})):f===l&&d>c&&(d--,u.push({type:`delete`,line:e[d]}))}for(;d>0&&f>0;)d--,f--,u.push({type:`equal`,line:e[d]});return u.reverse(),u}function Fo(e,t=3){let n=[],r=[];for(let t=0;t<e.length;t++)e[t].type!==`equal`&&r.push(t);if(r.length===0)return[];let i=0,a=[];for(let e=1;e<r.length;e++)r[e]-r[e-1]>2*t&&(a.push([i,e-1]),i=e);a.push([i,r.length-1]);for(let[i,o]of a){let a=r[i],s=r[o],c=Math.max(0,a-t),l=Math.min(e.length-1,s+t),u=[],d=0,f=0;for(let t=0;t<c;t++)(e[t].type===`equal`||e[t].type===`delete`)&&d++,(e[t].type===`equal`||e[t].type===`insert`)&&f++;let p=d+1,m=f+1,h=0,g=0;for(let t=c;t<=l;t++){let n=e[t];switch(n.type){case`equal`:u.push(` ${n.line}`),h++,g++;break;case`delete`:u.push(`-${n.line}`),h++;break;case`insert`:u.push(`+${n.line}`),g++;break}}n.push({oldStart:p,oldCount:h,newStart:m,newCount:g,lines:u})}return n}function Io(e){let{oldContent:t,newContent:n,oldName:r,newName:i,color:a=!0}=e;if(t===n)return``;let o=t.split(`
|
|
787
|
+
`);if(i=a.shift(),!i.startsWith(`unpack `))throw new Pt(`unpack ok" or "unpack [error message]`,i);t.ok=i===`unpack ok`,t.ok||(t.error=i.slice(7)),t.refs={};for(let e of a){if(e.trim()===``)continue;let n=e.slice(0,2),r=e.slice(3),i=r.indexOf(` `);i===-1&&(i=r.length);let a=r.slice(0,i),o=r.slice(i+1);t.refs[a]={ok:n===`ok`,error:o}}return t}async function ji({capabilities:e=[],triplets:t=[]}){let n=[],r=`\x00 ${e.join(` `)}`;for(let e of t)n.push(gr.encode(`${e.oldoid} ${e.oid} ${e.fullRef}${r}\n`)),r=``;return n.push(gr.flush()),n}async function Mi({fs:e,cache:t,http:n,onProgress:r,onMessage:i,onAuth:a,onAuthSuccess:o,onAuthFailure:s,onPrePush:c,gitdir:l,ref:u,remoteRef:d,remote:f,url:p,force:m=!1,delete:h=!1,corsProxy:g,headers:_={}}){let v=u||await lr({fs:e,gitdir:l});if(v===void 0)throw new Mt(`ref`);let y=await Ne.get({fs:e,gitdir:l});f=f||await y.get(`branch.${v}.pushRemote`)||await y.get(`remote.pushDefault`)||await y.get(`branch.${v}.remote`)||`origin`;let b=p||await y.get(`remote.${f}.pushurl`)||await y.get(`remote.${f}.url`);if(b===void 0)throw new Mt(`remote OR url`);let x=d||await y.get(`branch.${v}.merge`);if(b===void 0)throw new Mt(`remoteRef`);g===void 0&&(g=await y.get(`http.corsProxy`));let S=await V.expand({fs:e,gitdir:l,ref:v}),C=h?`0000000000000000000000000000000000000000`:await V.resolve({fs:e,gitdir:l,ref:S}),w=wr.getRemoteHelperFor({url:b}),T=await w.discover({http:n,onAuth:a,onAuthSuccess:o,onAuthFailure:s,corsProxy:g,service:`git-receive-pack`,url:b,headers:_,protocolVersion:1}),E=T.auth,D;if(!x)D=S;else try{D=await V.expandAgainstMap({ref:x,map:T.refs})}catch(e){if(e instanceof z)D=x.startsWith(`refs/`)?x:`refs/heads/${x}`;else throw e}let O=T.refs.get(D)||`0000000000000000000000000000000000000000`;if(c&&!await c({remote:f,url:b,localRef:{ref:h?`(delete)`:S,oid:C},remoteRef:{ref:D,oid:O}}))throw new Bt;let k=!T.capabilities.has(`no-thin`),A=new Set;if(!h){let n=[...T.refs.values()],r=new Set;if(O!==`0000000000000000000000000000000000000000`){let i=await ni({fs:e,cache:t,gitdir:l,oids:[C,O]});for(let e of i)n.push(e);k&&(r=await ki({fs:e,cache:t,gitdir:l,oids:i}))}if(n.includes(C)||(A=await ki({fs:e,cache:t,gitdir:l,oids:await Oi({fs:e,cache:t,gitdir:l,start:[C],finish:n})})),k){try{let n=await V.resolve({fs:e,gitdir:l,ref:`refs/remotes/${f}/HEAD`,depth:2}),{oid:i}=await V.resolveAgainstMap({ref:n.replace(`refs/remotes/${f}/`,``),fullref:n,map:T.refs}),a=[i];for(let n of await ki({fs:e,cache:t,gitdir:l,oids:a}))r.add(n)}catch{}for(let e of r)A.delete(e)}if(C===O&&(m=!0),!m){if(S.startsWith(`refs/tags`)&&O!==`0000000000000000000000000000000000000000`)throw new Ft(`tag-exists`);if(C!==`0000000000000000000000000000000000000000`&&O!==`0000000000000000000000000000000000000000`&&!await ui({fs:e,cache:t,gitdir:l,oid:C,ancestor:O,depth:-1}))throw new Ft(`not-fast-forward`)}}let ee=await ji({capabilities:Mr([...T.capabilities],[`report-status`,`side-band-64k`,`agent=${Nr.agent}`]),triplets:[{oldoid:O,oid:C,fullRef:D}]}),j=h?[]:await Ei({fs:e,cache:t,gitdir:l,oids:[...A]}),te=await w.connect({http:n,onProgress:r,corsProxy:g,service:`git-receive-pack`,url:b,auth:E,headers:_,body:[...ee,...j]}),{packfile:ne,progress:re}=await Lr.demux(te.body);i&&fr(Ir(re),async e=>{await i(e)});let ie=await Ai(ne);if(te.headers&&(ie.headers=te.headers),f&&ie.ok&&ie.refs[D].ok&&!S.startsWith(`refs/tags`)){let t=`refs/remotes/${f}/${D.replace(`refs/heads`,``)}`;h?await V.deleteRef({fs:e,gitdir:l,ref:t}):await V.writeRef({fs:e,gitdir:l,ref:t,value:C})}if(ie.ok&&Object.values(ie.refs).every(e=>e.ok))return ie;throw new wt(Object.entries(ie.refs).filter(([e,t])=>!t.ok).map(([e,t])=>`\n - ${e}: ${t.error}`).join(``),ie)}async function Ni({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPrePush:s,dir:c,gitdir:l=B(c,`.git`),ref:u,remoteRef:d,remote:f=`origin`,url:p,force:m=!1,delete:h=!1,corsProxy:g,headers:_={},cache:v={}}){try{K(`fs`,e),K(`http`,t),K(`gitdir`,l);let c=new G(e);return await Mi({fs:c,cache:v,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPrePush:s,gitdir:await q({fsp:c,dotgit:l}),ref:u,remoteRef:d,remote:f,url:p,force:m,delete:h,corsProxy:g,headers:_})}catch(e){throw e.caller=`git.push`,e}}async function Pi({fs:e,cache:t,gitdir:n,oid:r}){let{type:i,object:a}=await W({fs:e,cache:t,gitdir:n,oid:r});if(i===`tag`)return r=Zt.from(a).parse().object,Pi({fs:e,cache:t,gitdir:n,oid:r});if(i!==`blob`)throw new oe(r,i,`blob`);return{oid:r,blob:new Uint8Array(a)}}async function Fi({fs:e,cache:t,gitdir:n,oid:r,filepath:i=void 0}){return i!==void 0&&(r=await zn({fs:e,cache:t,gitdir:n,oid:r,filepath:i})),await Pi({fs:e,cache:t,gitdir:n,oid:r})}async function Ii({fs:e,dir:t,gitdir:n=B(t,`.git`),oid:r,filepath:i,cache:a={}}){try{K(`fs`,e),K(`gitdir`,n),K(`oid`,r);let t=new G(e);return await Fi({fs:t,cache:a,gitdir:await q({fsp:t,dotgit:n}),oid:r,filepath:i})}catch(e){throw e.caller=`git.readBlob`,e}}async function Li({fs:e,dir:t,gitdir:n=B(t,`.git`),oid:r,cache:i={}}){try{K(`fs`,e),K(`gitdir`,n),K(`oid`,r);let t=new G(e);return await In({fs:t,cache:i,gitdir:await q({fsp:t,dotgit:n}),oid:r})}catch(e){throw e.caller=`git.readCommit`,e}}async function Ri({fs:e,dir:t,gitdir:n=B(t,`.git`),oid:r,filepath:i=void 0,cache:a={}}){try{K(`fs`,e),K(`gitdir`,n),K(`oid`,r);let t=new G(e);return await Vn({fs:t,cache:a,gitdir:await q({fsp:t,dotgit:n}),oid:r,filepath:i})}catch(e){throw e.caller=`git.readTree`,e}}async function zi({fs:e,dir:t,gitdir:n=B(t,`.git`),filepath:r,cache:i={}}){try{K(`fs`,e),K(`gitdir`,n),K(`filepath`,r);let t=new G(e),a=await q({fsp:t,dotgit:n});await M.acquire({fs:t,gitdir:a,cache:i},async function(e){e.delete({filepath:r})})}catch(e){throw e.caller=`git.remove`,e}}async function Bi({gitdir:e,type:t,object:n}){return w(Ke.wrap({type:t,object:n}))}async function Vi({fs:e,dir:t,gitdir:n=B(t,`.git`),filepath:r,ref:i,cache:a={}}){try{K(`fs`,e),K(`gitdir`,n),K(`filepath`,r);let o=new G(e),s=await q({fsp:o,dotgit:n}),c,l;try{c=await V.resolve({fs:o,gitdir:s,ref:i||`HEAD`})}catch(e){if(i)throw e}if(c)try{c=await zn({fs:o,cache:a,gitdir:s,oid:c,filepath:r})}catch{c=null}let u={ctime:new Date(0),mtime:new Date(0),dev:0,ino:0,mode:0,uid:0,gid:0,size:0},d=t&&await o.read(B(t,r));d&&(l=await Bi({gitdir:s,type:`blob`,object:d}),c===l&&(u=await o.lstat(B(t,r)))),await M.acquire({fs:o,gitdir:s,cache:a},async function(e){e.delete({filepath:r}),c&&e.insert({filepath:r,stats:u,oid:c})})}catch(e){throw e.caller=`git.reset`,e}}async function Hi({fs:e,dir:t,gitdir:n=B(t,`.git`),ref:r,depth:i}){try{K(`fs`,e),K(`gitdir`,n),K(`ref`,r);let t=new G(e),a=await q({fsp:t,dotgit:n});return await V.resolve({fs:t,gitdir:a,ref:r,depth:i})}catch(e){throw e.caller=`git.resolveRef`,e}}async function Ui({fs:e,dir:t,gitdir:n=B(t,`.git`),path:r,value:i,append:a=!1}){try{K(`fs`,e),K(`gitdir`,n),K(`path`,r);let t=new G(e),o=await q({fsp:t,dotgit:n}),s=await Ne.get({fs:t,gitdir:o});a?await s.append(r,i):await s.set(r,i),await Ne.save({fs:t,gitdir:o,config:s})}catch(e){throw e.caller=`git.setConfig`,e}}async function Wi({fs:e,gitdir:t,commit:n}){return await Dn({fs:e,gitdir:t,type:`commit`,object:en.from(n).toObject(),format:`content`})}async function Gi({fs:e,dir:t,gitdir:n=B(t,`.git`),ref:r=`HEAD`,filepaths:i=[`.`],filter:a,cache:o={},ignored:s=!1}){try{K(`fs`,e),K(`gitdir`,n),K(`ref`,r);let c=new G(e);return await dn({fs:c,cache:o,dir:t,gitdir:await q({fsp:c,dotgit:n}),trees:[rn({ref:r}),on(),R()],map:async function(e,[n,r,o]){if(!n&&!o&&r&&!s&&await xn.isIgnored({fs:c,dir:t,filepath:e})||!i.some(t=>Xn(e,t)))return null;if(a&&!a(e))return;let[l,u,d]=await Promise.all([n&&n.type(),r&&r.type(),o&&o.type()]),f=[l,u,d].includes(`blob`);if((l===`tree`||l===`special`)&&!f)return;if(l===`commit`)return null;if((u===`tree`||u===`special`)&&!f)return;if(d===`commit`)return null;if((d===`tree`||d===`special`)&&!f)return;let p=l===`blob`?await n.oid():void 0,m=d===`blob`?await o.oid():void 0,h;l!==`blob`&&u===`blob`&&d!==`blob`?h=`42`:u===`blob`&&(h=await r.oid());let g=[void 0,p,h,m],_=g.map(e=>g.indexOf(e));return _.shift(),[e,..._]}})}catch(e){throw e.caller=`git.statusMatrix`,e}}async function Ki({fs:e,dir:t,gitdir:n=B(t,`.git`),ref:r,object:i,force:a=!1}){try{K(`fs`,e),K(`gitdir`,n),K(`ref`,r);let t=new G(e);if(r===void 0)throw new Mt(`ref`);r=r.startsWith(`refs/tags/`)?r:`refs/tags/${r}`;let o=await q({fsp:t,dotgit:n}),s=await V.resolve({fs:t,gitdir:o,ref:i||`HEAD`});if(!a&&await V.exists({fs:t,gitdir:o,ref:r}))throw new gt(`tag`,r);await V.writeRef({fs:t,gitdir:o,ref:r,value:s})}catch(e){throw e.caller=`git.tag`,e}}function qi(){try{return Nr.version}catch(e){throw e.caller=`git.version`,e}}async function Ji({fs:e,dir:t,gitdir:n=B(t,`.git`),trees:r,map:i,reduce:a,iterate:o,cache:s={}}){try{K(`fs`,e),K(`gitdir`,n),K(`trees`,r);let c=new G(e);return await dn({fs:c,cache:s,dir:t,gitdir:await q({fsp:c,dotgit:n}),trees:r,map:i,reduce:a,iterate:o})}catch(e){throw e.caller=`git.walk`,e}}async function Yi({fs:e,dir:t,gitdir:n=B(t,`.git`),blob:r}){try{K(`fs`,e),K(`gitdir`,n),K(`blob`,r);let t=new G(e);return await Dn({fs:t,gitdir:await q({fsp:t,dotgit:n}),type:`blob`,object:r,format:`content`})}catch(e){throw e.caller=`git.writeBlob`,e}}async function Xi({fs:e,dir:t,gitdir:n=B(t,`.git`),commit:r}){try{K(`fs`,e),K(`gitdir`,n),K(`commit`,r);let t=new G(e);return await Wi({fs:t,gitdir:await q({fsp:t,dotgit:n}),commit:r})}catch(e){throw e.caller=`git.writeCommit`,e}}async function Zi({fs:e,dir:t,gitdir:n=B(t,`.git`),ref:r,value:i,force:a=!1,symbolic:o=!1}){try{K(`fs`,e),K(`gitdir`,n),K(`ref`,r),K(`value`,i);let t=new G(e);if(!Wn(r,!0))throw new Dt(r,l.clean(r));let s=await q({fsp:t,dotgit:n});if(!a&&await V.exists({fs:t,gitdir:s,ref:r}))throw new gt(`ref`,r);o?await V.writeSymbolicRef({fs:t,gitdir:s,ref:r,value:i}):(i=await V.resolve({fs:t,gitdir:s,ref:i}),await V.writeRef({fs:t,gitdir:s,ref:r,value:i}))}catch(e){throw e.caller=`git.writeRef`,e}}async function Qi({fs:e,dir:t,gitdir:n=B(t,`.git`),tree:r}){try{K(`fs`,e),K(`gitdir`,n),K(`tree`,r);let t=new G(e);return await Hn({fs:t,gitdir:await q({fsp:t,dotgit:n}),tree:r})}catch(e){throw e.caller=`git.writeTree`,e}}e.STAGE=R,e.TREE=rn,e.add=kn,e.addRemote=J,e.annotatedTag=qn,e.branch=Yn,e.checkout=nr,e.clone=Ur,e.commit=Wr,e.currentBranch=Gr,e.deleteBranch=qr,e.deleteRemote=Yr,e.deleteTag=Zr,e.expandOid=ti,e.fetch=ai,e.findRoot=si,e.getConfig=ci,e.init=li,e.listBranches=di,e.listFiles=mi,e.listRemotes=gi,e.listTags=_i,e.log=Ci,e.merge=wi,e.pull=Di,e.push=Ni,e.readBlob=Ii,e.readCommit=Li,e.readTree=Ri,e.remove=zi,e.resetIndex=Vi,e.resolveRef=Hi,e.setConfig=Ui,e.statusMatrix=Gi,e.tag=Ki,e.version=qi,e.walk=Ji,e.writeBlob=Yi,e.writeCommit=Xi,e.writeRef=Zi,e.writeTree=Qi}))(),1);function jo(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function Mo(){return{request:async e=>{let{url:t,method:n=`GET`,headers:r={},body:i,onProgress:a}=e,o;if(i){let e=[];for await(let t of i)e.push(t);let t=e.reduce((e,t)=>e+t.length,0);o=new Uint8Array(t);let n=0;for(let t of e)o.set(t,n),n+=t.length}let s,c=r[`content-type`]??`application/octet-stream`,l=o?new Blob([o.buffer],{type:c}):void 0;if(jo())s=await fetch(t,{method:n,headers:r,body:l});else{let e={...r,"X-Target-URL":t};if(r[`content-type`]&&(e[`Content-Type`]=r[`content-type`]),s=await fetch(`/api/fetch-proxy`,{method:n,headers:e,body:l}),s.status===502||s.status===400){let e=await s.text(),t=`Proxy error ${s.status}`;try{t=JSON.parse(e).error??t}catch{}throw Error(t)}}let u={};s.headers.forEach((e,t)=>{u[t]=e});let d=s.body,f;if(d){let e=d.getReader(),t=0;f={[Symbol.asyncIterator](){return this},async next(){let{done:n,value:r}=await e.read();return n?{done:!0,value:void 0}:(t+=r.length,a&&a({phase:`Receiving`,loaded:t,total:parseInt(u[`content-length`]??`0`,10)||t}),{done:!1,value:r})}}}return{url:s.url||t,method:n,headers:u,body:f,statusCode:s.status,statusMessage:s.statusText}}}}var No=Mo();function Po(e,t){let n=e.length,r=t.length;if(n===0&&r===0)return[];if(n===0)return t.map(e=>({type:`insert`,line:e}));if(r===0)return e.map(e=>({type:`delete`,line:e}));let i=n+r,a=i,o=2*i+1,s=[],c=Array(o).fill(0),l=-1;outer:for(let o=0;o<=i;o++){s.push(c.slice());for(let i=-o;i<=o;i+=2){let s;s=i===-o||i!==o&&c[i-1+a]<c[i+1+a]?c[i+1+a]:c[i-1+a]+1;let u=s-i;for(;s<n&&u<r&&e[s]===t[u];)s++,u++;if(c[i+a]=s,s>=n&&u>=r){l=o;break outer}}}l===-1&&(l=i);let u=[],d=n,f=r;for(let n=l;n>0;n--){let r=s[n],i=d-f,o;o=i===-n||i!==n&&r[i-1+a]<r[i+1+a]?i+1:i-1;let c=r[o+a],l=c-o;for(;d>c&&f>l;)d--,f--,u.push({type:`equal`,line:e[d]});d===c&&f>l?(f--,u.push({type:`insert`,line:t[f]})):f===l&&d>c&&(d--,u.push({type:`delete`,line:e[d]}))}for(;d>0&&f>0;)d--,f--,u.push({type:`equal`,line:e[d]});return u.reverse(),u}function Fo(e,t=3){let n=[],r=[];for(let t=0;t<e.length;t++)e[t].type!==`equal`&&r.push(t);if(r.length===0)return[];let i=0,a=[];for(let e=1;e<r.length;e++)r[e]-r[e-1]>2*t&&(a.push([i,e-1]),i=e);a.push([i,r.length-1]);for(let[i,o]of a){let a=r[i],s=r[o],c=Math.max(0,a-t),l=Math.min(e.length-1,s+t),u=[],d=0,f=0;for(let t=0;t<c;t++)(e[t].type===`equal`||e[t].type===`delete`)&&d++,(e[t].type===`equal`||e[t].type===`insert`)&&f++;let p=d+1,m=f+1,h=0,g=0;for(let t=c;t<=l;t++){let n=e[t];switch(n.type){case`equal`:u.push(` ${n.line}`),h++,g++;break;case`delete`:u.push(`-${n.line}`),h++;break;case`insert`:u.push(`+${n.line}`),g++;break}}n.push({oldStart:p,oldCount:h,newStart:m,newCount:g,lines:u})}return n}function Io(e){let{oldContent:t,newContent:n,oldName:r,newName:i,color:a=!0}=e;if(t===n)return``;let o=t.split(`
|
|
788
788
|
`),s=n.split(`
|
|
789
789
|
`);o.length>0&&o[o.length-1]===``&&o.pop(),s.length>0&&s[s.length-1]===``&&s.pop();let c=Fo(Po(o,s));if(c.length===0)return``;let l=a?`\x1B[31m`:``,u=a?`\x1B[32m`:``,d=a?`\x1B[36m`:``,f=a?`\x1B[1m`:``,p=a?`\x1B[0m`:``,m=``;m+=`${f}diff --git a/${r} b/${i}${p}\n`,m+=`${f}--- a/${r}${p}\n`,m+=`${f}+++ b/${i}${p}\n`;for(let e of c){m+=`${d}@@ -${e.oldStart},${e.oldCount} +${e.newStart},${e.newCount} @@${p}\n`;for(let t of e.lines)t.startsWith(`+`)?m+=`${u}${t}${p}\n`:t.startsWith(`-`)?m+=`${l}${t}${p}\n`:m+=`${t}\n`}return m}function Lo(e,t){if(e===t)return{insertions:0,deletions:0};let n=e.split(`
|
|
790
790
|
`),r=t.split(`
|
|
@@ -1540,7 +1540,7 @@ on success.
|
|
|
1540
1540
|
Examples:
|
|
1541
1541
|
oauth-token adobe
|
|
1542
1542
|
curl -H "Authorization: Bearer $(oauth-token adobe)" https://api.corp.com/data
|
|
1543
|
-
`}function Fl(){return H(`oauth-token`,async e=>{let{getOAuthAccountInfo:t,getSelectedProvider:n,getAccounts:r}=await v(async()=>{let{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}=await import(`./provider-settings-
|
|
1543
|
+
`}function Fl(){return H(`oauth-token`,async e=>{let{getOAuthAccountInfo:t,getSelectedProvider:n,getAccounts:r}=await v(async()=>{let{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}=await import(`./provider-settings-Aax0EzI-.js`);return{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}},__vite__mapDeps([8,9,1,4,10,11,12,13,14])),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await v(async()=>{let{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}=await import(`./providers-43KOjQlK.js`);return{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}},__vite__mapDeps([15,9,1,4,10,11,12,13,14]));if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Pl(),stderr:``,exitCode:0};if(e.includes(`--list`))return Il(r,a,i,t);let o,s=e.indexOf(`--provider`);if(s>=0){if(o=e[s+1],!o)return{stdout:``,stderr:`oauth-token: --provider requires a value
|
|
1544
1544
|
`,exitCode:1}}else if(e.length>0)o=e[0];else{let e=n(),t=i(e);if(t?.isOAuth&&t.onOAuthLogin)o=e;else if(o=a().find(e=>{let t=i(e);return t?.isOAuth&&t.onOAuthLogin}),!o)return{stdout:``,stderr:`oauth-token: no OAuth providers configured
|
|
1545
1545
|
`,exitCode:1}}let c=i(o);if(!c)return{stdout:``,stderr:`oauth-token: unknown provider "${o}"\n`,exitCode:1};if(!c.isOAuth||!c.onOAuthLogin)return{stdout:``,stderr:`oauth-token: provider "${o}" is not an OAuth provider\n`,exitCode:1};let l=t(o);if(l&&!l.expired)return{stdout:`${l.token}\n`,stderr:``,exitCode:0};try{let{createOAuthLauncher:e}=await v(async()=>{let{createOAuthLauncher:e}=await import(`./oauth-service-BoyG8vZW.js`);return{createOAuthLauncher:e}},[]),n=e();await c.onOAuthLogin(n,()=>{});let r=t(o);return r&&r.token?{stdout:`${r.token}\n`,stderr:``,exitCode:0}:(console.error(`[oauth-token] Provider ${o}: login completed but no token was saved`),{stdout:``,stderr:`oauth-token: login completed but no token was saved
|
|
1546
1546
|
`,exitCode:1})}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${o}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}function Il(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
|
|
@@ -1671,7 +1671,7 @@ Options:
|
|
|
1671
1671
|
-h, --help Show this help message
|
|
1672
1672
|
`}function Vu(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function Hu(e){return`$${e.toFixed(2)}`}var Uu=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function Wu(e){let t=`${e.id} ${e.name??``}`;return!Uu.test(t)}function Gu(e){let t=e.toLowerCase();t=t.replace(/-\d{8}$/,``),t=t.replace(/-\d{4}$/,``),t=t.replace(/-(preview|latest)$/,``);let n=t.match(/^(claude-(?:opus|sonnet|haiku))/);if(n)return n[1];let r=t.match(/^(gpt-\d+)(?:\.\d+)?(-[a-z][-a-z]*)?$/);if(r)return r[1]+(r[2]??``);let i=t.match(/^gemini-[\d.]+-(.+)$/);if(i)return`gemini-${i[1]}`;let a=t.match(/^gemini-(\d+)-(.+)$/);if(a)return`gemini-${a[2]}`;let o=t.match(/^grok-[\d.]+-([\w-]+)$/);if(o)return`grok-${o[1]}`;if(t.match(/^(grok)-[\d.]+$/))return`grok`;let s=t.match(/^(o\d+(?:-[a-z]+)?)(?:-\d.*)?$/);return s?s[1]:t.replace(/-[\d.]+$/,``)}function Ku(e){let t=new Map;for(let n of e){let e=Gu(n.id);t.has(e)||t.set(e,n)}return[...t.values()]}function qu(e,t,n,r,i){let a=i?zu(e.id,i):void 0,o={id:e.id,name:e.name,provider:t,cost:e.cost??{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??0,maxTokens:e.maxTokens??0,reasoning:!!e.reasoning,input:e.input??[`text`],selected:e.id===n&&t===r};return a?.intelligence_index!=null&&(o.intelligence=a.intelligence_index),a?.coding_index!=null&&(o.codingScore=a.coding_index),a?.speed_tps!=null&&(o.speed=a.speed_tps),o}function Ju(e,t,n,r){let i=[];i.push(`Models for "${e}" (${t}):\n`);for(let e of n){let t=e.selected?` ► `:` `,n=e.id.padEnd(30),r=`${Hu(e.cost.input)} / ${Hu(e.cost.output)}`,a=`${Vu(e.contextWindow)} ctx`,o=e.intelligence==null?``:`IQ:${e.intelligence}`,s=e.speed==null?``:`${Math.round(e.speed)} t/s`,c=e.reasoning?`reasoning`:``,l=o||s?`${o.padEnd(6)} ${s.padEnd(8)}`:``;i.push(`${t}${n} ${r.padEnd(16)} ${a.padEnd(10)} ${l} ${c}`)}let a=n.find(e=>e.selected);return i.push(`\n ${n.length} model${n.length===1?``:`s`} available.${a?` Currently using: ${a.id}`:``}`),r&&i.push(` Intelligence data: artificialanalysis.ai`),i.join(`
|
|
1673
1673
|
`)+`
|
|
1674
|
-
`}function Yu(e){return H(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s}=await v(async()=>{let{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}=await import(`./provider-settings-
|
|
1674
|
+
`}function Yu(e){return H(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s}=await v(async()=>{let{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}=await import(`./provider-settings-Aax0EzI-.js`);return{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}},__vite__mapDeps([8,9,1,4,10,11,12,13,14]));if(t.includes(`--help`)||t.includes(`-h`))return{stdout:Bu(),stderr:``,exitCode:0};let c=t.includes(`--json`),l=t.includes(`--all`),u=t.includes(`--all-versions`),d=t.includes(`--refresh`),f=t.includes(`--no-benchmarks`),p=t.indexOf(`--provider`),m=p>=0?t[p+1]:void 0,h=o(),g=s(),_=n();if(_.length===0)return{stdout:``,stderr:`No provider accounts configured. Run the provider settings to add one.
|
|
1675
1675
|
`,exitCode:1};let y;f||(y=await Lu(e,d),y.length===0&&(y=void 0));let b;if(m){let e=r();if(!e.includes(m))return{stdout:``,stderr:`Unknown provider: ${m}. Available: ${e.join(`, `)}\n`,exitCode:1};b=[m]}else b=l?[...new Set(_.map(e=>e.providerId))]:[h];let x=[],S=[];for(let e of b){let t=a(e).filter(Wu);if(t.length===0){if(!l)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>qu(t,e,g,h,y)).sort((e,t)=>t.cost.input-e.cost.input);if(u||(n=Ku(n)),x.push(...n),!c){let t=i(e);S.push(Ju(t.name,e,n,!!y))}}return c?{stdout:JSON.stringify(x,null,2)+`
|
|
1676
1676
|
`,stderr:``,exitCode:0}:(!u&&!c&&S.push(`Showing latest versions only. Use --all-versions to see all.
|
|
1677
1677
|
`),{stdout:S.join(`
|
|
@@ -12597,9 +12597,9 @@ The following skills are available. To use a skill, first read its full instruct
|
|
|
12597
12597
|
|
|
12598
12598
|
${e.map(e=>{let t=e.metadata.allowedTools?` Allowed tools: ${e.metadata.allowedTools.join(`, `)}\n`:``;return`- **${e.metadata.name}**: ${e.metadata.description}\n${t} Path: ${e.path}`}).join(`
|
|
12599
12599
|
`)}
|
|
12600
|
-
---`}async function dp(e,t=`/workspace/skills`){let n=ip();for(let[r,i]of Object.entries(n)){let n=r.slice(18),a=n.startsWith(`/workspace/skills`),o=n.startsWith(`/workspace/scripts`);if(!a&&!o)continue;let s=n;a&&t!==`/workspace/skills`&&(s=n.replace(`/workspace/skills`,t)),o&&t!==`/workspace/skills`&&(s=t.replace(`/workspace/skills`,``)+n);try{await e.stat(s)}catch{let t=s.substring(0,s.lastIndexOf(`/`));try{await e.mkdir(t,{recursive:!0})}catch{}await e.writeFile(s,i),ep.info(`Created default file`,{path:s})}}}async function fp(e){let t=ip();for(let[n,r]of Object.entries(t)){let t=n.slice(18);if(t.startsWith(`/shared/`))try{await e.stat(t)}catch{let n=t.substring(0,t.lastIndexOf(`/`));try{await e.mkdir(n,{recursive:!0})}catch{}await e.writeFile(t,r),ep.info(`Created default shared file`,{path:t})}}}var pp=n(`scoop-management-tools`);function mp(e){let{scoop:t,onSendMessage:n,onFeedScoop:r,getScoops:i,
|
|
12601
|
-
`)}`}}}),
|
|
12602
|
-
`),e.isError);break}case`message_end`:if(e.message.role===`assistant`){let t=e.message.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);t&&!this.didStreamDeltas&&this.callbacks.onResponse(t,!1)}break;case`turn_end`:this.callbacks.onResponseDone();break;case`agent_end`:{let t=e.messages;if(t.length>0){let e=t[t.length-1];if(e.role===`assistant`&&e.errorMessage){let n=e.errorMessage;if(!this.isRecovering&&gp(n)){this.recoverFromImageError(t);break}if(!this.isRecovering&&
|
|
12600
|
+
---`}async function dp(e,t=`/workspace/skills`){let n=ip();for(let[r,i]of Object.entries(n)){let n=r.slice(18),a=n.startsWith(`/workspace/skills`),o=n.startsWith(`/workspace/scripts`);if(!a&&!o)continue;let s=n;a&&t!==`/workspace/skills`&&(s=n.replace(`/workspace/skills`,t)),o&&t!==`/workspace/skills`&&(s=t.replace(`/workspace/skills`,``)+n);try{await e.stat(s)}catch{let t=s.substring(0,s.lastIndexOf(`/`));try{await e.mkdir(t,{recursive:!0})}catch{}await e.writeFile(s,i),ep.info(`Created default file`,{path:s})}}}async function fp(e){let t=ip();for(let[n,r]of Object.entries(t)){let t=n.slice(18);if(t.startsWith(`/shared/`))try{await e.stat(t)}catch{let n=t.substring(0,t.lastIndexOf(`/`));try{await e.mkdir(n,{recursive:!0})}catch{}await e.writeFile(t,r),ep.info(`Created default shared file`,{path:t})}}}var pp=n(`scoop-management-tools`);function mp(e){let{scoop:t,onSendMessage:n,onFeedScoop:r,getScoops:i,getScoopTabState:a,onScoopScoop:o,onDropScoop:s,onSetGlobalMemory:c,getGlobalMemory:l}=e,u=[];return u.push({name:`send_message`,description:`Send a progress message while still working. Your final output is also sent.`,inputSchema:{type:`object`,properties:{text:{type:`string`,description:`The message text to send`},sender:{type:`string`,description:`Optional sender name/role (e.g., "Researcher"). Defaults to assistant name.`}},required:[`text`]},execute:async e=>{let{text:r,sender:i}=e;return n(r,i),pp.info(`Message sent`,{scoopFolder:t.folder,textLength:r.length}),{content:`Message sent.`}}}),t.isCone&&r&&u.push({name:`feed_scoop`,description:`Give a scoop a task. Provide a complete, self-contained prompt — the scoop has no access to your conversation. You'll be notified when it finishes.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Use list_scoops to see available scoops.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`}},required:[`scoop_name`,`prompt`]},execute:async e=>{let{scoop_name:t,prompt:n}=e,a=i().find(e=>e.folder===t||e.name===t);if(!a)return{content:`Scoop "${t}" not found. Available: ${i().filter(e=>!e.isCone).map(e=>e.folder).join(`, `)}`,isError:!0};if(a.isCone)return{content:`Cannot feed the cone (yourself).`,isError:!0};try{return await r(a.jid,n),pp.info(`Fed scoop`,{target:a.folder,promptLength:n.length}),{content:`Task sent to ${a.folder}. You will be notified when it completes.`}}catch(e){return{content:`Failed to feed scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}}),t.isCone&&(u.push({name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:async()=>{let e=i();return e.length===0?{content:`No scoops registered.`}:{content:`Registered scoops:\n${e.map(e=>{let t=a?.(e.jid),n=t?.status??`unknown`,r=t?.lastActivity?new Date(t.lastActivity).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0}):``,i=r?` — ${n} (since ${r})`:` — ${n}`;return e.isCone?`- ${e.assistantLabel} (${e.folder}) [CONE]${i}`:`- ${e.name} (${e.folder})${i}`}).join(`
|
|
12601
|
+
`)}`}}}),o&&u.push({name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model and/or a prompt. If prompt is provided, the scoop starts working immediately after creation (no separate feed_scoop needed).`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Display name for the scoop (e.g., "hero-block")`},model:{type:`string`,description:`Model ID for this scoop (e.g., "claude-sonnet-4-6"). If omitted, uses the same model as the cone.`},prompt:{type:`string`,description:`Task prompt for the scoop. If provided, the scoop starts working immediately after creation.`}},required:[`name`]},execute:async e=>{let{name:t,model:n,prompt:i}=e,a=t.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,50)+`-scoop`;try{let e=await o({name:t,folder:a,trigger:`@${a}`,isCone:!1,type:`scoop`,requiresTrigger:!0,assistantLabel:a,addedAt:new Date().toISOString(),config:n?{modelId:n}:void 0});return pp.info(`Scoop created`,{name:t,folder:a}),i&&r?(r(e.jid,i).catch(e=>{let n=e instanceof Error?e.message:String(e);pp.error(`Auto-feed failed`,{name:t,error:n})}),{content:`Scoop "${t}" created as "${a}" and task sent. It will start working as soon as initialization completes.`}):{content:`Scoop "${t}" created as "${a}". Use feed_scoop to give it a task.`}}catch(e){return{content:`Failed to create scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}}),s&&u.push({name:`drop_scoop`,description:`Remove a scoop and stop its work. The scoop will be unregistered and its context destroyed.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Use list_scoops to see available scoops.`}},required:[`scoop_name`]},execute:async e=>{let{scoop_name:t}=e,n=i().find(e=>e.folder===t||e.name===t);if(!n)return{content:`Scoop "${t}" not found. Available: ${i().filter(e=>!e.isCone).map(e=>e.folder).join(`, `)}`,isError:!0};if(n.isCone)return{content:`Cannot drop the cone (yourself).`,isError:!0};try{return await s(n.jid),pp.info(`Scoop dropped`,{name:n.name,folder:n.folder}),{content:`Scoop "${n.name}" (${n.folder}) has been dropped.`}}catch(e){return{content:`Failed to drop scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}}),c&&l&&u.push({name:`update_global_memory`,description:`Update the global CLAUDE.md memory file that is shared across all scoops. Use this instead of write_file for /shared/CLAUDE.md.`,inputSchema:{type:`object`,properties:{content:{type:`string`,description:`The new content for the global memory file`}},required:[`content`]},execute:async e=>{let{content:t}=e;try{return await c(t),pp.info(`Global memory updated`),{content:`Global memory updated successfully.`}}catch(e){return{content:`Failed to update global memory: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}})),u}var hp=n(`scoop-context`);function gp(e){return/image exceeds.*maximum/i.test(e)||/Could not process image/i.test(e)||/invalid.*image/i.test(e)||/image.*too (large|big)/i.test(e)}var _p=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;didStreamDeltas=!1;unsubscribe=null;sessionStore=null;sessionId;sessionCreatedAt=0;isRecovering=!1;skillsFs=null;skillsDir=`/workspace/skills`;constructor(e,t,n,r,i){this.scoop=e,this.callbacks=t,this.fs=n,this.sessionStore=r??null,this.skillsFs=i??null,this.sessionId=e.jid}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);hp.info(`Filesystem ready`,{folder:this.scoop.folder}),await this.ensureDirectoryStructure();let e=this.scoop.isCone?`/`:`/scoops/${this.scoop.folder}/workspace`,t=this.callbacks.getBrowserAPI();this.skillsDir=`/workspace/skills`,this.scoop.isCone&&await dp(this.fs,this.skillsDir);let n=this.skillsFs??this.fs;this.shell=new bf({fs:this.fs,cwd:e,browserAPI:t,jshDiscoveryFs:this.skillsFs?n:void 0}),hp.info(`WasmShell initialized`,{folder:this.scoop.folder});let r=await sp(n,this.skillsDir),i=mp({scoop:this.scoop,onSendMessage:this.callbacks.onSendMessage,getScoops:this.callbacks.getScoops,getScoopTabState:this.callbacks.getScoopTabState,onFeedScoop:this.callbacks.onFeedScoop,onScoopScoop:this.callbacks.onScoopScoop,onDropScoop:this.callbacks.onDropScoop,onSetGlobalMemory:this.callbacks.setGlobalMemory,getGlobalMemory:this.callbacks.getGlobalMemory}),a=S([...Sf(this.fs),Af(this.shell),...i]),o=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`,s=``;try{let e=await this.fs.readFile(o,{encoding:`utf-8`});s=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let c=await this.callbacks.getGlobalMemory();if(c)try{this.scoop.isCone&&await(`getUnderlyingFS`in this.fs?this.fs.getUnderlyingFS():this.fs).writeFile(`/shared/CLAUDE.md`,c)}catch{}if(!E()){let e=w();throw Error(`No API key configured for provider "${e}"`)}let l=this.scoop.config?.modelId?T(this.scoop.config.modelId):ie(),u=this.scoop.isCone?`Cone`:`Scoop "${this.scoop.name}"`;console.log(`[model] ${u} using model: ${l.id} (provider: ${l.provider})`);let d=this.buildSystemPrompt(c,s,r),f=[];if(this.sessionStore)try{let e=await this.sessionStore.load(this.sessionId);e&&(f=e.messages,this.sessionCreatedAt=e.createdAt,hp.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:f.length}))}catch(e){hp.error(`Failed to restore agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.callbacks.onError(`Conversation history could not be restored. Starting fresh.`)}let p=x({model:l,getApiKey:()=>E()??void 0});this.agent=new y({initialState:{model:l,tools:a,systemPrompt:d,messages:f},getApiKey:()=>E()??void 0,transformContext:p}),this.unsubscribe=this.agent.subscribe(e=>this.handleAgentEvent(e)),this.setStatus(`ready`),hp.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:a.length})}catch(e){let t=e instanceof Error?e.message:String(e);hp.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async prompt(e){if(!this.agent){this.callbacks.onError(`Agent not initialized`);return}let t=this.agent.state?.isStreaming??!1;if(this.isProcessing||t){hp.info(`Queueing prompt via followUp while processing`,{folder:this.scoop.folder,isProcessing:this.isProcessing,agentIsStreaming:t}),this.agent.followUp({role:`user`,content:[{type:`text`,text:e}],timestamp:Date.now()});return}this.isProcessing=!0,this.didStreamDeltas=!1,this.setStatus(`processing`);try{await this.agent.prompt(e)}catch(e){let t=e instanceof Error?e.message:String(e);hp.error(`Agent error`,{folder:this.scoop.folder,error:t}),this.callbacks.onError(t)}finally{this.isProcessing=!1,this.setStatus(`ready`)}}stop(){this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.isProcessing=!1,this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getSessionId(){return this.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){if(!this.agent)return;let e=ie();this.agent.state.model=e,hp.info(`Model updated on running agent`,{folder:this.scoop.folder,model:e.id})}async reloadSkills(){if(!this.agent)return;let e=await sp(this.skillsFs??this.fs,this.skillsDir),t=``,n=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{let e=await this.fs.readFile(n,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let r=await this.callbacks.getGlobalMemory(),i=this.buildSystemPrompt(r,t,e);this.agent.state.systemPrompt=i,hp.info(`Skills reloaded`,{folder:this.scoop.folder,skillCount:e.length})}dispose(){this.unsubscribe?.(),this.shell?.dispose(),this.agent=null,this.shell=null,this.fs=null}setStatus(e){this.status=e,this.callbacks.onStatusChange(e)}handleAgentEvent(e){switch(e.type){case`message_update`:{let t=e.assistantMessageEvent;t.type===`text_delta`&&(this.didStreamDeltas=!0,this.callbacks.onResponse(t.delta,!0));break}case`tool_execution_start`:this.callbacks.onToolStart?.(e.toolName,e.args);break;case`tool_execution_update`:{let t=e.partialResult;for(let n of t?.content??[])n.type===`tool_ui`&&n.requestId&&n.html?this.callbacks.onToolUI?.(e.toolName,n.requestId,n.html):n.type===`tool_ui_done`&&n.requestId&&this.callbacks.onToolUIDone?.(n.requestId);break}case`tool_execution_end`:{let t=e.result,n=[];for(let e of t?.content??[])e.type===`text`&&e.text&&n.push(e.text),e.type===`image`&&e.data&&e.mimeType&&n.push(`<img:data:${e.mimeType};base64,${e.data}>`);this.callbacks.onToolEnd?.(e.toolName,n.join(`
|
|
12602
|
+
`),e.isError);break}case`message_end`:if(e.message.role===`assistant`){let t=e.message.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);t&&!this.didStreamDeltas&&this.callbacks.onResponse(t,!1)}break;case`turn_end`:this.callbacks.onResponseDone();break;case`agent_end`:{let t=e.messages;if(t.length>0){let e=t[t.length-1];if(e.role===`assistant`&&e.errorMessage){let n=e.errorMessage;if(!this.isRecovering&&gp(n)){this.recoverFromImageError(t);break}if(!this.isRecovering&&O(e)){this.recoverFromOverflow(t);break}this.isRecovering=!1,this.callbacks.onError(n)}else this.isRecovering=!1}let n=this.agent?.state?.messages??e.messages;this.sessionStore&&n.length>0&&this.sessionStore.save({id:this.sessionId,messages:n,config:{},createdAt:this.sessionCreatedAt||Date.now(),updatedAt:Date.now()}).catch(e=>{hp.error(`Failed to save agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})});break}}}recoverFromOverflow(e){if(this.agent){hp.warn(`Context overflow detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length}),this.isRecovering=`overflow`,this.callbacks.onResponse(`Context window exceeded — recovering by trimming oversized messages...`,!1);try{let t=e.slice(0,-1),n=0;for(let e=t.length-1;e>=0&&n<5;e--){let r=t[e];if(!Array.isArray(r.content))continue;let i=0;for(let e of r.content)e.type===`text`&&e.text&&(i+=e.text.length),e.type===`image`&&e.data&&(i+=e.data.length);if(i>4e4){let a={type:`text`,text:`[Content removed: ${r.role===`toolResult`?`tool result`:r.role} was too large for context window (${Math.round(i/1e3)}K chars). The operation completed but output could not be retained.]`};if(r.role===`assistant`){let n=r.content.filter(e=>e.type===`toolCall`);t[e]={...r,content:[a,...n]}}else t[e]={...r,content:[a]};n++,hp.info(`Replaced oversized message`,{index:e,role:r.role,size:i,preservedToolCalls:r.role===`assistant`?r.content.filter(e=>e.type===`toolCall`).length:0})}}this.agent.state.messages=t;let r=n>0?`[System: Context overflow recovered. ${n} oversized message(s) were replaced with placeholders to fit within the context window. The conversation continues — you may need to re-read files or re-run commands if their output was removed.]`:`[System: Context overflow recovered. Older messages were trimmed. The conversation continues — compaction will summarize history on the next turn.]`;this.agent.prompt(r).catch(e=>{hp.error(`Recovery re-prompt failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Context overflow recovery failed: ${e instanceof Error?e.message:String(e)}`)})}catch(e){hp.error(`Recovery failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Context overflow recovery failed: ${e instanceof Error?e.message:String(e)}`)}}}recoverFromImageError(e){if(this.agent){hp.warn(`Image processing error detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length}),this.isRecovering=`image`,this.callbacks.onResponse(`Image rejected by API — removing problematic images and continuing...`,!1);try{let t=e.slice(0,-1),n=0,r=Math.max(0,t.length-10);for(let e=t.length-1;e>=r;e--){let r=t[e];if(!Array.isArray(r.content)||!r.content.some(e=>e.type===`image`))continue;let i=r.content.filter(e=>e.type!==`image`);i.length===0?t[e]={...r,content:[{type:`text`,text:`[Image removed: rejected by API]`}]}:t[e]={...r,content:i},n++}this.agent.state.messages=t;let i=`[System: An image was rejected by the API and has been removed from the conversation (${n} message(s) affected). The conversation continues without the image.]`;this.agent.prompt(i).catch(e=>{hp.error(`Image recovery re-prompt failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)})}catch(e){hp.error(`Image recovery failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)}}}async ensureDirectoryStructure(){if(!this.fs)return;let e=this.scoop.isCone?[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`]:[`/scoops/${this.scoop.folder}`,`/scoops/${this.scoop.folder}/workspace`,`/scoops/${this.scoop.folder}/home`,`/scoops/${this.scoop.folder}/tmp`,`/shared`];for(let t of e)try{await this.fs.mkdir(t,{recursive:!0})}catch{}let t=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{await this.fs.readFile(t)}catch{let e=`# ${this.scoop.assistantLabel} Memory
|
|
12603
12603
|
|
|
12604
12604
|
${this.scoop.isCone?`Role: Cone (main orchestrator)`:`Scoop: ${this.scoop.name}`}
|
|
12605
12605
|
Folder: ${this.scoop.folder}
|
|
@@ -12679,11 +12679,11 @@ ${e}
|
|
|
12679
12679
|
${this.scoop.isCone?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
|
|
12680
12680
|
${t}
|
|
12681
12681
|
---`);let a=up(n);return a&&(i+=a),i}},vp=n(`scheduler`),yp=class{callbacks;pollInterval=null;running=!1;constructor(e){this.callbacks=e}start(){this.running||(this.running=!0,this.pollInterval=window.setInterval(()=>this.checkTasks(),6e4),this.checkTasks(),vp.info(`Scheduler started`))}stop(){this.pollInterval&&=(clearInterval(this.pollInterval),null),this.running=!1,vp.info(`Scheduler stopped`)}async createTask(e,t,n,r){let i={id:`task-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,groupFolder:e,prompt:t,scheduleType:n,scheduleValue:r,status:`active`,nextRun:this.calculateNextRun(n,r),lastRun:null,createdAt:new Date().toISOString()};return await V(i),vp.info(`Task created`,{id:i.id,groupFolder:e,scheduleType:n}),i}async updateTask(e,t){let n=await Oe(e);if(!n)return null;let r={...n,...t};return(t.scheduleType||t.scheduleValue)&&(r.nextRun=this.calculateNextRun(r.scheduleType,r.scheduleValue)),await V(r),vp.info(`Task updated`,{id:e,updates:Object.keys(t)}),r}async pauseTask(e){return await this.updateTask(e,{status:`paused`})!==null}async resumeTask(e){return await Oe(e)?(await this.updateTask(e,{status:`active`}),!0):!1}async deleteTask(e){return await Oe(e)?(await ye(e),vp.info(`Task deleted`,{id:e}),!0):!1}async getTasksByScoop(e){return(await De()).filter(t=>t.groupFolder===e)}async getAllTasks(){return De()}async checkTasks(){let e=await De(),t=new Date;for(let n of e)n.status===`active`&&n.nextRun&&(new Date(n.nextRun)>t||await this.runTask(n))}async runTask(e){let t=this.callbacks.getScoop(e.groupFolder);if(!t){vp.warn(`Task scoop not found`,{taskId:e.id,groupFolder:e.groupFolder});return}vp.info(`Running task`,{id:e.id,groupFolder:e.groupFolder});try{let n=new Date().toISOString(),r=this.calculateNextRun(e.scheduleType,e.scheduleValue),i=e.scheduleType===`once`?`completed`:e.status;await V({...e,lastRun:n,nextRun:r,status:i}),await this.callbacks.onTaskRun(e,t),vp.info(`Task completed`,{id:e.id})}catch(t){vp.error(`Task execution failed`,{id:e.id,error:t instanceof Error?t.message:String(t)})}}calculateNextRun(e,t){let n=new Date;switch(e){case`cron`:return this.getNextCronTime(t,n)?.toISOString()??null;case`interval`:{let e=parseInt(t,10);return isNaN(e)||e<=0?null:new Date(n.getTime()+e).toISOString()}case`once`:return new Date(t)>n?t:null;default:return null}}getNextCronTime(e,t){let n=e.trim().split(/\s+/);if(n.length!==5)return null;let[r,i,a,o,s]=n,c=new Date(t);c.setSeconds(0),c.setMilliseconds(0),c.setMinutes(c.getMinutes()+1);for(let e=0;e<527040;e++){if(this.cronMatches(c,r,i,a,o,s))return c;c.setMinutes(c.getMinutes()+1)}return null}cronMatches(e,t,n,r,i,a){return this.cronFieldMatches(e.getMinutes(),t)&&this.cronFieldMatches(e.getHours(),n)&&this.cronFieldMatches(e.getDate(),r)&&this.cronFieldMatches(e.getMonth()+1,i)&&this.cronFieldMatches(e.getDay(),a)}cronFieldMatches(e,t){if(t===`*`)return!0;if(t.includes(`,`))return t.split(`,`).some(t=>this.cronFieldMatches(e,t.trim()));if(t.includes(`-`)){let[n,r]=t.split(`-`).map(e=>parseInt(e,10));return e>=n&&e<=r}if(t.includes(`/`)){let[n,r]=t.split(`/`),i=parseInt(r,10);if(n===`*`)return e%i===0;let a=parseInt(n,10);return e>=a&&(e-a)%i===0}return parseInt(t,10)===e}},bp=n(`lick-manager`),xp=class{webhooks=new Map;crontasks=new Map;cronInterval=null;eventHandler=null;async init(){await Te();let e=await Fe();for(let t of e)this.webhooks.set(t.id,t);bp.info(`Loaded webhooks`,{count:this.webhooks.size});let t=await Ne();for(let e of t)this.crontasks.set(e.id,e);bp.info(`Loaded crontasks`,{count:this.crontasks.size}),this.cronInterval=setInterval(()=>this.runCronScheduler(),6e4),bp.info(`Cron scheduler started`)}dispose(){this.cronInterval&&=(clearInterval(this.cronInterval),null)}setEventHandler(e){this.eventHandler=e}async createWebhook(e,t,n){let r=this.generateId(),i={id:r,name:e,createdAt:new Date().toISOString(),filter:n,scoop:t};return n&&this.compileFilter(n,!0),this.webhooks.set(r,i),await be(i),bp.info(`Webhook created`,{id:r,name:e,scoop:t}),i}async deleteWebhook(e){return this.webhooks.has(e)?(this.webhooks.delete(e),await Ae(e),bp.info(`Webhook deleted`,{id:e}),!0):!1}listWebhooks(){return Array.from(this.webhooks.values())}getWebhook(e){return this.webhooks.get(e)}handleWebhookEvent(e,t,n){let r=this.webhooks.get(e);if(!r){bp.warn(`Webhook not found`,{webhookId:e});return}let i={type:`webhook`,webhookId:e,webhookName:r.name,targetScoop:r.scoop,timestamp:new Date().toISOString(),headers:t,body:n};if(r.filter)try{let t=this.compileFilter(r.filter,!0)(i);if(t===!1){bp.debug(`Webhook event dropped by filter`,{webhookId:e,name:r.name});return}typeof t==`object`&&t&&(i=t)}catch(t){bp.error(`Webhook filter error`,{webhookId:e,error:t instanceof Error?t.message:String(t)})}bp.info(`Webhook event received`,{webhookId:e,name:r.name,targetScoop:r.scoop}),this.eventHandler?.(i)}async createCronTask(e,t,n,r){let i=this.getNextCronTime(t,new Date);if(!i)throw Error(`Invalid cron expression`);r&&this.compileFilter(r,!1);let a=this.generateId(),o={id:a,name:e,cron:t,scoop:n,filter:r,nextRun:i.toISOString(),lastRun:null,status:`active`,createdAt:new Date().toISOString()};return this.crontasks.set(a,o),await we(o),bp.info(`Cron task created`,{id:a,name:e,cron:t,scoop:n}),o}async deleteCronTask(e){return this.crontasks.has(e)?(this.crontasks.delete(e),await ke(e),bp.info(`Cron task deleted`,{id:e}),!0):!1}listCronTasks(){return Array.from(this.crontasks.values())}getCronTask(e){return this.crontasks.get(e)}getLicksForScoop(e,t){let n=n=>n===e||n===t||`${n}-scoop`===t;return{webhooks:Array.from(this.webhooks.values()).filter(e=>n(e.scoop)),cronTasks:Array.from(this.crontasks.values()).filter(e=>n(e.scoop))}}async runCronScheduler(){let e=new Date;for(let t of this.crontasks.values()){if(t.status!==`active`||!t.nextRun||new Date(t.nextRun)>e)continue;let n={time:e.toISOString()};if(t.filter)try{let r=this.compileFilter(t.filter,!1)(null);if(r===!1){bp.debug(`Cron task skipped by filter`,{id:t.id,name:t.name}),t.nextRun=this.getNextCronTime(t.cron,e)?.toISOString()??null,t.lastRun=e.toISOString(),await we(t);continue}typeof r==`object`&&r&&(n=r)}catch(e){bp.error(`Cron filter error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}let r={type:`cron`,cronId:t.id,cronName:t.name,targetScoop:t.scoop,timestamp:e.toISOString(),body:n};bp.info(`Cron task running`,{id:t.id,name:t.name}),this.eventHandler?.(r),t.nextRun=this.getNextCronTime(t.cron,e)?.toISOString()??null,t.lastRun=e.toISOString(),await we(t)}}generateId(){let e=``;for(let t=0;t<12;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`[Math.floor(Math.random()*36)];return e}compileFilter(e,t){try{return t?Function(`event`,`return (${e})(event);`):Function(`return (${e})();`)}catch(e){throw Error(`Invalid filter function: ${e instanceof Error?e.message:String(e)}`)}}getNextCronTime(e,t){let n=e.trim().split(/\s+/);if(n.length!==5)return null;let[r,i,a,o,s]=n,c=new Date(t);c.setSeconds(0),c.setMilliseconds(0),c.setMinutes(c.getMinutes()+1);let l=(e,t)=>{if(t===`*`)return!0;if(t.includes(`,`))return t.split(`,`).some(t=>l(e,t.trim()));if(t.includes(`-`)){let[n,r]=t.split(`-`).map(e=>parseInt(e,10));return e>=n&&e<=r}if(t.includes(`/`)){let[n,r]=t.split(`/`),i=parseInt(r,10);if(n===`*`)return e%i===0;let a=parseInt(n,10);return e>=a&&(e-a)%i===0}return parseInt(t,10)===e};for(let e=0;e<527040;e++){if(l(c.getMinutes(),r)&&l(c.getHours(),i)&&l(c.getDate(),a)&&l(c.getMonth()+1,o)&&l(c.getDay(),s))return c;c.setMinutes(c.getMinutes()+1)}return null}};function Sp(e,t,n){if(t.length===0&&n.length===0)return null;let r=[];t.length>0&&r.push(`${t.length} active webhook${t.length>1?`s`:``}`),n.length>0&&r.push(`${n.length} active cron task${n.length>1?`s`:``}`);let i=[...t.map(e=>` webhook delete ${e.id}`),...n.map(e=>` crontask delete ${e.id}`)].join(`
|
|
12682
|
-
`);return Error(`Cannot remove scoop '${e}': it has ${r.join(` and `)}. Unregister them first:\n${i}`)}var Cp=null;function wp(){return Cp||=new xp,Cp}var Q=n(`orchestrator`),Tp=class{scoops=new Map;tabs=new Map;contexts=new Map;messageQueues=new Map;lastAgentTimestamp=new Map;container;callbacks;config;pollInterval=null;scheduler=null;globalMemoryCache=``;sharedFs=null;scoopResponseBuffer=new Map;lickManager=null;sessionStore=null;constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n}async init(){await Te(),this.sharedFs=await z.create({dbName:`slicc-fs`}),this.sessionStore=new
|
|
12683
|
-
... (truncated)`:n,a={id:`scoop-done-${e}-${Date.now()}`,chatJid:r.jid,senderId:t.folder,senderName:t.assistantLabel,content:`[@${t.assistantLabel} completed]:\n${i}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-notify`};Q.info(`Routing scoop completion to cone`,{scoop:t.folder,responseLength:n.length}),this.handleMessage(a).catch(e=>{let n=e instanceof Error?e.message:String(e);Q.error(`Failed to route scoop completion to cone`,{scoop:t.folder,error:n}),this.callbacks.onError(r.jid,`Scoop ${t.folder} completed but notification failed: ${n}`)})}}}},onToolStart:(t,n)=>{this.callbacks.onToolStart?.(e,t,n)},onToolEnd:(t,n,r)=>{this.callbacks.onToolEnd?.(e,t,n,r)},onToolUI:(t,n,r)=>{this.callbacks.onToolUI?.(e,t,n,r)},onToolUIDone:t=>{this.callbacks.onToolUIDone?.(e,t)},onSendMessage:(t,n)=>{this.callbacks.onSendMessage(e,`${n?`[${n}] `:``}${t}`)},getScoops:()=>this.getScoops(),onFeedScoop:t.isCone?(e,n)=>this.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:t.isCone?async e=>{let t={...e,jid:`scoop_${e.folder}_${Date.now()}`};return await this.registerScoop(t),t}:void 0,onDropScoop:t.isCone?async e=>{await this.unregisterScoop(e)}:void 0,getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:t.isCone?e=>this.setGlobalMemory(e):void 0,getBrowserAPI:()=>this.callbacks.getBrowserAPI()},r,this.sessionStore??void 0,this.sharedFs??void 0);this.contexts.set(e,i),this.tabs.set(e,{jid:e,contextId:n,status:`initializing`,lastActivity:new Date().toISOString()}),await i.init();let a=this.tabs.get(e);a&&a.status===`initializing`&&(a.status=`ready`,this.tabs.set(e,a),this.callbacks.onStatusChange(e,`ready`)),Q.info(`Scoop context created`,{jid:e,contextId:n})}async destroyScoopTab(e){let t=this.contexts.get(e);t&&(t.dispose(),this.contexts.delete(e),this.tabs.delete(e),Q.info(`Scoop context destroyed`,{jid:e}))}isProcessing(e){return this.tabs.get(e)?.status===`processing`}getScoopContext(e){return this.contexts.get(e)}async clearQueuedMessages(e){let t=this.messageQueues.get(e);if(t&&t.length>0){for(let e of t)await Me(e.id);this.messageQueues.set(e,[])}}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let e=n.findIndex(e=>e.id===t);e!==-1&&n.splice(e,1)}await Me(t)}async getMessagesForScoop(e){return Se(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.tabs.get(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return Q.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r){let i=this.contexts.get(e);i||=(await this.createScoopTab(e),this.contexts.get(e));let a=this.tabs.get(e);if(a?.status===`initializing`){if(Q.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){Q.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}i=this.contexts.get(e),a=this.tabs.get(e)}if(!i){Q.error(`Context not found after creation`,{jid:e});return}this.scoopResponseBuffer.delete(e),a&&(a.status=`processing`,a.lastActivity=new Date().toISOString(),this.tabs.set(e,a),this.callbacks.onStatusChange(e,`processing`)),Q.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length}),await i.prompt(t)}async processScoopQueue(e){let t=this.messageQueues.get(e);if(!t||t.length===0){Q.debug(`processScoopQueue: empty queue`,{jid:e});return}let n=this.tabs.get(e);if(n?.status!==`ready`){Q.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.scoops.get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await Ce(e,a,i);if(Q.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,queueLength:t.length}),o.length===0){Q.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]);return}let s=o.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${e.content}`).join(`
|
|
12684
|
-
`);this.messageQueues.set(e,[]);let c=o[o.length-1];this.lastAgentTimestamp.set(e,c.timestamp),await Le(`lastAgentTs_${e}`,c.timestamp),await this.sendPrompt(e,s,c.senderId,c.senderName)}startMessageLoop(){this.pollInterval||=window.setInterval(()=>{for(let e of this.scoops.keys())this.tabs.get(e)?.status===`ready`&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Message queue processing failed`,{jid:e,error:n}),this.callbacks.onError(e,`Queue processing failed: ${n}`)})},2e3)}stopMessageLoop(){this.pollInterval&&=(clearInterval(this.pollInterval),null)}updateModel(){for(let e of this.contexts.values())e.updateModel();Q.info(`Model updated on all active contexts`,{contextCount:this.contexts.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.contexts){let r=this.tabs.get(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{Q.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),Q.info(`Skills reloaded across all contexts`,{count:e.length})}stopScoop(e){let t=this.contexts.get(e);t&&t.stop()}getSessionCosts(){let e=[];for(let t of this.scoops.values()){let n=this.contexts.get(t.jid);if(!n)continue;let r=n.getAgentMessages().filter(e=>e.role===`assistant`);if(r.length===0)continue;let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},a=new Map;for(let e of r)i.input+=e.usage.input,i.output+=e.usage.output,i.cacheRead+=e.usage.cacheRead,i.cacheWrite+=e.usage.cacheWrite,i.totalTokens+=e.usage.totalTokens,i.cost.input+=e.usage.cost.input,i.cost.output+=e.usage.cost.output,i.cost.cacheRead+=e.usage.cost.cacheRead,i.cost.cacheWrite+=e.usage.cost.cacheWrite,i.cost.total+=e.usage.cost.total,a.set(e.model,(a.get(e.model)??0)+1);let o=``,s=0;for(let[e,t]of a)t>s&&(o=e,s=t);e.push({name:t.assistantLabel,type:t.isCone?`cone`:`scoop`,model:o,usage:i,turns:r.length})}return e}async shutdown(){this.stopMessageLoop(),this.scheduler?.stop(),this.scheduler=null;for(let e of this.contexts.keys())await this.destroyScoopTab(e);Q.info(`Orchestrator shutdown`)}};n(`heartbeat`);var Ep=n(`tray-follower`);function Dp(e){let t=new URL(e);return t.searchParams.set(`json`,`true`),t.toString()}async function Op(e){let t=Dp(e.joinUrl),n=await Fp(await(e.fetchImpl??fetch)(t,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:e.controllerId,runtime:e.runtime})}));return Ep.info(`Follower tray attach response`,{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),kp(n)}function kp(e){let 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 Ap(e){return Pp(await Ip(e,{action:`poll`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function jp(e){return Pp(await Ip(e,{action:`answer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function Mp(e){return Pp(await Ip(e,{action:`ice-candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function Np(e){return Pp(await Ip(e,{action:`retry`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function Pp(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function Fp(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!Lp(n)){let n=t?t.slice(0,200):`(empty)`;throw Ep.warn(`Tray follower attach returned an invalid response`,{status:e.status,body:n}),Error(`Tray follower attach returned an invalid response (${e.status}): ${n}`)}return n}async function Ip(e,t){let n=Dp(e.joinUrl),r=await(e.fetchImpl??fetch)(n,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),i=await r.json().catch(()=>null);if(!Rp(i))throw Error(`Tray follower bootstrap returned an invalid response (${r.status})`);return i}function Lp(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.trayId!=`string`||typeof t.controllerId!=`string`||t.role!==`follower`||typeof t.participantCount!=`number`)return!1;let n=t.result;if(!n||typeof n!=`object`)return!1;let r=n;return r.action===`wait`?(r.code===`LEADER_NOT_ELECTED`||r.code===`LEADER_NOT_CONNECTED`)&&typeof r.retryAfterMs==`number`:r.action===`signal`?r.code===`LEADER_CONNECTED`&&zp(r.bootstrap):r.action===`fail`?(r.code===`INVALID_JOIN_CAPABILITY`||r.code===`TRAY_EXPIRED`)&&typeof r.error==`string`:!1}function Rp(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.trayId==`string`&&typeof t.controllerId==`string`&&t.role===`follower`&&typeof t.participantCount==`number`&&zp(t.bootstrap)&&Array.isArray(t.events)}function zp(e){if(!e||typeof e!=`object`)return!1;let 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`}var Bp=n(`tray-webrtc`),Vp=`tray-control`,Hp=250,Up=class{peerConnectionFactory;dataChannelLabel;peers=new Map;iceServers;constructor(e){this.options=e,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>Kp(this.iceServers)),this.dataChannelLabel=e.dataChannelLabel??Vp}setIceServers(e){this.iceServers=e}async handleControlMessage(e){e.type===`follower.join_requested`?(e.iceServers&&!this.iceServers&&(this.iceServers=e.iceServers),await this.handleJoinRequested(e)):e.type===`bootstrap.answer`?await this.peers.get(e.bootstrapId)?.peer.setRemoteDescription(e.answer):e.type===`bootstrap.ice_candidate`&&await this.peers.get(e.bootstrapId)?.peer.addIceCandidate(e.candidate)}getPeers(){return Array.from(this.peers.values()).map(({state:e})=>({...e}))}getChannel(e){return this.peers.get(e)?.channel??null}stop(){for(let e of this.peers.values())e.peer.close();this.peers.clear()}async handleJoinRequested(e){this.closeControllerPeers(e.controllerId);let t=this.peerConnectionFactory(),n={controllerId:e.controllerId,bootstrapId:e.bootstrapId,attempt:e.attempt,state:`connecting`,connectedAt:null,runtime:e.runtime},r=t.createDataChannel(this.dataChannelLabel);this.peers.set(e.bootstrapId,{state:n,peer:t,channel:r}),t.addEventListener(`icecandidate`,({candidate:t})=>{let n=Jp(t);n&&this.options.sendControlMessage({type:`bootstrap.ice_candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:n})}),t.addEventListener(`connectionstatechange`,()=>{let n=this.peers.get(e.bootstrapId);n&&(n.state.state===`connected`?(t.connectionState===`disconnected`||t.connectionState===`failed`)&&(Bp.warn(`Leader peer connection state changed post-connect`,{bootstrapId:e.bootstrapId,state:t.connectionState}),this.options.onPeerDisconnected?.(e.bootstrapId,`Peer connection ${t.connectionState}`)):t.connectionState===`failed`&&this.failPeer(e,`Leader peer connection failed before the data channel opened`))}),r.addEventListener(`open`,()=>{let t=this.peers.get(e.bootstrapId);!t||t.state.state===`connected`||(t.state.state=`connected`,t.state.connectedAt=new Date().toISOString(),this.options.onPeerConnected?.({...t.state},t.channel))}),r.addEventListener(`close`,()=>{let t=this.peers.get(e.bootstrapId);t&&(t.state.state===`connected`?(Bp.warn(`Leader data channel closed post-connect`,{bootstrapId:e.bootstrapId}),this.options.onPeerDisconnected?.(e.bootstrapId,`Data channel closed`)):this.failPeer(e,`Leader data channel closed before opening`))}),r.addEventListener(`error`,()=>{let t=this.peers.get(e.bootstrapId);t&&(t.state.state===`connected`?(Bp.warn(`Leader data channel error post-connect`,{bootstrapId:e.bootstrapId}),this.options.onPeerDisconnected?.(e.bootstrapId,`Data channel error`)):this.failPeer(e,`Leader data channel failed before opening`))});try{let n=await t.createOffer();await t.setLocalDescription(n),this.options.sendControlMessage({type:`bootstrap.offer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,offer:qp(t.localDescription??n,`offer`)})}catch(t){this.failPeer(e,t instanceof Error?t.message:String(t))}}closeControllerPeers(e){for(let[t,n]of this.peers.entries())n.state.controllerId===e&&(n.peer.close(),this.peers.delete(t))}failPeer(e,t){let n=this.peers.get(e.bootstrapId);if(n){n.peer.close(),this.peers.delete(e.bootstrapId);try{this.options.sendControlMessage({type:`bootstrap.failed`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,code:`WEBRTC_BOOTSTRAP_FAILED`,message:t,retryable:!0,retryAfterMs:1e3})}catch(e){Bp.warn(`Failed to report tray bootstrap failure`,{error:e instanceof Error?e.message:String(e)})}}}},Wp=class{fetchImpl;peerConnectionFactory;controllerIdFactory;sleep;pollIntervalMs;iceServers;activePeer=null;stopped=!1;constructor(e){this.options=e,this.fetchImpl=e.fetchImpl??fetch,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>Kp(this.iceServers)),this.controllerIdFactory=e.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),this.pollIntervalMs=e.pollIntervalMs??Hp}async start(){this.stopped=!1;let e=this.controllerIdFactory(),t=Date.now();f({state:`connecting`,joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:t,lastError:null}),Bp.info(`Follower tray join starting`,{joinUrl:this.options.joinUrl});let n=0;for(;;){Yp(this.stopped),n++;let t;try{t=await Op({joinUrl:this.options.joinUrl,controllerId:e,runtime:this.options.runtime,fetchImpl:this.fetchImpl})}catch(e){let t=e instanceof Error?e.message:String(e);throw f({...m(),attachAttempts:n,lastError:t}),e}if(f({...m(),attachAttempts:n,lastAttachCode:t.code}),t.action===`wait`){let e=t.retryAfterMs??1e3;Bp.info(`Follower tray attach waiting`,{attempt:n,code:t.code,retryAfterMs:e}),n%10==0&&Bp.warn(`Follower tray attach still waiting after ${n} attempts`,{attempt:n,code:t.code,retryAfterMs:e}),await this.sleep(e);continue}if(t.action===`fail`||!t.bootstrap){let e=t.error??`Tray follower attach failed (${t.code})`;throw f({state:`error`,joinUrl:this.options.joinUrl,trayId:null,error:e,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:e}),Bp.warn(`Follower tray attach failed`,{error:e}),Error(e)}t.iceServers&&(this.iceServers=t.iceServers);try{let r=await this.completeBootstrap(t.trayId,e,t.bootstrap);return f({state:`connected`,joinUrl:this.options.joinUrl,trayId:r.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:null}),Bp.info(`Follower tray connected`,{trayId:r.trayId,controllerId:e}),r}catch(e){let r=e instanceof Error?e.message:String(e);throw f({state:`error`,joinUrl:this.options.joinUrl,trayId:t.trayId,error:r,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:r}),Bp.warn(`Follower tray bootstrap failed`,{error:r}),e}}}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,f({state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null})}async completeBootstrap(e,t,n){let r=n,i=0;for(this.activePeer=this.createFollowerPeer(t,r.bootstrapId);;){if(Yp(this.stopped),this.activePeer.open&&this.activePeer.channel)return{trayId:e,controllerId:t,bootstrapId:r.bootstrapId,channel:this.activePeer.channel};if(this.activePeer.openError)throw Error(this.activePeer.openError);let n=await Ap({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,cursor:i,fetchImpl:this.fetchImpl});r=n.bootstrap,i=r.cursor;try{for(let e of n.events)if(e.type===`bootstrap.offer`){await this.activePeer.peer.setRemoteDescription(e.offer);let n=await this.activePeer.peer.createAnswer();await this.activePeer.peer.setLocalDescription(n),await jp({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,answer:qp(this.activePeer.peer.localDescription??n,`answer`),fetchImpl:this.fetchImpl})}else if(e.type===`bootstrap.ice_candidate`)await this.activePeer.peer.addIceCandidate(e.candidate);else if(e.type===`bootstrap.failed`)throw Error(e.failure.message)}catch(e){if(r.failure?.retryable&&r.retriesRemaining>0){r=(await Np({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,runtime:this.options.runtime,fetchImpl:this.fetchImpl})).bootstrap,i=0,this.activePeer.peer.close(),this.activePeer=this.createFollowerPeer(t,r.bootstrapId);continue}throw e}this.activePeer.open||await this.sleep(this.pollIntervalMs)}}createFollowerPeer(e,t){let n=this.peerConnectionFactory(),r={peer:n,channel:null,open:!1,openError:null};return n.addEventListener(`connectionstatechange`,()=>{r.open&&(n.connectionState===`disconnected`||n.connectionState===`failed`)&&(Bp.warn(`Follower peer connection state changed post-connect`,{bootstrapId:t,state:n.connectionState}),this.options.onDisconnected?.(`Peer connection ${n.connectionState}`))}),n.addEventListener(`datachannel`,({channel:e})=>{r.channel=e,e.addEventListener(`open`,()=>{r.open=!0}),e.addEventListener(`close`,()=>{r.open?(Bp.warn(`Follower data channel closed post-connect`,{bootstrapId:t}),this.options.onDisconnected?.(`Data channel closed`)):r.openError=`Follower data channel closed before opening`}),e.addEventListener(`error`,()=>{r.open?(Bp.warn(`Follower data channel error post-connect`,{bootstrapId:t}),this.options.onDisconnected?.(`Data channel error`)):r.openError=`Follower data channel failed before opening`})}),n.addEventListener(`icecandidate`,({candidate:n})=>{let r=Jp(n);r&&Mp({joinUrl:this.options.joinUrl,controllerId:e,bootstrapId:t,candidate:r,fetchImpl:this.fetchImpl}).catch(e=>{Bp.warn(`Failed to send follower ICE candidate`,{error:e instanceof Error?e.message:String(e)})})}),r}};function Gp(e,t){let n=t.baseDelayMs??1e3,r=t.backoffMultiplier??2,i=t.maxDelayMs??3e4,a=t.maxAttempts??10,o=t.sleep??e.sleep??(e=>new Promise(t=>setTimeout(t,e))),s=!1,c=!1,l=null,u={cancel(){s=!0,c=!1,l?.stop(),l=null},get reconnecting(){return c}},d=()=>{let t=new Wp({...e,sleep:o,onDisconnected:e=>{s||(Bp.warn(`Follower disconnected, starting reconnect loop`,{reason:e}),p(e))}});return l=t,{manager:t,connectionPromise:t.start()}},p=async u=>{if(s||c)return;c=!0,l?.stop(),l=null;let p=0,h=n,g=u??`Unknown disconnect`;for(;!s&&p<a&&(p++,t.onReconnecting?.(p),f({...m(),state:`reconnecting`,error:null,reconnectAttempts:p}),Bp.info(`Reconnect attempt`,{attempt:p,delay:h}),await o(h),!s);){let n=null;try{let r=d();n=r.manager;let i=await r.connectionPromise;if(s){n.stop();break}c=!1,f({...m(),state:`connected`,joinUrl:e.joinUrl,trayId:i.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),Bp.info(`Reconnect successful`,{attempt:p,trayId:i.trayId}),t.onConnected(i);return}catch(e){g=e instanceof Error?e.message:String(e),Bp.warn(`Reconnect attempt failed`,{attempt:p,error:g}),n?.stop(),l=null}h=Math.min(h*r,i)}s||(c=!1,f({...m(),state:`error`,error:`Reconnect failed after ${p} attempts: ${g}`,reconnectAttempts:p}),Bp.warn(`Reconnect gave up`,{attempts:p,lastError:g}),t.onGaveUp?.(g))},{connectionPromise:h}=d();return h.then(e=>{s||t.onConnected(e)}).catch(e=>{s||Bp.warn(`Initial follower connection failed`,{error:e instanceof Error?e.message:String(e)})}),u}function Kp(e){if(typeof RTCPeerConnection>`u`)throw Error(`RTCPeerConnection is not available in this runtime`);let t=e?.length?{iceServers:e}:void 0;return new RTCPeerConnection(t)}function qp(e,t){if(!e||e.type!==t||typeof e.sdp!=`string`)throw Error(`Expected a local ${t} description before signaling`);return{type:e.type,sdp:e.sdp}}function Jp(e){if(!e||typeof e!=`object`)return null;let 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 Yp(e){if(e)throw Error(`Tray follower stopped before WebRTC bootstrap completed`)}var Xp=64*1024;async function Zp(e,t){try{switch(t.op){case`readFile`:return await Qp(e,t.path,t.encoding);case`writeFile`:return[await $p(e,t.path,t.content,t.encoding)];case`stat`:return[await em(e,t.path)];case`readDir`:return[await tm(e,t.path)];case`mkdir`:return[await nm(e,t.path,t.recursive)];case`rm`:return[await rm(e,t.path,t.recursive)];case`exists`:return[await im(e,t.path)];case`walk`:return[await am(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(e){return[sm(e)]}}async function Qp(e,t,n){return(n??`utf-8`)===`utf-8`?om(await e.readFile(t,{encoding:`utf-8`}),`utf-8`):om(cm(await e.readFile(t,{encoding:`binary`})),`base64`)}async function $p(e,t,n,r){if(r===`base64`){let r=lm(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:`void`}}}async function em(e,t){return{ok:!0,data:{type:`stat`,stat:await e.stat(t)}}}async function tm(e,t){return{ok:!0,data:{type:`dirEntries`,entries:await e.readDir(t)}}}async function nm(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function rm(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function im(e,t){return{ok:!0,data:{type:`exists`,exists:await e.exists(t)}}}async function am(e,t){let n=[];for await(let r of e.walk(t))n.push(r);return{ok:!0,data:{type:`paths`,paths:n}}}function om(e,t){if(e.length<=Xp)return[{ok:!0,data:{type:`file`,content:e,encoding:t}}];let n=Math.ceil(e.length/Xp),r=[];for(let i=0;i<n;i++){let a=i*Xp,o=e.slice(a,a+Xp);r.push({ok:!0,data:{type:`file`,content:o,encoding:t},chunkIndex:i,totalChunks:n})}return r}function sm(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 cm(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function lm(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var um=class{runtimes=new Map;dirty=!1;setTargets(e,t){this.runtimes.set(e,t),this.dirty=!0}removeRuntime(e){this.runtimes.delete(e)&&(this.dirty=!0)}getEntries(){this.dirty=!1;let e=[];for(let[t,n]of this.runtimes)for(let r of n)e.push({targetId:`${t}:${r.targetId}`,localTargetId:r.targetId,runtimeId:t,title:r.title,url:r.url,isLocal:!1});return e}hasChanged(){return this.dirty}getRuntimeIds(){return[...this.runtimes.keys()]}},dm=n(`data-channel-keepalive`),fm=class{sendPing;onDead;intervalMs;maxMissed;timer=null;missedPongs=0;awaitingPong=!1;stopped=!1;constructor(e){this.sendPing=e.sendPing,this.onDead=e.onDead,this.intervalMs=e.intervalMs??1e4,this.maxMissed=e.maxMissed??3}start(){this.timer||this.stopped||(this.timer=setInterval(()=>this.tick(),this.intervalMs))}stop(){this.stopped=!0,this.timer&&=(clearInterval(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++,dm.debug(`Missed pong`,{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){dm.warn(`Channel declared dead`,{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}},pm=n(`tray-leader-sync`);function mm(e){return e?e.includes(`standalone`)?`standalone`:e.includes(`extension`)?`extension`:e.includes(`electron`)?`electron`:`unknown`:`unknown`}var hm=class{followers=new Map;registry=new um;runtimeToBootstrap=new Map;pendingCDPRoutes=new Map;cdpChunkBuffers=new Map;remoteTransports=new Map;pendingTabOpenRoutes=new Map;tabOpenResolvers=new Map;pendingFsRoutes=new Map;fsResolvers=new Map;constructor(e){this.options=e}addFollower(e,t,n){this.removeFollower(e);let r=fe(t),i=r.onMessage(t=>{this.handleFollowerMessage(e,t)}),a=new fm({sendPing:()=>r.send({type:`ping`}),onDead:()=>{pm.warn(`Follower keepalive dead, removing follower`,{bootstrapId:e}),this.removeFollower(e),this.options.onFollowerDead?.(e)}});a.start(),this.followers.set(e,{bootstrapId:e,sync:r,unsubscribe:i,keepalive:a,runtime:n?.runtime,connectedAt:n?.connectedAt,lastActivity:Date.now(),floatType:mm(n?.runtime)}),pm.info(`Follower added to sync`,{bootstrapId:e,followerCount:this.followers.size}),this.sendSnapshotToFollower(e);let o=this.getConnectedEntries();o.length>0&&r.send({type:`targets.registry`,targets:o})}removeFollower(e){let t=this.followers.get(e);if(t){t.keepalive.stop(),t.unsubscribe(),t.sync.close(),this.followers.delete(e);for(let[t,n]of this.runtimeToBootstrap)if(n===e){this.cleanupRemoteTransports(t),this.registry.removeRuntime(t),this.runtimeToBootstrap.delete(t);break}this.registry.hasChanged()&&this.broadcastTargetRegistry(),pm.info(`Follower removed from sync`,{bootstrapId:e,followerCount:this.followers.size})}}broadcastEvent(e){if(this.followers.size===0)return;let t={type:`agent_event`,event:e,scoopJid:this.options.getScoopJid()};for(let e of this.followers.values())e.sync.send(t)}broadcastUserMessage(e,t){if(this.followers.size===0)return;let n={type:`user_message_echo`,text:e,messageId:t,scoopJid:this.options.getScoopJid()};for(let e of this.followers.values())e.sync.send(n)}broadcastStatus(e){if(this.followers.size===0)return;let t={type:`status`,scoopStatus:e};for(let e of this.followers.values())e.sync.send(t)}sendSnapshotToFollower(e){let t=this.followers.get(e);if(!t)return;let n=this.options.getMessages(),r=this.options.getScoopJid();ue(t.sync,n,r),pm.debug(`Snapshot sent to follower`,{bootstrapId:e,messageCount:n.length})}handleFollowerMessage(e,t){switch(t.type){case`user_message`:pm.info(`Follower user message received`,{bootstrapId:e,messageId:t.messageId}),this.options.onFollowerMessage(t.text,t.messageId);break;case`abort`:pm.info(`Follower abort received`,{bootstrapId:e}),this.options.onFollowerAbort();break;case`request_snapshot`:pm.info(`Follower snapshot request received`,{bootstrapId:e}),this.sendSnapshotToFollower(e);break;case`targets.advertise`:pm.info(`Follower targets advertised`,{bootstrapId:e,runtimeId:t.runtimeId,targetCount:t.targets.length});for(let e of[...this.remoteTransports.keys()]){let n=e.substring(0,e.indexOf(`:`));n!==`leader`&&!this.runtimeToBootstrap.has(n)&&n!==t.runtimeId&&(this.remoteTransports.get(e)?.disconnect(),this.remoteTransports.delete(e),pm.debug(`Cleaned up orphaned remote transport on advertise`,{key:e}))}this.runtimeToBootstrap.set(t.runtimeId,e),this.registry.setTargets(t.runtimeId,t.targets),this.broadcastTargetRegistry();break;case`cdp.request`:{let{requestId:n,targetRuntimeId:r,localTargetId:i,method:a,params:o,sessionId:s}=t;r===`leader`?this.executeLocalCDP(n,i,a,o,s,e):this.forwardCDPRequest(n,r,i,a,o,s,e);break}case`cdp.response`:this.handleCDPResponse(t);break;case`cdp.event`:this.handleCDPEvent(e,t.method,t.params,t.sessionId);break;case`tab.open`:{let{requestId:n,targetRuntimeId:r,url:i}=t;r===`leader`?this.executeLocalTabOpen(n,i,e):this.forwardTabOpen(n,r,i,e);break}case`tab.opened`:this.handleTabOpenResponse(t.requestId,t.targetId);break;case`tab.open.error`:this.handleTabOpenError(t.requestId,t.error);break;case`fs.request`:{let{requestId:n,targetRuntimeId:r,request:i}=t;r===`leader`?this.executeLocalFs(n,i,e):this.forwardFsRequest(n,r,i,e);break}case`fs.response`:this.handleFsResponse(t.requestId,t.response);break;case`ping`:{let t=this.followers.get(e);t&&(t.keepalive.receivePing(),t.lastActivity=Date.now(),t.sync.send({type:`pong`}));break}case`pong`:{let t=this.followers.get(e);t&&(t.keepalive.receivePong(),t.lastActivity=Date.now());break}}}setLocalTargets(e){this.registry.setTargets(`leader`,e),this.registry.hasChanged()&&this.broadcastTargetRegistry()}broadcastTargetRegistry(){if(this.followers.size===0)return;let e={type:`targets.registry`,targets:this.getConnectedEntries()};for(let t of this.followers.values())t.sync.send(e)}getTargets(){return this.getConnectedEntries()}getConnectedEntries(){return this.registry.getEntries().filter(e=>{if(e.runtimeId===`leader`)return!0;let t=this.runtimeToBootstrap.get(e.runtimeId);return t?this.followers.has(t):!1})}createRemoteTransport(e,t){let n=new me({sendCDPRequest:(n,r,i,a)=>{let o=this.runtimeToBootstrap.get(e),s=o?this.followers.get(o):void 0;if(!s){this.remoteTransports.get(`${e}:${t}`)?.handleResponse(n,void 0,`Target runtime "${e}" not connected`);return}this.pendingCDPRoutes.set(n,{requesterBootstrapId:`__leader__`,requestId:n}),s.sync.send({type:`cdp.request`,requestId:n,localTargetId:t,method:r,params:i,sessionId:a})}});return this.remoteTransports.set(`${e}:${t}`,n),n}removeRemoteTransport(e,t){let n=`${e}:${t}`,r=this.remoteTransports.get(n);r&&(r.disconnect(),this.remoteTransports.delete(n))}cleanupRemoteTransports(e){let t=`${e}:`;for(let e of[...this.remoteTransports.keys()])e.startsWith(t)&&(this.remoteTransports.get(e)?.disconnect(),this.remoteTransports.delete(e),pm.debug(`Cleaned up stale remote transport`,{key:e}))}getConnectedFollowers(){return[...this.runtimeToBootstrap.entries()].map(([e,t])=>{let n=this.followers.get(t);return{runtimeId:e,runtime:n?.runtime,connectedAt:n?.connectedAt,lastActivity:n?.lastActivity,floatType:n?.floatType}})}getBestFollowerForTeleport(){let e=[];for(let[t,n]of this.runtimeToBootstrap){let r=this.followers.get(n);r&&e.push({runtimeId:t,bootstrapId:n,floatType:r.floatType,lastActivity:r.lastActivity})}if(e.length===0)return null;let t=e.filter(e=>e.floatType===`standalone`),n=t.length>0?t:e;return n.sort((e,t)=>t.lastActivity-e.lastActivity),n[0]}get hasFollowers(){return this.followers.size>0}stop(){for(let e of[...this.followers.keys()])this.removeFollower(e)}async executeLocalCDP(e,t,n,r,i,a){let o=this.followers.get(a);if(!o)return;let s=this.options.browserTransport;if(!s){o.sync.send({type:`cdp.response`,requestId:e,error:`Leader has no browser transport`});return}try{let t=await s.send(n,r,i);ge(o.sync,e,t)}catch(t){o.sync.send({type:`cdp.response`,requestId:e,error:t instanceof Error?t.message:String(t)})}}forwardCDPRequest(e,t,n,r,i,a,o){let s=this.runtimeToBootstrap.get(t),c=s?this.followers.get(s):void 0,l=this.followers.get(o);if(!c){l&&l.sync.send({type:`cdp.response`,requestId:e,error:`Target runtime "${t}" not connected`});return}this.pendingCDPRoutes.set(e,{requesterBootstrapId:o,requestId:e}),c.sync.send({type:`cdp.request`,requestId:e,localTargetId:n,method:r,params:i,sessionId:a})}handleCDPResponse(e){let{requestId:t,result:n,error:r,chunkData:i,chunkIndex:a,totalChunks:o}=e,s=this.pendingCDPRoutes.get(t);if(!s)return;let c=le(this.cdpChunkBuffers,e);if(!c)return;if(this.pendingCDPRoutes.delete(t),s.requesterBootstrapId===`__leader__`){for(let e of this.remoteTransports.values())e.handleResponse(t,c.result,c.error);return}let l=this.followers.get(s.requesterBootstrapId);l&&ge(l.sync,t,c.result,c.error)}handleCDPEvent(e,t,n,r){let i;for(let[t,n]of this.runtimeToBootstrap)if(n===e){i=t;break}if(!i)return;let a=`${i}:`;for(let[e,r]of this.remoteTransports)e.startsWith(a)&&r.handleEvent(t,n)}openRemoteTab(e,t){let n=this.runtimeToBootstrap.get(e),r=n?this.followers.get(n):void 0;if(!r)return Promise.reject(Error(`Target runtime "${e}" not connected`));let i=`tab-open-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((e,n)=>{this.tabOpenResolvers.set(i,{resolve:e,reject:n}),this.pendingTabOpenRoutes.set(i,{requesterBootstrapId:`__leader__`,requestId:i}),r.sync.send({type:`tab.open`,requestId:i,url:t})})}async executeLocalTabOpen(e,t,n){let r=this.followers.get(n);if(!r)return;let i=this.options.browserTransport;if(!i){r.sync.send({type:`tab.open.error`,requestId:e,error:`Leader has no browser transport`});return}try{let n=(await i.send(`Target.createTarget`,{url:t,background:!0})).targetId;r.sync.send({type:`tab.opened`,requestId:e,targetId:`leader:${n}`})}catch(t){r.sync.send({type:`tab.open.error`,requestId:e,error:t instanceof Error?t.message:String(t)})}}forwardTabOpen(e,t,n,r){let i=this.runtimeToBootstrap.get(t),a=i?this.followers.get(i):void 0,o=this.followers.get(r);if(!a){o&&o.sync.send({type:`tab.open.error`,requestId:e,error:`Target runtime "${t}" not connected`});return}this.pendingTabOpenRoutes.set(e,{requesterBootstrapId:r,requestId:e}),a.sync.send({type:`tab.open`,requestId:e,url:n})}handleTabOpenResponse(e,t){let n=this.pendingTabOpenRoutes.get(e);if(!n)return;if(this.pendingTabOpenRoutes.delete(e),n.requesterBootstrapId===`__leader__`){let n=this.tabOpenResolvers.get(e);n&&(this.tabOpenResolvers.delete(e),n.resolve(t));return}let r=this.followers.get(n.requesterBootstrapId);r&&r.sync.send({type:`tab.opened`,requestId:e,targetId:t})}handleTabOpenError(e,t){let n=this.pendingTabOpenRoutes.get(e);if(!n)return;if(this.pendingTabOpenRoutes.delete(e),n.requesterBootstrapId===`__leader__`){let n=this.tabOpenResolvers.get(e);n&&(this.tabOpenResolvers.delete(e),n.reject(Error(t)));return}let r=this.followers.get(n.requesterBootstrapId);r&&r.sync.send({type:`tab.open.error`,requestId:e,error:t})}async executeLocalFs(e,t,n){let r=this.followers.get(n);if(!r)return;let i=this.options.vfs;if(!i){r.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:`Leader has no VFS`}});return}let a=await Zp(i,t);for(let t of a)r.sync.send({type:`fs.response`,requestId:e,response:t})}forwardFsRequest(e,t,n,r){let i=this.runtimeToBootstrap.get(t),a=i?this.followers.get(i):void 0,o=this.followers.get(r);if(!a){o&&o.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:`Target runtime "${t}" not connected`}});return}this.pendingFsRoutes.set(e,{requesterBootstrapId:r,requestId:e,chunks:[],totalChunks:1}),a.sync.send({type:`fs.request`,requestId:e,request:n})}handleFsResponse(e,t){let n=this.pendingFsRoutes.get(e);if(!n){let n=this.fsResolvers.get(e);if(n){n.responses.push(t);let r=t.ok&&t.totalChunks||1;n.responses.length>=r&&(this.fsResolvers.delete(e),n.resolve(n.responses))}return}if(n.requesterBootstrapId===`__leader__`){let n=this.fsResolvers.get(e);if(n){n.responses.push(t);let r=t.ok&&t.totalChunks||1;n.responses.length>=r&&(this.fsResolvers.delete(e),this.pendingFsRoutes.delete(e),n.resolve(n.responses))}return}let r=this.followers.get(n.requesterBootstrapId);r&&r.sync.send({type:`fs.response`,requestId:e,response:t}),n.chunks.push(t),n.totalChunks=t.ok&&t.totalChunks||1,n.chunks.length>=n.totalChunks&&this.pendingFsRoutes.delete(e)}sendFsRequest(e,t){if(e===`leader`){let e=this.options.vfs;return e?Zp(e,t):Promise.resolve([{ok:!1,error:`Leader has no VFS`}])}let n=this.runtimeToBootstrap.get(e),r=n?this.followers.get(n):void 0;if(!r)return Promise.resolve([{ok:!1,error:`Target runtime "${e}" not connected`}]);let i=`fs-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((e,n)=>{this.fsResolvers.set(i,{resolve:e,reject:n,responses:[]}),this.pendingFsRoutes.set(i,{requesterBootstrapId:`__leader__`,requestId:i,chunks:[],totalChunks:1}),r.sync.send({type:`fs.request`,requestId:i,request:t})})}},gm=n(`tray-follower-sync`),_m=class{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;constructor(e,t={}){this.options=t,this.sync=he(e),this.unsubscribe=this.sync.onMessage(e=>{this.handleLeaderMessage(e)}),this.keepalive=new fm({sendPing:()=>this.sync.send({type:`ping`}),onDead:()=>{gm.warn(`Leader keepalive dead, cleaning up`),this.handleDisconnect(`Keepalive timeout — leader not responding`),this.options.onDead?.()}}),this.keepalive.start(),e.addEventListener(`close`,()=>{gm.warn(`Data channel closed`),this.handleDisconnect(`Data channel closed`)}),e.addEventListener(`error`,()=>{gm.warn(`Data channel error`),this.handleDisconnect(`Data channel error`)})}sendMessage(e,t){let n=t??`follower-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.sentMessageIds.add(n),this.sync.send({type:`user_message`,text:e,messageId:n}),gm.info(`Sent user message to leader`,{messageId:n})}onEvent(e){return this.eventListeners.add(e),()=>this.eventListeners.delete(e)}stop(){this.sync.send({type:`abort`}),gm.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(),gm.info(`Follower sync closed`)}advertiseTargets(e,t){this.sync.send({type:`targets.advertise`,targets:e,runtimeId:t})}getTargets(){return this.targetEntries}disconnected=!1;handleDisconnect(e){this.disconnected||(this.disconnected=!0,f({...m(),state:`error`,error:e}),this.emitEvent({type:`error`,error:`Connection to leader lost: ${e}`}),this.keepalive.stop(),this.cleanupCDPEventForwarding(),this.unsubscribe(),this.sync.close(),this.options.onDisconnect?.(e))}handleLeaderMessage(e){switch(e.type){case`snapshot`:gm.info(`Snapshot received from leader`,{messageCount:e.messages.length,scoopJid:e.scoopJid}),this.snapshotChunkBuffer=null,this.latestSnapshot={messages:e.messages,scoopJid:e.scoopJid},this.options.onSnapshot?.(e.messages,e.scoopJid);break;case`snapshot_chunk`:{let t=B(this.snapshotChunkBuffer,e);this.snapshotChunkBuffer=t.buffer,t.result&&(gm.info(`Chunked snapshot reassembled from leader`,{messageCount:t.result.messages.length,scoopJid:t.result.scoopJid}),this.latestSnapshot=t.result,this.options.onSnapshot?.(t.result.messages,t.result.scoopJid));break}case`agent_event`:this.emitEvent(e.event);break;case`user_message_echo`:if(this.sentMessageIds.has(e.messageId)){this.sentMessageIds.delete(e.messageId),gm.debug(`Skipping own message echo`,{messageId:e.messageId});break}gm.info(`User message echo received`,{messageId:e.messageId,scoopJid:e.scoopJid}),this.options.onUserMessage?.(e.text,e.messageId,e.scoopJid);break;case`status`:this.options.onStatus?.(e.scoopStatus);break;case`error`:gm.warn(`Error from leader`,{error:e.error}),this.emitEvent({type:`error`,error:e.error});break;case`targets.registry`:gm.info(`Target registry received from leader`,{targetCount:e.targets.length}),this.targetEntries=e.targets,this.options.onTargetsUpdated?.(this.targetEntries);break;case`cdp.request`:{let{requestId:t,localTargetId:n,method:r,params:i,sessionId:a}=e;this.executeLocalCDP(t,n,r,i,a);break}case`cdp.response`:this.routeCDPResponse(e);break;case`cdp.event`:for(let t of this.remoteTransports.values())t.handleEvent(e.method,e.params);break;case`tab.open`:this.executeLocalTabOpen(e.requestId,e.url);break;case`tab.opened`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.resolve(e.targetId));break}case`tab.open.error`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.reject(Error(e.error)));break}case`fs.request`:this.executeLocalFs(e.requestId,e.request);break;case`fs.response`:this.routeFsResponse(e.requestId,e.response);break;case`ping`:this.keepalive.receivePing(),this.sync.send({type:`pong`});break;case`pong`:this.keepalive.receivePong(),l(Date.now());break}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch(t){gm.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}}createRemoteTransport(e,t){let n=new me({sendCDPRequest:(n,r,i,a)=>{this.sync.send({type:`cdp.request`,requestId:n,targetRuntimeId:e,localTargetId:t,method:r,params:i,sessionId:a})}});return this.remoteTransports.set(`${e}:${t}`,n),n}removeRemoteTransport(e,t){let n=`${e}:${t}`,r=this.remoteTransports.get(n);r&&(r.disconnect(),this.remoteTransports.delete(n))}openRemoteTab(e,t){let n=`tab-open-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((r,i)=>{this.tabOpenResolvers.set(n,{resolve:r,reject:i}),this.sync.send({type:`tab.open`,requestId:n,targetRuntimeId:e,url:t})})}async executeLocalTabOpen(e,t){let n=this.options.browserTransport;if(!n){this.sync.send({type:`tab.open.error`,requestId:e,error:`Follower has no browser transport`});return}try{let r=(await n.send(`Target.createTarget`,{url:t,background:!0})).targetId;this.sync.send({type:`tab.opened`,requestId:e,targetId:r}),this.options.onTargetsChanged?.()}catch(t){this.sync.send({type:`tab.open.error`,requestId:e,error:t instanceof Error?t.message:String(t)})}}async executeLocalCDP(e,t,n,r,i){let a=this.options.browserTransport;if(!a){this.sync.send({type:`cdp.response`,requestId:e,error:`Follower has no browser transport`});return}try{let t=await a.send(n,r,i);if(n===`Target.attachToTarget`&&t.sessionId){let e=t.sessionId;this.remoteCDPSessions.add(e),this.setupCDPEventForwarding(a,e),gm.debug(`Tracking remote CDP session`,{remoteSessionId:e})}n===`Target.detachFromTarget`&&i&&this.remoteCDPSessions.has(i)&&(this.remoteCDPSessions.delete(i),gm.debug(`Removed remote CDP session on detach`,{sessionId:i})),ge(this.sync,e,t)}catch(t){this.sync.send({type:`cdp.response`,requestId:e,error:t instanceof Error?t.message:String(t)})}}setupCDPEventForwarding(e,t){for(let n of[`Page.frameNavigated`,`Page.loadEventFired`,`Page.domContentEventFired`,`Network.responseReceived`,`Network.loadingFinished`,`Network.requestWillBeSent`]){let r=e=>{if(e.sessionId!==t||!this.remoteCDPSessions.has(t))return;let{sessionId:r,...i}=e;this.sync.send({type:`cdp.event`,method:n,params:i,sessionId:t})};e.on(n,r),this.cdpEventCleanups.push(()=>e.off(n,r))}}cleanupCDPEventForwarding(){for(let e of this.cdpEventCleanups)e();this.cdpEventCleanups.length=0,this.remoteCDPSessions.clear()}routeCDPResponse(e){let t=le(this.cdpChunkBuffers,e);if(t)for(let n of this.remoteTransports.values())n.handleResponse(e.requestId,t.result,t.error)}async executeLocalFs(e,t){let n=this.options.vfs;if(!n){this.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:`Follower has no VFS`}});return}let r=await Zp(n,t);for(let t of r)this.sync.send({type:`fs.response`,requestId:e,response:t})}routeFsResponse(e,t){let n=this.fsResolvers.get(e);if(!n)return;n.responses.push(t);let r=t.ok&&t.totalChunks||1;n.responses.length>=r&&(this.fsResolvers.delete(e),n.resolve(n.responses))}sendFsRequest(e,t){let n=`fs-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((r,i)=>{this.fsResolvers.set(n,{resolve:r,reject:i,responses:[]}),this.sync.send({type:`fs.request`,requestId:n,targetRuntimeId:e,request:t})})}};function vm(e,t){if(t)return`extension`;try{return xm(new URL(e))?`electron-overlay`:`standalone`}catch{return`standalone`}}function ym(e,t){return e===`electron-overlay`||e===`standalone`&&t}function bm(e){try{let t=new URL(e).searchParams.get(`tab`);return t&&Bi(t)?t:Ri}catch{return Ri}}function xm(e){return e.pathname===`/electron`||e.pathname===`/electron/`||e.searchParams.get(`runtime`)===`electron-overlay`}function Sm(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}/licks-ws`}function Cm(e,t){return`${new URL(e).origin}/webhooks/${t}`}function wm(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function Tm(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`slicc-electron-overlay:set-tab`}var Em=[`/shared/sprinkles`];async function Dm(e){let t=new Map;for(let n of Em)await e.exists(n)&&await Om(e,n,t);return await Om(e,`/`,t),t}async function Om(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.shtml`))continue;let t=km(r);if(!n.has(t)){let i;try{i=await e.readFile(r,{encoding:`utf-8`})??``}catch{i=``}n.set(t,{name:t,path:r,title:Am(i,t),autoOpen:jm(i)})}}}function km(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.shtml`)?t.slice(0,-6):t}function Am(e,t){let n=e.match(/data-sprinkle-title=["']([^"']+)["']/);if(n)return n[1];let r=e.match(/<title>([^<]+)<\/title>/i);return r?r[1].trim():t}function jm(e){return/data-sprinkle-autoopen\b/.test(e)}var Mm=class{listeners=new Map;lickHandler;fs;closeHandler;constructor(e,t,n){this.fs=e,this.lickHandler=t,this.closeHandler=n}createAPI(e){let t={name:e,lick:t=>{let n=typeof t==`string`?t:t.action,r=typeof t==`string`?void 0:t.data,i={type:`sprinkle`,sprinkleName:e,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:n,data:r}};this.lickHandler(i)},on:(t,n)=>{let r=`${e}:${t}`,i=this.listeners.get(r);i||(i=new Set,this.listeners.set(r,i)),i.add(n)},off:(t,n)=>{let r=`${e}:${t}`;this.listeners.get(r)?.delete(n)},readFile:async e=>await this.fs.readFile(e,{encoding:`utf-8`}),writeFile:async(e,t)=>{await this.fs.writeFile(e,t)},readDir:async e=>(await this.fs.readDir(e)).map(e=>({name:e.name,type:e.type})),exists:async e=>this.fs.exists(e),stat:async e=>{let t=await this.fs.stat(e);return{type:t.type,size:t.size}},mkdir:async e=>{await this.fs.mkdir(e,{recursive:!0})},rm:async e=>{await this.fs.rm(e)},screenshot:async e=>{let n=t._container;if(!n)return``;let r=e?n.querySelector(e):n;if(!r)throw Error(`Element not found: `+(e||`container`));let i=r.getBoundingClientRect(),a=Math.ceil(i.width),o=Math.ceil(i.height);if(a===0||o===0)throw Error(`Element has zero dimensions`);let s=document.createElement(`canvas`),c=window.devicePixelRatio||1;s.width=a*c,s.height=o*c;let l=s.getContext(`2d`);l.scale(c,c);let u=r.cloneNode(!0),d=`<svg xmlns="http://www.w3.org/2000/svg" width="${a}" height="${o}"><foreignObject width="100%" height="100%">${new XMLSerializer().serializeToString(u)}</foreignObject></svg>`;return new Promise((e,t)=>{let n=new Image;n.onload=()=>{l.drawImage(n,0,0),e(s.toDataURL(`image/png`))},n.onerror=()=>t(Error(`Screenshot rendering failed`)),n.src=`data:image/svg+xml;charset=utf-8,`+encodeURIComponent(d)})},setState:t=>{try{localStorage.setItem(`slicc-sprinkle-state:${e}`,JSON.stringify(t))}catch{}},getState:()=>{try{let t=localStorage.getItem(`slicc-sprinkle-state:${e}`);return t?JSON.parse(t):null}catch{return null}},open:e=>{let t=/^https?:|^chrome-extension:/.test(e)?e:Mc(e);window.open(t,`_blank`)},close:()=>this.closeHandler(e)};return t}pushUpdate(e,t){let n=`${e}:update`,r=this.listeners.get(n);if(r)for(let e of r)try{e(t)}catch{}}removeSprinkle(e){for(let t of this.listeners.keys())t.startsWith(`${e}:`)&&this.listeners.delete(t)}},Nm=n(`sprinkle-manager`),Pm=`slicc-open-sprinkles`,Fm=class{fs;bridge;callbacks;availableSprinkles=new Map;openSprinkles=new Map;constructor(e,t,n){this.fs=e,this.bridge=new Mm(e,t,e=>this.close(e)),this.callbacks=n}async restoreOpenSprinkles(){try{let e=localStorage.getItem(Pm);if(!e){for(let e of this.availableSprinkles.values())if(e.autoOpen)try{await this.open(e.name)}catch{Nm.warn(`Failed to auto-open sprinkle`,{name:e.name})}return}let t=JSON.parse(e);for(let e of t)try{await this.open(e)}catch{Nm.warn(`Failed to restore sprinkle`,{name:e})}}catch{}}persistOpenSprinkles(){try{localStorage.setItem(Pm,JSON.stringify([...this.openSprinkles.keys()]))}catch{}}async openNewAutoOpenSprinkles(){await this.refresh();for(let e of this.availableSprinkles.values())if(e.autoOpen&&!this.openSprinkles.has(e.name))try{await this.open(e.name),Nm.info(`Auto-opened new sprinkle after install`,{name:e.name})}catch{Nm.warn(`Failed to auto-open new sprinkle`,{name:e.name})}}async refresh(){this.availableSprinkles=await Dm(this.fs),Nm.info(`Discovered sprinkles`,{count:this.availableSprinkles.size})}async open(e,t){if(this.openSprinkles.has(e)){Nm.info(`Sprinkle already open`,{name:e});return}let n=this.availableSprinkles.get(e);if(n||=(await this.refresh(),this.availableSprinkles.get(e)),!n)throw Error(`Sprinkle not found: ${e}`);let r=await this.fs.readFile(n.path,{encoding:`utf-8`}),i=document.createElement(`div`);i.className=`sprinkle-panel`,i.style.cssText=`width: 100%; height: 100%; display: flex; flex-direction: column; overflow: hidden;`,i.dataset.sprinkle=e,this.openSprinkles.set(e,{renderer:null,container:i}),this.callbacks.addSprinkle(e,n.title,i,t);let a=new Qr(i,this.bridge.createAPI(e));await a.render(r,e),this.openSprinkles.get(e).renderer=a,this.persistOpenSprinkles(),df(e),Nm.info(`Sprinkle opened`,{name:e,title:n.title})}close(e){let t=this.openSprinkles.get(e);t&&(t.renderer?.dispose(),t.container.remove(),this.bridge.removeSprinkle(e),this.openSprinkles.delete(e),this.callbacks.removeSprinkle(e),this.persistOpenSprinkles(),Nm.info(`Sprinkle closed`,{name:e}))}available(){return Array.from(this.availableSprinkles.values())}opened(){return Array.from(this.openSprinkles.keys())}sendToSprinkle(e,t){let n=this.openSprinkles.get(e);if(!n){Nm.warn(`Cannot send to closed sprinkle`,{name:e});return}this.bridge.pushUpdate(e,t),n.renderer.pushUpdate(t)}};function Im(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function Lm(e){let t=[],{payload:n}=e;if(n.title&&t.push(`# ${n.title}`),t.push(`A new handoff was accepted from ${Im(e.sourceUrl)}.`),t.push(`## Instruction`),t.push(n.instruction),n.urls&&n.urls.length>0){t.push(`## URLs`);for(let e of n.urls)t.push(`- ${e}`)}if(n.context&&(t.push(`## Context`),t.push(n.context)),n.acceptanceCriteria&&n.acceptanceCriteria.length>0){t.push(`## Acceptance Criteria`);for(let e of n.acceptanceCriteria)t.push(`- ${e}`)}return n.notes&&(t.push(`## Notes`),t.push(n.notes)),t.join(`
|
|
12682
|
+
`);return Error(`Cannot remove scoop '${e}': it has ${r.join(` and `)}. Unregister them first:\n${i}`)}var Cp=null;function wp(){return Cp||=new xp,Cp}var Q=n(`orchestrator`),Tp=120*1e3,Ep=class{scoops=new Map;tabs=new Map;contexts=new Map;messageQueues=new Map;lastAgentTimestamp=new Map;container;callbacks;config;pollInterval=null;scheduler=null;globalMemoryCache=``;sharedFs=null;scoopResponseBuffer=new Map;lickManager=null;sessionStore=null;idleTimers=new Map;constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n}async init(){await Te(),this.sharedFs=await z.create({dbName:`slicc-fs`}),this.sessionStore=new k,await this.ensureRootStructure();let e=await xe();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.scoops.set(t.jid,t),this.messageQueues.set(t.jid,[]);let e=await je(`lastAgentTs_${t.jid}`);e&&this.lastAgentTimestamp.set(t.jid,e)}await this.ensureGlobalMemory(),this.scheduler=new yp({onTaskRun:async(e,t)=>{Q.info(`Running scheduled task`,{taskId:e.id,scoop:t.name}),await this.sendPrompt(t.jid,`[SCHEDULED TASK]\n\n${e.prompt}`,`scheduler`,`Scheduled Task`)},getScoop:e=>{for(let t of this.scoops.values())if(t.folder===e)return t}}),this.scheduler.start(),Q.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let e of this.scoops.values())await this.createScoopTab(e.jid);Ve(()=>this.getSessionCosts()),this.startMessageLoop()}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}async ensureGlobalMemory(){if(this.sharedFs){await fp(this.sharedFs);try{let e=await this.sharedFs.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});this.globalMemoryCache=typeof e==`string`?e:new TextDecoder().decode(e)}catch{Q.warn(`Global memory file not found after creating defaults`)}}}async getGlobalMemory(){if(this.globalMemoryCache)return this.globalMemoryCache;if(this.sharedFs)try{let e=await this.sharedFs.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});this.globalMemoryCache=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}return this.globalMemoryCache}async setGlobalMemory(e){this.sharedFs&&(await this.sharedFs.writeFile(`/shared/CLAUDE.md`,e),this.globalMemoryCache=e,Q.info(`Global memory updated`))}getSharedFS(){return this.sharedFs}setLickManager(e){this.lickManager=e}async registerScoop(e){await Ie(e),this.scoops.set(e.jid,e),this.messageQueues.set(e.jid,[]),Q.info(`Scoop registered`,{jid:e.jid,name:e.name}),this.createScoopTab(e.jid).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Scoop init failed`,{jid:e.jid,error:n})})}async unregisterScoop(e){let t=this.scoops.get(e);if(t&&this.lickManager){let{webhooks:e,cronTasks:n}=this.lickManager.getLicksForScoop(t.name,t.folder),r=Sp(t.folder,e,n);if(r)throw r}this.clearIdleTimer(e),await this.destroyScoopTab(e),this.sessionStore?.delete(e).catch(t=>{Q.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await Ee(e),this.scoops.delete(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),Q.info(`Scoop unregistered`,{jid:e})}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}async resetFilesystem(){for(let[e,t]of this.contexts.entries())this.clearIdleTimer(e),t.stop(),this.contexts.delete(e);this.sharedFs=await z.create({dbName:`slicc-fs`,wipe:!0}),await this.ensureRootStructure(),await this.ensureGlobalMemory(),await dp(this.sharedFs).catch(e=>{Q.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),Q.info(`Filesystem reset and defaults re-seeded`)}async clearAllMessages(){await Pe(),this.sessionStore&&await this.sessionStore.clearAll().catch(e=>{Q.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.contexts.values())e.clearMessages();this.lastAgentTimestamp.clear();for(let e of this.scoops.keys())this.messageQueues.set(e,[]);Q.info(`All messages cleared`)}async handleMessage(e){Q.info(`handleMessage`,{id:e.id,chatJid:e.chatJid,sender:e.senderName,channel:e.channel,contentPreview:e.content.slice(0,80)});let t=this.scoops.get(e.chatJid);lf(t?.isCone?`cone`:t?.name??`unknown`,localStorage.getItem(`selected-model`)??`unknown`),await ve(e),await this.routeToScoop(e)}async delegateToScoop(e,t,n){let r=this.scoops.get(e);if(!r)throw Error(`Scoop not found: ${e}`);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`delegation`};await ve(i),this.callbacks.onIncomingMessage?.(e,i),Q.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Delegation failed`,{scoopJid:e,error:n}),this.callbacks.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.scoops.get(e.chatJid);if(!t){Q.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}let n=e.channel===`webhook`||e.channel===`cron`;if(!t.isCone&&t.requiresTrigger&&t.trigger&&!n&&!e.content.includes(t.trigger)){Q.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let r=this.messageQueues.get(e.chatJid)??[];r.push(e),this.messageQueues.set(e.chatJid,r);let i=this.tabs.get(e.chatJid);if(Q.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:i?.status??`no-tab`,queueLength:r.length}),i?.status===`error`){Q.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.createScoopTab(e.chatJid),i=this.tabs.get(e.chatJid)}catch{Q.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}i?.status===`ready`&&await this.processScoopQueue(e.chatJid)}async createScoopTab(e){let t=this.scoops.get(e);if(!t)throw Error(`Scoop not found: ${e}`);if(this.contexts.has(e))if(this.tabs.get(e)?.status===`error`)Q.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{Q.debug(`Context already exists`,{jid:e});return}if(!this.sharedFs)throw Error(`Shared filesystem not initialized`);let n=`scoop-${t.folder}-${Date.now()}`,r=t.isCone?this.sharedFs:new R(this.sharedFs,[`/scoops/${t.folder}/`,`/shared/`],[`/workspace/`]),i=new _p(t,{onResponse:(n,r)=>{if(this.callbacks.onResponse(e,n,r),!t.isCone)if(r){let t=this.scoopResponseBuffer.get(e)??``;this.scoopResponseBuffer.set(e,t+n)}else this.scoopResponseBuffer.set(e,n)},onResponseDone:()=>{let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),this.callbacks.onResponseDone(e)},onError:t=>{let n=this.tabs.get(e);n&&(n.status=`error`,n.error=t,this.tabs.set(e,n)),this.callbacks.onError(e,t),this.callbacks.onStatusChange(e,`error`)},onStatusChange:n=>{let r=this.tabs.get(e);if(r&&(r.status=n,r.lastActivity=new Date().toISOString(),this.tabs.set(e,r)),this.callbacks.onStatusChange(e,n),n===`ready`&&!t.isCone){let n=this.scoopResponseBuffer.get(e);if(this.scoopResponseBuffer.delete(e),n){let r=Array.from(this.scoops.values()).find(e=>e.isCone);if(r){let i=n.length>2e3?n.slice(0,2e3)+`
|
|
12683
|
+
... (truncated)`:n,a={id:`scoop-done-${e}-${Date.now()}`,chatJid:r.jid,senderId:t.folder,senderName:t.assistantLabel,content:`[@${t.assistantLabel} completed]:\n${i}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-notify`};Q.info(`Routing scoop completion to cone`,{scoop:t.folder,responseLength:n.length}),this.handleMessage(a).catch(e=>{let n=e instanceof Error?e.message:String(e);Q.error(`Failed to route scoop completion to cone`,{scoop:t.folder,error:n}),this.callbacks.onError(r.jid,`Scoop ${t.folder} completed but notification failed: ${n}`)})}}}},onToolStart:(t,n)=>{this.callbacks.onToolStart?.(e,t,n)},onToolEnd:(t,n,r)=>{this.callbacks.onToolEnd?.(e,t,n,r)},onToolUI:(t,n,r)=>{this.callbacks.onToolUI?.(e,t,n,r)},onToolUIDone:t=>{this.callbacks.onToolUIDone?.(e,t)},onSendMessage:(t,n)=>{this.callbacks.onSendMessage(e,`${n?`[${n}] `:``}${t}`)},getScoops:()=>this.getScoops(),getScoopTabState:t.isCone?e=>this.tabs.get(e):void 0,onFeedScoop:t.isCone?(e,n)=>this.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:t.isCone?async e=>{let t={...e,jid:`scoop_${e.folder}_${Date.now()}`};return await this.registerScoop(t),t}:void 0,onDropScoop:t.isCone?async e=>{await this.unregisterScoop(e)}:void 0,getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:t.isCone?e=>this.setGlobalMemory(e):void 0,getBrowserAPI:()=>this.callbacks.getBrowserAPI()},r,this.sessionStore??void 0,this.sharedFs??void 0);this.contexts.set(e,i),this.tabs.set(e,{jid:e,contextId:n,status:`initializing`,lastActivity:new Date().toISOString()}),await i.init();let a=this.tabs.get(e);a&&a.status===`initializing`&&(a.status=`ready`,this.tabs.set(e,a),this.callbacks.onStatusChange(e,`ready`));let o=this.scoops.get(e);o&&!o.isCone&&this.startIdleTimer(e),Q.info(`Scoop context created`,{jid:e,contextId:n})}async destroyScoopTab(e){this.clearIdleTimer(e);let t=this.contexts.get(e);t&&(t.dispose(),this.contexts.delete(e),this.tabs.delete(e),Q.info(`Scoop context destroyed`,{jid:e}))}isProcessing(e){return this.tabs.get(e)?.status===`processing`}getScoopContext(e){return this.contexts.get(e)}async clearQueuedMessages(e){let t=this.messageQueues.get(e);if(t&&t.length>0){for(let e of t)await Me(e.id);this.messageQueues.set(e,[])}}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let e=n.findIndex(e=>e.id===t);e!==-1&&n.splice(e,1)}await Me(t)}async getMessagesForScoop(e){return Se(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.tabs.get(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return Q.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r){let i=this.contexts.get(e);i||=(await this.createScoopTab(e),this.contexts.get(e));let a=this.tabs.get(e);if(a?.status===`initializing`){if(Q.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){Q.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}i=this.contexts.get(e),a=this.tabs.get(e)}if(!i){Q.error(`Context not found after creation`,{jid:e});return}this.clearIdleTimer(e),this.scoopResponseBuffer.delete(e),a&&(a.status=`processing`,a.lastActivity=new Date().toISOString(),this.tabs.set(e,a),this.callbacks.onStatusChange(e,`processing`)),Q.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length}),await i.prompt(t)}async processScoopQueue(e){let t=this.messageQueues.get(e);if(!t||t.length===0){Q.debug(`processScoopQueue: empty queue`,{jid:e});return}let n=this.tabs.get(e);if(n?.status!==`ready`){Q.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.scoops.get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await Ce(e,a,i);if(Q.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,queueLength:t.length}),o.length===0){Q.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]);return}let s=o.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${e.content}`).join(`
|
|
12684
|
+
`);this.messageQueues.set(e,[]);let c=o[o.length-1];this.lastAgentTimestamp.set(e,c.timestamp),await Le(`lastAgentTs_${e}`,c.timestamp),await this.sendPrompt(e,s,c.senderId,c.senderName)}startMessageLoop(){this.pollInterval||=window.setInterval(()=>{for(let e of this.scoops.keys())this.tabs.get(e)?.status===`ready`&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Message queue processing failed`,{jid:e,error:n}),this.callbacks.onError(e,`Queue processing failed: ${n}`)})},2e3)}stopMessageLoop(){this.pollInterval&&=(clearInterval(this.pollInterval),null)}updateModel(){for(let e of this.contexts.values())e.updateModel();Q.info(`Model updated on all active contexts`,{contextCount:this.contexts.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.contexts){let r=this.tabs.get(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{Q.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),Q.info(`Skills reloaded across all contexts`,{count:e.length})}stopScoop(e){let t=this.contexts.get(e);t&&t.stop()}getSessionCosts(){let e=[];for(let t of this.scoops.values()){let n=this.contexts.get(t.jid);if(!n)continue;let r=n.getAgentMessages().filter(e=>e.role===`assistant`);if(r.length===0)continue;let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},a=new Map;for(let e of r)i.input+=e.usage.input,i.output+=e.usage.output,i.cacheRead+=e.usage.cacheRead,i.cacheWrite+=e.usage.cacheWrite,i.totalTokens+=e.usage.totalTokens,i.cost.input+=e.usage.cost.input,i.cost.output+=e.usage.cost.output,i.cost.cacheRead+=e.usage.cost.cacheRead,i.cost.cacheWrite+=e.usage.cost.cacheWrite,i.cost.total+=e.usage.cost.total,a.set(e.model,(a.get(e.model)??0)+1);let o=``,s=0;for(let[e,t]of a)t>s&&(o=e,s=t);e.push({name:t.assistantLabel,type:t.isCone?`cone`:`scoop`,model:o,usage:i,turns:r.length})}return e}startIdleTimer(e){if(this.clearIdleTimer(e),this.tabs.get(e)?.status===`processing`)return;let t=setTimeout(()=>{this.idleTimers.delete(e);let t=this.scoops.get(e);if(!t||t.isCone||this.tabs.get(e)?.status!==`ready`)return;let n=Array.from(this.scoops.values()).find(e=>e.isCone);if(!n)return;let r={id:`scoop-idle-${e}-${Date.now()}`,chatJid:n.jid,senderId:t.folder,senderName:t.assistantLabel,content:`[@${t.assistantLabel} idle]: Scoop "${t.name}" has been ready for 2 minutes without receiving any work. This is expected if the scoop is waiting for webhooks or cron tasks. If you intended to delegate work, use feed_scoop to send a prompt.`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-idle`};Q.info(`Scoop idle timeout`,{jid:e,scoop:t.folder}),this.handleMessage(r).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Failed to send idle notification`,{jid:e,error:n})})},Tp);this.idleTimers.set(e,t)}clearIdleTimer(e){let t=this.idleTimers.get(e);t&&(clearTimeout(t),this.idleTimers.delete(e))}async shutdown(){this.stopMessageLoop();for(let e of this.idleTimers.keys())this.clearIdleTimer(e);this.scheduler?.stop(),this.scheduler=null;for(let e of this.contexts.keys())await this.destroyScoopTab(e);Q.info(`Orchestrator shutdown`)}};n(`heartbeat`);var Dp=n(`tray-follower`);function Op(e){let t=new URL(e);return t.searchParams.set(`json`,`true`),t.toString()}async function kp(e){let t=Op(e.joinUrl),n=await Ip(await(e.fetchImpl??fetch)(t,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:e.controllerId,runtime:e.runtime})}));return Dp.info(`Follower tray attach response`,{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),Ap(n)}function Ap(e){let 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 jp(e){return Fp(await Lp(e,{action:`poll`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function Mp(e){return Fp(await Lp(e,{action:`answer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function Np(e){return Fp(await Lp(e,{action:`ice-candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function Pp(e){return Fp(await Lp(e,{action:`retry`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function Fp(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function Ip(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!Rp(n)){let n=t?t.slice(0,200):`(empty)`;throw Dp.warn(`Tray follower attach returned an invalid response`,{status:e.status,body:n}),Error(`Tray follower attach returned an invalid response (${e.status}): ${n}`)}return n}async function Lp(e,t){let n=Op(e.joinUrl),r=await(e.fetchImpl??fetch)(n,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),i=await r.json().catch(()=>null);if(!zp(i))throw Error(`Tray follower bootstrap returned an invalid response (${r.status})`);return i}function Rp(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.trayId!=`string`||typeof t.controllerId!=`string`||t.role!==`follower`||typeof t.participantCount!=`number`)return!1;let n=t.result;if(!n||typeof n!=`object`)return!1;let r=n;return r.action===`wait`?(r.code===`LEADER_NOT_ELECTED`||r.code===`LEADER_NOT_CONNECTED`)&&typeof r.retryAfterMs==`number`:r.action===`signal`?r.code===`LEADER_CONNECTED`&&Bp(r.bootstrap):r.action===`fail`?(r.code===`INVALID_JOIN_CAPABILITY`||r.code===`TRAY_EXPIRED`)&&typeof r.error==`string`:!1}function zp(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.trayId==`string`&&typeof t.controllerId==`string`&&t.role===`follower`&&typeof t.participantCount==`number`&&Bp(t.bootstrap)&&Array.isArray(t.events)}function Bp(e){if(!e||typeof e!=`object`)return!1;let 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`}var Vp=n(`tray-webrtc`),Hp=`tray-control`,Up=250,Wp=class{peerConnectionFactory;dataChannelLabel;peers=new Map;iceServers;constructor(e){this.options=e,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>qp(this.iceServers)),this.dataChannelLabel=e.dataChannelLabel??Hp}setIceServers(e){this.iceServers=e}async handleControlMessage(e){e.type===`follower.join_requested`?(e.iceServers&&!this.iceServers&&(this.iceServers=e.iceServers),await this.handleJoinRequested(e)):e.type===`bootstrap.answer`?await this.peers.get(e.bootstrapId)?.peer.setRemoteDescription(e.answer):e.type===`bootstrap.ice_candidate`&&await this.peers.get(e.bootstrapId)?.peer.addIceCandidate(e.candidate)}getPeers(){return Array.from(this.peers.values()).map(({state:e})=>({...e}))}getChannel(e){return this.peers.get(e)?.channel??null}stop(){for(let e of this.peers.values())e.peer.close();this.peers.clear()}async handleJoinRequested(e){this.closeControllerPeers(e.controllerId);let t=this.peerConnectionFactory(),n={controllerId:e.controllerId,bootstrapId:e.bootstrapId,attempt:e.attempt,state:`connecting`,connectedAt:null,runtime:e.runtime},r=t.createDataChannel(this.dataChannelLabel);this.peers.set(e.bootstrapId,{state:n,peer:t,channel:r}),t.addEventListener(`icecandidate`,({candidate:t})=>{let n=Yp(t);n&&this.options.sendControlMessage({type:`bootstrap.ice_candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:n})}),t.addEventListener(`connectionstatechange`,()=>{let n=this.peers.get(e.bootstrapId);n&&(n.state.state===`connected`?(t.connectionState===`disconnected`||t.connectionState===`failed`)&&(Vp.warn(`Leader peer connection state changed post-connect`,{bootstrapId:e.bootstrapId,state:t.connectionState}),this.options.onPeerDisconnected?.(e.bootstrapId,`Peer connection ${t.connectionState}`)):t.connectionState===`failed`&&this.failPeer(e,`Leader peer connection failed before the data channel opened`))}),r.addEventListener(`open`,()=>{let t=this.peers.get(e.bootstrapId);!t||t.state.state===`connected`||(t.state.state=`connected`,t.state.connectedAt=new Date().toISOString(),this.options.onPeerConnected?.({...t.state},t.channel))}),r.addEventListener(`close`,()=>{let t=this.peers.get(e.bootstrapId);t&&(t.state.state===`connected`?(Vp.warn(`Leader data channel closed post-connect`,{bootstrapId:e.bootstrapId}),this.options.onPeerDisconnected?.(e.bootstrapId,`Data channel closed`)):this.failPeer(e,`Leader data channel closed before opening`))}),r.addEventListener(`error`,()=>{let t=this.peers.get(e.bootstrapId);t&&(t.state.state===`connected`?(Vp.warn(`Leader data channel error post-connect`,{bootstrapId:e.bootstrapId}),this.options.onPeerDisconnected?.(e.bootstrapId,`Data channel error`)):this.failPeer(e,`Leader data channel failed before opening`))});try{let n=await t.createOffer();await t.setLocalDescription(n),this.options.sendControlMessage({type:`bootstrap.offer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,offer:Jp(t.localDescription??n,`offer`)})}catch(t){this.failPeer(e,t instanceof Error?t.message:String(t))}}closeControllerPeers(e){for(let[t,n]of this.peers.entries())n.state.controllerId===e&&(n.peer.close(),this.peers.delete(t))}failPeer(e,t){let n=this.peers.get(e.bootstrapId);if(n){n.peer.close(),this.peers.delete(e.bootstrapId);try{this.options.sendControlMessage({type:`bootstrap.failed`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,code:`WEBRTC_BOOTSTRAP_FAILED`,message:t,retryable:!0,retryAfterMs:1e3})}catch(e){Vp.warn(`Failed to report tray bootstrap failure`,{error:e instanceof Error?e.message:String(e)})}}}},Gp=class{fetchImpl;peerConnectionFactory;controllerIdFactory;sleep;pollIntervalMs;iceServers;activePeer=null;stopped=!1;constructor(e){this.options=e,this.fetchImpl=e.fetchImpl??fetch,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>qp(this.iceServers)),this.controllerIdFactory=e.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),this.pollIntervalMs=e.pollIntervalMs??Up}async start(){this.stopped=!1;let e=this.controllerIdFactory(),t=Date.now();f({state:`connecting`,joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:t,lastError:null}),Vp.info(`Follower tray join starting`,{joinUrl:this.options.joinUrl});let n=0;for(;;){Xp(this.stopped),n++;let t;try{t=await kp({joinUrl:this.options.joinUrl,controllerId:e,runtime:this.options.runtime,fetchImpl:this.fetchImpl})}catch(e){let t=e instanceof Error?e.message:String(e);throw f({...m(),attachAttempts:n,lastError:t}),e}if(f({...m(),attachAttempts:n,lastAttachCode:t.code}),t.action===`wait`){let e=t.retryAfterMs??1e3;Vp.info(`Follower tray attach waiting`,{attempt:n,code:t.code,retryAfterMs:e}),n%10==0&&Vp.warn(`Follower tray attach still waiting after ${n} attempts`,{attempt:n,code:t.code,retryAfterMs:e}),await this.sleep(e);continue}if(t.action===`fail`||!t.bootstrap){let e=t.error??`Tray follower attach failed (${t.code})`;throw f({state:`error`,joinUrl:this.options.joinUrl,trayId:null,error:e,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:e}),Vp.warn(`Follower tray attach failed`,{error:e}),Error(e)}t.iceServers&&(this.iceServers=t.iceServers);try{let r=await this.completeBootstrap(t.trayId,e,t.bootstrap);return f({state:`connected`,joinUrl:this.options.joinUrl,trayId:r.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:null}),Vp.info(`Follower tray connected`,{trayId:r.trayId,controllerId:e}),r}catch(e){let r=e instanceof Error?e.message:String(e);throw f({state:`error`,joinUrl:this.options.joinUrl,trayId:t.trayId,error:r,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:r}),Vp.warn(`Follower tray bootstrap failed`,{error:r}),e}}}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,f({state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null})}async completeBootstrap(e,t,n){let r=n,i=0;for(this.activePeer=this.createFollowerPeer(t,r.bootstrapId);;){if(Xp(this.stopped),this.activePeer.open&&this.activePeer.channel)return{trayId:e,controllerId:t,bootstrapId:r.bootstrapId,channel:this.activePeer.channel};if(this.activePeer.openError)throw Error(this.activePeer.openError);let n=await jp({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,cursor:i,fetchImpl:this.fetchImpl});r=n.bootstrap,i=r.cursor;try{for(let e of n.events)if(e.type===`bootstrap.offer`){await this.activePeer.peer.setRemoteDescription(e.offer);let n=await this.activePeer.peer.createAnswer();await this.activePeer.peer.setLocalDescription(n),await Mp({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,answer:Jp(this.activePeer.peer.localDescription??n,`answer`),fetchImpl:this.fetchImpl})}else if(e.type===`bootstrap.ice_candidate`)await this.activePeer.peer.addIceCandidate(e.candidate);else if(e.type===`bootstrap.failed`)throw Error(e.failure.message)}catch(e){if(r.failure?.retryable&&r.retriesRemaining>0){r=(await Pp({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,runtime:this.options.runtime,fetchImpl:this.fetchImpl})).bootstrap,i=0,this.activePeer.peer.close(),this.activePeer=this.createFollowerPeer(t,r.bootstrapId);continue}throw e}this.activePeer.open||await this.sleep(this.pollIntervalMs)}}createFollowerPeer(e,t){let n=this.peerConnectionFactory(),r={peer:n,channel:null,open:!1,openError:null};return n.addEventListener(`connectionstatechange`,()=>{r.open&&(n.connectionState===`disconnected`||n.connectionState===`failed`)&&(Vp.warn(`Follower peer connection state changed post-connect`,{bootstrapId:t,state:n.connectionState}),this.options.onDisconnected?.(`Peer connection ${n.connectionState}`))}),n.addEventListener(`datachannel`,({channel:e})=>{r.channel=e,e.addEventListener(`open`,()=>{r.open=!0}),e.addEventListener(`close`,()=>{r.open?(Vp.warn(`Follower data channel closed post-connect`,{bootstrapId:t}),this.options.onDisconnected?.(`Data channel closed`)):r.openError=`Follower data channel closed before opening`}),e.addEventListener(`error`,()=>{r.open?(Vp.warn(`Follower data channel error post-connect`,{bootstrapId:t}),this.options.onDisconnected?.(`Data channel error`)):r.openError=`Follower data channel failed before opening`})}),n.addEventListener(`icecandidate`,({candidate:n})=>{let r=Yp(n);r&&Np({joinUrl:this.options.joinUrl,controllerId:e,bootstrapId:t,candidate:r,fetchImpl:this.fetchImpl}).catch(e=>{Vp.warn(`Failed to send follower ICE candidate`,{error:e instanceof Error?e.message:String(e)})})}),r}};function Kp(e,t){let n=t.baseDelayMs??1e3,r=t.backoffMultiplier??2,i=t.maxDelayMs??3e4,a=t.maxAttempts??10,o=t.sleep??e.sleep??(e=>new Promise(t=>setTimeout(t,e))),s=!1,c=!1,l=null,u={cancel(){s=!0,c=!1,l?.stop(),l=null},get reconnecting(){return c}},d=()=>{let t=new Gp({...e,sleep:o,onDisconnected:e=>{s||(Vp.warn(`Follower disconnected, starting reconnect loop`,{reason:e}),p(e))}});return l=t,{manager:t,connectionPromise:t.start()}},p=async u=>{if(s||c)return;c=!0,l?.stop(),l=null;let p=0,h=n,g=u??`Unknown disconnect`;for(;!s&&p<a&&(p++,t.onReconnecting?.(p),f({...m(),state:`reconnecting`,error:null,reconnectAttempts:p}),Vp.info(`Reconnect attempt`,{attempt:p,delay:h}),await o(h),!s);){let n=null;try{let r=d();n=r.manager;let i=await r.connectionPromise;if(s){n.stop();break}c=!1,f({...m(),state:`connected`,joinUrl:e.joinUrl,trayId:i.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),Vp.info(`Reconnect successful`,{attempt:p,trayId:i.trayId}),t.onConnected(i);return}catch(e){g=e instanceof Error?e.message:String(e),Vp.warn(`Reconnect attempt failed`,{attempt:p,error:g}),n?.stop(),l=null}h=Math.min(h*r,i)}s||(c=!1,f({...m(),state:`error`,error:`Reconnect failed after ${p} attempts: ${g}`,reconnectAttempts:p}),Vp.warn(`Reconnect gave up`,{attempts:p,lastError:g}),t.onGaveUp?.(g))},{connectionPromise:h}=d();return h.then(e=>{s||t.onConnected(e)}).catch(e=>{s||Vp.warn(`Initial follower connection failed`,{error:e instanceof Error?e.message:String(e)})}),u}function qp(e){if(typeof RTCPeerConnection>`u`)throw Error(`RTCPeerConnection is not available in this runtime`);let t=e?.length?{iceServers:e}:void 0;return new RTCPeerConnection(t)}function Jp(e,t){if(!e||e.type!==t||typeof e.sdp!=`string`)throw Error(`Expected a local ${t} description before signaling`);return{type:e.type,sdp:e.sdp}}function Yp(e){if(!e||typeof e!=`object`)return null;let 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 Xp(e){if(e)throw Error(`Tray follower stopped before WebRTC bootstrap completed`)}var Zp=64*1024;async function Qp(e,t){try{switch(t.op){case`readFile`:return await $p(e,t.path,t.encoding);case`writeFile`:return[await em(e,t.path,t.content,t.encoding)];case`stat`:return[await tm(e,t.path)];case`readDir`:return[await nm(e,t.path)];case`mkdir`:return[await rm(e,t.path,t.recursive)];case`rm`:return[await im(e,t.path,t.recursive)];case`exists`:return[await am(e,t.path)];case`walk`:return[await om(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(e){return[cm(e)]}}async function $p(e,t,n){return(n??`utf-8`)===`utf-8`?sm(await e.readFile(t,{encoding:`utf-8`}),`utf-8`):sm(lm(await e.readFile(t,{encoding:`binary`})),`base64`)}async function em(e,t,n,r){if(r===`base64`){let r=um(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:`void`}}}async function tm(e,t){return{ok:!0,data:{type:`stat`,stat:await e.stat(t)}}}async function nm(e,t){return{ok:!0,data:{type:`dirEntries`,entries:await e.readDir(t)}}}async function rm(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function im(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function am(e,t){return{ok:!0,data:{type:`exists`,exists:await e.exists(t)}}}async function om(e,t){let n=[];for await(let r of e.walk(t))n.push(r);return{ok:!0,data:{type:`paths`,paths:n}}}function sm(e,t){if(e.length<=Zp)return[{ok:!0,data:{type:`file`,content:e,encoding:t}}];let n=Math.ceil(e.length/Zp),r=[];for(let i=0;i<n;i++){let a=i*Zp,o=e.slice(a,a+Zp);r.push({ok:!0,data:{type:`file`,content:o,encoding:t},chunkIndex:i,totalChunks:n})}return r}function cm(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 lm(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function um(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var dm=class{runtimes=new Map;dirty=!1;setTargets(e,t){this.runtimes.set(e,t),this.dirty=!0}removeRuntime(e){this.runtimes.delete(e)&&(this.dirty=!0)}getEntries(){this.dirty=!1;let e=[];for(let[t,n]of this.runtimes)for(let r of n)e.push({targetId:`${t}:${r.targetId}`,localTargetId:r.targetId,runtimeId:t,title:r.title,url:r.url,isLocal:!1});return e}hasChanged(){return this.dirty}getRuntimeIds(){return[...this.runtimes.keys()]}},fm=n(`data-channel-keepalive`),pm=class{sendPing;onDead;intervalMs;maxMissed;timer=null;missedPongs=0;awaitingPong=!1;stopped=!1;constructor(e){this.sendPing=e.sendPing,this.onDead=e.onDead,this.intervalMs=e.intervalMs??1e4,this.maxMissed=e.maxMissed??3}start(){this.timer||this.stopped||(this.timer=setInterval(()=>this.tick(),this.intervalMs))}stop(){this.stopped=!0,this.timer&&=(clearInterval(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++,fm.debug(`Missed pong`,{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){fm.warn(`Channel declared dead`,{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}},mm=n(`tray-leader-sync`);function hm(e){return e?e.includes(`standalone`)?`standalone`:e.includes(`extension`)?`extension`:e.includes(`electron`)?`electron`:`unknown`:`unknown`}var gm=class{followers=new Map;registry=new dm;runtimeToBootstrap=new Map;pendingCDPRoutes=new Map;cdpChunkBuffers=new Map;remoteTransports=new Map;pendingTabOpenRoutes=new Map;tabOpenResolvers=new Map;pendingFsRoutes=new Map;fsResolvers=new Map;constructor(e){this.options=e}addFollower(e,t,n){this.removeFollower(e);let r=fe(t),i=r.onMessage(t=>{this.handleFollowerMessage(e,t)}),a=new pm({sendPing:()=>r.send({type:`ping`}),onDead:()=>{mm.warn(`Follower keepalive dead, removing follower`,{bootstrapId:e}),this.removeFollower(e),this.options.onFollowerDead?.(e)}});a.start(),this.followers.set(e,{bootstrapId:e,sync:r,unsubscribe:i,keepalive:a,runtime:n?.runtime,connectedAt:n?.connectedAt,lastActivity:Date.now(),floatType:hm(n?.runtime)}),mm.info(`Follower added to sync`,{bootstrapId:e,followerCount:this.followers.size}),this.sendSnapshotToFollower(e);let o=this.getConnectedEntries();o.length>0&&r.send({type:`targets.registry`,targets:o})}removeFollower(e){let t=this.followers.get(e);if(t){t.keepalive.stop(),t.unsubscribe(),t.sync.close(),this.followers.delete(e);for(let[t,n]of this.runtimeToBootstrap)if(n===e){this.cleanupRemoteTransports(t),this.registry.removeRuntime(t),this.runtimeToBootstrap.delete(t);break}this.registry.hasChanged()&&this.broadcastTargetRegistry(),mm.info(`Follower removed from sync`,{bootstrapId:e,followerCount:this.followers.size})}}broadcastEvent(e){if(this.followers.size===0)return;let t={type:`agent_event`,event:e,scoopJid:this.options.getScoopJid()};for(let e of this.followers.values())e.sync.send(t)}broadcastUserMessage(e,t){if(this.followers.size===0)return;let n={type:`user_message_echo`,text:e,messageId:t,scoopJid:this.options.getScoopJid()};for(let e of this.followers.values())e.sync.send(n)}broadcastStatus(e){if(this.followers.size===0)return;let t={type:`status`,scoopStatus:e};for(let e of this.followers.values())e.sync.send(t)}sendSnapshotToFollower(e){let t=this.followers.get(e);if(!t)return;let n=this.options.getMessages(),r=this.options.getScoopJid();ue(t.sync,n,r),mm.debug(`Snapshot sent to follower`,{bootstrapId:e,messageCount:n.length})}handleFollowerMessage(e,t){switch(t.type){case`user_message`:mm.info(`Follower user message received`,{bootstrapId:e,messageId:t.messageId}),this.options.onFollowerMessage(t.text,t.messageId);break;case`abort`:mm.info(`Follower abort received`,{bootstrapId:e}),this.options.onFollowerAbort();break;case`request_snapshot`:mm.info(`Follower snapshot request received`,{bootstrapId:e}),this.sendSnapshotToFollower(e);break;case`targets.advertise`:mm.info(`Follower targets advertised`,{bootstrapId:e,runtimeId:t.runtimeId,targetCount:t.targets.length});for(let e of[...this.remoteTransports.keys()]){let n=e.substring(0,e.indexOf(`:`));n!==`leader`&&!this.runtimeToBootstrap.has(n)&&n!==t.runtimeId&&(this.remoteTransports.get(e)?.disconnect(),this.remoteTransports.delete(e),mm.debug(`Cleaned up orphaned remote transport on advertise`,{key:e}))}this.runtimeToBootstrap.set(t.runtimeId,e),this.registry.setTargets(t.runtimeId,t.targets),this.broadcastTargetRegistry();break;case`cdp.request`:{let{requestId:n,targetRuntimeId:r,localTargetId:i,method:a,params:o,sessionId:s}=t;r===`leader`?this.executeLocalCDP(n,i,a,o,s,e):this.forwardCDPRequest(n,r,i,a,o,s,e);break}case`cdp.response`:this.handleCDPResponse(t);break;case`cdp.event`:this.handleCDPEvent(e,t.method,t.params,t.sessionId);break;case`tab.open`:{let{requestId:n,targetRuntimeId:r,url:i}=t;r===`leader`?this.executeLocalTabOpen(n,i,e):this.forwardTabOpen(n,r,i,e);break}case`tab.opened`:this.handleTabOpenResponse(t.requestId,t.targetId);break;case`tab.open.error`:this.handleTabOpenError(t.requestId,t.error);break;case`fs.request`:{let{requestId:n,targetRuntimeId:r,request:i}=t;r===`leader`?this.executeLocalFs(n,i,e):this.forwardFsRequest(n,r,i,e);break}case`fs.response`:this.handleFsResponse(t.requestId,t.response);break;case`ping`:{let t=this.followers.get(e);t&&(t.keepalive.receivePing(),t.lastActivity=Date.now(),t.sync.send({type:`pong`}));break}case`pong`:{let t=this.followers.get(e);t&&(t.keepalive.receivePong(),t.lastActivity=Date.now());break}}}setLocalTargets(e){this.registry.setTargets(`leader`,e),this.registry.hasChanged()&&this.broadcastTargetRegistry()}broadcastTargetRegistry(){if(this.followers.size===0)return;let e={type:`targets.registry`,targets:this.getConnectedEntries()};for(let t of this.followers.values())t.sync.send(e)}getTargets(){return this.getConnectedEntries()}getConnectedEntries(){return this.registry.getEntries().filter(e=>{if(e.runtimeId===`leader`)return!0;let t=this.runtimeToBootstrap.get(e.runtimeId);return t?this.followers.has(t):!1})}createRemoteTransport(e,t){let n=new me({sendCDPRequest:(n,r,i,a)=>{let o=this.runtimeToBootstrap.get(e),s=o?this.followers.get(o):void 0;if(!s){this.remoteTransports.get(`${e}:${t}`)?.handleResponse(n,void 0,`Target runtime "${e}" not connected`);return}this.pendingCDPRoutes.set(n,{requesterBootstrapId:`__leader__`,requestId:n}),s.sync.send({type:`cdp.request`,requestId:n,localTargetId:t,method:r,params:i,sessionId:a})}});return this.remoteTransports.set(`${e}:${t}`,n),n}removeRemoteTransport(e,t){let n=`${e}:${t}`,r=this.remoteTransports.get(n);r&&(r.disconnect(),this.remoteTransports.delete(n))}cleanupRemoteTransports(e){let t=`${e}:`;for(let e of[...this.remoteTransports.keys()])e.startsWith(t)&&(this.remoteTransports.get(e)?.disconnect(),this.remoteTransports.delete(e),mm.debug(`Cleaned up stale remote transport`,{key:e}))}getConnectedFollowers(){return[...this.runtimeToBootstrap.entries()].map(([e,t])=>{let n=this.followers.get(t);return{runtimeId:e,runtime:n?.runtime,connectedAt:n?.connectedAt,lastActivity:n?.lastActivity,floatType:n?.floatType}})}getBestFollowerForTeleport(){let e=[];for(let[t,n]of this.runtimeToBootstrap){let r=this.followers.get(n);r&&e.push({runtimeId:t,bootstrapId:n,floatType:r.floatType,lastActivity:r.lastActivity})}if(e.length===0)return null;let t=e.filter(e=>e.floatType===`standalone`),n=t.length>0?t:e;return n.sort((e,t)=>t.lastActivity-e.lastActivity),n[0]}get hasFollowers(){return this.followers.size>0}stop(){for(let e of[...this.followers.keys()])this.removeFollower(e)}async executeLocalCDP(e,t,n,r,i,a){let o=this.followers.get(a);if(!o)return;let s=this.options.browserTransport;if(!s){o.sync.send({type:`cdp.response`,requestId:e,error:`Leader has no browser transport`});return}try{let t=await s.send(n,r,i);ge(o.sync,e,t)}catch(t){o.sync.send({type:`cdp.response`,requestId:e,error:t instanceof Error?t.message:String(t)})}}forwardCDPRequest(e,t,n,r,i,a,o){let s=this.runtimeToBootstrap.get(t),c=s?this.followers.get(s):void 0,l=this.followers.get(o);if(!c){l&&l.sync.send({type:`cdp.response`,requestId:e,error:`Target runtime "${t}" not connected`});return}this.pendingCDPRoutes.set(e,{requesterBootstrapId:o,requestId:e}),c.sync.send({type:`cdp.request`,requestId:e,localTargetId:n,method:r,params:i,sessionId:a})}handleCDPResponse(e){let{requestId:t,result:n,error:r,chunkData:i,chunkIndex:a,totalChunks:o}=e,s=this.pendingCDPRoutes.get(t);if(!s)return;let c=le(this.cdpChunkBuffers,e);if(!c)return;if(this.pendingCDPRoutes.delete(t),s.requesterBootstrapId===`__leader__`){for(let e of this.remoteTransports.values())e.handleResponse(t,c.result,c.error);return}let l=this.followers.get(s.requesterBootstrapId);l&&ge(l.sync,t,c.result,c.error)}handleCDPEvent(e,t,n,r){let i;for(let[t,n]of this.runtimeToBootstrap)if(n===e){i=t;break}if(!i)return;let a=`${i}:`;for(let[e,r]of this.remoteTransports)e.startsWith(a)&&r.handleEvent(t,n)}openRemoteTab(e,t){let n=this.runtimeToBootstrap.get(e),r=n?this.followers.get(n):void 0;if(!r)return Promise.reject(Error(`Target runtime "${e}" not connected`));let i=`tab-open-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((e,n)=>{this.tabOpenResolvers.set(i,{resolve:e,reject:n}),this.pendingTabOpenRoutes.set(i,{requesterBootstrapId:`__leader__`,requestId:i}),r.sync.send({type:`tab.open`,requestId:i,url:t})})}async executeLocalTabOpen(e,t,n){let r=this.followers.get(n);if(!r)return;let i=this.options.browserTransport;if(!i){r.sync.send({type:`tab.open.error`,requestId:e,error:`Leader has no browser transport`});return}try{let n=(await i.send(`Target.createTarget`,{url:t,background:!0})).targetId;r.sync.send({type:`tab.opened`,requestId:e,targetId:`leader:${n}`})}catch(t){r.sync.send({type:`tab.open.error`,requestId:e,error:t instanceof Error?t.message:String(t)})}}forwardTabOpen(e,t,n,r){let i=this.runtimeToBootstrap.get(t),a=i?this.followers.get(i):void 0,o=this.followers.get(r);if(!a){o&&o.sync.send({type:`tab.open.error`,requestId:e,error:`Target runtime "${t}" not connected`});return}this.pendingTabOpenRoutes.set(e,{requesterBootstrapId:r,requestId:e}),a.sync.send({type:`tab.open`,requestId:e,url:n})}handleTabOpenResponse(e,t){let n=this.pendingTabOpenRoutes.get(e);if(!n)return;if(this.pendingTabOpenRoutes.delete(e),n.requesterBootstrapId===`__leader__`){let n=this.tabOpenResolvers.get(e);n&&(this.tabOpenResolvers.delete(e),n.resolve(t));return}let r=this.followers.get(n.requesterBootstrapId);r&&r.sync.send({type:`tab.opened`,requestId:e,targetId:t})}handleTabOpenError(e,t){let n=this.pendingTabOpenRoutes.get(e);if(!n)return;if(this.pendingTabOpenRoutes.delete(e),n.requesterBootstrapId===`__leader__`){let n=this.tabOpenResolvers.get(e);n&&(this.tabOpenResolvers.delete(e),n.reject(Error(t)));return}let r=this.followers.get(n.requesterBootstrapId);r&&r.sync.send({type:`tab.open.error`,requestId:e,error:t})}async executeLocalFs(e,t,n){let r=this.followers.get(n);if(!r)return;let i=this.options.vfs;if(!i){r.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:`Leader has no VFS`}});return}let a=await Qp(i,t);for(let t of a)r.sync.send({type:`fs.response`,requestId:e,response:t})}forwardFsRequest(e,t,n,r){let i=this.runtimeToBootstrap.get(t),a=i?this.followers.get(i):void 0,o=this.followers.get(r);if(!a){o&&o.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:`Target runtime "${t}" not connected`}});return}this.pendingFsRoutes.set(e,{requesterBootstrapId:r,requestId:e,chunks:[],totalChunks:1}),a.sync.send({type:`fs.request`,requestId:e,request:n})}handleFsResponse(e,t){let n=this.pendingFsRoutes.get(e);if(!n){let n=this.fsResolvers.get(e);if(n){n.responses.push(t);let r=t.ok&&t.totalChunks||1;n.responses.length>=r&&(this.fsResolvers.delete(e),n.resolve(n.responses))}return}if(n.requesterBootstrapId===`__leader__`){let n=this.fsResolvers.get(e);if(n){n.responses.push(t);let r=t.ok&&t.totalChunks||1;n.responses.length>=r&&(this.fsResolvers.delete(e),this.pendingFsRoutes.delete(e),n.resolve(n.responses))}return}let r=this.followers.get(n.requesterBootstrapId);r&&r.sync.send({type:`fs.response`,requestId:e,response:t}),n.chunks.push(t),n.totalChunks=t.ok&&t.totalChunks||1,n.chunks.length>=n.totalChunks&&this.pendingFsRoutes.delete(e)}sendFsRequest(e,t){if(e===`leader`){let e=this.options.vfs;return e?Qp(e,t):Promise.resolve([{ok:!1,error:`Leader has no VFS`}])}let n=this.runtimeToBootstrap.get(e),r=n?this.followers.get(n):void 0;if(!r)return Promise.resolve([{ok:!1,error:`Target runtime "${e}" not connected`}]);let i=`fs-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((e,n)=>{this.fsResolvers.set(i,{resolve:e,reject:n,responses:[]}),this.pendingFsRoutes.set(i,{requesterBootstrapId:`__leader__`,requestId:i,chunks:[],totalChunks:1}),r.sync.send({type:`fs.request`,requestId:i,request:t})})}},_m=n(`tray-follower-sync`),vm=class{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;constructor(e,t={}){this.options=t,this.sync=he(e),this.unsubscribe=this.sync.onMessage(e=>{this.handleLeaderMessage(e)}),this.keepalive=new pm({sendPing:()=>this.sync.send({type:`ping`}),onDead:()=>{_m.warn(`Leader keepalive dead, cleaning up`),this.handleDisconnect(`Keepalive timeout — leader not responding`),this.options.onDead?.()}}),this.keepalive.start(),e.addEventListener(`close`,()=>{_m.warn(`Data channel closed`),this.handleDisconnect(`Data channel closed`)}),e.addEventListener(`error`,()=>{_m.warn(`Data channel error`),this.handleDisconnect(`Data channel error`)})}sendMessage(e,t){let n=t??`follower-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.sentMessageIds.add(n),this.sync.send({type:`user_message`,text:e,messageId:n}),_m.info(`Sent user message to leader`,{messageId:n})}onEvent(e){return this.eventListeners.add(e),()=>this.eventListeners.delete(e)}stop(){this.sync.send({type:`abort`}),_m.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(),_m.info(`Follower sync closed`)}advertiseTargets(e,t){this.sync.send({type:`targets.advertise`,targets:e,runtimeId:t})}getTargets(){return this.targetEntries}disconnected=!1;handleDisconnect(e){this.disconnected||(this.disconnected=!0,f({...m(),state:`error`,error:e}),this.emitEvent({type:`error`,error:`Connection to leader lost: ${e}`}),this.keepalive.stop(),this.cleanupCDPEventForwarding(),this.unsubscribe(),this.sync.close(),this.options.onDisconnect?.(e))}handleLeaderMessage(e){switch(e.type){case`snapshot`:_m.info(`Snapshot received from leader`,{messageCount:e.messages.length,scoopJid:e.scoopJid}),this.snapshotChunkBuffer=null,this.latestSnapshot={messages:e.messages,scoopJid:e.scoopJid},this.options.onSnapshot?.(e.messages,e.scoopJid);break;case`snapshot_chunk`:{let t=B(this.snapshotChunkBuffer,e);this.snapshotChunkBuffer=t.buffer,t.result&&(_m.info(`Chunked snapshot reassembled from leader`,{messageCount:t.result.messages.length,scoopJid:t.result.scoopJid}),this.latestSnapshot=t.result,this.options.onSnapshot?.(t.result.messages,t.result.scoopJid));break}case`agent_event`:this.emitEvent(e.event);break;case`user_message_echo`:if(this.sentMessageIds.has(e.messageId)){this.sentMessageIds.delete(e.messageId),_m.debug(`Skipping own message echo`,{messageId:e.messageId});break}_m.info(`User message echo received`,{messageId:e.messageId,scoopJid:e.scoopJid}),this.options.onUserMessage?.(e.text,e.messageId,e.scoopJid);break;case`status`:this.options.onStatus?.(e.scoopStatus);break;case`error`:_m.warn(`Error from leader`,{error:e.error}),this.emitEvent({type:`error`,error:e.error});break;case`targets.registry`:_m.info(`Target registry received from leader`,{targetCount:e.targets.length}),this.targetEntries=e.targets,this.options.onTargetsUpdated?.(this.targetEntries);break;case`cdp.request`:{let{requestId:t,localTargetId:n,method:r,params:i,sessionId:a}=e;this.executeLocalCDP(t,n,r,i,a);break}case`cdp.response`:this.routeCDPResponse(e);break;case`cdp.event`:for(let t of this.remoteTransports.values())t.handleEvent(e.method,e.params);break;case`tab.open`:this.executeLocalTabOpen(e.requestId,e.url);break;case`tab.opened`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.resolve(e.targetId));break}case`tab.open.error`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.reject(Error(e.error)));break}case`fs.request`:this.executeLocalFs(e.requestId,e.request);break;case`fs.response`:this.routeFsResponse(e.requestId,e.response);break;case`ping`:this.keepalive.receivePing(),this.sync.send({type:`pong`});break;case`pong`:this.keepalive.receivePong(),l(Date.now());break}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch(t){_m.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}}createRemoteTransport(e,t){let n=new me({sendCDPRequest:(n,r,i,a)=>{this.sync.send({type:`cdp.request`,requestId:n,targetRuntimeId:e,localTargetId:t,method:r,params:i,sessionId:a})}});return this.remoteTransports.set(`${e}:${t}`,n),n}removeRemoteTransport(e,t){let n=`${e}:${t}`,r=this.remoteTransports.get(n);r&&(r.disconnect(),this.remoteTransports.delete(n))}openRemoteTab(e,t){let n=`tab-open-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((r,i)=>{this.tabOpenResolvers.set(n,{resolve:r,reject:i}),this.sync.send({type:`tab.open`,requestId:n,targetRuntimeId:e,url:t})})}async executeLocalTabOpen(e,t){let n=this.options.browserTransport;if(!n){this.sync.send({type:`tab.open.error`,requestId:e,error:`Follower has no browser transport`});return}try{let r=(await n.send(`Target.createTarget`,{url:t,background:!0})).targetId;this.sync.send({type:`tab.opened`,requestId:e,targetId:r}),this.options.onTargetsChanged?.()}catch(t){this.sync.send({type:`tab.open.error`,requestId:e,error:t instanceof Error?t.message:String(t)})}}async executeLocalCDP(e,t,n,r,i){let a=this.options.browserTransport;if(!a){this.sync.send({type:`cdp.response`,requestId:e,error:`Follower has no browser transport`});return}try{let t=await a.send(n,r,i);if(n===`Target.attachToTarget`&&t.sessionId){let e=t.sessionId;this.remoteCDPSessions.add(e),this.setupCDPEventForwarding(a,e),_m.debug(`Tracking remote CDP session`,{remoteSessionId:e})}n===`Target.detachFromTarget`&&i&&this.remoteCDPSessions.has(i)&&(this.remoteCDPSessions.delete(i),_m.debug(`Removed remote CDP session on detach`,{sessionId:i})),ge(this.sync,e,t)}catch(t){this.sync.send({type:`cdp.response`,requestId:e,error:t instanceof Error?t.message:String(t)})}}setupCDPEventForwarding(e,t){for(let n of[`Page.frameNavigated`,`Page.loadEventFired`,`Page.domContentEventFired`,`Network.responseReceived`,`Network.loadingFinished`,`Network.requestWillBeSent`]){let r=e=>{if(e.sessionId!==t||!this.remoteCDPSessions.has(t))return;let{sessionId:r,...i}=e;this.sync.send({type:`cdp.event`,method:n,params:i,sessionId:t})};e.on(n,r),this.cdpEventCleanups.push(()=>e.off(n,r))}}cleanupCDPEventForwarding(){for(let e of this.cdpEventCleanups)e();this.cdpEventCleanups.length=0,this.remoteCDPSessions.clear()}routeCDPResponse(e){let t=le(this.cdpChunkBuffers,e);if(t)for(let n of this.remoteTransports.values())n.handleResponse(e.requestId,t.result,t.error)}async executeLocalFs(e,t){let n=this.options.vfs;if(!n){this.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:`Follower has no VFS`}});return}let r=await Qp(n,t);for(let t of r)this.sync.send({type:`fs.response`,requestId:e,response:t})}routeFsResponse(e,t){let n=this.fsResolvers.get(e);if(!n)return;n.responses.push(t);let r=t.ok&&t.totalChunks||1;n.responses.length>=r&&(this.fsResolvers.delete(e),n.resolve(n.responses))}sendFsRequest(e,t){let n=`fs-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((r,i)=>{this.fsResolvers.set(n,{resolve:r,reject:i,responses:[]}),this.sync.send({type:`fs.request`,requestId:n,targetRuntimeId:e,request:t})})}};function ym(e,t){if(t)return`extension`;try{return Sm(new URL(e))?`electron-overlay`:`standalone`}catch{return`standalone`}}function bm(e,t){return e===`electron-overlay`||e===`standalone`&&t}function xm(e){try{let t=new URL(e).searchParams.get(`tab`);return t&&Bi(t)?t:Ri}catch{return Ri}}function Sm(e){return e.pathname===`/electron`||e.pathname===`/electron/`||e.searchParams.get(`runtime`)===`electron-overlay`}function Cm(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}/licks-ws`}function wm(e,t){return`${new URL(e).origin}/webhooks/${t}`}function Tm(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function Em(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`slicc-electron-overlay:set-tab`}var Dm=[`/shared/sprinkles`];async function Om(e){let t=new Map;for(let n of Dm)await e.exists(n)&&await km(e,n,t);return await km(e,`/`,t),t}async function km(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.shtml`))continue;let t=Am(r);if(!n.has(t)){let i;try{i=await e.readFile(r,{encoding:`utf-8`})??``}catch{i=``}n.set(t,{name:t,path:r,title:jm(i,t),autoOpen:Mm(i)})}}}function Am(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.shtml`)?t.slice(0,-6):t}function jm(e,t){let n=e.match(/data-sprinkle-title=["']([^"']+)["']/);if(n)return n[1];let r=e.match(/<title>([^<]+)<\/title>/i);return r?r[1].trim():t}function Mm(e){return/data-sprinkle-autoopen\b/.test(e)}var Nm=class{listeners=new Map;lickHandler;fs;closeHandler;constructor(e,t,n){this.fs=e,this.lickHandler=t,this.closeHandler=n}createAPI(e){let t={name:e,lick:t=>{let n=typeof t==`string`?t:t.action,r=typeof t==`string`?void 0:t.data,i={type:`sprinkle`,sprinkleName:e,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:n,data:r}};this.lickHandler(i)},on:(t,n)=>{let r=`${e}:${t}`,i=this.listeners.get(r);i||(i=new Set,this.listeners.set(r,i)),i.add(n)},off:(t,n)=>{let r=`${e}:${t}`;this.listeners.get(r)?.delete(n)},readFile:async e=>await this.fs.readFile(e,{encoding:`utf-8`}),writeFile:async(e,t)=>{await this.fs.writeFile(e,t)},readDir:async e=>(await this.fs.readDir(e)).map(e=>({name:e.name,type:e.type})),exists:async e=>this.fs.exists(e),stat:async e=>{let t=await this.fs.stat(e);return{type:t.type,size:t.size}},mkdir:async e=>{await this.fs.mkdir(e,{recursive:!0})},rm:async e=>{await this.fs.rm(e)},screenshot:async e=>{let n=t._container;if(!n)return``;let r=e?n.querySelector(e):n;if(!r)throw Error(`Element not found: `+(e||`container`));let i=r.getBoundingClientRect(),a=Math.ceil(i.width),o=Math.ceil(i.height);if(a===0||o===0)throw Error(`Element has zero dimensions`);let s=document.createElement(`canvas`),c=window.devicePixelRatio||1;s.width=a*c,s.height=o*c;let l=s.getContext(`2d`);l.scale(c,c);let u=r.cloneNode(!0),d=`<svg xmlns="http://www.w3.org/2000/svg" width="${a}" height="${o}"><foreignObject width="100%" height="100%">${new XMLSerializer().serializeToString(u)}</foreignObject></svg>`;return new Promise((e,t)=>{let n=new Image;n.onload=()=>{l.drawImage(n,0,0),e(s.toDataURL(`image/png`))},n.onerror=()=>t(Error(`Screenshot rendering failed`)),n.src=`data:image/svg+xml;charset=utf-8,`+encodeURIComponent(d)})},setState:t=>{try{localStorage.setItem(`slicc-sprinkle-state:${e}`,JSON.stringify(t))}catch{}},getState:()=>{try{let t=localStorage.getItem(`slicc-sprinkle-state:${e}`);return t?JSON.parse(t):null}catch{return null}},open:e=>{let t=/^https?:|^chrome-extension:/.test(e)?e:Mc(e);window.open(t,`_blank`)},close:()=>this.closeHandler(e)};return t}pushUpdate(e,t){let n=`${e}:update`,r=this.listeners.get(n);if(r)for(let e of r)try{e(t)}catch{}}removeSprinkle(e){for(let t of this.listeners.keys())t.startsWith(`${e}:`)&&this.listeners.delete(t)}},Pm=n(`sprinkle-manager`),Fm=`slicc-open-sprinkles`,Im=class{fs;bridge;callbacks;availableSprinkles=new Map;openSprinkles=new Map;constructor(e,t,n){this.fs=e,this.bridge=new Nm(e,t,e=>this.close(e)),this.callbacks=n}async restoreOpenSprinkles(){try{let e=localStorage.getItem(Fm);if(!e){for(let e of this.availableSprinkles.values())if(e.autoOpen)try{await this.open(e.name)}catch{Pm.warn(`Failed to auto-open sprinkle`,{name:e.name})}return}let t=JSON.parse(e);for(let e of t)try{await this.open(e)}catch{Pm.warn(`Failed to restore sprinkle`,{name:e})}}catch{}}persistOpenSprinkles(){try{localStorage.setItem(Fm,JSON.stringify([...this.openSprinkles.keys()]))}catch{}}async openNewAutoOpenSprinkles(){await this.refresh();for(let e of this.availableSprinkles.values())if(e.autoOpen&&!this.openSprinkles.has(e.name))try{await this.open(e.name),Pm.info(`Auto-opened new sprinkle after install`,{name:e.name})}catch{Pm.warn(`Failed to auto-open new sprinkle`,{name:e.name})}}async refresh(){this.availableSprinkles=await Om(this.fs),Pm.info(`Discovered sprinkles`,{count:this.availableSprinkles.size})}async open(e,t){if(this.openSprinkles.has(e)){Pm.info(`Sprinkle already open`,{name:e});return}let n=this.availableSprinkles.get(e);if(n||=(await this.refresh(),this.availableSprinkles.get(e)),!n)throw Error(`Sprinkle not found: ${e}`);let r=await this.fs.readFile(n.path,{encoding:`utf-8`}),i=document.createElement(`div`);i.className=`sprinkle-panel`,i.style.cssText=`width: 100%; height: 100%; display: flex; flex-direction: column; overflow: hidden;`,i.dataset.sprinkle=e,this.openSprinkles.set(e,{renderer:null,container:i}),this.callbacks.addSprinkle(e,n.title,i,t);let a=new Qr(i,this.bridge.createAPI(e));await a.render(r,e),this.openSprinkles.get(e).renderer=a,this.persistOpenSprinkles(),df(e),Pm.info(`Sprinkle opened`,{name:e,title:n.title})}close(e){let t=this.openSprinkles.get(e);t&&(t.renderer?.dispose(),t.container.remove(),this.bridge.removeSprinkle(e),this.openSprinkles.delete(e),this.callbacks.removeSprinkle(e),this.persistOpenSprinkles(),Pm.info(`Sprinkle closed`,{name:e}))}available(){return Array.from(this.availableSprinkles.values())}opened(){return Array.from(this.openSprinkles.keys())}sendToSprinkle(e,t){let n=this.openSprinkles.get(e);if(!n){Pm.warn(`Cannot send to closed sprinkle`,{name:e});return}this.bridge.pushUpdate(e,t),n.renderer.pushUpdate(t)}};function Lm(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function Rm(e){let t=[],{payload:n}=e;if(n.title&&t.push(`# ${n.title}`),t.push(`A new handoff was accepted from ${Lm(e.sourceUrl)}.`),t.push(`## Instruction`),t.push(n.instruction),n.urls&&n.urls.length>0){t.push(`## URLs`);for(let e of n.urls)t.push(`- ${e}`)}if(n.context&&(t.push(`## Context`),t.push(n.context)),n.acceptanceCriteria&&n.acceptanceCriteria.length>0){t.push(`## Acceptance Criteria`);for(let e of n.acceptanceCriteria)t.push(`- ${e}`)}return n.notes&&(t.push(`## Notes`),t.push(n.notes)),t.join(`
|
|
12685
12685
|
|
|
12686
|
-
`)}function Rm(e,t){return e.receivedAt.localeCompare(t.receivedAt)}var zm=class{onPendingHandoffsChange;pendingByHandoffId=new Map;constructor(e){this.onPendingHandoffsChange=e.onPendingHandoffsChange}injectHandoff(e,t=`local`){let n=`injected-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.pendingByHandoffId.set(n,{handoffId:n,sourceUrl:t,payload:e,receivedAt:new Date().toISOString()}),this.emitChange(),n}clearHandoff(e){let t=this.pendingByHandoffId.get(e)??null;return this.pendingByHandoffId.delete(e),t&&this.emitChange(),{handoff:t,targetIds:[]}}emitChange(){this.onPendingHandoffsChange?.([...this.pendingByHandoffId.values()].sort(Rm))}},$=n(`main`),Bm=`slicc-pending-mount`,Vm=`pendingMount`;async function Hm(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(Bm,1);n.onupgradeneeded=()=>n.result.createObjectStore(`handles`),n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),n=t.transaction(`handles`,`readwrite`);n.objectStore(`handles`).put(e,Vm),await new Promise(e=>n.oncomplete=()=>e()),t.close()}async function Um(e){let t;try{t=await new Promise((e,t)=>{let n=indexedDB.open(Bm,1);n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}catch{return}let n=t.transaction(`handles`,`readwrite`),r=await new Promise(e=>{let t=n.objectStore(`handles`).get(Vm);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)});if(r){n.objectStore(`handles`).delete(Vm),await new Promise(e=>n.oncomplete=()=>e());let t=`/mnt/${r.name}`;await e.mount(t,r),$.info(`Mounted folder from welcome onboarding`,{name:r.name,path:t})}t.close()}function Wm(){let e=document.createElement(`div`);e.className=`skill-drop-overlay`;let t=document.createElement(`div`);t.className=`skill-drop-overlay__card`;let n=document.createElement(`div`);n.className=`skill-drop-overlay__title`,t.appendChild(n);let r=document.createElement(`div`);return r.className=`skill-drop-overlay__desc`,t.appendChild(r),e.appendChild(t),document.body.appendChild(e),{show(t,i){n.textContent=t,r.textContent=i,e.classList.add(`skill-drop-overlay--visible`)},hide(){e.classList.remove(`skill-drop-overlay--visible`)}}}function Gm(){let e=document.createElement(`div`);return e.className=`skill-drop-toast-container`,document.body.appendChild(e),(t,n)=>{let r=document.createElement(`div`);r.className=`skill-drop-toast skill-drop-toast--${n}`,r.textContent=t,e.appendChild(r),requestAnimationFrame(()=>r.classList.add(`skill-drop-toast--visible`)),window.setTimeout(()=>{r.classList.remove(`skill-drop-toast--visible`),window.setTimeout(()=>r.remove(),180)},4200)}}function Km(e,t,n){let r=Wm(),i=0,a=!1,o=()=>{i=0,a||r.hide()};window.addEventListener(`dragenter`,e=>{ca(e.dataTransfer)&&(e.preventDefault(),i+=1,a||r.show(`Drop .skill to install`,`Unpack into /workspace/skills/{name}.`))}),window.addEventListener(`dragover`,e=>{ca(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect=`copy`),a||r.show(`Drop .skill to install`,`Unpack into /workspace/skills/{name}.`))}),window.addEventListener(`dragleave`,()=>{i!==0&&(i=Math.max(0,i-1),i===0&&!a&&r.hide())}),window.addEventListener(`dragend`,o),window.addEventListener(`blur`,o),window.addEventListener(`drop`,async s=>{let c=la(s.dataTransfer);if(!c){o();return}if(s.preventDefault(),i=0,a){r.hide(),t(`Another .skill installation is already in progress.`,`error`);return}a=!0,r.show(`Installing skill…`,c.name);try{let r=await se(e,c);await n(),t(`Installed "${r.skillName}" to ${r.destinationPath} (${r.fileCount} files). Run "skill install ${r.skillName}" to apply it.`,`success`)}catch(e){t(`Failed to install dropped skill: ${e instanceof Error?e.message:String(e)}`,`error`)}finally{a=!1,r.hide()}})}async function qm(e){let{OffscreenClient:t}=await v(async()=>{let{OffscreenClient:e}=await import(`./offscreen-client-B8UaOgaJ.js`);return{OffscreenClient:e}},__vite__mapDeps([21,14])),{VirtualFS:n}=await v(async()=>{let{VirtualFS:e}=await import(`./fs-BQWb1K18.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([19,1])),r=new Gi(e,!0);window.__slicc_debug_tabs=e=>r.setDebugTabs(e),await r.panels.chat.initSession(`session-cone`);let i=null,a=await n.create({dbName:`slicc-fs`});r.panels.fileBrowser.setFs(a),$.info(`File browser wired to shared VFS (local IndexedDB)`);let o=new BroadcastChannel(`preview-vfs`);o.onmessage=e=>{if(e.data?.type!==`preview-vfs-read`)return;let{id:t,path:n,asText:r}=e.data;(async()=>{try{let e=r?`utf-8`:`binary`,i=await a.readFile(n,{encoding:e});o.postMessage({type:`preview-vfs-response`,id:t,content:i})}catch(e){let r=e instanceof Error?e.message:String(e);r.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:n,error:r}),o.postMessage({type:`preview-vfs-response`,id:t,error:r})}})()},Km(a,Gm(),async()=>{await r.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await v(async()=>{let{WasmShell:e}=await import(`./shell-QbXxTSCK.js`);return{WasmShell:e}},[]),{PanelCdpProxy:t,BrowserAPI:n}=await v(async()=>{let{PanelCdpProxy:e,BrowserAPI:t}=await import(`./cdp-Bzco6_uI.js`).then(e=>e.t);return{PanelCdpProxy:e,BrowserAPI:t}},__vite__mapDeps([22,1,4,14])),i=new t;await i.connect();let o=new e({fs:a,browserAPI:new n(i)});await r.panels.terminal.mountShell(o),$.info(`Terminal mounted with shared VFS and BrowserAPI (CDP proxy)`)}catch(e){$.warn(`Failed to mount shell to terminal`,e)}{let{registerSessionCostsProvider:e}=await v(async()=>{let{registerSessionCostsProvider:e}=await import(`./cost-command-BK0NsK_J.js`).then(e=>e.t);return{registerSessionCostsProvider:e}},__vite__mapDeps([23,1]));e(()=>new Promise(e=>{chrome.runtime.sendMessage({source:`panel`,payload:{type:`get-session-costs`}},t=>{if(chrome.runtime.lastError||!t?.ok){e([]);return}e(t.costs??[])})}))}let c,l=new Set,u=e=>{r.setPendingHandoffCount(e.length),r.panels.chat.setPendingHandoffs(e)},d=async e=>{i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid),r.setScoopSwitcherSelected?.(e.jid),r.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=e.isCone?void 0:e.name;await r.panels.chat.switchToContext(t,!e.isCone,n),c.isProcessing(e.jid)&&r.panels.chat.setProcessing(!0)};c=new t({onStatusChange:(e,t)=>{r.panels.scoops.updateScoopStatus(e,t),r.updateScoopSwitcherStatus?.(e,t),i?.jid===e&&(r.setAgentProcessing(t===`processing`),t===`processing`?r.panels.chat.setProcessing(!0):t===`ready`&&r.panels.chat.setProcessing(!1))},onScoopCreated:e=>{r.panels.scoops.refreshScoops(),r.refreshScoopSwitcher?.(),i||(i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid))},onScoopListUpdate:()=>{let e=new Set(c.getScoops().map(e=>e.folder));for(let t of l)e.has(t)||r.panels.chat.deleteSessionById(`session-${t}`);if(l=e,r.panels.scoops.refreshScoops(),r.refreshScoopSwitcher?.(),!i){let e=c.getScoops().find(e=>e.isCone);e&&(i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid))}},onIncomingMessage:(e,t)=>{if(i?.jid===e){let e=t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content;r.panels.chat.addUserMessage(e)}},onPendingHandoffsChange:u,onReady:async()=>{try{$.info(`Offscreen engine ready, scoop count:`,c.getScoops().length),window.localStorage.getItem(`slicc.trayJoinUrl`)&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`refresh-tray-runtime`}}).catch(()=>{});let e=i??c.getScoops().find(e=>e.isCone)??c.getScoops()[0];e&&(i=e,c.selectedScoopJid=e.jid,await d(e))}catch(e){$.error(`Failed to initialize on ready`,{error:e instanceof Error?e.message:String(e)})}}}),c.setLocalFS(a);let f=c.createAgentHandle();r.panels.chat.setAgent(f),r.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=c.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await d(t),r.setActiveTab(`chat`),f.sendMessage(Lm(e),`handoff-${e.handoffId}`),c.acceptPendingHandoff(e.handoffId)},onDismiss:e=>{c.dismissPendingHandoff(e.handoffId)}}),c.requestPendingHandoffs(),r.panels.scoops.setOrchestrator(c),r.panels.memory.setOrchestrator(c),r.setScoopSwitcherOrchestrator?.(c),r.onScoopSelect=d,r.onModelChange=e=>{localStorage.setItem(`selected-model`,e),c.updateModel()},r.onClearChat=async()=>{let e=c.getScoops();for(let t of e){let e=t.isCone?`session-cone`:`session-${t.folder}`;await r.panels.chat.deleteSessionById(e)}c.clearAllMessages()},r.onClearFilesystem=async()=>{c.clearFilesystem()},r.panels.chat.onInlineSprinkleLick=(e,t)=>{c.sendSprinkleLick(`inline`,{action:e,data:t})};let p=new Fm(a,async e=>{if(e.type===`sprinkle`){if(e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&a.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome completion marker`,e)),n===`shortcut-migrate`&&p.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&Um(a).catch(e=>$.warn(`Failed to mount workspace from onboarding`,e))}if(e.sprinkleName===`welcome`&&e.body?.action===`request-mount`){try{let e=window;if(!e.showDirectoryPicker)throw Error(`showDirectoryPicker not supported`);let t=await e.showDirectoryPicker({mode:`readwrite`});await Hm(t),p.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),p.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}return}c.sendSprinkleLick(e.sprinkleName,e.body)}},{addSprinkle:(e,t,n,i)=>r.addSprinkle(e,t,n,i),removeSprinkle:e=>r.removeSprinkle(e)});if(window.__slicc_sprinkleManager=p,window.__slicc_reloadSkills=()=>(chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}}),Promise.resolve()),c.setSprinkleOpHandler(e=>{let{id:t,op:n,name:r,data:i}=e;console.log(`[main-ext] sprinkle-op handler called`,{id:t,op:n,name:r}),(async()=>{try{let e;switch(n){case`list`:await p.refresh(),e=p.available();break;case`opened`:e=p.opened();break;case`refresh`:await p.refresh(),e=p.available().length;break;case`open`:await p.open(r),e=!0;break;case`close`:p.close(r),e=!0;break;case`send`:p.sendToSprinkle(r,i),e=!0;break;case`openNewAutoOpen`:await p.openNewAutoOpenSprinkles(),e=!0;break}console.log(`[main-ext] sprinkle-op response sending`,{id:t,op:n,result:typeof e}),chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,result:e}}).catch(()=>{})}catch(e){chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}})()}),await p.refresh(),r.onSprinkleClose=e=>p.close(e),r.getAvailableSprinkles=()=>{let e=new Set(p.opened());return p.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},r.onOpenSprinkle=(e,t)=>p.open(e,t),r.updateAddButtons(),await p.restoreOpenSprinkles(),!await a.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await a.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await a.exists(`/shared/.welcomed`)&&!s(window.localStorage)&&p.available().some(e=>e.name===`welcome`))try{await p.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}$.info(`SprinkleManager initialized (extension mode)`),c.requestState(),$.info(`Extension UI connected to offscreen agent engine`),cf().catch(()=>{})}async function Jm(){Zi(),aa();let e=document.getElementById(`app`);if(!e)throw Error(`#app element not found`);`serviceWorker`in navigator&&navigator.serviceWorker.register(`/preview-sw.js`,{scope:`/preview/`}).then(()=>$.info(`Preview SW registered`)).catch(e=>$.error(`Preview SW registration failed — preview feature will not work`,e)),k();let t=T(),n=s(window.localStorage);if(!t&&!n){let e=window.location.port===`5710`||window.location.port===`3000`;window.location.port===``&&window.location.pathname.includes(`/join/`)?await C({autoJoinUrl:window.location.origin+window.location.pathname}):!e&&window.location.port!==``?await C({preferTrayJoin:!0}):await C(),t=T()}let i=!t&&s(window.localStorage),a=typeof chrome<`u`&&!!chrome?.runtime?.id,c=vm(window.location.href,a);if(c===`extension`)return qm(e);let l=new Gi(e,c===`electron-overlay`);if(c===`electron-overlay`){let e=bm(window.location.href);l.setActiveTab(e);let t=document.createElement(`style`);t.id=`slicc-electron-overlay-runtime-style`,t.textContent=`
|
|
12686
|
+
`)}function zm(e,t){return e.receivedAt.localeCompare(t.receivedAt)}var Bm=class{onPendingHandoffsChange;pendingByHandoffId=new Map;constructor(e){this.onPendingHandoffsChange=e.onPendingHandoffsChange}injectHandoff(e,t=`local`){let n=`injected-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.pendingByHandoffId.set(n,{handoffId:n,sourceUrl:t,payload:e,receivedAt:new Date().toISOString()}),this.emitChange(),n}clearHandoff(e){let t=this.pendingByHandoffId.get(e)??null;return this.pendingByHandoffId.delete(e),t&&this.emitChange(),{handoff:t,targetIds:[]}}emitChange(){this.onPendingHandoffsChange?.([...this.pendingByHandoffId.values()].sort(zm))}},$=n(`main`),Vm=`slicc-pending-mount`,Hm=`pendingMount`;async function Um(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(Vm,1);n.onupgradeneeded=()=>n.result.createObjectStore(`handles`),n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),n=t.transaction(`handles`,`readwrite`);n.objectStore(`handles`).put(e,Hm),await new Promise(e=>n.oncomplete=()=>e()),t.close()}async function Wm(e){let t;try{t=await new Promise((e,t)=>{let n=indexedDB.open(Vm,1);n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}catch{return}let n=t.transaction(`handles`,`readwrite`),r=await new Promise(e=>{let t=n.objectStore(`handles`).get(Hm);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)});if(r){n.objectStore(`handles`).delete(Hm),await new Promise(e=>n.oncomplete=()=>e());let t=`/mnt/${r.name}`;await e.mount(t,r),$.info(`Mounted folder from welcome onboarding`,{name:r.name,path:t})}t.close()}function Gm(){let e=document.createElement(`div`);e.className=`skill-drop-overlay`;let t=document.createElement(`div`);t.className=`skill-drop-overlay__card`;let n=document.createElement(`div`);n.className=`skill-drop-overlay__title`,t.appendChild(n);let r=document.createElement(`div`);return r.className=`skill-drop-overlay__desc`,t.appendChild(r),e.appendChild(t),document.body.appendChild(e),{show(t,i){n.textContent=t,r.textContent=i,e.classList.add(`skill-drop-overlay--visible`)},hide(){e.classList.remove(`skill-drop-overlay--visible`)}}}function Km(){let e=document.createElement(`div`);return e.className=`skill-drop-toast-container`,document.body.appendChild(e),(t,n)=>{let r=document.createElement(`div`);r.className=`skill-drop-toast skill-drop-toast--${n}`,r.textContent=t,e.appendChild(r),requestAnimationFrame(()=>r.classList.add(`skill-drop-toast--visible`)),window.setTimeout(()=>{r.classList.remove(`skill-drop-toast--visible`),window.setTimeout(()=>r.remove(),180)},4200)}}function qm(e,t,n){let r=Gm(),i=0,a=!1,o=()=>{i=0,a||r.hide()};window.addEventListener(`dragenter`,e=>{ca(e.dataTransfer)&&(e.preventDefault(),i+=1,a||r.show(`Drop .skill to install`,`Unpack into /workspace/skills/{name}.`))}),window.addEventListener(`dragover`,e=>{ca(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect=`copy`),a||r.show(`Drop .skill to install`,`Unpack into /workspace/skills/{name}.`))}),window.addEventListener(`dragleave`,()=>{i!==0&&(i=Math.max(0,i-1),i===0&&!a&&r.hide())}),window.addEventListener(`dragend`,o),window.addEventListener(`blur`,o),window.addEventListener(`drop`,async s=>{let c=la(s.dataTransfer);if(!c){o();return}if(s.preventDefault(),i=0,a){r.hide(),t(`Another .skill installation is already in progress.`,`error`);return}a=!0,r.show(`Installing skill…`,c.name);try{let r=await se(e,c);await n(),t(`Installed "${r.skillName}" to ${r.destinationPath} (${r.fileCount} files). Run "skill install ${r.skillName}" to apply it.`,`success`)}catch(e){t(`Failed to install dropped skill: ${e instanceof Error?e.message:String(e)}`,`error`)}finally{a=!1,r.hide()}})}async function Jm(e){let{OffscreenClient:t}=await v(async()=>{let{OffscreenClient:e}=await import(`./offscreen-client-B8UaOgaJ.js`);return{OffscreenClient:e}},__vite__mapDeps([21,14])),{VirtualFS:n}=await v(async()=>{let{VirtualFS:e}=await import(`./fs-BQWb1K18.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([19,1])),r=new Gi(e,!0);window.__slicc_debug_tabs=e=>r.setDebugTabs(e),await r.panels.chat.initSession(`session-cone`);let i=null,a=await n.create({dbName:`slicc-fs`});r.panels.fileBrowser.setFs(a),$.info(`File browser wired to shared VFS (local IndexedDB)`);let o=new BroadcastChannel(`preview-vfs`);o.onmessage=e=>{if(e.data?.type!==`preview-vfs-read`)return;let{id:t,path:n,asText:r}=e.data;(async()=>{try{let e=r?`utf-8`:`binary`,i=await a.readFile(n,{encoding:e});o.postMessage({type:`preview-vfs-response`,id:t,content:i})}catch(e){let r=e instanceof Error?e.message:String(e);r.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:n,error:r}),o.postMessage({type:`preview-vfs-response`,id:t,error:r})}})()},qm(a,Km(),async()=>{await r.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await v(async()=>{let{WasmShell:e}=await import(`./shell-xFrhOqcd.js`);return{WasmShell:e}},[]),{PanelCdpProxy:t,BrowserAPI:n}=await v(async()=>{let{PanelCdpProxy:e,BrowserAPI:t}=await import(`./cdp-Bzco6_uI.js`).then(e=>e.t);return{PanelCdpProxy:e,BrowserAPI:t}},__vite__mapDeps([22,1,4,14])),i=new t;await i.connect();let o=new e({fs:a,browserAPI:new n(i)});await r.panels.terminal.mountShell(o),$.info(`Terminal mounted with shared VFS and BrowserAPI (CDP proxy)`)}catch(e){$.warn(`Failed to mount shell to terminal`,e)}{let{registerSessionCostsProvider:e}=await v(async()=>{let{registerSessionCostsProvider:e}=await import(`./cost-command-BK0NsK_J.js`).then(e=>e.t);return{registerSessionCostsProvider:e}},__vite__mapDeps([23,1]));e(()=>new Promise(e=>{chrome.runtime.sendMessage({source:`panel`,payload:{type:`get-session-costs`}},t=>{if(chrome.runtime.lastError||!t?.ok){e([]);return}e(t.costs??[])})}))}let c,l=new Set,u=e=>{r.setPendingHandoffCount(e.length),r.panels.chat.setPendingHandoffs(e)},d=async e=>{i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid),r.setScoopSwitcherSelected?.(e.jid),r.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=e.isCone?void 0:e.name;await r.panels.chat.switchToContext(t,!e.isCone,n),c.isProcessing(e.jid)&&r.panels.chat.setProcessing(!0)};c=new t({onStatusChange:(e,t)=>{r.panels.scoops.updateScoopStatus(e,t),r.updateScoopSwitcherStatus?.(e,t),i?.jid===e&&(r.setAgentProcessing(t===`processing`),t===`processing`?r.panels.chat.setProcessing(!0):t===`ready`&&r.panels.chat.setProcessing(!1))},onScoopCreated:e=>{r.panels.scoops.refreshScoops(),r.refreshScoopSwitcher?.(),i||(i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid))},onScoopListUpdate:()=>{let e=new Set(c.getScoops().map(e=>e.folder));for(let t of l)e.has(t)||r.panels.chat.deleteSessionById(`session-${t}`);if(l=e,r.panels.scoops.refreshScoops(),r.refreshScoopSwitcher?.(),!i){let e=c.getScoops().find(e=>e.isCone);e&&(i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid))}},onIncomingMessage:(e,t)=>{if(i?.jid===e){let e=t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content;r.panels.chat.addUserMessage(e)}},onPendingHandoffsChange:u,onReady:async()=>{try{$.info(`Offscreen engine ready, scoop count:`,c.getScoops().length),window.localStorage.getItem(`slicc.trayJoinUrl`)&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`refresh-tray-runtime`}}).catch(()=>{});let e=i??c.getScoops().find(e=>e.isCone)??c.getScoops()[0];e&&(i=e,c.selectedScoopJid=e.jid,await d(e))}catch(e){$.error(`Failed to initialize on ready`,{error:e instanceof Error?e.message:String(e)})}}}),c.setLocalFS(a);let f=c.createAgentHandle();r.panels.chat.setAgent(f),r.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=c.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await d(t),r.setActiveTab(`chat`),f.sendMessage(Rm(e),`handoff-${e.handoffId}`),c.acceptPendingHandoff(e.handoffId)},onDismiss:e=>{c.dismissPendingHandoff(e.handoffId)}}),c.requestPendingHandoffs(),r.panels.scoops.setOrchestrator(c),r.panels.memory.setOrchestrator(c),r.setScoopSwitcherOrchestrator?.(c),r.onScoopSelect=d,r.onModelChange=e=>{localStorage.setItem(`selected-model`,e),c.updateModel()},r.onClearChat=async()=>{let e=c.getScoops();for(let t of e){let e=t.isCone?`session-cone`:`session-${t.folder}`;await r.panels.chat.deleteSessionById(e)}c.clearAllMessages()},r.onClearFilesystem=async()=>{c.clearFilesystem()},r.panels.chat.onInlineSprinkleLick=(e,t)=>{c.sendSprinkleLick(`inline`,{action:e,data:t})};let p=new Im(a,async e=>{if(e.type===`sprinkle`){if(e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&a.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome completion marker`,e)),n===`shortcut-migrate`&&p.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&Wm(a).catch(e=>$.warn(`Failed to mount workspace from onboarding`,e))}if(e.sprinkleName===`welcome`&&e.body?.action===`request-mount`){try{let e=window;if(!e.showDirectoryPicker)throw Error(`showDirectoryPicker not supported`);let t=await e.showDirectoryPicker({mode:`readwrite`});await Um(t),p.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),p.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}return}c.sendSprinkleLick(e.sprinkleName,e.body)}},{addSprinkle:(e,t,n,i)=>r.addSprinkle(e,t,n,i),removeSprinkle:e=>r.removeSprinkle(e)});if(window.__slicc_sprinkleManager=p,window.__slicc_reloadSkills=()=>(chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}}),Promise.resolve()),c.setSprinkleOpHandler(e=>{let{id:t,op:n,name:r,data:i}=e;console.log(`[main-ext] sprinkle-op handler called`,{id:t,op:n,name:r}),(async()=>{try{let e;switch(n){case`list`:await p.refresh(),e=p.available();break;case`opened`:e=p.opened();break;case`refresh`:await p.refresh(),e=p.available().length;break;case`open`:await p.open(r),e=!0;break;case`close`:p.close(r),e=!0;break;case`send`:p.sendToSprinkle(r,i),e=!0;break;case`openNewAutoOpen`:await p.openNewAutoOpenSprinkles(),e=!0;break}console.log(`[main-ext] sprinkle-op response sending`,{id:t,op:n,result:typeof e}),chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,result:e}}).catch(()=>{})}catch(e){chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}})()}),await p.refresh(),r.onSprinkleClose=e=>p.close(e),r.getAvailableSprinkles=()=>{let e=new Set(p.opened());return p.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},r.onOpenSprinkle=(e,t)=>p.open(e,t),r.updateAddButtons(),await p.restoreOpenSprinkles(),!await a.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await a.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await a.exists(`/shared/.welcomed`)&&!s(window.localStorage)&&p.available().some(e=>e.name===`welcome`))try{await p.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}$.info(`SprinkleManager initialized (extension mode)`),c.requestState(),$.info(`Extension UI connected to offscreen agent engine`),cf().catch(()=>{})}async function Ym(){Zi(),aa();let e=document.getElementById(`app`);if(!e)throw Error(`#app element not found`);`serviceWorker`in navigator&&navigator.serviceWorker.register(`/preview-sw.js`,{scope:`/preview/`}).then(()=>$.info(`Preview SW registered`)).catch(e=>$.error(`Preview SW registration failed — preview feature will not work`,e)),ee();let t=E(),n=s(window.localStorage);if(!t&&!n){let e=window.location.port===`5710`||window.location.port===`3000`;window.location.port===``&&window.location.pathname.includes(`/join/`)?await b({autoJoinUrl:window.location.origin+window.location.pathname}):!e&&window.location.port!==``?await b({preferTrayJoin:!0}):await b(),t=E()}let i=!t&&s(window.localStorage),a=typeof chrome<`u`&&!!chrome?.runtime?.id,c=ym(window.location.href,a);if(c===`extension`)return Jm(e);let l=new Gi(e,c===`electron-overlay`);if(c===`electron-overlay`){let e=xm(window.location.href);l.setActiveTab(e);let t=document.createElement(`style`);t.id=`slicc-electron-overlay-runtime-style`,t.textContent=`
|
|
12687
12687
|
#app > .tab-bar { display: none !important; }
|
|
12688
12688
|
#app > .tab-content {
|
|
12689
12689
|
height: calc(100vh - var(--s2-header-height));
|
|
@@ -12691,4 +12691,4 @@ ${t}
|
|
|
12691
12691
|
#app > .tab-content > .tab-content__panel {
|
|
12692
12692
|
height: 100%;
|
|
12693
12693
|
}
|
|
12694
|
-
`,document.head.appendChild(t),window.addEventListener(`message`,e=>{e.source===window.parent&&Tm(e.data)&&l.setActiveTab(bm(`http://localhost/?tab=${e.data.tab??``}`))}),window.addEventListener(`keydown`,e=>{e.code===`Semicolon`&&(e.metaKey||e.ctrlKey)&&!e.shiftKey&&!e.altKey&&!e.repeat&&(e.preventDefault(),e.stopPropagation(),window.parent.postMessage({type:`slicc-electron-overlay:toggle`},`*`))},!0)}let d=Gm();await l.panels.chat.initSession(`session-cone`),$.info(`Session initialized`);let f=new _e,p=e=>{l.setPendingHandoffCount(e.length),l.panels.chat.setPendingHandoffs(e)},m=new Set,g=e=>{$.debug(`Emit to UI`,{type:e.type,listenerCount:m.size});for(let t of m)try{t(e)}catch(t){$.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}},_=null,y=new Map,b=new Map;function x(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function S(e){let t=b.get(e);return t||(t=[],b.set(e,t)),t}function w(e,t){let n=S(e),r=y.get(e);if(r){let e=n.find(e=>e.id===r);if(e)return e}r=`scoop-${e}-${x()}`,y.set(e,r);let i=E.getScoops().find(t=>t.jid===e),a=i?.isCone?`cone`:i?.name??`unknown`,o={id:r,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:a,channel:t};return n.push(o),_?.jid===e&&g({type:`message_start`,messageId:r}),o}let E=new Tp(l.getIframeContainer(),{onResponse:(e,t,n)=>{let r=w(e);n?r.content+=t:(r.content=t,r.isStreaming=!1),_?.jid===e&&(g({type:`content_delta`,messageId:r.id,text:t}),n||g({type:`content_done`,messageId:r.id}))},onResponseDone:e=>{let t=S(e),n=y.get(e);if(n){let r=t.find(e=>e.id===n);r&&(r.isStreaming=!1),_?.jid===e&&g({type:`content_done`,messageId:n}),y.delete(e)}},onSendMessage:(e,t)=>{$.debug(`Send message requested`,{targetJid:e,textLength:t.length});let n=`msg-${x()}`,r={id:n,chatJid:e,senderId:`assistant`,senderName:`sliccy`,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`web`};E.handleMessage(r),S(e).push({id:n,role:`assistant`,content:t,timestamp:Date.now()}),_?.jid===e&&(g({type:`message_start`,messageId:n}),g({type:`content_delta`,messageId:n,text:t}),g({type:`content_done`,messageId:n}))},onStatusChange:(e,t)=>{if(l.panels.scoops.updateScoopStatus(e,t),l.updateScoopSwitcherStatus?.(e,t),_?.jid===e){if(l.setAgentProcessing(t===`processing`),t===`processing`)l.panels.chat.setProcessing(!0);else if(t===`ready`){l.panels.chat.setProcessing(!1);let t=y.get(e)??`done-${e}-${x()}`;y.delete(e),g({type:`turn_end`,messageId:t})}}},onError:(e,t)=>{$.error(`Scoop error`,{scoopJid:e,error:t}),_?.jid===e&&g({type:`error`,error:t})},getBrowserAPI:()=>f,onToolStart:(e,t,n)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let r=w(e);r.toolCalls||=[],r.toolCalls.push({id:x(),name:t,input:n}),_?.jid===e&&g({type:`tool_use_start`,messageId:r.id,toolName:t,toolInput:n})},onToolEnd:(e,t,n,r)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let i=S(e),a=y.get(e);if(a){let e=i.find(e=>e.id===a);if(e?.toolCalls){let i=[...e.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);i&&(i.result=n,i.isError=r)}}_?.jid===e&&a&&g({type:`tool_result`,messageId:a,toolName:t,result:n,isError:r})},onToolUI:(e,t,n,r)=>{let i=y.get(e);i?g({type:`tool_ui`,messageId:i,toolName:t,requestId:n,html:r}):$.warn(`Cannot emit tool_ui - no message ID for scoop`,{scoopJid:e,requestId:n})},onToolUIDone:(e,t)=>{let n=y.get(e);n&&g({type:`tool_ui_done`,messageId:n,requestId:t})},onIncomingMessage:(e,t)=>{let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel};S(e).push(n),_?.jid===e&&(g({type:`message_start`,messageId:t.id}),g({type:`content_delta`,messageId:t.id,text:n.content}),g({type:`content_done`,messageId:t.id}))}});await E.init(),l.panels.scoops.setOrchestrator(E),l.panels.memory.setOrchestrator(E),l.setScoopSwitcherOrchestrator?.(E);let D=E.getSharedFS();if(D){l.panels.fileBrowser.setFs(D),$.info(`File browser wired to shared VFS`);let e=new BroadcastChannel(`preview-vfs`);e.onmessage=t=>{if(t.data?.type!==`preview-vfs-read`)return;let{id:n,path:r,asText:i}=t.data;(async()=>{try{let t=i?`utf-8`:`binary`,a=await D.readFile(r,{encoding:t});e.postMessage({type:`preview-vfs-response`,id:n,content:a})}catch(t){let i=t instanceof Error?t.message:String(t);i.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:r,error:i}),e.postMessage({type:`preview-vfs-response`,id:n,error:i})}})()},Km(D,(e,t)=>{t===`error`?$.warn(`Dropped skill install failed`,{message:e}):$.info(`Dropped skill installed`,{message:e}),d(e,t)},async()=>{await l.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await v(async()=>{let{WasmShell:e}=await import(`./shell-QbXxTSCK.js`);return{WasmShell:e}},[]),t=new e({fs:D,browserAPI:f});await l.panels.terminal.mountShell(t),$.info(`Terminal mounted with shared VFS`);try{let{BshWatchdog:e}=await v(async()=>{let{BshWatchdog:e}=await import(`./bsh-watchdog-2ucB7RyN.js`);return{BshWatchdog:e}},__vite__mapDeps([24,14])),t=new e({browserAPI:f,fs:D});t.start(),window.addEventListener(`beforeunload`,()=>t.stop(),{once:!0}),$.info(`BSH navigation watchdog started`)}catch(e){$.warn(`Failed to start BSH watchdog`,e)}}catch(e){$.warn(`Failed to mount shell to terminal`,e)}}let O=E.getScoops(),ee=O.some(e=>e.isCone);if(i)$.info(`Skipping local cone bootstrap while joining a tray without a configured provider`);else if(!ee)_=await l.panels.scoops.createScoop(`Cone`,!0),$.info(`Created cone`);else{let e=new URLSearchParams(window.location.search).get(`scoop`);if(e){let t=O.find(t=>t.folder===e);t?(_=t,$.info(`Restored scoop from URL`,{folder:e})):_=O.find(e=>e.isCone)??O[0]}else _=O.find(e=>e.isCone)??O[0]}_&&l.panels.memory.setSelectedScoop(_.jid);let A=null,j=null,te={sendMessage(e,t){if(!_){g({type:`error`,error:`No scoop selected`});return}let n={id:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:_.jid,senderId:`user`,senderName:`User`,content:e,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`};S(_.jid).push({id:n.id,role:`user`,content:e,timestamp:Date.now()}),A?.broadcastUserMessage(e,n.id),E.handleMessage(n),E.createScoopTab(_.jid)},onEvent(e){return m.add(e),()=>m.delete(e)},stop(){_&&(E.stopScoop(_.jid),E.clearQueuedMessages(_.jid).catch(e=>{$.error(`Failed to clear queued messages on stop`,{error:e instanceof Error?e.message:String(e)})}))}};l.panels.chat.setAgent(te),l.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=E.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await P(t),l.setActiveTab(`chat`),te.sendMessage(Lm(e),`handoff-${e.handoffId}`);let n=j?.clearHandoff(e.handoffId);n&&await Promise.allSettled(n.targetIds.map(e=>f.closePage(e)))},onDismiss:async e=>{let t=j?.clearHandoff(e.handoffId);t&&await Promise.allSettled(t.targetIds.map(e=>f.closePage(e)))}}),l.panels.chat.setDeleteQueuedMessageCallback(e=>{if(_){E.deleteQueuedMessage(_.jid,e).catch(t=>{$.error(`Failed to delete queued message`,{messageId:e,error:t instanceof Error?t.message:String(t)})});let t=b.get(_.jid);if(t){let n=t.findIndex(t=>t.id===e);n!==-1&&t.splice(n,1)}}}),$.info(`Cone agent handle wired to chat UI`);let{getLickManager:ne}=await v(async()=>{let{getLickManager:e}=await import(`./lick-manager-CMMQIB6z.js`);return{getLickManager:e}},[]),re=ne();await re.init(),E.setLickManager(re);let ie=e=>{let t=e.type===`webhook`,n=e.type===`sprinkle`,r=t?e.webhookName:n?e.sprinkleName:e.cronName,i=t?e.webhookId:n?e.sprinkleName:e.cronId,a=e.type;if($.debug(`Lick event`,{type:e.type,name:r,targetScoop:e.targetScoop}),n&&e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&D?.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome marker`,e)),n===`shortcut-migrate`&&M?.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&D&&Um(D).catch(e=>$.warn(`Failed to mount workspace from onboarding`,e))}if(n&&e.sprinkleName===`welcome`&&e.body?.action===`request-mount`){(async()=>{try{let e=window;if(!e.showDirectoryPicker)throw Error(`showDirectoryPicker not supported`);let t=await e.showDirectoryPicker({mode:`readwrite`});await Hm(t),M?.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),M?.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}})();return}let o=E.getScoops(),s;if(s=n||!e.targetScoop?o.find(e=>e.isCone):o.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`),s){let o=`${a}-${i}-${Date.now()}`,c=`[${t?`Webhook Event`:n?`Sprinkle Event`:`Cron Event`}: ${r}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``,u={id:o,chatJid:s.jid,senderId:a,senderName:`${a}:${r}`,content:c,timestamp:e.timestamp,fromAssistant:!1,channel:a};S(s.jid).push({id:o,role:`user`,content:c,timestamp:Date.now(),source:`lick`,channel:a}),_?.jid===s.jid&&l.panels.chat.addLickMessage(o,c,a),$.info(`Routing lick to scoop`,{type:a,name:r,scoopJid:s.jid}),E.handleMessage(u)}else $.warn(`Lick target scoop not found`,{targetScoop:e.targetScoop})};re.setEventHandler(ie),l.panels.chat.onInlineSprinkleLick=(e,t)=>{ie({type:`sprinkle`,sprinkleName:`inline`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:e,data:t}})};let M=null;if(D){if(M=new Fm(D,ie,{addSprinkle:(e,t,n,r)=>l.addSprinkle(e,t,n,r),removeSprinkle:e=>l.removeSprinkle(e)}),window.__slicc_sprinkleManager=M,window.__slicc_reloadSkills=()=>E.reloadAllSkills(),await M.refresh(),l.onSprinkleClose=e=>M.close(e),l.getAvailableSprinkles=()=>{let e=new Set(M.opened());return M.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},l.onOpenSprinkle=(e,t)=>M.open(e,t),l.updateAddButtons(),!await D.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await D.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await D.exists(`/shared/.welcomed`)&&!i&&M.available().some(e=>e.name===`welcome`))try{await M.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}await M.restoreOpenSprinkles(),$.info(`SprinkleManager initialized`)}let N=()=>{let e=Sm(window.location.href),t=new WebSocket(e);t.onopen=()=>{$.info(`Lick WebSocket connected`)},t.onmessage=async e=>{try{let n=JSON.parse(e.data);if(n.requestId){let e;try{switch(n.type){case`list_webhooks`:e={type:`response`,requestId:n.requestId,data:re.listWebhooks()};break;case`create_webhook`:{let t=await re.createWebhook(n.name||`default`,n.scoop,n.filter),r=qs().session,i=r?.webhookUrl?wm(r.webhookUrl,t.id):Cm(window.location.href,t.id);e={type:`response`,requestId:n.requestId,data:{...t,url:i}};break}case`delete_webhook`:e=await re.deleteWebhook(n.id)?{type:`response`,requestId:n.requestId,data:{ok:!0}}:{type:`response`,requestId:n.requestId,data:{error:`Webhook not found`}};break;case`list_crontasks`:e={type:`response`,requestId:n.requestId,data:re.listCronTasks()};break;case`create_crontask`:{if(!n.name)throw Error(`name is required`);if(!n.cron)throw Error(`cron is required`);let t=await re.createCronTask(n.name,n.cron,n.scoop,n.filter);e={type:`response`,requestId:n.requestId,data:t};break}case`delete_crontask`:e=await re.deleteCronTask(n.id)?{type:`response`,requestId:n.requestId,data:{ok:!0}}:{type:`response`,requestId:n.requestId,data:{error:`Cron task not found`}};break;case`tray_status`:{let t=qs();e={type:`response`,requestId:n.requestId,data:{state:t.state,joinUrl:t.session?.joinUrl??null,workerBaseUrl:t.session?.workerBaseUrl??null,trayId:t.session?.trayId??null}};break}default:e={type:`response`,requestId:n.requestId,error:`Unknown request type: ${n.type}`}}}catch(t){e={type:`response`,requestId:n.requestId,error:t instanceof Error?t.message:String(t)}}t.send(JSON.stringify(e));return}n.type===`webhook_event`&&re.handleWebhookEvent(n.webhookId,n.headers,n.body),n.type===`handoff_event`&&j&&j.injectHandoff(n.payload,n.sourceUrl)}catch(e){$.error(`Failed to process lick message`,{error:e instanceof Error?e.message:String(e)})}},t.onclose=()=>{$.warn(`Lick WebSocket disconnected, reconnecting in 3s...`),setTimeout(N,3e3)},t.onerror=e=>{$.error(`Lick WebSocket error`,{error:String(e)})}};N(),l.onModelChange=e=>{localStorage.setItem(`selected-model`,e),E.updateModel()},l.onClearChat=async()=>{await E.clearAllMessages(),b.clear()},l.onClearFilesystem=async()=>{await E.resetFilesystem()};let P=async e=>{$.info(`Scoop selected`,{jid:e.jid,name:e.name}),_=e,E.createScoopTab(e.jid),l.panels.memory.setSelectedScoop(e.jid),l.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=b.get(e.jid),r=e.isCone?void 0:e.name;if(n&&n.length>0)await l.panels.chat.switchToContext(t,!e.isCone,r),l.panels.chat.loadMessages(n);else if(await l.panels.chat.switchToContext(t,!e.isCone,r),l.panels.chat.getMessages().length===0){let t=await E.getMessagesForScoop(e.jid);for(let n of t){let t=n.channel===`webhook`||n.channel===`cron`,r=n.channel===`delegation`;if(t){let t={id:n.id,role:`user`,content:n.content,timestamp:new Date(n.timestamp).getTime(),source:`lick`,channel:n.channel};S(e.jid).push(t),l.panels.chat.addUserMessage(n.content)}else if(r){let t={id:n.id,role:`user`,content:`**[Instructions from sliccy]**\n\n${n.content}`,timestamp:new Date(n.timestamp).getTime(),source:`delegation`,channel:`delegation`};S(e.jid).push(t),l.panels.chat.addUserMessage(t.content)}else n.fromAssistant?(g({type:`message_start`,messageId:n.id}),g({type:`content_delta`,messageId:n.id,text:n.content}),g({type:`content_done`,messageId:n.id})):l.panels.chat.addUserMessage(n.content)}}e.isCone&&E.isProcessing(e.jid)&&l.panels.chat.setProcessing(!0)};if(l.onScoopSelect=P,_&&(E.createScoopTab(_.jid),await P(_)),j=new zm({onPendingHandoffsChange:p}),c===`standalone`||c===`electron-overlay`){let e=await r(),t=ym(c,e!==null)?o:null,n=await h({locationHref:window.location.href,storage:window.localStorage,envBaseUrl:null,defaultWorkerBaseUrl:t,runtimeConfigFetcher:async()=>e}),i=null,a=null,s=null;zl(()=>A?(e,t)=>A.sendFsRequest(e,t):i?(e,t)=>i.sendFsRequest(e,t):null),Vo(()=>A?()=>A.getBestFollowerForTeleport():null),Ho(()=>A?()=>A.getConnectedFollowers():null);let d=e=>{s&&=(clearInterval(s),null),i?.close();let t=`follower-${e.bootstrapId}`,n=new _m(e.channel,{browserTransport:f.getTransport(),browserAPI:f,onSnapshot:e=>{l.panels.chat.loadMessages(e)},onUserMessage:e=>{l.panels.chat.addUserMessage(e)},onStatus:e=>{l.panels.chat.setProcessing(e===`processing`)},onTargetsChanged:()=>void r()});i=n,f.setTrayTargetProvider(n),l.panels.chat.setAgent(n),n.requestSnapshot();let r=async()=>{try{let e=await f.listPages();n.advertiseTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})),t)}catch{}};s=setInterval(r,5e3),r(),$.info(`Follower sync wired to chat panel`,{trayId:e.trayId})},p=e=>{a?.cancel(),s&&=(clearInterval(s),null),i?.close(),i=null,a=Gp({joinUrl:e,runtime:`slicc-standalone`,fetchImpl:tc()},{onConnected:e=>d(e),onReconnecting:e=>{$.info(`Follower reconnecting`,{attempt:e})},onGaveUp:e=>{$.warn(`Follower reconnect gave up`,{lastError:e})}})};if(window.addEventListener(`slicc:tray-join`,(e=>{p(e.detail.joinUrl)})),window.addEventListener(`beforeunload`,()=>{s&&clearInterval(s),i?.close(),a?.cancel()},{once:!0}),n?.joinUrl)p(n.joinUrl);else if(n?.workerBaseUrl){let e,t,r,i,a=()=>{t=new hm({browserTransport:f.getTransport(),browserAPI:f,getMessages:()=>l.panels.chat.getMessages(),getScoopJid:()=>_?.jid??`cone`,onFollowerMessage:(e,t)=>{l.panels.chat.addUserMessage(e),te.sendMessage(e,t)},onFollowerAbort:()=>{te.stop()}}),A=t,rc(()=>t.getConnectedFollowers()),f.setTrayTargetProvider(t),i&&clearInterval(i);let n=async()=>{try{let e=await f.listPages();t.setLocalTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})))}catch{}};i=setInterval(n,5e3),n(),r=new Up({sendControlMessage:t=>e.sendControlMessage(t),onPeerConnected:(e,n)=>{$.info(`Tray follower data channel opened`,{controllerId:e.controllerId,bootstrapId:e.bootstrapId,attempt:e.attempt,runtime:e.runtime}),t.addFollower(e.bootstrapId,n,{runtime:e.runtime,connectedAt:e.connectedAt??void 0})}})};a(),m.add(e=>{t.broadcastEvent(e)}),e=new Zs({workerBaseUrl:n.workerBaseUrl,runtime:`slicc-standalone`,fetchImpl:tc(),onControlMessage:e=>{if(e.type===`webhook.event`){re.handleWebhookEvent(e.webhookId,e.headers,e.body);return}r.handleControlMessage(e).catch(e=>{$.warn(`Tray leader bootstrap handling failed`,{error:e instanceof Error?e.message:String(e)})})}}),oc(async()=>{t.stop(),r.stop(),e.stop(),await e.clearSession();let n=await e.start(),i=u(window.location.href,n.workerBaseUrl,n.trayId);return i!==window.location.href&&window.history.replaceState(window.history.state,``,i),a(),qs()}),e.start().then(e=>{let t=u(window.location.href,e.workerBaseUrl,e.trayId);t!==window.location.href&&window.history.replaceState(window.history.state,``,t)}).catch(e=>{$.warn(`Leader tray join failed`,{error:e instanceof Error?e.message:String(e)})}),window.addEventListener(`beforeunload`,()=>{clearInterval(i),t.stop(),r.stop(),e.stop()},{once:!0})}}$.info(`Orchestrator initialized — cone+scoops ready`,{scoopCount:E.getScoops().length}),cf().catch(()=>{})}Jm().catch(e=>{$.error(`Fatal error`,e);let t=document.getElementById(`app`);if(t){let n=document.createElement(`div`);n.style.cssText=`padding: 2rem; text-align: center;`;let r=document.createElement(`h1`);r.style.color=`var(--s2-negative, #e34850)`,r.textContent=`Failed to start`;let i=document.createElement(`p`);i.style.color=`var(--s2-content-tertiary, #717171)`,i.textContent=e.message,n.appendChild(r),n.appendChild(i);let a=document.createElement(`button`);for(a.textContent=`Reset all data & reload`,a.style.cssText=`margin-top: 1rem; padding: 0.5rem 1.5rem; background: var(--s2-negative, #e34850); color: #fff; border: none; border-radius: 6px; cursor: pointer; font-size: 14px;`,a.addEventListener(`click`,async()=>{a.disabled=!0,a.textContent=`Resetting…`;let e=await indexedDB.databases();await Promise.all(e.map(e=>e.name?new Promise(t=>{let n=indexedDB.deleteDatabase(e.name);n.onsuccess=()=>t(),n.onerror=()=>t(),n.onblocked=()=>t()}):Promise.resolve())),location.reload()}),n.appendChild(a);t.firstChild;)t.removeChild(t.firstChild);t.appendChild(n)}});export{_a as a,Zr as c,bf as i,Sp as n,Qr as o,wp as r,ei as s,xp as t};
|
|
12694
|
+
`,document.head.appendChild(t),window.addEventListener(`message`,e=>{e.source===window.parent&&Em(e.data)&&l.setActiveTab(xm(`http://localhost/?tab=${e.data.tab??``}`))}),window.addEventListener(`keydown`,e=>{e.code===`Semicolon`&&(e.metaKey||e.ctrlKey)&&!e.shiftKey&&!e.altKey&&!e.repeat&&(e.preventDefault(),e.stopPropagation(),window.parent.postMessage({type:`slicc-electron-overlay:toggle`},`*`))},!0)}let d=Km();await l.panels.chat.initSession(`session-cone`),$.info(`Session initialized`);let f=new _e,p=e=>{l.setPendingHandoffCount(e.length),l.panels.chat.setPendingHandoffs(e)},m=new Set,g=e=>{$.debug(`Emit to UI`,{type:e.type,listenerCount:m.size});for(let t of m)try{t(e)}catch(t){$.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}},_=null,y=new Map,x=new Map;function S(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function C(e){let t=x.get(e);return t||(t=[],x.set(e,t)),t}function w(e,t){let n=C(e),r=y.get(e);if(r){let e=n.find(e=>e.id===r);if(e)return e}r=`scoop-${e}-${S()}`,y.set(e,r);let i=T.getScoops().find(t=>t.jid===e),a=i?.isCone?`cone`:i?.name??`unknown`,o={id:r,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:a,channel:t};return n.push(o),_?.jid===e&&g({type:`message_start`,messageId:r}),o}let T=new Ep(l.getIframeContainer(),{onResponse:(e,t,n)=>{let r=w(e);n?r.content+=t:(r.content=t,r.isStreaming=!1),_?.jid===e&&(g({type:`content_delta`,messageId:r.id,text:t}),n||g({type:`content_done`,messageId:r.id}))},onResponseDone:e=>{let t=C(e),n=y.get(e);if(n){let r=t.find(e=>e.id===n);r&&(r.isStreaming=!1),_?.jid===e&&g({type:`content_done`,messageId:n}),y.delete(e)}},onSendMessage:(e,t)=>{$.debug(`Send message requested`,{targetJid:e,textLength:t.length});let n=`msg-${S()}`,r={id:n,chatJid:e,senderId:`assistant`,senderName:`sliccy`,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`web`};T.handleMessage(r),C(e).push({id:n,role:`assistant`,content:t,timestamp:Date.now()}),_?.jid===e&&(g({type:`message_start`,messageId:n}),g({type:`content_delta`,messageId:n,text:t}),g({type:`content_done`,messageId:n}))},onStatusChange:(e,t)=>{if(l.panels.scoops.updateScoopStatus(e,t),l.updateScoopSwitcherStatus?.(e,t),_?.jid===e){if(l.setAgentProcessing(t===`processing`),t===`processing`)l.panels.chat.setProcessing(!0);else if(t===`ready`){l.panels.chat.setProcessing(!1);let t=y.get(e)??`done-${e}-${S()}`;y.delete(e),g({type:`turn_end`,messageId:t})}}},onError:(e,t)=>{$.error(`Scoop error`,{scoopJid:e,error:t}),_?.jid===e&&g({type:`error`,error:t})},getBrowserAPI:()=>f,onToolStart:(e,t,n)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let r=w(e);r.toolCalls||=[],r.toolCalls.push({id:S(),name:t,input:n}),_?.jid===e&&g({type:`tool_use_start`,messageId:r.id,toolName:t,toolInput:n})},onToolEnd:(e,t,n,r)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let i=C(e),a=y.get(e);if(a){let e=i.find(e=>e.id===a);if(e?.toolCalls){let i=[...e.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);i&&(i.result=n,i.isError=r)}}_?.jid===e&&a&&g({type:`tool_result`,messageId:a,toolName:t,result:n,isError:r})},onToolUI:(e,t,n,r)=>{let i=y.get(e);i?g({type:`tool_ui`,messageId:i,toolName:t,requestId:n,html:r}):$.warn(`Cannot emit tool_ui - no message ID for scoop`,{scoopJid:e,requestId:n})},onToolUIDone:(e,t)=>{let n=y.get(e);n&&g({type:`tool_ui_done`,messageId:n,requestId:t})},onIncomingMessage:(e,t)=>{let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel};C(e).push(n),_?.jid===e&&(g({type:`message_start`,messageId:t.id}),g({type:`content_delta`,messageId:t.id,text:n.content}),g({type:`content_done`,messageId:t.id}))}});await T.init(),l.panels.scoops.setOrchestrator(T),l.panels.memory.setOrchestrator(T),l.setScoopSwitcherOrchestrator?.(T);let D=T.getSharedFS();if(D){l.panels.fileBrowser.setFs(D),$.info(`File browser wired to shared VFS`);let e=new BroadcastChannel(`preview-vfs`);e.onmessage=t=>{if(t.data?.type!==`preview-vfs-read`)return;let{id:n,path:r,asText:i}=t.data;(async()=>{try{let t=i?`utf-8`:`binary`,a=await D.readFile(r,{encoding:t});e.postMessage({type:`preview-vfs-response`,id:n,content:a})}catch(t){let i=t instanceof Error?t.message:String(t);i.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:r,error:i}),e.postMessage({type:`preview-vfs-response`,id:n,error:i})}})()},qm(D,(e,t)=>{t===`error`?$.warn(`Dropped skill install failed`,{message:e}):$.info(`Dropped skill installed`,{message:e}),d(e,t)},async()=>{await l.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await v(async()=>{let{WasmShell:e}=await import(`./shell-xFrhOqcd.js`);return{WasmShell:e}},[]),t=new e({fs:D,browserAPI:f});await l.panels.terminal.mountShell(t),$.info(`Terminal mounted with shared VFS`);try{let{BshWatchdog:e}=await v(async()=>{let{BshWatchdog:e}=await import(`./bsh-watchdog-2ucB7RyN.js`);return{BshWatchdog:e}},__vite__mapDeps([24,14])),t=new e({browserAPI:f,fs:D});t.start(),window.addEventListener(`beforeunload`,()=>t.stop(),{once:!0}),$.info(`BSH navigation watchdog started`)}catch(e){$.warn(`Failed to start BSH watchdog`,e)}}catch(e){$.warn(`Failed to mount shell to terminal`,e)}}let O=T.getScoops(),k=O.some(e=>e.isCone);if(i)$.info(`Skipping local cone bootstrap while joining a tray without a configured provider`);else if(!k)_=await l.panels.scoops.createScoop(`Cone`,!0),$.info(`Created cone`);else{let e=new URLSearchParams(window.location.search).get(`scoop`);if(e){let t=O.find(t=>t.folder===e);t?(_=t,$.info(`Restored scoop from URL`,{folder:e})):_=O.find(e=>e.isCone)??O[0]}else _=O.find(e=>e.isCone)??O[0]}_&&l.panels.memory.setSelectedScoop(_.jid);let A=null,j=null,te={sendMessage(e,t){if(!_){g({type:`error`,error:`No scoop selected`});return}let n={id:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:_.jid,senderId:`user`,senderName:`User`,content:e,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`};C(_.jid).push({id:n.id,role:`user`,content:e,timestamp:Date.now()}),A?.broadcastUserMessage(e,n.id),T.handleMessage(n),T.createScoopTab(_.jid)},onEvent(e){return m.add(e),()=>m.delete(e)},stop(){_&&(T.stopScoop(_.jid),T.clearQueuedMessages(_.jid).catch(e=>{$.error(`Failed to clear queued messages on stop`,{error:e instanceof Error?e.message:String(e)})}))}};l.panels.chat.setAgent(te),l.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=T.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await P(t),l.setActiveTab(`chat`),te.sendMessage(Rm(e),`handoff-${e.handoffId}`);let n=j?.clearHandoff(e.handoffId);n&&await Promise.allSettled(n.targetIds.map(e=>f.closePage(e)))},onDismiss:async e=>{let t=j?.clearHandoff(e.handoffId);t&&await Promise.allSettled(t.targetIds.map(e=>f.closePage(e)))}}),l.panels.chat.setDeleteQueuedMessageCallback(e=>{if(_){T.deleteQueuedMessage(_.jid,e).catch(t=>{$.error(`Failed to delete queued message`,{messageId:e,error:t instanceof Error?t.message:String(t)})});let t=x.get(_.jid);if(t){let n=t.findIndex(t=>t.id===e);n!==-1&&t.splice(n,1)}}}),$.info(`Cone agent handle wired to chat UI`);let{getLickManager:ne}=await v(async()=>{let{getLickManager:e}=await import(`./lick-manager-BYt1_XLw.js`);return{getLickManager:e}},[]),re=ne();await re.init(),T.setLickManager(re);let ie=e=>{let t=e.type===`webhook`,n=e.type===`sprinkle`,r=t?e.webhookName:n?e.sprinkleName:e.cronName,i=t?e.webhookId:n?e.sprinkleName:e.cronId,a=e.type;if($.debug(`Lick event`,{type:e.type,name:r,targetScoop:e.targetScoop}),n&&e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&D?.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome marker`,e)),n===`shortcut-migrate`&&M?.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&D&&Wm(D).catch(e=>$.warn(`Failed to mount workspace from onboarding`,e))}if(n&&e.sprinkleName===`welcome`&&e.body?.action===`request-mount`){(async()=>{try{let e=window;if(!e.showDirectoryPicker)throw Error(`showDirectoryPicker not supported`);let t=await e.showDirectoryPicker({mode:`readwrite`});await Um(t),M?.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),M?.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}})();return}let o=T.getScoops(),s;if(s=n||!e.targetScoop?o.find(e=>e.isCone):o.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`),s){let o=`${a}-${i}-${Date.now()}`,c=`[${t?`Webhook Event`:n?`Sprinkle Event`:`Cron Event`}: ${r}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``,u={id:o,chatJid:s.jid,senderId:a,senderName:`${a}:${r}`,content:c,timestamp:e.timestamp,fromAssistant:!1,channel:a};C(s.jid).push({id:o,role:`user`,content:c,timestamp:Date.now(),source:`lick`,channel:a}),_?.jid===s.jid&&l.panels.chat.addLickMessage(o,c,a),$.info(`Routing lick to scoop`,{type:a,name:r,scoopJid:s.jid}),T.handleMessage(u)}else $.warn(`Lick target scoop not found`,{targetScoop:e.targetScoop})};re.setEventHandler(ie),l.panels.chat.onInlineSprinkleLick=(e,t)=>{ie({type:`sprinkle`,sprinkleName:`inline`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:e,data:t}})};let M=null;if(D){if(M=new Im(D,ie,{addSprinkle:(e,t,n,r)=>l.addSprinkle(e,t,n,r),removeSprinkle:e=>l.removeSprinkle(e)}),window.__slicc_sprinkleManager=M,window.__slicc_reloadSkills=()=>T.reloadAllSkills(),await M.refresh(),l.onSprinkleClose=e=>M.close(e),l.getAvailableSprinkles=()=>{let e=new Set(M.opened());return M.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},l.onOpenSprinkle=(e,t)=>M.open(e,t),l.updateAddButtons(),!await D.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await D.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await D.exists(`/shared/.welcomed`)&&!i&&M.available().some(e=>e.name===`welcome`))try{await M.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}await M.restoreOpenSprinkles(),$.info(`SprinkleManager initialized`)}let N=()=>{let e=Cm(window.location.href),t=new WebSocket(e);t.onopen=()=>{$.info(`Lick WebSocket connected`)},t.onmessage=async e=>{try{let n=JSON.parse(e.data);if(n.requestId){let e;try{switch(n.type){case`list_webhooks`:e={type:`response`,requestId:n.requestId,data:re.listWebhooks()};break;case`create_webhook`:{let t=await re.createWebhook(n.name||`default`,n.scoop,n.filter),r=qs().session,i=r?.webhookUrl?Tm(r.webhookUrl,t.id):wm(window.location.href,t.id);e={type:`response`,requestId:n.requestId,data:{...t,url:i}};break}case`delete_webhook`:e=await re.deleteWebhook(n.id)?{type:`response`,requestId:n.requestId,data:{ok:!0}}:{type:`response`,requestId:n.requestId,data:{error:`Webhook not found`}};break;case`list_crontasks`:e={type:`response`,requestId:n.requestId,data:re.listCronTasks()};break;case`create_crontask`:{if(!n.name)throw Error(`name is required`);if(!n.cron)throw Error(`cron is required`);let t=await re.createCronTask(n.name,n.cron,n.scoop,n.filter);e={type:`response`,requestId:n.requestId,data:t};break}case`delete_crontask`:e=await re.deleteCronTask(n.id)?{type:`response`,requestId:n.requestId,data:{ok:!0}}:{type:`response`,requestId:n.requestId,data:{error:`Cron task not found`}};break;case`tray_status`:{let t=qs();e={type:`response`,requestId:n.requestId,data:{state:t.state,joinUrl:t.session?.joinUrl??null,workerBaseUrl:t.session?.workerBaseUrl??null,trayId:t.session?.trayId??null}};break}default:e={type:`response`,requestId:n.requestId,error:`Unknown request type: ${n.type}`}}}catch(t){e={type:`response`,requestId:n.requestId,error:t instanceof Error?t.message:String(t)}}t.send(JSON.stringify(e));return}n.type===`webhook_event`&&re.handleWebhookEvent(n.webhookId,n.headers,n.body),n.type===`handoff_event`&&j&&j.injectHandoff(n.payload,n.sourceUrl)}catch(e){$.error(`Failed to process lick message`,{error:e instanceof Error?e.message:String(e)})}},t.onclose=()=>{$.warn(`Lick WebSocket disconnected, reconnecting in 3s...`),setTimeout(N,3e3)},t.onerror=e=>{$.error(`Lick WebSocket error`,{error:String(e)})}};N(),l.onModelChange=e=>{localStorage.setItem(`selected-model`,e),T.updateModel()},l.onClearChat=async()=>{await T.clearAllMessages(),x.clear()},l.onClearFilesystem=async()=>{await T.resetFilesystem()};let P=async e=>{$.info(`Scoop selected`,{jid:e.jid,name:e.name}),_=e,T.createScoopTab(e.jid),l.panels.memory.setSelectedScoop(e.jid),l.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=x.get(e.jid),r=e.isCone?void 0:e.name;if(n&&n.length>0)await l.panels.chat.switchToContext(t,!e.isCone,r),l.panels.chat.loadMessages(n);else if(await l.panels.chat.switchToContext(t,!e.isCone,r),l.panels.chat.getMessages().length===0){let t=await T.getMessagesForScoop(e.jid);for(let n of t){let t=n.channel===`webhook`||n.channel===`cron`,r=n.channel===`delegation`;if(t){let t={id:n.id,role:`user`,content:n.content,timestamp:new Date(n.timestamp).getTime(),source:`lick`,channel:n.channel};C(e.jid).push(t),l.panels.chat.addUserMessage(n.content)}else if(r){let t={id:n.id,role:`user`,content:`**[Instructions from sliccy]**\n\n${n.content}`,timestamp:new Date(n.timestamp).getTime(),source:`delegation`,channel:`delegation`};C(e.jid).push(t),l.panels.chat.addUserMessage(t.content)}else n.fromAssistant?(g({type:`message_start`,messageId:n.id}),g({type:`content_delta`,messageId:n.id,text:n.content}),g({type:`content_done`,messageId:n.id})):l.panels.chat.addUserMessage(n.content)}}e.isCone&&T.isProcessing(e.jid)&&l.panels.chat.setProcessing(!0)};if(l.onScoopSelect=P,_&&(T.createScoopTab(_.jid),await P(_)),j=new Bm({onPendingHandoffsChange:p}),c===`standalone`||c===`electron-overlay`){let e=await r(),t=bm(c,e!==null)?o:null,n=await h({locationHref:window.location.href,storage:window.localStorage,envBaseUrl:null,defaultWorkerBaseUrl:t,runtimeConfigFetcher:async()=>e}),i=null,a=null,s=null;zl(()=>A?(e,t)=>A.sendFsRequest(e,t):i?(e,t)=>i.sendFsRequest(e,t):null),Vo(()=>A?()=>A.getBestFollowerForTeleport():null),Ho(()=>A?()=>A.getConnectedFollowers():null);let d=e=>{s&&=(clearInterval(s),null),i?.close();let t=`follower-${e.bootstrapId}`,n=new vm(e.channel,{browserTransport:f.getTransport(),browserAPI:f,onSnapshot:e=>{l.panels.chat.loadMessages(e)},onUserMessage:e=>{l.panels.chat.addUserMessage(e)},onStatus:e=>{l.panels.chat.setProcessing(e===`processing`)},onTargetsChanged:()=>void r()});i=n,f.setTrayTargetProvider(n),l.panels.chat.setAgent(n),n.requestSnapshot();let r=async()=>{try{let e=await f.listPages();n.advertiseTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})),t)}catch{}};s=setInterval(r,5e3),r(),$.info(`Follower sync wired to chat panel`,{trayId:e.trayId})},p=e=>{a?.cancel(),s&&=(clearInterval(s),null),i?.close(),i=null,a=Kp({joinUrl:e,runtime:`slicc-standalone`,fetchImpl:tc()},{onConnected:e=>d(e),onReconnecting:e=>{$.info(`Follower reconnecting`,{attempt:e})},onGaveUp:e=>{$.warn(`Follower reconnect gave up`,{lastError:e})}})};if(window.addEventListener(`slicc:tray-join`,(e=>{p(e.detail.joinUrl)})),window.addEventListener(`beforeunload`,()=>{s&&clearInterval(s),i?.close(),a?.cancel()},{once:!0}),n?.joinUrl)p(n.joinUrl);else if(n?.workerBaseUrl){let e,t,r,i,a=()=>{t=new gm({browserTransport:f.getTransport(),browserAPI:f,getMessages:()=>l.panels.chat.getMessages(),getScoopJid:()=>_?.jid??`cone`,onFollowerMessage:(e,t)=>{l.panels.chat.addUserMessage(e),te.sendMessage(e,t)},onFollowerAbort:()=>{te.stop()}}),A=t,rc(()=>t.getConnectedFollowers()),f.setTrayTargetProvider(t),i&&clearInterval(i);let n=async()=>{try{let e=await f.listPages();t.setLocalTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})))}catch{}};i=setInterval(n,5e3),n(),r=new Wp({sendControlMessage:t=>e.sendControlMessage(t),onPeerConnected:(e,n)=>{$.info(`Tray follower data channel opened`,{controllerId:e.controllerId,bootstrapId:e.bootstrapId,attempt:e.attempt,runtime:e.runtime}),t.addFollower(e.bootstrapId,n,{runtime:e.runtime,connectedAt:e.connectedAt??void 0})}})};a(),m.add(e=>{t.broadcastEvent(e)}),e=new Zs({workerBaseUrl:n.workerBaseUrl,runtime:`slicc-standalone`,fetchImpl:tc(),onControlMessage:e=>{if(e.type===`webhook.event`){re.handleWebhookEvent(e.webhookId,e.headers,e.body);return}r.handleControlMessage(e).catch(e=>{$.warn(`Tray leader bootstrap handling failed`,{error:e instanceof Error?e.message:String(e)})})}}),oc(async()=>{t.stop(),r.stop(),e.stop(),await e.clearSession();let n=await e.start(),i=u(window.location.href,n.workerBaseUrl,n.trayId);return i!==window.location.href&&window.history.replaceState(window.history.state,``,i),a(),qs()}),e.start().then(e=>{let t=u(window.location.href,e.workerBaseUrl,e.trayId);t!==window.location.href&&window.history.replaceState(window.history.state,``,t)}).catch(e=>{$.warn(`Leader tray join failed`,{error:e instanceof Error?e.message:String(e)})}),window.addEventListener(`beforeunload`,()=>{clearInterval(i),t.stop(),r.stop(),e.stop()},{once:!0})}}$.info(`Orchestrator initialized — cone+scoops ready`,{scoopCount:T.getScoops().length}),cf().catch(()=>{})}Ym().catch(e=>{$.error(`Fatal error`,e);let t=document.getElementById(`app`);if(t){let n=document.createElement(`div`);n.style.cssText=`padding: 2rem; text-align: center;`;let r=document.createElement(`h1`);r.style.color=`var(--s2-negative, #e34850)`,r.textContent=`Failed to start`;let i=document.createElement(`p`);i.style.color=`var(--s2-content-tertiary, #717171)`,i.textContent=e.message,n.appendChild(r),n.appendChild(i);let a=document.createElement(`button`);for(a.textContent=`Reset all data & reload`,a.style.cssText=`margin-top: 1rem; padding: 0.5rem 1.5rem; background: var(--s2-negative, #e34850); color: #fff; border: none; border-radius: 6px; cursor: pointer; font-size: 14px;`,a.addEventListener(`click`,async()=>{a.disabled=!0,a.textContent=`Resetting…`;let e=await indexedDB.databases();await Promise.all(e.map(e=>e.name?new Promise(t=>{let n=indexedDB.deleteDatabase(e.name);n.onsuccess=()=>t(),n.onerror=()=>t(),n.onblocked=()=>t()}):Promise.resolve())),location.reload()}),n.appendChild(a);t.firstChild;)t.removeChild(t.firstChild);t.appendChild(n)}});export{_a as a,Zr as c,bf as i,Sp as n,Qr as o,wp as r,ei as s,xp as t};
|