sliccy 1.63.0 → 1.64.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.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/slicc-editor-BZFYYDy6.js","assets/preload-helper-D4M6sveU.js","assets/dist-D3v74401.js","assets/sql-wasm-CLEWdRiw.js","assets/chunk-zsgVPwQN.js","assets/__vite-browser-external-fVHSRdZ9.js","assets/pyodide-BIt8RVoH.js","assets/es-DlWKrNhH.js","assets/pako-djzWUVJp.js","assets/dist-Di8uHUFs.js","assets/provider-settings-C5wu60VY.js","assets/provider-settings-Cd1ewVSe.js","assets/env-api-keys-qwjmVNjS.js","assets/simple-options-DZXt61Q2.js","assets/json-parse-JW3qhabb.js","assets/openai-Cn7eGqwa.js","assets/tray-follower-status-LqS6IS1u.js","assets/logger-B-No_qN_.js","assets/providers-BBlrK0ha.js","assets/skills-DJj8wY51.js","assets/constants-Dqhmtsws.js","assets/skills-qZX0JSOS.js","assets/fs-DcTkzcRE.js","assets/xterm-BmfB5bmM.css","assets/offscreen-client-BMlTH2Sh.js","assets/cdp-Dln7uDXr.js","assets/cost-command-DhUP8Ozj.js","assets/bsh-watchdog-UyxqvRBs.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{t as r}from"./preload-helper-D4M6sveU.js";import{c as i,f as a,h as o,i as s,l as c,m as l,n as u,o as d,p as f,r as p,s as m,t as h,u as g,v as _,y as v}from"./tray-follower-status-LqS6IS1u.js";import{A as y,M as b,N as x,S,T as C,b as w,c as T,g as E,j as D,k as O,n as k,o as ee,r as A,s as j,v as te,w as ne,x as M,y as re}from"./provider-settings-Cd1ewVSe.js";import{f as N,l as P,p as F,s as ie,u as I}from"./constants-Dqhmtsws.js";import{a as ae,i as L,l as oe,n as se,o as ce,r as le,s as R}from"./fs-DcTkzcRE.js";import{d as ue,n as de}from"./skills-qZX0JSOS.js";import{a as fe,c as pe,d as me,i as he,l as ge,n as _e,o as ve,r as ye,s as be,u as xe}from"./cdp-Dln7uDXr.js";import{_ as Se,a as Ce,b as we,c as Te,d as Ee,f as De,g as Oe,h as ke,i as Ae,l as je,m as Me,n as Ne,o as Pe,p as Fe,r as Ie,s as Le,t as Re,u as ze,v as Be,x as Ve,y as He}from"./db-QbwB670D.js";import{a as Ue,i as We,n as Ge,o as z,r as Ke,s as qe}from"./cost-command-DhUP8Ozj.js";import{t as Je}from"./pako-djzWUVJp.js";import{t as Ye}from"./magick-wasm-zICxCuIf.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 Xe(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ze=Xe();function Qe(e){Ze=e}var $e={exec:()=>null};function B(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(tt.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var et=(()=>{try{return!0}catch{return!1}})(),tt={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)}}>`)},nt=/^(?:[ \t]*(?:\n|$))+/,rt=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,it=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,at=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ot=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,st=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,ct=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,lt=B(ct).replace(/bull/g,st).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(),ut=B(ct).replace(/bull/g,st).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(),dt=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ft=/^[^\n]+/,pt=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,mt=B(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,pt).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ht=B(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,st).getRegex(),gt=`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`,_t=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,vt=B(`^ {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`,_t).replace(`tag`,gt).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),yt=B(dt).replace(`hr`,at).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`,gt).getRegex(),bt={blockquote:B(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,yt).getRegex(),code:rt,def:mt,fences:it,heading:ot,hr:at,html:vt,lheading:lt,list:ht,newline:nt,paragraph:yt,table:$e,text:ft},xt=B(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,at).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`,gt).getRegex(),St={...bt,lheading:ut,table:xt,paragraph:B(dt).replace(`hr`,at).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,xt).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`,gt).getRegex()},Ct={...bt,html:B(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,_t).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:$e,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:B(dt).replace(`hr`,at).replace(`heading`,` *#{1,6} *[^
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/slicc-editor-BZFYYDy6.js","assets/preload-helper-D4M6sveU.js","assets/dist-D3v74401.js","assets/sql-wasm-CLEWdRiw.js","assets/chunk-zsgVPwQN.js","assets/__vite-browser-external-fVHSRdZ9.js","assets/pyodide-BIt8RVoH.js","assets/es-DlWKrNhH.js","assets/pako-djzWUVJp.js","assets/dist-Di8uHUFs.js","assets/provider-settings-DDuKtmwj.js","assets/provider-settings-CzImpUb7.js","assets/env-api-keys-qwjmVNjS.js","assets/simple-options-DZXt61Q2.js","assets/json-parse-JW3qhabb.js","assets/openai-Cn7eGqwa.js","assets/tray-follower-status-LqS6IS1u.js","assets/logger-B-No_qN_.js","assets/providers-BjLZ1m3N.js","assets/skills-DJj8wY51.js","assets/constants-Dqhmtsws.js","assets/skills-qZX0JSOS.js","assets/fs-DcTkzcRE.js","assets/xterm-BmfB5bmM.css","assets/offscreen-client-BMlTH2Sh.js","assets/cdp-Dln7uDXr.js","assets/cost-command-DhUP8Ozj.js","assets/bsh-watchdog-UyxqvRBs.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{t as r}from"./preload-helper-D4M6sveU.js";import{c as i,f as a,h as o,i as s,l as c,m as l,n as u,o as d,p as f,r as p,s as m,t as h,u as g,v as _,y as v}from"./tray-follower-status-LqS6IS1u.js";import{A as y,C as b,M as x,O as S,_ as C,b as w,c as T,h as E,j as D,k as ee,n as O,o as k,r as te,s as A,v as ne,w as re,x as ie,y as ae}from"./provider-settings-CzImpUb7.js";import{f as j,l as M,p as N,s as oe,u as P}from"./constants-Dqhmtsws.js";import{a as se,i as F,l as I,n as ce,o as le,r as ue,s as L}from"./fs-DcTkzcRE.js";import{d as de,n as fe}from"./skills-qZX0JSOS.js";import{a as pe,c as me,d as he,i as ge,l as _e,n as ve,o as ye,r as be,s as xe,u as Se}from"./cdp-Dln7uDXr.js";import{_ as Ce,a as we,b as Te,c as Ee,d as De,f as Oe,g as ke,h as Ae,i as je,l as Me,m as Ne,n as Pe,o as Fe,p as Ie,r as Le,s as Re,t as ze,u as Be,v as Ve,x as R,y as He}from"./db-QbwB670D.js";import{a as Ue,i as We,n as Ge,o as z,r as Ke,s as qe}from"./cost-command-DhUP8Ozj.js";import{t as Je}from"./pako-djzWUVJp.js";import{t as Ye}from"./magick-wasm-zICxCuIf.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 Xe(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ze=Xe();function Qe(e){Ze=e}var $e={exec:()=>null};function B(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(tt.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var et=(()=>{try{return!0}catch{return!1}})(),tt={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)}}>`)},nt=/^(?:[ \t]*(?:\n|$))+/,rt=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,it=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,at=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ot=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,st=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,ct=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,lt=B(ct).replace(/bull/g,st).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(),ut=B(ct).replace(/bull/g,st).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(),dt=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ft=/^[^\n]+/,pt=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,mt=B(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,pt).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ht=B(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,st).getRegex(),gt=`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`,_t=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,vt=B(`^ {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`,_t).replace(`tag`,gt).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),yt=B(dt).replace(`hr`,at).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`,gt).getRegex(),bt={blockquote:B(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,yt).getRegex(),code:rt,def:mt,fences:it,heading:ot,hr:at,html:vt,lheading:lt,list:ht,newline:nt,paragraph:yt,table:$e,text:ft},xt=B(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,at).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`,gt).getRegex(),St={...bt,lheading:ut,table:xt,paragraph:B(dt).replace(`hr`,at).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,xt).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`,gt).getRegex()},Ct={...bt,html:B(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,_t).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:$e,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:B(dt).replace(`hr`,at).replace(`heading`,` *#{1,6} *[^
3
3
  ]`).replace(`lheading`,lt).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},wt=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Tt=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Et=/^( {2,}|\\)\n(?!\s*$)/,Dt=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ot=/[\p{P}\p{S}]/u,kt=/[\s\p{P}\p{S}]/u,At=/[^\s\p{P}\p{S}]/u,jt=B(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,kt).getRegex(),Mt=/(?!~)[\p{P}\p{S}]/u,Nt=/(?!~)[\s\p{P}\p{S}]/u,Pt=/(?:[^\s\p{P}\p{S}]|~)/u,Ft=B(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,et?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),It=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Lt=B(It,`u`).replace(/punct/g,Ot).getRegex(),Rt=B(It,`u`).replace(/punct/g,Mt).getRegex(),zt=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,Bt=B(zt,`gu`).replace(/notPunctSpace/g,At).replace(/punctSpace/g,kt).replace(/punct/g,Ot).getRegex(),Vt=B(zt,`gu`).replace(/notPunctSpace/g,Pt).replace(/punctSpace/g,Nt).replace(/punct/g,Mt).getRegex(),Ht=B(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,At).replace(/punctSpace/g,kt).replace(/punct/g,Ot).getRegex(),Ut=B(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,Ot).getRegex(),Wt=B(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,At).replace(/punctSpace/g,kt).replace(/punct/g,Ot).getRegex(),Gt=B(/\\(punct)/,`gu`).replace(/punct/g,Ot).getRegex(),Kt=B(/^<(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(),qt=B(_t).replace(`(?:-->|$)`,`-->`).getRegex(),Jt=B(`^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`,qt).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Yt=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Xt=B(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,Yt).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Zt=B(/^!?\[(label)\]\[(ref)\]/).replace(`label`,Yt).replace(`ref`,pt).getRegex(),Qt=B(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,pt).getRegex(),$t=B(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,Zt).replace(`nolink`,Qt).getRegex(),en=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,tn={_backpedal:$e,anyPunctuation:Gt,autolink:Kt,blockSkip:Ft,br:Et,code:Tt,del:$e,delLDelim:$e,delRDelim:$e,emStrongLDelim:Lt,emStrongRDelimAst:Bt,emStrongRDelimUnd:Ht,escape:wt,link:Xt,nolink:Qt,punctuation:jt,reflink:Zt,reflinkSearch:$t,tag:Jt,text:Dt,url:$e},nn={...tn,link:B(/^!?\[(label)\]\((.*?)\)/).replace(`label`,Yt).getRegex(),reflink:B(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,Yt).getRegex()},rn={...tn,emStrongRDelimAst:Vt,emStrongLDelim:Rt,delLDelim:Ut,delRDelim:Wt,url:B(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,en).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:B(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,en).getRegex()},an={...rn,br:B(Et).replace(`{2,}`,`*`).getRegex(),text:B(rn.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},on={normal:bt,gfm:St,pedantic:Ct},sn={normal:tn,gfm:rn,breaks:an,pedantic:nn},cn={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},ln=e=>cn[e];function un(e,t){if(t){if(tt.escapeTest.test(e))return e.replace(tt.escapeReplace,ln)}else if(tt.escapeTestNoEncode.test(e))return e.replace(tt.escapeReplaceNoEncode,ln);return e}function dn(e){try{e=encodeURI(e).replace(tt.percentDecode,`%`)}catch{return null}return e}function fn(e,t){let n=e.replace(tt.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(tt.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(tt.slashPipe,`|`);return n}function pn(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 mn(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 hn(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 gn(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 _n(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 vn(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>${un(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=dn(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+un(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=dn(e);if(i===null)return un(n);e=i;let a=`<img src="${e}" alt="${un(n)}"`;return t&&(a+=` title="${un(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:un(e.text)}},Sn=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}},Cn=class e{options;renderer;textRenderer;constructor(e){this.options=e||Ze,this.options.renderer=this.options.renderer||new xn,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Sn}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}},wn=class{options;block;constructor(e){this.options=e||Ze}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?bn.lex:bn.lexInline}provideParser(e=this.block){return e?Cn.parse:Cn.parseInline}},Tn=class{defaults=Xe();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Cn;Renderer=xn;TextRenderer=Sn;Lexer=bn;Tokenizer=yn;Hooks=wn;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 xn(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 yn(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 wn;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];wn.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&wn.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 bn.lex(e,t??this.defaults)}parser(e,t){return Cn.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?bn.lex:bn.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?Cn.parse:Cn.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?bn.lex:bn.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?Cn.parse:Cn.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>`+un(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}},En=new Tn;function V(e,t){return En.parse(e,t)}V.options=V.setOptions=function(e){return En.setOptions(e),V.defaults=En.defaults,Qe(V.defaults),V},V.getDefaults=Xe,V.defaults=Ze,V.use=function(...e){return En.use(...e),V.defaults=En.defaults,Qe(V.defaults),V},V.walkTokens=function(e,t){return En.walkTokens(e,t)},V.parseInline=En.parseInline,V.Parser=Cn,V.parser=Cn.parse,V.Renderer=xn,V.TextRenderer=Sn,V.Lexer=bn,V.lexer=bn.lex,V.Tokenizer=yn,V.Hooks=wn,V.parse=V,V.options,V.setOptions,V.use,V.walkTokens,V.parseInline,Cn.parse,bn.lex;var{entries:Dn,setPrototypeOf:On,isFrozen:kn,getPrototypeOf:An,getOwnPropertyDescriptor:jn}=Object,{freeze:Mn,seal:Nn,create:Pn}=Object,{apply:Fn,construct:In}=typeof Reflect<`u`&&Reflect;Mn||=function(e){return e},Nn||=function(e){return e},Fn||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},In||=function(e){return new e(...[...arguments].slice(1))};var Ln=Zn(Array.prototype.forEach),Rn=Zn(Array.prototype.lastIndexOf),zn=Zn(Array.prototype.pop),Bn=Zn(Array.prototype.push),Vn=Zn(Array.prototype.splice),Hn=Zn(String.prototype.toLowerCase),Un=Zn(String.prototype.toString),Wn=Zn(String.prototype.match),Gn=Zn(String.prototype.replace),Kn=Zn(String.prototype.indexOf),qn=Zn(String.prototype.trim),Jn=Zn(Object.prototype.hasOwnProperty),Yn=Zn(RegExp.prototype.test),Xn=Qn(TypeError);function Zn(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return Fn(e,t,n)}}function Qn(e){return function(){return In(e,[...arguments])}}function H(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Hn;On&&On(e,null);let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(kn(t)||(t[r]=e),i=e)}e[i]=!0}return e}function $n(e){for(let t=0;t<e.length;t++)Jn(e,t)||(e[t]=null);return e}function er(e){let t=Pn(null);for(let[n,r]of Dn(e))Jn(e,n)&&(Array.isArray(r)?t[n]=$n(r):r&&typeof r==`object`&&r.constructor===Object?t[n]=er(r):t[n]=r);return t}function tr(e,t){for(;e!==null;){let n=jn(e,t);if(n){if(n.get)return Zn(n.get);if(typeof n.value==`function`)return Zn(n.value)}e=An(e)}function n(){return null}return n}var nr=Mn(`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(`.`)),rr=Mn(`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(`.`)),ir=Mn([`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`]),ar=Mn([`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`]),or=Mn(`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(`.`)),sr=Mn([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),cr=Mn([`#text`]),lr=Mn(`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(`.`)),ur=Mn(`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(`.`)),dr=Mn(`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(`.`)),fr=Mn([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),pr=Nn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),mr=Nn(/<%[\w\W]*|[\w\W]*%>/gm),hr=Nn(/\$\{[\w\W]*/gm),gr=Nn(/^data-[\-\w.\u00B7-\uFFFF]+$/),_r=Nn(/^aria-[\-\w]+$/),vr=Nn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),yr=Nn(/^(?:\w+script|data):/i),br=Nn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),xr=Nn(/^html$/i),Sr=Nn(/^[a-z][.\w]*(-[.\w]+)+$/i),Cr=Object.freeze({__proto__:null,ARIA_ATTR:_r,ATTR_WHITESPACE:br,CUSTOM_ELEMENT:Sr,DATA_ATTR:gr,DOCTYPE_NAME:xr,ERB_EXPR:mr,IS_ALLOWED_URI:vr,IS_SCRIPT_OR_DATA:yr,MUSTACHE_EXPR:pr,TMPLIT_EXPR:hr}),wr={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Tr=function(){return typeof window>`u`?null:window},Er=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}},Dr=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Or(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Tr(),t=e=>Or(e);if(t.version=`3.3.3`,t.removed=[],!e||!e.document||e.document.nodeType!==wr.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=tr(m,`cloneNode`),g=tr(m,`remove`),_=tr(m,`nextSibling`),v=tr(m,`childNodes`),y=tr(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=Dr();t.isSupported=typeof Dn==`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:M}=Cr,{IS_ALLOWED_URI:re}=Cr,N=null,P=H({},[...nr,...rr,...ir,...or,...cr]),F=null,ie=H({},[...lr,...ur,...dr,...fr]),I=Object.seal(Pn(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}})),ae=null,L=null,oe=Object.seal(Pn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),se=!0,ce=!0,le=!1,R=!0,ue=!1,de=!0,fe=!1,pe=!1,me=!1,he=!1,ge=!1,_e=!1,ve=!0,ye=!1,be=!0,xe=!1,Se={},Ce=null,we=H({},[`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`]),Te=null,Ee=H({},[`audio`,`video`,`img`,`source`,`image`,`track`]),De=null,Oe=H({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),ke=`http://www.w3.org/1998/Math/MathML`,Ae=`http://www.w3.org/2000/svg`,je=`http://www.w3.org/1999/xhtml`,Me=je,Ne=!1,Pe=null,Fe=H({},[ke,Ae,je],Un),Ie=H({},[`mi`,`mo`,`mn`,`ms`,`mtext`]),Le=H({},[`annotation-xml`]),Re=H({},[`title`,`style`,`font`,`a`,`script`]),ze=null,Be=[`application/xhtml+xml`,`text/html`],Ve=null,He=null,Ue=n.createElement(`form`),We=function(e){return e instanceof RegExp||e instanceof Function},Ge=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(He&&He===e)){if((!e||typeof e!=`object`)&&(e={}),e=er(e),ze=Be.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,Ve=ze===`application/xhtml+xml`?Un:Hn,N=Jn(e,`ALLOWED_TAGS`)?H({},e.ALLOWED_TAGS,Ve):P,F=Jn(e,`ALLOWED_ATTR`)?H({},e.ALLOWED_ATTR,Ve):ie,Pe=Jn(e,`ALLOWED_NAMESPACES`)?H({},e.ALLOWED_NAMESPACES,Un):Fe,De=Jn(e,`ADD_URI_SAFE_ATTR`)?H(er(Oe),e.ADD_URI_SAFE_ATTR,Ve):Oe,Te=Jn(e,`ADD_DATA_URI_TAGS`)?H(er(Ee),e.ADD_DATA_URI_TAGS,Ve):Ee,Ce=Jn(e,`FORBID_CONTENTS`)?H({},e.FORBID_CONTENTS,Ve):we,ae=Jn(e,`FORBID_TAGS`)?H({},e.FORBID_TAGS,Ve):er({}),L=Jn(e,`FORBID_ATTR`)?H({},e.FORBID_ATTR,Ve):er({}),Se=Jn(e,`USE_PROFILES`)?e.USE_PROFILES:!1,se=e.ALLOW_ARIA_ATTR!==!1,ce=e.ALLOW_DATA_ATTR!==!1,le=e.ALLOW_UNKNOWN_PROTOCOLS||!1,R=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ue=e.SAFE_FOR_TEMPLATES||!1,de=e.SAFE_FOR_XML!==!1,fe=e.WHOLE_DOCUMENT||!1,he=e.RETURN_DOM||!1,ge=e.RETURN_DOM_FRAGMENT||!1,_e=e.RETURN_TRUSTED_TYPE||!1,me=e.FORCE_BODY||!1,ve=e.SANITIZE_DOM!==!1,ye=e.SANITIZE_NAMED_PROPS||!1,be=e.KEEP_CONTENT!==!1,xe=e.IN_PLACE||!1,re=e.ALLOWED_URI_REGEXP||vr,Me=e.NAMESPACE||je,Ie=e.MATHML_TEXT_INTEGRATION_POINTS||Ie,Le=e.HTML_INTEGRATION_POINTS||Le,I=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&We(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(I.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&We(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(I.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements==`boolean`&&(I.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ue&&(ce=!1),ge&&(he=!0),Se&&(N=H({},cr),F=Pn(null),Se.html===!0&&(H(N,nr),H(F,lr)),Se.svg===!0&&(H(N,rr),H(F,ur),H(F,fr)),Se.svgFilters===!0&&(H(N,ir),H(F,ur),H(F,fr)),Se.mathMl===!0&&(H(N,or),H(F,dr),H(F,fr))),Jn(e,`ADD_TAGS`)||(oe.tagCheck=null),Jn(e,`ADD_ATTR`)||(oe.attributeCheck=null),e.ADD_TAGS&&(typeof e.ADD_TAGS==`function`?oe.tagCheck=e.ADD_TAGS:(N===P&&(N=er(N)),H(N,e.ADD_TAGS,Ve))),e.ADD_ATTR&&(typeof e.ADD_ATTR==`function`?oe.attributeCheck=e.ADD_ATTR:(F===ie&&(F=er(F)),H(F,e.ADD_ATTR,Ve))),e.ADD_URI_SAFE_ATTR&&H(De,e.ADD_URI_SAFE_ATTR,Ve),e.FORBID_CONTENTS&&(Ce===we&&(Ce=er(Ce)),H(Ce,e.FORBID_CONTENTS,Ve)),e.ADD_FORBID_CONTENTS&&(Ce===we&&(Ce=er(Ce)),H(Ce,e.ADD_FORBID_CONTENTS,Ve)),be&&(N[`#text`]=!0),fe&&H(N,[`html`,`head`,`body`]),N.table&&(H(N,[`tbody`]),delete ae.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw Xn(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw Xn(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);b=e.TRUSTED_TYPES_POLICY,x=b.createHTML(``)}else b===void 0&&(b=Er(p,i)),b!==null&&typeof x==`string`&&(x=b.createHTML(``));Mn&&Mn(e),He=e}},z=H({},[...rr,...ir,...ar]),Ke=H({},[...or,...sr]),qe=function(e){let t=y(e);(!t||!t.tagName)&&(t={namespaceURI:Me,tagName:`template`});let n=Hn(e.tagName),r=Hn(t.tagName);return Pe[e.namespaceURI]?e.namespaceURI===Ae?t.namespaceURI===je?n===`svg`:t.namespaceURI===ke?n===`svg`&&(r===`annotation-xml`||Ie[r]):!!z[n]:e.namespaceURI===ke?t.namespaceURI===je?n===`math`:t.namespaceURI===Ae?n===`math`&&Le[r]:!!Ke[n]:e.namespaceURI===je?t.namespaceURI===Ae&&!Le[r]||t.namespaceURI===ke&&!Ie[r]?!1:!Ke[n]&&(Re[n]||!z[n]):!!(ze===`application/xhtml+xml`&&Pe[e.namespaceURI]):!1},Je=function(e){Bn(t.removed,{element:e});try{y(e).removeChild(e)}catch{g(e)}},Ye=function(e,n){try{Bn(t.removed,{attribute:n.getAttributeNode(e),from:n})}catch{Bn(t.removed,{attribute:null,from:n})}if(n.removeAttribute(e),e===`is`)if(he||ge)try{Je(n)}catch{}else try{n.setAttribute(e,``)}catch{}},Xe=function(e){let t=null,r=null;if(me)e=`<remove></remove>`+e;else{let t=Wn(e,/^[\r\n\t ]+/);r=t&&t[0]}ze===`application/xhtml+xml`&&Me===je&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=b?b.createHTML(e):e;if(Me===je)try{t=new f().parseFromString(i,ze)}catch{}if(!t||!t.documentElement){t=S.createDocument(Me,`template`,null);try{t.documentElement.innerHTML=Ne?x:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),Me===je?T.call(t,fe?`html`:`body`)[0]:fe?t.documentElement:a},Ze=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)},Qe=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`)},$e=function(e){return typeof s==`function`&&e instanceof s};function B(e,n,r){Ln(e,e=>{e.call(t,n,r,He)})}let et=function(e){let n=null;if(B(D.beforeSanitizeElements,e,null),Qe(e))return Je(e),!0;let r=Ve(e.nodeName);if(B(D.uponSanitizeElement,e,{tagName:r,allowedTags:N}),de&&e.hasChildNodes()&&!$e(e.firstElementChild)&&Yn(/<[/\w!]/g,e.innerHTML)&&Yn(/<[/\w!]/g,e.textContent)||e.nodeType===wr.progressingInstruction||de&&e.nodeType===wr.comment&&Yn(/<[/\w]/g,e.data))return Je(e),!0;if(!(oe.tagCheck instanceof Function&&oe.tagCheck(r))&&(!N[r]||ae[r])){if(!ae[r]&&nt(r)&&(I.tagNameCheck instanceof RegExp&&Yn(I.tagNameCheck,r)||I.tagNameCheck instanceof Function&&I.tagNameCheck(r)))return!1;if(be&&!Ce[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 Je(e),!0}return e instanceof c&&!qe(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&Yn(/<\/no(script|embed|frames)/i,e.innerHTML)?(Je(e),!0):(ue&&e.nodeType===wr.text&&(n=e.textContent,Ln([O,k,ee],e=>{n=Gn(n,e,` `)}),e.textContent!==n&&(Bn(t.removed,{element:e.cloneNode()}),e.textContent=n)),B(D.afterSanitizeElements,e,null),!1)},tt=function(e,t,r){if(L[t]||ve&&(t===`id`||t===`name`)&&(r in n||r in Ue))return!1;if(!(ce&&!L[t]&&Yn(A,t))&&!(se&&Yn(j,t))&&!(oe.attributeCheck instanceof Function&&oe.attributeCheck(t,e))){if(!F[t]||L[t]){if(!(nt(e)&&(I.tagNameCheck instanceof RegExp&&Yn(I.tagNameCheck,e)||I.tagNameCheck instanceof Function&&I.tagNameCheck(e))&&(I.attributeNameCheck instanceof RegExp&&Yn(I.attributeNameCheck,t)||I.attributeNameCheck instanceof Function&&I.attributeNameCheck(t,e))||t===`is`&&I.allowCustomizedBuiltInElements&&(I.tagNameCheck instanceof RegExp&&Yn(I.tagNameCheck,r)||I.tagNameCheck instanceof Function&&I.tagNameCheck(r))))return!1}else if(!De[t]&&!Yn(re,Gn(r,ne,``))&&!((t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&Kn(r,`data:`)===0&&Te[e])&&!(le&&!Yn(te,Gn(r,ne,``)))&&r)return!1}return!0},nt=function(e){return e!==`annotation-xml`&&Wn(e,M)},rt=function(e){B(D.beforeSanitizeAttributes,e,null);let{attributes:n}=e;if(!n||Qe(e))return;let r={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:F,forceKeepAttr:void 0},i=n.length;for(;i--;){let{name:a,namespaceURI:o,value:s}=n[i],c=Ve(a),l=s,u=a===`value`?l:qn(l);if(r.attrName=c,r.attrValue=u,r.keepAttr=!0,r.forceKeepAttr=void 0,B(D.uponSanitizeAttribute,e,r),u=r.attrValue,ye&&(c===`id`||c===`name`)&&(Ye(a,e),u=`user-content-`+u),de&&Yn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,u)){Ye(a,e);continue}if(c===`attributename`&&Wn(u,`href`)){Ye(a,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){Ye(a,e);continue}if(!R&&Yn(/\/>/i,u)){Ye(a,e);continue}ue&&Ln([O,k,ee],e=>{u=Gn(u,e,` `)});let d=Ve(e.nodeName);if(!tt(d,c,u)){Ye(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),Qe(e)?Je(e):zn(t.removed)}catch{Ye(a,e)}}B(D.afterSanitizeAttributes,e,null)},it=function e(t){let n=null,r=Ze(t);for(B(D.beforeSanitizeShadowDOM,t,null);n=r.nextNode();)B(D.uponSanitizeShadowNode,n,null),et(n),rt(n),n.content instanceof a&&e(n.content);B(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(Ne=!e,Ne&&(e=`<!-->`),typeof e!=`string`&&!$e(e))if(typeof e.toString==`function`){if(e=e.toString(),typeof e!=`string`)throw Xn(`dirty is not a string, aborting`)}else throw Xn(`toString is not a function`);if(!t.isSupported)return e;if(pe||Ge(n),t.removed=[],typeof e==`string`&&(xe=!1),xe){if(e.nodeName){let t=Ve(e.nodeName);if(!N[t]||ae[t])throw Xn(`root node is forbidden and cannot be sanitized in-place`)}}else if(e instanceof s)i=Xe(`<!---->`),o=i.ownerDocument.importNode(e,!0),o.nodeType===wr.element&&o.nodeName===`BODY`||o.nodeName===`HTML`?i=o:i.appendChild(o);else{if(!he&&!ue&&!fe&&e.indexOf(`<`)===-1)return b&&_e?b.createHTML(e):e;if(i=Xe(e),!i)return he?null:_e?x:``}i&&me&&Je(i.firstChild);let u=Ze(xe?e:i);for(;c=u.nextNode();)et(c),rt(c),c.content instanceof a&&it(c.content);if(xe)return e;if(he){if(ge)for(l=w.call(i.ownerDocument);i.firstChild;)l.appendChild(i.firstChild);else l=i;return(F.shadowroot||F.shadowrootmode)&&(l=E.call(r,l,!0)),l}let d=fe?i.outerHTML:i.innerHTML;return fe&&N[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&Yn(xr,i.ownerDocument.doctype.name)&&(d=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
66
- `+d),ue&&Ln([O,k,ee],e=>{d=Gn(d,e,` `)}),b&&_e?b.createHTML(d):d},t.setConfig=function(){Ge(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),pe=!0},t.clearConfig=function(){He=null,pe=!1},t.isValidAttribute=function(e,t,n){return He||Ge({}),tt(Ve(e),Ve(t),n)},t.addHook=function(e,t){typeof t==`function`&&Bn(D[e],t)},t.removeHook=function(e,t){if(t!==void 0){let n=Rn(D[e],t);return n===-1?void 0:Vn(D[e],n,1)[0]}return zn(D[e])},t.removeHooks=function(e){D[e]=[]},t.removeAllHooks=function(){D=Dr()},t}var kr=Or(),Ar=kr.sanitize.bind(kr);kr.isSupported,kr.addHook.bind(kr),kr.removeHook.bind(kr),kr.removeHooks.bind(kr),kr.removeAllHooks.bind(kr),kr.setConfig.bind(kr),kr.clearConfig.bind(kr),kr.isValidAttribute.bind(kr),kr.version,kr.removed;function jr(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#x27;`)}function Mr(e,t){let n=jr(e);return t===`shtml`||([`js`,`javascript`,`ts`,`typescript`,`jsx`,`tsx`].includes(t)?n=Pr(n):t===`json`?n=Fr(n):[`bash`,`sh`,`shell`,`zsh`].includes(t)&&(n=Ir(n))),n}function Nr(e){let t=[];return{html:e.replace(/<span class="tok-(?:comment|string)">[\s\S]*?<\/span>/g,e=>{let n=String.fromCharCode(57344+t.length);return t.push(e),n}),restore:e=>e.replace(/[\ue000-\uf8ff]/g,e=>t[e.charCodeAt(0)-57344]??e)}}function Pr(e){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(/(&quot;[^&]*?&quot;|&#x27;[^&]*?&#x27;|`[^`]*?`)/g,`<span class="tok-string">$1</span>`);let t=Nr(e);return e=t.html,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>`),t.restore(e)}function Fr(e){return e=e.replace(/(&quot;[^&]*?&quot;)\s*:/g,`<span class="tok-keyword">$1</span>:`),e=e.replace(/:\s*(&quot;[^&]*?&quot;)/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 Ir(e){return e=e.replace(/(#[^\n]*)/g,`<span class="tok-comment">$1</span>`),e=e.replace(/(&quot;[^&]*?&quot;|&#x27;[^&]*?&#x27;)/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 Lr=new Tn({gfm:!0,breaks:!0,async:!1,renderer:{code({text:e,lang:t}){let n=t??``,r=Mr(e,n);return`<pre><code${n?` class="language-${jr(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="${jr(t)}"`:``,a=this.parser.parseInline(n);return`<a href="${jr(r)}"${i} target="_blank" rel="noopener noreferrer">${a}</a>`}}}),Rr={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 zr(e){return Ar(e,Rr)}function Br(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 Vr=/<p><strong>Error:<\/strong>\s*([\s\S]*?)<\/p>/g;function Hr(e){return Br(zr(Lr.parse(e)))}function Ur(e){return e.replace(Vr,(e,t)=>`<div class="msg__error" role="alert"><div class="msg__error-label">Error</div><div class="msg__error-body">${t}</div></div>`)}function Wr(e){return Hr(e)}function Gr(e){return Ur(Hr(e))}function Kr(e){if(typeof e==`string`)return jr(e);try{return jr(JSON.stringify(e,null,2))}catch{return jr(String(e))}}var qr=`browser-coding-agent`,Jr=1,Yr=`sessions`;function Xr(){return new Promise((e,t)=>{let n=indexedDB.open(qr,Jr);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Yr)||e.createObjectStore(Yr,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var Zr=class{db=null;async init(){this.db=await Xr()}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(Yr,`readwrite`);i.objectStore(Yr).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(Yr,`readonly`).objectStore(Yr).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(Yr,`readonly`).objectStore(Yr).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(Yr,`readwrite`);i.objectStore(Yr).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)}},Qr={"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 $r(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function ei(){return typeof window>`u`?null:window.SpeechRecognition||window.webkitSpeechRecognition||null}var ti=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=ei();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($r())this.startExtensionPopup();else{this.shouldBeListening=!1;let t=e?.name,n=Qr[`not-allowed`];t===`NotFoundError`?n=Qr[`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=Qr[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=Qr[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=ei();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}},ni={autoSend:`voice-auto-send`,lang:`voice-lang`};function ri(){return localStorage.getItem(ni.lang)||`en-US`}var ii=typeof chrome<`u`&&!!chrome?.runtime?.id;function ai(e){let t=e.trimStart().toLowerCase();return t.startsWith(`<!doctype`)||t.startsWith(`<html`)}var oi=class e{container;bridge;scripts=[];iframe=null;static cachedLucideScript=null;static lucideScriptPromise=null;messageHandler=null;constructor(e,t){this.container=e,this.bridge=t}async render(e,t){this.dispose(),ii?await this.renderInSandbox(e,t,ai(e)):ai(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-stop-cone`)this.bridge.stopCone();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(),c=``,l=``;if(n){let t=[];e.includes(`<slicc-editor`)&&t.push(fetch(chrome.runtime.getURL(`slicc-editor.js`)).then(e=>e.ok?e.text():``).then(e=>{c=e}).catch(()=>{})),e.includes(`<slicc-diff`)&&t.push(fetch(chrome.runtime.getURL(`slicc-diff.js`)).then(e=>e.ok?e.text():``).then(e=>{l=e}).catch(()=>{})),await Promise.all(t)}let u=await this.getLucideScript();r.contentWindow.postMessage({type:`sprinkle-render`,content:e,name:t,themeCSS:i,savedState:s,savedStorage:a,fullDoc:n,editorScript:c,diffScript:l,lucideScript:u},`*`)}pushUpdate(e){this.iframe?.contentWindow&&this.iframe.contentWindow.postMessage({type:`sprinkle-update`,data:e},`*`)}collectThemeCSS(){return ci()}generateBridgeScript(){return`(function() {
65
+ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+un(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}},En=new Tn;function V(e,t){return En.parse(e,t)}V.options=V.setOptions=function(e){return En.setOptions(e),V.defaults=En.defaults,Qe(V.defaults),V},V.getDefaults=Xe,V.defaults=Ze,V.use=function(...e){return En.use(...e),V.defaults=En.defaults,Qe(V.defaults),V},V.walkTokens=function(e,t){return En.walkTokens(e,t)},V.parseInline=En.parseInline,V.Parser=Cn,V.parser=Cn.parse,V.Renderer=xn,V.TextRenderer=Sn,V.Lexer=bn,V.lexer=bn.lex,V.Tokenizer=yn,V.Hooks=wn,V.parse=V,V.options,V.setOptions,V.use,V.walkTokens,V.parseInline,Cn.parse,bn.lex;var{entries:Dn,setPrototypeOf:On,isFrozen:kn,getPrototypeOf:An,getOwnPropertyDescriptor:jn}=Object,{freeze:Mn,seal:Nn,create:Pn}=Object,{apply:Fn,construct:In}=typeof Reflect<`u`&&Reflect;Mn||=function(e){return e},Nn||=function(e){return e},Fn||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},In||=function(e){return new e(...[...arguments].slice(1))};var Ln=Zn(Array.prototype.forEach),Rn=Zn(Array.prototype.lastIndexOf),zn=Zn(Array.prototype.pop),Bn=Zn(Array.prototype.push),Vn=Zn(Array.prototype.splice),Hn=Zn(String.prototype.toLowerCase),Un=Zn(String.prototype.toString),Wn=Zn(String.prototype.match),Gn=Zn(String.prototype.replace),Kn=Zn(String.prototype.indexOf),qn=Zn(String.prototype.trim),Jn=Zn(Object.prototype.hasOwnProperty),Yn=Zn(RegExp.prototype.test),Xn=Qn(TypeError);function Zn(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return Fn(e,t,n)}}function Qn(e){return function(){return In(e,[...arguments])}}function H(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Hn;On&&On(e,null);let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(kn(t)||(t[r]=e),i=e)}e[i]=!0}return e}function $n(e){for(let t=0;t<e.length;t++)Jn(e,t)||(e[t]=null);return e}function er(e){let t=Pn(null);for(let[n,r]of Dn(e))Jn(e,n)&&(Array.isArray(r)?t[n]=$n(r):r&&typeof r==`object`&&r.constructor===Object?t[n]=er(r):t[n]=r);return t}function tr(e,t){for(;e!==null;){let n=jn(e,t);if(n){if(n.get)return Zn(n.get);if(typeof n.value==`function`)return Zn(n.value)}e=An(e)}function n(){return null}return n}var nr=Mn(`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(`.`)),rr=Mn(`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(`.`)),ir=Mn([`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`]),ar=Mn([`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`]),or=Mn(`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(`.`)),sr=Mn([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),cr=Mn([`#text`]),lr=Mn(`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(`.`)),ur=Mn(`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(`.`)),dr=Mn(`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(`.`)),fr=Mn([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),pr=Nn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),mr=Nn(/<%[\w\W]*|[\w\W]*%>/gm),hr=Nn(/\$\{[\w\W]*/gm),gr=Nn(/^data-[\-\w.\u00B7-\uFFFF]+$/),_r=Nn(/^aria-[\-\w]+$/),vr=Nn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),yr=Nn(/^(?:\w+script|data):/i),br=Nn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),xr=Nn(/^html$/i),Sr=Nn(/^[a-z][.\w]*(-[.\w]+)+$/i),Cr=Object.freeze({__proto__:null,ARIA_ATTR:_r,ATTR_WHITESPACE:br,CUSTOM_ELEMENT:Sr,DATA_ATTR:gr,DOCTYPE_NAME:xr,ERB_EXPR:mr,IS_ALLOWED_URI:vr,IS_SCRIPT_OR_DATA:yr,MUSTACHE_EXPR:pr,TMPLIT_EXPR:hr}),wr={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Tr=function(){return typeof window>`u`?null:window},Er=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}},Dr=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Or(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Tr(),t=e=>Or(e);if(t.version=`3.3.3`,t.removed=[],!e||!e.document||e.document.nodeType!==wr.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=tr(m,`cloneNode`),g=tr(m,`remove`),_=tr(m,`nextSibling`),v=tr(m,`childNodes`),y=tr(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=Dr();t.isSupported=typeof Dn==`function`&&typeof y==`function`&&S&&S.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:ee,ERB_EXPR:O,TMPLIT_EXPR:k,DATA_ATTR:te,ARIA_ATTR:A,IS_SCRIPT_OR_DATA:ne,ATTR_WHITESPACE:re,CUSTOM_ELEMENT:ie}=Cr,{IS_ALLOWED_URI:ae}=Cr,j=null,M=H({},[...nr,...rr,...ir,...or,...cr]),N=null,oe=H({},[...lr,...ur,...dr,...fr]),P=Object.seal(Pn(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}})),se=null,F=null,I=Object.seal(Pn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),ce=!0,le=!0,ue=!1,L=!0,de=!1,fe=!0,pe=!1,me=!1,he=!1,ge=!1,_e=!1,ve=!1,ye=!0,be=!1,xe=!0,Se=!1,Ce={},we=null,Te=H({},[`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`]),Ee=null,De=H({},[`audio`,`video`,`img`,`source`,`image`,`track`]),Oe=null,ke=H({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),Ae=`http://www.w3.org/1998/Math/MathML`,je=`http://www.w3.org/2000/svg`,Me=`http://www.w3.org/1999/xhtml`,Ne=Me,Pe=!1,Fe=null,Ie=H({},[Ae,je,Me],Un),Le=H({},[`mi`,`mo`,`mn`,`ms`,`mtext`]),Re=H({},[`annotation-xml`]),ze=H({},[`title`,`style`,`font`,`a`,`script`]),Be=null,Ve=[`application/xhtml+xml`,`text/html`],R=null,He=null,Ue=n.createElement(`form`),We=function(e){return e instanceof RegExp||e instanceof Function},Ge=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(He&&He===e)){if((!e||typeof e!=`object`)&&(e={}),e=er(e),Be=Ve.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,R=Be===`application/xhtml+xml`?Un:Hn,j=Jn(e,`ALLOWED_TAGS`)?H({},e.ALLOWED_TAGS,R):M,N=Jn(e,`ALLOWED_ATTR`)?H({},e.ALLOWED_ATTR,R):oe,Fe=Jn(e,`ALLOWED_NAMESPACES`)?H({},e.ALLOWED_NAMESPACES,Un):Ie,Oe=Jn(e,`ADD_URI_SAFE_ATTR`)?H(er(ke),e.ADD_URI_SAFE_ATTR,R):ke,Ee=Jn(e,`ADD_DATA_URI_TAGS`)?H(er(De),e.ADD_DATA_URI_TAGS,R):De,we=Jn(e,`FORBID_CONTENTS`)?H({},e.FORBID_CONTENTS,R):Te,se=Jn(e,`FORBID_TAGS`)?H({},e.FORBID_TAGS,R):er({}),F=Jn(e,`FORBID_ATTR`)?H({},e.FORBID_ATTR,R):er({}),Ce=Jn(e,`USE_PROFILES`)?e.USE_PROFILES:!1,ce=e.ALLOW_ARIA_ATTR!==!1,le=e.ALLOW_DATA_ATTR!==!1,ue=e.ALLOW_UNKNOWN_PROTOCOLS||!1,L=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,de=e.SAFE_FOR_TEMPLATES||!1,fe=e.SAFE_FOR_XML!==!1,pe=e.WHOLE_DOCUMENT||!1,ge=e.RETURN_DOM||!1,_e=e.RETURN_DOM_FRAGMENT||!1,ve=e.RETURN_TRUSTED_TYPE||!1,he=e.FORCE_BODY||!1,ye=e.SANITIZE_DOM!==!1,be=e.SANITIZE_NAMED_PROPS||!1,xe=e.KEEP_CONTENT!==!1,Se=e.IN_PLACE||!1,ae=e.ALLOWED_URI_REGEXP||vr,Ne=e.NAMESPACE||Me,Le=e.MATHML_TEXT_INTEGRATION_POINTS||Le,Re=e.HTML_INTEGRATION_POINTS||Re,P=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&We(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(P.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&We(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(P.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements==`boolean`&&(P.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),de&&(le=!1),_e&&(ge=!0),Ce&&(j=H({},cr),N=Pn(null),Ce.html===!0&&(H(j,nr),H(N,lr)),Ce.svg===!0&&(H(j,rr),H(N,ur),H(N,fr)),Ce.svgFilters===!0&&(H(j,ir),H(N,ur),H(N,fr)),Ce.mathMl===!0&&(H(j,or),H(N,dr),H(N,fr))),Jn(e,`ADD_TAGS`)||(I.tagCheck=null),Jn(e,`ADD_ATTR`)||(I.attributeCheck=null),e.ADD_TAGS&&(typeof e.ADD_TAGS==`function`?I.tagCheck=e.ADD_TAGS:(j===M&&(j=er(j)),H(j,e.ADD_TAGS,R))),e.ADD_ATTR&&(typeof e.ADD_ATTR==`function`?I.attributeCheck=e.ADD_ATTR:(N===oe&&(N=er(N)),H(N,e.ADD_ATTR,R))),e.ADD_URI_SAFE_ATTR&&H(Oe,e.ADD_URI_SAFE_ATTR,R),e.FORBID_CONTENTS&&(we===Te&&(we=er(we)),H(we,e.FORBID_CONTENTS,R)),e.ADD_FORBID_CONTENTS&&(we===Te&&(we=er(we)),H(we,e.ADD_FORBID_CONTENTS,R)),xe&&(j[`#text`]=!0),pe&&H(j,[`html`,`head`,`body`]),j.table&&(H(j,[`tbody`]),delete se.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw Xn(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw Xn(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);b=e.TRUSTED_TYPES_POLICY,x=b.createHTML(``)}else b===void 0&&(b=Er(p,i)),b!==null&&typeof x==`string`&&(x=b.createHTML(``));Mn&&Mn(e),He=e}},z=H({},[...rr,...ir,...ar]),Ke=H({},[...or,...sr]),qe=function(e){let t=y(e);(!t||!t.tagName)&&(t={namespaceURI:Ne,tagName:`template`});let n=Hn(e.tagName),r=Hn(t.tagName);return Fe[e.namespaceURI]?e.namespaceURI===je?t.namespaceURI===Me?n===`svg`:t.namespaceURI===Ae?n===`svg`&&(r===`annotation-xml`||Le[r]):!!z[n]:e.namespaceURI===Ae?t.namespaceURI===Me?n===`math`:t.namespaceURI===je?n===`math`&&Re[r]:!!Ke[n]:e.namespaceURI===Me?t.namespaceURI===je&&!Re[r]||t.namespaceURI===Ae&&!Le[r]?!1:!Ke[n]&&(ze[n]||!z[n]):!!(Be===`application/xhtml+xml`&&Fe[e.namespaceURI]):!1},Je=function(e){Bn(t.removed,{element:e});try{y(e).removeChild(e)}catch{g(e)}},Ye=function(e,n){try{Bn(t.removed,{attribute:n.getAttributeNode(e),from:n})}catch{Bn(t.removed,{attribute:null,from:n})}if(n.removeAttribute(e),e===`is`)if(ge||_e)try{Je(n)}catch{}else try{n.setAttribute(e,``)}catch{}},Xe=function(e){let t=null,r=null;if(he)e=`<remove></remove>`+e;else{let t=Wn(e,/^[\r\n\t ]+/);r=t&&t[0]}Be===`application/xhtml+xml`&&Ne===Me&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=b?b.createHTML(e):e;if(Ne===Me)try{t=new f().parseFromString(i,Be)}catch{}if(!t||!t.documentElement){t=S.createDocument(Ne,`template`,null);try{t.documentElement.innerHTML=Pe?x:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),Ne===Me?T.call(t,pe?`html`:`body`)[0]:pe?t.documentElement:a},Ze=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)},Qe=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`)},$e=function(e){return typeof s==`function`&&e instanceof s};function B(e,n,r){Ln(e,e=>{e.call(t,n,r,He)})}let et=function(e){let n=null;if(B(D.beforeSanitizeElements,e,null),Qe(e))return Je(e),!0;let r=R(e.nodeName);if(B(D.uponSanitizeElement,e,{tagName:r,allowedTags:j}),fe&&e.hasChildNodes()&&!$e(e.firstElementChild)&&Yn(/<[/\w!]/g,e.innerHTML)&&Yn(/<[/\w!]/g,e.textContent)||e.nodeType===wr.progressingInstruction||fe&&e.nodeType===wr.comment&&Yn(/<[/\w]/g,e.data))return Je(e),!0;if(!(I.tagCheck instanceof Function&&I.tagCheck(r))&&(!j[r]||se[r])){if(!se[r]&&nt(r)&&(P.tagNameCheck instanceof RegExp&&Yn(P.tagNameCheck,r)||P.tagNameCheck instanceof Function&&P.tagNameCheck(r)))return!1;if(xe&&!we[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 Je(e),!0}return e instanceof c&&!qe(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&Yn(/<\/no(script|embed|frames)/i,e.innerHTML)?(Je(e),!0):(de&&e.nodeType===wr.text&&(n=e.textContent,Ln([ee,O,k],e=>{n=Gn(n,e,` `)}),e.textContent!==n&&(Bn(t.removed,{element:e.cloneNode()}),e.textContent=n)),B(D.afterSanitizeElements,e,null),!1)},tt=function(e,t,r){if(F[t]||ye&&(t===`id`||t===`name`)&&(r in n||r in Ue))return!1;if(!(le&&!F[t]&&Yn(te,t))&&!(ce&&Yn(A,t))&&!(I.attributeCheck instanceof Function&&I.attributeCheck(t,e))){if(!N[t]||F[t]){if(!(nt(e)&&(P.tagNameCheck instanceof RegExp&&Yn(P.tagNameCheck,e)||P.tagNameCheck instanceof Function&&P.tagNameCheck(e))&&(P.attributeNameCheck instanceof RegExp&&Yn(P.attributeNameCheck,t)||P.attributeNameCheck instanceof Function&&P.attributeNameCheck(t,e))||t===`is`&&P.allowCustomizedBuiltInElements&&(P.tagNameCheck instanceof RegExp&&Yn(P.tagNameCheck,r)||P.tagNameCheck instanceof Function&&P.tagNameCheck(r))))return!1}else if(!Oe[t]&&!Yn(ae,Gn(r,re,``))&&!((t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&Kn(r,`data:`)===0&&Ee[e])&&!(ue&&!Yn(ne,Gn(r,re,``)))&&r)return!1}return!0},nt=function(e){return e!==`annotation-xml`&&Wn(e,ie)},rt=function(e){B(D.beforeSanitizeAttributes,e,null);let{attributes:n}=e;if(!n||Qe(e))return;let r={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:N,forceKeepAttr:void 0},i=n.length;for(;i--;){let{name:a,namespaceURI:o,value:s}=n[i],c=R(a),l=s,u=a===`value`?l:qn(l);if(r.attrName=c,r.attrValue=u,r.keepAttr=!0,r.forceKeepAttr=void 0,B(D.uponSanitizeAttribute,e,r),u=r.attrValue,be&&(c===`id`||c===`name`)&&(Ye(a,e),u=`user-content-`+u),fe&&Yn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,u)){Ye(a,e);continue}if(c===`attributename`&&Wn(u,`href`)){Ye(a,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){Ye(a,e);continue}if(!L&&Yn(/\/>/i,u)){Ye(a,e);continue}de&&Ln([ee,O,k],e=>{u=Gn(u,e,` `)});let d=R(e.nodeName);if(!tt(d,c,u)){Ye(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),Qe(e)?Je(e):zn(t.removed)}catch{Ye(a,e)}}B(D.afterSanitizeAttributes,e,null)},it=function e(t){let n=null,r=Ze(t);for(B(D.beforeSanitizeShadowDOM,t,null);n=r.nextNode();)B(D.uponSanitizeShadowNode,n,null),et(n),rt(n),n.content instanceof a&&e(n.content);B(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(Pe=!e,Pe&&(e=`<!-->`),typeof e!=`string`&&!$e(e))if(typeof e.toString==`function`){if(e=e.toString(),typeof e!=`string`)throw Xn(`dirty is not a string, aborting`)}else throw Xn(`toString is not a function`);if(!t.isSupported)return e;if(me||Ge(n),t.removed=[],typeof e==`string`&&(Se=!1),Se){if(e.nodeName){let t=R(e.nodeName);if(!j[t]||se[t])throw Xn(`root node is forbidden and cannot be sanitized in-place`)}}else if(e instanceof s)i=Xe(`<!---->`),o=i.ownerDocument.importNode(e,!0),o.nodeType===wr.element&&o.nodeName===`BODY`||o.nodeName===`HTML`?i=o:i.appendChild(o);else{if(!ge&&!de&&!pe&&e.indexOf(`<`)===-1)return b&&ve?b.createHTML(e):e;if(i=Xe(e),!i)return ge?null:ve?x:``}i&&he&&Je(i.firstChild);let u=Ze(Se?e:i);for(;c=u.nextNode();)et(c),rt(c),c.content instanceof a&&it(c.content);if(Se)return e;if(ge){if(_e)for(l=w.call(i.ownerDocument);i.firstChild;)l.appendChild(i.firstChild);else l=i;return(N.shadowroot||N.shadowrootmode)&&(l=E.call(r,l,!0)),l}let d=pe?i.outerHTML:i.innerHTML;return pe&&j[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&Yn(xr,i.ownerDocument.doctype.name)&&(d=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
66
+ `+d),de&&Ln([ee,O,k],e=>{d=Gn(d,e,` `)}),b&&ve?b.createHTML(d):d},t.setConfig=function(){Ge(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),me=!0},t.clearConfig=function(){He=null,me=!1},t.isValidAttribute=function(e,t,n){return He||Ge({}),tt(R(e),R(t),n)},t.addHook=function(e,t){typeof t==`function`&&Bn(D[e],t)},t.removeHook=function(e,t){if(t!==void 0){let n=Rn(D[e],t);return n===-1?void 0:Vn(D[e],n,1)[0]}return zn(D[e])},t.removeHooks=function(e){D[e]=[]},t.removeAllHooks=function(){D=Dr()},t}var kr=Or(),Ar=kr.sanitize.bind(kr);kr.isSupported,kr.addHook.bind(kr),kr.removeHook.bind(kr),kr.removeHooks.bind(kr),kr.removeAllHooks.bind(kr),kr.setConfig.bind(kr),kr.clearConfig.bind(kr),kr.isValidAttribute.bind(kr),kr.version,kr.removed;function jr(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#x27;`)}function Mr(e,t){let n=jr(e);return t===`shtml`||([`js`,`javascript`,`ts`,`typescript`,`jsx`,`tsx`].includes(t)?n=Pr(n):t===`json`?n=Fr(n):[`bash`,`sh`,`shell`,`zsh`].includes(t)&&(n=Ir(n))),n}function Nr(e){let t=[];return{html:e.replace(/<span class="tok-(?:comment|string)">[\s\S]*?<\/span>/g,e=>{let n=String.fromCharCode(57344+t.length);return t.push(e),n}),restore:e=>e.replace(/[\ue000-\uf8ff]/g,e=>t[e.charCodeAt(0)-57344]??e)}}function Pr(e){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(/(&quot;[^&]*?&quot;|&#x27;[^&]*?&#x27;|`[^`]*?`)/g,`<span class="tok-string">$1</span>`);let t=Nr(e);return e=t.html,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>`),t.restore(e)}function Fr(e){return e=e.replace(/(&quot;[^&]*?&quot;)\s*:/g,`<span class="tok-keyword">$1</span>:`),e=e.replace(/:\s*(&quot;[^&]*?&quot;)/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 Ir(e){return e=e.replace(/(#[^\n]*)/g,`<span class="tok-comment">$1</span>`),e=e.replace(/(&quot;[^&]*?&quot;|&#x27;[^&]*?&#x27;)/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 Lr=new Tn({gfm:!0,breaks:!0,async:!1,renderer:{code({text:e,lang:t}){let n=t??``,r=Mr(e,n);return`<pre><code${n?` class="language-${jr(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="${jr(t)}"`:``,a=this.parser.parseInline(n);return`<a href="${jr(r)}"${i} target="_blank" rel="noopener noreferrer">${a}</a>`}}}),Rr={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 zr(e){return Ar(e,Rr)}function Br(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 Vr=/<p><strong>Error:<\/strong>\s*([\s\S]*?)<\/p>/g;function Hr(e){return Br(zr(Lr.parse(e)))}function Ur(e){return e.replace(Vr,(e,t)=>`<div class="msg__error" role="alert"><div class="msg__error-label">Error</div><div class="msg__error-body">${t}</div></div>`)}function Wr(e){return Hr(e)}function Gr(e){return Ur(Hr(e))}function Kr(e){if(typeof e==`string`)return jr(e);try{return jr(JSON.stringify(e,null,2))}catch{return jr(String(e))}}var qr=`browser-coding-agent`,Jr=1,Yr=`sessions`;function Xr(){return new Promise((e,t)=>{let n=indexedDB.open(qr,Jr);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Yr)||e.createObjectStore(Yr,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var Zr=class{db=null;async init(){this.db=await Xr()}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(Yr,`readwrite`);i.objectStore(Yr).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(Yr,`readonly`).objectStore(Yr).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(Yr,`readonly`).objectStore(Yr).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(Yr,`readwrite`);i.objectStore(Yr).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)}},Qr={"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 $r(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function ei(){return typeof window>`u`?null:window.SpeechRecognition||window.webkitSpeechRecognition||null}var ti=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=ei();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($r())this.startExtensionPopup();else{this.shouldBeListening=!1;let t=e?.name,n=Qr[`not-allowed`];t===`NotFoundError`?n=Qr[`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=Qr[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=Qr[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=ei();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}},ni={autoSend:`voice-auto-send`,lang:`voice-lang`};function ri(){return localStorage.getItem(ni.lang)||`en-US`}var ii=typeof chrome<`u`&&!!chrome?.runtime?.id;function ai(e){let t=e.trimStart().toLowerCase();return t.startsWith(`<!doctype`)||t.startsWith(`<html`)}var oi=class e{container;bridge;scripts=[];iframe=null;static cachedLucideScript=null;static lucideScriptPromise=null;messageHandler=null;constructor(e,t){this.container=e,this.bridge=t}async render(e,t){this.dispose(),ii?await this.renderInSandbox(e,t,ai(e)):ai(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-stop-cone`)this.bridge.stopCone();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(),c=``,l=``;if(n){let t=[];e.includes(`<slicc-editor`)&&t.push(fetch(chrome.runtime.getURL(`slicc-editor.js`)).then(e=>e.ok?e.text():``).then(e=>{c=e}).catch(()=>{})),e.includes(`<slicc-diff`)&&t.push(fetch(chrome.runtime.getURL(`slicc-diff.js`)).then(e=>e.ok?e.text():``).then(e=>{l=e}).catch(()=>{})),await Promise.all(t)}let u=await this.getLucideScript();r.contentWindow.postMessage({type:`sprinkle-render`,content:e,name:t,themeCSS:i,savedState:s,savedStorage:a,fullDoc:n,editorScript:c,diffScript:l,lucideScript:u},`*`)}pushUpdate(e){this.iframe?.contentWindow&&this.iframe.contentWindow.postMessage({type:`sprinkle-update`,data:e},`*`)}collectThemeCSS(){return ci()}generateBridgeScript(){return`(function() {
67
67
  var _updateListeners = new Set();
68
68
  var _sprinkleName = '';
69
69
  var _state = null;
@@ -239,7 +239,7 @@ ${t.includes(`<slicc-editor`)?`<script src="/slicc-editor.js"><\/script>`:``}
239
239
  ${t.includes(`<slicc-diff`)?`<script src="/slicc-diff.js"><\/script>`:``}
240
240
  <script src="/lucide-icons.js"><\/script>
241
241
  </head>
242
- <body class="sprinkle-inline">${t}</body></html>`;if(li)return mi(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 fi(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(di(a,i,t))}return r}function pi(e){for(let t of e)try{t.dispose()}catch{}e.length=0}function mi(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 hi=n(`tool-ui-renderer`),gi=typeof chrome<`u`&&!!chrome?.runtime?.id,_i=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){gi?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(()=>{hi.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){hi.warn(`Tool UI message nonce mismatch`,{expected:this.nonce,received:n.nonce});return}n.type===`tool-ui-action`&&n.id===this.requestId?(hi.info(`Tool UI action received`,{id:n.id,action:n.action}),v.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 r(async()=>{let{collectThemeCSS:e}=await import(`./sprinkle-renderer-DPJgJR85.js`);return{collectThemeCSS:e}},[]),i=n();t.contentWindow.postMessage({type:`tool-ui-render`,id:this.requestId,nonce:this.nonce,html:e,themeCSS:i},`*`)}renderWithInlineSprinkle(e){let t=document.createElement(`div`);t.className=`msg__inline-sprinkle`,this.container.appendChild(t),this.inlineSprinkle=di(t,e,(e,t)=>{hi.info(`Tool UI action (inline sprinkle)`,{id:this.requestId,action:e}),v.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)}},vi=new Map;function yi(e,t,n){let r=vi.get(t);r&&r.dispose();let i=new _i(e,t);return vi.set(t,i),i.render(n).catch(e=>{hi.error(`Failed to render tool UI`,{requestId:t,error:e.message})}),i}function bi(e){let t=vi.get(e);t&&(t.dispose(),vi.delete(e))}var xi=n(`chat-panel`);function Si(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var Ci={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 wi(e){return Ci[e]??`?`}function Ti(e){return e.role===`assistant`?Gr(e.content):Wr(e.content)}var Ei=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 Zr,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:Si(),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:Si(),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 ti({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=>{xi.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:ri()}),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=`
242
+ <body class="sprinkle-inline">${t}</body></html>`;if(li)return mi(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 fi(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(di(a,i,t))}return r}function pi(e){for(let t of e)try{t.dispose()}catch{}e.length=0}function mi(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 hi=n(`tool-ui-renderer`),gi=typeof chrome<`u`&&!!chrome?.runtime?.id,_i=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){gi?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(()=>{hi.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){hi.warn(`Tool UI message nonce mismatch`,{expected:this.nonce,received:n.nonce});return}n.type===`tool-ui-action`&&n.id===this.requestId?(hi.info(`Tool UI action received`,{id:n.id,action:n.action}),v.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 r(async()=>{let{collectThemeCSS:e}=await import(`./sprinkle-renderer-Cyc1ZOQ0.js`);return{collectThemeCSS:e}},[]),i=n();t.contentWindow.postMessage({type:`tool-ui-render`,id:this.requestId,nonce:this.nonce,html:e,themeCSS:i},`*`)}renderWithInlineSprinkle(e){let t=document.createElement(`div`);t.className=`msg__inline-sprinkle`,this.container.appendChild(t),this.inlineSprinkle=di(t,e,(e,t)=>{hi.info(`Tool UI action (inline sprinkle)`,{id:this.requestId,action:e}),v.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)}},vi=new Map;function yi(e,t,n){let r=vi.get(t);r&&r.dispose();let i=new _i(e,t);return vi.set(t,i),i.render(n).catch(e=>{hi.error(`Failed to render tool UI`,{requestId:t,error:e.message})}),i}function bi(e){let t=vi.get(e);t&&(t.dispose(),vi.delete(e))}var xi=n(`chat-panel`);function Si(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var Ci={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 wi(e){return Ci[e]??`?`}function Ti(e){return e.role===`assistant`?Gr(e.content):Wr(e.content)}var Ei=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 Zr,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:Si(),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:Si(),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 ti({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=>{xi.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:ri()}),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=`
243
243
  <div class="chat__handoffs-inner">
244
244
  <div class="chat__handoffs-header">${jr(e)}</div>
245
245
  ${this.pendingHandoffs.map(e=>this.renderPendingHandoffCard(e)).join(``)}
@@ -253,8 +253,8 @@ ${t.includes(`<slicc-diff`)?`<script src="/slicc-diff.js"><\/script>`:``}
253
253
  <button class="chat__handoff-btn" data-action="dismiss" data-handoff-id="${jr(e.handoffId)}" type="button">Dismiss</button>
254
254
  </div>
255
255
  </section>
256
- `}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:Si(),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(xi.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:Si(),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}xi.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){xi.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}xi.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)),yi(e,n,r)}else i<10?setTimeout(()=>this.handleToolUI(e,t,n,r,i+1),100):xi.warn(`handleToolUI: tool call element not found in DOM after retries`,{toolName:t})}handleToolUIDone(e,t){bi(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:Si(),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=j(),n=te(),r=re(),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}`;ne(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=Ti(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`||e.channel===`fswatch`){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`||e.channel===`fswatch`)&&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=Ti(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=Ti(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`:e.channel===`fswatch`?`File Watch`:`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=Wr(e.content),t.appendChild(o),t}createToolCallEl(e){wi(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">${jr(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=Kr(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&&(pi(t),this.inlineSprinkles.delete(e))}disposeAllInlineSprinkles(){for(let[,e]of this.inlineSprinkles)pi(e);this.inlineSprinkles.clear()}hydrateInlineSprinklesInEl(e,t){let n=fi(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=``}},Di=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
257
- `,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 Oi(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 ki(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 Ai(){return ki([`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 ji(){return ki([`M6 2h5l5 5v9a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1z`,`M11 2v5h5`])}function Mi(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 Ni(e){return`'${e.replace(/'/g,`'\\''`)}'`}function Pi(e){return`${f(e)?`imgcat`:`cat`} ${Ni(e)}`}var Fi=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(Mi(e)),a.appendChild(o);let s=document.createElement(`span`);s.className=`file-browser__icon`,s.appendChild(Ai()),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(ji()),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=Oi(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?f(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=F(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=Pi(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)}},Ii=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)}},Li=n(`scoops-panel`),Ri=class e{container;orchestrator=null;callbacks;selectedScoopJid=null;scoopStatuses=new Map;expanded=!1;eyesEl=null;hoveredJid=null;lastProcessingJid=null;coneJid=null;leftPupilGroup=null;rightPupilGroup=null;eyesSvg=null;mouseMoveBound=null;constructor(e,t){this.container=e,this.callbacks=t,this.render()}dispose(){this.mouseMoveBound&&=(document.removeEventListener(`mousemove`,this.mouseMoveBound),null),this.eyesEl?.remove(),this.eyesEl=null,this.eyesSvg=null,this.leftPupilGroup=null,this.rightPupilGroup=null,document.querySelectorAll(`.scoop-fixed-tooltip`).forEach(e=>e.remove())}toggleExpanded(){this.expanded=!this.expanded,this.container.classList.toggle(`layout__scoops--expanded`,this.expanded)}static LEFT_EYE={cx:55,cy:50,r:38};static RIGHT_EYE={cx:145,cy:50,r:38};static PUPIL_R=18;static MAX_OFFSET=16;createEyesEl(){let t=`http://www.w3.org/2000/svg`,n=document.createElement(`div`);n.className=`scoop-eyes`;let r=document.createElementNS(t,`svg`);r.setAttribute(`viewBox`,`0 0 200 100`),r.setAttribute(`width`,`100%`),r.setAttribute(`height`,`100%`);let{LEFT_EYE:i,RIGHT_EYE:a,PUPIL_R:o}=e,s=e=>{let n=document.createElementNS(t,`circle`);n.setAttribute(`cx`,String(e.cx)),n.setAttribute(`cy`,String(e.cy)),n.setAttribute(`r`,String(e.r)),n.setAttribute(`fill`,`#fff`),n.setAttribute(`stroke`,`#000`),n.setAttribute(`stroke-width`,`4`),r.appendChild(n);let i=document.createElementNS(t,`g`),a=document.createElementNS(t,`circle`);a.setAttribute(`cx`,String(e.cx)),a.setAttribute(`cy`,String(e.cy)),a.setAttribute(`r`,String(o)),a.setAttribute(`fill`,`#000`),i.appendChild(a);let s=document.createElementNS(t,`circle`);return s.setAttribute(`cx`,String(e.cx-o*.3)),s.setAttribute(`cy`,String(e.cy-o*.35)),s.setAttribute(`r`,String(o*.4)),s.setAttribute(`fill`,`#fff`),i.appendChild(s),r.appendChild(i),i};return this.leftPupilGroup=s(i),this.rightPupilGroup=s(a),n.appendChild(r),this.eyesSvg=r,this.mouseMoveBound||(this.mouseMoveBound=e=>this.onMouseMove(e),document.addEventListener(`mousemove`,this.mouseMoveBound)),n}onMouseMove(t){if(!this.eyesSvg||!this.leftPupilGroup||!this.rightPupilGroup)return;let n=this.eyesSvg.getBoundingClientRect();if(n.width===0||n.height===0)return;let r=200/n.width,i=100/n.height,a=(t.clientX-n.left)*r,o=(t.clientY-n.top)*i,{LEFT_EYE:s,RIGHT_EYE:c,MAX_OFFSET:l}=e;this.positionPupilGroup(this.leftPupilGroup,s.cx,s.cy,a,o,l),this.positionPupilGroup(this.rightPupilGroup,c.cx,c.cy,a,o,l)}positionPupilGroup(e,t,n,r,i,a){let o=r-t,s=i-n,c=Math.sqrt(o*o+s*s),l=Math.min(c,a),u=c>0?o/c*l:0,d=c>0?s/c*l:0;e.setAttribute(`transform`,`translate(${u},${d})`)}resolveEyesOwner(){if(this.hoveredJid&&this.hasScoopItem(this.hoveredJid))return this.hoveredJid;if(this.lastProcessingJid&&this.scoopStatuses.get(this.lastProcessingJid)===`processing`&&this.hasScoopItem(this.lastProcessingJid))return this.lastProcessingJid;for(let[e,t]of this.scoopStatuses)if(t===`processing`&&this.hasScoopItem(e))return this.lastProcessingJid=e,e;return this.coneJid}hasScoopItem(e){return!!this.container.querySelector(`.scoop-item[data-jid="${CSS.escape(e)}"]`)}moveEyes(){this.eyesEl||=this.createEyesEl();let e=this.resolveEyesOwner();if(!e)return;let t=this.container.querySelector(`.scoop-item[data-jid="${CSS.escape(e)}"]`);if(!t)return;let n=t.querySelector(`.scoop-icon-wrap`);n&&this.eyesEl.parentElement!==n&&n.appendChild(this.eyesEl)}setOrchestrator(e){this.orchestrator=e,this.refreshScoops()}updateScoopStatus(e,t){this.scoopStatuses.set(e,t),t===`processing`&&(this.lastProcessingJid=e),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){this.coneJid=t.jid;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`);if(l.setAttribute(`width`,`24`),l.setAttribute(`height`,`24`),l.setAttribute(`viewBox`,`70 330 440 570`),l.innerHTML=`<path d="M108.22,414.88l189.84,460.03c1.36,3.3,6.09,3.16,7.25-.22l159.34-463.34c.87-2.53-1.03-5.16-3.7-5.13l-349.18,3.32c-2.74.03-4.59,2.82-3.55,5.35Z" fill="${i}" stroke="${i}" stroke-linejoin="round" stroke-width="12"/><path d="M261.93,482.48h0c15.03-15.03,4.46-40.72-16.79-40.83h0c-21.37-.11-32.14,25.72-17.03,40.83h0c9.34,9.34,24.48,9.34,33.82,0Z" fill="${a}"/><path d="M384.85,527.49l-51.82,51.82c-2.24,2.24-2.24,5.86,0,8.1l55.71,55.71c2.24,2.24,5.86,2.24,8.1,0h0c.62-.62,1.08-1.36,1.37-2.19l26.52-77.11c.71-2.07.18-4.36-1.37-5.91l-30.41-30.41c-2.24-2.24-5.86-2.24-8.1,0Z" fill="${a}"/><rect x="274.59" y="463.59" width="84.73" height="95.66" rx="42.36" ry="42.36" transform="translate(-268.79 373.91) rotate(-45)" fill="${a}"/><rect x="291.06" y="603.84" width="72.24" height="90.24" rx="36.12" ry="36.12" transform="translate(-363.06 421.43) rotate(-45)" fill="${a}"/><path d="M371.7,684.58l-25.94,25.94c-2.24,2.24-2.24,5.86,0,8.1l12.67,12.67c2.99,2.99,8.09,1.82,9.46-2.19l13.28-38.61c1.97-5.74-5.17-10.2-9.46-5.91Z" fill="${a}"/><path d="M159.42,564.14l2.73,6.83c1.52,3.82,6.46,4.83,9.37,1.93l2.05-2.05c2.24-2.24,2.24-5.86,0-8.1l-4.78-4.78c-4.4-4.4-11.67.39-9.37,6.17Z" fill="${a}"/><path d="M243.92,633.11l-48.65-48.65c-5.24-5.24-13.74-5.24-18.99,0h0c-3.8,3.8-4.97,9.49-2.98,14.47l27.77,69.54c3.58,8.95,15.14,11.33,21.96,4.51l20.89-20.89c5.24-5.24,5.24-13.74,0-18.99Z" fill="${a}"/><path d="M211.32,533.1h0c14.11-14.11,14.11-36.98,0-51.08l-34.94-34.94c-.72-.72-.72-1.89,0-2.62h0c1.16-1.16.34-3.15-1.3-3.16l-11.23-.06c-25.62-.13-43.23,25.72-33.73,49.51l5.37,13.45c1.82,4.55,4.54,8.68,8,12.15l16.74,16.74c14.11,14.11,36.98,14.11,51.08,0Z" fill="${a}"/><path d="M263.74,792.53h0c-5.69,5.69-7.45,14.23-4.46,21.71l22.5,56.36c6.92,17.34,31.68,16.74,37.75-.92l8.66-25.2c2.5-7.28.64-15.35-4.8-20.79l-31.17-31.17c-7.87-7.87-20.62-7.87-28.48,0Z" fill="${a}"/><path d="M392.94,503.07l40.81-40.81c2.24-2.24,5.86-2.24,8.1,0l.06.06c2.24,2.24,2.24,5.86,0,8.1l-40.81,40.81c-2.24,2.24-2.24,5.86,0,8.1l22.48,22.48c2.99,2.99,8.09,1.82,9.46-2.19l30.71-89.32c1.27-3.71-1.47-7.57-5.39-7.59l-120.63-.6c-5.11-.03-7.69,6.16-4.08,9.77l51.18,51.18c2.24,2.24,5.86,2.24,8.1,0Z" fill="${a}"/><rect x="217.18" y="527.25" width="72.24" height="95.66" rx="36.12" ry="36.12" transform="translate(-332.45 347.55) rotate(-45)" fill="${a}"/><path d="M350.28,739.46h0c-9.24-9.24-24.22-9.24-33.46,0l-13.94,13.94c-9.24,9.24-9.24,24.22,0,33.46l6.81,6.81c12.37,12.37,33.42,7.5,39.1-9.04l7.13-20.75c2.94-8.55.75-18.03-5.64-24.42Z" fill="${a}"/><path d="M234.18,749.12l13.2,33.06c1.52,3.82,6.46,4.83,9.37,1.93l9.93-9.93c2.24-2.24,2.24-5.86,0-8.1l-23.13-23.13c-4.4-4.4-11.67.39-9.37,6.17Z" fill="${a}"/><rect x="236.26" y="661.25" width="67.04" height="90.24" rx="33.52" ry="33.52" transform="translate(-420.46 397.65) rotate(-45)" fill="${a}"/><ellipse cx="288.37" cy="404.38" rx="182.34" ry="67.01" fill="${i}" stroke="${i}" stroke-miterlimit="10" stroke-width="12"/>`,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 u=document.createElement(`div`);u.className=`scoop-info`;let d=document.createElement(`div`);if(d.className=`scoop-name`,d.textContent=t.assistantLabel,u.appendChild(d),e===`processing`||e===`error`){let t=document.createElement(`div`);t.className=`scoop-subtitle`,t.textContent=e===`processing`?`Working…`:`Error`,u.appendChild(t)}s.appendChild(u);let f=document.createElement(`div`);if(f.className=`scoop-actions`,e===`processing`){let e=document.createElement(`span`);e.className=`scoop-spin-dot`,f.appendChild(e)}else if(e===`error`){let e=document.createElement(`span`);e.className=`scoop-err-dot`,f.appendChild(e)}s.appendChild(f),s.addEventListener(`click`,()=>this.selectScoop(t)),s.addEventListener(`mouseenter`,()=>{this.hoveredJid=t.jid,this.moveEyes()}),s.addEventListener(`mouseleave`,()=>{this.hoveredJid===t.jid&&(this.hoveredJid=null),this.moveEyes()});let p=t.assistantLabel;s.addEventListener(`mouseenter`,()=>{if(this.expanded)return;let e=document.createElement(`div`);e.className=`scoop-fixed-tooltip`,e.textContent=p,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),this.moveEyes();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(`viewBox`,`0 0 580 470`);let h=document.createElementNS(r,`path`);if(h.setAttribute(`d`,`M566.75,340.67c0-29.85-12.97-56.87-33.96-76.47,4.8-9.98,7.44-20.71,7.44-31.9,0-38.29-30.62-71.33-74.92-86.77.33-3.07.51-6.17.51-9.3,0-69.72-84.29-126.24-188.26-126.24s-188.26,56.52-188.26,126.24c0,4,.29,7.95.83,11.86-34.94,15.4-58.48,44.25-58.48,77.34,0,18.21,7.15,35.15,19.39,49.26-25.1,19.88-41.05,49.47-41.05,82.54,0,59.85,52.15,108.37,116.49,108.37,10.83,0,21.3-1.4,31.26-3.98,31.42,41.91,83.55,69.34,142.55,69.34,64.73,0,121.2-33,151.11-81.94,63.8-.57,115.34-48.85,115.34-108.34Z`),h.setAttribute(`fill`,l),h.setAttribute(`stroke`,l),h.setAttribute(`stroke-width`,`10`),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`,()=>{this.hoveredJid=t.jid,this.moveEyes()}),d.addEventListener(`mouseleave`,()=>{this.hoveredJid===t.jid&&(this.hoveredJid=null),this.moveEyes()}),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),this.moveEyes()}}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(),Li.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(),Li.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(`div`);t.className=`scoop-cone-header`,e.appendChild(t);let n=document.createElement(`div`);n.className=`scoops-list`,e.appendChild(n),this.container.appendChild(e);let r=document.createElement(`style`);r.textContent=`
256
+ `}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:Si(),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(xi.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:Si(),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}xi.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){xi.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}xi.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)),yi(e,n,r)}else i<10?setTimeout(()=>this.handleToolUI(e,t,n,r,i+1),100):xi.warn(`handleToolUI: tool call element not found in DOM after retries`,{toolName:t})}handleToolUIDone(e,t){bi(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:Si(),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=A(),n=C(),r=ne(),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}`;b(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=Ti(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`||e.channel===`fswatch`){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`||e.channel===`fswatch`)&&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=Ti(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=Ti(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`:e.channel===`fswatch`?`File Watch`:`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=Wr(e.content),t.appendChild(o),t}createToolCallEl(e){wi(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">${jr(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=Kr(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&&(pi(t),this.inlineSprinkles.delete(e))}disposeAllInlineSprinkles(){for(let[,e]of this.inlineSprinkles)pi(e);this.inlineSprinkles.clear()}hydrateInlineSprinklesInEl(e,t){let n=fi(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=``}},Di=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
257
+ `,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 Oi(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 ki(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 Ai(){return ki([`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 ji(){return ki([`M6 2h5l5 5v9a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1z`,`M11 2v5h5`])}function Mi(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 Ni(e){return`'${e.replace(/'/g,`'\\''`)}'`}function Pi(e){return`${f(e)?`imgcat`:`cat`} ${Ni(e)}`}var Fi=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(Mi(e)),a.appendChild(o);let s=document.createElement(`span`);s.className=`file-browser__icon`,s.appendChild(Ai()),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(ji()),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=Oi(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?f(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=N(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=Pi(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)}},Ii=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)}},Li=n(`scoops-panel`),Ri=class e{container;orchestrator=null;callbacks;selectedScoopJid=null;scoopStatuses=new Map;expanded=!1;eyesEl=null;hoveredJid=null;lastProcessingJid=null;coneJid=null;leftPupilGroup=null;rightPupilGroup=null;eyesSvg=null;mouseMoveBound=null;constructor(e,t){this.container=e,this.callbacks=t,this.render()}dispose(){this.mouseMoveBound&&=(document.removeEventListener(`mousemove`,this.mouseMoveBound),null),this.eyesEl?.remove(),this.eyesEl=null,this.eyesSvg=null,this.leftPupilGroup=null,this.rightPupilGroup=null,document.querySelectorAll(`.scoop-fixed-tooltip`).forEach(e=>e.remove())}toggleExpanded(){this.expanded=!this.expanded,this.container.classList.toggle(`layout__scoops--expanded`,this.expanded)}static LEFT_EYE={cx:55,cy:50,r:38};static RIGHT_EYE={cx:145,cy:50,r:38};static PUPIL_R=18;static MAX_OFFSET=16;createEyesEl(){let t=`http://www.w3.org/2000/svg`,n=document.createElement(`div`);n.className=`scoop-eyes`;let r=document.createElementNS(t,`svg`);r.setAttribute(`viewBox`,`0 0 200 100`),r.setAttribute(`width`,`100%`),r.setAttribute(`height`,`100%`);let{LEFT_EYE:i,RIGHT_EYE:a,PUPIL_R:o}=e,s=e=>{let n=document.createElementNS(t,`circle`);n.setAttribute(`cx`,String(e.cx)),n.setAttribute(`cy`,String(e.cy)),n.setAttribute(`r`,String(e.r)),n.setAttribute(`fill`,`#fff`),n.setAttribute(`stroke`,`#000`),n.setAttribute(`stroke-width`,`4`),r.appendChild(n);let i=document.createElementNS(t,`g`),a=document.createElementNS(t,`circle`);a.setAttribute(`cx`,String(e.cx)),a.setAttribute(`cy`,String(e.cy)),a.setAttribute(`r`,String(o)),a.setAttribute(`fill`,`#000`),i.appendChild(a);let s=document.createElementNS(t,`circle`);return s.setAttribute(`cx`,String(e.cx-o*.3)),s.setAttribute(`cy`,String(e.cy-o*.35)),s.setAttribute(`r`,String(o*.4)),s.setAttribute(`fill`,`#fff`),i.appendChild(s),r.appendChild(i),i};return this.leftPupilGroup=s(i),this.rightPupilGroup=s(a),n.appendChild(r),this.eyesSvg=r,this.mouseMoveBound||(this.mouseMoveBound=e=>this.onMouseMove(e),document.addEventListener(`mousemove`,this.mouseMoveBound)),n}onMouseMove(t){if(!this.eyesSvg||!this.leftPupilGroup||!this.rightPupilGroup)return;let n=this.eyesSvg.getBoundingClientRect();if(n.width===0||n.height===0)return;let r=200/n.width,i=100/n.height,a=(t.clientX-n.left)*r,o=(t.clientY-n.top)*i,{LEFT_EYE:s,RIGHT_EYE:c,MAX_OFFSET:l}=e;this.positionPupilGroup(this.leftPupilGroup,s.cx,s.cy,a,o,l),this.positionPupilGroup(this.rightPupilGroup,c.cx,c.cy,a,o,l)}positionPupilGroup(e,t,n,r,i,a){let o=r-t,s=i-n,c=Math.sqrt(o*o+s*s),l=Math.min(c,a),u=c>0?o/c*l:0,d=c>0?s/c*l:0;e.setAttribute(`transform`,`translate(${u},${d})`)}resolveEyesOwner(){if(this.hoveredJid&&this.hasScoopItem(this.hoveredJid))return this.hoveredJid;if(this.lastProcessingJid&&this.scoopStatuses.get(this.lastProcessingJid)===`processing`&&this.hasScoopItem(this.lastProcessingJid))return this.lastProcessingJid;for(let[e,t]of this.scoopStatuses)if(t===`processing`&&this.hasScoopItem(e))return this.lastProcessingJid=e,e;return this.coneJid}hasScoopItem(e){return!!this.container.querySelector(`.scoop-item[data-jid="${CSS.escape(e)}"]`)}moveEyes(){this.eyesEl||=this.createEyesEl();let e=this.resolveEyesOwner();if(!e)return;let t=this.container.querySelector(`.scoop-item[data-jid="${CSS.escape(e)}"]`);if(!t)return;let n=t.querySelector(`.scoop-icon-wrap`);n&&this.eyesEl.parentElement!==n&&n.appendChild(this.eyesEl)}setOrchestrator(e){this.orchestrator=e,this.refreshScoops()}updateScoopStatus(e,t){this.scoopStatuses.set(e,t),t===`processing`&&(this.lastProcessingJid=e),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){this.coneJid=t.jid;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`);if(l.setAttribute(`width`,`24`),l.setAttribute(`height`,`24`),l.setAttribute(`viewBox`,`70 330 440 570`),l.innerHTML=`<path d="M108.22,414.88l189.84,460.03c1.36,3.3,6.09,3.16,7.25-.22l159.34-463.34c.87-2.53-1.03-5.16-3.7-5.13l-349.18,3.32c-2.74.03-4.59,2.82-3.55,5.35Z" fill="${i}" stroke="${i}" stroke-linejoin="round" stroke-width="12"/><path d="M261.93,482.48h0c15.03-15.03,4.46-40.72-16.79-40.83h0c-21.37-.11-32.14,25.72-17.03,40.83h0c9.34,9.34,24.48,9.34,33.82,0Z" fill="${a}"/><path d="M384.85,527.49l-51.82,51.82c-2.24,2.24-2.24,5.86,0,8.1l55.71,55.71c2.24,2.24,5.86,2.24,8.1,0h0c.62-.62,1.08-1.36,1.37-2.19l26.52-77.11c.71-2.07.18-4.36-1.37-5.91l-30.41-30.41c-2.24-2.24-5.86-2.24-8.1,0Z" fill="${a}"/><rect x="274.59" y="463.59" width="84.73" height="95.66" rx="42.36" ry="42.36" transform="translate(-268.79 373.91) rotate(-45)" fill="${a}"/><rect x="291.06" y="603.84" width="72.24" height="90.24" rx="36.12" ry="36.12" transform="translate(-363.06 421.43) rotate(-45)" fill="${a}"/><path d="M371.7,684.58l-25.94,25.94c-2.24,2.24-2.24,5.86,0,8.1l12.67,12.67c2.99,2.99,8.09,1.82,9.46-2.19l13.28-38.61c1.97-5.74-5.17-10.2-9.46-5.91Z" fill="${a}"/><path d="M159.42,564.14l2.73,6.83c1.52,3.82,6.46,4.83,9.37,1.93l2.05-2.05c2.24-2.24,2.24-5.86,0-8.1l-4.78-4.78c-4.4-4.4-11.67.39-9.37,6.17Z" fill="${a}"/><path d="M243.92,633.11l-48.65-48.65c-5.24-5.24-13.74-5.24-18.99,0h0c-3.8,3.8-4.97,9.49-2.98,14.47l27.77,69.54c3.58,8.95,15.14,11.33,21.96,4.51l20.89-20.89c5.24-5.24,5.24-13.74,0-18.99Z" fill="${a}"/><path d="M211.32,533.1h0c14.11-14.11,14.11-36.98,0-51.08l-34.94-34.94c-.72-.72-.72-1.89,0-2.62h0c1.16-1.16.34-3.15-1.3-3.16l-11.23-.06c-25.62-.13-43.23,25.72-33.73,49.51l5.37,13.45c1.82,4.55,4.54,8.68,8,12.15l16.74,16.74c14.11,14.11,36.98,14.11,51.08,0Z" fill="${a}"/><path d="M263.74,792.53h0c-5.69,5.69-7.45,14.23-4.46,21.71l22.5,56.36c6.92,17.34,31.68,16.74,37.75-.92l8.66-25.2c2.5-7.28.64-15.35-4.8-20.79l-31.17-31.17c-7.87-7.87-20.62-7.87-28.48,0Z" fill="${a}"/><path d="M392.94,503.07l40.81-40.81c2.24-2.24,5.86-2.24,8.1,0l.06.06c2.24,2.24,2.24,5.86,0,8.1l-40.81,40.81c-2.24,2.24-2.24,5.86,0,8.1l22.48,22.48c2.99,2.99,8.09,1.82,9.46-2.19l30.71-89.32c1.27-3.71-1.47-7.57-5.39-7.59l-120.63-.6c-5.11-.03-7.69,6.16-4.08,9.77l51.18,51.18c2.24,2.24,5.86,2.24,8.1,0Z" fill="${a}"/><rect x="217.18" y="527.25" width="72.24" height="95.66" rx="36.12" ry="36.12" transform="translate(-332.45 347.55) rotate(-45)" fill="${a}"/><path d="M350.28,739.46h0c-9.24-9.24-24.22-9.24-33.46,0l-13.94,13.94c-9.24,9.24-9.24,24.22,0,33.46l6.81,6.81c12.37,12.37,33.42,7.5,39.1-9.04l7.13-20.75c2.94-8.55.75-18.03-5.64-24.42Z" fill="${a}"/><path d="M234.18,749.12l13.2,33.06c1.52,3.82,6.46,4.83,9.37,1.93l9.93-9.93c2.24-2.24,2.24-5.86,0-8.1l-23.13-23.13c-4.4-4.4-11.67.39-9.37,6.17Z" fill="${a}"/><rect x="236.26" y="661.25" width="67.04" height="90.24" rx="33.52" ry="33.52" transform="translate(-420.46 397.65) rotate(-45)" fill="${a}"/><ellipse cx="288.37" cy="404.38" rx="182.34" ry="67.01" fill="${i}" stroke="${i}" stroke-miterlimit="10" stroke-width="12"/>`,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 u=document.createElement(`div`);u.className=`scoop-info`;let d=document.createElement(`div`);if(d.className=`scoop-name`,d.textContent=t.assistantLabel,u.appendChild(d),e===`processing`||e===`error`){let t=document.createElement(`div`);t.className=`scoop-subtitle`,t.textContent=e===`processing`?`Working…`:`Error`,u.appendChild(t)}s.appendChild(u);let f=document.createElement(`div`);if(f.className=`scoop-actions`,e===`processing`){let e=document.createElement(`span`);e.className=`scoop-spin-dot`,f.appendChild(e)}else if(e===`error`){let e=document.createElement(`span`);e.className=`scoop-err-dot`,f.appendChild(e)}s.appendChild(f),s.addEventListener(`click`,()=>this.selectScoop(t)),s.addEventListener(`mouseenter`,()=>{this.hoveredJid=t.jid,this.moveEyes()}),s.addEventListener(`mouseleave`,()=>{this.hoveredJid===t.jid&&(this.hoveredJid=null),this.moveEyes()});let p=t.assistantLabel;s.addEventListener(`mouseenter`,()=>{if(this.expanded)return;let e=document.createElement(`div`);e.className=`scoop-fixed-tooltip`,e.textContent=p,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),this.moveEyes();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(`viewBox`,`0 0 580 470`);let h=document.createElementNS(r,`path`);if(h.setAttribute(`d`,`M566.75,340.67c0-29.85-12.97-56.87-33.96-76.47,4.8-9.98,7.44-20.71,7.44-31.9,0-38.29-30.62-71.33-74.92-86.77.33-3.07.51-6.17.51-9.3,0-69.72-84.29-126.24-188.26-126.24s-188.26,56.52-188.26,126.24c0,4,.29,7.95.83,11.86-34.94,15.4-58.48,44.25-58.48,77.34,0,18.21,7.15,35.15,19.39,49.26-25.1,19.88-41.05,49.47-41.05,82.54,0,59.85,52.15,108.37,116.49,108.37,10.83,0,21.3-1.4,31.26-3.98,31.42,41.91,83.55,69.34,142.55,69.34,64.73,0,121.2-33,151.11-81.94,63.8-.57,115.34-48.85,115.34-108.34Z`),h.setAttribute(`fill`,l),h.setAttribute(`stroke`,l),h.setAttribute(`stroke-width`,`10`),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`,()=>{this.hoveredJid=t.jid,this.moveEyes()}),d.addEventListener(`mouseleave`,()=>{this.hoveredJid===t.jid&&(this.hoveredJid=null),this.moveEyes()}),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),this.moveEyes()}}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(),Li.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(),Li.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(`div`);t.className=`scoop-cone-header`,e.appendChild(t);let n=document.createElement(`div`);n.className=`scoops-list`,e.appendChild(n),this.container.appendChild(e);let r=document.createElement(`style`);r.textContent=`
258
258
  .scoops-panel {
259
259
  display: flex;
260
260
  flex-direction: column;
@@ -725,7 +725,7 @@ ${t.includes(`<slicc-diff`)?`<script src="/slicc-diff.js"><\/script>`:``}
725
725
  50% { transform: scale(1.3); }
726
726
  100% { transform: scale(1); }
727
727
  }
728
- `,document.head.appendChild(e)}},Bi=[{id:`chat`,label:`Chat`},{id:`terminal`,label:`Terminal`},{id:`files`,label:`Files`},{id:`memory`,label:`Memory`}],Vi=`slicc-hidden-tabs`,Hi=[`terminal`,`memory`];function Ui(){try{let e=localStorage.getItem(Vi);return e?new Set(JSON.parse(e)):new Set(Hi)}catch{return new Set(Hi)}}function Wi(e){let t=e.filter(e=>e!==`chat`);localStorage.setItem(Vi,JSON.stringify(t))}var Gi=Bi.filter(e=>!Ui().has(e.id)),Ki=`chat`,qi=new Set(Bi.map(e=>e.id));function Ji(e){return qi.has(e)}var Yi=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}},Xi=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 Zi(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=Qi(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=Qi(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 Qi(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 $i=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;headerHamburger=null;panels;registry=new Xi;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));Wi(e?[]:[`terminal`,`memory`])}buildHeader(e){let t=document.createElement(`div`);t.className=`header`;let n=()=>{if(te())return;let e=j();for(let t of e)if(t.models.length>0){let{defaultModelId:e}=E(t.providerId),n=(e?t.models.find(t=>t.id.toLowerCase().includes(e.toLowerCase())):void 0)??t.models[0];ne(`${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`);if(i.className=`header__brand`,this.isExtension){let e=this.sliccLogo(24);i.appendChild(e)}else{let e=document.createElement(`button`);e.className=`scoops-hamburger`,e.dataset.tooltip=`Toggle navigation`,e.dataset.tooltipPos=`right`,e.setAttribute(`aria-label`,`Toggle navigation`),e.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>`,this.headerHamburger=e,e.addEventListener(`click`,()=>{this.panels?.scoops?.toggleExpanded(),e.innerHTML=this.scoopsEl?.classList.contains(`layout__scoops--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>`}),i.appendChild(e)}let a=document.createElement(`div`);a.className=`header__title`,a.textContent=`slicc`,i.appendChild(a),r.appendChild(i),this.isExtension&&(this.scoopSwitcherEl=document.createElement(`div`),this.scoopSwitcherEl.className=`scoop-switcher`,this.scoopSwitcher=new zi(this.scoopSwitcherEl,{onScoopSelect:e=>this.onScoopSelect?.(e),onDeleteScoop:e=>{this.panels?.scoops?.deleteScoop?.(e)}}),r.appendChild(this.scoopSwitcherEl));let o=document.createElement(`div`);o.className=`header__spacer`,r.appendChild(o),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=E(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`,()=>{A(),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()||A(),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 Yi(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 Gi){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 Ei(n),terminal:new Di(r,{onClearTerminal:()=>{this.panels.terminal.clearTerminal()}}),fileBrowser:new Fi(i,{onRunCommand:async e=>{await this.runFileBrowserCommand(e),this.extensionZone.activateTab(`terminal`)}}),memory:new Ii(a),scoops:new Ri(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&&Zi(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 Yi(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 Ei(o),terminal:new Di(this.terminalContainer,{onClearTerminal:()=>{this.panels.terminal.clearTerminal(),this.openTerminal()}}),fileBrowser:new Fi(u,{onRunCommand:async e=>{await this.runFileBrowserCommand(e),this.openTerminal()}}),memory:new Ii(d),scoops:new Ri(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));Zi(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.panels.scoops.dispose();this.root.firstChild;)this.root.removeChild(this.root.firstChild)}},ea=`slicc-theme`,ta=new Set([`dark`,`light`,`system`]);function na(){let e=localStorage.getItem(ea);return e&&ta.has(e)?e:`system`}function ra(){let e=na(),t=e===`light`;e===`system`&&(t=window.matchMedia?.(`(prefers-color-scheme: light)`).matches??!1),document.documentElement.classList.toggle(`theme-light`,t)}var ia;function aa(){ra(),ia=window.matchMedia?.(`(prefers-color-scheme: light)`),ia?.addEventListener?.(`change`,()=>{na()===`system`&&ra()})}var oa=300,sa=6,ca=null,la=null;function ua(){return ca||(ca=document.createElement(`div`),ca.className=`s2-tooltip`,document.body.appendChild(ca)),ca}function da(e){let t=e.getAttribute(`data-tooltip`);if(!t)return;let n=ua();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-sa,s=r.left+r.width/2-i.width/2):a===`right`?(o=r.top+r.height/2-i.height/2,s=r.right+sa):(o=r.bottom+sa,s=r.left+r.width/2-i.width/2),a===`bottom`&&o+i.height>window.innerHeight-4?o=r.top-i.height-sa:a===`top`&&o<4&&(o=r.bottom+sa),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 fa(){la&&=(clearTimeout(la),null),ca?.classList.remove(`s2-tooltip--visible`)}function pa(){document.addEventListener(`pointerenter`,e=>{let t=e.target.closest?.(`[data-tooltip]`);t&&(fa(),la=setTimeout(()=>da(t),oa))},!0),document.addEventListener(`pointerleave`,e=>{e.target.closest?.(`[data-tooltip]`)&&fa()},!0),document.addEventListener(`pointerdown`,fa,!0)}function ma(e){return e.toLowerCase().endsWith(ie)}function ha(e){return Array.from(e).find(e=>ma(e.name))??null}function ga(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 _a(e){if(!e)return null;if(e.files){let t=ha(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&&ma(e.name))return e}return null}var va=new Map,ya=new Map;function ba(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 xa(e,t){let n=ba(e);va.set(n,t),setTimeout(()=>va.delete(n),1e4)}function Sa(e,t){ya.set(e,t),setTimeout(()=>ya.delete(e),1e4)}function Ca(e){let t=ya.get(e);return t?(ya.delete(e),t):null}function wa(e){let t=ba(e),n=va.get(t);return n?(va.delete(t),n):null}var Ta=class{registeredCommandsFn=null;constructor(e){this.vfs=e}setRegisteredCommandsFn(e){this.registeredCommandsFn=e}getVirtualBinCommands(){return this.registeredCommandsFn?.()??[]}async readFile(e,t){let n=R(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=R(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=R(e);if(typeof t==`string`){let e=wa(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=R(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=R(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=R(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=this.vfs.statSync(t);if(n)return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!!n.isSymlink,mode:n.type===`directory`?493:420,size:n.size,mtime:new Date(n.mtime)};let r=await this.vfs.stat(t);return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:!!r.isSymlink,mode:r.type===`directory`?493:420,size:r.size,mtime:new Date(r.mtime)}}async lstat(e){let t=R(e),n=this.vfs.lstatSync(t);if(n)return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`,mode:n.type===`directory`?493:n.type===`symlink`?511:420,size:n.size,mtime:new Date(n.mtime)};let r=await this.vfs.lstat(t);return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:r.type===`symlink`,mode:r.type===`directory`?493:r.type===`symlink`?511:420,size:r.size,mtime:new Date(r.mtime)}}async mkdir(e,t){await this.vfs.mkdir(R(e),t)}async readdir(e){let t=R(e);if(t===`/usr`)return[`bin`];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort();let n=this.vfs.readDirSync(t);return n===null?(await this.vfs.readDir(t)).map(e=>e.name):n.map(e=>e.name)}async readdirWithFileTypes(e){let t=R(e);if(t===`/usr`)return[{name:`bin`,isFile:!1,isDirectory:!0,isSymbolicLink:!1}];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort().map(e=>({name:e,isFile:!0,isDirectory:!1,isSymbolicLink:!1}));let n=this.vfs.readDirSync(t);if(n!==null){let e=[];for(let r of n)if(r.type===`symlink`){let n=t===`/`?`/${r.name}`:`${t}/${r.name}`,i=this.vfs.statSync(n);if(i)e.push({name:r.name,isFile:i.type===`file`,isDirectory:i.type===`directory`,isSymbolicLink:!0});else{let t=!1,i=!1;try{let e=await this.vfs.stat(n);t=e.type===`file`,i=e.type===`directory`}catch{}e.push({name:r.name,isFile:t,isDirectory:i,isSymbolicLink:!0})}}else e.push({name:r.name,isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:!1});return e}let r=await this.vfs.readDir(t),i=[];for(let e of r)if(e.type===`symlink`){let n=!1,r=!1;try{let i=t===`/`?`/${e.name}`:`${t}/${e.name}`,a=await this.vfs.stat(i);n=a.type===`file`,r=a.type===`directory`}catch{}i.push({name:e.name,isFile:n,isDirectory:r,isSymbolicLink:!0})}else i.push({name:e.name,isFile:e.type===`file`,isDirectory:e.type===`directory`,isSymbolicLink:!1});return i}async rm(e,t){await this.vfs.rm(R(e),t)}async cp(e,t,n){let r=R(e),i=R(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=ce(e,r.name),i=ce(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(R(e),R(t))}resolvePath(e,t){return t.startsWith(`/`)?R(t):R(ce(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){await this.vfs.symlink(e,R(t))}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){return this.vfs.readlink(R(e))}async realpath(e){return this.vfs.realpath(R(e))}async utimes(e,t,n){}},Ea=new TextDecoder;function Da(e){return typeof e==`string`?e:Ea.decode(e)}function Oa(e){return JSON.parse(Da(e))}function ka(e){if(typeof e!=`string`)return e;let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}var Aa=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(``)}})),ja=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}})),Ma=t((e=>{var t=Aa(),n=ja(),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(ye(e,ArrayBuffer)||e&&ye(e.buffer,ArrayBuffer)||typeof SharedArrayBuffer<`u`&&(ye(e,SharedArrayBuffer)||e&&ye(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(ye(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`||be(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(ye(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),ye(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(ye(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)||ye(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 me(e).length;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return n*2;case`hex`:return n>>>1;case`base64`:return _e(e).length;default:if(i)return r?-1:me(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 M(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 re(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(ye(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,be(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(be(r))return o;e[n+o]=r}return o}function T(e,t,n,r){return ve(me(t,e.length-n),e,n,r)}function E(e,t,n,r){return ve(he(t),e,n,r)}function D(e,t,n,r){return ve(_e(t),e,n,r)}function O(e,t,n,r){return ve(ge(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 M(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+=xe[e[r]];return i}function re(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 N(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||N(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||N(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||N(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||N(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||N(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Se(function(e){e>>>=0,ue(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&de(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=Se(function(e){e>>>=0,ue(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&de(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||N(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||N(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||N(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||N(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||N(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||N(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||N(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Se(function(e){e>>>=0,ue(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&de(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=Se(function(e){e>>>=0,ue(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&de(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||N(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||N(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||N(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||N(e,8,this.length),n.read(this,e,!1,52,8)};function P(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;P(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;P(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||P(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||P(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||P(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||P(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||P(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 F(e,t,n,r,i){R(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 ie(e,t,n,r,i){R(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=Se(function(e,t=0){return F(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeBigUInt64BE=Se(function(e,t=0){return ie(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);P(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);P(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||P(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||P(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||P(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||P(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||P(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=Se(function(e,t=0){return F(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))}),s.prototype.writeBigInt64BE=Se(function(e,t=0){return ie(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))});function I(e,t,n,r,i,a){if(n+r>e.length||n<0)throw RangeError(`Index out of range`)}function ae(e,t,r,i,a){return t=+t,r>>>=0,a||I(e,t,r,4,34028234663852886e22,-34028234663852886e22),n.write(e,t,r,i,23,4),r+4}s.prototype.writeFloatLE=function(e,t,n){return ae(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return ae(this,e,t,!1,n)};function L(e,t,r,i,a){return t=+t,r>>>=0,a||I(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 oe={};function se(e,t,n){oe[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}`}}}se(`ERR_BUFFER_OUT_OF_BOUNDS`,function(e){return e?`${e} is outside of buffer bounds`:`Attempt to access memory outside buffer bounds`},RangeError),se(`ERR_INVALID_ARG_TYPE`,function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),se(`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=ce(String(n)):typeof n==`bigint`&&(i=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(i=ce(i)),i+=`n`),r+=` It must be ${t}. Received ${i}`,r},RangeError);function ce(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 le(e,t,n){ue(t,`offset`),(e[t]===void 0||e[t+n]===void 0)&&de(t,e.length-(n+1))}function R(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 oe.ERR_OUT_OF_RANGE(`value`,i,e)}le(r,i,a)}function ue(e,t){if(typeof e!=`number`)throw new oe.ERR_INVALID_ARG_TYPE(t,`number`,e)}function de(e,t,n){throw Math.floor(e)===e?t<0?new oe.ERR_BUFFER_OUT_OF_BOUNDS:new oe.ERR_OUT_OF_RANGE(n||`offset`,`>= ${+!!n} and <= ${t}`,e):(ue(e,n),new oe.ERR_OUT_OF_RANGE(n||`offset`,`an integer`,e))}var fe=/[^+/0-9A-Za-z-_]/g;function pe(e){if(e=e.split(`=`)[0],e=e.trim().replace(fe,``),e.length<2)return``;for(;e.length%4!=0;)e+=`=`;return e}function me(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 he(e){let t=[];for(let n=0;n<e.length;++n)t.push(e.charCodeAt(n)&255);return t}function ge(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 _e(e){return t.toByteArray(pe(e))}function ve(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 ye(e,t){return e instanceof t||e!=null&&e.constructor!=null&&e.constructor.name!=null&&e.constructor.name===t.name}function be(e){return e!==e}var xe=(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 Se(e){return typeof BigInt>`u`?Ce:e}function Ce(){throw Error(`BigInt not supported`)}})),Na=Ma();globalThis.Buffer===void 0&&(globalThis.Buffer=Na.Buffer);var Pa=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})),Fa=t(((e,t)=>{t.exports=Pa()})),Ia=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}}})),La=t(((e,t)=>{var n=Ma(),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)}})),Ra=t(((e,t)=>{var n={}.toString;t.exports=Array.isArray||function(e){return n.call(e)==`[object Array]`}})),za=t(((e,t)=>{t.exports=TypeError})),Ba=t(((e,t)=>{t.exports=Object})),Va=t(((e,t)=>{t.exports=Error})),Ha=t(((e,t)=>{t.exports=EvalError})),Ua=t(((e,t)=>{t.exports=RangeError})),Wa=t(((e,t)=>{t.exports=ReferenceError})),Ga=t(((e,t)=>{t.exports=SyntaxError})),Ka=t(((e,t)=>{t.exports=URIError})),qa=t(((e,t)=>{t.exports=Math.abs})),Ja=t(((e,t)=>{t.exports=Math.floor})),Ya=t(((e,t)=>{t.exports=Math.max})),Xa=t(((e,t)=>{t.exports=Math.min})),Za=t(((e,t)=>{t.exports=Math.pow})),Qa=t(((e,t)=>{t.exports=Math.round})),$a=t(((e,t)=>{t.exports=Number.isNaN||function(e){return e!==e}})),eo=t(((e,t)=>{var n=$a();t.exports=function(e){return n(e)||e===0?e:e<0?-1:1}})),to=t(((e,t)=>{t.exports=Object.getOwnPropertyDescriptor})),no=t(((e,t)=>{var n=to();if(n)try{n([],`length`)}catch{n=null}t.exports=n})),ro=t(((e,t)=>{var n=Object.defineProperty||!1;if(n)try{n({},`a`,{value:1})}catch{n=!1}t.exports=n})),io=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}})),ao=t(((e,t)=>{var n=typeof Symbol<`u`&&Symbol,r=io();t.exports=function(){return typeof n!=`function`||typeof Symbol!=`function`||typeof n(`foo`)!=`symbol`||typeof Symbol(`bar`)!=`symbol`?!1:r()}})),oo=t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect.getPrototypeOf||null})),so=t(((e,t)=>{t.exports=Ba().getPrototypeOf||null})),co=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}})),lo=t(((e,t)=>{var n=co();t.exports=Function.prototype.bind||n})),uo=t(((e,t)=>{t.exports=Function.prototype.call})),fo=t(((e,t)=>{t.exports=Function.prototype.apply})),po=t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect&&Reflect.apply})),mo=t(((e,t)=>{var n=lo(),r=fo(),i=uo();t.exports=po()||n.call(i,r)})),ho=t(((e,t)=>{var n=lo(),r=za(),i=uo(),a=mo();t.exports=function(e){if(e.length<1||typeof e[0]!=`function`)throw new r(`a function is required`);return a(n,i,e)}})),go=t(((e,t)=>{var n=ho(),r=no(),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})),_o=t(((e,t)=>{var n=oo(),r=so(),i=go();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})),vo=t(((e,t)=>{var n=Function.prototype.call,r=Object.prototype.hasOwnProperty;t.exports=lo().call(n,r)})),yo=t(((e,t)=>{var n,r=Ba(),i=Va(),a=Ha(),o=Ua(),s=Wa(),c=Ga(),l=za(),u=Ka(),d=qa(),f=Ja(),p=Ya(),m=Xa(),h=Za(),g=Qa(),_=eo(),v=Function,y=function(e){try{return v(`"use strict"; return (`+e+`).constructor;`)()}catch{}},b=no(),x=ro(),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=ao()(),T=_o(),E=so(),D=oo(),O=fo(),k=uo(),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`]},M=lo(),re=vo(),N=M.call(k,Array.prototype.concat),P=M.call(O,Array.prototype.splice),F=M.call(k,String.prototype.replace),ie=M.call(k,String.prototype.slice),I=M.call(k,RegExp.prototype.exec),ae=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,L=/\\(\\)?/g,oe=function(e){var t=ie(e,0,1),n=ie(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 F(e,ae,function(e,t,n,i){r[r.length]=n?F(i,L,`$1`):t||e}),r},se=function(e,t){var n=e,r;if(re(ne,n)&&(r=ne[n],n=`%`+r[0]+`%`),re(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(I(/^%?[^%]*%?$/,e)===null)throw new c("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=oe(e),r=n.length>0?n[0]:``,i=se(`%`+r+`%`,t),a=i.name,o=i.value,s=!1,u=i.alias;u&&(r=u[0],P(n,N([0,1],u)));for(var d=1,f=!0;d<n.length;d+=1){var p=n[d],m=ie(p,0,1),h=ie(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+`%`,re(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=re(o,p),o=o[p];f&&!s&&(j[a]=o)}}return o}})),bo=t(((e,t)=>{var n=yo(),r=ho(),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}})),xo=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)}})),So=t(((e,t)=>{var n=xo(),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)}})),Co=t(((e,t)=>{t.exports=[`Float16Array`,`Float32Array`,`Float64Array`,`Int8Array`,`Int16Array`,`Int32Array`,`Uint8Array`,`Uint8ClampedArray`,`Uint16Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`]})),wo=t(((e,t)=>{var n=Co(),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}})),To=t(((e,t)=>{var n=ro(),r=Ga(),i=za(),a=no();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.`)}})),Eo=t(((e,t)=>{var n=ro(),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})),Do=t(((e,t)=>{var n=yo(),r=To(),i=Eo()(),a=no(),o=za(),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}})),Oo=t(((e,t)=>{var n=lo(),r=fo(),i=mo();t.exports=function(){return i(n,r,arguments)}})),ko=t(((e,t)=>{var n=Do(),r=ro(),i=ho(),a=Oo();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})),Ao=t(((e,t)=>{var n=io();t.exports=function(){return n()&&!!Symbol.toStringTag}})),jo=t(((e,t)=>{var n=So(),r=wo(),i=ko(),a=bo(),o=no(),s=_o(),c=a(`Object.prototype.toString`),l=Ao()(),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}})),Mo=t(((e,t)=>{var n=jo();t.exports=function(e){return!!n(e)}})),No=t(((e,t)=>{var n=za(),r=bo()(`TypedArray.prototype.buffer`,!0),i=Mo();t.exports=r||function(e){if(!i(e))throw new n(`Not a Typed Array`);return e.buffer}})),Po=t(((e,t)=>{var n=La().Buffer,r=Ra(),i=No(),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.`)}})),Fo=t(((e,t)=>{var n=La().Buffer,r=Po();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})),Io=t(((e,t)=>{var n=Ia(),r=Fo(),i=La().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})),Lo=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})})),Ro=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}})),zo=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)}})),Bo=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}}})),Vo=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)}}}})),Ho=t(((e,t)=>{var n=Vo();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})),Uo=e(Fa(),1),Wo=e(Io(),1),Go=e(Lo(),1),Ko=e(Je(),1),qo=e(Ro(),1),Jo=e(zo(),1),Yo=e(Bo(),1),Xo=e(Ho(),1),U=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}},Zo=class e extends U{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}}};Zo.code=`UnmergedPathsError`;var W=class e extends U{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}}};W.code=`InternalError`;var Qo=class e extends U{constructor(t){super(`The filepath "${t}" contains unsafe character sequences`),this.code=this.name=e.code,this.data={filepath:t}}};Qo.code=`UnsafeFilepathError`;var $o=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 es(e,t){return-(e<t)||+(e>t)}function ts(e,t){return es(e.path,t.path)}function ns(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 rs=2**32;function is(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 as(e){let[t,n]=is(e.ctimeSeconds,e.ctimeNanoseconds,e.ctimeMs,e.ctime),[r,i]=is(e.mtimeSeconds,e.mtimeNanoseconds,e.mtimeMs,e.mtime);return{ctimeSeconds:t%rs,ctimeNanoseconds:n%rs,mtimeSeconds:r%rs,mtimeNanoseconds:i%rs,dev:e.dev%rs,ino:e.ino%rs,mode:ns(e.mode%rs),uid:e.uid%rs,gid:e.gid%rs,size:e.size>-1?e.size%rs:0}}function os(e){let t=``;for(let n of new Uint8Array(e))n<16&&(t+=`0`),t+=n.toString(16);return t}var ss=null;async function cs(e){return ss===null&&(ss=await ds()),ss?us(e):ls(e)}function ls(e){return new Wo.default().update(e).digest(`hex`)}async function us(e){return os(await crypto.subtle.digest(`SHA-1`,e))}async function ds(){try{return await us(new Uint8Array([]))===`da39a3ee5e6b4b0d3255bfef95601890afd80709`}catch{}return!1}function fs(e){return{assumeValid:!!(e&32768),extended:!!(e&16384),stage:(e&12288)>>12,nameLength:e&4095}}function ps(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 ms=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 W(`invalid type passed to GitIndex.from`)}static async fromBuffer(t){if(t.length===0)throw new W(`Index file is empty (.git/index)`);let n=new e,r=new $o(t),i=r.toString(`utf8`,4);if(i!==`DIRC`)throw new W(`Invalid dircache magic file number: ${i}`);let a=await cs(t.slice(0,-20)),o=t.slice(-20).toString(`hex`);if(o!==a)throw new W(`Invalid checksum in GitIndex buffer: expected ${o} but saw ${a}`);let s=r.readUInt32BE();if(s!==2)throw new W(`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=fs(r.readUInt16BE());let i=t.indexOf(0,r.tell()+1)-r.tell();if(i<1)throw new W(`Got a path length of: ${i}`);if(e.path=r.toString(`utf8`,i),e.path.includes(`..\\`)||e.path.includes(`../`))throw new Qo(e.path);let a=8-(r.tell()-12)%8;for(a===0&&(a=8);a--;){let t=r.readUInt8();if(t!==0)throw new W(`Expected 1-8 null characters but got '${t}' after ${e.path}`);if(r.eof())throw new W(`Unexpected end of file`)}e.stages=[],n._addEntry(e),l++}return n}get unmergedPaths(){return[...this._unmergedPaths]}get entries(){return[...this._entries.values()].sort(ts)}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=as(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(`
728
+ `,document.head.appendChild(e)}},Bi=[{id:`chat`,label:`Chat`},{id:`terminal`,label:`Terminal`},{id:`files`,label:`Files`},{id:`memory`,label:`Memory`}],Vi=`slicc-hidden-tabs`,Hi=[`terminal`,`memory`];function Ui(){try{let e=localStorage.getItem(Vi);return e?new Set(JSON.parse(e)):new Set(Hi)}catch{return new Set(Hi)}}function Wi(e){let t=e.filter(e=>e!==`chat`);localStorage.setItem(Vi,JSON.stringify(t))}var Gi=Bi.filter(e=>!Ui().has(e.id)),Ki=`chat`,qi=new Set(Bi.map(e=>e.id));function Ji(e){return qi.has(e)}var Yi=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}},Xi=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 Zi(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=Qi(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=Qi(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 Qi(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 $i=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;headerHamburger=null;panels;registry=new Xi;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));Wi(e?[]:[`terminal`,`memory`])}buildHeader(e){let t=document.createElement(`div`);t.className=`header`;let n=()=>{if(C())return;let e=A();for(let t of e)if(t.models.length>0){let{defaultModelId:e}=E(t.providerId),n=(e?t.models.find(t=>t.id.toLowerCase().includes(e.toLowerCase())):void 0)??t.models[0];b(`${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`);if(i.className=`header__brand`,this.isExtension){let e=this.sliccLogo(24);i.appendChild(e)}else{let e=document.createElement(`button`);e.className=`scoops-hamburger`,e.dataset.tooltip=`Toggle navigation`,e.dataset.tooltipPos=`right`,e.setAttribute(`aria-label`,`Toggle navigation`),e.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>`,this.headerHamburger=e,e.addEventListener(`click`,()=>{this.panels?.scoops?.toggleExpanded(),e.innerHTML=this.scoopsEl?.classList.contains(`layout__scoops--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>`}),i.appendChild(e)}let a=document.createElement(`div`);a.className=`header__title`,a.textContent=`slicc`,i.appendChild(a),r.appendChild(i),this.isExtension&&(this.scoopSwitcherEl=document.createElement(`div`),this.scoopSwitcherEl.className=`scoop-switcher`,this.scoopSwitcher=new zi(this.scoopSwitcherEl,{onScoopSelect:e=>this.onScoopSelect?.(e),onDeleteScoop:e=>{this.panels?.scoops?.deleteScoop?.(e)}}),r.appendChild(this.scoopSwitcherEl));let o=document.createElement(`div`);o.className=`header__spacer`,r.appendChild(o),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=k().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=k(),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=E(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`,()=>{ae(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(),T()||te(),await re()&&(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 Yi(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 Gi){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 Ei(n),terminal:new Di(r,{onClearTerminal:()=>{this.panels.terminal.clearTerminal()}}),fileBrowser:new Fi(i,{onRunCommand:async e=>{await this.runFileBrowserCommand(e),this.extensionZone.activateTab(`terminal`)}}),memory:new Ii(a),scoops:new Ri(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&&Zi(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 Yi(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 Ei(o),terminal:new Di(this.terminalContainer,{onClearTerminal:()=>{this.panels.terminal.clearTerminal(),this.openTerminal()}}),fileBrowser:new Fi(u,{onRunCommand:async e=>{await this.runFileBrowserCommand(e),this.openTerminal()}}),memory:new Ii(d),scoops:new Ri(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));Zi(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.panels.scoops.dispose();this.root.firstChild;)this.root.removeChild(this.root.firstChild)}},ea=`slicc-theme`,ta=new Set([`dark`,`light`,`system`]);function na(){let e=localStorage.getItem(ea);return e&&ta.has(e)?e:`system`}function ra(){let e=na(),t=e===`light`;e===`system`&&(t=window.matchMedia?.(`(prefers-color-scheme: light)`).matches??!1),document.documentElement.classList.toggle(`theme-light`,t)}var ia;function aa(){ra(),ia=window.matchMedia?.(`(prefers-color-scheme: light)`),ia?.addEventListener?.(`change`,()=>{na()===`system`&&ra()})}var oa=300,sa=6,ca=null,la=null;function ua(){return ca||(ca=document.createElement(`div`),ca.className=`s2-tooltip`,document.body.appendChild(ca)),ca}function da(e){let t=e.getAttribute(`data-tooltip`);if(!t)return;let n=ua();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-sa,s=r.left+r.width/2-i.width/2):a===`right`?(o=r.top+r.height/2-i.height/2,s=r.right+sa):(o=r.bottom+sa,s=r.left+r.width/2-i.width/2),a===`bottom`&&o+i.height>window.innerHeight-4?o=r.top-i.height-sa:a===`top`&&o<4&&(o=r.bottom+sa),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 fa(){la&&=(clearTimeout(la),null),ca?.classList.remove(`s2-tooltip--visible`)}function pa(){document.addEventListener(`pointerenter`,e=>{let t=e.target.closest?.(`[data-tooltip]`);t&&(fa(),la=setTimeout(()=>da(t),oa))},!0),document.addEventListener(`pointerleave`,e=>{e.target.closest?.(`[data-tooltip]`)&&fa()},!0),document.addEventListener(`pointerdown`,fa,!0)}function ma(e){return e.toLowerCase().endsWith(oe)}function ha(e){return Array.from(e).find(e=>ma(e.name))??null}function ga(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 _a(e){if(!e)return null;if(e.files){let t=ha(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&&ma(e.name))return e}return null}var va=new Map,ya=new Map;function ba(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 xa(e,t){let n=ba(e);va.set(n,t),setTimeout(()=>va.delete(n),1e4)}function Sa(e,t){ya.set(e,t),setTimeout(()=>ya.delete(e),1e4)}function Ca(e){let t=ya.get(e);return t?(ya.delete(e),t):null}function wa(e){let t=ba(e),n=va.get(t);return n?(va.delete(t),n):null}var Ta=class{registeredCommandsFn=null;constructor(e){this.vfs=e}setRegisteredCommandsFn(e){this.registeredCommandsFn=e}getVirtualBinCommands(){return this.registeredCommandsFn?.()??[]}async readFile(e,t){let n=L(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=L(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=L(e);if(typeof t==`string`){let e=wa(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=L(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 I&&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=L(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=L(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=this.vfs.statSync(t);if(n)return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!!n.isSymlink,mode:n.type===`directory`?493:420,size:n.size,mtime:new Date(n.mtime)};let r=await this.vfs.stat(t);return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:!!r.isSymlink,mode:r.type===`directory`?493:420,size:r.size,mtime:new Date(r.mtime)}}async lstat(e){let t=L(e),n=this.vfs.lstatSync(t);if(n)return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`,mode:n.type===`directory`?493:n.type===`symlink`?511:420,size:n.size,mtime:new Date(n.mtime)};let r=await this.vfs.lstat(t);return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:r.type===`symlink`,mode:r.type===`directory`?493:r.type===`symlink`?511:420,size:r.size,mtime:new Date(r.mtime)}}async mkdir(e,t){await this.vfs.mkdir(L(e),t)}async readdir(e){let t=L(e);if(t===`/usr`)return[`bin`];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort();let n=this.vfs.readDirSync(t);return n===null?(await this.vfs.readDir(t)).map(e=>e.name):n.map(e=>e.name)}async readdirWithFileTypes(e){let t=L(e);if(t===`/usr`)return[{name:`bin`,isFile:!1,isDirectory:!0,isSymbolicLink:!1}];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort().map(e=>({name:e,isFile:!0,isDirectory:!1,isSymbolicLink:!1}));let n=this.vfs.readDirSync(t);if(n!==null){let e=[];for(let r of n)if(r.type===`symlink`){let n=t===`/`?`/${r.name}`:`${t}/${r.name}`,i=this.vfs.statSync(n);if(i)e.push({name:r.name,isFile:i.type===`file`,isDirectory:i.type===`directory`,isSymbolicLink:!0});else{let t=!1,i=!1;try{let e=await this.vfs.stat(n);t=e.type===`file`,i=e.type===`directory`}catch{}e.push({name:r.name,isFile:t,isDirectory:i,isSymbolicLink:!0})}}else e.push({name:r.name,isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:!1});return e}let r=await this.vfs.readDir(t),i=[];for(let e of r)if(e.type===`symlink`){let n=!1,r=!1;try{let i=t===`/`?`/${e.name}`:`${t}/${e.name}`,a=await this.vfs.stat(i);n=a.type===`file`,r=a.type===`directory`}catch{}i.push({name:e.name,isFile:n,isDirectory:r,isSymbolicLink:!0})}else i.push({name:e.name,isFile:e.type===`file`,isDirectory:e.type===`directory`,isSymbolicLink:!1});return i}async rm(e,t){await this.vfs.rm(L(e),t)}async cp(e,t,n){let r=L(e),i=L(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new I(`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=le(e,r.name),i=le(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(L(e),L(t))}resolvePath(e,t){return t.startsWith(`/`)?L(t):L(le(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){await this.vfs.symlink(e,L(t))}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){return this.vfs.readlink(L(e))}async realpath(e){return this.vfs.realpath(L(e))}async utimes(e,t,n){}},Ea=new TextDecoder;function Da(e){return typeof e==`string`?e:Ea.decode(e)}function Oa(e){return JSON.parse(Da(e))}function ka(e){if(typeof e!=`string`)return e;let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}var Aa=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(``)}})),ja=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}})),Ma=t((e=>{var t=Aa(),n=ja(),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(be(e,ArrayBuffer)||e&&be(e.buffer,ArrayBuffer)||typeof SharedArrayBuffer<`u`&&(be(e,SharedArrayBuffer)||e&&be(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(be(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`||xe(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(be(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),be(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(be(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)||be(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 he(e).length;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return n*2;case`hex`:return n>>>1;case`base64`:return ve(e).length;default:if(i)return r?-1:he(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 ie(this,t,n);case`utf8`:case`utf-8`:return k(this,t,n);case`ascii`:return ne(this,t,n);case`latin1`:case`binary`:return re(this,t,n);case`base64`:return O(this,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return ae(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?k(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(be(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,xe(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(xe(r))return o;e[n+o]=r}return o}function T(e,t,n,r){return ye(he(t,e.length-n),e,n,r)}function E(e,t,n,r){return ye(ge(t),e,n,r)}function D(e,t,n,r){return ye(ve(t),e,n,r)}function ee(e,t,n,r){return ye(_e(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 ee(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 O(e,n,r){return n===0&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function k(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 A(r)}var te=4096;function A(e){let t=e.length;if(t<=te)return String.fromCharCode.apply(String,e);let n=``,r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=te));return n}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]&127);return r}function re(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 ie(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+=Se[e[r]];return i}function ae(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 j(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||j(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||j(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||j(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||j(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||j(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||j(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||j(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Ce(function(e){e>>>=0,de(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&fe(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=Ce(function(e){e>>>=0,de(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&fe(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||j(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||j(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||j(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||j(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||j(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||j(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||j(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Ce(function(e){e>>>=0,de(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&fe(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=Ce(function(e){e>>>=0,de(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&fe(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||j(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||j(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||j(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||j(e,8,this.length),n.read(this,e,!1,52,8)};function M(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;M(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;M(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||M(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||M(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||M(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||M(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||M(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 N(e,t,n,r,i){L(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 oe(e,t,n,r,i){L(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=Ce(function(e,t=0){return N(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeBigUInt64BE=Ce(function(e,t=0){return oe(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);M(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);M(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||M(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||M(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||M(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||M(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||M(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=Ce(function(e,t=0){return N(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))}),s.prototype.writeBigInt64BE=Ce(function(e,t=0){return oe(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))});function P(e,t,n,r,i,a){if(n+r>e.length||n<0)throw RangeError(`Index out of range`)}function se(e,t,r,i,a){return t=+t,r>>>=0,a||P(e,t,r,4,34028234663852886e22,-34028234663852886e22),n.write(e,t,r,i,23,4),r+4}s.prototype.writeFloatLE=function(e,t,n){return se(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return se(this,e,t,!1,n)};function F(e,t,r,i,a){return t=+t,r>>>=0,a||P(e,t,r,8,17976931348623157e292,-17976931348623157e292),n.write(e,t,r,i,52,8),r+8}s.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return F(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 I={};function ce(e,t,n){I[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}`}}}ce(`ERR_BUFFER_OUT_OF_BOUNDS`,function(e){return e?`${e} is outside of buffer bounds`:`Attempt to access memory outside buffer bounds`},RangeError),ce(`ERR_INVALID_ARG_TYPE`,function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),ce(`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=le(String(n)):typeof n==`bigint`&&(i=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(i=le(i)),i+=`n`),r+=` It must be ${t}. Received ${i}`,r},RangeError);function le(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 ue(e,t,n){de(t,`offset`),(e[t]===void 0||e[t+n]===void 0)&&fe(t,e.length-(n+1))}function L(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 I.ERR_OUT_OF_RANGE(`value`,i,e)}ue(r,i,a)}function de(e,t){if(typeof e!=`number`)throw new I.ERR_INVALID_ARG_TYPE(t,`number`,e)}function fe(e,t,n){throw Math.floor(e)===e?t<0?new I.ERR_BUFFER_OUT_OF_BOUNDS:new I.ERR_OUT_OF_RANGE(n||`offset`,`>= ${+!!n} and <= ${t}`,e):(de(e,n),new I.ERR_OUT_OF_RANGE(n||`offset`,`an integer`,e))}var pe=/[^+/0-9A-Za-z-_]/g;function me(e){if(e=e.split(`=`)[0],e=e.trim().replace(pe,``),e.length<2)return``;for(;e.length%4!=0;)e+=`=`;return e}function he(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 ge(e){let t=[];for(let n=0;n<e.length;++n)t.push(e.charCodeAt(n)&255);return t}function _e(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 ve(e){return t.toByteArray(me(e))}function ye(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 be(e,t){return e instanceof t||e!=null&&e.constructor!=null&&e.constructor.name!=null&&e.constructor.name===t.name}function xe(e){return e!==e}var Se=(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 Ce(e){return typeof BigInt>`u`?we:e}function we(){throw Error(`BigInt not supported`)}})),Na=Ma();globalThis.Buffer===void 0&&(globalThis.Buffer=Na.Buffer);var Pa=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})),Fa=t(((e,t)=>{t.exports=Pa()})),Ia=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}}})),La=t(((e,t)=>{var n=Ma(),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)}})),Ra=t(((e,t)=>{var n={}.toString;t.exports=Array.isArray||function(e){return n.call(e)==`[object Array]`}})),za=t(((e,t)=>{t.exports=TypeError})),Ba=t(((e,t)=>{t.exports=Object})),Va=t(((e,t)=>{t.exports=Error})),Ha=t(((e,t)=>{t.exports=EvalError})),Ua=t(((e,t)=>{t.exports=RangeError})),Wa=t(((e,t)=>{t.exports=ReferenceError})),Ga=t(((e,t)=>{t.exports=SyntaxError})),Ka=t(((e,t)=>{t.exports=URIError})),qa=t(((e,t)=>{t.exports=Math.abs})),Ja=t(((e,t)=>{t.exports=Math.floor})),Ya=t(((e,t)=>{t.exports=Math.max})),Xa=t(((e,t)=>{t.exports=Math.min})),Za=t(((e,t)=>{t.exports=Math.pow})),Qa=t(((e,t)=>{t.exports=Math.round})),$a=t(((e,t)=>{t.exports=Number.isNaN||function(e){return e!==e}})),eo=t(((e,t)=>{var n=$a();t.exports=function(e){return n(e)||e===0?e:e<0?-1:1}})),to=t(((e,t)=>{t.exports=Object.getOwnPropertyDescriptor})),no=t(((e,t)=>{var n=to();if(n)try{n([],`length`)}catch{n=null}t.exports=n})),ro=t(((e,t)=>{var n=Object.defineProperty||!1;if(n)try{n({},`a`,{value:1})}catch{n=!1}t.exports=n})),io=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}})),ao=t(((e,t)=>{var n=typeof Symbol<`u`&&Symbol,r=io();t.exports=function(){return typeof n!=`function`||typeof Symbol!=`function`||typeof n(`foo`)!=`symbol`||typeof Symbol(`bar`)!=`symbol`?!1:r()}})),oo=t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect.getPrototypeOf||null})),so=t(((e,t)=>{t.exports=Ba().getPrototypeOf||null})),co=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}})),lo=t(((e,t)=>{var n=co();t.exports=Function.prototype.bind||n})),uo=t(((e,t)=>{t.exports=Function.prototype.call})),fo=t(((e,t)=>{t.exports=Function.prototype.apply})),po=t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect&&Reflect.apply})),mo=t(((e,t)=>{var n=lo(),r=fo(),i=uo();t.exports=po()||n.call(i,r)})),ho=t(((e,t)=>{var n=lo(),r=za(),i=uo(),a=mo();t.exports=function(e){if(e.length<1||typeof e[0]!=`function`)throw new r(`a function is required`);return a(n,i,e)}})),go=t(((e,t)=>{var n=ho(),r=no(),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})),_o=t(((e,t)=>{var n=oo(),r=so(),i=go();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})),vo=t(((e,t)=>{var n=Function.prototype.call,r=Object.prototype.hasOwnProperty;t.exports=lo().call(n,r)})),yo=t(((e,t)=>{var n,r=Ba(),i=Va(),a=Ha(),o=Ua(),s=Wa(),c=Ga(),l=za(),u=Ka(),d=qa(),f=Ja(),p=Ya(),m=Xa(),h=Za(),g=Qa(),_=eo(),v=Function,y=function(e){try{return v(`"use strict"; return (`+e+`).constructor;`)()}catch{}},b=no(),x=ro(),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=ao()(),T=_o(),E=so(),D=oo(),ee=fo(),O=uo(),k={},te=typeof Uint8Array>`u`||!T?n:T(Uint8Array),A={__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%":k,"%AsyncGenerator%":k,"%AsyncGeneratorFunction%":k,"%AsyncIteratorPrototype%":k,"%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%":k,"%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%":te,"%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%":O,"%Function.prototype.apply%":ee,"%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){A[`%Error.prototype%`]=T(T(e))}var ne=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 A[t]=n,n},re={__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`]},ie=lo(),ae=vo(),j=ie.call(O,Array.prototype.concat),M=ie.call(ee,Array.prototype.splice),N=ie.call(O,String.prototype.replace),oe=ie.call(O,String.prototype.slice),P=ie.call(O,RegExp.prototype.exec),se=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,F=/\\(\\)?/g,I=function(e){var t=oe(e,0,1),n=oe(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 N(e,se,function(e,t,n,i){r[r.length]=n?N(i,F,`$1`):t||e}),r},ce=function(e,t){var n=e,r;if(ae(re,n)&&(r=re[n],n=`%`+r[0]+`%`),ae(A,n)){var i=A[n];if(i===k&&(i=ne(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(P(/^%?[^%]*%?$/,e)===null)throw new c("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=I(e),r=n.length>0?n[0]:``,i=ce(`%`+r+`%`,t),a=i.name,o=i.value,s=!1,u=i.alias;u&&(r=u[0],M(n,j([0,1],u)));for(var d=1,f=!0;d<n.length;d+=1){var p=n[d],m=oe(p,0,1),h=oe(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+`%`,ae(A,a))o=A[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=ae(o,p),o=o[p];f&&!s&&(A[a]=o)}}return o}})),bo=t(((e,t)=>{var n=yo(),r=ho(),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}})),xo=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)}})),So=t(((e,t)=>{var n=xo(),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)}})),Co=t(((e,t)=>{t.exports=[`Float16Array`,`Float32Array`,`Float64Array`,`Int8Array`,`Int16Array`,`Int32Array`,`Uint8Array`,`Uint8ClampedArray`,`Uint16Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`]})),wo=t(((e,t)=>{var n=Co(),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}})),To=t(((e,t)=>{var n=ro(),r=Ga(),i=za(),a=no();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.`)}})),Eo=t(((e,t)=>{var n=ro(),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})),Do=t(((e,t)=>{var n=yo(),r=To(),i=Eo()(),a=no(),o=za(),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}})),Oo=t(((e,t)=>{var n=lo(),r=fo(),i=mo();t.exports=function(){return i(n,r,arguments)}})),ko=t(((e,t)=>{var n=Do(),r=ro(),i=ho(),a=Oo();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})),Ao=t(((e,t)=>{var n=io();t.exports=function(){return n()&&!!Symbol.toStringTag}})),jo=t(((e,t)=>{var n=So(),r=wo(),i=ko(),a=bo(),o=no(),s=_o(),c=a(`Object.prototype.toString`),l=Ao()(),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}})),Mo=t(((e,t)=>{var n=jo();t.exports=function(e){return!!n(e)}})),No=t(((e,t)=>{var n=za(),r=bo()(`TypedArray.prototype.buffer`,!0),i=Mo();t.exports=r||function(e){if(!i(e))throw new n(`Not a Typed Array`);return e.buffer}})),Po=t(((e,t)=>{var n=La().Buffer,r=Ra(),i=No(),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.`)}})),Fo=t(((e,t)=>{var n=La().Buffer,r=Po();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})),Io=t(((e,t)=>{var n=Ia(),r=Fo(),i=La().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})),Lo=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})})),Ro=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}})),zo=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)},ee=(e,t)=>{throw new t(e)},O=(e,t,n)=>C(e)?e?O.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),k=e=>d.test(e);O.isNotRelative=k,O.convert=e=>e;var te=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&&O.convert(e);return O(i,e,this._allowRelativePaths?_:ee),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)}},A=e=>new te(e);if(A.isPathValid=e=>O(e&&O.convert(e),e,_),A.default=A,t.exports=A,typeof process<`u`&&({}.IGNORE_TEST_WIN32||process.platform===`win32`)){O.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;O.isNotRelative=t=>e.test(t)||k(t)}})),Bo=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}}})),Vo=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)}}}})),Ho=t(((e,t)=>{var n=Vo();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]),ee=y[2][1]+(g-y[2][3]);l.push([-1,T,E-T,h,g-h,D,ee-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})),Uo=e(Fa(),1),Wo=e(Io(),1),Go=e(Lo(),1),Ko=e(Je(),1),qo=e(Ro(),1),Jo=e(zo(),1),Yo=e(Bo(),1),Xo=e(Ho(),1),U=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}},Zo=class e extends U{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}}};Zo.code=`UnmergedPathsError`;var W=class e extends U{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}}};W.code=`InternalError`;var Qo=class e extends U{constructor(t){super(`The filepath "${t}" contains unsafe character sequences`),this.code=this.name=e.code,this.data={filepath:t}}};Qo.code=`UnsafeFilepathError`;var $o=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 es(e,t){return-(e<t)||+(e>t)}function ts(e,t){return es(e.path,t.path)}function ns(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 rs=2**32;function is(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 as(e){let[t,n]=is(e.ctimeSeconds,e.ctimeNanoseconds,e.ctimeMs,e.ctime),[r,i]=is(e.mtimeSeconds,e.mtimeNanoseconds,e.mtimeMs,e.mtime);return{ctimeSeconds:t%rs,ctimeNanoseconds:n%rs,mtimeSeconds:r%rs,mtimeNanoseconds:i%rs,dev:e.dev%rs,ino:e.ino%rs,mode:ns(e.mode%rs),uid:e.uid%rs,gid:e.gid%rs,size:e.size>-1?e.size%rs:0}}function os(e){let t=``;for(let n of new Uint8Array(e))n<16&&(t+=`0`),t+=n.toString(16);return t}var ss=null;async function cs(e){return ss===null&&(ss=await ds()),ss?us(e):ls(e)}function ls(e){return new Wo.default().update(e).digest(`hex`)}async function us(e){return os(await crypto.subtle.digest(`SHA-1`,e))}async function ds(){try{return await us(new Uint8Array([]))===`da39a3ee5e6b4b0d3255bfef95601890afd80709`}catch{}return!1}function fs(e){return{assumeValid:!!(e&32768),extended:!!(e&16384),stage:(e&12288)>>12,nameLength:e&4095}}function ps(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 ms=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 W(`invalid type passed to GitIndex.from`)}static async fromBuffer(t){if(t.length===0)throw new W(`Index file is empty (.git/index)`);let n=new e,r=new $o(t),i=r.toString(`utf8`,4);if(i!==`DIRC`)throw new W(`Invalid dircache magic file number: ${i}`);let a=await cs(t.slice(0,-20)),o=t.slice(-20).toString(`hex`);if(o!==a)throw new W(`Invalid checksum in GitIndex buffer: expected ${o} but saw ${a}`);let s=r.readUInt32BE();if(s!==2)throw new W(`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=fs(r.readUInt16BE());let i=t.indexOf(0,r.tell()+1)-r.tell();if(i<1)throw new W(`Got a path length of: ${i}`);if(e.path=r.toString(`utf8`,i),e.path.includes(`..\\`)||e.path.includes(`../`))throw new Qo(e.path);let a=8-(r.tell()-12)%8;for(a===0&&(a=8);a--;){let t=r.readUInt8();if(t!==0)throw new W(`Expected 1-8 null characters but got '${t}' after ${e.path}`);if(r.eof())throw new W(`Unexpected end of file`)}e.stages=[],n._addEntry(e),l++}return n}get unmergedPaths(){return[...this._unmergedPaths]}get entries(){return[...this._entries.values()].sort(ts)}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=as(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(`
729
729
  `)}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 $o(r),a=as(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(ps(e)),i.write(e.path,t.length,`utf8`),r}async toObject(){let t=Buffer.alloc(12),n=new $o(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 cs(a);return Buffer.concat([a,Buffer.from(o,`hex`)])}};function hs(e,t,n=!0,r=!0){let i=as(e),a=as(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 gs=null,_s=Symbol(`IndexCache`);function vs(){return{map:new Map,stats:new Map}}async function ys(e,t,n){let[r,i]=await Promise.all([e.lstat(t),e.read(t)]),a=await ms.from(i);n.map.set(t,a),n.stats.set(t,r)}async function bs(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:hs(r,i)}var xs=class{static async acquire({fs:e,gitdir:t,cache:n,allowUnmerged:r=!0},i){n[_s]||(n[_s]=vs());let a=`${t}/index`;gs===null&&(gs=new Uo.default({maxPending:1/0}));let o,s=[];return await gs.acquire(a,async()=>{let t=n[_s];await bs(e,a,t)&&await ys(e,a,t);let c=t.map.get(a);if(s=c.unmergedPaths,s.length&&!r)throw new Zo(s);if(o=await i(c),c._dirty){let n=await c.toObject();await e.write(a,n),t.stats.set(a,await e.lstat(a)),c._dirty=!1}}),o}};function Ss(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t>-1&&(e=e.slice(t+1)),e}function Cs(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t===-1?`.`:t===0?`/`:e.slice(0,t)}function ws(e){let t=new Map,n=function(e){if(!t.has(e)){let r={type:`tree`,fullpath:e,basename:Ss(e),metadata:{},children:[]};t.set(e,r),r.parent=n(Cs(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:Ss(e),metadata:r,parent:n(Cs(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 Ts(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 W(`Unexpected GitTree entry mode: ${e.toString(8)}`)}var Es=class{constructor({fs:e,gitdir:t,cache:n}){this.treePromise=xs.acquire({fs:e,gitdir:t,cache:n},async function(e){return ws(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(es),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`?{}:as(t.metadata);e._type=t.type===`tree`?`tree`:Ts(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}},Ds=Symbol(`GitWalkSymbol`);function Os(){let e=Object.create(null);return Object.defineProperty(e,Ds,{value:function({fs:e,gitdir:t,cache:n}){return new Es({fs:e,gitdir:t,cache:n})}}),Object.freeze(e),e}var ks=class e extends U{constructor(t){super(`Could not find ${t}.`),this.code=this.name=e.code,this.data={what:t}}};ks.code=`NotFoundError`;var As=class e extends U{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}}};As.code=`ObjectTypeError`;var js=class e extends U{constructor(t){super(`Expected a 40-char hex object id but saw "${t}".`),this.code=this.name=e.code,this.data={value:t}}};js.code=`InvalidOidError`;var Ms=class e extends U{constructor(t){super(`Could not find a fetch refspec for remote "${t}". Make sure the config file has an entry like the following:
730
730
  [remote "${t}"]
731
731
  \tfetch = +refs/heads/*:refs/remotes/origin/*
@@ -779,7 +779,7 @@ gpgsig`+Sl(o)+`
779
779
  `)+`
780
780
  `;await Xu.acquire(r,async function(){await e.write(r,t,{encoding:`utf8`})})}else await Xu.acquire(r,async function(){await e.rm(r)})}};async function Qu({fs:e,gitdir:t,oid:n}){let r=`objects/${n.slice(0,2)}/${n.slice(2)}`;return e.exists(`${t}/${r}`)}async function $u({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:i}){let a=await e.readdir(G(n,`objects/pack`));a=a.filter(e=>e.endsWith(`.idx`));for(let o of a){let a=await Ic({fs:e,cache:t,filename:`${n}/objects/pack/${o}`,getExternalRefDelta:i});if(a.error)throw new W(a.error);if(a.offsets.has(r))return!0}return!1}async function ed({fs:e,cache:t,gitdir:n,oid:r,format:i=`content`}){let a=r=>zc({fs:e,cache:t,gitdir:n,oid:r}),o=await Qu({fs:e,gitdir:n,oid:r});return o||=await $u({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:a}),o}function td(e){return e.slice(0,12).toString(`hex`)===`5041434b0000000200000000`}function nd(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 rd={name:`isomorphic-git`,version:`1.37.5`,agent:`git/isomorphic-git@1.37.5`},id=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 ad(e){let t=e.indexOf(`\r`),n=e.indexOf(`
781
781
  `);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 od(e){let t=new id,n=``;return(async()=>{await Iu(e,e=>{for(e=e.toString(`utf8`),n+=e;;){let e=ad(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 sd=class{static demux(e){let t=Bu.streamReader(e),n=new id,r=new id,i=new id,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 cd(e){let{packetlines:t,packfile:n,progress:r}=sd.demux(e),i=[],a=[],o=[],s=!1,c=!1;return new Promise((l,u)=>{Iu(t,t=>{let d=t.toString(`utf8`).trim();if(d.startsWith(`shallow`)){let e=d.slice(-41).trim();e.length!==40&&u(new js(e)),i.push(e)}else if(d.startsWith(`unshallow`)){let e=d.slice(-41).trim();e.length!==40&&u(new js(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 ld({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(Bu.encode(`want ${e}${c}\n`)),c=``;for(let e of r)s.push(Bu.encode(`shallow ${e}\n`));i!==null&&s.push(Bu.encode(`deepen ${i}\n`)),a!==null&&s.push(Bu.encode(`deepen-since ${Math.floor(a.valueOf()/1e3)}\n`));for(let e of o)s.push(Bu.encode(`deepen-not ${e}\n`));s.push(Bu.flush());for(let e of n)s.push(Bu.encode(`have ${e}\n`));return s.push(Bu.encode(`done
782
- `)),s}async function ud({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 Nu({fs:e,gitdir:c,test:!0}),w=await rc.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 nl(`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=Ju.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}),ee=k.auth,A=k.refs;if(A.size===0)return{defaultBranch:null,fetchHead:null,fetchHeadDescription:null};if(m!==null&&!k.capabilities.has(`shallow`))throw new ol(`shallow`,`depth`);if(h!==null&&!k.capabilities.has(`deepen-since`))throw new ol(`deepen-since`,`since`);if(g.length>0&&!k.capabilities.has(`deepen-not`))throw new ol(`deepen-not`,`exclude`);if(_===!0&&!k.capabilities.has(`deepen-relative`))throw new ol(`deepen-relative`,`relative`);let{oid:j,fullref:te}=K.resolveAgainstMap({ref:D,map:A});for(let e of A.keys())e===te||e===`HEAD`||e.startsWith(`refs/heads/`)||v&&e.startsWith(`refs/tags/`)||A.delete(e);let ne=nd([...k.capabilities],[`multi_ack_detailed`,`no-done`,`side-band-64k`,`ofs-delta`,`agent=${rd.agent}`]);_&&ne.push(`deepen-relative`);let M=y?[j]:A.values(),re=y?[C]:await K.listRefs({fs:e,gitdir:c,filepath:`refs`}),N=[];for(let n of re)try{n=await K.expand({fs:e,gitdir:c,ref:n});let r=await K.resolve({fs:e,gitdir:c,ref:n});await ed({fs:e,cache:t,gitdir:c,oid:r})&&N.push(r)}catch{}N=[...new Set(N)];let P=await Zu.read({fs:e,gitdir:c}),F=k.capabilities.has(`shallow`)?[...P]:[],ie=ld({capabilities:ne,wants:M,haves:N,shallows:F,depth:m,since:h,exclude:g}),I=Buffer.from(await Lu(ie)),ae=await O.connect({http:n,onProgress:r,corsProxy:p,service:`git-upload-pack`,url:E,auth:ee,body:[I],headers:b}),L=await cd(ae.body);ae.headers&&(L.headers=ae.headers);for(let n of L.shallows)if(!P.has(n))try{let{object:r}=await zc({fs:e,cache:t,gitdir:c,oid:n}),i=new wl(r),a=await Promise.all(i.headers().parent.map(n=>ed({fs:e,cache:t,gitdir:c,oid:n})));a.length===0||a.every(e=>e)||P.add(n)}catch{P.add(n)}for(let e of L.unshallows)P.delete(e);if(await Zu.write({fs:e,gitdir:c,oids:P}),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=A.get(i);a&&t.set(i,a);let{pruned:o}=await K.updateRemoteRefs({fs:e,gitdir:c,remote:T,refs:t,symrefs:n,tags:v,prune:x});x&&(L.pruned=o)}else{let{pruned:t}=await K.updateRemoteRefs({fs:e,gitdir:c,remote:T,refs:A,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}=K.resolveAgainstMap({ref:`HEAD`,map:A});for(let[t,n]of A.entries())if(t!==`HEAD`&&n===e){L.HEAD=t;break}}L.FETCH_HEAD={oid:j,description:`${te.startsWith(`refs/tags`)?`tag`:`branch`} '${Mu(te)}' of ${E}`},(r||i)&&Iu(od(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 oe=Buffer.from(await Lu(L.packfile));if(ae.body.error)throw ae.body.error;let se=oe.slice(-20).toString(`hex`),ce={defaultBranch:L.HEAD,fetchHead:L.FETCH_HEAD.oid,fetchHeadDescription:L.FETCH_HEAD.description};if(L.headers&&(ce.headers=L.headers),x&&(ce.pruned=L.pruned),se!==``&&!td(oe)){ce.packfile=`objects/pack/pack-${se}.pack`;let n=G(c,ce.packfile);await e.write(n,oe);let i=await Nc.fromPack({pack:oe,getExternalRefDelta:n=>zc({fs:e,cache:t,gitdir:c,oid:n}),onProgress:r});await e.write(n.replace(/\.pack$/,`.idx`),await i.toBuffer())}return ce}async function dd({fs:e,bare:t=!1,dir:n,gitdir:r=t?n:G(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]
782
+ `)),s}async function ud({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 Nu({fs:e,gitdir:c,test:!0}),w=await rc.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 nl(`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 ee=Ju.getRemoteHelperFor({url:E}),O=await ee.discover({http:n,onAuth:a,onAuthSuccess:o,onAuthFailure:s,corsProxy:p,service:`git-upload-pack`,url:E,headers:b,protocolVersion:1}),k=O.auth,te=O.refs;if(te.size===0)return{defaultBranch:null,fetchHead:null,fetchHeadDescription:null};if(m!==null&&!O.capabilities.has(`shallow`))throw new ol(`shallow`,`depth`);if(h!==null&&!O.capabilities.has(`deepen-since`))throw new ol(`deepen-since`,`since`);if(g.length>0&&!O.capabilities.has(`deepen-not`))throw new ol(`deepen-not`,`exclude`);if(_===!0&&!O.capabilities.has(`deepen-relative`))throw new ol(`deepen-relative`,`relative`);let{oid:A,fullref:ne}=K.resolveAgainstMap({ref:D,map:te});for(let e of te.keys())e===ne||e===`HEAD`||e.startsWith(`refs/heads/`)||v&&e.startsWith(`refs/tags/`)||te.delete(e);let re=nd([...O.capabilities],[`multi_ack_detailed`,`no-done`,`side-band-64k`,`ofs-delta`,`agent=${rd.agent}`]);_&&re.push(`deepen-relative`);let ie=y?[A]:te.values(),ae=y?[C]:await K.listRefs({fs:e,gitdir:c,filepath:`refs`}),j=[];for(let n of ae)try{n=await K.expand({fs:e,gitdir:c,ref:n});let r=await K.resolve({fs:e,gitdir:c,ref:n});await ed({fs:e,cache:t,gitdir:c,oid:r})&&j.push(r)}catch{}j=[...new Set(j)];let M=await Zu.read({fs:e,gitdir:c}),N=O.capabilities.has(`shallow`)?[...M]:[],oe=ld({capabilities:re,wants:ie,haves:j,shallows:N,depth:m,since:h,exclude:g}),P=Buffer.from(await Lu(oe)),se=await ee.connect({http:n,onProgress:r,corsProxy:p,service:`git-upload-pack`,url:E,auth:k,body:[P],headers:b}),F=await cd(se.body);se.headers&&(F.headers=se.headers);for(let n of F.shallows)if(!M.has(n))try{let{object:r}=await zc({fs:e,cache:t,gitdir:c,oid:n}),i=new wl(r),a=await Promise.all(i.headers().parent.map(n=>ed({fs:e,cache:t,gitdir:c,oid:n})));a.length===0||a.every(e=>e)||M.add(n)}catch{M.add(n)}for(let e of F.unshallows)M.delete(e);if(await Zu.write({fs:e,gitdir:c,oids:M}),y){let t=new Map([[ne,A]]),n=new Map,r=10,i=ne;for(;r--;){let e=O.symrefs.get(i);if(e===void 0)break;n.set(i,e),i=e}let a=te.get(i);a&&t.set(i,a);let{pruned:o}=await K.updateRemoteRefs({fs:e,gitdir:c,remote:T,refs:t,symrefs:n,tags:v,prune:x});x&&(F.pruned=o)}else{let{pruned:t}=await K.updateRemoteRefs({fs:e,gitdir:c,remote:T,refs:te,symrefs:O.symrefs,tags:v,prune:x,pruneTags:S});x&&(F.pruned=t)}if(F.HEAD=O.symrefs.get(`HEAD`),F.HEAD===void 0){let{oid:e}=K.resolveAgainstMap({ref:`HEAD`,map:te});for(let[t,n]of te.entries())if(t!==`HEAD`&&n===e){F.HEAD=t;break}}F.FETCH_HEAD={oid:A,description:`${ne.startsWith(`refs/tags`)?`tag`:`branch`} '${Mu(ne)}' of ${E}`},(r||i)&&Iu(od(F.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 I=Buffer.from(await Lu(F.packfile));if(se.body.error)throw se.body.error;let ce=I.slice(-20).toString(`hex`),le={defaultBranch:F.HEAD,fetchHead:F.FETCH_HEAD.oid,fetchHeadDescription:F.FETCH_HEAD.description};if(F.headers&&(le.headers=F.headers),x&&(le.pruned=F.pruned),ce!==``&&!td(I)){le.packfile=`objects/pack/pack-${ce}.pack`;let n=G(c,le.packfile);await e.write(n,I);let i=await Nc.fromPack({pack:I,getExternalRefDelta:n=>zc({fs:e,cache:t,gitdir:c,oid:n}),onProgress:r});await e.write(n.replace(/\.pack$/,`.idx`),await i.toBuffer())}return le}async function dd({fs:e,bare:t=!1,dir:n,gitdir:r=t?n:G(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]
783
783
  repositoryformatversion = 0
784
784
  filemode = false
785
785
  \tbare = ${t}\n`+(t?``:` logallrefupdates = true
@@ -787,11 +787,11 @@ gpgsig`+Sl(o)+`
787
787
  ignorecase = true
788
788
  `),await e.write(r+`/HEAD`,`ref: refs/heads/${i}\n`)}async function fd({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 dd({fs:e,gitdir:u}),await mu({fs:e,gitdir:u,remote:m,url:d,force:!1}),f){let t=await rc.get({fs:e,gitdir:u});await t.set(`http.corsProxy`,f),await rc.save({fs:e,gitdir:u,config:t})}let{defaultBranch:T,fetchHead:E}=await ud({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 xu({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 pd({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPostCheckout:s,dir:c,gitdir:l=G(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{J(`fs`,e),J(`http`,t),J(`gitdir`,l),y||J(`dir`,c),J(`url`,u);let T=new q(e);return await fd({fs:T,cache:S,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPostCheckout:s,dir:c,gitdir:await Y({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 md({fs:e,onSign:t,dir:n,gitdir:r=G(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{J(`fs`,e),c||J(`message`,i),s&&J(`onSign`,t);let n=new q(e);return await ou({fs:n,cache:m,onSign:t,gitdir:await Y({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 hd({fs:e,dir:t,gitdir:n=G(t,`.git`),fullname:r=!1,test:i=!1}){try{J(`fs`,e),J(`gitdir`,n);let t=new q(e);return await Nu({fs:t,gitdir:await Y({fsp:t,dotgit:n}),fullname:r,test:i})}catch(e){throw e.caller=`git.currentBranch`,e}}async function gd({fs:e,gitdir:t,ref:n}){if(n=n.startsWith(`refs/heads/`)?n:`refs/heads/${n}`,!await K.exists({fs:e,gitdir:t,ref:n}))throw new ks(n);let r=await K.expand({fs:e,gitdir:t,ref:n});if(r===await Nu({fs:e,gitdir:t,fullname:!0})){let n=await K.resolve({fs:e,gitdir:t,ref:r});await K.writeRef({fs:e,gitdir:t,ref:`HEAD`,value:n})}await K.deleteRef({fs:e,gitdir:t,ref:r});let i=Mu(n),a=await rc.get({fs:e,gitdir:t});await a.deleteSection(`branch`,i),await rc.save({fs:e,gitdir:t,config:a})}async function _d({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r}){try{J(`fs`,e),J(`ref`,r);let t=new q(e);return await gd({fs:t,gitdir:await Y({fsp:t,dotgit:n}),ref:r})}catch(e){throw e.caller=`git.deleteBranch`,e}}async function vd({fs:e,gitdir:t,remote:n}){let r=await rc.get({fs:e,gitdir:t});await r.deleteSection(`remote`,n),await rc.save({fs:e,gitdir:t,config:r})}async function yd({fs:e,dir:t,gitdir:n=G(t,`.git`),remote:r}){try{J(`fs`,e),J(`remote`,r);let t=new q(e);return await vd({fs:t,gitdir:await Y({fsp:t,dotgit:n}),remote:r})}catch(e){throw e.caller=`git.deleteRemote`,e}}async function bd({fs:e,gitdir:t,ref:n}){n=n.startsWith(`refs/tags/`)?n:`refs/tags/${n}`,await K.deleteRef({fs:e,gitdir:t,ref:n})}async function xd({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r}){try{J(`fs`,e),J(`ref`,r);let t=new q(e);return await bd({fs:t,gitdir:await Y({fsp:t,dotgit:n}),ref:r})}catch(e){throw e.caller=`git.deleteTag`,e}}async function Sd({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 Cd({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:i}){let a=[],o=await e.readdir(G(n,`objects/pack`));o=o.filter(e=>e.endsWith(`.idx`));for(let s of o){let o=await Ic({fs:e,cache:t,filename:`${n}/objects/pack/${s}`,getExternalRefDelta:i});if(o.error)throw new W(o.error);for(let e of o.offsets.keys())e.startsWith(r)&&a.push(e)}return a}async function wd({fs:e,cache:t,gitdir:n,oid:r}){let i=r=>zc({fs:e,cache:t,gitdir:n,oid:r}),a=await Sd({fs:e,gitdir:n,oid:r}),o=await Cd({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 Vc(`oids`,r,a):new ks(`an object matching "${r}"`)}async function Td({fs:e,dir:t,gitdir:n=G(t,`.git`),oid:r,cache:i={}}){try{J(`fs`,e),J(`gitdir`,n),J(`oid`,r);let t=new q(e);return await wd({fs:t,cache:i,gitdir:await Y({fsp:t,dotgit:n}),oid:r})}catch(e){throw e.caller=`git.expandOid`,e}}async function Ed({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 zc({fs:e,cache:t,gitdir:n,oid:r}),{parent:c}=wl.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 Dd({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 Nu({fs:e,gitdir:r,fullname:!0})),i=await K.expand({fs:e,gitdir:r,ref:i}),a=await K.expand({fs:e,gitdir:r,ref:a});let v=await K.resolve({fs:e,gitdir:r,ref:i}),y=await K.resolve({fs:e,gitdir:r,ref:a}),b=await Ed({fs:e,cache:t,gitdir:r,oids:[v,y]});if(b.length!==1)if(b.length===0&&_)b.push(`4b825dc642cb6eb9a060e54bf8d69288fbee4904`);else throw new $c;let x=b[0];if(x===y)return{oid:v,alreadyMerged:!0};if(o&&x===v)return!c&&!l&&await K.writeRef({fs:e,gitdir:r,ref:i,value:y}),{oid:y,fastForward:!0};{if(s)throw new qc;let o=await xs.acquire({fs:e,gitdir:r,cache:t,allowUnmerged:!1},async o=>ku({fs:e,cache:t,dir:n,gitdir:r,index:o,ourOid:v,theirOid:y,baseOid:x,ourName:Mu(i),baseName:`base`,theirName:Mu(a),dryRun:c,abortOnConflict:u,mergeDriver:g}));if(o instanceof el)throw o;return d||=`Merge branch '${Mu(a)}' into ${Mu(i)}`,{oid:await ou({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 Od({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 Nu({fs:e,gitdir:l});if(!t)throw new nl(`ref`);u=t}let{fetchHead:w,fetchHeadDescription:T}=await ud({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 Dd({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 xu({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 kd({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,dir:s,gitdir:c=G(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{J(`fs`,e),J(`http`,t),J(`gitdir`,c);let s=new q(e);return await ud({fs:s,cache:C,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,gitdir:await Y({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 Ad({fs:e,filepath:t}){if(await e.exists(G(t,`.git`)))return t;{let n=Cs(t);if(n===t)throw new ks(`git root for ${t}`);return Ad({fs:e,filepath:n})}}async function jd({fs:e,filepath:t}){try{return J(`fs`,e),J(`filepath`,t),await Ad({fs:new q(e),filepath:t})}catch(e){throw e.caller=`git.findRoot`,e}}async function Md({fs:e,dir:t,gitdir:n=G(t,`.git`),path:r}){try{J(`fs`,e),J(`gitdir`,n),J(`path`,r);let t=new q(e);return await eu({fs:t,gitdir:await Y({fsp:t,dotgit:n}),path:r})}catch(e){throw e.caller=`git.getConfig`,e}}async function Nd({fs:e,bare:t=!1,dir:n,gitdir:r=t?n:G(n,`.git`),defaultBranch:i=`master`}){try{J(`fs`,e),J(`gitdir`,r),t||J(`dir`,n);let a=new q(e);return await dd({fs:a,bare:t,dir:n,gitdir:await Y({fsp:a,dotgit:r}),defaultBranch:i})}catch(e){throw e.caller=`git.init`,e}}async function Pd({fs:e,cache:t,gitdir:n,oid:r,ancestor:i,depth:a}){let o=await Zu.read({fs:e,gitdir:n});if(!r)throw new nl(`oid`);if(!i)throw new nl(`ancestor`);if(r===i)return!1;let s=[r],c=new Set,l=0;for(;s.length;){if(l++===a)throw new Qc(a);let r=s.shift(),{type:u,object:d}=await zc({fs:e,cache:t,gitdir:n,oid:r});if(u!==`commit`)throw new As(r,u,`commit`);let f=wl.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 Fd({fs:e,dir:t,gitdir:n=G(t,`.git`),remote:r}){try{J(`fs`,e),J(`gitdir`,n);let t=new q(e),i=await Y({fsp:t,dotgit:n});return K.listBranches({fs:t,gitdir:i,remote:r})}catch(e){throw e.caller=`git.listBranches`,e}}async function Id({fs:e,gitdir:t,ref:n,cache:r}){if(n){let i=await K.resolve({gitdir:t,fs:e,ref:n}),a=[];return await Ld({fs:e,cache:r,gitdir:t,oid:i,filenames:a,prefix:``}),a}else return xs.acquire({fs:e,gitdir:t,cache:r},async function(e){return e.entries.map(e=>e.path)})}async function Ld({fs:e,cache:t,gitdir:n,oid:r,filenames:i,prefix:a}){let{tree:o}=await uu({fs:e,cache:t,gitdir:n,oid:r});for(let r of o)r.type===`tree`?await Ld({fs:e,cache:t,gitdir:n,oid:r.oid,filenames:i,prefix:G(a,r.path)}):i.push(G(a,r.path))}async function Rd({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,cache:i={}}){try{J(`fs`,e),J(`gitdir`,n);let t=new q(e);return await Id({fs:t,cache:i,gitdir:await Y({fsp:t,dotgit:n}),ref:r})}catch(e){throw e.caller=`git.listFiles`,e}}async function zd({fs:e,gitdir:t}){let n=await rc.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 Bd({fs:e,dir:t,gitdir:n=G(t,`.git`)}){try{J(`fs`,e),J(`gitdir`,n);let t=new q(e);return await zd({fs:t,gitdir:await Y({fsp:t,dotgit:n})})}catch(e){throw e.caller=`git.listRemotes`,e}}async function Vd({fs:e,dir:t,gitdir:n=G(t,`.git`)}){try{J(`fs`,e),J(`gitdir`,n);let t=new q(e),r=await Y({fsp:t,dotgit:n});return K.listTags({fs:t,gitdir:r})}catch(e){throw e.caller=`git.listTags`,e}}function Hd(e,t){return e.committer.timestamp-t.committer.timestamp}var Ud=`e69de29bb2d1d6434b8b29ae775ad8c2e48c5391`;async function Wd({fs:e,cache:t,gitdir:n,oid:r,fileId:i}){if(i===Ud)return;let a=r,o,s=await Tl({fs:e,cache:t,gitdir:n,oid:r}),c=s.tree;return i===s.oid?o=s.path:(o=await Gd({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 Gd({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=G(s,r.path),o.push(c)):r.type===`tree`&&(c=zc({fs:e,cache:t,gitdir:n,oid:r.oid}).then(function({object:c}){return Gd({fs:e,cache:t,gitdir:n,tree:mc.from(c),fileId:i,oid:a,filepaths:o,parentPath:G(s,r.path)})})),c});return await Promise.all(c),o}async function Kd({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 Zu.read({fs:e,gitdir:n}),f=[await au({fs:e,cache:t,gitdir:n,oid:await K.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 cu({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 ks){let o=c&&p;if(o&&(o=await Wd({fs:e,cache:t,gitdir:n,oid:i.commit.tree,fileId:p}),o))if(Array.isArray(o)){if(m){let i=await Wd({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 au({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)=>Hd(e.commit,t.commit))}return u}async function qd({fs:e,dir:t,gitdir:n=G(t,`.git`),filepath:r,ref:i=`HEAD`,depth:a,since:o,force:s,follow:c,cache:l={}}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,i);let t=new q(e);return await Kd({fs:t,cache:l,gitdir:await Y({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 Jd({fs:e,onSign:t,dir:n,gitdir:r=G(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{J(`fs`,e),m&&J(`onSign`,t);let v=new q(e),y=await Y({fsp:v,dotgit:r}),b=await nu({fs:v,gitdir:y,author:f});if(!b&&(!s||!o))throw new tl(`author`);let x=await ru({fs:v,gitdir:y,author:b,committer:p});if(!x&&(!s||!o))throw new tl(`committer`);return await Dd({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 Yd={commit:16,tree:32,blob:48,tag:64,ofs_delta:96,ref_delta:112};async function Xd({fs:e,cache:t,dir:n,gitdir:r=G(n,`.git`),oids:i}){let a=new Wo.default,o=[];function s(e,t){let n=Buffer.from(e,t);o.push(n),a.update(n)}async function c({stype:e,object:t}){let n=Yd[e],r=t.length,i=r>15?128:0,a=r&15;r>>>=4;let o=(i|n|a).toString(16);for(s(o,`hex`);i;)i=r>127?128:0,o=i|r&127,s(zu(2,o),`hex`),r>>>=7;s(Buffer.from(await ql(t)))}s(`PACK`),s(`00000002`,`hex`),s(zu(8,i.length),`hex`);for(let n of i){let{type:i,object:a}=await zc({fs:e,cache:t,gitdir:r,oid:n});await c({write:s,object:a,stype:i})}let l=a.digest();return o.push(l),o}async function Zd({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,dir:s,gitdir:c=G(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{J(`fs`,e),J(`gitdir`,c);let w=new q(e),T=await Y({fsp:w,dotgit:c}),E=await nu({fs:w,gitdir:T,author:b});if(!E)throw new tl(`author`);let D=await ru({fs:w,gitdir:T,author:E,committer:x});if(!D)throw new tl(`committer`);return await Od({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 Qd({fs:e,cache:t,dir:n,gitdir:r=G(n,`.git`),start:i,finish:a}){let o=await Zu.read({fs:e,gitdir:r}),s=new Set,c=new Set;for(let t of i)s.add(await K.resolve({fs:e,gitdir:r,ref:t}));for(let t of a)try{let n=await K.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 zc({fs:e,cache:t,gitdir:r,oid:n});if(i===`tag`){let e=xl.from(a).headers().object;return u(e)}if(i!==`commit`)throw new As(n,i,`commit`);if(!o.has(n))for(n of wl.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 $d({fs:e,cache:t,dir:n,gitdir:r=G(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 zc({fs:e,cache:t,gitdir:r,oid:n});if(i===`tag`){let e=xl.from(s).headers().object;await o(e)}else if(i===`commit`){let e=wl.from(s).headers().tree;await o(e)}else if(i===`tree`){let e=mc.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 ef(e){let t={},n=``,r=Bu.streamReader(e),i=await r();for(;i!==!0;)i!==null&&(n+=i.toString(`utf8`)+`
789
789
  `),i=await r();let a=n.toString(`utf8`).split(`
790
- `);if(i=a.shift(),!i.startsWith(`unpack `))throw new il(`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 tf({capabilities:e=[],triplets:t=[]}){let n=[],r=`\x00 ${e.join(` `)}`;for(let e of t)n.push(Bu.encode(`${e.oldoid} ${e.oid} ${e.fullRef}${r}\n`)),r=``;return n.push(Bu.flush()),n}async function nf({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 Nu({fs:e,gitdir:l});if(v===void 0)throw new nl(`ref`);let y=await rc.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 nl(`remote OR url`);let x=d||await y.get(`branch.${v}.merge`);if(b===void 0)throw new nl(`remoteRef`);g===void 0&&(g=await y.get(`http.corsProxy`));let S=await K.expand({fs:e,gitdir:l,ref:v}),C=h?`0000000000000000000000000000000000000000`:await K.resolve({fs:e,gitdir:l,ref:S}),w=Ju.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 K.expandAgainstMap({ref:x,map:T.refs})}catch(e){if(e instanceof ks)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 ul;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 Ed({fs:e,cache:t,gitdir:l,oids:[C,O]});for(let e of i)n.push(e);k&&(r=await $d({fs:e,cache:t,gitdir:l,oids:i}))}if(n.includes(C)||(ee=await $d({fs:e,cache:t,gitdir:l,oids:await Qd({fs:e,cache:t,gitdir:l,start:[C],finish:n})})),k){try{let n=await K.resolve({fs:e,gitdir:l,ref:`refs/remotes/${f}/HEAD`,depth:2}),{oid:i}=await K.resolveAgainstMap({ref:n.replace(`refs/remotes/${f}/`,``),fullref:n,map:T.refs}),a=[i];for(let n of await $d({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 al(`tag-exists`);if(C!==`0000000000000000000000000000000000000000`&&O!==`0000000000000000000000000000000000000000`&&!await Pd({fs:e,cache:t,gitdir:l,oid:C,ancestor:O,depth:-1}))throw new al(`not-fast-forward`)}}let A=await tf({capabilities:nd([...T.capabilities],[`report-status`,`side-band-64k`,`agent=${rd.agent}`]),triplets:[{oldoid:O,oid:C,fullRef:D}]}),j=h?[]:await Xd({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:M}=await sd.demux(te.body);i&&Iu(od(M),async e=>{await i(e)});let re=await ef(ne);if(te.headers&&(re.headers=te.headers),f&&re.ok&&re.refs[D].ok&&!S.startsWith(`refs/tags`)){let t=`refs/remotes/${f}/${D.replace(`refs/heads`,``)}`;h?await K.deleteRef({fs:e,gitdir:l,ref:t}):await K.writeRef({fs:e,gitdir:l,ref:t,value:C})}if(re.ok&&Object.values(re.refs).every(e=>e.ok))return re;throw new Jc(Object.entries(re.refs).filter(([e,t])=>!t.ok).map(([e,t])=>`\n - ${e}: ${t.error}`).join(``),re)}async function rf({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPrePush:s,dir:c,gitdir:l=G(c,`.git`),ref:u,remoteRef:d,remote:f=`origin`,url:p,force:m=!1,delete:h=!1,corsProxy:g,headers:_={},cache:v={}}){try{J(`fs`,e),J(`http`,t),J(`gitdir`,l);let c=new q(e);return await nf({fs:c,cache:v,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPrePush:s,gitdir:await Y({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 af({fs:e,cache:t,gitdir:n,oid:r}){let{type:i,object:a}=await zc({fs:e,cache:t,gitdir:n,oid:r});if(i===`tag`)return r=xl.from(a).parse().object,af({fs:e,cache:t,gitdir:n,oid:r});if(i!==`blob`)throw new As(r,i,`blob`);return{oid:r,blob:new Uint8Array(a)}}async function of({fs:e,cache:t,gitdir:n,oid:r,filepath:i=void 0}){return i!==void 0&&(r=await cu({fs:e,cache:t,gitdir:n,oid:r,filepath:i})),await af({fs:e,cache:t,gitdir:n,oid:r})}async function sf({fs:e,dir:t,gitdir:n=G(t,`.git`),oid:r,filepath:i,cache:a={}}){try{J(`fs`,e),J(`gitdir`,n),J(`oid`,r);let t=new q(e);return await of({fs:t,cache:a,gitdir:await Y({fsp:t,dotgit:n}),oid:r,filepath:i})}catch(e){throw e.caller=`git.readBlob`,e}}async function cf({fs:e,dir:t,gitdir:n=G(t,`.git`),oid:r,cache:i={}}){try{J(`fs`,e),J(`gitdir`,n),J(`oid`,r);let t=new q(e);return await au({fs:t,cache:i,gitdir:await Y({fsp:t,dotgit:n}),oid:r})}catch(e){throw e.caller=`git.readCommit`,e}}async function lf({fs:e,dir:t,gitdir:n=G(t,`.git`),oid:r,filepath:i=void 0,cache:a={}}){try{J(`fs`,e),J(`gitdir`,n),J(`oid`,r);let t=new q(e);return await uu({fs:t,cache:a,gitdir:await Y({fsp:t,dotgit:n}),oid:r,filepath:i})}catch(e){throw e.caller=`git.readTree`,e}}async function uf({fs:e,dir:t,gitdir:n=G(t,`.git`),filepath:r,cache:i={}}){try{J(`fs`,e),J(`gitdir`,n),J(`filepath`,r);let t=new q(e),a=await Y({fsp:t,dotgit:n});await xs.acquire({fs:t,gitdir:a,cache:i},async function(e){e.delete({filepath:r})})}catch(e){throw e.caller=`git.remove`,e}}async function df({gitdir:e,type:t,object:n}){return cs(hc.wrap({type:t,object:n}))}async function ff({fs:e,dir:t,gitdir:n=G(t,`.git`),filepath:r,ref:i,cache:a={}}){try{J(`fs`,e),J(`gitdir`,n),J(`filepath`,r);let o=new q(e),s=await Y({fsp:o,dotgit:n}),c,l;try{c=await K.resolve({fs:o,gitdir:s,ref:i||`HEAD`})}catch(e){if(i)throw e}if(c)try{c=await cu({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(G(t,r));d&&(l=await df({gitdir:s,type:`blob`,object:d}),c===l&&(u=await o.lstat(G(t,r)))),await xs.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 pf({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,depth:i}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r);let t=new q(e),a=await Y({fsp:t,dotgit:n});return await K.resolve({fs:t,gitdir:a,ref:r,depth:i})}catch(e){throw e.caller=`git.resolveRef`,e}}async function mf({fs:e,dir:t,gitdir:n=G(t,`.git`),path:r,value:i,append:a=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`path`,r);let t=new q(e),o=await Y({fsp:t,dotgit:n}),s=await rc.get({fs:t,gitdir:o});a?await s.append(r,i):await s.set(r,i),await rc.save({fs:t,gitdir:o,config:s})}catch(e){throw e.caller=`git.setConfig`,e}}async function hf({fs:e,gitdir:t,commit:n}){return await Xl({fs:e,gitdir:t,type:`commit`,object:wl.from(n).toObject(),format:`content`})}async function gf({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r=`HEAD`,filepaths:i=[`.`],filter:a,cache:o={},ignored:s=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r);let c=new q(e);return await Pl({fs:c,cache:o,dir:t,gitdir:await Y({fsp:c,dotgit:n}),trees:[Dl({ref:r}),kl(),Os()],map:async function(e,[n,r,o]){if(!n&&!o&&r&&!s&&await Wl.isIgnored({fs:c,dir:t,filepath:e})||!i.some(t=>bu(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 _f({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,object:i,force:a=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r);let t=new q(e);if(r===void 0)throw new nl(`ref`);r=r.startsWith(`refs/tags/`)?r:`refs/tags/${r}`;let o=await Y({fsp:t,dotgit:n}),s=await K.resolve({fs:t,gitdir:o,ref:i||`HEAD`});if(!a&&await K.exists({fs:t,gitdir:o,ref:r}))throw new Bc(`tag`,r);await K.writeRef({fs:t,gitdir:o,ref:r,value:s})}catch(e){throw e.caller=`git.tag`,e}}function vf(){try{return rd.version}catch(e){throw e.caller=`git.version`,e}}async function yf({fs:e,dir:t,gitdir:n=G(t,`.git`),trees:r,map:i,reduce:a,iterate:o,cache:s={}}){try{J(`fs`,e),J(`gitdir`,n),J(`trees`,r);let c=new q(e);return await Pl({fs:c,cache:s,dir:t,gitdir:await Y({fsp:c,dotgit:n}),trees:r,map:i,reduce:a,iterate:o})}catch(e){throw e.caller=`git.walk`,e}}async function bf({fs:e,dir:t,gitdir:n=G(t,`.git`),blob:r}){try{J(`fs`,e),J(`gitdir`,n),J(`blob`,r);let t=new q(e);return await Xl({fs:t,gitdir:await Y({fsp:t,dotgit:n}),type:`blob`,object:r,format:`content`})}catch(e){throw e.caller=`git.writeBlob`,e}}async function xf({fs:e,dir:t,gitdir:n=G(t,`.git`),commit:r}){try{J(`fs`,e),J(`gitdir`,n),J(`commit`,r);let t=new q(e);return await hf({fs:t,gitdir:await Y({fsp:t,dotgit:n}),commit:r})}catch(e){throw e.caller=`git.writeCommit`,e}}async function Sf({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,value:i,force:a=!1,symbolic:o=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r),J(`value`,i);let t=new q(e);if(!pu(r,!0))throw new Zc(r,Yo.default.clean(r));let s=await Y({fsp:t,dotgit:n});if(!a&&await K.exists({fs:t,gitdir:s,ref:r}))throw new Bc(`ref`,r);o?await K.writeSymbolicRef({fs:t,gitdir:s,ref:r,value:i}):(i=await K.resolve({fs:t,gitdir:s,ref:i}),await K.writeRef({fs:t,gitdir:s,ref:r,value:i}))}catch(e){throw e.caller=`git.writeRef`,e}}async function Cf({fs:e,dir:t,gitdir:n=G(t,`.git`),tree:r}){try{J(`fs`,e),J(`gitdir`,n),J(`tree`,r);let t=new q(e);return await du({fs:t,gitdir:await Y({fsp:t,dotgit:n}),tree:r})}catch(e){throw e.caller=`git.writeTree`,e}}function wf(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function Tf(){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(wf())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 Ef=Tf();function Df(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 Of(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 kf(e){let{oldContent:t,newContent:n,oldName:r,newName:i,color:a=!0}=e;if(t===n)return``;let o=t.split(`
790
+ `);if(i=a.shift(),!i.startsWith(`unpack `))throw new il(`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 tf({capabilities:e=[],triplets:t=[]}){let n=[],r=`\x00 ${e.join(` `)}`;for(let e of t)n.push(Bu.encode(`${e.oldoid} ${e.oid} ${e.fullRef}${r}\n`)),r=``;return n.push(Bu.flush()),n}async function nf({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 Nu({fs:e,gitdir:l});if(v===void 0)throw new nl(`ref`);let y=await rc.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 nl(`remote OR url`);let x=d||await y.get(`branch.${v}.merge`);if(b===void 0)throw new nl(`remoteRef`);g===void 0&&(g=await y.get(`http.corsProxy`));let S=await K.expand({fs:e,gitdir:l,ref:v}),C=h?`0000000000000000000000000000000000000000`:await K.resolve({fs:e,gitdir:l,ref:S}),w=Ju.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 K.expandAgainstMap({ref:x,map:T.refs})}catch(e){if(e instanceof ks)D=x.startsWith(`refs/`)?x:`refs/heads/${x}`;else throw e}let ee=T.refs.get(D)||`0000000000000000000000000000000000000000`;if(c&&!await c({remote:f,url:b,localRef:{ref:h?`(delete)`:S,oid:C},remoteRef:{ref:D,oid:ee}}))throw new ul;let O=!T.capabilities.has(`no-thin`),k=new Set;if(!h){let n=[...T.refs.values()],r=new Set;if(ee!==`0000000000000000000000000000000000000000`){let i=await Ed({fs:e,cache:t,gitdir:l,oids:[C,ee]});for(let e of i)n.push(e);O&&(r=await $d({fs:e,cache:t,gitdir:l,oids:i}))}if(n.includes(C)||(k=await $d({fs:e,cache:t,gitdir:l,oids:await Qd({fs:e,cache:t,gitdir:l,start:[C],finish:n})})),O){try{let n=await K.resolve({fs:e,gitdir:l,ref:`refs/remotes/${f}/HEAD`,depth:2}),{oid:i}=await K.resolveAgainstMap({ref:n.replace(`refs/remotes/${f}/`,``),fullref:n,map:T.refs}),a=[i];for(let n of await $d({fs:e,cache:t,gitdir:l,oids:a}))r.add(n)}catch{}for(let e of r)k.delete(e)}if(C===ee&&(m=!0),!m){if(S.startsWith(`refs/tags`)&&ee!==`0000000000000000000000000000000000000000`)throw new al(`tag-exists`);if(C!==`0000000000000000000000000000000000000000`&&ee!==`0000000000000000000000000000000000000000`&&!await Pd({fs:e,cache:t,gitdir:l,oid:C,ancestor:ee,depth:-1}))throw new al(`not-fast-forward`)}}let te=await tf({capabilities:nd([...T.capabilities],[`report-status`,`side-band-64k`,`agent=${rd.agent}`]),triplets:[{oldoid:ee,oid:C,fullRef:D}]}),A=h?[]:await Xd({fs:e,cache:t,gitdir:l,oids:[...k]}),ne=await w.connect({http:n,onProgress:r,corsProxy:g,service:`git-receive-pack`,url:b,auth:E,headers:_,body:[...te,...A]}),{packfile:re,progress:ie}=await sd.demux(ne.body);i&&Iu(od(ie),async e=>{await i(e)});let ae=await ef(re);if(ne.headers&&(ae.headers=ne.headers),f&&ae.ok&&ae.refs[D].ok&&!S.startsWith(`refs/tags`)){let t=`refs/remotes/${f}/${D.replace(`refs/heads`,``)}`;h?await K.deleteRef({fs:e,gitdir:l,ref:t}):await K.writeRef({fs:e,gitdir:l,ref:t,value:C})}if(ae.ok&&Object.values(ae.refs).every(e=>e.ok))return ae;throw new Jc(Object.entries(ae.refs).filter(([e,t])=>!t.ok).map(([e,t])=>`\n - ${e}: ${t.error}`).join(``),ae)}async function rf({fs:e,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPrePush:s,dir:c,gitdir:l=G(c,`.git`),ref:u,remoteRef:d,remote:f=`origin`,url:p,force:m=!1,delete:h=!1,corsProxy:g,headers:_={},cache:v={}}){try{J(`fs`,e),J(`http`,t),J(`gitdir`,l);let c=new q(e);return await nf({fs:c,cache:v,http:t,onProgress:n,onMessage:r,onAuth:i,onAuthSuccess:a,onAuthFailure:o,onPrePush:s,gitdir:await Y({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 af({fs:e,cache:t,gitdir:n,oid:r}){let{type:i,object:a}=await zc({fs:e,cache:t,gitdir:n,oid:r});if(i===`tag`)return r=xl.from(a).parse().object,af({fs:e,cache:t,gitdir:n,oid:r});if(i!==`blob`)throw new As(r,i,`blob`);return{oid:r,blob:new Uint8Array(a)}}async function of({fs:e,cache:t,gitdir:n,oid:r,filepath:i=void 0}){return i!==void 0&&(r=await cu({fs:e,cache:t,gitdir:n,oid:r,filepath:i})),await af({fs:e,cache:t,gitdir:n,oid:r})}async function sf({fs:e,dir:t,gitdir:n=G(t,`.git`),oid:r,filepath:i,cache:a={}}){try{J(`fs`,e),J(`gitdir`,n),J(`oid`,r);let t=new q(e);return await of({fs:t,cache:a,gitdir:await Y({fsp:t,dotgit:n}),oid:r,filepath:i})}catch(e){throw e.caller=`git.readBlob`,e}}async function cf({fs:e,dir:t,gitdir:n=G(t,`.git`),oid:r,cache:i={}}){try{J(`fs`,e),J(`gitdir`,n),J(`oid`,r);let t=new q(e);return await au({fs:t,cache:i,gitdir:await Y({fsp:t,dotgit:n}),oid:r})}catch(e){throw e.caller=`git.readCommit`,e}}async function lf({fs:e,dir:t,gitdir:n=G(t,`.git`),oid:r,filepath:i=void 0,cache:a={}}){try{J(`fs`,e),J(`gitdir`,n),J(`oid`,r);let t=new q(e);return await uu({fs:t,cache:a,gitdir:await Y({fsp:t,dotgit:n}),oid:r,filepath:i})}catch(e){throw e.caller=`git.readTree`,e}}async function uf({fs:e,dir:t,gitdir:n=G(t,`.git`),filepath:r,cache:i={}}){try{J(`fs`,e),J(`gitdir`,n),J(`filepath`,r);let t=new q(e),a=await Y({fsp:t,dotgit:n});await xs.acquire({fs:t,gitdir:a,cache:i},async function(e){e.delete({filepath:r})})}catch(e){throw e.caller=`git.remove`,e}}async function df({gitdir:e,type:t,object:n}){return cs(hc.wrap({type:t,object:n}))}async function ff({fs:e,dir:t,gitdir:n=G(t,`.git`),filepath:r,ref:i,cache:a={}}){try{J(`fs`,e),J(`gitdir`,n),J(`filepath`,r);let o=new q(e),s=await Y({fsp:o,dotgit:n}),c,l;try{c=await K.resolve({fs:o,gitdir:s,ref:i||`HEAD`})}catch(e){if(i)throw e}if(c)try{c=await cu({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(G(t,r));d&&(l=await df({gitdir:s,type:`blob`,object:d}),c===l&&(u=await o.lstat(G(t,r)))),await xs.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 pf({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,depth:i}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r);let t=new q(e),a=await Y({fsp:t,dotgit:n});return await K.resolve({fs:t,gitdir:a,ref:r,depth:i})}catch(e){throw e.caller=`git.resolveRef`,e}}async function mf({fs:e,dir:t,gitdir:n=G(t,`.git`),path:r,value:i,append:a=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`path`,r);let t=new q(e),o=await Y({fsp:t,dotgit:n}),s=await rc.get({fs:t,gitdir:o});a?await s.append(r,i):await s.set(r,i),await rc.save({fs:t,gitdir:o,config:s})}catch(e){throw e.caller=`git.setConfig`,e}}async function hf({fs:e,gitdir:t,commit:n}){return await Xl({fs:e,gitdir:t,type:`commit`,object:wl.from(n).toObject(),format:`content`})}async function gf({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r=`HEAD`,filepaths:i=[`.`],filter:a,cache:o={},ignored:s=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r);let c=new q(e);return await Pl({fs:c,cache:o,dir:t,gitdir:await Y({fsp:c,dotgit:n}),trees:[Dl({ref:r}),kl(),Os()],map:async function(e,[n,r,o]){if(!n&&!o&&r&&!s&&await Wl.isIgnored({fs:c,dir:t,filepath:e})||!i.some(t=>bu(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 _f({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,object:i,force:a=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r);let t=new q(e);if(r===void 0)throw new nl(`ref`);r=r.startsWith(`refs/tags/`)?r:`refs/tags/${r}`;let o=await Y({fsp:t,dotgit:n}),s=await K.resolve({fs:t,gitdir:o,ref:i||`HEAD`});if(!a&&await K.exists({fs:t,gitdir:o,ref:r}))throw new Bc(`tag`,r);await K.writeRef({fs:t,gitdir:o,ref:r,value:s})}catch(e){throw e.caller=`git.tag`,e}}function vf(){try{return rd.version}catch(e){throw e.caller=`git.version`,e}}async function yf({fs:e,dir:t,gitdir:n=G(t,`.git`),trees:r,map:i,reduce:a,iterate:o,cache:s={}}){try{J(`fs`,e),J(`gitdir`,n),J(`trees`,r);let c=new q(e);return await Pl({fs:c,cache:s,dir:t,gitdir:await Y({fsp:c,dotgit:n}),trees:r,map:i,reduce:a,iterate:o})}catch(e){throw e.caller=`git.walk`,e}}async function bf({fs:e,dir:t,gitdir:n=G(t,`.git`),blob:r}){try{J(`fs`,e),J(`gitdir`,n),J(`blob`,r);let t=new q(e);return await Xl({fs:t,gitdir:await Y({fsp:t,dotgit:n}),type:`blob`,object:r,format:`content`})}catch(e){throw e.caller=`git.writeBlob`,e}}async function xf({fs:e,dir:t,gitdir:n=G(t,`.git`),commit:r}){try{J(`fs`,e),J(`gitdir`,n),J(`commit`,r);let t=new q(e);return await hf({fs:t,gitdir:await Y({fsp:t,dotgit:n}),commit:r})}catch(e){throw e.caller=`git.writeCommit`,e}}async function Sf({fs:e,dir:t,gitdir:n=G(t,`.git`),ref:r,value:i,force:a=!1,symbolic:o=!1}){try{J(`fs`,e),J(`gitdir`,n),J(`ref`,r),J(`value`,i);let t=new q(e);if(!pu(r,!0))throw new Zc(r,Yo.default.clean(r));let s=await Y({fsp:t,dotgit:n});if(!a&&await K.exists({fs:t,gitdir:s,ref:r}))throw new Bc(`ref`,r);o?await K.writeSymbolicRef({fs:t,gitdir:s,ref:r,value:i}):(i=await K.resolve({fs:t,gitdir:s,ref:i}),await K.writeRef({fs:t,gitdir:s,ref:r,value:i}))}catch(e){throw e.caller=`git.writeRef`,e}}async function Cf({fs:e,dir:t,gitdir:n=G(t,`.git`),tree:r}){try{J(`fs`,e),J(`gitdir`,n),J(`tree`,r);let t=new q(e);return await du({fs:t,gitdir:await Y({fsp:t,dotgit:n}),tree:r})}catch(e){throw e.caller=`git.writeTree`,e}}function wf(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function Tf(){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(wf())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 Ef=Tf();function Df(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 Of(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 kf(e){let{oldContent:t,newContent:n,oldName:r,newName:i,color:a=!0}=e;if(t===n)return``;let o=t.split(`
791
791
  `),s=n.split(`
792
792
  `);o.length>0&&o[o.length-1]===``&&o.pop(),s.length>0&&s[s.length-1]===``&&s.pop();let c=Of(Df(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 Af(e,t){if(e===t)return{insertions:0,deletions:0};let n=e.split(`
793
793
  `),r=t.split(`
794
- `);n.length>0&&n[n.length-1]===``&&n.pop(),r.length>0&&r[r.length-1]===``&&r.pop();let i=Df(n,r),a=0,o=0;for(let e of i)e.type===`insert`&&a++,e.type===`delete`&&o++;return{insertions:a,deletions:o}}var jf=class e{static globalFsByDbName=new Map;lfs;corsProxy;authorName;authorEmail;globalDbName;githubToken;githubTokenLoaded=!1;constructor(e){this.options=e,this.lfs=e.fs.getLightningFS(),this.corsProxy=e.corsProxy,this.authorName=e.authorName??`User`,this.authorEmail=e.authorEmail??`user@example.com`,this.globalDbName=e.globalDbName??`slicc-fs-global`}getOnAuth(){if(!this.githubToken)return;let e=this.githubToken;return()=>({username:`x-access-token`,password:e})}getGlobalFs(){let t=e.globalFsByDbName.get(this.globalDbName);if(t)return t;let n=L.create({dbName:this.globalDbName});return e.globalFsByDbName.set(this.globalDbName,n),n}async ensureGithubTokenLoaded(){if(!this.githubTokenLoaded){this.githubTokenLoaded=!0;try{this.githubToken=(await(await this.getGlobalFs()).readTextFile(`/workspace/.git/github-token`)).trim()||void 0}catch{this.githubToken=void 0}}}async setGithubToken(e){let t=e.trim(),n=await this.getGlobalFs();if(!t){try{await n.rm(`/workspace/.git/github-token`)}catch{}this.githubToken=void 0,this.githubTokenLoaded=!0;return}await n.writeFile(`/workspace/.git/github-token`,t),this.githubToken=t,this.githubTokenLoaded=!0}async execute(e,t){if(e.length===0)return this.help();let[n,...r]=e;try{switch(await this.ensureGithubTokenLoaded(),n){case`init`:return this.init(t,r);case`clone`:return this.clone(t,r);case`add`:return this.add(t,r);case`status`:return this.status(t,r);case`commit`:return this.commit(t,r);case`log`:return this.log(t,r);case`branch`:return this.branch(t,r);case`checkout`:return this.checkout(t,r);case`diff`:return this.diff(t,r);case`show`:return this.show(t,r);case`remote`:return this.remote(t,r);case`fetch`:return this.fetch(t,r);case`pull`:return this.pull(t,r);case`push`:return this.push(t,r);case`merge`:return this.merge(t,r);case`reset`:return this.reset(t,r);case`config`:return this.config(t,r);case`tag`:return this.tag(t,r);case`ls-files`:return this.lsFiles(t,r);case`show-ref`:return this.showRef(t,r);case`stash`:return this.stash(t,r);case`rm`:return this.rm(t,r);case`mv`:return this.mv(t,r);case`rev-parse`:return this.revParse(t,r);case`help`:case`--help`:case`-h`:return this.help();case`version`:case`--version`:return this.version();default:return{stdout:``,stderr:`git: '${n}' is not a git command. See 'git help'.\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`fatal: ${e instanceof Error?e.message:String(e)}\n`,exitCode:128}}}version(){return{stdout:`git version 2.43.0 (isomorphic-git ${vf()})\n`,stderr:``,exitCode:0}}help(){return{stdout:`usage: git <command> [<args>]
794
+ `);n.length>0&&n[n.length-1]===``&&n.pop(),r.length>0&&r[r.length-1]===``&&r.pop();let i=Df(n,r),a=0,o=0;for(let e of i)e.type===`insert`&&a++,e.type===`delete`&&o++;return{insertions:a,deletions:o}}var jf=class e{static globalFsByDbName=new Map;lfs;corsProxy;authorName;authorEmail;globalDbName;githubToken;githubTokenLoaded=!1;constructor(e){this.options=e,this.lfs=e.fs.getLightningFS(),this.corsProxy=e.corsProxy,this.authorName=e.authorName??`User`,this.authorEmail=e.authorEmail??`user@example.com`,this.globalDbName=e.globalDbName??`slicc-fs-global`}getOnAuth(){if(!this.githubToken)return;let e=this.githubToken;return()=>({username:`x-access-token`,password:e})}getGlobalFs(){let t=e.globalFsByDbName.get(this.globalDbName);if(t)return t;let n=F.create({dbName:this.globalDbName});return e.globalFsByDbName.set(this.globalDbName,n),n}async ensureGithubTokenLoaded(){if(!this.githubTokenLoaded){this.githubTokenLoaded=!0;try{this.githubToken=(await(await this.getGlobalFs()).readTextFile(`/workspace/.git/github-token`)).trim()||void 0}catch{this.githubToken=void 0}}}async setGithubToken(e){let t=e.trim(),n=await this.getGlobalFs();if(!t){try{await n.rm(`/workspace/.git/github-token`)}catch{}this.githubToken=void 0,this.githubTokenLoaded=!0;return}await n.writeFile(`/workspace/.git/github-token`,t),this.githubToken=t,this.githubTokenLoaded=!0}async execute(e,t){if(e.length===0)return this.help();let[n,...r]=e;try{switch(await this.ensureGithubTokenLoaded(),n){case`init`:return this.init(t,r);case`clone`:return this.clone(t,r);case`add`:return this.add(t,r);case`status`:return this.status(t,r);case`commit`:return this.commit(t,r);case`log`:return this.log(t,r);case`branch`:return this.branch(t,r);case`checkout`:return this.checkout(t,r);case`diff`:return this.diff(t,r);case`show`:return this.show(t,r);case`remote`:return this.remote(t,r);case`fetch`:return this.fetch(t,r);case`pull`:return this.pull(t,r);case`push`:return this.push(t,r);case`merge`:return this.merge(t,r);case`reset`:return this.reset(t,r);case`config`:return this.config(t,r);case`tag`:return this.tag(t,r);case`ls-files`:return this.lsFiles(t,r);case`show-ref`:return this.showRef(t,r);case`stash`:return this.stash(t,r);case`rm`:return this.rm(t,r);case`mv`:return this.mv(t,r);case`rev-parse`:return this.revParse(t,r);case`help`:case`--help`:case`-h`:return this.help();case`version`:case`--version`:return this.version();default:return{stdout:``,stderr:`git: '${n}' is not a git command. See 'git help'.\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`fatal: ${e instanceof Error?e.message:String(e)}\n`,exitCode:128}}}version(){return{stdout:`git version 2.43.0 (isomorphic-git ${vf()})\n`,stderr:``,exitCode:0}}help(){return{stdout:`usage: git <command> [<args>]
795
795
 
796
796
  Available commands:
797
797
  init Initialize a new repository
@@ -883,7 +883,7 @@ Available commands:
883
883
  `,exitCode:128};let r=n[0],i=n[1],a=r.startsWith(`/`)?r:`${e}/${r}`,o=i.startsWith(`/`)?i:`${e}/${i}`,s;try{s=await this.options.fs.readFile(a,{encoding:`binary`})}catch{return{stdout:``,stderr:`fatal: bad source, source=${r}, destination=${i}\n`,exitCode:128}}let c=o.lastIndexOf(`/`);return c!==-1&&await this.options.fs.mkdir(o.slice(0,c),{recursive:!0}),await this.options.fs.writeFile(o,s),await this.options.fs.rm(a),await Ql({fs:this.lfs,dir:e,filepath:i}),await uf({fs:this.lfs,dir:e,filepath:r}),{stdout:``,stderr:``,exitCode:0}}async revParse(e,t){if(t.includes(`--show-toplevel`))try{return{stdout:`${await jd({fs:this.lfs,filepath:e})}\n`,stderr:``,exitCode:0}}catch{return{stdout:``,stderr:`fatal: not a git repository
884
884
  `,exitCode:128}}if(t.includes(`--is-inside-work-tree`))try{return await jd({fs:this.lfs,filepath:e}),{stdout:`true
885
885
  `,stderr:``,exitCode:0}}catch{return{stdout:`false
886
- `,stderr:``,exitCode:0}}let n=t.find(e=>!e.startsWith(`-`))??`HEAD`;try{return{stdout:`${await pf({fs:this.lfs,dir:e,ref:n})}\n`,stderr:``,exitCode:0}}catch{return{stdout:``,stderr:`fatal: ambiguous argument '${n}'\n`,exitCode:128}}}parseArg(e,...t){for(let n of t){let t=e.indexOf(n);if(t!==-1&&e[t+1])return e[t+1];for(let t of e)if(t.startsWith(`${n}=`))return t.slice(n.length+1)}}parseBooleanFlag(e,t,n){let r=`--no-${t.slice(2)}`,i=n;for(let n of e)n===t&&(i=!0),n===r&&(i=!1);return i}},X=n(`playwright-teleport`),Mf=null,Nf=null;function Pf(e){Mf=e}function Ff(e){Nf=e}function If(e){let t=e.match(/^(f[0-9]+)(e[0-9]+)$/);return t?{framePrefix:t[1],isIframe:!0}:{framePrefix:``,isIframe:!1}}function Lf(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 Rf=[`playwright-cli`,`playwright`,`puppeteer`],zf=new WeakMap,Bf=new Set([`click`,`dblclick`,`fill`,`type`,`press`,`goto`,`navigate`,`select`,`check`,`uncheck`,`drag`,`dialog-accept`,`dialog-dismiss`]);function Vf(e){return e.toISOString().replace(/:/g,`-`)}function Hf(e,t){let n=zf.get(e);n||(n=new WeakMap,zf.set(e,n));let r=n.get(t);return r||(r={snapshots:new Map,appTabId:null,harRecorder:null,sessionDirsCreated:!1,teleportWatchers:new Map},n.set(t,r)),r}function Uf(e){return e instanceof oe||typeof e==`object`&&e&&`code`in e?e.code===`EEXIST`:e instanceof Error&&e.message.includes(`EEXIST`)}var Wf=`function(text) {
886
+ `,stderr:``,exitCode:0}}let n=t.find(e=>!e.startsWith(`-`))??`HEAD`;try{return{stdout:`${await pf({fs:this.lfs,dir:e,ref:n})}\n`,stderr:``,exitCode:0}}catch{return{stdout:``,stderr:`fatal: ambiguous argument '${n}'\n`,exitCode:128}}}parseArg(e,...t){for(let n of t){let t=e.indexOf(n);if(t!==-1&&e[t+1])return e[t+1];for(let t of e)if(t.startsWith(`${n}=`))return t.slice(n.length+1)}}parseBooleanFlag(e,t,n){let r=`--no-${t.slice(2)}`,i=n;for(let n of e)n===t&&(i=!0),n===r&&(i=!1);return i}},X=n(`playwright-teleport`),Mf=null,Nf=null;function Pf(e){Mf=e}function Ff(e){Nf=e}function If(e){let t=e.match(/^(f[0-9]+)(e[0-9]+)$/);return t?{framePrefix:t[1],isIframe:!0}:{framePrefix:``,isIframe:!1}}function Lf(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 Rf=[`playwright-cli`,`playwright`,`puppeteer`],zf=new WeakMap,Bf=new Set([`click`,`dblclick`,`fill`,`type`,`press`,`goto`,`navigate`,`select`,`check`,`uncheck`,`drag`,`dialog-accept`,`dialog-dismiss`]);function Vf(e){return e.toISOString().replace(/:/g,`-`)}function Hf(e,t){let n=zf.get(e);n||(n=new WeakMap,zf.set(e,n));let r=n.get(t);return r||(r={snapshots:new Map,appTabId:null,harRecorder:null,sessionDirsCreated:!1,teleportWatchers:new Map},n.set(t,r)),r}function Uf(e){return e instanceof I||typeof e==`object`&&e&&`code`in e?e.code===`EEXIST`:e instanceof Error&&e.message.includes(`EEXIST`)}var Wf=`function(text) {
887
887
  const el = this;
888
888
  const tag = el.tagName;
889
889
  const proto = tag === 'TEXTAREA' ? window.HTMLTextAreaElement.prototype : window.HTMLInputElement.prototype;
@@ -927,7 +927,7 @@ Available commands:
927
927
  `),o=[`Page URL: ${r}`,`Page Title: ${i}`,``,a].join(`
928
928
  `),s=`/.playwright/snapshots/page-${Vf(new Date)}.yml`;return await t.writeFile(s,o),s})}catch{return null}}async function Xf(e,t,n){await Jf(e,t);let r=new Date().toISOString(),i=`playwright-cli ${n.command}${n.args.length?` `+n.args.join(` `):``}`,a=n.result.exitCode===0?n.result.stdout.trim()||`OK`:`Error: ${n.result.stderr.trim()}`,o=[`### ${i}`,`- **Time**: ${r}`];if(n.tabUrl||n.targetId){let e=n.tabUrl?`${n.tabUrl}${n.targetId?` (targetId: ${n.targetId})`:``}`:`targetId: ${n.targetId}`;o.push(`- **Tab**: ${e}`)}o.push(`- **Result**: ${a}`),n.snapshotPath&&o.push(``,`[Snapshot](${n.snapshotPath})`),o.push(`---`,``);let s=o.join(`
929
929
  `)+`
930
- `,c=`/.playwright/session.md`,l=``;try{let t=await e.readFile(c);l=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await e.writeFile(c,l+s)}function Zf(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`)}function Qf(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function $f(e,t,n,r,i=``,a=``){let o=[],s=me(e.role,`unknown`).toLowerCase(),c=me(e.name),l=me(e.value),u=![`none`,`presentation`,`generic`,`rootwebarea`].includes(s)&&(c||s===`textbox`||s===`button`||s===`link`||s===`checkbox`||s===`radio`),d=``;if(u){d=a+`e${++r.value}`,e.backendNodeId&&n.set(d,e.backendNodeId);let i=Qf(c),o=``;o=s===`button`&&c?`button[aria-label="${i}"], button[title="${i}"]`:s===`link`&&c?`a[aria-label="${i}"], a[title="${i}"]`:s===`textbox`?c?`input[aria-label="${i}"], textarea[aria-label="${i}"], [contenteditable][aria-label="${i}"], input[placeholder="${i}"], textarea[placeholder="${i}"], [contenteditable][placeholder="${i}"], input[title="${i}"], textarea[title="${i}"], [contenteditable][title="${i}"]`:`input, textarea, [contenteditable]`:s===`checkbox`?`input[type="checkbox"]`:s===`radio`?`input[type="radio"]`:c?`[aria-label="${i}"], [title="${i}"]`:`[role="${s}"]`,t.set(d,o)}let f=`${i}- ${s}`;if(c&&(f+=` "${Zf(c)}"`),d&&(f+=` [ref=${d}]`),l&&(f+=`: "${Zf(l)}"`),o.push(f),e.children)for(let s of e.children)o.push(...$f(s,t,n,r,i+` `,a));return o}async function ep(e,t){if(t.appTabId)return;let n=await e.listPages(),r=typeof window<`u`?window.location.origin:`http://localhost:5710`,i=n.find(e=>e.url.startsWith(r)&&!e.url.includes(`/preview/`));i&&(t.appTabId=i.targetId)}function tp(e,t){return t===e.appTabId}function np(e){let t=e.url.trim(),n=e.title.trim();return n===`Omnibox Popup`||t.startsWith(`chrome://`)||t.startsWith(`chrome-search://`)||t.startsWith(`chrome-untrusted://`)||t.startsWith(`devtools://`)||t.length===0&&/popup$/i.test(n)}function rp(e,t){return!tp(e,t.targetId)&&!np(t)}async function ip(e,t){return await ep(e,t),(typeof e.listAllTargets==`function`?await e.listAllTargets():await e.listPages()).filter(e=>rp(t,e))}async function ap(e,t,n,r){await e.attachToPage(n);let i=await e.evaluate(`JSON.stringify({ url: location.href, title: document.title })`),{url:a,title:o}=JSON.parse(i),s=await e.getAccessibilityTree(),c=new Map,l=new Map,u=new Map,d=$f(s,c,l,{value:0}).join(`
930
+ `,c=`/.playwright/session.md`,l=``;try{let t=await e.readFile(c);l=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await e.writeFile(c,l+s)}function Zf(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`)}function Qf(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function $f(e,t,n,r,i=``,a=``){let o=[],s=he(e.role,`unknown`).toLowerCase(),c=he(e.name),l=he(e.value),u=![`none`,`presentation`,`generic`,`rootwebarea`].includes(s)&&(c||s===`textbox`||s===`button`||s===`link`||s===`checkbox`||s===`radio`),d=``;if(u){d=a+`e${++r.value}`,e.backendNodeId&&n.set(d,e.backendNodeId);let i=Qf(c),o=``;o=s===`button`&&c?`button[aria-label="${i}"], button[title="${i}"]`:s===`link`&&c?`a[aria-label="${i}"], a[title="${i}"]`:s===`textbox`?c?`input[aria-label="${i}"], textarea[aria-label="${i}"], [contenteditable][aria-label="${i}"], input[placeholder="${i}"], textarea[placeholder="${i}"], [contenteditable][placeholder="${i}"], input[title="${i}"], textarea[title="${i}"], [contenteditable][title="${i}"]`:`input, textarea, [contenteditable]`:s===`checkbox`?`input[type="checkbox"]`:s===`radio`?`input[type="radio"]`:c?`[aria-label="${i}"], [title="${i}"]`:`[role="${s}"]`,t.set(d,o)}let f=`${i}- ${s}`;if(c&&(f+=` "${Zf(c)}"`),d&&(f+=` [ref=${d}]`),l&&(f+=`: "${Zf(l)}"`),o.push(f),e.children)for(let s of e.children)o.push(...$f(s,t,n,r,i+` `,a));return o}async function ep(e,t){if(t.appTabId)return;let n=await e.listPages(),r=typeof window<`u`?window.location.origin:`http://localhost:5710`,i=n.find(e=>e.url.startsWith(r)&&!e.url.includes(`/preview/`));i&&(t.appTabId=i.targetId)}function tp(e,t){return t===e.appTabId}function np(e){let t=e.url.trim(),n=e.title.trim();return n===`Omnibox Popup`||t.startsWith(`chrome://`)||t.startsWith(`chrome-search://`)||t.startsWith(`chrome-untrusted://`)||t.startsWith(`devtools://`)||t.length===0&&/popup$/i.test(n)}function rp(e,t){return!tp(e,t.targetId)&&!np(t)}async function ip(e,t){return await ep(e,t),(typeof e.listAllTargets==`function`?await e.listAllTargets():await e.listPages()).filter(e=>rp(t,e))}async function ap(e,t,n,r){await e.attachToPage(n);let i=await e.evaluate(`JSON.stringify({ url: location.href, title: document.title })`),{url:a,title:o}=JSON.parse(i),s=await e.getAccessibilityTree(),c=new Map,l=new Map,u=new Map,d=$f(s,c,l,{value:0}).join(`
931
931
  `);if(!r?.noIframes&&typeof e.getFrameTree==`function`)try{let t=(await e.getFrameTree()).filter(e=>e.parentFrameId);if(t.length>0){let n=0,r=d.split(`
932
932
  `),i=[],o=new Set;for(let s of r){i.push(s);let r=s.match(/^(\s*)- iframe\s/);if(!r)continue;let d=s.match(/:\s*"([^"]+)"\s*$/);if(!d)continue;let f=d[1],p=t.find(e=>{if(o.has(e.frameId))return!1;try{let t=new URL(e.url),n=new URL(f,a),r=n.origin+n.pathname.replace(/\/$/,``)+n.search;return t.origin+t.pathname.replace(/\/$/,``)+t.search===r}catch{return e.url===f}});if(!p)continue;o.add(p.frameId),n++;let m=`f${n}`,h=r[1]+` `;try{let t=await e.getAccessibilityTreeForFrame(p.frameId),n=new Map,r=new Map,a=$f(t,n,r,{value:0},h,m);for(let[e,t]of n)c.set(e,t),u.set(e,p.frameId);for(let[e,t]of r)l.set(e,t),u.set(e,p.frameId);i.push(...a)}catch{}}d=i.join(`
933
933
  `)}}catch{}let f={url:a,title:o,refToSelector:c,refToBackendNodeId:l,refToFrameId:u,content:d,timestamp:Date.now()};return t.snapshots.set(n,f),{snapshot:f,output:[`Page URL: ${a}`,`Page Title: ${o}`,``,d].join(`
@@ -1194,7 +1194,7 @@ Aliases: ${Rf.filter(t=>t!==e).join(`, `)}`}function Dp(e){let t=[],n={};for(let
1194
1194
  `,stderr:``,exitCode:0};break}case`sessionstorage-set`:{if(c.length<2){u={stdout:``,stderr:`sessionstorage-set requires <key> <value>
1195
1195
  `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>{await t.evaluate(`sessionStorage.setItem(${JSON.stringify(c[0])}, ${JSON.stringify(c.slice(1).join(` `))})`)}),u={stdout:`sessionStorage "${c[0]}" set\n`,stderr:``,exitCode:0};break}case`sessionstorage-delete`:{if(c.length===0){u={stdout:``,stderr:`sessionstorage-delete requires a key
1196
1196
  `,exitCode:1};break}let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>{await t.evaluate(`sessionStorage.removeItem(${JSON.stringify(c[0])})`)}),u={stdout:`sessionStorage "${c[0]}" deleted\n`,stderr:``,exitCode:0};break}case`sessionstorage-clear`:{let e=Z(l);if(`error`in e){u={stdout:``,stderr:e.error,exitCode:1};break}await t.withTab(e.targetId,async()=>{await t.evaluate(`sessionStorage.clear()`)}),u={stdout:`sessionStorage cleared
1197
- `,stderr:``,exitCode:0};break}case`record`:{let e=c[0]||`about:blank`,r=l.filter;await ep(t,i);let a=await t.createPage(e),o=t.getTransport(),s=(await o.send(`Target.attachToTarget`,{targetId:a,flatten:!0})).sessionId;i.harRecorder||=new ge(o,n);let d=await i.harRecorder.startRecording(a,s,r);u={stdout:`Recording started (targetId: ${a}, recordingId: ${d}) at ${e}\nHAR saved to /recordings/${d}/\n`,stderr:``,exitCode:0};break}case`stop-recording`:{if(c.length===0){u={stdout:``,stderr:`stop-recording requires a recordingId
1197
+ `,stderr:``,exitCode:0};break}case`record`:{let e=c[0]||`about:blank`,r=l.filter;await ep(t,i);let a=await t.createPage(e),o=t.getTransport(),s=(await o.send(`Target.attachToTarget`,{targetId:a,flatten:!0})).sessionId;i.harRecorder||=new _e(o,n);let d=await i.harRecorder.startRecording(a,s,r);u={stdout:`Recording started (targetId: ${a}, recordingId: ${d}) at ${e}\nHAR saved to /recordings/${d}/\n`,stderr:``,exitCode:0};break}case`stop-recording`:{if(c.length===0){u={stdout:``,stderr:`stop-recording requires a recordingId
1198
1198
  `,exitCode:1};break}let e=c[0];if(!i.harRecorder){u={stdout:``,stderr:`Recording not found: ${e}\n`,exitCode:1};break}u={stdout:`Recording stopped. HAR files saved to ${await i.harRecorder.stopRecording(e)}\n`,stderr:``,exitCode:0};break}default:u={stdout:``,stderr:`Unknown command: ${o}\nRun "playwright-cli help" for usage.\n`,exitCode:1};break}}catch(e){u={stdout:``,stderr:`Error: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let d=l.tab??null,f=null;Bf.has(o)&&u.exitCode===0&&d&&(f=await Yf(t,n,i,d));try{await Xf(n,i,{command:o,args:s,result:u,snapshotPath:f,targetId:d})}catch{}return u})}var kp=new Map([[`File operations`,[`ls`,`cat`,`head`,`tail`,`wc`,`touch`,`mkdir`,`rm`,`cp`,`mv`,`ln`,`chmod`,`stat`,`readlink`]],[`Text processing`,[`grep`,`sed`,`awk`,`sort`,`uniq`,`cut`,`tr`,`tee`,`diff`]],[`Search`,[`find`,`rg`]],[`Navigation & paths`,[`pwd`,`basename`,`dirname`,`tree`,`du`,`cd`]],[`Archives`,[`zip`,`unzip`,`pdftk`,`pdf`]],[`Media`,[`convert`,`magick`]],[`Audio`,[`say`,`afplay`,`chime`]],[`Environment & shell`,[`echo`,`printf`,`env`,`printenv`,`export`,`alias`,`unalias`,`history`,`clear`,`true`,`false`,`bash`,`sh`,`commands`,`which`,`uname`,`man`,`host`,`oauth-token`,`secret`,`nuke`,`models`,`cost`]],[`Data processing`,[`xargs`,`jq`,`base64`,`date`]],[`Network`,[`curl`,`wget`,`html-to-markdown`]],[`Version control`,[`git`]],[`Languages`,[`node`,`python`,`python3`,`sqlite3`]],[`Skills`,[`skill`,`upskill`]],[`Browser & UI`,[`serve`,`open`,`imgcat`,...Rf,`webhook`]],[`Filesystem`,[`mount`,`fswatch`]]]);function Ap(e,t=[]){let n=[],r=new Set(e);n.push(`Available commands:
1199
1199
  `);let i=[];for(let[e,t]of kp){let i=t.filter(e=>r.has(e));if(i.length>0){n.push(` ${e}:`),n.push(` ${i.join(`, `)}\n`);for(let e of i)r.delete(e)}}for(let e of r)i.push(e);return i.length>0&&(n.push(` Other:`),n.push(` ${i.sort().join(`, `)}\n`)),t.length>0&&(n.push(` User scripts (.jsh):`),n.push(` ${t.sort().join(`, `)}\n`)),n.push(`Use '<command> --help' for details on a specific command.`),n.join(`
1200
1200
  `)+`
@@ -1224,7 +1224,7 @@ Examples:
1224
1224
  convert photo.png -resize 50% smaller.png
1225
1225
  convert image.jpg -rotate 90 -quality 85 rotated.jpg
1226
1226
  convert input.png -crop 100x100+50+50 cropped.png
1227
- `,stderr:``,exitCode:0}}function Pp(e=`convert`){return z(e,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return Np();let r=[],i=[],a=0;for(;a<t.length;){let n=t[a];if(n===`-resize`){if(a+1>=t.length||t[a+1].startsWith(`-`))return{stdout:``,stderr:`${e}: missing argument for -resize\n`,exitCode:1};i.push({type:`resize`,value:t[a+1]}),a+=2}else if(n===`-rotate`){if(a+1>=t.length||t[a+1].startsWith(`-`))return{stdout:``,stderr:`${e}: missing argument for -rotate\n`,exitCode:1};i.push({type:`rotate`,value:t[a+1]}),a+=2}else if(n===`-crop`){if(a+1>=t.length||t[a+1].startsWith(`-`))return{stdout:``,stderr:`${e}: missing argument for -crop\n`,exitCode:1};i.push({type:`crop`,value:t[a+1]}),a+=2}else if(n===`-quality`){if(a+1>=t.length||t[a+1].startsWith(`-`))return{stdout:``,stderr:`${e}: missing argument for -quality\n`,exitCode:1};i.push({type:`quality`,value:t[a+1]}),a+=2}else if(n.startsWith(`-`))return{stdout:``,stderr:`${e}: unsupported option ${n}\n`,exitCode:1};else r.push(n),a++}if(r.length!==2)return{stdout:``,stderr:`${e}: expected exactly one input file and one output file\n`,exitCode:1};let o=r[0],s=r[1];try{let e=n.fs.resolvePath(n.cwd,o),t=await n.fs.readFileBuffer(e),r=await Ye(),a=null;if(await r.ImageMagick.read(t,async e=>{for(let t of i)switch(t.type){case`resize`:{let n=t.value.match(/^(\d+)%$/);if(n){let t=parseInt(n[1],10),r=Math.round(e.width*t/100),i=Math.round(e.height*t/100);e.resize(r,i)}else{let n=t.value.endsWith(`!`),i=(n?t.value.slice(0,-1):t.value).split(`x`);if(i.length===2){let t=parseInt(i[0],10),a=parseInt(i[1],10);if(n){let n=new r.MagickGeometry(t,a);n.ignoreAspectRatio=!0,e.resize(n)}else e.resize(t,a)}else throw Error(`Invalid resize format: ${t.value}`)}break}case`rotate`:{let n=parseFloat(t.value);if(isNaN(n))throw Error(`Invalid rotation degrees: ${t.value}`);e.rotate(n);break}case`crop`:{if(!t.value.match(/^(\d+)x(\d+)\+(\d+)\+(\d+)$/))throw Error(`Invalid crop format: ${t.value} (expected WxH+X+Y)`);let n=new r.MagickGeometry(t.value);e.crop(n);break}case`quality`:{let n=parseInt(t.value,10);if(isNaN(n)||n<0||n>100)throw Error(`Invalid quality: ${t.value} (must be 0-100)`);e.quality=n;break}}let t=Mp(s);e.write(t,e=>{a=e})}),!a)throw Error(`Failed to generate output image`);let c=n.fs.resolvePath(n.cwd,s);return await n.fs.writeFile(c,a),{stdout:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}var Fp=n(`tray-leader`),Ip=`leader-tray-session`,Lp=3e4,Rp=1e4,zp={state:`inactive`,session:null,error:null};function Bp(){return{...zp,session:zp.session?{...zp.session}:null}}function Vp(e){zp={...e,session:e.session?{...e.session}:null}}var Hp=class{constructor(e=Ip){this.key=e}async load(){return Up(await Fe(this.key))}async save(e){await Ve(this.key,JSON.stringify(e))}async clear(){await Ve(this.key,``)}};function Up(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t.workerBaseUrl!=`string`||typeof t.trayId!=`string`||typeof t.createdAt!=`string`||typeof t.controllerId!=`string`||typeof t.controllerUrl!=`string`||typeof t.joinUrl!=`string`||typeof t.webhookUrl!=`string`||typeof t.runtime!=`string`?null:{workerBaseUrl:t.workerBaseUrl,trayId:t.trayId,createdAt:t.createdAt,controllerId:t.controllerId,controllerUrl:t.controllerUrl,joinUrl:t.joinUrl,webhookUrl:t.webhookUrl,leaderKey:typeof t.leaderKey==`string`?t.leaderKey:void 0,leaderWebSocketUrl:typeof t.leaderWebSocketUrl==`string`?t.leaderWebSocketUrl:null,runtime:t.runtime}}catch{return null}}var Wp=class{store;fetchImpl;webSocketFactory;pingIntervalMs;connectTimeoutMs;socket=null;pingTimer=null;currentSession=null;constructor(e){this.options=e,this.store=e.store??new Hp,this.fetchImpl=e.fetchImpl??Jp(),this.webSocketFactory=e.webSocketFactory??(e=>new WebSocket(e)),this.pingIntervalMs=e.pingIntervalMs??Lp,this.connectTimeoutMs=e.connectTimeoutMs??Rp}async start(){if(this.currentSession&&this.socket)return Vp({state:`leader`,session:this.currentSession,error:null}),this.currentSession;Vp({state:`connecting`,session:null,error:null}),this.currentSession=null;try{let e=await this.store.load(),t=e?.workerBaseUrl===this.options.workerBaseUrl?e:null,n=await this.attachWithRecovery(t);this.currentSession=n;let r=await this.openLeaderSocket(n.leaderWebSocketUrl);return this.socket=r,this.startPingLoop(r),Vp({state:`leader`,session:n,error:null}),Fp.info(`Leader joined tray`,{trayId:n.trayId,controllerId:n.controllerId,runtime:n.runtime}),n}catch(e){throw Vp({state:`error`,session:this.currentSession,error:e instanceof Error?e.message:String(e)}),e}}stop(){if(this.pingTimer&&=(clearInterval(this.pingTimer),null),this.socket){try{this.socket.close()}catch{}this.socket=null}this.currentSession=null,Vp({state:`inactive`,session:null,error:null})}async clearSession(){await this.store.clear()}sendControlMessage(e){if(!this.socket)throw Error(`Tray leader WebSocket is not connected`);this.socket.send(JSON.stringify(e))}async attachWithRecovery(e){try{return await this.claimLeaderSession(e)}catch(t){if(!e||!Kp(t))throw t;return Fp.warn(`Stored tray session is stale, creating a fresh tray`,{trayId:e.trayId,error:t instanceof Error?t.message:String(t)}),await this.store.clear(),this.claimLeaderSession(null)}}async claimLeaderSession(e){let t=e??await this.createTraySession(),n=await this.fetchJson(t.controllerUrl,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:t.controllerId,leaderKey:t.leaderKey,runtime:this.options.runtime})});if(n.role!==`leader`||!n.leaderKey||!n.websocket?.url)throw Error(`Tray attach did not return leader access for controller ${n.controllerId}`);let r={...t,trayId:n.trayId,controllerId:n.controllerId,leaderKey:n.leaderKey,leaderWebSocketUrl:n.websocket.url,runtime:this.options.runtime};return await this.store.save(r),r}async createTraySession(){let e=await this.fetchJson(m(this.options.workerBaseUrl,`tray`),{method:`POST`});return{workerBaseUrl:this.options.workerBaseUrl,trayId:e.trayId,createdAt:e.createdAt,controllerId:crypto.randomUUID(),controllerUrl:e.capabilities.controller.url,joinUrl:e.capabilities.join.url,webhookUrl:e.capabilities.webhook.url,runtime:this.options.runtime}}async openLeaderSocket(e){return await new Promise((t,n)=>{let r=this.webSocketFactory(e),i=!1,a=setTimeout(()=>{o(`Tray leader WebSocket timed out after ${this.connectTimeoutMs}ms waiting for leader.connected`);try{r.close(1e3,`leader.connected timeout`)}catch{}},this.connectTimeoutMs),o=e=>{i||(i=!0,clearTimeout(a),n(Error(e)))};r.addEventListener(`message`,e=>{let n=qp(e.data);if(n){if(n.type===`leader.connected`){i||(i=!0,clearTimeout(a),t(r));return}if(n.type===`pong`){Fp.debug(`Tray leader heartbeat acknowledged`,{trayId:this.currentSession?.trayId});return}this.options.onControlMessage?.(n)}}),r.addEventListener(`close`,()=>o(`Tray leader WebSocket closed before leader.connected`)),r.addEventListener(`error`,()=>o(`Tray leader WebSocket failed before leader.connected`))})}startPingLoop(e){this.pingTimer&&clearInterval(this.pingTimer);let t=()=>{try{e.send(JSON.stringify({type:`ping`}))}catch{this.stop()}};t(),this.pingTimer=setInterval(t,this.pingIntervalMs),e.addEventListener(`close`,()=>this.stop()),e.addEventListener(`error`,()=>this.stop())}async fetchJson(e,t){let n=await this.fetchImpl(e,t);if(!n.ok)throw await Gp.fromResponse(n);return await n.json()}},Gp=class e extends Error{constructor(e,t,n){super(n),this.status=e,this.code=t,this.name=`LeaderTrayHttpError`}static async fromResponse(t){try{let n=await t.json();return new e(t.status,n.code??null,n.error??`Tray request failed (${t.status})`)}catch{return new e(t.status,null,`Tray request failed (${t.status})`)}}};function Kp(e){return e instanceof Gp&&[403,404,410].includes(e.status)}function qp(e){if(typeof e!=`string`)return null;try{return JSON.parse(e)}catch{return null}}function Jp(e=fetch){return typeof chrome<`u`&&chrome?.runtime?.id?e:async(t,n={})=>{let r=typeof t==`string`?t:t.toString();try{if(new URL(r).origin===window.location.origin)return e(r,{...n,cache:`no-store`})}catch{}let i=new Headers(n.headers);i.set(`X-Target-URL`,r);let a=await e(`/api/fetch-proxy`,{...n,headers:i,cache:`no-store`});if(a.status===400||a.status===502){let e=`Proxy error ${a.status}`;try{e=(await a.json()).error??e}catch{}throw Error(e)}return a}}var Yp=null;function Xp(e){Yp=e}function Zp(){return Yp?.()??[]}var Qp=null;function $p(e){Qp=e}function em(){return Qp??void 0}function tm(){return{stdout:`host - display or manage the current tray host status
1227
+ `,stderr:``,exitCode:0}}function Pp(e=`convert`){return z(e,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return Np();let r=[],i=[],a=0;for(;a<t.length;){let n=t[a];if(n===`-resize`){if(a+1>=t.length||t[a+1].startsWith(`-`))return{stdout:``,stderr:`${e}: missing argument for -resize\n`,exitCode:1};i.push({type:`resize`,value:t[a+1]}),a+=2}else if(n===`-rotate`){if(a+1>=t.length||t[a+1].startsWith(`-`))return{stdout:``,stderr:`${e}: missing argument for -rotate\n`,exitCode:1};i.push({type:`rotate`,value:t[a+1]}),a+=2}else if(n===`-crop`){if(a+1>=t.length||t[a+1].startsWith(`-`))return{stdout:``,stderr:`${e}: missing argument for -crop\n`,exitCode:1};i.push({type:`crop`,value:t[a+1]}),a+=2}else if(n===`-quality`){if(a+1>=t.length||t[a+1].startsWith(`-`))return{stdout:``,stderr:`${e}: missing argument for -quality\n`,exitCode:1};i.push({type:`quality`,value:t[a+1]}),a+=2}else if(n.startsWith(`-`))return{stdout:``,stderr:`${e}: unsupported option ${n}\n`,exitCode:1};else r.push(n),a++}if(r.length!==2)return{stdout:``,stderr:`${e}: expected exactly one input file and one output file\n`,exitCode:1};let o=r[0],s=r[1];try{let e=n.fs.resolvePath(n.cwd,o),t=await n.fs.readFileBuffer(e),r=await Ye(),a=null;if(await r.ImageMagick.read(t,async e=>{for(let t of i)switch(t.type){case`resize`:{let n=t.value.match(/^(\d+)%$/);if(n){let t=parseInt(n[1],10),r=Math.round(e.width*t/100),i=Math.round(e.height*t/100);e.resize(r,i)}else{let n=t.value.endsWith(`!`),i=(n?t.value.slice(0,-1):t.value).split(`x`);if(i.length===2){let t=parseInt(i[0],10),a=parseInt(i[1],10);if(n){let n=new r.MagickGeometry(t,a);n.ignoreAspectRatio=!0,e.resize(n)}else e.resize(t,a)}else throw Error(`Invalid resize format: ${t.value}`)}break}case`rotate`:{let n=parseFloat(t.value);if(isNaN(n))throw Error(`Invalid rotation degrees: ${t.value}`);e.rotate(n);break}case`crop`:{if(!t.value.match(/^(\d+)x(\d+)\+(\d+)\+(\d+)$/))throw Error(`Invalid crop format: ${t.value} (expected WxH+X+Y)`);let n=new r.MagickGeometry(t.value);e.crop(n);break}case`quality`:{let n=parseInt(t.value,10);if(isNaN(n)||n<0||n>100)throw Error(`Invalid quality: ${t.value} (must be 0-100)`);e.quality=n;break}}let t=Mp(s);e.write(t,e=>{a=e})}),!a)throw Error(`Failed to generate output image`);let c=n.fs.resolvePath(n.cwd,s);return await n.fs.writeFile(c,a),{stdout:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}var Fp=n(`tray-leader`),Ip=`leader-tray-session`,Lp=3e4,Rp=1e4,zp={state:`inactive`,session:null,error:null};function Bp(){return{...zp,session:zp.session?{...zp.session}:null}}function Vp(e){zp={...e,session:e.session?{...e.session}:null}}var Hp=class{constructor(e=Ip){this.key=e}async load(){return Up(await Ie(this.key))}async save(e){await R(this.key,JSON.stringify(e))}async clear(){await R(this.key,``)}};function Up(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t.workerBaseUrl!=`string`||typeof t.trayId!=`string`||typeof t.createdAt!=`string`||typeof t.controllerId!=`string`||typeof t.controllerUrl!=`string`||typeof t.joinUrl!=`string`||typeof t.webhookUrl!=`string`||typeof t.runtime!=`string`?null:{workerBaseUrl:t.workerBaseUrl,trayId:t.trayId,createdAt:t.createdAt,controllerId:t.controllerId,controllerUrl:t.controllerUrl,joinUrl:t.joinUrl,webhookUrl:t.webhookUrl,leaderKey:typeof t.leaderKey==`string`?t.leaderKey:void 0,leaderWebSocketUrl:typeof t.leaderWebSocketUrl==`string`?t.leaderWebSocketUrl:null,runtime:t.runtime}}catch{return null}}var Wp=class{store;fetchImpl;webSocketFactory;pingIntervalMs;connectTimeoutMs;socket=null;pingTimer=null;currentSession=null;constructor(e){this.options=e,this.store=e.store??new Hp,this.fetchImpl=e.fetchImpl??Jp(),this.webSocketFactory=e.webSocketFactory??(e=>new WebSocket(e)),this.pingIntervalMs=e.pingIntervalMs??Lp,this.connectTimeoutMs=e.connectTimeoutMs??Rp}async start(){if(this.currentSession&&this.socket)return Vp({state:`leader`,session:this.currentSession,error:null}),this.currentSession;Vp({state:`connecting`,session:null,error:null}),this.currentSession=null;try{let e=await this.store.load(),t=e?.workerBaseUrl===this.options.workerBaseUrl?e:null,n=await this.attachWithRecovery(t);this.currentSession=n;let r=await this.openLeaderSocket(n.leaderWebSocketUrl);return this.socket=r,this.startPingLoop(r),Vp({state:`leader`,session:n,error:null}),Fp.info(`Leader joined tray`,{trayId:n.trayId,controllerId:n.controllerId,runtime:n.runtime}),n}catch(e){throw Vp({state:`error`,session:this.currentSession,error:e instanceof Error?e.message:String(e)}),e}}stop(){if(this.pingTimer&&=(clearInterval(this.pingTimer),null),this.socket){try{this.socket.close()}catch{}this.socket=null}this.currentSession=null,Vp({state:`inactive`,session:null,error:null})}async clearSession(){await this.store.clear()}sendControlMessage(e){if(!this.socket)throw Error(`Tray leader WebSocket is not connected`);this.socket.send(JSON.stringify(e))}async attachWithRecovery(e){try{return await this.claimLeaderSession(e)}catch(t){if(!e||!Kp(t))throw t;return Fp.warn(`Stored tray session is stale, creating a fresh tray`,{trayId:e.trayId,error:t instanceof Error?t.message:String(t)}),await this.store.clear(),this.claimLeaderSession(null)}}async claimLeaderSession(e){let t=e??await this.createTraySession(),n=await this.fetchJson(t.controllerUrl,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:t.controllerId,leaderKey:t.leaderKey,runtime:this.options.runtime})});if(n.role!==`leader`||!n.leaderKey||!n.websocket?.url)throw Error(`Tray attach did not return leader access for controller ${n.controllerId}`);let r={...t,trayId:n.trayId,controllerId:n.controllerId,leaderKey:n.leaderKey,leaderWebSocketUrl:n.websocket.url,runtime:this.options.runtime};return await this.store.save(r),r}async createTraySession(){let e=await this.fetchJson(m(this.options.workerBaseUrl,`tray`),{method:`POST`});return{workerBaseUrl:this.options.workerBaseUrl,trayId:e.trayId,createdAt:e.createdAt,controllerId:crypto.randomUUID(),controllerUrl:e.capabilities.controller.url,joinUrl:e.capabilities.join.url,webhookUrl:e.capabilities.webhook.url,runtime:this.options.runtime}}async openLeaderSocket(e){return await new Promise((t,n)=>{let r=this.webSocketFactory(e),i=!1,a=setTimeout(()=>{o(`Tray leader WebSocket timed out after ${this.connectTimeoutMs}ms waiting for leader.connected`);try{r.close(1e3,`leader.connected timeout`)}catch{}},this.connectTimeoutMs),o=e=>{i||(i=!0,clearTimeout(a),n(Error(e)))};r.addEventListener(`message`,e=>{let n=qp(e.data);if(n){if(n.type===`leader.connected`){i||(i=!0,clearTimeout(a),t(r));return}if(n.type===`pong`){Fp.debug(`Tray leader heartbeat acknowledged`,{trayId:this.currentSession?.trayId});return}this.options.onControlMessage?.(n)}}),r.addEventListener(`close`,()=>o(`Tray leader WebSocket closed before leader.connected`)),r.addEventListener(`error`,()=>o(`Tray leader WebSocket failed before leader.connected`))})}startPingLoop(e){this.pingTimer&&clearInterval(this.pingTimer);let t=()=>{try{e.send(JSON.stringify({type:`ping`}))}catch{this.stop()}};t(),this.pingTimer=setInterval(t,this.pingIntervalMs),e.addEventListener(`close`,()=>this.stop()),e.addEventListener(`error`,()=>this.stop())}async fetchJson(e,t){let n=await this.fetchImpl(e,t);if(!n.ok)throw await Gp.fromResponse(n);return await n.json()}},Gp=class e extends Error{constructor(e,t,n){super(n),this.status=e,this.code=t,this.name=`LeaderTrayHttpError`}static async fromResponse(t){try{let n=await t.json();return new e(t.status,n.code??null,n.error??`Tray request failed (${t.status})`)}catch{return new e(t.status,null,`Tray request failed (${t.status})`)}}};function Kp(e){return e instanceof Gp&&[403,404,410].includes(e.status)}function qp(e){if(typeof e!=`string`)return null;try{return JSON.parse(e)}catch{return null}}function Jp(e=fetch){return typeof chrome<`u`&&chrome?.runtime?.id?e:async(t,n={})=>{let r=typeof t==`string`?t:t.toString();try{if(new URL(r).origin===window.location.origin)return e(r,{...n,cache:`no-store`})}catch{}let i=new Headers(n.headers);i.set(`X-Target-URL`,r);let a=await e(`/api/fetch-proxy`,{...n,headers:i,cache:`no-store`});if(a.status===400||a.status===502){let e=`Proxy error ${a.status}`;try{e=(await a.json()).error??e}catch{}throw Error(e)}return a}}var Yp=null;function Xp(e){Yp=e}function Zp(){return Yp?.()??[]}var Qp=null;function $p(e){Qp=e}function em(){return Qp??void 0}function tm(){return{stdout:`host - display or manage the current tray host status
1228
1228
 
1229
1229
  Usage: host [reset]
1230
1230
 
@@ -1267,7 +1267,7 @@ except SystemExit as exc:
1267
1267
  except BaseException:
1268
1268
  traceback.print_exc()
1269
1269
  __slicc_exit_code = 1
1270
- `,pm=null,mm=null,hm=Object.create(null),gm=class extends Error{constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function _m(e){let t=e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e,n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}function vm(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}function ym(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function bm(e){if(/^(https?:\/\/|about:|file:|chrome:)/i.test(e))return!0;try{return new URL(e).protocol.length>0}catch{return!1}}function xm(e,t){return e===`/`?t.startsWith(`/`):t===e||t.startsWith(`${e}/`)}function Sm(e){return Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Cm(e){return e==null?``:e instanceof Uint8Array?`x'${Sm(e)}'`:String(e)}function wm(e){return a(e)}function Tm(e){let t=typeof chrome<`u`&&!!chrome?.runtime?.id,n=`/preview${e}`;return t?chrome.runtime.getURL(n):`${typeof window<`u`&&window.location?.origin?window.location.origin:`http://localhost:5710`}${n}`}function Em(e){return e.length===0||e.startsWith(`/`)?!1:!e.split(`/`).some(e=>e===`..`)}function Dm(e,t){return R(`${e}/${t}`)}function Om(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function km(e,t){let n=import.meta.resolve;if(typeof n==`function`)try{return new URL(`./`,n(e))}catch{}return new URL(t,import.meta.url)}async function Am(){return pm||=(async()=>{let t=(await r(()=>import(`./sql-wasm-CLEWdRiw.js`).then(t=>e(t.default,1)),__vite__mapDeps([3,4,5]))).default,n=typeof window>`u`?km(`sql.js/dist/sql-wasm.js`,`../../../../../node_modules/sql.js/dist/`).toString():lm;return t({locateFile:e=>`${n}${e}`})})(),pm}var jm=typeof chrome<`u`&&!!chrome?.runtime?.id;async function Mm(){return mm||=(async()=>{let{loadPyodide:e}=await r(async()=>{let{loadPyodide:e}=await import(`./pyodide-BIt8RVoH.js`);return{loadPyodide:e}},__vite__mapDeps([6,4,1])),t;return t=typeof window>`u`?decodeURIComponent(km(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname):jm?chrome.runtime.getURL(`pyodide/`):um,e({indexURL:t,fullStdLib:!1})})(),mm}var Nm=new Set([`http`,`https`,`net`,`tls`,`dgram`,`dns`,`cluster`,`worker_threads`,`child_process`,`crypto`,`os`,`stream`,`zlib`,`vm`,`v8`,`perf_hooks`,`readline`,`repl`,`tty`,`inspector`]);function Pm(e){let t=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,n=new Set,r;for(;(r=t.exec(e))!==null;)n.add(r[2]);return[...n]}function Fm(){return{stdout:`usage: node -e <code> [args...]
1270
+ `,pm=null,mm=null,hm=Object.create(null),gm=class extends Error{constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function _m(e){let t=e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e,n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}function vm(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}function ym(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function bm(e){if(/^(https?:\/\/|about:|file:|chrome:)/i.test(e))return!0;try{return new URL(e).protocol.length>0}catch{return!1}}function xm(e,t){return e===`/`?t.startsWith(`/`):t===e||t.startsWith(`${e}/`)}function Sm(e){return Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Cm(e){return e==null?``:e instanceof Uint8Array?`x'${Sm(e)}'`:String(e)}function wm(e){return a(e)}function Tm(e){let t=typeof chrome<`u`&&!!chrome?.runtime?.id,n=`/preview${e}`;return t?chrome.runtime.getURL(n):`${typeof window<`u`&&window.location?.origin?window.location.origin:`http://localhost:5710`}${n}`}function Em(e){return e.length===0||e.startsWith(`/`)?!1:!e.split(`/`).some(e=>e===`..`)}function Dm(e,t){return L(`${e}/${t}`)}function Om(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function km(e,t){let n=import.meta.resolve;if(typeof n==`function`)try{return new URL(`./`,n(e))}catch{}return new URL(t,import.meta.url)}async function Am(){return pm||=(async()=>{let t=(await r(()=>import(`./sql-wasm-CLEWdRiw.js`).then(t=>e(t.default,1)),__vite__mapDeps([3,4,5]))).default,n=typeof window>`u`?km(`sql.js/dist/sql-wasm.js`,`../../../../../node_modules/sql.js/dist/`).toString():lm;return t({locateFile:e=>`${n}${e}`})})(),pm}var jm=typeof chrome<`u`&&!!chrome?.runtime?.id;async function Mm(){return mm||=(async()=>{let{loadPyodide:e}=await r(async()=>{let{loadPyodide:e}=await import(`./pyodide-BIt8RVoH.js`);return{loadPyodide:e}},__vite__mapDeps([6,4,1])),t;return t=typeof window>`u`?decodeURIComponent(km(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname):jm?chrome.runtime.getURL(`pyodide/`):um,e({indexURL:t,fullStdLib:!1})})(),mm}var Nm=new Set([`http`,`https`,`net`,`tls`,`dgram`,`dns`,`cluster`,`worker_threads`,`child_process`,`crypto`,`os`,`stream`,`zlib`,`vm`,`v8`,`perf_hooks`,`readline`,`repl`,`tty`,`inspector`]);function Pm(e){let t=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,n=new Set,r;for(;(r=t.exec(e))!==null;)n.add(r[2]);return[...n]}function Fm(){return{stdout:`usage: node -e <code> [args...]
1271
1271
  `,stderr:``,exitCode:0}}function Im(){return{stdout:`${dm}\n`,stderr:``,exitCode:0}}function Lm(){return z(`node`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return Fm();if(e.includes(`--version`)||e.includes(`-v`))return Im();let n=``,i=`<stdin>`,a=[`node`];if(e.length>0&&(e[0]===`-e`||e[0]===`--eval`)){if(!e[1])return{stdout:``,stderr:`node: option requires an argument -- eval
1272
1272
  `,exitCode:9};n=e[1],i=`[eval]`,a=[`node`,...e.slice(2)]}else if(e.length>0&&!e[0].startsWith(`-`)){let r=e[0],o=t.fs.resolvePath(t.cwd,r);if(!await t.fs.exists(o))return{stdout:``,stderr:`node: cannot find module '${r}'\n`,exitCode:1};n=await t.fs.readFile(o),i=r,a=[`node`,r,...e.slice(1)]}else if(t.stdin.trim().length>0)n=t.stdin,i=`<stdin>`,a=[`node`];else if(e.length>0)return{stdout:``,stderr:`node: unsupported option '${e[0]}'\n`,exitCode:9};else return{stdout:``,stderr:`node: REPL mode is not supported in this environment; use node -e "code"
1273
1273
  `,exitCode:9};let o=[],s=[],c=e=>{o.push(typeof e==`string`?e:String(e))},l=e=>{s.push(typeof e==`string`?e:String(e))},u={log:(...e)=>c(`${e.map(Om).join(` `)}\n`),info:(...e)=>c(`${e.map(Om).join(` `)}\n`),warn:(...e)=>l(`${e.map(Om).join(` `)}\n`),error:(...e)=>l(`${e.map(Om).join(` `)}\n`)},d={argv:a,env:Object.fromEntries(t.env.entries()),cwd:()=>t.cwd,exit:e=>{throw new gm(Number.isFinite(e)?Number(e):0)},stdout:{write:c},stderr:{write:l}},f={readFile:async e=>{let n=t.fs.resolvePath(t.cwd,e);return t.fs.readFile(n)},readFileBinary:async e=>{let n=t.fs.resolvePath(t.cwd,e);return t.fs.readFileBuffer(n)},writeFile:async(e,n)=>{let r=t.fs.resolvePath(t.cwd,e);await t.fs.writeFile(r,n)},writeFileBinary:async(e,n)=>{let r=t.fs.resolvePath(t.cwd,e),i=new Uint8Array(n.byteLength);i.set(n),await t.fs.writeFile(r,i)},readDir:async e=>{let n=t.fs.resolvePath(t.cwd,e);return t.fs.readdir(n)},exists:async e=>{let n=t.fs.resolvePath(t.cwd,e);return t.fs.exists(n)},fetchToFile:async(e,n)=>{if(typeof fetch>`u`)throw Error(`fetch is not available in this runtime`);let r=await fetch(e);if(!r.ok)throw Error(`fetch ${r.status} ${r.statusText}`);let i=new Uint8Array(await r.arrayBuffer()),a=t.fs.resolvePath(t.cwd,n);return await t.fs.writeFile(a,i),i.byteLength}},p=async e=>{if(!t.exec)throw Error(`exec is not available in this runtime`);let n=await t.exec(e,{cwd:t.cwd});return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}},m=typeof chrome<`u`&&!!chrome?.runtime?.id;if(!m){let e=Pm(n),t=new Set([`fs`,`process`,`buffer`]),i=e.map(e=>e.startsWith(`node:`)?e.slice(5):e).filter(e=>!t.has(e)&&!Nm.has(e)),a=hm.__requireCache??=Object.create(null),o=i.filter(e=>!(e in a));if(o.length>0){let e=await Promise.allSettled(o.map(async e=>{let t=await r(()=>import(`https://esm.sh/`+e),[]);a[e]=t&&typeof t==`object`&&`default`in t?t.default:t}));for(let t=0;t<e.length;t++)if(e[t].status===`rejected`){let n=e[t].reason;l(`Warning: failed to pre-load require('${o[t]}'): ${n instanceof Error?n.message:String(n)}\n`)}}}let h=e=>{let t=e.startsWith(`node:`)?e.slice(5):e;if(t===`fs`)return f;if(t===`process`)return d;if(t===`buffer`)return{Buffer:globalThis.Buffer};if(t===`path`){let t=hm.__requireCache;if(t&&`path`in t)return t.path;if(t&&e in t)return t[e];throw Error(`require('${e}'): path module not pre-loaded. Add require('path') as a static import.`)}if(Nm.has(t))throw Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${{http:` Use fetch() instead.`,https:` Use fetch() instead.`,child_process:` Use exec() which is available as a shell bridge.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`}[t]||``}`);let n=hm.__requireCache;if(n&&e in n)return n[e];throw Error(`require('${e}'): module not pre-loaded. Use a string literal or await import('https://esm.sh/${e}') directly.`)},g={exports:{},filename:i};try{if(m){let e=`
@@ -1441,7 +1441,7 @@ For example, try 'man commands'.
1441
1441
  `,exitCode:1};let t=e.join(`-`),n=`https://www.sliccy.com/man/${t}.plain.html`;try{let e=await fetch(n);return e.status===404?{stdout:``,stderr:`No manual entry for ${t}\n`,exitCode:1}:e.ok?{stdout:uh(await e.text())+`
1442
1442
  `,stderr:``,exitCode:0}:{stdout:``,stderr:`man: failed to fetch manual page for ${t}: ${e.status} ${e.statusText}\n`,exitCode:1}}catch(e){return{stdout:``,stderr:`man: ${e.message||String(e)}\n`,exitCode:1}}})}function fh(){return{stdout:`usage: unzip <archive.zip> [-d <destination>]
1443
1443
  `,stderr:``,exitCode:0}}function ph(){return z(`unzip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return fh();let n=`.`,r=[];for(let t=0;t<e.length;t++){let i=e[t];if(i===`-d`){n=e[t+1]??``,t++;continue}if(i.startsWith(`-`))return{stdout:``,stderr:`unzip: unsupported option ${i}\n`,exitCode:1};r.push(i)}if(r.length<1)return{stdout:``,stderr:`unzip: expected archive path
1444
- `,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=t.fs.resolvePath(t.cwd,n||`.`);await t.fs.mkdir(a,{recursive:!0});let o=N(await t.fs.readFileBuffer(i)),s=0;for(let[e,n]of Object.entries(o)){let r=e.replace(/\\/g,`/`);if(!r||r.endsWith(`/`))continue;let i=t.fs.resolvePath(a,r);if(!xm(a,i))return{stdout:``,stderr:`unzip: blocked suspicious path ${e}\n`,exitCode:1};let o=vm(i);o!==`/`&&await t.fs.mkdir(o,{recursive:!0}),await t.fs.writeFile(i,n),s++}return{stdout:`extracted ${s} file(s) to ${a}\n`,stderr:``,exitCode:0}})}function mh(){return{stdout:`usage: webhook <command> [options]
1444
+ `,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=t.fs.resolvePath(t.cwd,n||`.`);await t.fs.mkdir(a,{recursive:!0});let o=j(await t.fs.readFileBuffer(i)),s=0;for(let[e,n]of Object.entries(o)){let r=e.replace(/\\/g,`/`);if(!r||r.endsWith(`/`))continue;let i=t.fs.resolvePath(a,r);if(!xm(a,i))return{stdout:``,stderr:`unzip: blocked suspicious path ${e}\n`,exitCode:1};let o=vm(i);o!==`/`&&await t.fs.mkdir(o,{recursive:!0}),await t.fs.writeFile(i,n),s++}return{stdout:`extracted ${s} file(s) to ${a}\n`,stderr:``,exitCode:0}})}function mh(){return{stdout:`usage: webhook <command> [options]
1445
1445
 
1446
1446
  Commands:
1447
1447
  create --scoop <name> [--name <name>] [--filter <code>] Create a new webhook endpoint
@@ -1566,7 +1566,7 @@ on success.
1566
1566
  Examples:
1567
1567
  oauth-token adobe
1568
1568
  curl -H "Authorization: Bearer $(oauth-token adobe)" https://api.corp.com/data
1569
- `}function zh(){return z(`oauth-token`,async e=>{let{getOAuthAccountInfo:t,getSelectedProvider:n,getAccounts:i}=await r(async()=>{let{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}=await import(`./provider-settings-C5wu60VY.js`);return{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}},__vite__mapDeps([10,11,4,1,12,13,14,15,16,17])),{getRegisteredProviderConfig:a,getRegisteredProviderIds:o}=await r(async()=>{let{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}=await import(`./providers-BBlrK0ha.js`);return{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}},__vite__mapDeps([18,11,4,1,12,13,14,15,16,17]));if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Rh(),stderr:``,exitCode:0};if(e.includes(`--list`))return Bh(i,o,a,t);let s,c=e.indexOf(`--provider`);if(c>=0){if(s=e[c+1],!s)return{stdout:``,stderr:`oauth-token: --provider requires a value
1569
+ `}function zh(){return z(`oauth-token`,async e=>{let{getOAuthAccountInfo:t,getSelectedProvider:n,getAccounts:i}=await r(async()=>{let{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}=await import(`./provider-settings-DDuKtmwj.js`);return{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}},__vite__mapDeps([10,11,4,1,12,13,14,15,16,17])),{getRegisteredProviderConfig:a,getRegisteredProviderIds:o}=await r(async()=>{let{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}=await import(`./providers-BjLZ1m3N.js`);return{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}},__vite__mapDeps([18,11,4,1,12,13,14,15,16,17]));if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Rh(),stderr:``,exitCode:0};if(e.includes(`--list`))return Bh(i,o,a,t);let s,c=e.indexOf(`--provider`);if(c>=0){if(s=e[c+1],!s)return{stdout:``,stderr:`oauth-token: --provider requires a value
1570
1570
  `,exitCode:1}}else if(e.length>0)s=e[0];else{let e=n(),t=a(e);if(t?.isOAuth&&t.onOAuthLogin)s=e;else if(s=o().find(e=>{let t=a(e);return t?.isOAuth&&t.onOAuthLogin}),!s)return{stdout:``,stderr:`oauth-token: no OAuth providers configured
1571
1571
  `,exitCode:1}}let l=a(s);if(!l)return{stdout:``,stderr:`oauth-token: unknown provider "${s}"\n`,exitCode:1};if(!l.isOAuth||!l.onOAuthLogin)return{stdout:``,stderr:`oauth-token: provider "${s}" is not an OAuth provider\n`,exitCode:1};let u=t(s);if(u&&!u.expired)return{stdout:`${u.token}\n`,stderr:``,exitCode:0};try{let{createOAuthLauncher:e}=await r(async()=>{let{createOAuthLauncher:e}=await import(`./oauth-service-BPHxAgX7.js`);return{createOAuthLauncher:e}},[]),n=e();await l.onOAuthLogin(n,()=>{});let i=t(s);return i&&i.token?{stdout:`${i.token}\n`,stderr:``,exitCode:0}:(console.error(`[oauth-token] Provider ${s}: login completed but no token was saved`),{stdout:``,stderr:`oauth-token: login completed but no token was saved
1572
1572
  `,exitCode:1})}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${s}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}function Bh(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
@@ -1646,7 +1646,7 @@ Exit code 0 if all commands found, 1 if any not found.
1646
1646
  `:``,stderr:``,exitCode:+!s}})}async function pg(e,t,n,r){if((await e.fs.stat(t)).isFile)return r[n]=await e.fs.readFileBuffer(t),1;let i=await e.fs.readdir(t),a=0;for(let o of i){let i=ym(t,o),s=n?`${n}/${o}`:o;a+=await pg(e,i,s,r)}return a}function mg(){return{stdout:`usage: zip [-r] <archive.zip> <path> [path...]
1647
1647
  `,stderr:``,exitCode:0}}function hg(){return z(`zip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return mg();let n=!1,r=[];for(let t of e){if(t===`-r`){n=!0;continue}if(t.startsWith(`-`))return{stdout:``,stderr:`zip: unsupported option ${t}\n`,exitCode:1};r.push(t)}if(r.length<2)return{stdout:``,stderr:`zip: expected archive path and at least one input path
1648
1648
  `,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=r.slice(1),o={},s=0;for(let e of a){let r=t.fs.resolvePath(t.cwd,e),i=await t.fs.stat(r),a=(e.startsWith(`/`)?e.slice(1):e.replace(/^\.\//,``))||_m(r);if(i.isDirectory&&!n)return{stdout:``,stderr:`zip: ${e} is a directory (use -r)\n`,exitCode:1};s+=await pg(t,r,a,o)}if(s===0)return{stdout:``,stderr:`zip: nothing to do
1649
- `,exitCode:1};let c=F(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function gg(){return{stdout:`screencapture - capture screen, window, or tab using browser screen sharing
1649
+ `,exitCode:1};let c=N(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function gg(){return{stdout:`screencapture - capture screen, window, or tab using browser screen sharing
1650
1650
 
1651
1651
  Usage: screencapture [options] <output-file>
1652
1652
 
@@ -1726,7 +1726,7 @@ Options:
1726
1726
  -h, --help Show this help message
1727
1727
  `}function Yg(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function Xg(e){return`$${e.toFixed(2)}`}var Zg=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function Qg(e){let t=`${e.id} ${e.name??``}`;return!Zg.test(t)}function $g(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 e_(e){let t=new Map;for(let n of e){let e=$g(n.id);t.has(e)||t.set(e,n)}return[...t.values()]}function t_(e,t,n,r,i){let a=i?qg(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 n_(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=`${Xg(e.cost.input)} / ${Xg(e.cost.output)}`,a=`${Yg(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(`
1728
1728
  `)+`
1729
- `}function r_(e){return z(`models`,async t=>{let{getAccounts:n,getAvailableProviders:i,getProviderConfig:a,getProviderModels:o,getSelectedProvider:s,getSelectedModelId:c}=await r(async()=>{let{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}=await import(`./provider-settings-C5wu60VY.js`);return{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}},__vite__mapDeps([10,11,4,1,12,13,14,15,16,17]));if(t.includes(`--help`)||t.includes(`-h`))return{stdout:Jg(),stderr:``,exitCode:0};let l=t.includes(`--json`),u=t.includes(`--all`),d=t.includes(`--all-versions`),f=t.includes(`--refresh`),p=t.includes(`--no-benchmarks`),m=t.indexOf(`--provider`),h=m>=0?t[m+1]:void 0,g=s(),_=c(),v=n();if(v.length===0)return{stdout:``,stderr:`No provider accounts configured. Run the provider settings to add one.
1729
+ `}function r_(e){return z(`models`,async t=>{let{getAccounts:n,getAvailableProviders:i,getProviderConfig:a,getProviderModels:o,getSelectedProvider:s,getSelectedModelId:c}=await r(async()=>{let{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}=await import(`./provider-settings-DDuKtmwj.js`);return{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}},__vite__mapDeps([10,11,4,1,12,13,14,15,16,17]));if(t.includes(`--help`)||t.includes(`-h`))return{stdout:Jg(),stderr:``,exitCode:0};let l=t.includes(`--json`),u=t.includes(`--all`),d=t.includes(`--all-versions`),f=t.includes(`--refresh`),p=t.includes(`--no-benchmarks`),m=t.indexOf(`--provider`),h=m>=0?t[m+1]:void 0,g=s(),_=c(),v=n();if(v.length===0)return{stdout:``,stderr:`No provider accounts configured. Run the provider settings to add one.
1730
1730
  `,exitCode:1};let y;p||(y=await Gg(e,f),y.length===0&&(y=void 0));let b;if(h){let e=i();if(!e.includes(h))return{stdout:``,stderr:`Unknown provider: ${h}. Available: ${e.join(`, `)}\n`,exitCode:1};b=[h]}else b=u?[...new Set(v.map(e=>e.providerId))]:[g];let x=[],S=[];for(let e of b){let t=o(e).filter(Qg);if(t.length===0){if(!u)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>t_(t,e,_,g,y)).sort((e,t)=>t.cost.input-e.cost.input);if(d||(n=e_(n)),x.push(...n),!l){let t=a(e);S.push(n_(t.name,e,n,!!y))}}return l?{stdout:JSON.stringify(x,null,2)+`
1731
1731
  `,stderr:``,exitCode:0}:(!d&&!l&&S.push(`Showing latest versions only. Use --all-versions to see all.
1732
1732
  `),{stdout:S.join(`
@@ -1738,7 +1738,7 @@ Requires the secret launch code to proceed.
1738
1738
  `,stderr:``,exitCode:0}:e.join(``).includes(`1234`)?(indexedDB.databases().then(e=>{for(let t of e)t.name&&indexedDB.deleteDatabase(t.name)}),setTimeout(()=>location.reload(),0),{stdout:`Nuking everything…
1739
1739
  `,stderr:``,exitCode:0}):{stdout:``,stderr:`⚠️ WARNING: this will reset the entire environment, file system, chats, and scoops.
1740
1740
  Run nuke again with the secret launch code to proceed.
1741
- `,exitCode:1})}function a_(e={}){let t=[jp({getJshCommands:e.getJshCommands}),am(),ih(e.browserAPI,e.fs),Vm(),cm(e),hg(),ph(),oh(`sqlite3`),oh(`sqllite`),Lm(),th(`python3`),th(`python`),gh(),Ch(),Eh(),Lh(),Xm(`pdftk`),Xm(`pdf`),Pp(`convert`),Pp(`magick`),fg({fs:e.fs,scriptCatalog:e.scriptCatalog}),ch(),dh(),zh(),Wh(),sg({fs:e.fs}),bg(),Dg(),Og(),kg(`xclip`),kg(`xsel`),Pg(),zg(),Bg(),r_(e.fs),Ge(),i_()];return typeof chrome<`u`&&chrome?.runtime?.id&&t.push(Vg()),e.fs&&t.push(...Rf.map(t=>Op(t,e.browserAPI,e.fs))),t}var o_=`https://wry-manatee-359.convex.site/api/v1`,s_=`https://api.tessl.io`,c_=`/workspace/skills`,l_=`slicc-fs-global`,u_=`/workspace/.git/github-token`,d_=`application/vnd.github.v3+json`,f_=`https://www.sliccy.com/skills/catalog.json`;function p_(e){if(!(!e||!e.trim()))return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function m_(e){return e.map(e=>{let t=e.boost?parseFloat(e.boost):NaN,n=Number.isFinite(t)?t:void 0;return{name:e.name,displayName:e.displayName||e.name,description:e.description||``,source:{repo:e.repo,path:e.path||void 0,skill:e.skill||void 0},affinity:{apps:p_(e.apps),tasks:p_(e.tasks),role:p_(e.role),purpose:p_(e.purpose)},priority:n}})}var h_={apps:3,tasks:2,role:1,purpose:1};function g_(e,t){return e.map(e=>{let n=0,r=[],i=(e.affinity.apps??[]).filter(e=>t.apps.includes(e));i.length&&(n+=i.length*h_.apps,r.push(`apps(${i.join(`, `)})`));let a=(e.affinity.tasks??[]).filter(e=>t.tasks.includes(e));return a.length&&(n+=a.length*h_.tasks,r.push(`tasks(${a.join(`, `)})`)),(e.affinity.role??[]).includes(t.role)&&(n+=h_.role,r.push(`role(${t.role})`)),(e.affinity.purpose??[]).includes(t.purpose)&&(n+=h_.purpose,r.push(`purpose(${t.purpose})`)),n*=e.priority??1,{entry:e,score:n,matchReasons:r}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score)}function __(e){let t=`upskill ${e.repo}`;return e.path&&(t+=` --path ${e.path}`),e.skill&&(t+=` --skill ${e.skill}`),t}async function v_(e){let t=new Set;try{let n=await e.readDir(c_);for(let e of n)e.type===`directory`&&t.add(e.name)}catch{}try{let n=await e.readTextFile(`/${P}/${I}`),r=JSON.parse(n);for(let e of r.applied_skills??[])t.add(e.name)}catch{}let n=[`.agents`,`.claude`];try{let r=await e.readDir(`/`);for(let i of r)if(i.type===`directory`)for(let r of n)try{let n=`/${i.name}/${r}/skills`,a=await e.readDir(n);for(let e of a)e.type===`directory`&&t.add(e.name)}catch{}}catch{}return t}var y_;function b_(){return y_||=L.create({dbName:l_}),y_}async function x_(){try{return(await(await b_()).readTextFile(u_)).trim()||void 0}catch{return}}function S_(e,t=d_){let n={Accept:t,"User-Agent":`slicc-upskill`};return e&&(n.Authorization=`Bearer ${e}`),n}async function C_(e){let t=await x_();return{hasToken:!!t,request:(n,r=d_)=>e(n,{headers:S_(t,r)})}}function w_(e,t){if(!e)return;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r}function T_(e){let t=Da(e);if(!t)return;try{let e=JSON.parse(t);if(typeof e.message==`string`&&e.message.trim())return e.message.trim()}catch{}let n=t.trim();if(n)return n.slice(0,200)}function E_(e,t,n){let r=T_(e.body),i=r?` GitHub said: ${r}`:``,a=w_(e.headers,`retry-after`),o=w_(e.headers,`x-ratelimit-remaining`),s=r?.toLowerCase()??``;if(e.status===429||o===`0`||s.includes(`rate limit`))return n?`GitHub rate-limited access to ${t} (HTTP ${e.status}). The configured github.token was used, so retry later${a?` after about ${a} seconds`:``}.${i}`:`GitHub rate-limited anonymous access to ${t} (HTTP ${e.status}). This often happens on shared VPNs or corporate egress IPs because unauthenticated GitHub API requests are limited per IP. Configure a token with: git config github.token <PAT>, then retry. You can also retry off VPN or later.${i}`;if(e.status===401)return n?`GitHub rejected the configured github.token while accessing ${t} (HTTP 401). Update it with: git config github.token <PAT>, then retry.${i}`:`GitHub requires authentication to access ${t} (HTTP 401). Configure a token with: git config github.token <PAT>, then retry.${i}`;if(e.status===404)return`GitHub could not find ${t} (HTTP 404). Check the repository, path, and permissions.${i}`;if(e.status===403)return n?`GitHub denied access to ${t} (HTTP 403). Check that your github.token can access this repository or retry later if GitHub is throttling requests.${i}`:`GitHub denied anonymous access to ${t} (HTTP 403). If this repo is public on a shared VPN, you may have hit GitHub's shared IP limit; otherwise the repository or path may require authentication. Configure a token with: git config github.token <PAT>, then retry.${i}`;let c=e.statusText?` ${e.statusText}`:``;return`GitHub request for ${t} failed (HTTP ${e.status}${c}).${i}`}function D_(){return`Discovery roots: /workspace/skills plus accessible **/.agents/skills/* and **/.claude/skills/* anywhere in the VFS.
1741
+ `,exitCode:1})}function a_(e={}){let t=[jp({getJshCommands:e.getJshCommands}),am(),ih(e.browserAPI,e.fs),Vm(),cm(e),hg(),ph(),oh(`sqlite3`),oh(`sqllite`),Lm(),th(`python3`),th(`python`),gh(),Ch(),Eh(),Lh(),Xm(`pdftk`),Xm(`pdf`),Pp(`convert`),Pp(`magick`),fg({fs:e.fs,scriptCatalog:e.scriptCatalog}),ch(),dh(),zh(),Wh(),sg({fs:e.fs}),bg(),Dg(),Og(),kg(`xclip`),kg(`xsel`),Pg(),zg(),Bg(),r_(e.fs),Ge(),i_()];return typeof chrome<`u`&&chrome?.runtime?.id&&t.push(Vg()),e.fs&&t.push(...Rf.map(t=>Op(t,e.browserAPI,e.fs))),t}var o_=`https://wry-manatee-359.convex.site/api/v1`,s_=`https://api.tessl.io`,c_=`/workspace/skills`,l_=`slicc-fs-global`,u_=`/workspace/.git/github-token`,d_=`application/vnd.github.v3+json`,f_=`https://www.sliccy.com/skills/catalog.json`;function p_(e){if(!(!e||!e.trim()))return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function m_(e){return e.map(e=>{let t=e.boost?parseFloat(e.boost):NaN,n=Number.isFinite(t)?t:void 0;return{name:e.name,displayName:e.displayName||e.name,description:e.description||``,source:{repo:e.repo,path:e.path||void 0,skill:e.skill||void 0},affinity:{apps:p_(e.apps),tasks:p_(e.tasks),role:p_(e.role),purpose:p_(e.purpose)},priority:n}})}var h_={apps:3,tasks:2,role:1,purpose:1};function g_(e,t){return e.map(e=>{let n=0,r=[],i=(e.affinity.apps??[]).filter(e=>t.apps.includes(e));i.length&&(n+=i.length*h_.apps,r.push(`apps(${i.join(`, `)})`));let a=(e.affinity.tasks??[]).filter(e=>t.tasks.includes(e));return a.length&&(n+=a.length*h_.tasks,r.push(`tasks(${a.join(`, `)})`)),(e.affinity.role??[]).includes(t.role)&&(n+=h_.role,r.push(`role(${t.role})`)),(e.affinity.purpose??[]).includes(t.purpose)&&(n+=h_.purpose,r.push(`purpose(${t.purpose})`)),n*=e.priority??1,{entry:e,score:n,matchReasons:r}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score)}function __(e){let t=`upskill ${e.repo}`;return e.path&&(t+=` --path ${e.path}`),e.skill&&(t+=` --skill ${e.skill}`),t}async function v_(e){let t=new Set;try{let n=await e.readDir(c_);for(let e of n)e.type===`directory`&&t.add(e.name)}catch{}try{let n=await e.readTextFile(`/${M}/${P}`),r=JSON.parse(n);for(let e of r.applied_skills??[])t.add(e.name)}catch{}let n=[`.agents`,`.claude`];try{let r=await e.readDir(`/`);for(let i of r)if(i.type===`directory`)for(let r of n)try{let n=`/${i.name}/${r}/skills`,a=await e.readDir(n);for(let e of a)e.type===`directory`&&t.add(e.name)}catch{}}catch{}return t}var y_;function b_(){return y_||=F.create({dbName:l_}),y_}async function x_(){try{return(await(await b_()).readTextFile(u_)).trim()||void 0}catch{return}}function S_(e,t=d_){let n={Accept:t,"User-Agent":`slicc-upskill`};return e&&(n.Authorization=`Bearer ${e}`),n}async function C_(e){let t=await x_();return{hasToken:!!t,request:(n,r=d_)=>e(n,{headers:S_(t,r)})}}function w_(e,t){if(!e)return;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r}function T_(e){let t=Da(e);if(!t)return;try{let e=JSON.parse(t);if(typeof e.message==`string`&&e.message.trim())return e.message.trim()}catch{}let n=t.trim();if(n)return n.slice(0,200)}function E_(e,t,n){let r=T_(e.body),i=r?` GitHub said: ${r}`:``,a=w_(e.headers,`retry-after`),o=w_(e.headers,`x-ratelimit-remaining`),s=r?.toLowerCase()??``;if(e.status===429||o===`0`||s.includes(`rate limit`))return n?`GitHub rate-limited access to ${t} (HTTP ${e.status}). The configured github.token was used, so retry later${a?` after about ${a} seconds`:``}.${i}`:`GitHub rate-limited anonymous access to ${t} (HTTP ${e.status}). This often happens on shared VPNs or corporate egress IPs because unauthenticated GitHub API requests are limited per IP. Configure a token with: git config github.token <PAT>, then retry. You can also retry off VPN or later.${i}`;if(e.status===401)return n?`GitHub rejected the configured github.token while accessing ${t} (HTTP 401). Update it with: git config github.token <PAT>, then retry.${i}`:`GitHub requires authentication to access ${t} (HTTP 401). Configure a token with: git config github.token <PAT>, then retry.${i}`;if(e.status===404)return`GitHub could not find ${t} (HTTP 404). Check the repository, path, and permissions.${i}`;if(e.status===403)return n?`GitHub denied access to ${t} (HTTP 403). Check that your github.token can access this repository or retry later if GitHub is throttling requests.${i}`:`GitHub denied anonymous access to ${t} (HTTP 403). If this repo is public on a shared VPN, you may have hit GitHub's shared IP limit; otherwise the repository or path may require authentication. Configure a token with: git config github.token <PAT>, then retry.${i}`;let c=e.statusText?` ${e.statusText}`:``;return`GitHub request for ${t} failed (HTTP ${e.status}${c}).${i}`}function D_(){return`Discovery roots: /workspace/skills plus accessible **/.agents/skills/* and **/.claude/skills/* anywhere in the VFS.
1742
1742
  `}function O_(){return`Only native /workspace/skills entries are install-managed; compatibility-discovered .agents/.claude skills remain read-only.
1743
1743
  `}function k_(e){switch(e){case`native`:return`native`;case`agents`:return`.agents`;case`claude`:return`.claude`}}function A_(e){return e.source===`native`}function j_(e){return A_(e)?e.installed&&e.installedVersion?`installed (v${e.installedVersion})`:`available`:e.installed&&e.installedVersion?`compatibility (state v${e.installedVersion})`:`compatibility (read-only)`}function M_(e){return A_(e)?`install-managed (/workspace/skills)`:`compatibility-only (read-only)`}function N_(e,t){let n=`${t}:\n\n`;n+=` NAME VERSION SOURCE STATUS
1744
1744
  `,n+=` ─────────────────────────────────────────────────────────────
@@ -1802,7 +1802,7 @@ Examples:
1802
1802
  `}return f<d&&(h+=`Showing ${p+1}-${p+m.length} of ${u}. `,h+=`Next page: upskill search ${e} --page ${f+1}\n\n`),h+=`To install:
1803
1803
  `,a.length>0&&(h+=` From ClawHub: upskill clawhub:<slug>
1804
1804
  `),o.length>0&&(h+=` From Tessl: upskill <owner/repo> --skill <name>
1805
- `),{stdout:h,stderr:``,exitCode:0}}async function H_(e,t,n,r=!1,i){try{let a=`${c_}/${e}`;try{if(await t.stat(a),!r)return{stdout:``,stderr:`upskill: skill "${e}" already exists (use --force to overwrite)\n`,exitCode:1};await t.rm(a,{recursive:!0})}catch{}let o=`${o_}/download?slug=${encodeURIComponent(e)}`,s=await n(o,{});if(s.status===404)return{stdout:``,stderr:`upskill: skill "${e}" not found on ClawHub\n`,exitCode:1};if(s.status!==200)return{stdout:``,stderr:`upskill: failed to download skill (HTTP ${s.status})\n`,exitCode:1};let c=s.headers[`content-type`]||``,l=Ca(o);l||=ka(s.body);let u;try{u=N(l)}catch(e){let t=e instanceof Error?e.message:String(e),n=Array.from(l.slice(0,20)).map(e=>e.toString(16).padStart(2,`0`)).join(` `);return{stdout:``,stderr:`upskill: failed to unzip: ${t}\nContent-Type: ${c}\nBody: ${l.length} bytes\nHex: ${n}\n`,exitCode:1}}await t.mkdir(a,{recursive:!0});let d=0;for(let[e,n]of Object.entries(u)){let r=e.replace(/\\/g,`/`);if(!r||r.endsWith(`/`)||r===`_meta.json`)continue;let i=`${a}/${r}`,o=i.substring(0,i.lastIndexOf(`/`));o!==a&&await t.mkdir(o,{recursive:!0}),await t.writeFile(i,n),d++}let f=U_(u,i);return await Z_(),{stdout:`Installed skill "${e}" from ClawHub (${d} files)\n${f}`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`upskill: failed to install from ClawHub: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function U_(e,t){let n;for(let[t,r]of Object.entries(e))if((t.split(`/`).pop()||``).toLowerCase()===`skill.md`){n=new TextDecoder().decode(r);break}if(!n)return``;let r=n.match(/^---\s*\n([\s\S]*?)\n---/);if(!r)return``;let i=r[1],a=W_(i);if(a.length===0)return``;if(!t||t.length===0)return` Requires: ${a.join(`, `)}\n`;let o=new Set(t),s=a.filter(e=>!o.has(e));return s.length===0?` Requires: ${a.join(`, `)} (all available)\n`:` Requires: ${a.join(`, `)}\n Missing: ${s.join(`, `)} -- this skill may not work in the SLICC shell\n`}function W_(e){let t=e.match(/metadata:\s*\n\s*(\{[\s\S]*\})/);if(t)try{let e=JSON.parse(t[1]);for(let t of[`openclaw`,`clawdis`,`clawdbot`]){let n=e[t];if(n?.requires&&typeof n.requires==`object`){let e=n.requires;if(Array.isArray(e.bins))return e.bins.filter(e=>typeof e==`string`)}}}catch{}let n=e.match(/"bins"\s*:\s*\[([^\]]*)\]/);return n?n[1].split(`,`).map(e=>e.trim().replace(/^["']|["']$/g,``)).filter(Boolean):[]}async function G_(e,t){let n=await t(`${s_}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=5`,{headers:{Accept:`application/json`}});if(n.status!==200)return{error:`Tessl search failed (HTTP ${n.status})`};let r=Oa(n.body).data?.find(t=>t.type===`skill`&&t.attributes.name===e);if(!r)return{error:`skill "${e}" not found on Tessl registry`};let i=R_(r.attributes.sourceUrl);if(!i)return{error:`skill "${e}" has no GitHub source URL`};let a=r.attributes.path.replace(/\/SKILL\.md$/i,``);return{owner:i.owner,repo:i.repo,skillPath:a,skillName:e}}async function K_(e,t,n,r=`main`){let i=`https://codeload.github.com/${e}/${t}/zip/refs/heads/${r}`,a=await n(i,{headers:{"User-Agent":`slicc-upskill`}});if(a.status===404)return r===`main`?K_(e,t,n,`master`):{status:`not_found`};if(a.status!==200)return{status:`error`,message:`codeload returned HTTP ${a.status}`};let o=Ca(i);o||=ka(a.body);try{return{status:`ok`,files:N(o)}}catch(e){return{status:`error`,message:`failed to unzip: ${e instanceof Error?e.message:String(e)}`}}}function q_(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.indexOf(`/`);if(e<0)continue;let i=n.slice(e+1);i&&(t[i]=r)}return t}async function J_(e,t,n,r,i,a){if(i){let n=await K_(e,t,i,a);if(n.status===`ok`){let e=q_(n.files),t=[],i=r?r.replace(/^\/|\/$/g,``)+`/`:``;for(let n of Object.keys(e))if(n.startsWith(i)&&(n.split(`/`).pop()||``)===`SKILL.md`){let e=n.replace(/\/SKILL\.md$/,``),r=e.split(`/`).pop()||e;t.push({name:r,path:e})}return{skills:t}}if(n.status===`not_found`)return{skills:[],error:`${a?`branch "${a}" in ${e}/${t}`:`repository ${e}/${t}`} not found`}}let o=[];async function s(r){let i=`https://api.github.com/repos/${e}/${t}/contents/${r}`,c=a?`${i}?ref=${encodeURIComponent(a)}`:i,l=await n.request(c);if(l.status!==200)throw Error(E_(l,`${e}/${t}${r?`/${r}`:``}`,n.hasToken));let u=Oa(l.body);for(let e of u)if(e.type===`file`&&e.name===`SKILL.md`){let t=e.path.replace(`/SKILL.md`,``),n=t.split(`/`).pop()||t;o.push({name:n,path:t})}else e.type===`dir`&&await s(e.path)}try{return await s(r||``),{skills:o}}catch(e){return{skills:[],error:e instanceof Error?e.message:String(e)}}}async function Y_(e,t,n,r,i,a,o=!1,s,c){try{let l=`${c_}/${r}`;try{if(await i.stat(l),!o)return{stdout:``,stderr:`upskill: skill "${r}" already exists (use --force to overwrite)\n`,exitCode:1};await i.rm(l,{recursive:!0})}catch{}if(s){let a=await K_(e,t,s,c);if(a.status===`not_found`)return{stdout:``,stderr:`upskill: ${c?`branch "${c}" in ${e}/${t}`:`repository ${e}/${t}`} not found\n`,exitCode:1};if(a.status===`ok`){let o=q_(a.files),s=n.replace(/^\/|\/$/g,``)+`/`;await i.mkdir(l,{recursive:!0});let c=0;for(let[e,t]of Object.entries(o)){if(!e.startsWith(s))continue;let n=e.slice(s.length);if(!n||e.endsWith(`/`))continue;let r=`${l}/${n}`,a=r.substring(0,r.lastIndexOf(`/`));a!==l&&await i.mkdir(a,{recursive:!0}),await i.writeFile(r,t),c++}if(c>0)return await tv(),await $_(),{stdout:`Installed skill "${r}" from ${e}/${t}\n`,stderr:``,exitCode:0}}}let u=`https://api.github.com/repos/${e}/${t}/contents/${n}`,d=c?`${u}?ref=${encodeURIComponent(c)}`:u,f=await a.request(d);if(f.status!==200)return{stdout:``,stderr:`upskill: ${E_(f,`${e}/${t}/${n}`,a.hasToken)}\n`,exitCode:1};let p=Oa(f.body);await i.mkdir(l,{recursive:!0});async function m(n,r){for(let o of n)if(o.type===`file`&&o.download_url){let n=await a.request(o.download_url,`*/*`);if(n.status!==200)throw Error(E_(n,`${e}/${t}/${o.path}`,a.hasToken));let s=Ca(o.download_url);await i.writeFile(`${r}/${o.name}`,s??n.body)}else if(o.type===`dir`){let n=`https://api.github.com/repos/${e}/${t}/contents/${o.path}`,s=c?`${n}?ref=${encodeURIComponent(c)}`:n,l=await a.request(s);if(l.status!==200)throw Error(E_(l,`${e}/${t}/${o.path}`,a.hasToken));let u=Oa(l.body);await i.mkdir(`${r}/${o.name}`,{recursive:!0}),await m(u,`${r}/${o.name}`)}}try{await m(p,l)}catch(e){try{await i.rm(l,{recursive:!0})}catch{}throw e}return await Z_(),{stdout:`Installed skill "${r}" from ${e}/${t}\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`upskill: failed to install from GitHub: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function X_(e){let t=e.match(/^https?:\/\/clawhub\.ai\/[^\/]+\/([^\/]+)/);if(t)return t[1];if(e.startsWith(`clawhub:`)){let t=e.slice(8);return t.includes(`/`)?t.split(`/`)[1]:t}return null}async function Z_(){await tv(),await $_()}async function Q_(e,t,n,r,i=!1){let a=`${c_}/${t}`;try{if(await r.stat(a),!i)return{ok:!1,error:`skill "${t}" already exists (use --force to overwrite)`};await r.rm(a,{recursive:!0})}catch{}let o=e.replace(/^\/|\/$/g,``),s=o?o+`/`:``;await r.mkdir(a,{recursive:!0});let c=0;try{for(let[e,t]of Object.entries(n)){if(!e.startsWith(s))continue;let n=e.slice(s.length);if(!n||e.endsWith(`/`))continue;let i=`${a}/${n}`,o=i.replace(/\/+/g,`/`);if(o.includes(`/../`)||o.includes(`/..`)||!o.startsWith(a+`/`))continue;let l=i.substring(0,i.lastIndexOf(`/`));l!==a&&await r.mkdir(l,{recursive:!0}),await r.writeFile(i,t),c++}}catch(e){throw await r.rm(a,{recursive:!0}).catch(()=>{}),e}return c===0?(await r.rm(a,{recursive:!0}).catch(()=>{}),{ok:!1,error:`no files found for skill "${t}" in ZIP`}):{ok:!0}}async function $_(){try{let e=(typeof window<`u`?window:globalThis).__slicc_reloadSkills;if(typeof e==`function`){await e();return}typeof chrome<`u`&&chrome?.runtime?.sendMessage&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}})}catch{}}function ev(e){let t=e.match(/^([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_.-]+)(?:@([a-zA-Z0-9_./\-]+))?$/);return t?{owner:t[1],repo:t[2],branch:t[3]}:null}async function tv(){try{if(typeof window>`u`)return;let e=window.__slicc_sprinkleManager;e&&typeof e.openNewAutoOpenSprinkles==`function`&&await e.openNewAutoOpenSprinkles()}catch{}}async function nv(e,t,n){let r=null;try{let t=await e.readDir(`/home`);for(let n of t)try{let t=await e.readTextFile(`/home/${n.name}/.welcome.json`);r=JSON.parse(t);break}catch{}}catch{}if(!r)return{stdout:``,stderr:`upskill: no user profile found. Complete the welcome onboarding first, or create /home/<name>/.welcome.json manually.
1805
+ `),{stdout:h,stderr:``,exitCode:0}}async function H_(e,t,n,r=!1,i){try{let a=`${c_}/${e}`;try{if(await t.stat(a),!r)return{stdout:``,stderr:`upskill: skill "${e}" already exists (use --force to overwrite)\n`,exitCode:1};await t.rm(a,{recursive:!0})}catch{}let o=`${o_}/download?slug=${encodeURIComponent(e)}`,s=await n(o,{});if(s.status===404)return{stdout:``,stderr:`upskill: skill "${e}" not found on ClawHub\n`,exitCode:1};if(s.status!==200)return{stdout:``,stderr:`upskill: failed to download skill (HTTP ${s.status})\n`,exitCode:1};let c=s.headers[`content-type`]||``,l=Ca(o);l||=ka(s.body);let u;try{u=j(l)}catch(e){let t=e instanceof Error?e.message:String(e),n=Array.from(l.slice(0,20)).map(e=>e.toString(16).padStart(2,`0`)).join(` `);return{stdout:``,stderr:`upskill: failed to unzip: ${t}\nContent-Type: ${c}\nBody: ${l.length} bytes\nHex: ${n}\n`,exitCode:1}}await t.mkdir(a,{recursive:!0});let d=0;for(let[e,n]of Object.entries(u)){let r=e.replace(/\\/g,`/`);if(!r||r.endsWith(`/`)||r===`_meta.json`)continue;let i=`${a}/${r}`,o=i.substring(0,i.lastIndexOf(`/`));o!==a&&await t.mkdir(o,{recursive:!0}),await t.writeFile(i,n),d++}let f=U_(u,i);return await Z_(),{stdout:`Installed skill "${e}" from ClawHub (${d} files)\n${f}`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`upskill: failed to install from ClawHub: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function U_(e,t){let n;for(let[t,r]of Object.entries(e))if((t.split(`/`).pop()||``).toLowerCase()===`skill.md`){n=new TextDecoder().decode(r);break}if(!n)return``;let r=n.match(/^---\s*\n([\s\S]*?)\n---/);if(!r)return``;let i=r[1],a=W_(i);if(a.length===0)return``;if(!t||t.length===0)return` Requires: ${a.join(`, `)}\n`;let o=new Set(t),s=a.filter(e=>!o.has(e));return s.length===0?` Requires: ${a.join(`, `)} (all available)\n`:` Requires: ${a.join(`, `)}\n Missing: ${s.join(`, `)} -- this skill may not work in the SLICC shell\n`}function W_(e){let t=e.match(/metadata:\s*\n\s*(\{[\s\S]*\})/);if(t)try{let e=JSON.parse(t[1]);for(let t of[`openclaw`,`clawdis`,`clawdbot`]){let n=e[t];if(n?.requires&&typeof n.requires==`object`){let e=n.requires;if(Array.isArray(e.bins))return e.bins.filter(e=>typeof e==`string`)}}}catch{}let n=e.match(/"bins"\s*:\s*\[([^\]]*)\]/);return n?n[1].split(`,`).map(e=>e.trim().replace(/^["']|["']$/g,``)).filter(Boolean):[]}async function G_(e,t){let n=await t(`${s_}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=5`,{headers:{Accept:`application/json`}});if(n.status!==200)return{error:`Tessl search failed (HTTP ${n.status})`};let r=Oa(n.body).data?.find(t=>t.type===`skill`&&t.attributes.name===e);if(!r)return{error:`skill "${e}" not found on Tessl registry`};let i=R_(r.attributes.sourceUrl);if(!i)return{error:`skill "${e}" has no GitHub source URL`};let a=r.attributes.path.replace(/\/SKILL\.md$/i,``);return{owner:i.owner,repo:i.repo,skillPath:a,skillName:e}}async function K_(e,t,n,r=`main`){let i=`https://codeload.github.com/${e}/${t}/zip/refs/heads/${r}`,a=await n(i,{headers:{"User-Agent":`slicc-upskill`}});if(a.status===404)return r===`main`?K_(e,t,n,`master`):{status:`not_found`};if(a.status!==200)return{status:`error`,message:`codeload returned HTTP ${a.status}`};let o=Ca(i);o||=ka(a.body);try{return{status:`ok`,files:j(o)}}catch(e){return{status:`error`,message:`failed to unzip: ${e instanceof Error?e.message:String(e)}`}}}function q_(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.indexOf(`/`);if(e<0)continue;let i=n.slice(e+1);i&&(t[i]=r)}return t}async function J_(e,t,n,r,i,a){if(i){let n=await K_(e,t,i,a);if(n.status===`ok`){let e=q_(n.files),t=[],i=r?r.replace(/^\/|\/$/g,``)+`/`:``;for(let n of Object.keys(e))if(n.startsWith(i)&&(n.split(`/`).pop()||``)===`SKILL.md`){let e=n.replace(/\/SKILL\.md$/,``),r=e.split(`/`).pop()||e;t.push({name:r,path:e})}return{skills:t}}if(n.status===`not_found`)return{skills:[],error:`${a?`branch "${a}" in ${e}/${t}`:`repository ${e}/${t}`} not found`}}let o=[];async function s(r){let i=`https://api.github.com/repos/${e}/${t}/contents/${r}`,c=a?`${i}?ref=${encodeURIComponent(a)}`:i,l=await n.request(c);if(l.status!==200)throw Error(E_(l,`${e}/${t}${r?`/${r}`:``}`,n.hasToken));let u=Oa(l.body);for(let e of u)if(e.type===`file`&&e.name===`SKILL.md`){let t=e.path.replace(`/SKILL.md`,``),n=t.split(`/`).pop()||t;o.push({name:n,path:t})}else e.type===`dir`&&await s(e.path)}try{return await s(r||``),{skills:o}}catch(e){return{skills:[],error:e instanceof Error?e.message:String(e)}}}async function Y_(e,t,n,r,i,a,o=!1,s,c){try{let l=`${c_}/${r}`;try{if(await i.stat(l),!o)return{stdout:``,stderr:`upskill: skill "${r}" already exists (use --force to overwrite)\n`,exitCode:1};await i.rm(l,{recursive:!0})}catch{}if(s){let a=await K_(e,t,s,c);if(a.status===`not_found`)return{stdout:``,stderr:`upskill: ${c?`branch "${c}" in ${e}/${t}`:`repository ${e}/${t}`} not found\n`,exitCode:1};if(a.status===`ok`){let o=q_(a.files),s=n.replace(/^\/|\/$/g,``)+`/`;await i.mkdir(l,{recursive:!0});let c=0;for(let[e,t]of Object.entries(o)){if(!e.startsWith(s))continue;let n=e.slice(s.length);if(!n||e.endsWith(`/`))continue;let r=`${l}/${n}`,a=r.substring(0,r.lastIndexOf(`/`));a!==l&&await i.mkdir(a,{recursive:!0}),await i.writeFile(r,t),c++}if(c>0)return await tv(),await $_(),{stdout:`Installed skill "${r}" from ${e}/${t}\n`,stderr:``,exitCode:0}}}let u=`https://api.github.com/repos/${e}/${t}/contents/${n}`,d=c?`${u}?ref=${encodeURIComponent(c)}`:u,f=await a.request(d);if(f.status!==200)return{stdout:``,stderr:`upskill: ${E_(f,`${e}/${t}/${n}`,a.hasToken)}\n`,exitCode:1};let p=Oa(f.body);await i.mkdir(l,{recursive:!0});async function m(n,r){for(let o of n)if(o.type===`file`&&o.download_url){let n=await a.request(o.download_url,`*/*`);if(n.status!==200)throw Error(E_(n,`${e}/${t}/${o.path}`,a.hasToken));let s=Ca(o.download_url);await i.writeFile(`${r}/${o.name}`,s??n.body)}else if(o.type===`dir`){let n=`https://api.github.com/repos/${e}/${t}/contents/${o.path}`,s=c?`${n}?ref=${encodeURIComponent(c)}`:n,l=await a.request(s);if(l.status!==200)throw Error(E_(l,`${e}/${t}/${o.path}`,a.hasToken));let u=Oa(l.body);await i.mkdir(`${r}/${o.name}`,{recursive:!0}),await m(u,`${r}/${o.name}`)}}try{await m(p,l)}catch(e){try{await i.rm(l,{recursive:!0})}catch{}throw e}return await Z_(),{stdout:`Installed skill "${r}" from ${e}/${t}\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`upskill: failed to install from GitHub: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function X_(e){let t=e.match(/^https?:\/\/clawhub\.ai\/[^\/]+\/([^\/]+)/);if(t)return t[1];if(e.startsWith(`clawhub:`)){let t=e.slice(8);return t.includes(`/`)?t.split(`/`)[1]:t}return null}async function Z_(){await tv(),await $_()}async function Q_(e,t,n,r,i=!1){let a=`${c_}/${t}`;try{if(await r.stat(a),!i)return{ok:!1,error:`skill "${t}" already exists (use --force to overwrite)`};await r.rm(a,{recursive:!0})}catch{}let o=e.replace(/^\/|\/$/g,``),s=o?o+`/`:``;await r.mkdir(a,{recursive:!0});let c=0;try{for(let[e,t]of Object.entries(n)){if(!e.startsWith(s))continue;let n=e.slice(s.length);if(!n||e.endsWith(`/`))continue;let i=`${a}/${n}`,o=i.replace(/\/+/g,`/`);if(o.includes(`/../`)||o.includes(`/..`)||!o.startsWith(a+`/`))continue;let l=i.substring(0,i.lastIndexOf(`/`));l!==a&&await r.mkdir(l,{recursive:!0}),await r.writeFile(i,t),c++}}catch(e){throw await r.rm(a,{recursive:!0}).catch(()=>{}),e}return c===0?(await r.rm(a,{recursive:!0}).catch(()=>{}),{ok:!1,error:`no files found for skill "${t}" in ZIP`}):{ok:!0}}async function $_(){try{let e=(typeof window<`u`?window:globalThis).__slicc_reloadSkills;if(typeof e==`function`){await e();return}typeof chrome<`u`&&chrome?.runtime?.sendMessage&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}})}catch{}}function ev(e){let t=e.match(/^([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_.-]+)(?:@([a-zA-Z0-9_./\-]+))?$/);return t?{owner:t[1],repo:t[2],branch:t[3]}:null}async function tv(){try{if(typeof window>`u`)return;let e=window.__slicc_sprinkleManager;e&&typeof e.openNewAutoOpenSprinkles==`function`&&await e.openNewAutoOpenSprinkles()}catch{}}async function nv(e,t,n){let r=null;try{let t=await e.readDir(`/home`);for(let n of t)try{let t=await e.readTextFile(`/home/${n.name}/.welcome.json`);r=JSON.parse(t);break}catch{}}catch{}if(!r)return{stdout:``,stderr:`upskill: no user profile found. Complete the welcome onboarding first, or create /home/<name>/.welcome.json manually.
1806
1806
  `,exitCode:1};let i,a;try{let[n,r]=await Promise.all([(async()=>{let e=await t(f_,{headers:{Accept:`application/json`}});if(e.status!==200)throw Error(`HTTP ${e.status}`);return m_(Oa(e.body).data)})(),v_(e)]);i=n,a=r}catch(e){return{stdout:``,stderr:`upskill: failed to fetch skill catalog from ${f_}: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let o=g_(i,r).filter(e=>!a.has(e.entry.name));if(o.length===0)return{stdout:`No new skill recommendations — all matching skills are already installed.
1807
1807
  `,stderr:``,exitCode:0};if(n){let n=new Map;for(let e of o){let t=e.entry.source.repo,r=n.get(t);r?r.push(e):n.set(t,[e])}let r=o.length,i=0,a=Date.now(),s=``,c=``,l=0,u=await Promise.allSettled(Array.from(n.entries()).map(async([n,o])=>{let[c,l]=n.split(`/`),u=await K_(c,l,t);if(u.status===`not_found`||u.status===`error`){let e=u.status===`not_found`?`upskill: repository ${n} not found\n`:`upskill: failed to fetch ${n}: ${u.message}\n`,t=[];for(let e of o){i++,((Date.now()-a)/1e3).toFixed(1);let o=i<r?` (~${Math.round((r-i)*(Date.now()-a)/i/1e3)}s remaining)`:``;s+=`[${i}/${r}] Failed "${e.entry.name}" from ${n}: repo fetch failed${o}\n`,t.push({ok:!1,name:e.entry.name,error:`repo fetch failed for ${n}`})}return{errors:e,results:t}}let d=q_(u.files),f=[],p=new Map;for(let e of Object.keys(d))if(e.endsWith(`/SKILL.md`)){let t=e.replace(/\/SKILL\.md$/,``),n=t.split(`/`).pop()||t;p.set(n,t)}for(let t of o){let o=t.entry.source,c,l;if(o.skill){let e=p.get(o.skill);if(e)c=e,l=o.skill;else if(o.path)c=o.path.replace(/^\/|\/$/g,``),l=o.skill;else{let e=`skill "${o.skill}" not found in ${n}`;f.push({ok:!1,name:t.entry.name,error:e}),i++;let c=i<r?` (~${Math.round((r-i)*(Date.now()-a)/i/1e3)}s remaining)`:``;s+=`[${i}/${r}] Failed "${t.entry.name}" from ${n}: ${e}${c}\n`;continue}}else if(o.path)c=o.path.replace(/^\/|\/$/g,``),l=t.entry.name;else{let e=p.get(t.entry.name);if(e)c=e,l=t.entry.name;else{let e=`skill "${t.entry.name}" not found in ${n} and no explicit path provided`;f.push({ok:!1,name:t.entry.name,error:e}),i++;let o=i<r?` (~${Math.round((r-i)*(Date.now()-a)/i/1e3)}s remaining)`:``;s+=`[${i}/${r}] Failed "${t.entry.name}" from ${n}: ${e}${o}\n`;continue}}let u=Date.now(),m=await Q_(c,l,d,e,!1);i++;let h=((Date.now()-u)/1e3).toFixed(1),g=(Date.now()-a)/i,_=Math.round((r-i)*g/1e3),v=i<r?` (~${_}s remaining)`:``;m.ok?(f.push({ok:!0,name:l}),s+=`[${i}/${r}] Installed "${l}" from ${n} (${h}s)${v}\n`):(f.push({ok:!1,name:l,error:m.error}),s+=`[${i}/${r}] Failed "${l}" from ${n}: ${m.error}${v}\n`)}return{errors:``,results:f}}));for(let e of u){if(e.status===`rejected`){c+=`upskill: unexpected error: ${e.reason}\n`;continue}e.value.errors&&(c+=e.value.errors);for(let t of e.value.results)t.ok?l++:t.error&&(c+=`upskill: ${t.error}\n`)}let d=((Date.now()-a)/1e3).toFixed(1);return l>0&&(s+=`\nInstalled ${l} recommended skill(s) in ${d}s\n`,await Z_()),{stdout:s,stderr:c,exitCode:+!!c}}let s=`Recommended skills for you:
1808
1808
 
@@ -13012,7 +13012,7 @@ Do NOT save a profile, update \`/shared/CLAUDE.md\`, or write a greeting.
13012
13012
  - **\`start-task\` lick** — treat as the user's first request, begin the task immediately.
13013
13013
  - **Sparse profiles** (user skipped most steps) — keep greeting brief, ask what they need.
13014
13014
  `,wy=`data:audio/mpeg;base64,SUQzBAAAAAAAIlRTU0UAAAAOAAADTGF2ZjYyLjMuMTAwAAAAAAAAAAAAAAD/+0DAAAAAAAAAAAAAAAAAAAAAAABYaW5nAAAADwAAAAcAAAYbAJWVlZWVlZWVlZWVlZWVqqqqqqqqqqqqqqqqqqq7u7u7u7u7u7u7u7u7u8zMzMzMzMzMzMzMzMzMzN3d3d3d3d3d3d3d3d3d7u7u7u7u7u7u7u7u7u7//////////////////wAAAABMYXZjNjIuMTEAAAAAAAAAAAAAAAAkA2kAAAAAAAAGG+gbtfQAAAAAAP/7wMQAAAv4N1B0ZIAqHxVpvznQgAr9rb7PJkyd34smDgMBk078/BAKAoGBQw+OHn/gAGf4eHv/wB3mf/gb/+OAf/AMf/h4A78AMP/oeAGfAAw/+h4AZ8BGH/48AM/iMf/+AAAAAAYeHh4eAAAAAAYeHh48AQMIAMGIBMXNwtEAoEAwAAQFAIBXCQKu8YAEJgcFBQtl1DXh6g4LDYWQ0TAcKGhAZbDTOWxGG4ECgfmRFLtKMFhAMNgLYEsYxXEXG8YqgB/V3RF/XZhqJUcp//99nKcqIv7vmWv///4zWppVVpf///////5TWpqarS0v8RBUFREe/1gqIgqCoiXfkTAVAAwAAMY6g6nK2AAgTCmlJdBcQAwEcSQmFALZslhoW7uNZ4gSBAGEM6A0KbEqs5LgGh4TzAuMFNh9L4FA2JwwsRBsKsxbGrvVd4Ah/AtwTpu046oAoLB7MBAHAAAuQSQgTSmJa2mO8ncaGTeyJsz3wn9TbdBmuCWkp8D8E//+gA4/C9YFwCq9RAA7S+AQNicISCx60KQy7HHeq7wBD0BcwnTfOPUM5NC/UFgAAAA6uQ6OhMlAQIF6e9CTI2Vyp7bkY0xyAhvA8Zp848zYQBSgCAONoPJlh0OM6j8g0QAE5IcEu49m0ZsbxZWX6cQwG6gzS0dl1wT//6UO9sCfUFoAAAAziH7QUEI6FiQEQGYIOeVMMQXnACAteiQWVmmckZbEXG1w7KCMN9bB7QFyC3ELRigOQJdCo56zhEjAgXAlbcHreLLGmdkZTD2m1w6ygjUO98CeUH4AAAAziH/QkCMDzpmjj44B3nBC54YUDZoxbLGmdEdERly9qyhjDfixayBkA2cGE4UKrxIIhgz8HwBS3YlbIGxt21jWiK0hatrEYEjVTEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVB3aABwAfwAAAMj7DgFUgDBxFLY4XWT6pcoZrVtbqPGBB//sgxO8Axmw5Qd29gCiLCCg4DdB0oi1tkrKwMMFBV000qkxBTUUzLjEwMKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqv/7EMT6AEVwQTPgcEPgk4goOA3QdKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq//sQxPsARMRBQ+Dqg2C2iCa8Pgh8qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqr/+xDE+oDFuEFD4Whj4KMIKDgtDHyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqv/7EMT4gMVgQUXhYGPgmgan+AHgBaqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq//sQxO0DxaRHKeDgY+gAAD/AAAAEqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqo=`,Ty=n(`skills`),Ey=Object.assign({"/packages/vfs-root/AGENTS.md":ty,"/packages/vfs-root/CLAUDE.md":ty,"/packages/vfs-root/shared/CLAUDE.md":ny,"/packages/vfs-root/shared/sprinkles/brand-compliance/brand-compliance.shtml":ry,"/packages/vfs-root/shared/sprinkles/content-tree/content-tree.shtml":iy,"/packages/vfs-root/shared/sprinkles/funnels/funnels.shtml":ay,"/packages/vfs-root/shared/sprinkles/page-editor/page-editor.shtml":oy,"/packages/vfs-root/shared/sprinkles/performance/performance.shtml":sy,"/packages/vfs-root/shared/sprinkles/readability/readability.shtml":cy,"/packages/vfs-root/shared/sprinkles/review-workflow/review-workflow.shtml":ly,"/packages/vfs-root/shared/sprinkles/schema-editor/schema-editor.shtml":uy,"/packages/vfs-root/shared/sprinkles/seo-dashboard/seo-dashboard.shtml":dy,"/packages/vfs-root/shared/sprinkles/tone-voice/tone-voice.shtml":fy,"/packages/vfs-root/shared/sprinkles/welcome/welcome.shtml":py,"/packages/vfs-root/workspace/skills/automation/SKILL.md":my,"/packages/vfs-root/workspace/skills/inline-widgets/SKILL.md":hy,"/packages/vfs-root/workspace/skills/playwright-cli/SKILL.md":gy,"/packages/vfs-root/workspace/skills/scoop-management/SKILL.md":_y,"/packages/vfs-root/workspace/skills/skill-authoring/SKILL.md":vy,"/packages/vfs-root/workspace/skills/sprinkle-guide/SKILL.md":yy,"/packages/vfs-root/workspace/skills/sprinkles/SKILL.md":by,"/packages/vfs-root/workspace/skills/sprinkles/icon-example.md":xy,"/packages/vfs-root/workspace/skills/sprinkles/style-guide.md":Sy,"/packages/vfs-root/workspace/skills/welcome/SKILL.md":Cy}),Dy=Object.assign({"/packages/vfs-root/shared/sounds/chime.mp3":wy});function Oy(e){let t=e.split(`,`)[1],n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}function ky(){let e={};for(let[t,n]of Object.entries(Ey))e[t]=n;for(let[t,n]of Object.entries(Dy))e[t]=Oy(n);return e}function Ay(e){let t=new Map;for(let n of e){if(t.has(n.metadata.name)){Ty.debug(`Skipped shadowed runtime skill`,{name:n.metadata.name,path:n.path,winnerPath:t.get(n.metadata.name)?.path});continue}t.set(n.metadata.name,n)}return Array.from(t.values())}function jy(e){let t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);if(!t)return{metadata:{},body:e};let[,n,r]=t,i={};for(let e of n.split(`
13015
- `)){let t=e.match(/^(\w[\w-]*):\s*(.*)$/);if(!t)continue;let[,n,r]=t,a=r.trim();switch(n){case`name`:i.name=a;break;case`description`:i.description=a;break;case`allowed-tools`:i.allowedTools=a.split(`,`).map(e=>e.trim());break}}return{metadata:i,body:r}}async function My(e,t){let n=await Ny(e,t),r=await Py(e,t),i=n.filter(e=>e.source===`native`),a=n.filter(e=>e.source!==`native`),o=Ay([...i,...r,...a]);return Ty.info(`Skills loaded`,{count:o.length,dir:t}),o}async function Ny(e,t){let n=await de(e,t),r=[];for(let t of n)if(t.skillFilePath)try{let{metadata:n,body:i}=jy(await e.readTextFile(t.skillFilePath)),a=n.name||t.name;r.push({metadata:{name:a,description:n.description||t.manifest.description||``,allowedTools:n.allowedTools},content:i,path:t.skillFilePath,source:t.source}),Ty.debug(`Loaded discovered skill`,{name:a,path:t.skillFilePath,source:t.source})}catch{Ty.debug(`Failed to load discovered skill`,{name:t.name,path:t.skillFilePath})}return r}async function Py(e,t){let n=[];try{let r=await e.readDir(t);for(let i of r)if(i.type===`file`&&i.name.endsWith(`.md`)){let r=`${t}/${i.name}`;try{let t=await e.readFile(r,{encoding:`utf-8`}),{metadata:a,body:o}=jy(typeof t==`string`?t:new TextDecoder().decode(t)),s=a.name||i.name.replace(`.md`,``);n.push({metadata:{name:s,description:a.description||``,allowedTools:a.allowedTools},content:o,path:r}),Ty.debug(`Loaded standalone skill`,{name:s,path:r})}catch{}}}catch{Ty.debug(`Standalone skills directory not found`,{dir:t})}return n}function Fy(e){return e.length===0?``:`
13015
+ `)){let t=e.match(/^(\w[\w-]*):\s*(.*)$/);if(!t)continue;let[,n,r]=t,a=r.trim();switch(n){case`name`:i.name=a;break;case`description`:i.description=a;break;case`allowed-tools`:i.allowedTools=a.split(`,`).map(e=>e.trim());break}}return{metadata:i,body:r}}async function My(e,t){let n=await Ny(e,t),r=await Py(e,t),i=n.filter(e=>e.source===`native`),a=n.filter(e=>e.source!==`native`),o=Ay([...i,...r,...a]);return Ty.info(`Skills loaded`,{count:o.length,dir:t}),o}async function Ny(e,t){let n=await fe(e,t),r=[];for(let t of n)if(t.skillFilePath)try{let{metadata:n,body:i}=jy(await e.readTextFile(t.skillFilePath)),a=n.name||t.name;r.push({metadata:{name:a,description:n.description||t.manifest.description||``,allowedTools:n.allowedTools},content:i,path:t.skillFilePath,source:t.source}),Ty.debug(`Loaded discovered skill`,{name:a,path:t.skillFilePath,source:t.source})}catch{Ty.debug(`Failed to load discovered skill`,{name:t.name,path:t.skillFilePath})}return r}async function Py(e,t){let n=[];try{let r=await e.readDir(t);for(let i of r)if(i.type===`file`&&i.name.endsWith(`.md`)){let r=`${t}/${i.name}`;try{let t=await e.readFile(r,{encoding:`utf-8`}),{metadata:a,body:o}=jy(typeof t==`string`?t:new TextDecoder().decode(t)),s=a.name||i.name.replace(`.md`,``);n.push({metadata:{name:s,description:a.description||``,allowedTools:a.allowedTools},content:o,path:r}),Ty.debug(`Loaded standalone skill`,{name:s,path:r})}catch{}}}catch{Ty.debug(`Standalone skills directory not found`,{dir:t})}return n}function Fy(e){return e.length===0?``:`
13016
13016
  ---
13017
13017
  AVAILABLE SKILLS
13018
13018
 
@@ -13022,7 +13022,7 @@ The following skills are available. To use a skill, first read its full instruct
13022
13022
  ${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(`
13023
13023
  `)}
13024
13024
  ---`}async function Iy(e,t=`/workspace/skills`){let n=ky();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),Ty.info(`Created default file`,{path:s})}}}async function Ly(e){let t=ky();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),Ty.info(`Created default shared file`,{path:t})}}}var Ry=n(`scoop-management-tools`);function zy(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),Ry.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),Ry.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(`
13025
- `)}`}}}),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 Ry.info(`Scoop created`,{name:t,folder:a}),i&&r?(r(e.jid,i).catch(e=>{let n=e instanceof Error?e.message:String(e);Ry.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),Ry.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),Ry.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 By=n(`secret-env`);async function Vy(){if(typeof chrome<`u`&&chrome?.runtime?.id)return{};try{let e=await fetch(`/api/secrets/masked`);if(!e.ok)return By.warn(`Failed to fetch masked secrets`,{status:e.status}),{};let t=await e.json();if(!Array.isArray(t)||t.length===0)return{};let n={};for(let e of t)e.name&&e.maskedValue&&(n[e.name]=e.maskedValue);return Object.keys(n).length>0&&By.info(`Loaded masked secrets into shell env`,{count:Object.keys(n).length}),n}catch(e){return By.debug(`Could not fetch masked secrets (server may be unavailable)`,{error:e instanceof Error?e.message:String(e)}),{}}}var Hy=n(`scoop-context`);function Uy(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 Wy=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!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`);Hy.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 Iy(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await Vy();this.shell=new Wv({fs:this.fs,cwd:e,env:Object.keys(r).length>0?r:void 0,browserAPI:t,jshDiscoveryFs:this.skillsFs?n:void 0}),Hy.info(`WasmShell initialized`,{folder:this.scoop.folder});let i=await My(n,this.skillsDir),a=zy({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}),o=y([...Kv(this.fs),ey(this.shell),...a]),s=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`,c=``;try{let e=await this.fs.readFile(s,{encoding:`utf-8`});c=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let l=await this.callbacks.getGlobalMemory();if(l)try{this.scoop.isCone&&await(`getUnderlyingFS`in this.fs?this.fs.getUnderlyingFS():this.fs).writeFile(`/shared/CLAUDE.md`,l)}catch{}if(!T()){let e=re();throw Error(`No API key configured for provider "${e}"`)}let u=this.scoop.config?.modelId?S(this.scoop.config.modelId):M(),d=this.scoop.isCone?`Cone`:`Scoop "${this.scoop.name}"`;console.log(`[model] ${d} using model: ${u.id} (provider: ${u.provider})`);let f=this.buildSystemPrompt(l,c,i),p=[];if(this.sessionStore)try{let e=await this.sessionStore.load(this.sessionId);e&&(p=e.messages,this.sessionCreatedAt=e.createdAt,Hy.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:p.length}))}catch(e){Hy.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 m=O({model:u,getApiKey:()=>T()??void 0});if(this.disposed)return;this.agent=new b({initialState:{model:u,tools:o,systemPrompt:f,messages:p},getApiKey:()=>T()??void 0,transformContext:m}),this.unsubscribe=this.agent.subscribe(e=>this.handleAgentEvent(e)),this.setStatus(`ready`),Hy.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:o.length})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);Hy.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){Hy.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){if(!this.disposed){let t=e instanceof Error?e.message:String(e);Hy.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=M();this.agent.state.model=e,Hy.info(`Model updated on running agent`,{folder:this.scoop.folder,model:e.id})}async reloadSkills(){if(!this.agent)return;let e=await My(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,Hy.info(`Skills reloaded`,{folder:this.scoop.folder,skillCount:e.length})}dispose(){this.disposed=!0,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.shell?.dispose(),this.agent=null,this.shell=null,this.fs=null}setStatus(e){this.disposed||(this.status=e,this.callbacks.onStatusChange(e))}handleAgentEvent(e){if(!this.disposed)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(`
13025
+ `)}`}}}),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 Ry.info(`Scoop created`,{name:t,folder:a}),i&&r?(r(e.jid,i).catch(e=>{let n=e instanceof Error?e.message:String(e);Ry.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),Ry.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),Ry.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 By=n(`secret-env`);async function Vy(){if(typeof chrome<`u`&&chrome?.runtime?.id)return{};try{let e=await fetch(`/api/secrets/masked`);if(!e.ok)return By.warn(`Failed to fetch masked secrets`,{status:e.status}),{};let t=await e.json();if(!Array.isArray(t)||t.length===0)return{};let n={};for(let e of t)e.name&&e.maskedValue&&(n[e.name]=e.maskedValue);return Object.keys(n).length>0&&By.info(`Loaded masked secrets into shell env`,{count:Object.keys(n).length}),n}catch(e){return By.debug(`Could not fetch masked secrets (server may be unavailable)`,{error:e instanceof Error?e.message:String(e)}),{}}}var Hy=n(`scoop-context`);function Uy(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 Wy=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!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`);Hy.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 Iy(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await Vy();this.shell=new Wv({fs:this.fs,cwd:e,env:Object.keys(r).length>0?r:void 0,browserAPI:t,jshDiscoveryFs:this.skillsFs?n:void 0}),Hy.info(`WasmShell initialized`,{folder:this.scoop.folder});let i=await My(n,this.skillsDir),a=zy({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}),o=ee([...Kv(this.fs),ey(this.shell),...a]),s=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`,c=``;try{let e=await this.fs.readFile(s,{encoding:`utf-8`});c=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let l=await this.callbacks.getGlobalMemory();if(l)try{this.scoop.isCone&&await(`getUnderlyingFS`in this.fs?this.fs.getUnderlyingFS():this.fs).writeFile(`/shared/CLAUDE.md`,l)}catch{}if(!T()){let e=ne();throw Error(`No API key configured for provider "${e}"`)}let u=this.scoop.config?.modelId?ie(this.scoop.config.modelId):w(),d=this.scoop.isCone?`Cone`:`Scoop "${this.scoop.name}"`;console.log(`[model] ${d} using model: ${u.id} (provider: ${u.provider})`);let f=this.buildSystemPrompt(l,c,i),p=[];if(this.sessionStore)try{let e=await this.sessionStore.load(this.sessionId);e&&(p=e.messages,this.sessionCreatedAt=e.createdAt,Hy.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:p.length}))}catch(e){Hy.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 m=S({model:u,getApiKey:()=>T()??void 0});if(this.disposed)return;this.agent=new D({initialState:{model:u,tools:o,systemPrompt:f,messages:p},getApiKey:()=>T()??void 0,transformContext:m}),this.unsubscribe=this.agent.subscribe(e=>this.handleAgentEvent(e)),this.setStatus(`ready`),Hy.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:o.length})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);Hy.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){Hy.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){if(!this.disposed){let t=e instanceof Error?e.message:String(e);Hy.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=w();this.agent.state.model=e,Hy.info(`Model updated on running agent`,{folder:this.scoop.folder,model:e.id})}async reloadSkills(){if(!this.agent)return;let e=await My(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,Hy.info(`Skills reloaded`,{folder:this.scoop.folder,skillCount:e.length})}dispose(){this.disposed=!0,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.shell?.dispose(),this.agent=null,this.shell=null,this.fs=null}setStatus(e){this.disposed||(this.status=e,this.callbacks.onStatusChange(e))}handleAgentEvent(e){if(!this.disposed)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(`
13026
13026
  `),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&&Uy(n)){this.recoverFromImageError(t);break}if(!this.isRecovering&&x(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=>{Hy.error(`Failed to save agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})});break}}}recoverFromOverflow(e){if(this.agent){Hy.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++,Hy.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=>{Hy.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){Hy.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){Hy.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=>{Hy.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){Hy.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
13027
13027
 
13028
13028
  ${this.scoop.isCone?`Role: Cone (main orchestrator)`:`Scoop: ${this.scoop.name}`}
@@ -13102,12 +13102,12 @@ ${e}
13102
13102
  ---
13103
13103
  ${this.scoop.isCone?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
13104
13104
  ${t}
13105
- ---`);let a=Fy(n);return a&&(i+=a),i}},Gy=n(`scheduler`),Ky=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(),Gy.info(`Scheduler started`))}stop(){this.pollInterval&&=(clearInterval(this.pollInterval),null),this.running=!1,Gy.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 He(i),Gy.info(`Task created`,{id:i.id,groupFolder:e,scheduleType:n}),i}async updateTask(e,t){let n=await Me(e);if(!n)return null;let r={...n,...t};return(t.scheduleType||t.scheduleValue)&&(r.nextRun=this.calculateNextRun(r.scheduleType,r.scheduleValue)),await He(r),Gy.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 Me(e)?(await this.updateTask(e,{status:`active`}),!0):!1}async deleteTask(e){return await Me(e)?(await Ce(e),Gy.info(`Task deleted`,{id:e}),!0):!1}async getTasksByScoop(e){return(await je()).filter(t=>t.groupFolder===e)}async getAllTasks(){return je()}async checkTasks(){let e=await je(),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){Gy.warn(`Task scoop not found`,{taskId:e.id,groupFolder:e.groupFolder});return}Gy.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 He({...e,lastRun:n,nextRun:r,status:i}),await this.callbacks.onTaskRun(e,t),Gy.info(`Task completed`,{id:e.id})}catch(t){Gy.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}},qy=n(`lick-manager`),Jy=class{webhooks=new Map;crontasks=new Map;cronInterval=null;eventHandler=null;async init(){await ke();let e=await ze();for(let t of e)this.webhooks.set(t.id,t);qy.info(`Loaded webhooks`,{count:this.webhooks.size});let t=await Le();for(let e of t)this.crontasks.set(e.id,e);qy.info(`Loaded crontasks`,{count:this.crontasks.size}),this.cronInterval=setInterval(()=>this.runCronScheduler(),6e4),qy.info(`Cron scheduler started`)}dispose(){this.cronInterval&&=(clearInterval(this.cronInterval),null)}setEventHandler(e){this.eventHandler=e}emitEvent(e){qy.info(`External lick event`,{type:e.type,target:e.targetScoop}),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 we(i),qy.info(`Webhook created`,{id:r,name:e,scoop:t}),i}async deleteWebhook(e){return this.webhooks.has(e)?(this.webhooks.delete(e),await Pe(e),qy.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){qy.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){qy.debug(`Webhook event dropped by filter`,{webhookId:e,name:r.name});return}typeof t==`object`&&t&&(i=t)}catch(t){qy.error(`Webhook filter error`,{webhookId:e,error:t instanceof Error?t.message:String(t)})}qy.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 Oe(o),qy.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 Ne(e),qy.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){qy.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 Oe(t);continue}typeof r==`object`&&r&&(n=r)}catch(e){qy.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};qy.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 Oe(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 Yy(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(`
13106
- `);return Error(`Cannot remove scoop '${e}': it has ${r.join(` and `)}. Unregister them first:\n${i}`)}var Xy=null;function Zy(){return Xy||=new Jy,Xy}var Q=n(`orchestrator`),Qy=120*1e3,$y=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;fsWatcher=null;idleTimers=new Map;droppedScoopCosts=[];constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n}async init(){await ke(),this.sharedFs=await L.create({dbName:`slicc-fs`}),this.sessionStore=new D,this.fsWatcher=new se,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure();let e=await Te();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 Fe(`lastAgentTs_${t.jid}`);e&&this.lastAgentTimestamp.set(t.jid,e)}await this.ensureGlobalMemory(),this.scheduler=new Ky({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);Ke(()=>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 Ly(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,globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}async registerScoop(e){await Be(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=Yy(t.folder,e,n);if(r)throw r}this.snapshotScoopCost(e),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 Ae(e),this.scoops.delete(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.scoopResponseBuffer.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 L.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.ensureGlobalMemory(),await Iy(this.sharedFs).catch(e=>{Q.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.droppedScoopCosts=[],Q.info(`Filesystem reset and defaults re-seeded`)}async clearAllMessages(){await Re(),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,[]);this.droppedScoopCosts=[],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);Mv(t?.isCone?`cone`:t?.name??`unknown`,localStorage.getItem(`selected-model`)??`unknown`),await Se(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 Se(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`||e.channel===`fswatch`||e.channel===`sprinkle`;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 le(this.sharedFs,[`/scoops/${t.folder}/`,`/shared/`],[`/workspace/`]),i=new Wy(t,{onResponse:(n,r)=>{if(this.scoops.has(e)&&(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:()=>{if(!this.scoops.has(e))return;let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),this.callbacks.onResponseDone(e)},onError:t=>{if(!this.scoops.has(e))return;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=>{if(!this.scoops.has(e))return;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)+`
13107
- ... (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 Ie(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 Ie(t)}async getMessagesForScoop(e){return Ee(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 De(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(`
13108
- `);this.messageQueues.set(e,[]);let c=o[o.length-1];this.lastAgentTimestamp.set(e,c.timestamp),await Ve(`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()}buildScoopCost(e,t){let n=t.getAgentMessages().filter(e=>e.role===`assistant`);if(n.length===0)return null;let r={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},i=new Map;for(let e of n)r.input+=e.usage.input,r.output+=e.usage.output,r.cacheRead+=e.usage.cacheRead,r.cacheWrite+=e.usage.cacheWrite,r.totalTokens+=e.usage.totalTokens,r.cost.input+=e.usage.cost.input,r.cost.output+=e.usage.cost.output,r.cost.cacheRead+=e.usage.cost.cacheRead,r.cost.cacheWrite+=e.usage.cost.cacheWrite,r.cost.total+=e.usage.cost.total,i.set(e.model,(i.get(e.model)??0)+1);let a=``,o=0;for(let[e,t]of i)t>o&&(a=e,o=t);return{name:e.assistantLabel,type:e.isCone?`cone`:`scoop`,model:a,usage:r,turns:n.length}}snapshotScoopCost(e){let t=this.scoops.get(e),n=this.contexts.get(e);if(!t||!n)return;let r=this.buildScoopCost(t,n);r&&this.droppedScoopCosts.push(r)}getSessionCosts(){let e=[];for(let t of this.scoops.values()){let n=this.contexts.get(t.jid);if(!n)continue;let r=this.buildScoopCost(t,n);r&&e.push(r)}return e.push(...this.droppedScoopCosts),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})})},Qy);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 eb=n(`tray-follower`);function tb(e){let t=new URL(e);return t.searchParams.set(`json`,`true`),t.toString()}async function nb(e){let t=tb(e.joinUrl),n=await lb(await(e.fetchImpl??fetch)(t,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:e.controllerId,runtime:e.runtime})}));return eb.info(`Follower tray attach response`,{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),rb(n)}function rb(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 ib(e){return cb(await ub(e,{action:`poll`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function ab(e){return cb(await ub(e,{action:`answer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function ob(e){return cb(await ub(e,{action:`ice-candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function sb(e){return cb(await ub(e,{action:`retry`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function cb(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function lb(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!db(n)){let n=t?t.slice(0,200):`(empty)`;throw eb.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 ub(e,t){let n=tb(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(!fb(i))throw Error(`Tray follower bootstrap returned an invalid response (${r.status})`);return i}function db(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`&&pb(r.bootstrap):r.action===`fail`?(r.code===`INVALID_JOIN_CAPABILITY`||r.code===`TRAY_EXPIRED`)&&typeof r.error==`string`:!1}function fb(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`&&pb(t.bootstrap)&&Array.isArray(t.events)}function pb(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 mb=n(`tray-webrtc`),hb=`tray-control`,gb=250,_b=class{peerConnectionFactory;dataChannelLabel;peers=new Map;iceServers;constructor(e){this.options=e,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>bb(this.iceServers)),this.dataChannelLabel=e.dataChannelLabel??hb}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=Sb(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`)&&(mb.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`?(mb.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`?(mb.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:xb(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){mb.warn(`Failed to report tray bootstrap failure`,{error:e instanceof Error?e.message:String(e)})}}}},vb=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??(()=>bb(this.iceServers)),this.controllerIdFactory=e.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),this.pollIntervalMs=e.pollIntervalMs??gb}async start(){this.stopped=!1;let e=this.controllerIdFactory(),t=Date.now();p({state:`connecting`,joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:t,lastError:null}),mb.info(`Follower tray join starting`,{joinUrl:this.options.joinUrl});let n=0;for(;;){Cb(this.stopped),n++;let t;try{t=await nb({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 p({...h(),attachAttempts:n,lastError:t}),e}if(p({...h(),attachAttempts:n,lastAttachCode:t.code}),t.action===`wait`){let e=t.retryAfterMs??1e3;mb.info(`Follower tray attach waiting`,{attempt:n,code:t.code,retryAfterMs:e}),n%10==0&&mb.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 p({state:`error`,joinUrl:this.options.joinUrl,trayId:null,error:e,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:e}),mb.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 p({state:`connected`,joinUrl:this.options.joinUrl,trayId:r.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:null}),mb.info(`Follower tray connected`,{trayId:r.trayId,controllerId:e}),r}catch(e){let r=e instanceof Error?e.message:String(e);throw p({state:`error`,joinUrl:this.options.joinUrl,trayId:t.trayId,error:r,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:r}),mb.warn(`Follower tray bootstrap failed`,{error:r}),e}}}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,p({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(Cb(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 ib({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 ab({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,answer:xb(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 sb({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`)&&(mb.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?(mb.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?(mb.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=Sb(n);r&&ob({joinUrl:this.options.joinUrl,controllerId:e,bootstrapId:t,candidate:r,fetchImpl:this.fetchImpl}).catch(e=>{mb.warn(`Failed to send follower ICE candidate`,{error:e instanceof Error?e.message:String(e)})})}),r}};function yb(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 vb({...e,sleep:o,onDisconnected:e=>{s||(mb.warn(`Follower disconnected, starting reconnect loop`,{reason:e}),f(e))}});return l=t,{manager:t,connectionPromise:t.start()}},f=async u=>{if(s||c)return;c=!0,l?.stop(),l=null;let f=0,m=n,g=u??`Unknown disconnect`;for(;!s&&f<a&&(f++,t.onReconnecting?.(f),p({...h(),state:`reconnecting`,error:null,reconnectAttempts:f}),mb.info(`Reconnect attempt`,{attempt:f,delay:m}),await o(m),!s);){let n=null;try{let r=d();n=r.manager;let i=await r.connectionPromise;if(s){n.stop();break}c=!1,p({...h(),state:`connected`,joinUrl:e.joinUrl,trayId:i.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),mb.info(`Reconnect successful`,{attempt:f,trayId:i.trayId}),t.onConnected(i);return}catch(e){g=e instanceof Error?e.message:String(e),mb.warn(`Reconnect attempt failed`,{attempt:f,error:g}),n?.stop(),l=null}m=Math.min(m*r,i)}s||(c=!1,p({...h(),state:`error`,error:`Reconnect failed after ${f} attempts: ${g}`,reconnectAttempts:f}),mb.warn(`Reconnect gave up`,{attempts:f,lastError:g}),t.onGaveUp?.(g))},{connectionPromise:m}=d();return m.then(e=>{s||t.onConnected(e)}).catch(e=>{s||mb.warn(`Initial follower connection failed`,{error:e instanceof Error?e.message:String(e)})}),u}function bb(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 xb(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 Sb(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 Cb(e){if(e)throw Error(`Tray follower stopped before WebRTC bootstrap completed`)}var wb=64*1024;async function Tb(e,t){try{switch(t.op){case`readFile`:return await Eb(e,t.path,t.encoding);case`writeFile`:return[await Db(e,t.path,t.content,t.encoding)];case`stat`:return[await Ob(e,t.path)];case`readDir`:return[await kb(e,t.path)];case`mkdir`:return[await Ab(e,t.path,t.recursive)];case`rm`:return[await jb(e,t.path,t.recursive)];case`exists`:return[await Mb(e,t.path)];case`walk`:return[await Nb(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(e){return[Fb(e)]}}async function Eb(e,t,n){return(n??`utf-8`)===`utf-8`?Pb(await e.readFile(t,{encoding:`utf-8`}),`utf-8`):Pb(Ib(await e.readFile(t,{encoding:`binary`})),`base64`)}async function Db(e,t,n,r){if(r===`base64`){let r=Lb(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:`void`}}}async function Ob(e,t){return{ok:!0,data:{type:`stat`,stat:await e.stat(t)}}}async function kb(e,t){return{ok:!0,data:{type:`dirEntries`,entries:await e.readDir(t)}}}async function Ab(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function jb(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function Mb(e,t){return{ok:!0,data:{type:`exists`,exists:await e.exists(t)}}}async function Nb(e,t){let n=[];for await(let r of e.walk(t))n.push(r);return{ok:!0,data:{type:`paths`,paths:n}}}function Pb(e,t){if(e.length<=wb)return[{ok:!0,data:{type:`file`,content:e,encoding:t}}];let n=Math.ceil(e.length/wb),r=[];for(let i=0;i<n;i++){let a=i*wb,o=e.slice(a,a+wb);r.push({ok:!0,data:{type:`file`,content:o,encoding:t},chunkIndex:i,totalChunks:n})}return r}function Fb(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 Ib(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Lb(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 Rb=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()]}},zb=n(`data-channel-keepalive`),Bb=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++,zb.debug(`Missed pong`,{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){zb.warn(`Channel declared dead`,{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}},Vb=n(`tray-leader-sync`);function Hb(e){return e?e.includes(`standalone`)?`standalone`:e.includes(`extension`)?`extension`:e.includes(`electron`)?`electron`:`unknown`:`unknown`}var Ub=class{followers=new Map;registry=new Rb;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=he(t),i=r.onMessage(t=>{this.handleFollowerMessage(e,t)}),a=new Bb({sendPing:()=>r.send({type:`ping`}),onDead:()=>{Vb.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:Hb(n?.runtime)}),Vb.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(),Vb.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();pe(t.sync,n,r),Vb.debug(`Snapshot sent to follower`,{bootstrapId:e,messageCount:n.length})}handleFollowerMessage(e,t){switch(t.type){case`user_message`:Vb.info(`Follower user message received`,{bootstrapId:e,messageId:t.messageId}),this.options.onFollowerMessage(t.text,t.messageId);break;case`abort`:Vb.info(`Follower abort received`,{bootstrapId:e}),this.options.onFollowerAbort();break;case`request_snapshot`:Vb.info(`Follower snapshot request received`,{bootstrapId:e}),this.sendSnapshotToFollower(e);break;case`targets.advertise`:Vb.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),Vb.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 _e({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),Vb.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);be(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=fe(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&&be(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 Tb(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?Tb(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})})}},Wb=n(`tray-follower-sync`),Gb=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=ye(e),this.unsubscribe=this.sync.onMessage(e=>{this.handleLeaderMessage(e)}),this.keepalive=new Bb({sendPing:()=>this.sync.send({type:`ping`}),onDead:()=>{Wb.warn(`Leader keepalive dead, cleaning up`),this.handleDisconnect(`Keepalive timeout — leader not responding`),this.options.onDead?.()}}),this.keepalive.start(),e.addEventListener(`close`,()=>{Wb.warn(`Data channel closed`),this.handleDisconnect(`Data channel closed`)}),e.addEventListener(`error`,()=>{Wb.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}),Wb.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`}),Wb.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(),Wb.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,p({...h(),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`:Wb.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=ve(this.snapshotChunkBuffer,e);this.snapshotChunkBuffer=t.buffer,t.result&&(Wb.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),Wb.debug(`Skipping own message echo`,{messageId:e.messageId});break}Wb.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`:Wb.warn(`Error from leader`,{error:e.error}),this.emitEvent({type:`error`,error:e.error});break;case`targets.registry`:Wb.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(),u(Date.now());break}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch(t){Wb.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}}createRemoteTransport(e,t){let n=new _e({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),Wb.debug(`Tracking remote CDP session`,{remoteSessionId:e})}n===`Target.detachFromTarget`&&i&&this.remoteCDPSessions.has(i)&&(this.remoteCDPSessions.delete(i),Wb.debug(`Removed remote CDP session on detach`,{sessionId:i})),be(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=fe(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 Tb(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 Kb(e,t){if(t)return`extension`;try{return Yb(new URL(e))?`electron-overlay`:`standalone`}catch{return`standalone`}}function qb(e,t){return e===`electron-overlay`||e===`standalone`&&t}function Jb(e){try{let t=new URL(e).searchParams.get(`tab`);return t&&Ji(t)?t:Ki}catch{return Ki}}function Yb(e){return e.pathname===`/electron`||e.pathname===`/electron/`||e.searchParams.get(`runtime`)===`electron-overlay`}function Xb(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}/licks-ws`}function Zb(e,t){return`${new URL(e).origin}/webhooks/${t}`}function Qb(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function $b(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`slicc-electron-overlay:set-tab`}var ex=[`/shared/sprinkles`];async function tx(e){let t=new Map;for(let n of ex)await e.exists(n)&&await nx(e,n,t);return await nx(e,`/`,t),t}async function nx(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.shtml`))continue;let t=rx(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:ix(i,t),autoOpen:ax(i)})}}}function rx(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.shtml`)?t.slice(0,-6):t}function ix(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 ax(e){return/data-sprinkle-autoopen\b/.test(e)}var ox=n(`sprinkle-manager`),sx=`slicc-open-sprinkles`,cx=class{fs;bridge;callbacks;availableSprinkles=new Map;watcherUnsub;openSprinkles=new Map;constructor(e,t,n,r){this.fs=e,this.bridge=new Dh(e,t,e=>this.close(e),r),this.callbacks=n}async restoreOpenSprinkles(){try{let e=localStorage.getItem(sx);if(!e){for(let e of this.availableSprinkles.values())if(e.autoOpen)try{await this.open(e.name)}catch{ox.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{ox.warn(`Failed to restore sprinkle`,{name:e})}}catch{}}persistOpenSprinkles(){try{localStorage.setItem(sx,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),ox.info(`Auto-opened new sprinkle after install`,{name:e.name})}catch{ox.warn(`Failed to auto-open new sprinkle`,{name:e.name})}}async refresh(){this.availableSprinkles=await tx(this.fs),ox.info(`Discovered sprinkles`,{count:this.availableSprinkles.size})}async open(e,t){if(this.openSprinkles.has(e)){ox.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 oi(i,this.bridge.createAPI(e));await a.render(r,e),this.openSprinkles.get(e).renderer=a,this.persistOpenSprinkles(),Pv(e),ox.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(),ox.info(`Sprinkle closed`,{name:e}))}available(){return Array.from(this.availableSprinkles.values())}opened(){return Array.from(this.openSprinkles.keys())}setupWatcher(e){this.watcherUnsub=e.watch(`/workspace`,e=>e.endsWith(`.shtml`),()=>void this.refresh())}dispose(){this.watcherUnsub?.()}sendToSprinkle(e,t){let n=this.openSprinkles.get(e);if(!n){ox.warn(`Cannot send to closed sprinkle`,{name:e});return}this.bridge.pushUpdate(e,t),n.renderer.pushUpdate(t)}};function lx(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function ux(e){let t=[],{payload:n}=e;if(n.title&&t.push(`# ${n.title}`),t.push(`A new handoff was accepted from ${lx(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(`
13105
+ ---`);let a=Fy(n);return a&&(i+=a),i}},Gy=n(`scheduler`),Ky=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(),Gy.info(`Scheduler started`))}stop(){this.pollInterval&&=(clearInterval(this.pollInterval),null),this.running=!1,Gy.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 He(i),Gy.info(`Task created`,{id:i.id,groupFolder:e,scheduleType:n}),i}async updateTask(e,t){let n=await Ne(e);if(!n)return null;let r={...n,...t};return(t.scheduleType||t.scheduleValue)&&(r.nextRun=this.calculateNextRun(r.scheduleType,r.scheduleValue)),await He(r),Gy.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 Ne(e)?(await this.updateTask(e,{status:`active`}),!0):!1}async deleteTask(e){return await Ne(e)?(await we(e),Gy.info(`Task deleted`,{id:e}),!0):!1}async getTasksByScoop(e){return(await Me()).filter(t=>t.groupFolder===e)}async getAllTasks(){return Me()}async checkTasks(){let e=await Me(),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){Gy.warn(`Task scoop not found`,{taskId:e.id,groupFolder:e.groupFolder});return}Gy.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 He({...e,lastRun:n,nextRun:r,status:i}),await this.callbacks.onTaskRun(e,t),Gy.info(`Task completed`,{id:e.id})}catch(t){Gy.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}},qy=n(`lick-manager`),Jy=class{webhooks=new Map;crontasks=new Map;cronInterval=null;eventHandler=null;async init(){await Ae();let e=await Be();for(let t of e)this.webhooks.set(t.id,t);qy.info(`Loaded webhooks`,{count:this.webhooks.size});let t=await Re();for(let e of t)this.crontasks.set(e.id,e);qy.info(`Loaded crontasks`,{count:this.crontasks.size}),this.cronInterval=setInterval(()=>this.runCronScheduler(),6e4),qy.info(`Cron scheduler started`)}dispose(){this.cronInterval&&=(clearInterval(this.cronInterval),null)}setEventHandler(e){this.eventHandler=e}emitEvent(e){qy.info(`External lick event`,{type:e.type,target:e.targetScoop}),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 Te(i),qy.info(`Webhook created`,{id:r,name:e,scoop:t}),i}async deleteWebhook(e){return this.webhooks.has(e)?(this.webhooks.delete(e),await Fe(e),qy.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){qy.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){qy.debug(`Webhook event dropped by filter`,{webhookId:e,name:r.name});return}typeof t==`object`&&t&&(i=t)}catch(t){qy.error(`Webhook filter error`,{webhookId:e,error:t instanceof Error?t.message:String(t)})}qy.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 ke(o),qy.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 Pe(e),qy.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){qy.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 ke(t);continue}typeof r==`object`&&r&&(n=r)}catch(e){qy.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};qy.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 ke(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 Yy(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(`
13106
+ `);return Error(`Cannot remove scoop '${e}': it has ${r.join(` and `)}. Unregister them first:\n${i}`)}var Xy=null;function Zy(){return Xy||=new Jy,Xy}var Q=n(`orchestrator`),Qy=120*1e3,$y=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;fsWatcher=null;idleTimers=new Map;droppedScoopCosts=[];constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n}async init(){await Ae(),this.sharedFs=await F.create({dbName:`slicc-fs`}),this.sessionStore=new y,this.fsWatcher=new ce,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure();let e=await Ee();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 Ie(`lastAgentTs_${t.jid}`);e&&this.lastAgentTimestamp.set(t.jid,e)}await this.ensureGlobalMemory(),this.scheduler=new Ky({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);Ke(()=>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 Ly(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,globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}async registerScoop(e){await Ve(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=Yy(t.folder,e,n);if(r)throw r}this.snapshotScoopCost(e),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 je(e),this.scoops.delete(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.scoopResponseBuffer.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 F.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.ensureGlobalMemory(),await Iy(this.sharedFs).catch(e=>{Q.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.droppedScoopCosts=[],Q.info(`Filesystem reset and defaults re-seeded`)}async clearAllMessages(){await ze(),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,[]);this.droppedScoopCosts=[],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);Mv(t?.isCone?`cone`:t?.name??`unknown`,localStorage.getItem(`selected-model`)??`unknown`),await Ce(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 Ce(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`||e.channel===`fswatch`||e.channel===`sprinkle`;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 ue(this.sharedFs,[`/scoops/${t.folder}/`,`/shared/`],[`/workspace/`]),i=new Wy(t,{onResponse:(n,r)=>{if(this.scoops.has(e)&&(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:()=>{if(!this.scoops.has(e))return;let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),this.callbacks.onResponseDone(e)},onError:t=>{if(!this.scoops.has(e))return;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=>{if(!this.scoops.has(e))return;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)+`
13107
+ ... (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 Le(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 Le(t)}async getMessagesForScoop(e){return De(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 Oe(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(`
13108
+ `);this.messageQueues.set(e,[]);let c=o[o.length-1];this.lastAgentTimestamp.set(e,c.timestamp),await R(`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()}buildScoopCost(e,t){let n=t.getAgentMessages().filter(e=>e.role===`assistant`);if(n.length===0)return null;let r={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},i=new Map;for(let e of n)r.input+=e.usage.input,r.output+=e.usage.output,r.cacheRead+=e.usage.cacheRead,r.cacheWrite+=e.usage.cacheWrite,r.totalTokens+=e.usage.totalTokens,r.cost.input+=e.usage.cost.input,r.cost.output+=e.usage.cost.output,r.cost.cacheRead+=e.usage.cost.cacheRead,r.cost.cacheWrite+=e.usage.cost.cacheWrite,r.cost.total+=e.usage.cost.total,i.set(e.model,(i.get(e.model)??0)+1);let a=``,o=0;for(let[e,t]of i)t>o&&(a=e,o=t);return{name:e.assistantLabel,type:e.isCone?`cone`:`scoop`,model:a,usage:r,turns:n.length}}snapshotScoopCost(e){let t=this.scoops.get(e),n=this.contexts.get(e);if(!t||!n)return;let r=this.buildScoopCost(t,n);r&&this.droppedScoopCosts.push(r)}getSessionCosts(){let e=[];for(let t of this.scoops.values()){let n=this.contexts.get(t.jid);if(!n)continue;let r=this.buildScoopCost(t,n);r&&e.push(r)}return e.push(...this.droppedScoopCosts),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})})},Qy);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 eb=n(`tray-follower`);function tb(e){let t=new URL(e);return t.searchParams.set(`json`,`true`),t.toString()}async function nb(e){let t=tb(e.joinUrl),n=await lb(await(e.fetchImpl??fetch)(t,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:e.controllerId,runtime:e.runtime})}));return eb.info(`Follower tray attach response`,{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),rb(n)}function rb(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 ib(e){return cb(await ub(e,{action:`poll`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function ab(e){return cb(await ub(e,{action:`answer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function ob(e){return cb(await ub(e,{action:`ice-candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function sb(e){return cb(await ub(e,{action:`retry`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function cb(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function lb(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!db(n)){let n=t?t.slice(0,200):`(empty)`;throw eb.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 ub(e,t){let n=tb(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(!fb(i))throw Error(`Tray follower bootstrap returned an invalid response (${r.status})`);return i}function db(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`&&pb(r.bootstrap):r.action===`fail`?(r.code===`INVALID_JOIN_CAPABILITY`||r.code===`TRAY_EXPIRED`)&&typeof r.error==`string`:!1}function fb(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`&&pb(t.bootstrap)&&Array.isArray(t.events)}function pb(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 mb=n(`tray-webrtc`),hb=`tray-control`,gb=250,_b=class{peerConnectionFactory;dataChannelLabel;peers=new Map;iceServers;constructor(e){this.options=e,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>bb(this.iceServers)),this.dataChannelLabel=e.dataChannelLabel??hb}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=Sb(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`)&&(mb.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`?(mb.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`?(mb.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:xb(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){mb.warn(`Failed to report tray bootstrap failure`,{error:e instanceof Error?e.message:String(e)})}}}},vb=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??(()=>bb(this.iceServers)),this.controllerIdFactory=e.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),this.pollIntervalMs=e.pollIntervalMs??gb}async start(){this.stopped=!1;let e=this.controllerIdFactory(),t=Date.now();p({state:`connecting`,joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:t,lastError:null}),mb.info(`Follower tray join starting`,{joinUrl:this.options.joinUrl});let n=0;for(;;){Cb(this.stopped),n++;let t;try{t=await nb({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 p({...h(),attachAttempts:n,lastError:t}),e}if(p({...h(),attachAttempts:n,lastAttachCode:t.code}),t.action===`wait`){let e=t.retryAfterMs??1e3;mb.info(`Follower tray attach waiting`,{attempt:n,code:t.code,retryAfterMs:e}),n%10==0&&mb.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 p({state:`error`,joinUrl:this.options.joinUrl,trayId:null,error:e,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:e}),mb.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 p({state:`connected`,joinUrl:this.options.joinUrl,trayId:r.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:null}),mb.info(`Follower tray connected`,{trayId:r.trayId,controllerId:e}),r}catch(e){let r=e instanceof Error?e.message:String(e);throw p({state:`error`,joinUrl:this.options.joinUrl,trayId:t.trayId,error:r,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:r}),mb.warn(`Follower tray bootstrap failed`,{error:r}),e}}}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,p({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(Cb(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 ib({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 ab({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,answer:xb(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 sb({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`)&&(mb.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?(mb.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?(mb.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=Sb(n);r&&ob({joinUrl:this.options.joinUrl,controllerId:e,bootstrapId:t,candidate:r,fetchImpl:this.fetchImpl}).catch(e=>{mb.warn(`Failed to send follower ICE candidate`,{error:e instanceof Error?e.message:String(e)})})}),r}};function yb(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 vb({...e,sleep:o,onDisconnected:e=>{s||(mb.warn(`Follower disconnected, starting reconnect loop`,{reason:e}),f(e))}});return l=t,{manager:t,connectionPromise:t.start()}},f=async u=>{if(s||c)return;c=!0,l?.stop(),l=null;let f=0,m=n,g=u??`Unknown disconnect`;for(;!s&&f<a&&(f++,t.onReconnecting?.(f),p({...h(),state:`reconnecting`,error:null,reconnectAttempts:f}),mb.info(`Reconnect attempt`,{attempt:f,delay:m}),await o(m),!s);){let n=null;try{let r=d();n=r.manager;let i=await r.connectionPromise;if(s){n.stop();break}c=!1,p({...h(),state:`connected`,joinUrl:e.joinUrl,trayId:i.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),mb.info(`Reconnect successful`,{attempt:f,trayId:i.trayId}),t.onConnected(i);return}catch(e){g=e instanceof Error?e.message:String(e),mb.warn(`Reconnect attempt failed`,{attempt:f,error:g}),n?.stop(),l=null}m=Math.min(m*r,i)}s||(c=!1,p({...h(),state:`error`,error:`Reconnect failed after ${f} attempts: ${g}`,reconnectAttempts:f}),mb.warn(`Reconnect gave up`,{attempts:f,lastError:g}),t.onGaveUp?.(g))},{connectionPromise:m}=d();return m.then(e=>{s||t.onConnected(e)}).catch(e=>{s||mb.warn(`Initial follower connection failed`,{error:e instanceof Error?e.message:String(e)})}),u}function bb(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 xb(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 Sb(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 Cb(e){if(e)throw Error(`Tray follower stopped before WebRTC bootstrap completed`)}var wb=64*1024;async function Tb(e,t){try{switch(t.op){case`readFile`:return await Eb(e,t.path,t.encoding);case`writeFile`:return[await Db(e,t.path,t.content,t.encoding)];case`stat`:return[await Ob(e,t.path)];case`readDir`:return[await kb(e,t.path)];case`mkdir`:return[await Ab(e,t.path,t.recursive)];case`rm`:return[await jb(e,t.path,t.recursive)];case`exists`:return[await Mb(e,t.path)];case`walk`:return[await Nb(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(e){return[Fb(e)]}}async function Eb(e,t,n){return(n??`utf-8`)===`utf-8`?Pb(await e.readFile(t,{encoding:`utf-8`}),`utf-8`):Pb(Ib(await e.readFile(t,{encoding:`binary`})),`base64`)}async function Db(e,t,n,r){if(r===`base64`){let r=Lb(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:`void`}}}async function Ob(e,t){return{ok:!0,data:{type:`stat`,stat:await e.stat(t)}}}async function kb(e,t){return{ok:!0,data:{type:`dirEntries`,entries:await e.readDir(t)}}}async function Ab(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function jb(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function Mb(e,t){return{ok:!0,data:{type:`exists`,exists:await e.exists(t)}}}async function Nb(e,t){let n=[];for await(let r of e.walk(t))n.push(r);return{ok:!0,data:{type:`paths`,paths:n}}}function Pb(e,t){if(e.length<=wb)return[{ok:!0,data:{type:`file`,content:e,encoding:t}}];let n=Math.ceil(e.length/wb),r=[];for(let i=0;i<n;i++){let a=i*wb,o=e.slice(a,a+wb);r.push({ok:!0,data:{type:`file`,content:o,encoding:t},chunkIndex:i,totalChunks:n})}return r}function Fb(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 Ib(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Lb(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 Rb=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()]}},zb=n(`data-channel-keepalive`),Bb=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++,zb.debug(`Missed pong`,{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){zb.warn(`Channel declared dead`,{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}},Vb=n(`tray-leader-sync`);function Hb(e){return e?e.includes(`standalone`)?`standalone`:e.includes(`extension`)?`extension`:e.includes(`electron`)?`electron`:`unknown`:`unknown`}var Ub=class{followers=new Map;registry=new Rb;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=ge(t),i=r.onMessage(t=>{this.handleFollowerMessage(e,t)}),a=new Bb({sendPing:()=>r.send({type:`ping`}),onDead:()=>{Vb.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:Hb(n?.runtime)}),Vb.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(),Vb.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();me(t.sync,n,r),Vb.debug(`Snapshot sent to follower`,{bootstrapId:e,messageCount:n.length})}handleFollowerMessage(e,t){switch(t.type){case`user_message`:Vb.info(`Follower user message received`,{bootstrapId:e,messageId:t.messageId}),this.options.onFollowerMessage(t.text,t.messageId);break;case`abort`:Vb.info(`Follower abort received`,{bootstrapId:e}),this.options.onFollowerAbort();break;case`request_snapshot`:Vb.info(`Follower snapshot request received`,{bootstrapId:e}),this.sendSnapshotToFollower(e);break;case`targets.advertise`:Vb.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),Vb.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 ve({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),Vb.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);xe(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=pe(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&&xe(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 Tb(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?Tb(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})})}},Wb=n(`tray-follower-sync`),Gb=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=be(e),this.unsubscribe=this.sync.onMessage(e=>{this.handleLeaderMessage(e)}),this.keepalive=new Bb({sendPing:()=>this.sync.send({type:`ping`}),onDead:()=>{Wb.warn(`Leader keepalive dead, cleaning up`),this.handleDisconnect(`Keepalive timeout — leader not responding`),this.options.onDead?.()}}),this.keepalive.start(),e.addEventListener(`close`,()=>{Wb.warn(`Data channel closed`),this.handleDisconnect(`Data channel closed`)}),e.addEventListener(`error`,()=>{Wb.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}),Wb.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`}),Wb.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(),Wb.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,p({...h(),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`:Wb.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=ye(this.snapshotChunkBuffer,e);this.snapshotChunkBuffer=t.buffer,t.result&&(Wb.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),Wb.debug(`Skipping own message echo`,{messageId:e.messageId});break}Wb.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`:Wb.warn(`Error from leader`,{error:e.error}),this.emitEvent({type:`error`,error:e.error});break;case`targets.registry`:Wb.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(),u(Date.now());break}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch(t){Wb.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}}createRemoteTransport(e,t){let n=new ve({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),Wb.debug(`Tracking remote CDP session`,{remoteSessionId:e})}n===`Target.detachFromTarget`&&i&&this.remoteCDPSessions.has(i)&&(this.remoteCDPSessions.delete(i),Wb.debug(`Removed remote CDP session on detach`,{sessionId:i})),xe(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=pe(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 Tb(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 Kb(e,t){if(t)return`extension`;try{return Yb(new URL(e))?`electron-overlay`:`standalone`}catch{return`standalone`}}function qb(e,t){return e===`electron-overlay`||e===`standalone`&&t}function Jb(e){try{let t=new URL(e).searchParams.get(`tab`);return t&&Ji(t)?t:Ki}catch{return Ki}}function Yb(e){return e.pathname===`/electron`||e.pathname===`/electron/`||e.searchParams.get(`runtime`)===`electron-overlay`}function Xb(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}/licks-ws`}function Zb(e,t){return`${new URL(e).origin}/webhooks/${t}`}function Qb(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function $b(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`slicc-electron-overlay:set-tab`}var ex=[`/shared/sprinkles`];async function tx(e){let t=new Map;for(let n of ex)await e.exists(n)&&await nx(e,n,t);return await nx(e,`/`,t),t}async function nx(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.shtml`))continue;let t=rx(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:ix(i,t),autoOpen:ax(i)})}}}function rx(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.shtml`)?t.slice(0,-6):t}function ix(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 ax(e){return/data-sprinkle-autoopen\b/.test(e)}var ox=n(`sprinkle-manager`),sx=`slicc-open-sprinkles`,cx=class{fs;bridge;callbacks;availableSprinkles=new Map;watcherUnsub;openSprinkles=new Map;constructor(e,t,n,r){this.fs=e,this.bridge=new Dh(e,t,e=>this.close(e),r),this.callbacks=n}async restoreOpenSprinkles(){try{let e=localStorage.getItem(sx);if(!e){for(let e of this.availableSprinkles.values())if(e.autoOpen)try{await this.open(e.name)}catch{ox.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{ox.warn(`Failed to restore sprinkle`,{name:e})}}catch{}}persistOpenSprinkles(){try{localStorage.setItem(sx,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),ox.info(`Auto-opened new sprinkle after install`,{name:e.name})}catch{ox.warn(`Failed to auto-open new sprinkle`,{name:e.name})}}async refresh(){this.availableSprinkles=await tx(this.fs),ox.info(`Discovered sprinkles`,{count:this.availableSprinkles.size})}async open(e,t){if(this.openSprinkles.has(e)){ox.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 oi(i,this.bridge.createAPI(e));await a.render(r,e),this.openSprinkles.get(e).renderer=a,this.persistOpenSprinkles(),Pv(e),ox.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(),ox.info(`Sprinkle closed`,{name:e}))}available(){return Array.from(this.availableSprinkles.values())}opened(){return Array.from(this.openSprinkles.keys())}setupWatcher(e){this.watcherUnsub=e.watch(`/workspace`,e=>e.endsWith(`.shtml`),()=>void this.refresh())}dispose(){this.watcherUnsub?.()}sendToSprinkle(e,t){let n=this.openSprinkles.get(e);if(!n){ox.warn(`Cannot send to closed sprinkle`,{name:e});return}this.bridge.pushUpdate(e,t),n.renderer.pushUpdate(t)}};function lx(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function ux(e){let t=[],{payload:n}=e;if(n.title&&t.push(`# ${n.title}`),t.push(`A new handoff was accepted from ${lx(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(`
13109
13109
 
13110
- `)}function dx(e,t){return e.receivedAt.localeCompare(t.receivedAt)}var fx=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(dx))}},$=n(`main`),px=`slicc-pending-mount`,mx=`pendingMount`;async function hx(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(px,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,mx),await new Promise(e=>n.oncomplete=()=>e()),t.close()}async function gx(e){let t;try{t=await new Promise((e,t)=>{let n=indexedDB.open(px,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(mx);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)});if(r){n.objectStore(`handles`).delete(mx),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 _x(){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 vx(){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 yx(e,t,n){let r=_x(),i=0,a=!1,o=()=>{i=0,a||r.hide()};window.addEventListener(`dragenter`,e=>{ga(e.dataTransfer)&&(e.preventDefault(),i+=1,a||r.show(`Drop .skill to install`,`Unpack into /workspace/skills/{name}.`))}),window.addEventListener(`dragover`,e=>{ga(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=_a(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 ue(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 bx(e){let{OffscreenClient:t}=await r(async()=>{let{OffscreenClient:e}=await import(`./offscreen-client-BMlTH2Sh.js`);return{OffscreenClient:e}},__vite__mapDeps([24,17])),{VirtualFS:n}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-DcTkzcRE.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([22,4,17])),i=new $i(e,!0);window.__slicc_debug_tabs=e=>i.setDebugTabs(e),await i.panels.chat.initSession(`session-cone`);let a=null,o=await n.create({dbName:`slicc-fs`});i.panels.fileBrowser.setFs(o),$.info(`File browser wired to shared VFS (local IndexedDB)`);let s=new BroadcastChannel(`preview-vfs`);s.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 o.readFile(n,{encoding:e});s.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}),s.postMessage({type:`preview-vfs-response`,id:t,error:r})}})()},yx(o,vx(),async()=>{await i.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await r(async()=>{let{WasmShell:e}=await import(`./shell-daz5ud1k.js`);return{WasmShell:e}},[]),{PanelCdpProxy:t,BrowserAPI:n}=await r(async()=>{let{PanelCdpProxy:e,BrowserAPI:t}=await import(`./cdp-Dln7uDXr.js`).then(e=>e.t);return{PanelCdpProxy:e,BrowserAPI:t}},__vite__mapDeps([25,4,1,17])),{fetchSecretEnvVars:a}=await r(async()=>{let{fetchSecretEnvVars:e}=await import(`./secret-env-Bf95PNcT.js`);return{fetchSecretEnvVars:e}},[]),s=new t;await s.connect();let c=new n(s),l=await a(),u=new e({fs:o,browserAPI:c,env:Object.keys(l).length>0?l:void 0});await i.panels.terminal.mountShell(u),$.info(`Terminal mounted with shared VFS and BrowserAPI (CDP proxy)`)}catch(e){$.warn(`Failed to mount shell to terminal`,e)}{let{registerSessionCostsProvider:e}=await r(async()=>{let{registerSessionCostsProvider:e}=await import(`./cost-command-DhUP8Ozj.js`).then(e=>e.t);return{registerSessionCostsProvider:e}},__vite__mapDeps([26,4]));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 l,u=new Set,d=e=>{i.setPendingHandoffCount(e.length),i.panels.chat.setPendingHandoffs(e)},f=async e=>{a=e,l.selectedScoopJid=e.jid,i.panels.memory.setSelectedScoop(e.jid),i.setScoopSwitcherSelected?.(e.jid),i.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=e.isCone?void 0:e.name;await i.panels.chat.switchToContext(t,!e.isCone,n),l.isProcessing(e.jid)&&i.panels.chat.setProcessing(!0)};l=new t({onStatusChange:(e,t)=>{i.panels.scoops.updateScoopStatus(e,t),i.updateScoopSwitcherStatus?.(e,t),a?.jid===e&&(i.setAgentProcessing(t===`processing`),t===`processing`?i.panels.chat.setProcessing(!0):t===`ready`&&i.panels.chat.setProcessing(!1))},onScoopCreated:e=>{i.panels.scoops.refreshScoops(),i.refreshScoopSwitcher?.(),a||(a=e,l.selectedScoopJid=e.jid,i.panels.memory.setSelectedScoop(e.jid))},onScoopListUpdate:()=>{let e=new Set(l.getScoops().map(e=>e.folder));for(let t of u)e.has(t)||i.panels.chat.deleteSessionById(`session-${t}`);if(u=e,i.panels.scoops.refreshScoops(),i.refreshScoopSwitcher?.(),!a){let e=l.getScoops().find(e=>e.isCone);e&&(a=e,l.selectedScoopJid=e.jid,i.panels.memory.setSelectedScoop(e.jid))}},onIncomingMessage:(e,t)=>{if(a?.jid===e){let e=t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content;i.panels.chat.addUserMessage(e)}},onPendingHandoffsChange:d,onReady:async()=>{try{$.info(`Offscreen engine ready, scoop count:`,l.getScoops().length),window.localStorage.getItem(`slicc.trayJoinUrl`)&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`refresh-tray-runtime`}}).catch(()=>{});let e=a??l.getScoops().find(e=>e.isCone)??l.getScoops()[0];e&&(a=e,l.selectedScoopJid=e.jid,await f(e))}catch(e){$.error(`Failed to initialize on ready`,{error:e instanceof Error?e.message:String(e)})}}}),l.setLocalFS(o);let p=l.createAgentHandle();i.panels.chat.setAgent(p),i.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=l.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await f(t),i.setActiveTab(`chat`),p.sendMessage(ux(e),`handoff-${e.handoffId}`),l.acceptPendingHandoff(e.handoffId)},onDismiss:e=>{l.dismissPendingHandoff(e.handoffId)}}),l.requestPendingHandoffs(),i.panels.scoops.setOrchestrator(l),i.panels.memory.setOrchestrator(l),i.setScoopSwitcherOrchestrator?.(l),i.onScoopSelect=f,i.onModelChange=e=>{localStorage.setItem(`selected-model`,e),l.updateModel()},i.onClearChat=async()=>{let e=l.getScoops();for(let t of e){let e=t.isCone?`session-cone`:`session-${t.folder}`;await i.panels.chat.deleteSessionById(e)}l.clearAllMessages()},i.onClearFilesystem=async()=>{l.clearFilesystem()},i.panels.chat.onInlineSprinkleLick=(e,t)=>{l.sendSprinkleLick(`inline`,{action:e,data:t})};let m=new cx(o,async e=>{if(e.type===`sprinkle`){if(e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&o.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome completion marker`,e)),n===`shortcut-migrate`&&m.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&gx(o).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 hx(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}l.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop)}},{addSprinkle:(e,t,n,r)=>i.addSprinkle(e,t,n,r),removeSprinkle:e=>i.removeSprinkle(e)},()=>{let e=l.getScoops().find(e=>e.isCone);e&&l.stopScoop(e.jid)});if(window.__slicc_sprinkleManager=m,window.__slicc_reloadSkills=()=>(chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}}),Promise.resolve()),l.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 m.refresh(),e=m.available();break;case`opened`:e=m.opened();break;case`refresh`:await m.refresh(),e=m.available().length;break;case`open`:await m.open(r),e=!0;break;case`close`:m.close(r),e=!0;break;case`send`:m.sendToSprinkle(r,i),e=!0;break;case`openNewAutoOpen`:await m.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 m.refresh(),i.onSprinkleClose=e=>m.close(e),i.getAvailableSprinkles=()=>{let e=new Set(m.opened());return m.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},i.onOpenSprinkle=(e,t)=>m.open(e,t),i.updateAddButtons(),await m.restoreOpenSprinkles(),!await o.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await o.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await o.exists(`/shared/.welcomed`)&&!c(window.localStorage)&&m.available().some(e=>e.name===`welcome`))try{await m.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}$.info(`SprinkleManager initialized (extension mode)`),l.requestState(),$.info(`Extension UI connected to offscreen agent engine`),jv().catch(()=>{})}function xx(){if(typeof chrome<`u`&&chrome?.runtime?.id)return;let e=new Blob([`
13110
+ `)}function dx(e,t){return e.receivedAt.localeCompare(t.receivedAt)}var fx=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(dx))}},$=n(`main`),px=`slicc-pending-mount`,mx=`pendingMount`;async function hx(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(px,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,mx),await new Promise(e=>n.oncomplete=()=>e()),t.close()}async function gx(e){let t;try{t=await new Promise((e,t)=>{let n=indexedDB.open(px,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(mx);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)});if(r){n.objectStore(`handles`).delete(mx),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 _x(){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 vx(){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 yx(e,t,n){let r=_x(),i=0,a=!1,o=()=>{i=0,a||r.hide()};window.addEventListener(`dragenter`,e=>{ga(e.dataTransfer)&&(e.preventDefault(),i+=1,a||r.show(`Drop .skill to install`,`Unpack into /workspace/skills/{name}.`))}),window.addEventListener(`dragover`,e=>{ga(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=_a(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 de(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 bx(e){let{OffscreenClient:t}=await r(async()=>{let{OffscreenClient:e}=await import(`./offscreen-client-BMlTH2Sh.js`);return{OffscreenClient:e}},__vite__mapDeps([24,17])),{VirtualFS:n}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-DcTkzcRE.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([22,4,17])),i=new $i(e,!0);window.__slicc_debug_tabs=e=>i.setDebugTabs(e),await i.panels.chat.initSession(`session-cone`);let a=null,o=await n.create({dbName:`slicc-fs`});i.panels.fileBrowser.setFs(o),$.info(`File browser wired to shared VFS (local IndexedDB)`);let s=new BroadcastChannel(`preview-vfs`);s.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 o.readFile(n,{encoding:e});s.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}),s.postMessage({type:`preview-vfs-response`,id:t,error:r})}})()},yx(o,vx(),async()=>{await i.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await r(async()=>{let{WasmShell:e}=await import(`./shell-DIpPZO9s.js`);return{WasmShell:e}},[]),{PanelCdpProxy:t,BrowserAPI:n}=await r(async()=>{let{PanelCdpProxy:e,BrowserAPI:t}=await import(`./cdp-Dln7uDXr.js`).then(e=>e.t);return{PanelCdpProxy:e,BrowserAPI:t}},__vite__mapDeps([25,4,1,17])),{fetchSecretEnvVars:a}=await r(async()=>{let{fetchSecretEnvVars:e}=await import(`./secret-env-sHNUtcyc.js`);return{fetchSecretEnvVars:e}},[]),s=new t;await s.connect();let c=new n(s),l=await a(),u=new e({fs:o,browserAPI:c,env:Object.keys(l).length>0?l:void 0});await i.panels.terminal.mountShell(u),$.info(`Terminal mounted with shared VFS and BrowserAPI (CDP proxy)`)}catch(e){$.warn(`Failed to mount shell to terminal`,e)}{let{registerSessionCostsProvider:e}=await r(async()=>{let{registerSessionCostsProvider:e}=await import(`./cost-command-DhUP8Ozj.js`).then(e=>e.t);return{registerSessionCostsProvider:e}},__vite__mapDeps([26,4]));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 l,u=new Set,d=e=>{i.setPendingHandoffCount(e.length),i.panels.chat.setPendingHandoffs(e)},f=async e=>{a=e,l.selectedScoopJid=e.jid,i.panels.memory.setSelectedScoop(e.jid),i.setScoopSwitcherSelected?.(e.jid),i.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=e.isCone?void 0:e.name;await i.panels.chat.switchToContext(t,!e.isCone,n),l.isProcessing(e.jid)&&i.panels.chat.setProcessing(!0)};l=new t({onStatusChange:(e,t)=>{i.panels.scoops.updateScoopStatus(e,t),i.updateScoopSwitcherStatus?.(e,t),a?.jid===e&&(i.setAgentProcessing(t===`processing`),t===`processing`?i.panels.chat.setProcessing(!0):t===`ready`&&i.panels.chat.setProcessing(!1))},onScoopCreated:e=>{i.panels.scoops.refreshScoops(),i.refreshScoopSwitcher?.(),a||(a=e,l.selectedScoopJid=e.jid,i.panels.memory.setSelectedScoop(e.jid))},onScoopListUpdate:()=>{let e=new Set(l.getScoops().map(e=>e.folder));for(let t of u)e.has(t)||i.panels.chat.deleteSessionById(`session-${t}`);if(u=e,i.panels.scoops.refreshScoops(),i.refreshScoopSwitcher?.(),!a){let e=l.getScoops().find(e=>e.isCone);e&&(a=e,l.selectedScoopJid=e.jid,i.panels.memory.setSelectedScoop(e.jid))}},onIncomingMessage:(e,t)=>{if(a?.jid===e){let e=t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content;i.panels.chat.addUserMessage(e)}},onPendingHandoffsChange:d,onReady:async()=>{try{$.info(`Offscreen engine ready, scoop count:`,l.getScoops().length),window.localStorage.getItem(`slicc.trayJoinUrl`)&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`refresh-tray-runtime`}}).catch(()=>{});let e=a??l.getScoops().find(e=>e.isCone)??l.getScoops()[0];e&&(a=e,l.selectedScoopJid=e.jid,await f(e))}catch(e){$.error(`Failed to initialize on ready`,{error:e instanceof Error?e.message:String(e)})}}}),l.setLocalFS(o);let p=l.createAgentHandle();i.panels.chat.setAgent(p),i.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=l.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await f(t),i.setActiveTab(`chat`),p.sendMessage(ux(e),`handoff-${e.handoffId}`),l.acceptPendingHandoff(e.handoffId)},onDismiss:e=>{l.dismissPendingHandoff(e.handoffId)}}),l.requestPendingHandoffs(),i.panels.scoops.setOrchestrator(l),i.panels.memory.setOrchestrator(l),i.setScoopSwitcherOrchestrator?.(l),i.onScoopSelect=f,i.onModelChange=e=>{localStorage.setItem(`selected-model`,e),l.updateModel()},i.onClearChat=async()=>{let e=l.getScoops();for(let t of e){let e=t.isCone?`session-cone`:`session-${t.folder}`;await i.panels.chat.deleteSessionById(e)}l.clearAllMessages()},i.onClearFilesystem=async()=>{l.clearFilesystem()},i.panels.chat.onInlineSprinkleLick=(e,t)=>{l.sendSprinkleLick(`inline`,{action:e,data:t})};let m=new cx(o,async e=>{if(e.type===`sprinkle`){if(e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&o.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome completion marker`,e)),n===`shortcut-migrate`&&m.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&gx(o).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 hx(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}l.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop)}},{addSprinkle:(e,t,n,r)=>i.addSprinkle(e,t,n,r),removeSprinkle:e=>i.removeSprinkle(e)},()=>{let e=l.getScoops().find(e=>e.isCone);e&&l.stopScoop(e.jid)});if(window.__slicc_sprinkleManager=m,window.__slicc_reloadSkills=()=>(chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}}),Promise.resolve()),l.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 m.refresh(),e=m.available();break;case`opened`:e=m.opened();break;case`refresh`:await m.refresh(),e=m.available().length;break;case`open`:await m.open(r),e=!0;break;case`close`:m.close(r),e=!0;break;case`send`:m.sendToSprinkle(r,i),e=!0;break;case`openNewAutoOpen`:await m.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 m.refresh(),i.onSprinkleClose=e=>m.close(e),i.getAvailableSprinkles=()=>{let e=new Set(m.opened());return m.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},i.onOpenSprinkle=(e,t)=>m.open(e,t),i.updateAddButtons(),await m.restoreOpenSprinkles(),!await o.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await o.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await o.exists(`/shared/.welcomed`)&&!c(window.localStorage)&&m.available().some(e=>e.name===`welcome`))try{await m.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}$.info(`SprinkleManager initialized (extension mode)`),l.requestState(),$.info(`Extension UI connected to offscreen agent engine`),jv().catch(()=>{})}function xx(){if(typeof chrome<`u`&&chrome?.runtime?.id)return;let e=new Blob([`
13111
13111
  let lastPong = Date.now();
13112
13112
  let frozen = false;
13113
13113
  setInterval(() => {
@@ -13127,7 +13127,7 @@ ${t}
13127
13127
  }
13128
13128
  }
13129
13129
  };
13130
- `],{type:`application/javascript`}),t=URL.createObjectURL(e),n=new Worker(t);URL.revokeObjectURL(t),n.onmessage=e=>{if(e.data.type===`ping`)n.postMessage({type:`pong`});else if(e.data.type===`freeze-detected`)console.error(`[freeze-watchdog] Main thread blocked for ${e.data.elapsed}ms — capturing trace on recovery`);else if(e.data.type===`freeze-recovered`){console.error(`[freeze-watchdog] Main thread recovered. Stack trace at recovery point:`),console.trace(`[freeze-watchdog] recovery stack`);let e=performance.getEntriesByType(`longtask`);e.length>0&&console.error(`[freeze-watchdog] Long tasks:`,e.map(e=>({duration:e.duration,startTime:e.startTime,name:e.name})))}},window.addEventListener(`beforeunload`,()=>{n.terminate()},{once:!0})}async function Sx(){xx(),aa(),pa();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=c(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 a=!t&&c(window.localStorage),o=typeof chrome<`u`&&!!chrome?.runtime?.id,l=Kb(window.location.href,o);if(l===`extension`)return bx(e);let u=new $i(e,l===`electron-overlay`);if(l===`electron-overlay`){let e=Jb(window.location.href);u.setActiveTab(e);let t=document.createElement(`style`);t.id=`slicc-electron-overlay-runtime-style`,t.textContent=`
13130
+ `],{type:`application/javascript`}),t=URL.createObjectURL(e),n=new Worker(t);URL.revokeObjectURL(t),n.onmessage=e=>{if(e.data.type===`ping`)n.postMessage({type:`pong`});else if(e.data.type===`freeze-detected`)console.error(`[freeze-watchdog] Main thread blocked for ${e.data.elapsed}ms — capturing trace on recovery`);else if(e.data.type===`freeze-recovered`){console.error(`[freeze-watchdog] Main thread recovered. Stack trace at recovery point:`),console.trace(`[freeze-watchdog] recovery stack`);let e=performance.getEntriesByType(`longtask`);e.length>0&&console.error(`[freeze-watchdog] Long tasks:`,e.map(e=>({duration:e.duration,startTime:e.startTime,name:e.name})))}},window.addEventListener(`beforeunload`,()=>{n.terminate()},{once:!0})}async function Sx(){xx(),aa(),pa();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)),O();let t=T(),n=c(window.localStorage);if(!t&&!n){let e=window.location.port===`5710`||window.location.port===`3000`;window.location.port===``&&window.location.pathname.includes(`/join/`)?await re({autoJoinUrl:window.location.origin+window.location.pathname}):!e&&window.location.port!==``?await re({preferTrayJoin:!0}):await re(),t=T()}let a=!t&&c(window.localStorage),o=typeof chrome<`u`&&!!chrome?.runtime?.id,l=Kb(window.location.href,o);if(l===`extension`)return bx(e);let u=new $i(e,l===`electron-overlay`);if(l===`electron-overlay`){let e=Jb(window.location.href);u.setActiveTab(e);let t=document.createElement(`style`);t.id=`slicc-electron-overlay-runtime-style`,t.textContent=`
13131
13131
  #app > .tab-bar { display: none !important; }
13132
13132
  #app > .tab-content {
13133
13133
  height: calc(100vh - var(--s2-header-height));
@@ -13135,4 +13135,4 @@ ${t}
13135
13135
  #app > .tab-content > .tab-content__panel {
13136
13136
  height: 100%;
13137
13137
  }
13138
- `,document.head.appendChild(t),window.addEventListener(`message`,e=>{e.source===window.parent&&$b(e.data)&&u.setActiveTab(Jb(`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 f=vx();await u.panels.chat.initSession(`session-cone`),$.info(`Session initialized`);let p=new xe,m=e=>{u.setPendingHandoffCount(e.length),u.panels.chat.setPendingHandoffs(e)},h=new Set,_=e=>{$.debug(`Emit to UI`,{type:e.type,listenerCount:h.size});for(let t of h)try{t(e)}catch(t){$.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}},v=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),v?.jid===e&&_({type:`message_start`,messageId:r}),o}let E=new $y(u.getIframeContainer(),{onResponse:(e,t,n)=>{let r=w(e);n?r.content+=t:(r.content=t,r.isStreaming=!1),v?.jid===e&&(_({type:`content_delta`,messageId:r.id,text:t}),n||_({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),v?.jid===e&&_({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()}),v?.jid===e&&(_({type:`message_start`,messageId:n}),_({type:`content_delta`,messageId:n,text:t}),_({type:`content_done`,messageId:n}))},onStatusChange:(e,t)=>{if(u.panels.scoops.updateScoopStatus(e,t),u.updateScoopSwitcherStatus?.(e,t),v?.jid===e){if(u.setAgentProcessing(t===`processing`),t===`processing`)u.panels.chat.setProcessing(!0);else if(t===`ready`){u.panels.chat.setProcessing(!1);let t=y.get(e)??`done-${e}-${x()}`;y.delete(e),_({type:`turn_end`,messageId:t})}}},onError:(e,t)=>{$.error(`Scoop error`,{scoopJid:e,error:t}),v?.jid===e&&_({type:`error`,error:t})},getBrowserAPI:()=>p,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}),v?.jid===e&&_({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)}}v?.jid===e&&a&&_({type:`tool_result`,messageId:a,toolName:t,result:n,isError:r})},onToolUI:(e,t,n,r)=>{let i=y.get(e);i?_({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&&_({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),v?.jid===e&&(_({type:`message_start`,messageId:t.id}),_({type:`content_delta`,messageId:t.id,text:n.content}),_({type:`content_done`,messageId:t.id}))}});await E.init(),u.panels.scoops.setOrchestrator(E),u.panels.memory.setOrchestrator(E),u.setScoopSwitcherOrchestrator?.(E);let D=E.getSharedFS();if(D){u.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})}})()},yx(D,(e,t)=>{t===`error`?$.warn(`Dropped skill install failed`,{message:e}):$.info(`Dropped skill installed`,{message:e}),f(e,t)},async()=>{await u.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await r(async()=>{let{WasmShell:e}=await import(`./shell-daz5ud1k.js`);return{WasmShell:e}},[]),{fetchSecretEnvVars:t}=await r(async()=>{let{fetchSecretEnvVars:e}=await import(`./secret-env-Bf95PNcT.js`);return{fetchSecretEnvVars:e}},[]),n=await t(),i=new e({fs:D,browserAPI:p,env:Object.keys(n).length>0?n:void 0});await u.panels.terminal.mountShell(i),$.info(`Terminal mounted with shared VFS`);try{let{BshWatchdog:e}=await r(async()=>{let{BshWatchdog:e}=await import(`./bsh-watchdog-UyxqvRBs.js`);return{BshWatchdog:e}},__vite__mapDeps([27,17])),t=new e({browserAPI:p,scriptCatalog:i.getScriptCatalog(),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(a)$.info(`Skipping local cone bootstrap while joining a tray without a configured provider`);else if(!ee)v=await u.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?(v=t,$.info(`Restored scoop from URL`,{folder:e})):v=O.find(e=>e.isCone)??O[0]}else v=O.find(e=>e.isCone)??O[0]}v&&u.panels.memory.setSelectedScoop(v.jid);let A=null,j=null,te={sendMessage(e,t){if(!v){_({type:`error`,error:`No scoop selected`});return}let n={id:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:v.jid,senderId:`user`,senderName:`User`,content:e,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`};S(v.jid).push({id:n.id,role:`user`,content:e,timestamp:Date.now()}),A?.broadcastUserMessage(e,n.id),E.handleMessage(n),E.createScoopTab(v.jid)},onEvent(e){return h.add(e),()=>h.delete(e)},stop(){v&&(E.stopScoop(v.jid),E.clearQueuedMessages(v.jid).catch(e=>{$.error(`Failed to clear queued messages on stop`,{error:e instanceof Error?e.message:String(e)})}))}};u.panels.chat.setAgent(te),u.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 F(t),u.setActiveTab(`chat`),te.sendMessage(ux(e),`handoff-${e.handoffId}`);let n=j?.clearHandoff(e.handoffId);n&&await Promise.allSettled(n.targetIds.map(e=>p.closePage(e)))},onDismiss:async e=>{let t=j?.clearHandoff(e.handoffId);t&&await Promise.allSettled(t.targetIds.map(e=>p.closePage(e)))}}),u.panels.chat.setDeleteQueuedMessageCallback(e=>{if(v){E.deleteQueuedMessage(v.jid,e).catch(t=>{$.error(`Failed to delete queued message`,{messageId:e,error:t instanceof Error?t.message:String(t)})});let t=b.get(v.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 r(async()=>{let{getLickManager:e}=await import(`./lick-manager-RAKOzfxb.js`);return{getLickManager:e}},[]),M=ne();await M.init(),E.setLickManager(M);let re=e=>{let t=e.type===`webhook`,n=e.type===`sprinkle`,r=e.type===`fswatch`,i=e.type===`session-reload`,a=t?e.webhookName:n?e.sprinkleName:r?e.fswatchName:i?`session-reload`:e.cronName,o=t?e.webhookId:n?e.sprinkleName:r?e.fswatchId:i?`session-reload`:e.cronId,s=e.type;if($.debug(`Lick event`,{type:e.type,name:a,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`&&N?.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&D&&gx(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 hx(t),N?.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),N?.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}})();return}let c=E.getScoops(),l;if(l=e.targetScoop?c.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):c.find(e=>e.isCone),l){let c=`${s}-${o}-${Date.now()}`,d=`[${t?`Webhook Event`:n?`Sprinkle Event`:r?`File Watch Event`:i?`Session Reload`:`Cron Event`}: ${a}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``,f={id:c,chatJid:l.jid,senderId:s,senderName:`${s}:${a}`,content:d,timestamp:e.timestamp,fromAssistant:!1,channel:s};S(l.jid).push({id:c,role:`user`,content:d,timestamp:Date.now(),source:`lick`,channel:s}),v?.jid===l.jid&&u.panels.chat.addLickMessage(c,d,s),$.info(`Routing lick to scoop`,{type:s,name:a,scoopJid:l.jid}),E.handleMessage(f)}else $.warn(`Lick target scoop not found`,{targetScoop:e.targetScoop})};M.setEventHandler(re),D&&ae().then(async e=>{if(e.length===0)return;let t=[];for(let{path:n,handle:r}of e)try{if(!(`queryPermission`in r)){t.push({path:n,dirName:r.name});continue}await r.queryPermission({mode:`readwrite`})===`granted`?(await D.mount(n,r),$.info(`Restored mount from previous session`,{path:n,name:r.name})):t.push({path:n,dirName:r.name})}catch{t.push({path:n,dirName:r.name})}t.length>0&&re({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:t}})}).catch(e=>$.warn(`Failed to restore persisted mounts`,e)),u.panels.chat.onInlineSprinkleLick=(e,t)=>{re({type:`sprinkle`,sprinkleName:`inline`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:e,data:t}})};let N=null;if(D){if(N=new cx(D,re,{addSprinkle:(e,t,n,r)=>u.addSprinkle(e,t,n,r),removeSprinkle:e=>u.removeSprinkle(e)},()=>{let e=E.getScoops().find(e=>e.isCone);e&&(E.stopScoop(e.jid),E.clearQueuedMessages(e.jid).catch(e=>{$.error(`Failed to clear queued messages on sprinkle stopCone`,{error:e instanceof Error?e.message:String(e)})}))}),window.__slicc_sprinkleManager=N,window.__slicc_reloadSkills=()=>E.reloadAllSkills(),await N.refresh(),u.onSprinkleClose=e=>N.close(e),u.getAvailableSprinkles=()=>{let e=new Set(N.opened());return N.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},u.onOpenSprinkle=(e,t)=>N.open(e,t),u.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`)&&!a&&N.available().some(e=>e.name===`welcome`))try{await N.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}await N.restoreOpenSprinkles(),$.info(`SprinkleManager initialized`)}let P=()=>{let e=Xb(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:M.listWebhooks()};break;case`create_webhook`:{let t=await M.createWebhook(n.name||`default`,n.scoop,n.filter),r=Bp().session,i=r?.webhookUrl?Qb(r.webhookUrl,t.id):Zb(window.location.href,t.id);e={type:`response`,requestId:n.requestId,data:{...t,url:i}};break}case`delete_webhook`:e=await M.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:M.listCronTasks()};break;case`create_crontask`:{if(!n.name)throw Error(`name is required`);if(!n.cron)throw Error(`cron is required`);let t=await M.createCronTask(n.name,n.cron,n.scoop,n.filter);e={type:`response`,requestId:n.requestId,data:t};break}case`delete_crontask`:e=await M.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=Bp();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`&&M.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(P,3e3)},t.onerror=e=>{$.error(`Lick WebSocket error`,{error:String(e)})}};P(),u.onModelChange=e=>{localStorage.setItem(`selected-model`,e),E.updateModel()},u.onClearChat=async()=>{await E.clearAllMessages(),b.clear()},u.onClearFilesystem=async()=>{await E.resetFilesystem()};let F=async e=>{$.info(`Scoop selected`,{jid:e.jid,name:e.name}),v=e,E.createScoopTab(e.jid),u.panels.memory.setSelectedScoop(e.jid),u.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 u.panels.chat.switchToContext(t,!e.isCone,r),u.panels.chat.loadMessages(n);else if(await u.panels.chat.switchToContext(t,!e.isCone,r),u.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),u.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),u.panels.chat.addUserMessage(t.content)}else n.fromAssistant?(_({type:`message_start`,messageId:n.id}),_({type:`content_delta`,messageId:n.id,text:n.content}),_({type:`content_done`,messageId:n.id})):u.panels.chat.addUserMessage(n.content)}}e.isCone&&E.isProcessing(e.jid)&&u.panels.chat.setProcessing(!0)};if(u.onScoopSelect=F,v&&(E.createScoopTab(v.jid),await F(v)),j=new fx({onPendingHandoffsChange:m}),l===`standalone`||l===`electron-overlay`){let e=await i(),t=qb(l,e!==null)?s:null,n=await g({locationHref:window.location.href,storage:window.localStorage,envBaseUrl:null,defaultWorkerBaseUrl:t,runtimeConfigFetcher:async()=>e}),r=null,a=null,o=null;qh(()=>A?(e,t)=>A.sendFsRequest(e,t):r?(e,t)=>r.sendFsRequest(e,t):null),Pf(()=>A?()=>A.getBestFollowerForTeleport():null),Ff(()=>A?()=>A.getConnectedFollowers():null);let c=e=>{o&&=(clearInterval(o),null),r?.close();let t=`follower-${e.bootstrapId}`,n=new Gb(e.channel,{browserTransport:p.getTransport(),browserAPI:p,onSnapshot:e=>{u.panels.chat.loadMessages(e)},onUserMessage:e=>{u.panels.chat.addUserMessage(e)},onStatus:e=>{u.panels.chat.setProcessing(e===`processing`)},onTargetsChanged:()=>void i()});r=n,p.setTrayTargetProvider(n),u.panels.chat.setAgent(n),n.requestSnapshot();let i=async()=>{try{let e=await p.listPages();n.advertiseTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})),t)}catch{}};o=setInterval(i,5e3),i(),$.info(`Follower sync wired to chat panel`,{trayId:e.trayId})},f=e=>{a?.cancel(),o&&=(clearInterval(o),null),r?.close(),r=null,a=yb({joinUrl:e,runtime:`slicc-standalone`,fetchImpl:Jp()},{onConnected:e=>c(e),onReconnecting:e=>{$.info(`Follower reconnecting`,{attempt:e})},onGaveUp:e=>{$.warn(`Follower reconnect gave up`,{lastError:e})}})};if(window.addEventListener(`slicc:tray-join`,(e=>{f(e.detail.joinUrl)})),window.addEventListener(`beforeunload`,()=>{o&&clearInterval(o),r?.close(),a?.cancel()},{once:!0}),n?.joinUrl)f(n.joinUrl);else if(n?.workerBaseUrl){let e,t,r,i,a=()=>{t=new Ub({browserTransport:p.getTransport(),browserAPI:p,getMessages:()=>u.panels.chat.getMessages(),getScoopJid:()=>v?.jid??`cone`,onFollowerMessage:(e,t)=>{u.panels.chat.addUserMessage(e),te.sendMessage(e,t)},onFollowerAbort:()=>{te.stop()}}),A=t,Xp(()=>t.getConnectedFollowers()),p.setTrayTargetProvider(t),i&&clearInterval(i);let n=async()=>{try{let e=await p.listPages();t.setLocalTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})))}catch{}};i=setInterval(n,5e3),n(),r=new _b({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(),h.add(e=>{t.broadcastEvent(e)}),e=new Wp({workerBaseUrl:n.workerBaseUrl,runtime:`slicc-standalone`,fetchImpl:Jp(),onControlMessage:e=>{if(e.type===`webhook.event`){M.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)})})}}),$p(async()=>{t.stop(),r.stop(),e.stop(),await e.clearSession();let n=await e.start(),i=d(window.location.href,n.workerBaseUrl,n.trayId);return i!==window.location.href&&window.history.replaceState(window.history.state,``,i),a(),Bp()}),e.start().then(e=>{let t=d(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}),jv().catch(()=>{})}Sx().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{Wv as a,ci as c,Vy as i,ai as l,Yy as n,Ta as o,Zy as r,oi as s,Jy as t};
13138
+ `,document.head.appendChild(t),window.addEventListener(`message`,e=>{e.source===window.parent&&$b(e.data)&&u.setActiveTab(Jb(`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 f=vx();await u.panels.chat.initSession(`session-cone`),$.info(`Session initialized`);let p=new Se,m=e=>{u.setPendingHandoffCount(e.length),u.panels.chat.setPendingHandoffs(e)},h=new Set,_=e=>{$.debug(`Emit to UI`,{type:e.type,listenerCount:h.size});for(let t of h)try{t(e)}catch(t){$.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}},v=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 C(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=w.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),v?.jid===e&&_({type:`message_start`,messageId:r}),o}let w=new $y(u.getIframeContainer(),{onResponse:(e,t,n)=>{let r=C(e);n?r.content+=t:(r.content=t,r.isStreaming=!1),v?.jid===e&&(_({type:`content_delta`,messageId:r.id,text:t}),n||_({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),v?.jid===e&&_({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`};w.handleMessage(r),S(e).push({id:n,role:`assistant`,content:t,timestamp:Date.now()}),v?.jid===e&&(_({type:`message_start`,messageId:n}),_({type:`content_delta`,messageId:n,text:t}),_({type:`content_done`,messageId:n}))},onStatusChange:(e,t)=>{if(u.panels.scoops.updateScoopStatus(e,t),u.updateScoopSwitcherStatus?.(e,t),v?.jid===e){if(u.setAgentProcessing(t===`processing`),t===`processing`)u.panels.chat.setProcessing(!0);else if(t===`ready`){u.panels.chat.setProcessing(!1);let t=y.get(e)??`done-${e}-${x()}`;y.delete(e),_({type:`turn_end`,messageId:t})}}},onError:(e,t)=>{$.error(`Scoop error`,{scoopJid:e,error:t}),v?.jid===e&&_({type:`error`,error:t})},getBrowserAPI:()=>p,onToolStart:(e,t,n)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let r=C(e);r.toolCalls||=[],r.toolCalls.push({id:x(),name:t,input:n}),v?.jid===e&&_({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)}}v?.jid===e&&a&&_({type:`tool_result`,messageId:a,toolName:t,result:n,isError:r})},onToolUI:(e,t,n,r)=>{let i=y.get(e);i?_({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&&_({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),v?.jid===e&&(_({type:`message_start`,messageId:t.id}),_({type:`content_delta`,messageId:t.id,text:n.content}),_({type:`content_done`,messageId:t.id}))}});await w.init(),u.panels.scoops.setOrchestrator(w),u.panels.memory.setOrchestrator(w),u.setScoopSwitcherOrchestrator?.(w);let E=w.getSharedFS();if(E){u.panels.fileBrowser.setFs(E),$.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 E.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})}})()},yx(E,(e,t)=>{t===`error`?$.warn(`Dropped skill install failed`,{message:e}):$.info(`Dropped skill installed`,{message:e}),f(e,t)},async()=>{await u.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await r(async()=>{let{WasmShell:e}=await import(`./shell-DIpPZO9s.js`);return{WasmShell:e}},[]),{fetchSecretEnvVars:t}=await r(async()=>{let{fetchSecretEnvVars:e}=await import(`./secret-env-sHNUtcyc.js`);return{fetchSecretEnvVars:e}},[]),n=await t(),i=new e({fs:E,browserAPI:p,env:Object.keys(n).length>0?n:void 0});await u.panels.terminal.mountShell(i),$.info(`Terminal mounted with shared VFS`);try{let{BshWatchdog:e}=await r(async()=>{let{BshWatchdog:e}=await import(`./bsh-watchdog-UyxqvRBs.js`);return{BshWatchdog:e}},__vite__mapDeps([27,17])),t=new e({browserAPI:p,scriptCatalog:i.getScriptCatalog(),fs:E});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 D=w.getScoops(),ee=D.some(e=>e.isCone);if(a)$.info(`Skipping local cone bootstrap while joining a tray without a configured provider`);else if(!ee)v=await u.panels.scoops.createScoop(`Cone`,!0),$.info(`Created cone`);else{let e=new URLSearchParams(window.location.search).get(`scoop`);if(e){let t=D.find(t=>t.folder===e);t?(v=t,$.info(`Restored scoop from URL`,{folder:e})):v=D.find(e=>e.isCone)??D[0]}else v=D.find(e=>e.isCone)??D[0]}v&&u.panels.memory.setSelectedScoop(v.jid);let k=null,te=null,A={sendMessage(e,t){if(!v){_({type:`error`,error:`No scoop selected`});return}let n={id:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:v.jid,senderId:`user`,senderName:`User`,content:e,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`};S(v.jid).push({id:n.id,role:`user`,content:e,timestamp:Date.now()}),k?.broadcastUserMessage(e,n.id),w.handleMessage(n),w.createScoopTab(v.jid)},onEvent(e){return h.add(e),()=>h.delete(e)},stop(){v&&(w.stopScoop(v.jid),w.clearQueuedMessages(v.jid).catch(e=>{$.error(`Failed to clear queued messages on stop`,{error:e instanceof Error?e.message:String(e)})}))}};u.panels.chat.setAgent(A),u.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=w.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await N(t),u.setActiveTab(`chat`),A.sendMessage(ux(e),`handoff-${e.handoffId}`);let n=te?.clearHandoff(e.handoffId);n&&await Promise.allSettled(n.targetIds.map(e=>p.closePage(e)))},onDismiss:async e=>{let t=te?.clearHandoff(e.handoffId);t&&await Promise.allSettled(t.targetIds.map(e=>p.closePage(e)))}}),u.panels.chat.setDeleteQueuedMessageCallback(e=>{if(v){w.deleteQueuedMessage(v.jid,e).catch(t=>{$.error(`Failed to delete queued message`,{messageId:e,error:t instanceof Error?t.message:String(t)})});let t=b.get(v.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 r(async()=>{let{getLickManager:e}=await import(`./lick-manager-DQg9qWyf.js`);return{getLickManager:e}},[]),ie=ne();await ie.init(),w.setLickManager(ie);let ae=e=>{let t=e.type===`webhook`,n=e.type===`sprinkle`,r=e.type===`fswatch`,i=e.type===`session-reload`,a=t?e.webhookName:n?e.sprinkleName:r?e.fswatchName:i?`session-reload`:e.cronName,o=t?e.webhookId:n?e.sprinkleName:r?e.fswatchId:i?`session-reload`:e.cronId,s=e.type;if($.debug(`Lick event`,{type:e.type,name:a,targetScoop:e.targetScoop}),n&&e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&E?.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome marker`,e)),n===`shortcut-migrate`&&j?.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&E&&gx(E).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 hx(t),j?.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),j?.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}})();return}let c=w.getScoops(),l;if(l=e.targetScoop?c.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):c.find(e=>e.isCone),l){let c=`${s}-${o}-${Date.now()}`,d=`[${t?`Webhook Event`:n?`Sprinkle Event`:r?`File Watch Event`:i?`Session Reload`:`Cron Event`}: ${a}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``,f={id:c,chatJid:l.jid,senderId:s,senderName:`${s}:${a}`,content:d,timestamp:e.timestamp,fromAssistant:!1,channel:s};S(l.jid).push({id:c,role:`user`,content:d,timestamp:Date.now(),source:`lick`,channel:s}),v?.jid===l.jid&&u.panels.chat.addLickMessage(c,d,s),$.info(`Routing lick to scoop`,{type:s,name:a,scoopJid:l.jid}),w.handleMessage(f)}else $.warn(`Lick target scoop not found`,{targetScoop:e.targetScoop})};ie.setEventHandler(ae),E&&se().then(async e=>{if(e.length===0)return;let t=[];for(let{path:n,handle:r}of e)try{if(!(`queryPermission`in r)){t.push({path:n,dirName:r.name});continue}await r.queryPermission({mode:`readwrite`})===`granted`?(await E.mount(n,r),$.info(`Restored mount from previous session`,{path:n,name:r.name})):t.push({path:n,dirName:r.name})}catch{t.push({path:n,dirName:r.name})}t.length>0&&ae({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:t}})}).catch(e=>$.warn(`Failed to restore persisted mounts`,e)),u.panels.chat.onInlineSprinkleLick=(e,t)=>{ae({type:`sprinkle`,sprinkleName:`inline`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:e,data:t}})};let j=null;if(E){if(j=new cx(E,ae,{addSprinkle:(e,t,n,r)=>u.addSprinkle(e,t,n,r),removeSprinkle:e=>u.removeSprinkle(e)},()=>{let e=w.getScoops().find(e=>e.isCone);e&&(w.stopScoop(e.jid),w.clearQueuedMessages(e.jid).catch(e=>{$.error(`Failed to clear queued messages on sprinkle stopCone`,{error:e instanceof Error?e.message:String(e)})}))}),window.__slicc_sprinkleManager=j,window.__slicc_reloadSkills=()=>w.reloadAllSkills(),await j.refresh(),u.onSprinkleClose=e=>j.close(e),u.getAvailableSprinkles=()=>{let e=new Set(j.opened());return j.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},u.onOpenSprinkle=(e,t)=>j.open(e,t),u.updateAddButtons(),!await E.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await E.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await E.exists(`/shared/.welcomed`)&&!a&&j.available().some(e=>e.name===`welcome`))try{await j.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}await j.restoreOpenSprinkles(),$.info(`SprinkleManager initialized`)}let M=()=>{let e=Xb(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:ie.listWebhooks()};break;case`create_webhook`:{let t=await ie.createWebhook(n.name||`default`,n.scoop,n.filter),r=Bp().session,i=r?.webhookUrl?Qb(r.webhookUrl,t.id):Zb(window.location.href,t.id);e={type:`response`,requestId:n.requestId,data:{...t,url:i}};break}case`delete_webhook`:e=await ie.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:ie.listCronTasks()};break;case`create_crontask`:{if(!n.name)throw Error(`name is required`);if(!n.cron)throw Error(`cron is required`);let t=await ie.createCronTask(n.name,n.cron,n.scoop,n.filter);e={type:`response`,requestId:n.requestId,data:t};break}case`delete_crontask`:e=await ie.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=Bp();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`&&ie.handleWebhookEvent(n.webhookId,n.headers,n.body),n.type===`handoff_event`&&te&&te.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(M,3e3)},t.onerror=e=>{$.error(`Lick WebSocket error`,{error:String(e)})}};M(),u.onModelChange=e=>{localStorage.setItem(`selected-model`,e),w.updateModel()},u.onClearChat=async()=>{await w.clearAllMessages(),b.clear()},u.onClearFilesystem=async()=>{await w.resetFilesystem()};let N=async e=>{$.info(`Scoop selected`,{jid:e.jid,name:e.name}),v=e,w.createScoopTab(e.jid),u.panels.memory.setSelectedScoop(e.jid),u.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 u.panels.chat.switchToContext(t,!e.isCone,r),u.panels.chat.loadMessages(n);else if(await u.panels.chat.switchToContext(t,!e.isCone,r),u.panels.chat.getMessages().length===0){let t=await w.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),u.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),u.panels.chat.addUserMessage(t.content)}else n.fromAssistant?(_({type:`message_start`,messageId:n.id}),_({type:`content_delta`,messageId:n.id,text:n.content}),_({type:`content_done`,messageId:n.id})):u.panels.chat.addUserMessage(n.content)}}e.isCone&&w.isProcessing(e.jid)&&u.panels.chat.setProcessing(!0)};if(u.onScoopSelect=N,v&&(w.createScoopTab(v.jid),await N(v)),te=new fx({onPendingHandoffsChange:m}),l===`standalone`||l===`electron-overlay`){let e=await i(),t=qb(l,e!==null)?s:null,n=await g({locationHref:window.location.href,storage:window.localStorage,envBaseUrl:null,defaultWorkerBaseUrl:t,runtimeConfigFetcher:async()=>e}),r=null,a=null,o=null;qh(()=>k?(e,t)=>k.sendFsRequest(e,t):r?(e,t)=>r.sendFsRequest(e,t):null),Pf(()=>k?()=>k.getBestFollowerForTeleport():null),Ff(()=>k?()=>k.getConnectedFollowers():null);let c=e=>{o&&=(clearInterval(o),null),r?.close();let t=`follower-${e.bootstrapId}`,n=new Gb(e.channel,{browserTransport:p.getTransport(),browserAPI:p,onSnapshot:e=>{u.panels.chat.loadMessages(e)},onUserMessage:e=>{u.panels.chat.addUserMessage(e)},onStatus:e=>{u.panels.chat.setProcessing(e===`processing`)},onTargetsChanged:()=>void i()});r=n,p.setTrayTargetProvider(n),u.panels.chat.setAgent(n),n.requestSnapshot();let i=async()=>{try{let e=await p.listPages();n.advertiseTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})),t)}catch{}};o=setInterval(i,5e3),i(),$.info(`Follower sync wired to chat panel`,{trayId:e.trayId})},f=e=>{a?.cancel(),o&&=(clearInterval(o),null),r?.close(),r=null,a=yb({joinUrl:e,runtime:`slicc-standalone`,fetchImpl:Jp()},{onConnected:e=>c(e),onReconnecting:e=>{$.info(`Follower reconnecting`,{attempt:e})},onGaveUp:e=>{$.warn(`Follower reconnect gave up`,{lastError:e})}})};if(window.addEventListener(`slicc:tray-join`,(e=>{f(e.detail.joinUrl)})),window.addEventListener(`beforeunload`,()=>{o&&clearInterval(o),r?.close(),a?.cancel()},{once:!0}),n?.joinUrl)f(n.joinUrl);else if(n?.workerBaseUrl){let e,t,r,i,a=()=>{t=new Ub({browserTransport:p.getTransport(),browserAPI:p,getMessages:()=>u.panels.chat.getMessages(),getScoopJid:()=>v?.jid??`cone`,onFollowerMessage:(e,t)=>{u.panels.chat.addUserMessage(e),A.sendMessage(e,t)},onFollowerAbort:()=>{A.stop()}}),k=t,Xp(()=>t.getConnectedFollowers()),p.setTrayTargetProvider(t),i&&clearInterval(i);let n=async()=>{try{let e=await p.listPages();t.setLocalTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})))}catch{}};i=setInterval(n,5e3),n(),r=new _b({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(),h.add(e=>{t.broadcastEvent(e)}),e=new Wp({workerBaseUrl:n.workerBaseUrl,runtime:`slicc-standalone`,fetchImpl:Jp(),onControlMessage:e=>{if(e.type===`webhook.event`){ie.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)})})}}),$p(async()=>{t.stop(),r.stop(),e.stop(),await e.clearSession();let n=await e.start(),i=d(window.location.href,n.workerBaseUrl,n.trayId);return i!==window.location.href&&window.history.replaceState(window.history.state,``,i),a(),Bp()}),e.start().then(e=>{let t=d(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:w.getScoops().length}),jv().catch(()=>{})}Sx().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{Wv as a,ci as c,Vy as i,ai as l,Yy as n,Ta as o,Zy as r,oi as s,Jy as t};