sliccy 1.58.1 → 1.59.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/sql-wasm-Cx-UtEsl.js","assets/chunk-zsgVPwQN.js","assets/__vite-browser-external-fVHSRdZ9.js","assets/pyodide-CDyS-YOW.js","assets/preload-helper-ca-nBW7U.js","assets/es-DlWKrNhH.js","assets/pako-djzWUVJp.js","assets/dist-B3JYrjq2.js","assets/provider-settings-DtthfIx_.js","assets/provider-settings-B3VwS5n4.js","assets/env-api-keys-DlVZ9FrG.js","assets/simple-options-DZXt61Q2.js","assets/json-parse-JW3qhabb.js","assets/openai-Cn7eGqwa.js","assets/tray-follower-status-BlQSlF6m.js","assets/logger-B-No_qN_.js","assets/providers-CBTIfSNw.js","assets/skills-DuL04FMa.js","assets/constants-Dqhmtsws.js","assets/skills-Bp26ndk0.js","assets/fs-Br5jEe6j.js","assets/xterm-BmfB5bmM.css","assets/offscreen-client-BIdj4gf1.js","assets/cdp-B4yzwpE0.js","assets/cost-command-DhUP8Ozj.js","assets/bsh-watchdog-BaiyTJC8.js"])))=>i.map(i=>d[i]);
2
- import{o as e,t}from"./chunk-zsgVPwQN.js";import{t as n}from"./logger-B-No_qN_.js";import{c as r,f as i,h as a,i as o,l as s,m as c,n as l,o as u,p as d,r as f,s as p,t as m,u as h,v as g,y as _}from"./tray-follower-status-BlQSlF6m.js";import{t as v}from"./preload-helper-ca-nBW7U.js";import{A as y,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 re,y as ie}from"./provider-settings-B3VwS5n4.js";import{f as M,l as N,p as P,s as ae,u as F}from"./constants-Dqhmtsws.js";import{a as oe,i as I,l as L,n as se,o as ce,r as le,s as R}from"./fs-Br5jEe6j.js";import{d as ue,n as de}from"./skills-Bp26ndk0.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-B4yzwpE0.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-cJ5msdlA.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/sql-wasm-Cx-UtEsl.js","assets/chunk-zsgVPwQN.js","assets/__vite-browser-external-fVHSRdZ9.js","assets/pyodide-CDyS-YOW.js","assets/preload-helper-ca-nBW7U.js","assets/es-DlWKrNhH.js","assets/pako-djzWUVJp.js","assets/dist-B3JYrjq2.js","assets/provider-settings-DtthfIx_.js","assets/provider-settings-B3VwS5n4.js","assets/env-api-keys-DlVZ9FrG.js","assets/simple-options-DZXt61Q2.js","assets/json-parse-JW3qhabb.js","assets/openai-Cn7eGqwa.js","assets/tray-follower-status-BlQSlF6m.js","assets/logger-B-No_qN_.js","assets/providers-CBTIfSNw.js","assets/skills-DuL04FMa.js","assets/constants-Dqhmtsws.js","assets/skills-Bp26ndk0.js","assets/fs-Br5jEe6j.js","assets/xterm-BmfB5bmM.css","assets/offscreen-client-BhqrZE0B.js","assets/cdp-B4yzwpE0.js","assets/cost-command-DhUP8Ozj.js","assets/bsh-watchdog-BaiyTJC8.js"])))=>i.map(i=>d[i]);
2
+ import{o as e,t}from"./chunk-zsgVPwQN.js";import{t as n}from"./logger-B-No_qN_.js";import{c as r,f as i,h as a,i as o,l as s,m as c,n as l,o as u,p as d,r as f,s as p,t as m,u as h,v as g,y as _}from"./tray-follower-status-BlQSlF6m.js";import{t as v}from"./preload-helper-ca-nBW7U.js";import{A as y,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-B3VwS5n4.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-Br5jEe6j.js";import{d as ue,n as de}from"./skills-Bp26ndk0.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-B4yzwpE0.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-cJ5msdlA.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,7 +62,7 @@ ${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:re}=Cr,{IS_ALLOWED_URI:ie}=Cr,M=null,N=H({},[...nr,...rr,...ir,...or,...cr]),P=null,ae=H({},[...lr,...ur,...dr,...fr]),F=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}})),oe=null,I=null,L=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,M=Jn(e,`ALLOWED_TAGS`)?H({},e.ALLOWED_TAGS,Ve):N,P=Jn(e,`ALLOWED_ATTR`)?H({},e.ALLOWED_ATTR,Ve):ae,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,oe=Jn(e,`FORBID_TAGS`)?H({},e.FORBID_TAGS,Ve):er({}),I=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,ie=e.ALLOWED_URI_REGEXP||vr,Me=e.NAMESPACE||je,Ie=e.MATHML_TEXT_INTEGRATION_POINTS||Ie,Le=e.HTML_INTEGRATION_POINTS||Le,F=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&We(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(F.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&We(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(F.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements==`boolean`&&(F.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ue&&(ce=!1),ge&&(he=!0),Se&&(M=H({},cr),P=Pn(null),Se.html===!0&&(H(M,nr),H(P,lr)),Se.svg===!0&&(H(M,rr),H(P,ur),H(P,fr)),Se.svgFilters===!0&&(H(M,ir),H(P,ur),H(P,fr)),Se.mathMl===!0&&(H(M,or),H(P,dr),H(P,fr))),Jn(e,`ADD_TAGS`)||(L.tagCheck=null),Jn(e,`ADD_ATTR`)||(L.attributeCheck=null),e.ADD_TAGS&&(typeof e.ADD_TAGS==`function`?L.tagCheck=e.ADD_TAGS:(M===N&&(M=er(M)),H(M,e.ADD_TAGS,Ve))),e.ADD_ATTR&&(typeof e.ADD_ATTR==`function`?L.attributeCheck=e.ADD_ATTR:(P===ae&&(P=er(P)),H(P,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&&(M[`#text`]=!0),fe&&H(M,[`html`,`head`,`body`]),M.table&&(H(M,[`tbody`]),delete oe.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:M}),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(!(L.tagCheck instanceof Function&&L.tagCheck(r))&&(!M[r]||oe[r])){if(!oe[r]&&nt(r)&&(F.tagNameCheck instanceof RegExp&&Yn(F.tagNameCheck,r)||F.tagNameCheck instanceof Function&&F.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(I[t]||ve&&(t===`id`||t===`name`)&&(r in n||r in Ue))return!1;if(!(ce&&!I[t]&&Yn(A,t))&&!(se&&Yn(j,t))&&!(L.attributeCheck instanceof Function&&L.attributeCheck(t,e))){if(!P[t]||I[t]){if(!(nt(e)&&(F.tagNameCheck instanceof RegExp&&Yn(F.tagNameCheck,e)||F.tagNameCheck instanceof Function&&F.tagNameCheck(e))&&(F.attributeNameCheck instanceof RegExp&&Yn(F.attributeNameCheck,t)||F.attributeNameCheck instanceof Function&&F.attributeNameCheck(t,e))||t===`is`&&F.allowCustomizedBuiltInElements&&(F.tagNameCheck instanceof RegExp&&Yn(F.tagNameCheck,r)||F.tagNameCheck instanceof Function&&F.tagNameCheck(r))))return!1}else if(!De[t]&&!Yn(ie,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,re)},rt=function(e){B(D.beforeSanitizeAttributes,e,null);let{attributes:n}=e;if(!n||Qe(e))return;let r={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:P,forceKeepAttr:void 0},i=n.length;for(;i--;){let{name:a,namespaceURI:o,value:s}=n[i],c=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(!M[t]||oe[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(P.shadowroot||P.shadowrootmode)&&(l=E.call(r,l,!0)),l}let d=fe?i.outerHTML:i.innerHTML;return fe&&M[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&Yn(xr,i.ownerDocument.doctype.name)&&(d=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
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
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=Nr(n):t===`json`?n=Pr(n):[`bash`,`sh`,`shell`,`zsh`].includes(t)&&(n=Fr(n))),n}function Nr(e){return e=e.replace(/(\/\/[^\n]*)/g,`<span class="tok-comment">$1</span>`),e=e.replace(/(\/\*[\s\S]*?\*\/)/g,`<span class="tok-comment">$1</span>`),e=e.replace(/(&quot;[^&]*?&quot;|&#x27;[^&]*?&#x27;|`[^`]*?`)/g,`<span class="tok-string">$1</span>`),e=e.replace(RegExp(`\\b(${`const.let.var.function.return.if.else.for.while.class.extends.import.export.from.default.new.this.async.await.try.catch.throw.typeof.instanceof.interface.type.enum.implements.abstract.public.private.protected.readonly.static.void.null.undefined.true.false`.split(`.`).join(`|`)})\\b`,`g`),`<span class="tok-keyword">$1</span>`),e=e.replace(/\b(\d+\.?\d*)\b/g,`<span class="tok-number">$1</span>`),e=e.replace(/\b([a-zA-Z_$][\w$]*)\s*(?=\()/g,`<span class="tok-fn">$1</span>`),e}function Pr(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 Fr(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 Ir=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>`}}}),Lr={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 Rr(e){return Ar(e,Lr)}function zr(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 Br=/<p><strong>Error:<\/strong>\s*([\s\S]*?)<\/p>/g;function Vr(e){return zr(Rr(Ir.parse(e)))}function Hr(e){return e.replace(Br,(e,t)=>`<div class="msg__error" role="alert"><div class="msg__error-label">Error</div><div class="msg__error-body">${t}</div></div>`)}function Ur(e){return Vr(e)}function Wr(e){return Hr(Vr(e))}function Gr(e){if(typeof e==`string`)return jr(e);try{return jr(JSON.stringify(e,null,2))}catch{return jr(String(e))}}var Kr=`browser-coding-agent`,qr=1,Jr=`sessions`;function Yr(){return new Promise((e,t)=>{let n=indexedDB.open(Kr,qr);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Jr)||e.createObjectStore(Jr,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var Xr=class{db=null;async init(){this.db=await Yr()}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(Jr,`readwrite`);i.objectStore(Jr).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(Jr,`readonly`).objectStore(Jr).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(Jr,`readonly`).objectStore(Jr).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(Jr,`readwrite`);i.objectStore(Jr).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)}},Zr={"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 Qr(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function $r(){return typeof window>`u`?null:window.SpeechRecognition||window.webkitSpeechRecognition||null}var ei=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=$r();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(Qr())this.startExtensionPopup();else{this.shouldBeListening=!1;let t=e?.name,n=Zr[`not-allowed`];t===`NotFoundError`?n=Zr[`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=Zr[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=Zr[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=$r();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}},ti={autoSend:`voice-auto-send`,lang:`voice-lang`};function ni(){return localStorage.getItem(ti.lang)||`en-US`}var ri=typeof chrome<`u`&&!!chrome?.runtime?.id;function ii(e){let t=e.trimStart().toLowerCase();return t.startsWith(`<!doctype`)||t.startsWith(`<html`)}var ai=class{container;bridge;scripts=[];iframe=null;messageHandler=null;constructor(e,t){this.container=e,this.bridge=t}async render(e,t){this.dispose(),ri?await this.renderInSandbox(e,t,ii(e)):ii(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();r.contentWindow.postMessage({type:`sprinkle-render`,content:e,name:t,themeCSS:i,savedState:s,savedStorage:a,fullDoc:n},`*`)}pushUpdate(e){this.iframe?.contentWindow&&this.iframe.contentWindow.postMessage({type:`sprinkle-update`,data:e},`*`)}collectThemeCSS(){return si()}generateBridgeScript(){return`(function() {
67
67
  var _updateListeners = new Set();
68
68
  var _sprinkleName = '';
@@ -236,7 +236,7 @@ mark{background:color-mix(in srgb,var(--s2-accent) 25%,transparent);color:inheri
236
236
  </style>
237
237
  <script>${li}<\/script>
238
238
  </head>
239
- <body class="sprinkle-inline">${t}</body></html>`;if(ci)return pi(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 di(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(ui(a,i,t))}return r}function fi(e){for(let t of e)try{t.dispose()}catch{}e.length=0}function pi(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 mi=n(`tool-ui-renderer`),hi=typeof chrome<`u`&&!!chrome?.runtime?.id,gi=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){hi?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(()=>{mi.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){mi.warn(`Tool UI message nonce mismatch`,{expected:this.nonce,received:n.nonce});return}n.type===`tool-ui-action`&&n.id===this.requestId?(mi.info(`Tool UI action received`,{id:n.id,action:n.action}),_.handleAction(n.id,{action:n.action,data:n.data})):n.type===`tool-ui-rendered`&&n.id===this.requestId?n.height&&this.iframe&&(this.iframe.style.height=`${Math.max(60,n.height)}px`):n.type===`tool-ui-resize`&&n.id===this.requestId&&n.height&&this.iframe&&(this.iframe.style.height=`${Math.max(60,n.height)}px`)}},window.addEventListener(`message`,this.messageHandler);let{collectThemeCSS:n}=await v(async()=>{let{collectThemeCSS:e}=await import(`./sprinkle-renderer-Dnz_l3xR.js`);return{collectThemeCSS:e}},[]),r=n();t.contentWindow.postMessage({type:`tool-ui-render`,id:this.requestId,nonce:this.nonce,html:e,themeCSS:r},`*`)}renderWithInlineSprinkle(e){let t=document.createElement(`div`);t.className=`msg__inline-sprinkle`,this.container.appendChild(t),this.inlineSprinkle=ui(t,e,(e,t)=>{mi.info(`Tool UI action (inline sprinkle)`,{id:this.requestId,action:e}),_.handleAction(this.requestId,{action:e,data:t})})}dispose(){this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.iframe&&=(this.iframe.remove(),null),this.inlineSprinkle&&=(this.inlineSprinkle.dispose(),null)}},_i=new Map;function vi(e,t,n){let r=_i.get(t);r&&r.dispose();let i=new gi(e,t);return _i.set(t,i),i.render(n).catch(e=>{mi.error(`Failed to render tool UI`,{requestId:t,error:e.message})}),i}function yi(e){let t=_i.get(e);t&&(t.dispose(),_i.delete(e))}var bi=n(`chat-panel`);function xi(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var Si={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 Ci(e){return Si[e]??`?`}function wi(e){return e.role===`assistant`?Wr(e.content):Ur(e.content)}var Ti=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 Xr,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:xi(),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:xi(),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 ei({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=>{bi.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:ni()}),this.micBtn.addEventListener(`click`,()=>{this.toggleVoiceMode()}),this.keydownListener=e=>{e.shiftKey&&(e.ctrlKey||e.metaKey)&&e.key===`V`&&(e.preventDefault(),this.toggleVoiceMode())},document.addEventListener(`keydown`,this.keydownListener)}renderPendingHandoffs(){if(!this.handoffsEl)return;if(this.pendingHandoffs.length===0){this.handoffsEl.hidden=!0,this.handoffsEl.innerHTML=``;return}let e=this.pendingHandoffs.length===1?`1 pending handoff`:`${this.pendingHandoffs.length} pending handoffs`;this.handoffsEl.hidden=!1,this.handoffsEl.innerHTML=`
239
+ <body class="sprinkle-inline">${t}</body></html>`;if(ci)return pi(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 di(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(ui(a,i,t))}return r}function fi(e){for(let t of e)try{t.dispose()}catch{}e.length=0}function pi(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 mi=n(`tool-ui-renderer`),hi=typeof chrome<`u`&&!!chrome?.runtime?.id,gi=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){hi?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(()=>{mi.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){mi.warn(`Tool UI message nonce mismatch`,{expected:this.nonce,received:n.nonce});return}n.type===`tool-ui-action`&&n.id===this.requestId?(mi.info(`Tool UI action received`,{id:n.id,action:n.action}),_.handleAction(n.id,{action:n.action,data:n.data})):n.type===`tool-ui-rendered`&&n.id===this.requestId?n.height&&this.iframe&&(this.iframe.style.height=`${Math.max(60,n.height)}px`):n.type===`tool-ui-resize`&&n.id===this.requestId&&n.height&&this.iframe&&(this.iframe.style.height=`${Math.max(60,n.height)}px`)}},window.addEventListener(`message`,this.messageHandler);let{collectThemeCSS:n}=await v(async()=>{let{collectThemeCSS:e}=await import(`./sprinkle-renderer-BY-gXpo0.js`);return{collectThemeCSS:e}},[]),r=n();t.contentWindow.postMessage({type:`tool-ui-render`,id:this.requestId,nonce:this.nonce,html:e,themeCSS:r},`*`)}renderWithInlineSprinkle(e){let t=document.createElement(`div`);t.className=`msg__inline-sprinkle`,this.container.appendChild(t),this.inlineSprinkle=ui(t,e,(e,t)=>{mi.info(`Tool UI action (inline sprinkle)`,{id:this.requestId,action:e}),_.handleAction(this.requestId,{action:e,data:t})})}dispose(){this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.iframe&&=(this.iframe.remove(),null),this.inlineSprinkle&&=(this.inlineSprinkle.dispose(),null)}},_i=new Map;function vi(e,t,n){let r=_i.get(t);r&&r.dispose();let i=new gi(e,t);return _i.set(t,i),i.render(n).catch(e=>{mi.error(`Failed to render tool UI`,{requestId:t,error:e.message})}),i}function yi(e){let t=_i.get(e);t&&(t.dispose(),_i.delete(e))}var bi=n(`chat-panel`);function xi(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var Si={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 Ci(e){return Si[e]??`?`}function wi(e){return e.role===`assistant`?Wr(e.content):Ur(e.content)}var Ti=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 Xr,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:xi(),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:xi(),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 ei({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=>{bi.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:ni()}),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=`
240
240
  <div class="chat__handoffs-inner">
241
241
  <div class="chat__handoffs-header">${jr(e)}</div>
242
242
  ${this.pendingHandoffs.map(e=>this.renderPendingHandoffCard(e)).join(``)}
@@ -250,8 +250,8 @@ mark{background:color-mix(in srgb,var(--s2-accent) 25%,transparent);color:inheri
250
250
  <button class="chat__handoff-btn" data-action="dismiss" data-handoff-id="${jr(e.handoffId)}" type="button">Dismiss</button>
251
251
  </div>
252
252
  </section>
253
- `}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:xi(),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(bi.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:xi(),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}bi.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){bi.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}bi.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)),vi(e,n,r)}else i<10?setTimeout(()=>this.handleToolUI(e,t,n,r,i+1),100):bi.warn(`handleToolUI: tool call element not found in DOM after retries`,{toolName:t})}handleToolUIDone(e,t){yi(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:xi(),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=ie(),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=wi(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=wi(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=wi(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=Ur(e.content),t.appendChild(o),t}createToolCallEl(e){Ci(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=Gr(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&&(fi(t),this.inlineSprinkles.delete(e))}disposeAllInlineSprinkles(){for(let[,e]of this.inlineSprinkles)fi(e);this.inlineSprinkles.clear()}hydrateInlineSprinklesInEl(e,t){let n=di(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=``}},Ei=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
254
- `,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 Di(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 Oi(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 ki(){return Oi([`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 Ai(){return Oi([`M6 2h5l5 5v9a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1z`,`M11 2v5h5`])}function ji(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 Mi(e){return`'${e.replace(/'/g,`'\\''`)}'`}function Ni(e){return`${d(e)?`imgcat`:`cat`} ${Mi(e)}`}var Pi=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(ji(e)),a.appendChild(o);let s=document.createElement(`span`);s.className=`file-browser__icon`,s.appendChild(ki()),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(Ai()),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=Di(e.size),a.appendChild(t)}catch(e){console.warn(`[FileBrowser] stat failed:`,i,e instanceof Error?e.message:String(e))}let s=document.createElement(`button`);s.className=`file-browser__action-btn`,s.style.marginLeft=`8px`,s.textContent=`CAT`,s.title=this.onRunCommand?d(i)?`Preview media in terminal`:`Preview in terminal`:`Terminal unavailable`,s.disabled=!this.onRunCommand,s.addEventListener(`click`,e=>{e.stopPropagation(),this.previewFile(i)}),a.appendChild(s),a.addEventListener(`click`,()=>{this.selectPath(i,`file`)}),t.appendChild(a)}}}async collectFiles(e,t){if(!this.fs)return{};let n={},r=await this.fs.readDir(e);for(let i of r){let r=e===`/`?`/`+i.name:e+`/`+i.name,a=t?t+`/`+i.name:i.name;if(i.type===`directory`){let e=await this.collectFiles(r,a);Object.assign(n,e)}else{let e=await this.fs.readFile(r,{encoding:`binary`});n[a]=e instanceof Uint8Array?e:new TextEncoder().encode(e)}}return n}async downloadDirAsZip(e,t){if(this.fs)try{let n=P(await this.collectFiles(e,``)),r=new Blob([n.buffer],{type:`application/zip`}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=t+`.zip`,a.click(),URL.revokeObjectURL(i)}catch(t){console.error(`[FileBrowser] ZIP download failed:`,e,t instanceof Error?t.message:String(t))}}previewFile(e){if(!this.onRunCommand)return;let t=Ni(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)}},Fi=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)}},Ii=n(`scoops-panel`),Li=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(),Ii.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(),Ii.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=`
253
+ `}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:xi(),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(bi.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:xi(),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}bi.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){bi.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}bi.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)),vi(e,n,r)}else i<10?setTimeout(()=>this.handleToolUI(e,t,n,r,i+1),100):bi.warn(`handleToolUI: tool call element not found in DOM after retries`,{toolName:t})}handleToolUIDone(e,t){yi(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:xi(),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=wi(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=wi(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=wi(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=Ur(e.content),t.appendChild(o),t}createToolCallEl(e){Ci(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=Gr(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&&(fi(t),this.inlineSprinkles.delete(e))}disposeAllInlineSprinkles(){for(let[,e]of this.inlineSprinkles)fi(e);this.inlineSprinkles.clear()}hydrateInlineSprinklesInEl(e,t){let n=di(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=``}},Ei=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
254
+ `,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 Di(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 Oi(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 ki(){return Oi([`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 Ai(){return Oi([`M6 2h5l5 5v9a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1z`,`M11 2v5h5`])}function ji(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 Mi(e){return`'${e.replace(/'/g,`'\\''`)}'`}function Ni(e){return`${d(e)?`imgcat`:`cat`} ${Mi(e)}`}var Pi=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(ji(e)),a.appendChild(o);let s=document.createElement(`span`);s.className=`file-browser__icon`,s.appendChild(ki()),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(Ai()),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=Di(e.size),a.appendChild(t)}catch(e){console.warn(`[FileBrowser] stat failed:`,i,e instanceof Error?e.message:String(e))}let s=document.createElement(`button`);s.className=`file-browser__action-btn`,s.style.marginLeft=`8px`,s.textContent=`CAT`,s.title=this.onRunCommand?d(i)?`Preview media in terminal`:`Preview in terminal`:`Terminal unavailable`,s.disabled=!this.onRunCommand,s.addEventListener(`click`,e=>{e.stopPropagation(),this.previewFile(i)}),a.appendChild(s),a.addEventListener(`click`,()=>{this.selectPath(i,`file`)}),t.appendChild(a)}}}async collectFiles(e,t){if(!this.fs)return{};let n={},r=await this.fs.readDir(e);for(let i of r){let r=e===`/`?`/`+i.name:e+`/`+i.name,a=t?t+`/`+i.name:i.name;if(i.type===`directory`){let e=await this.collectFiles(r,a);Object.assign(n,e)}else{let e=await this.fs.readFile(r,{encoding:`binary`});n[a]=e instanceof Uint8Array?e:new TextEncoder().encode(e)}}return n}async downloadDirAsZip(e,t){if(this.fs)try{let n=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=Ni(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)}},Fi=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)}},Ii=n(`scoops-panel`),Li=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(),Ii.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(),Ii.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=`
255
255
  .scoops-panel {
256
256
  display: flex;
257
257
  flex-direction: column;
@@ -722,7 +722,7 @@ mark{background:color-mix(in srgb,var(--s2-accent) 25%,transparent);color:inheri
722
722
  50% { transform: scale(1.3); }
723
723
  100% { transform: scale(1); }
724
724
  }
725
- `,document.head.appendChild(e)}},zi=[{id:`chat`,label:`Chat`},{id:`terminal`,label:`Terminal`},{id:`files`,label:`Files`},{id:`memory`,label:`Memory`}],Bi=`slicc-hidden-tabs`,Vi=[`terminal`,`memory`];function Hi(){try{let e=localStorage.getItem(Bi);return e?new Set(JSON.parse(e)):new Set(Vi)}catch{return new Set(Vi)}}function Ui(e){let t=e.filter(e=>e!==`chat`);localStorage.setItem(Bi,JSON.stringify(t))}var Wi=zi.filter(e=>!Hi().has(e.id)),Gi=`chat`,Ki=new Set(zi.map(e=>e.id));function qi(e){return Ki.has(e)}var Ji=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}},Yi=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 Xi(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=Zi(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=Zi(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 Zi(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 Qi=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 Yi;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));Ui(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 Ri(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 Ji(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 Wi){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 Ti(n),terminal:new Ei(r,{onClearTerminal:()=>{this.panels.terminal.clearTerminal()}}),fileBrowser:new Pi(i,{onRunCommand:async e=>{await this.runFileBrowserCommand(e),this.extensionZone.activateTab(`terminal`)}}),memory:new Fi(a),scoops:new Li(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&&Xi(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 Ji(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 Ti(o),terminal:new Ei(this.terminalContainer,{onClearTerminal:()=>{this.panels.terminal.clearTerminal(),this.openTerminal()}}),fileBrowser:new Pi(u,{onRunCommand:async e=>{await this.runFileBrowserCommand(e),this.openTerminal()}}),memory:new Fi(d),scoops:new Li(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));Xi(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)}},$i=`slicc-theme`,ea=new Set([`dark`,`light`,`system`]);function ta(){let e=localStorage.getItem($i);return e&&ea.has(e)?e:`system`}function na(){let e=ta(),t=e===`light`;e===`system`&&(t=window.matchMedia?.(`(prefers-color-scheme: light)`).matches??!1),document.documentElement.classList.toggle(`theme-light`,t)}var ra;function ia(){na(),ra=window.matchMedia?.(`(prefers-color-scheme: light)`),ra?.addEventListener?.(`change`,()=>{ta()===`system`&&na()})}var aa=300,oa=6,sa=null,ca=null;function la(){return sa||(sa=document.createElement(`div`),sa.className=`s2-tooltip`,document.body.appendChild(sa)),sa}function ua(e){let t=e.getAttribute(`data-tooltip`);if(!t)return;let n=la();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-oa,s=r.left+r.width/2-i.width/2):a===`right`?(o=r.top+r.height/2-i.height/2,s=r.right+oa):(o=r.bottom+oa,s=r.left+r.width/2-i.width/2),a===`bottom`&&o+i.height>window.innerHeight-4?o=r.top-i.height-oa:a===`top`&&o<4&&(o=r.bottom+oa),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 da(){ca&&=(clearTimeout(ca),null),sa?.classList.remove(`s2-tooltip--visible`)}function fa(){document.addEventListener(`pointerenter`,e=>{let t=e.target.closest?.(`[data-tooltip]`);t&&(da(),ca=setTimeout(()=>ua(t),aa))},!0),document.addEventListener(`pointerleave`,e=>{e.target.closest?.(`[data-tooltip]`)&&da()},!0),document.addEventListener(`pointerdown`,da,!0)}function pa(e){return e.toLowerCase().endsWith(ae)}function ma(e){return Array.from(e).find(e=>pa(e.name))??null}function ha(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 ga(e){if(!e)return null;if(e.files){let t=ma(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&&pa(e.name))return e}return null}var _a=new Map,va=new Map;function ya(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 ba(e,t){let n=ya(e);_a.set(n,t),setTimeout(()=>_a.delete(n),1e4)}function xa(e,t){va.set(e,t),setTimeout(()=>va.delete(e),1e4)}function Sa(e){let t=va.get(e);return t?(va.delete(e),t):null}function Ca(e){let t=ya(e),n=_a.get(t);return n?(_a.delete(t),n):null}var wa=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=Ca(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 L&&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=await this.vfs.stat(t);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)}}async lstat(e){let t=R(e),n=await this.vfs.lstat(t);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)}}async mkdir(e,t){await this.vfs.mkdir(R(e),t)}async readdir(e){let t=R(e);return t===`/usr`?[`bin`]:t===`/usr/bin`?this.getVirtualBinCommands().slice().sort():(await this.vfs.readDir(t)).map(e=>e.name)}async readdirWithFileTypes(e){let t=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=await this.vfs.readDir(t),r=[];for(let e of n)if(e.type===`symlink`){let n=!1,i=!1;try{let r=t===`/`?`/${e.name}`:`${t}/${e.name}`,a=await this.vfs.stat(r);n=a.type===`file`,i=a.type===`directory`}catch{}r.push({name:e.name,isFile:n,isDirectory:i,isSymbolicLink:!0})}else r.push({name:e.name,isFile:e.type===`file`,isDirectory:e.type===`directory`,isSymbolicLink:!1});return r}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 L(`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){}},Ta=new TextDecoder;function Ea(e){return typeof e==`string`?e:Ta.decode(e)}function Da(e){return JSON.parse(Ea(e))}function Oa(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 ka=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(``)}})),Aa=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}})),ja=t((e=>{var t=ka(),n=Aa(),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 re(this,t,n);case`utf8`:case`utf-8`:return ee(this,t,n);case`ascii`:return te(this,t,n);case`latin1`:case`binary`:return ne(this,t,n);case`base64`:return k(this,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return ie(this,t,n);default:if(r)throw TypeError(`Unknown encoding: `+e);e=(e+``).toLowerCase(),r=!0}}s.prototype._isBuffer=!0;function x(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}s.prototype.swap16=function(){let e=this.length;if(e%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(let t=0;t<e;t+=2)x(this,t,t+1);return this},s.prototype.swap32=function(){let e=this.length;if(e%4!=0)throw RangeError(`Buffer size must be a multiple of 32-bits`);for(let t=0;t<e;t+=4)x(this,t,t+3),x(this,t+1,t+2);return this},s.prototype.swap64=function(){let e=this.length;if(e%8!=0)throw RangeError(`Buffer size must be a multiple of 64-bits`);for(let t=0;t<e;t+=8)x(this,t,t+7),x(this,t+1,t+6),x(this,t+2,t+5),x(this,t+3,t+4);return this},s.prototype.toString=function(){let e=this.length;return e===0?``:arguments.length===0?ee(this,0,e):b.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw TypeError(`Argument must be a Buffer`);return this===e?!0:s.compare(this,e)===0},s.prototype.inspect=function(){let t=``,n=e.INSPECT_MAX_BYTES;return t=this.toString(`hex`,0,n).replace(/(.{2})/g,`$1 `).trim(),this.length>n&&(t+=` ... `),`<Buffer `+t+`>`},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(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 re(e,t,n){let r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let i=``;for(let r=t;r<n;++r)i+=xe[e[r]];return i}function ie(e,t,n){let r=e.slice(t,n),i=``;for(let e=0;e<r.length-1;e+=2)i+=String.fromCharCode(r[e]+r[e+1]*256);return i}s.prototype.slice=function(e,t){let n=this.length;e=~~e,t=t===void 0?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t<e&&(t=e);let r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r};function M(e,t,n){if(e%1!=0||e<0)throw RangeError(`offset is not uint`);if(e+t>n)throw RangeError(`Trying to access beyond buffer length`)}s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e],i=1,a=0;for(;++a<t&&(i*=256);)r+=this[e+a]*i;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=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||M(e,t,this.length);let r=this[e],i=1,a=0;for(;++a<t&&(i*=256);)r+=this[e+a]*i;return i*=128,r>=i&&(r-=2**(8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=t,i=1,a=this[e+--r];for(;r>0&&(i*=256);)a+=this[e+--r]*i;return i*=128,a>=i&&(a-=2**(8*t)),a},s.prototype.readInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||M(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||M(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=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||M(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||M(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||M(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||M(e,8,this.length),n.read(this,e,!1,52,8)};function N(e,t,n,r,i,a){if(!s.isBuffer(e))throw TypeError(`"buffer" argument must be a Buffer instance`);if(t>i||t<a)throw RangeError(`"value" argument is out of bounds`);if(n+r>e.length)throw RangeError(`Index out of range`)}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;N(this,e,t,n,r,0)}let i=1,a=0;for(this[t]=e&255;++a<n&&(i*=256);)this[t+a]=e/i&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;N(this,e,t,n,r,0)}let i=n-1,a=1;for(this[t+i]=e&255;--i>=0&&(a*=256);)this[t+i]=e/a&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,255,0),this[t]=e&255,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function P(e,t,n,r,i){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 ae(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 P(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeBigUInt64BE=Se(function(e,t=0){return ae(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);N(this,e,t,n,r-1,-r)}let i=0,a=1,o=0;for(this[t]=e&255;++i<n&&(a*=256);)e<0&&o===0&&this[t+i-1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);N(this,e,t,n,r-1,-r)}let i=n-1,a=1,o=0;for(this[t+i]=e&255;--i>=0&&(a*=256);)e<0&&o===0&&this[t+i+1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4},s.prototype.writeBigInt64LE=Se(function(e,t=0){return P(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))}),s.prototype.writeBigInt64BE=Se(function(e,t=0){return ae(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))});function F(e,t,n,r,i,a){if(n+r>e.length||n<0)throw RangeError(`Index out of range`)}function oe(e,t,r,i,a){return t=+t,r>>>=0,a||F(e,t,r,4,34028234663852886e22,-34028234663852886e22),n.write(e,t,r,i,23,4),r+4}s.prototype.writeFloatLE=function(e,t,n){return oe(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return oe(this,e,t,!1,n)};function I(e,t,r,i,a){return t=+t,r>>>=0,a||F(e,t,r,8,17976931348623157e292,-17976931348623157e292),n.write(e,t,r,i,52,8),r+8}s.prototype.writeDoubleLE=function(e,t,n){return I(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return I(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 L={};function se(e,t,n){L[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 L.ERR_OUT_OF_RANGE(`value`,i,e)}le(r,i,a)}function ue(e,t){if(typeof e!=`number`)throw new L.ERR_INVALID_ARG_TYPE(t,`number`,e)}function de(e,t,n){throw Math.floor(e)===e?t<0?new L.ERR_BUFFER_OUT_OF_BOUNDS:new L.ERR_OUT_OF_RANGE(n||`offset`,`>= ${+!!n} and <= ${t}`,e):(ue(e,n),new L.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`)}})),Ma=ja();globalThis.Buffer===void 0&&(globalThis.Buffer=Ma.Buffer);var Na=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})),Pa=t(((e,t)=>{t.exports=Na()})),Fa=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}}})),Ia=t(((e,t)=>{var n=ja(),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)}})),La=t(((e,t)=>{var n={}.toString;t.exports=Array.isArray||function(e){return n.call(e)==`[object Array]`}})),Ra=t(((e,t)=>{t.exports=TypeError})),za=t(((e,t)=>{t.exports=Object})),Ba=t(((e,t)=>{t.exports=Error})),Va=t(((e,t)=>{t.exports=EvalError})),Ha=t(((e,t)=>{t.exports=RangeError})),Ua=t(((e,t)=>{t.exports=ReferenceError})),Wa=t(((e,t)=>{t.exports=SyntaxError})),Ga=t(((e,t)=>{t.exports=URIError})),Ka=t(((e,t)=>{t.exports=Math.abs})),qa=t(((e,t)=>{t.exports=Math.floor})),Ja=t(((e,t)=>{t.exports=Math.max})),Ya=t(((e,t)=>{t.exports=Math.min})),Xa=t(((e,t)=>{t.exports=Math.pow})),Za=t(((e,t)=>{t.exports=Math.round})),Qa=t(((e,t)=>{t.exports=Number.isNaN||function(e){return e!==e}})),$a=t(((e,t)=>{var n=Qa();t.exports=function(e){return n(e)||e===0?e:e<0?-1:1}})),eo=t(((e,t)=>{t.exports=Object.getOwnPropertyDescriptor})),to=t(((e,t)=>{var n=eo();if(n)try{n([],`length`)}catch{n=null}t.exports=n})),no=t(((e,t)=>{var n=Object.defineProperty||!1;if(n)try{n({},`a`,{value:1})}catch{n=!1}t.exports=n})),ro=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}})),io=t(((e,t)=>{var n=typeof Symbol<`u`&&Symbol,r=ro();t.exports=function(){return typeof n!=`function`||typeof Symbol!=`function`||typeof n(`foo`)!=`symbol`||typeof Symbol(`bar`)!=`symbol`?!1:r()}})),ao=t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect.getPrototypeOf||null})),oo=t(((e,t)=>{t.exports=za().getPrototypeOf||null})),so=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}})),co=t(((e,t)=>{var n=so();t.exports=Function.prototype.bind||n})),lo=t(((e,t)=>{t.exports=Function.prototype.call})),uo=t(((e,t)=>{t.exports=Function.prototype.apply})),fo=t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect&&Reflect.apply})),po=t(((e,t)=>{var n=co(),r=uo(),i=lo();t.exports=fo()||n.call(i,r)})),mo=t(((e,t)=>{var n=co(),r=Ra(),i=lo(),a=po();t.exports=function(e){if(e.length<1||typeof e[0]!=`function`)throw new r(`a function is required`);return a(n,i,e)}})),ho=t(((e,t)=>{var n=mo(),r=to(),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})),go=t(((e,t)=>{var n=ao(),r=oo(),i=ho();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})),_o=t(((e,t)=>{var n=Function.prototype.call,r=Object.prototype.hasOwnProperty;t.exports=co().call(n,r)})),vo=t(((e,t)=>{var n,r=za(),i=Ba(),a=Va(),o=Ha(),s=Ua(),c=Wa(),l=Ra(),u=Ga(),d=Ka(),f=qa(),p=Ja(),m=Ya(),h=Xa(),g=Za(),_=$a(),v=Function,y=function(e){try{return v(`"use strict"; return (`+e+`).constructor;`)()}catch{}},b=to(),x=no(),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=io()(),T=go(),E=oo(),D=ao(),O=uo(),k=lo(),ee={},A=typeof Uint8Array>`u`||!T?n:T(Uint8Array),j={__proto__:null,"%AggregateError%":typeof AggregateError>`u`?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>`u`?n:ArrayBuffer,"%ArrayIteratorPrototype%":w&&T?T([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":ee,"%AsyncGenerator%":ee,"%AsyncGeneratorFunction%":ee,"%AsyncIteratorPrototype%":ee,"%Atomics%":typeof Atomics>`u`?n:Atomics,"%BigInt%":typeof BigInt>`u`?n:BigInt,"%BigInt64Array%":typeof BigInt64Array>`u`?n:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>`u`?n:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>`u`?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":i,"%eval%":eval,"%EvalError%":a,"%Float16Array%":typeof Float16Array>`u`?n:Float16Array,"%Float32Array%":typeof Float32Array>`u`?n:Float32Array,"%Float64Array%":typeof Float64Array>`u`?n:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>`u`?n:FinalizationRegistry,"%Function%":v,"%GeneratorFunction%":ee,"%Int8Array%":typeof Int8Array>`u`?n:Int8Array,"%Int16Array%":typeof Int16Array>`u`?n:Int16Array,"%Int32Array%":typeof Int32Array>`u`?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":w&&T?T(T([][Symbol.iterator]())):n,"%JSON%":typeof JSON==`object`?JSON:n,"%Map%":typeof Map>`u`?n:Map,"%MapIteratorPrototype%":typeof Map>`u`||!w||!T?n:T(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":r,"%Object.getOwnPropertyDescriptor%":b,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>`u`?n:Promise,"%Proxy%":typeof Proxy>`u`?n:Proxy,"%RangeError%":o,"%ReferenceError%":s,"%Reflect%":typeof Reflect>`u`?n:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>`u`?n:Set,"%SetIteratorPrototype%":typeof Set>`u`||!w||!T?n:T(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>`u`?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":w&&T?T(``[Symbol.iterator]()):n,"%Symbol%":w?Symbol:n,"%SyntaxError%":c,"%ThrowTypeError%":C,"%TypedArray%":A,"%TypeError%":l,"%Uint8Array%":typeof Uint8Array>`u`?n:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>`u`?n:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>`u`?n:Uint16Array,"%Uint32Array%":typeof Uint32Array>`u`?n:Uint32Array,"%URIError%":u,"%WeakMap%":typeof WeakMap>`u`?n:WeakMap,"%WeakRef%":typeof WeakRef>`u`?n:WeakRef,"%WeakSet%":typeof WeakSet>`u`?n:WeakSet,"%Function.prototype.call%":k,"%Function.prototype.apply%":O,"%Object.defineProperty%":x,"%Object.getPrototypeOf%":E,"%Math.abs%":d,"%Math.floor%":f,"%Math.max%":p,"%Math.min%":m,"%Math.pow%":h,"%Math.round%":g,"%Math.sign%":_,"%Reflect.getPrototypeOf%":D};if(T)try{null.error}catch(e){j[`%Error.prototype%`]=T(T(e))}var te=function e(t){var n;if(t===`%AsyncFunction%`)n=y(`async function () {}`);else if(t===`%GeneratorFunction%`)n=y(`function* () {}`);else if(t===`%AsyncGeneratorFunction%`)n=y(`async function* () {}`);else if(t===`%AsyncGenerator%`){var r=e(`%AsyncGeneratorFunction%`);r&&(n=r.prototype)}else if(t===`%AsyncIteratorPrototype%`){var i=e(`%AsyncGenerator%`);i&&T&&(n=T(i.prototype))}return j[t]=n,n},ne={__proto__:null,"%ArrayBufferPrototype%":[`ArrayBuffer`,`prototype`],"%ArrayPrototype%":[`Array`,`prototype`],"%ArrayProto_entries%":[`Array`,`prototype`,`entries`],"%ArrayProto_forEach%":[`Array`,`prototype`,`forEach`],"%ArrayProto_keys%":[`Array`,`prototype`,`keys`],"%ArrayProto_values%":[`Array`,`prototype`,`values`],"%AsyncFunctionPrototype%":[`AsyncFunction`,`prototype`],"%AsyncGenerator%":[`AsyncGeneratorFunction`,`prototype`],"%AsyncGeneratorPrototype%":[`AsyncGeneratorFunction`,`prototype`,`prototype`],"%BooleanPrototype%":[`Boolean`,`prototype`],"%DataViewPrototype%":[`DataView`,`prototype`],"%DatePrototype%":[`Date`,`prototype`],"%ErrorPrototype%":[`Error`,`prototype`],"%EvalErrorPrototype%":[`EvalError`,`prototype`],"%Float32ArrayPrototype%":[`Float32Array`,`prototype`],"%Float64ArrayPrototype%":[`Float64Array`,`prototype`],"%FunctionPrototype%":[`Function`,`prototype`],"%Generator%":[`GeneratorFunction`,`prototype`],"%GeneratorPrototype%":[`GeneratorFunction`,`prototype`,`prototype`],"%Int8ArrayPrototype%":[`Int8Array`,`prototype`],"%Int16ArrayPrototype%":[`Int16Array`,`prototype`],"%Int32ArrayPrototype%":[`Int32Array`,`prototype`],"%JSONParse%":[`JSON`,`parse`],"%JSONStringify%":[`JSON`,`stringify`],"%MapPrototype%":[`Map`,`prototype`],"%NumberPrototype%":[`Number`,`prototype`],"%ObjectPrototype%":[`Object`,`prototype`],"%ObjProto_toString%":[`Object`,`prototype`,`toString`],"%ObjProto_valueOf%":[`Object`,`prototype`,`valueOf`],"%PromisePrototype%":[`Promise`,`prototype`],"%PromiseProto_then%":[`Promise`,`prototype`,`then`],"%Promise_all%":[`Promise`,`all`],"%Promise_reject%":[`Promise`,`reject`],"%Promise_resolve%":[`Promise`,`resolve`],"%RangeErrorPrototype%":[`RangeError`,`prototype`],"%ReferenceErrorPrototype%":[`ReferenceError`,`prototype`],"%RegExpPrototype%":[`RegExp`,`prototype`],"%SetPrototype%":[`Set`,`prototype`],"%SharedArrayBufferPrototype%":[`SharedArrayBuffer`,`prototype`],"%StringPrototype%":[`String`,`prototype`],"%SymbolPrototype%":[`Symbol`,`prototype`],"%SyntaxErrorPrototype%":[`SyntaxError`,`prototype`],"%TypedArrayPrototype%":[`TypedArray`,`prototype`],"%TypeErrorPrototype%":[`TypeError`,`prototype`],"%Uint8ArrayPrototype%":[`Uint8Array`,`prototype`],"%Uint8ClampedArrayPrototype%":[`Uint8ClampedArray`,`prototype`],"%Uint16ArrayPrototype%":[`Uint16Array`,`prototype`],"%Uint32ArrayPrototype%":[`Uint32Array`,`prototype`],"%URIErrorPrototype%":[`URIError`,`prototype`],"%WeakMapPrototype%":[`WeakMap`,`prototype`],"%WeakSetPrototype%":[`WeakSet`,`prototype`]},re=co(),ie=_o(),M=re.call(k,Array.prototype.concat),N=re.call(O,Array.prototype.splice),P=re.call(k,String.prototype.replace),ae=re.call(k,String.prototype.slice),F=re.call(k,RegExp.prototype.exec),oe=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,I=/\\(\\)?/g,L=function(e){var t=ae(e,0,1),n=ae(e,-1);if(t===`%`&&n!==`%`)throw new c("invalid intrinsic syntax, expected closing `%`");if(n===`%`&&t!==`%`)throw new c("invalid intrinsic syntax, expected opening `%`");var r=[];return P(e,oe,function(e,t,n,i){r[r.length]=n?P(i,I,`$1`):t||e}),r},se=function(e,t){var n=e,r;if(ie(ne,n)&&(r=ne[n],n=`%`+r[0]+`%`),ie(j,n)){var i=j[n];if(i===ee&&(i=te(n)),i===void 0&&!t)throw new l(`intrinsic `+e+` exists, but is not available. Please file an issue!`);return{alias:r,name:n,value:i}}throw new c(`intrinsic `+e+` does not exist!`)};t.exports=function(e,t){if(typeof e!=`string`||e.length===0)throw new l(`intrinsic name must be a non-empty string`);if(arguments.length>1&&typeof t!=`boolean`)throw new l(`"allowMissing" argument must be a boolean`);if(F(/^%?[^%]*%?$/,e)===null)throw new c("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=L(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],N(n,M([0,1],u)));for(var d=1,f=!0;d<n.length;d+=1){var p=n[d],m=ae(p,0,1),h=ae(p,-1);if((m===`"`||m===`'`||m==="`"||h===`"`||h===`'`||h==="`")&&m!==h)throw new c(`property names with quotes must have matching quotes`);if((p===`constructor`||!f)&&(s=!0),r+=`.`+p,a=`%`+r+`%`,ie(j,a))o=j[a];else if(o!=null){if(!(p in o)){if(!t)throw new l(`base intrinsic for `+e+` exists, but the property is not available.`);return}if(b&&d+1>=n.length){var g=b(o,p);f=!!g,o=f&&`get`in g&&!(`originalValue`in g.get)?g.get:o[p]}else f=ie(o,p),o=o[p];f&&!s&&(j[a]=o)}}return o}})),yo=t(((e,t)=>{var n=vo(),r=mo(),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}})),bo=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)}})),xo=t(((e,t)=>{var n=bo(),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)}})),So=t(((e,t)=>{t.exports=[`Float16Array`,`Float32Array`,`Float64Array`,`Int8Array`,`Int16Array`,`Int32Array`,`Uint8Array`,`Uint8ClampedArray`,`Uint16Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`]})),Co=t(((e,t)=>{var n=So(),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}})),wo=t(((e,t)=>{var n=no(),r=Wa(),i=Ra(),a=to();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.`)}})),To=t(((e,t)=>{var n=no(),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})),Eo=t(((e,t)=>{var n=vo(),r=wo(),i=To()(),a=to(),o=Ra(),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}})),Do=t(((e,t)=>{var n=co(),r=uo(),i=po();t.exports=function(){return i(n,r,arguments)}})),Oo=t(((e,t)=>{var n=Eo(),r=no(),i=mo(),a=Do();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})),ko=t(((e,t)=>{var n=ro();t.exports=function(){return n()&&!!Symbol.toStringTag}})),Ao=t(((e,t)=>{var n=xo(),r=Co(),i=Oo(),a=yo(),o=to(),s=go(),c=a(`Object.prototype.toString`),l=ko()(),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}})),jo=t(((e,t)=>{var n=Ao();t.exports=function(e){return!!n(e)}})),Mo=t(((e,t)=>{var n=Ra(),r=yo()(`TypedArray.prototype.buffer`,!0),i=jo();t.exports=r||function(e){if(!i(e))throw new n(`Not a Typed Array`);return e.buffer}})),No=t(((e,t)=>{var n=Ia().Buffer,r=La(),i=Mo(),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.`)}})),Po=t(((e,t)=>{var n=Ia().Buffer,r=No();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})),Fo=t(((e,t)=>{var n=Fa(),r=Po(),i=Ia().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})),Io=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})})),Lo=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}})),Ro=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)}})),zo=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}}})),Bo=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)}}}})),Vo=t(((e,t)=>{var n=Bo();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})),Ho=e(Pa(),1),Uo=e(Fo(),1),Wo=e(Io(),1),Go=e(Je(),1),Ko=e(Lo(),1),qo=e(Ro(),1),Jo=e(zo(),1),Yo=e(Vo(),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}},Xo=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}}};Xo.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 Zo=class e extends U{constructor(t){super(`The filepath "${t}" contains unsafe character sequences`),this.code=this.name=e.code,this.data={filepath:t}}};Zo.code=`UnsafeFilepathError`;var Qo=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 $o(e,t){return-(e<t)||+(e>t)}function es(e,t){return $o(e.path,t.path)}function ts(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 ns=2**32;function rs(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 is(e){let[t,n]=rs(e.ctimeSeconds,e.ctimeNanoseconds,e.ctimeMs,e.ctime),[r,i]=rs(e.mtimeSeconds,e.mtimeNanoseconds,e.mtimeMs,e.mtime);return{ctimeSeconds:t%ns,ctimeNanoseconds:n%ns,mtimeSeconds:r%ns,mtimeNanoseconds:i%ns,dev:e.dev%ns,ino:e.ino%ns,mode:ts(e.mode%ns),uid:e.uid%ns,gid:e.gid%ns,size:e.size>-1?e.size%ns:0}}function as(e){let t=``;for(let n of new Uint8Array(e))n<16&&(t+=`0`),t+=n.toString(16);return t}var os=null;async function ss(e){return os===null&&(os=await us()),os?ls(e):cs(e)}function cs(e){return new Uo.default().update(e).digest(`hex`)}async function ls(e){return as(await crypto.subtle.digest(`SHA-1`,e))}async function us(){try{return await ls(new Uint8Array([]))===`da39a3ee5e6b4b0d3255bfef95601890afd80709`}catch{}return!1}function ds(e){return{assumeValid:!!(e&32768),extended:!!(e&16384),stage:(e&12288)>>12,nameLength:e&4095}}function fs(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 ps=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 Qo(t),i=r.toString(`utf8`,4);if(i!==`DIRC`)throw new W(`Invalid dircache magic file number: ${i}`);let a=await ss(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=ds(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 Zo(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(es)}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=is(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(`
725
+ `,document.head.appendChild(e)}},zi=[{id:`chat`,label:`Chat`},{id:`terminal`,label:`Terminal`},{id:`files`,label:`Files`},{id:`memory`,label:`Memory`}],Bi=`slicc-hidden-tabs`,Vi=[`terminal`,`memory`];function Hi(){try{let e=localStorage.getItem(Bi);return e?new Set(JSON.parse(e)):new Set(Vi)}catch{return new Set(Vi)}}function Ui(e){let t=e.filter(e=>e!==`chat`);localStorage.setItem(Bi,JSON.stringify(t))}var Wi=zi.filter(e=>!Hi().has(e.id)),Gi=`chat`,Ki=new Set(zi.map(e=>e.id));function qi(e){return Ki.has(e)}var Ji=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}},Yi=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 Xi(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=Zi(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=Zi(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 Zi(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 Qi=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 Yi;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));Ui(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 Ri(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 Ji(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 Wi){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 Ti(n),terminal:new Ei(r,{onClearTerminal:()=>{this.panels.terminal.clearTerminal()}}),fileBrowser:new Pi(i,{onRunCommand:async e=>{await this.runFileBrowserCommand(e),this.extensionZone.activateTab(`terminal`)}}),memory:new Fi(a),scoops:new Li(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&&Xi(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 Ji(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 Ti(o),terminal:new Ei(this.terminalContainer,{onClearTerminal:()=>{this.panels.terminal.clearTerminal(),this.openTerminal()}}),fileBrowser:new Pi(u,{onRunCommand:async e=>{await this.runFileBrowserCommand(e),this.openTerminal()}}),memory:new Fi(d),scoops:new Li(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));Xi(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)}},$i=`slicc-theme`,ea=new Set([`dark`,`light`,`system`]);function ta(){let e=localStorage.getItem($i);return e&&ea.has(e)?e:`system`}function na(){let e=ta(),t=e===`light`;e===`system`&&(t=window.matchMedia?.(`(prefers-color-scheme: light)`).matches??!1),document.documentElement.classList.toggle(`theme-light`,t)}var ra;function ia(){na(),ra=window.matchMedia?.(`(prefers-color-scheme: light)`),ra?.addEventListener?.(`change`,()=>{ta()===`system`&&na()})}var aa=300,oa=6,sa=null,ca=null;function la(){return sa||(sa=document.createElement(`div`),sa.className=`s2-tooltip`,document.body.appendChild(sa)),sa}function ua(e){let t=e.getAttribute(`data-tooltip`);if(!t)return;let n=la();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-oa,s=r.left+r.width/2-i.width/2):a===`right`?(o=r.top+r.height/2-i.height/2,s=r.right+oa):(o=r.bottom+oa,s=r.left+r.width/2-i.width/2),a===`bottom`&&o+i.height>window.innerHeight-4?o=r.top-i.height-oa:a===`top`&&o<4&&(o=r.bottom+oa),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 da(){ca&&=(clearTimeout(ca),null),sa?.classList.remove(`s2-tooltip--visible`)}function fa(){document.addEventListener(`pointerenter`,e=>{let t=e.target.closest?.(`[data-tooltip]`);t&&(da(),ca=setTimeout(()=>ua(t),aa))},!0),document.addEventListener(`pointerleave`,e=>{e.target.closest?.(`[data-tooltip]`)&&da()},!0),document.addEventListener(`pointerdown`,da,!0)}function pa(e){return e.toLowerCase().endsWith(ie)}function ma(e){return Array.from(e).find(e=>pa(e.name))??null}function ha(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 ga(e){if(!e)return null;if(e.files){let t=ma(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&&pa(e.name))return e}return null}var _a=new Map,va=new Map;function ya(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 ba(e,t){let n=ya(e);_a.set(n,t),setTimeout(()=>_a.delete(n),1e4)}function xa(e,t){va.set(e,t),setTimeout(()=>va.delete(e),1e4)}function Sa(e){let t=va.get(e);return t?(va.delete(e),t):null}function Ca(e){let t=ya(e),n=_a.get(t);return n?(_a.delete(t),n):null}var wa=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=Ca(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=await this.vfs.stat(t);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)}}async lstat(e){let t=R(e),n=await this.vfs.lstat(t);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)}}async mkdir(e,t){await this.vfs.mkdir(R(e),t)}async readdir(e){let t=R(e);return t===`/usr`?[`bin`]:t===`/usr/bin`?this.getVirtualBinCommands().slice().sort():(await this.vfs.readDir(t)).map(e=>e.name)}async readdirWithFileTypes(e){let t=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=await this.vfs.readDir(t),r=[];for(let e of n)if(e.type===`symlink`){let n=!1,i=!1;try{let r=t===`/`?`/${e.name}`:`${t}/${e.name}`,a=await this.vfs.stat(r);n=a.type===`file`,i=a.type===`directory`}catch{}r.push({name:e.name,isFile:n,isDirectory:i,isSymbolicLink:!0})}else r.push({name:e.name,isFile:e.type===`file`,isDirectory:e.type===`directory`,isSymbolicLink:!1});return r}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){}},Ta=new TextDecoder;function Ea(e){return typeof e==`string`?e:Ta.decode(e)}function Da(e){return JSON.parse(Ea(e))}function Oa(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 ka=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(``)}})),Aa=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}})),ja=t((e=>{var t=ka(),n=Aa(),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`)}})),Ma=ja();globalThis.Buffer===void 0&&(globalThis.Buffer=Ma.Buffer);var Na=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})),Pa=t(((e,t)=>{t.exports=Na()})),Fa=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}}})),Ia=t(((e,t)=>{var n=ja(),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)}})),La=t(((e,t)=>{var n={}.toString;t.exports=Array.isArray||function(e){return n.call(e)==`[object Array]`}})),Ra=t(((e,t)=>{t.exports=TypeError})),za=t(((e,t)=>{t.exports=Object})),Ba=t(((e,t)=>{t.exports=Error})),Va=t(((e,t)=>{t.exports=EvalError})),Ha=t(((e,t)=>{t.exports=RangeError})),Ua=t(((e,t)=>{t.exports=ReferenceError})),Wa=t(((e,t)=>{t.exports=SyntaxError})),Ga=t(((e,t)=>{t.exports=URIError})),Ka=t(((e,t)=>{t.exports=Math.abs})),qa=t(((e,t)=>{t.exports=Math.floor})),Ja=t(((e,t)=>{t.exports=Math.max})),Ya=t(((e,t)=>{t.exports=Math.min})),Xa=t(((e,t)=>{t.exports=Math.pow})),Za=t(((e,t)=>{t.exports=Math.round})),Qa=t(((e,t)=>{t.exports=Number.isNaN||function(e){return e!==e}})),$a=t(((e,t)=>{var n=Qa();t.exports=function(e){return n(e)||e===0?e:e<0?-1:1}})),eo=t(((e,t)=>{t.exports=Object.getOwnPropertyDescriptor})),to=t(((e,t)=>{var n=eo();if(n)try{n([],`length`)}catch{n=null}t.exports=n})),no=t(((e,t)=>{var n=Object.defineProperty||!1;if(n)try{n({},`a`,{value:1})}catch{n=!1}t.exports=n})),ro=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}})),io=t(((e,t)=>{var n=typeof Symbol<`u`&&Symbol,r=ro();t.exports=function(){return typeof n!=`function`||typeof Symbol!=`function`||typeof n(`foo`)!=`symbol`||typeof Symbol(`bar`)!=`symbol`?!1:r()}})),ao=t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect.getPrototypeOf||null})),oo=t(((e,t)=>{t.exports=za().getPrototypeOf||null})),so=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}})),co=t(((e,t)=>{var n=so();t.exports=Function.prototype.bind||n})),lo=t(((e,t)=>{t.exports=Function.prototype.call})),uo=t(((e,t)=>{t.exports=Function.prototype.apply})),fo=t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect&&Reflect.apply})),po=t(((e,t)=>{var n=co(),r=uo(),i=lo();t.exports=fo()||n.call(i,r)})),mo=t(((e,t)=>{var n=co(),r=Ra(),i=lo(),a=po();t.exports=function(e){if(e.length<1||typeof e[0]!=`function`)throw new r(`a function is required`);return a(n,i,e)}})),ho=t(((e,t)=>{var n=mo(),r=to(),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})),go=t(((e,t)=>{var n=ao(),r=oo(),i=ho();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})),_o=t(((e,t)=>{var n=Function.prototype.call,r=Object.prototype.hasOwnProperty;t.exports=co().call(n,r)})),vo=t(((e,t)=>{var n,r=za(),i=Ba(),a=Va(),o=Ha(),s=Ua(),c=Wa(),l=Ra(),u=Ga(),d=Ka(),f=qa(),p=Ja(),m=Ya(),h=Xa(),g=Za(),_=$a(),v=Function,y=function(e){try{return v(`"use strict"; return (`+e+`).constructor;`)()}catch{}},b=to(),x=no(),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=io()(),T=go(),E=oo(),D=ao(),O=uo(),k=lo(),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=co(),re=_o(),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}})),yo=t(((e,t)=>{var n=vo(),r=mo(),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}})),bo=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)}})),xo=t(((e,t)=>{var n=bo(),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)}})),So=t(((e,t)=>{t.exports=[`Float16Array`,`Float32Array`,`Float64Array`,`Int8Array`,`Int16Array`,`Int32Array`,`Uint8Array`,`Uint8ClampedArray`,`Uint16Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`]})),Co=t(((e,t)=>{var n=So(),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}})),wo=t(((e,t)=>{var n=no(),r=Wa(),i=Ra(),a=to();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.`)}})),To=t(((e,t)=>{var n=no(),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})),Eo=t(((e,t)=>{var n=vo(),r=wo(),i=To()(),a=to(),o=Ra(),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}})),Do=t(((e,t)=>{var n=co(),r=uo(),i=po();t.exports=function(){return i(n,r,arguments)}})),Oo=t(((e,t)=>{var n=Eo(),r=no(),i=mo(),a=Do();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})),ko=t(((e,t)=>{var n=ro();t.exports=function(){return n()&&!!Symbol.toStringTag}})),Ao=t(((e,t)=>{var n=xo(),r=Co(),i=Oo(),a=yo(),o=to(),s=go(),c=a(`Object.prototype.toString`),l=ko()(),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}})),jo=t(((e,t)=>{var n=Ao();t.exports=function(e){return!!n(e)}})),Mo=t(((e,t)=>{var n=Ra(),r=yo()(`TypedArray.prototype.buffer`,!0),i=jo();t.exports=r||function(e){if(!i(e))throw new n(`Not a Typed Array`);return e.buffer}})),No=t(((e,t)=>{var n=Ia().Buffer,r=La(),i=Mo(),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.`)}})),Po=t(((e,t)=>{var n=Ia().Buffer,r=No();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})),Fo=t(((e,t)=>{var n=Fa(),r=Po(),i=Ia().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})),Io=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})})),Lo=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}})),Ro=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)}})),zo=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}}})),Bo=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)}}}})),Vo=t(((e,t)=>{var n=Bo();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})),Ho=e(Pa(),1),Uo=e(Fo(),1),Wo=e(Io(),1),Go=e(Je(),1),Ko=e(Lo(),1),qo=e(Ro(),1),Jo=e(zo(),1),Yo=e(Vo(),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}},Xo=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}}};Xo.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 Zo=class e extends U{constructor(t){super(`The filepath "${t}" contains unsafe character sequences`),this.code=this.name=e.code,this.data={filepath:t}}};Zo.code=`UnsafeFilepathError`;var Qo=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 $o(e,t){return-(e<t)||+(e>t)}function es(e,t){return $o(e.path,t.path)}function ts(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 ns=2**32;function rs(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 is(e){let[t,n]=rs(e.ctimeSeconds,e.ctimeNanoseconds,e.ctimeMs,e.ctime),[r,i]=rs(e.mtimeSeconds,e.mtimeNanoseconds,e.mtimeMs,e.mtime);return{ctimeSeconds:t%ns,ctimeNanoseconds:n%ns,mtimeSeconds:r%ns,mtimeNanoseconds:i%ns,dev:e.dev%ns,ino:e.ino%ns,mode:ts(e.mode%ns),uid:e.uid%ns,gid:e.gid%ns,size:e.size>-1?e.size%ns:0}}function as(e){let t=``;for(let n of new Uint8Array(e))n<16&&(t+=`0`),t+=n.toString(16);return t}var os=null;async function ss(e){return os===null&&(os=await us()),os?ls(e):cs(e)}function cs(e){return new Uo.default().update(e).digest(`hex`)}async function ls(e){return as(await crypto.subtle.digest(`SHA-1`,e))}async function us(){try{return await ls(new Uint8Array([]))===`da39a3ee5e6b4b0d3255bfef95601890afd80709`}catch{}return!1}function ds(e){return{assumeValid:!!(e&32768),extended:!!(e&16384),stage:(e&12288)>>12,nameLength:e&4095}}function fs(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 ps=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 Qo(t),i=r.toString(`utf8`,4);if(i!==`DIRC`)throw new W(`Invalid dircache magic file number: ${i}`);let a=await ss(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=ds(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 Zo(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(es)}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=is(t);let i=Buffer.from(e),a={ctimeSeconds:t.ctimeSeconds,ctimeNanoseconds:t.ctimeNanoseconds,mtimeSeconds:t.mtimeSeconds,mtimeNanoseconds:t.mtimeNanoseconds,dev:t.dev,ino:t.ino,mode:t.mode||33188,uid:t.uid,gid:t.gid,size:t.size,path:e,oid:n,flags:{assumeValid:!1,extended:!1,stage:r,nameLength:i.length<4095?i.length:4095},stages:[]};this._addEntry(a),this._dirty=!0}delete({filepath:e}){if(this._entries.has(e))this._entries.delete(e);else for(let t of this._entries.keys())t.startsWith(e+`/`)&&this._entries.delete(t);this._unmergedPaths.has(e)&&this._unmergedPaths.delete(e),this._dirty=!0}clear(){this._entries.clear(),this._dirty=!0}has({filepath:e}){return this._entries.has(e)}render(){return this.entries.map(e=>`${e.mode.toString(8)} ${e.oid} ${e.path}`).join(`
726
726
  `)}static async _entryToBuffer(e){let t=Buffer.from(e.path),n=Math.ceil((62+t.length+1)/8)*8,r=Buffer.alloc(n),i=new Qo(r),a=is(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(fs(e)),i.write(e.path,t.length,`utf8`),r}async toObject(){let t=Buffer.alloc(12),n=new Qo(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 ss(a);return Buffer.concat([a,Buffer.from(o,`hex`)])}};function ms(e,t,n=!0,r=!0){let i=is(e),a=is(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 hs=null,gs=Symbol(`IndexCache`);function _s(){return{map:new Map,stats:new Map}}async function vs(e,t,n){let[r,i]=await Promise.all([e.lstat(t),e.read(t)]),a=await ps.from(i);n.map.set(t,a),n.stats.set(t,r)}async function ys(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:ms(r,i)}var bs=class{static async acquire({fs:e,gitdir:t,cache:n,allowUnmerged:r=!0},i){n[gs]||(n[gs]=_s());let a=`${t}/index`;hs===null&&(hs=new Ho.default({maxPending:1/0}));let o,s=[];return await hs.acquire(a,async()=>{let t=n[gs];await ys(e,a,t)&&await vs(e,a,t);let c=t.map.get(a);if(s=c.unmergedPaths,s.length&&!r)throw new Xo(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 xs(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t>-1&&(e=e.slice(t+1)),e}function Ss(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t===-1?`.`:t===0?`/`:e.slice(0,t)}function Cs(e){let t=new Map,n=function(e){if(!t.has(e)){let r={type:`tree`,fullpath:e,basename:xs(e),metadata:{},children:[]};t.set(e,r),r.parent=n(Ss(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:xs(e),metadata:r,parent:n(Ss(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 ws(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 Ts=class{constructor({fs:e,gitdir:t,cache:n}){this.treePromise=bs.acquire({fs:e,gitdir:t,cache:n},async function(e){return Cs(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($o),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`?{}:is(t.metadata);e._type=t.type===`tree`?`tree`:ws(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}},Es=Symbol(`GitWalkSymbol`);function Ds(){let e=Object.create(null);return Object.defineProperty(e,Es,{value:function({fs:e,gitdir:t,cache:n}){return new Ts({fs:e,gitdir:t,cache:n})}}),Object.freeze(e),e}var Os=class e extends U{constructor(t){super(`Could not find ${t}.`),this.code=this.name=e.code,this.data={what:t}}};Os.code=`NotFoundError`;var ks=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}}};ks.code=`ObjectTypeError`;var As=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}}};As.code=`InvalidOidError`;var js=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:
727
727
  [remote "${t}"]
728
728
  \tfetch = +refs/heads/*:refs/remotes/origin/*
@@ -776,7 +776,7 @@ gpgsig`+xl(o)+`
776
776
  `)+`
777
777
  `;await Yu.acquire(r,async function(){await e.write(r,t,{encoding:`utf8`})})}else await Yu.acquire(r,async function(){await e.rm(r)})}};async function Zu({fs:e,gitdir:t,oid:n}){let r=`objects/${n.slice(0,2)}/${n.slice(2)}`;return e.exists(`${t}/${r}`)}async function Qu({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 Fc({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 $u({fs:e,cache:t,gitdir:n,oid:r,format:i=`content`}){let a=r=>Rc({fs:e,cache:t,gitdir:n,oid:r}),o=await Zu({fs:e,gitdir:n,oid:r});return o||=await Qu({fs:e,cache:t,gitdir:n,oid:r,getExternalRefDelta:a}),o}function ed(e){return e.slice(0,12).toString(`hex`)===`5041434b0000000200000000`}function td(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 nd={name:`isomorphic-git`,version:`1.37.5`,agent:`git/isomorphic-git@1.37.5`},rd=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 id(e){let t=e.indexOf(`\r`),n=e.indexOf(`
778
778
  `);return t===-1&&n===-1?-1:t===-1?n+1:n===-1?t+1:n===t+1?n+1:Math.min(t,n)+1}function ad(e){let t=new rd,n=``;return(async()=>{await Fu(e,e=>{for(e=e.toString(`utf8`),n+=e;;){let e=id(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 od=class{static demux(e){let t=zu.streamReader(e),n=new rd,r=new rd,i=new rd,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 sd(e){let{packetlines:t,packfile:n,progress:r}=od.demux(e),i=[],a=[],o=[],s=!1,c=!1;return new Promise((l,u)=>{Fu(t,t=>{let d=t.toString(`utf8`).trim();if(d.startsWith(`shallow`)){let e=d.slice(-41).trim();e.length!==40&&u(new As(e)),i.push(e)}else if(d.startsWith(`unshallow`)){let e=d.slice(-41).trim();e.length!==40&&u(new As(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 cd({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(zu.encode(`want ${e}${c}\n`)),c=``;for(let e of r)s.push(zu.encode(`shallow ${e}\n`));i!==null&&s.push(zu.encode(`deepen ${i}\n`)),a!==null&&s.push(zu.encode(`deepen-since ${Math.floor(a.valueOf()/1e3)}\n`));for(let e of o)s.push(zu.encode(`deepen-not ${e}\n`));s.push(zu.flush());for(let e of n)s.push(zu.encode(`have ${e}\n`));return s.push(zu.encode(`done
779
- `)),s}async function ld({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 Mu({fs:e,gitdir:c,test:!0}),w=await nc.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 tl(`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=qu.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 al(`shallow`,`depth`);if(h!==null&&!k.capabilities.has(`deepen-since`))throw new al(`deepen-since`,`since`);if(g.length>0&&!k.capabilities.has(`deepen-not`))throw new al(`deepen-not`,`exclude`);if(_===!0&&!k.capabilities.has(`deepen-relative`))throw new al(`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=td([...k.capabilities],[`multi_ack_detailed`,`no-done`,`side-band-64k`,`ofs-delta`,`agent=${nd.agent}`]);_&&ne.push(`deepen-relative`);let re=y?[j]:A.values(),ie=y?[C]:await K.listRefs({fs:e,gitdir:c,filepath:`refs`}),M=[];for(let n of ie)try{n=await K.expand({fs:e,gitdir:c,ref:n});let r=await K.resolve({fs:e,gitdir:c,ref:n});await $u({fs:e,cache:t,gitdir:c,oid:r})&&M.push(r)}catch{}M=[...new Set(M)];let N=await Xu.read({fs:e,gitdir:c}),P=k.capabilities.has(`shallow`)?[...N]:[],ae=cd({capabilities:ne,wants:re,haves:M,shallows:P,depth:m,since:h,exclude:g}),F=Buffer.from(await Iu(ae)),oe=await O.connect({http:n,onProgress:r,corsProxy:p,service:`git-upload-pack`,url:E,auth:ee,body:[F],headers:b}),I=await sd(oe.body);oe.headers&&(I.headers=oe.headers);for(let n of I.shallows)if(!N.has(n))try{let{object:r}=await Rc({fs:e,cache:t,gitdir:c,oid:n}),i=new Cl(r),a=await Promise.all(i.headers().parent.map(n=>$u({fs:e,cache:t,gitdir:c,oid:n})));a.length===0||a.every(e=>e)||N.add(n)}catch{N.add(n)}for(let e of I.unshallows)N.delete(e);if(await Xu.write({fs:e,gitdir:c,oids:N}),y){let t=new Map([[te,j]]),n=new Map,r=10,i=te;for(;r--;){let e=k.symrefs.get(i);if(e===void 0)break;n.set(i,e),i=e}let a=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&&(I.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&&(I.pruned=t)}if(I.HEAD=k.symrefs.get(`HEAD`),I.HEAD===void 0){let{oid:e}=K.resolveAgainstMap({ref:`HEAD`,map:A});for(let[t,n]of A.entries())if(t!==`HEAD`&&n===e){I.HEAD=t;break}}I.FETCH_HEAD={oid:j,description:`${te.startsWith(`refs/tags`)?`tag`:`branch`} '${ju(te)}' of ${E}`},(r||i)&&Fu(ad(I.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 L=Buffer.from(await Iu(I.packfile));if(oe.body.error)throw oe.body.error;let se=L.slice(-20).toString(`hex`),ce={defaultBranch:I.HEAD,fetchHead:I.FETCH_HEAD.oid,fetchHeadDescription:I.FETCH_HEAD.description};if(I.headers&&(ce.headers=I.headers),x&&(ce.pruned=I.pruned),se!==``&&!ed(L)){ce.packfile=`objects/pack/pack-${se}.pack`;let n=G(c,ce.packfile);await e.write(n,L);let i=await Mc.fromPack({pack:L,getExternalRefDelta:n=>Rc({fs:e,cache:t,gitdir:c,oid:n}),onProgress:r});await e.write(n.replace(/\.pack$/,`.idx`),await i.toBuffer())}return ce}async function ud({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]
779
+ `)),s}async function ld({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 Mu({fs:e,gitdir:c,test:!0}),w=await nc.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 tl(`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=qu.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 al(`shallow`,`depth`);if(h!==null&&!k.capabilities.has(`deepen-since`))throw new al(`deepen-since`,`since`);if(g.length>0&&!k.capabilities.has(`deepen-not`))throw new al(`deepen-not`,`exclude`);if(_===!0&&!k.capabilities.has(`deepen-relative`))throw new al(`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=td([...k.capabilities],[`multi_ack_detailed`,`no-done`,`side-band-64k`,`ofs-delta`,`agent=${nd.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 $u({fs:e,cache:t,gitdir:c,oid:r})&&N.push(r)}catch{}N=[...new Set(N)];let P=await Xu.read({fs:e,gitdir:c}),F=k.capabilities.has(`shallow`)?[...P]:[],ie=cd({capabilities:ne,wants:M,haves:N,shallows:F,depth:m,since:h,exclude:g}),I=Buffer.from(await Iu(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 sd(ae.body);ae.headers&&(L.headers=ae.headers);for(let n of L.shallows)if(!P.has(n))try{let{object:r}=await Rc({fs:e,cache:t,gitdir:c,oid:n}),i=new Cl(r),a=await Promise.all(i.headers().parent.map(n=>$u({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 Xu.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`} '${ju(te)}' of ${E}`},(r||i)&&Fu(ad(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 Iu(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!==``&&!ed(oe)){ce.packfile=`objects/pack/pack-${se}.pack`;let n=G(c,ce.packfile);await e.write(n,oe);let i=await Mc.fromPack({pack:oe,getExternalRefDelta:n=>Rc({fs:e,cache:t,gitdir:c,oid:n}),onProgress:r});await e.write(n.replace(/\.pack$/,`.idx`),await i.toBuffer())}return ce}async function ud({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]
780
780
  repositoryformatversion = 0
781
781
  filemode = false
782
782
  \tbare = ${t}\n`+(t?``:` logallrefupdates = true
@@ -784,11 +784,11 @@ gpgsig`+xl(o)+`
784
784
  ignorecase = true
785
785
  `),await e.write(r+`/HEAD`,`ref: refs/heads/${i}\n`)}async function dd({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 ud({fs:e,gitdir:u}),await pu({fs:e,gitdir:u,remote:m,url:d,force:!1}),f){let t=await nc.get({fs:e,gitdir:u});await t.set(`http.corsProxy`,f),await nc.save({fs:e,gitdir:u,config:t})}let{defaultBranch:T,fetchHead:E}=await ld({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 bu({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 fd({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 dd({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 pd({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 au({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 md({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 Mu({fs:t,gitdir:await Y({fsp:t,dotgit:n}),fullname:r,test:i})}catch(e){throw e.caller=`git.currentBranch`,e}}async function hd({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 Os(n);let r=await K.expand({fs:e,gitdir:t,ref:n});if(r===await Mu({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=ju(n),a=await nc.get({fs:e,gitdir:t});await a.deleteSection(`branch`,i),await nc.save({fs:e,gitdir:t,config:a})}async function gd({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 hd({fs:t,gitdir:await Y({fsp:t,dotgit:n}),ref:r})}catch(e){throw e.caller=`git.deleteBranch`,e}}async function _d({fs:e,gitdir:t,remote:n}){let r=await nc.get({fs:e,gitdir:t});await r.deleteSection(`remote`,n),await nc.save({fs:e,gitdir:t,config:r})}async function vd({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 _d({fs:t,gitdir:await Y({fsp:t,dotgit:n}),remote:r})}catch(e){throw e.caller=`git.deleteRemote`,e}}async function yd({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 bd({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 yd({fs:t,gitdir:await Y({fsp:t,dotgit:n}),ref:r})}catch(e){throw e.caller=`git.deleteTag`,e}}async function xd({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 Sd({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 Fc({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 Cd({fs:e,cache:t,gitdir:n,oid:r}){let i=r=>Rc({fs:e,cache:t,gitdir:n,oid:r}),a=await xd({fs:e,gitdir:n,oid:r}),o=await Sd({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 Bc(`oids`,r,a):new Os(`an object matching "${r}"`)}async function wd({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 Cd({fs:t,cache:i,gitdir:await Y({fsp:t,dotgit:n}),oid:r})}catch(e){throw e.caller=`git.expandOid`,e}}async function Td({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 Rc({fs:e,cache:t,gitdir:n,oid:r}),{parent:c}=Cl.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 Ed({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 Mu({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 Td({fs:e,cache:t,gitdir:r,oids:[v,y]});if(b.length!==1)if(b.length===0&&_)b.push(`4b825dc642cb6eb9a060e54bf8d69288fbee4904`);else throw new Qc;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 Kc;let o=await bs.acquire({fs:e,gitdir:r,cache:t,allowUnmerged:!1},async o=>Ou({fs:e,cache:t,dir:n,gitdir:r,index:o,ourOid:v,theirOid:y,baseOid:x,ourName:ju(i),baseName:`base`,theirName:ju(a),dryRun:c,abortOnConflict:u,mergeDriver:g}));if(o instanceof $c)throw o;return d||=`Merge branch '${ju(a)}' into ${ju(i)}`,{oid:await au({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 Dd({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 Mu({fs:e,gitdir:l});if(!t)throw new tl(`ref`);u=t}let{fetchHead:w,fetchHeadDescription:T}=await ld({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 Ed({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 bu({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 Od({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 ld({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 kd({fs:e,filepath:t}){if(await e.exists(G(t,`.git`)))return t;{let n=Ss(t);if(n===t)throw new Os(`git root for ${t}`);return kd({fs:e,filepath:n})}}async function Ad({fs:e,filepath:t}){try{return J(`fs`,e),J(`filepath`,t),await kd({fs:new q(e),filepath:t})}catch(e){throw e.caller=`git.findRoot`,e}}async function jd({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 $l({fs:t,gitdir:await Y({fsp:t,dotgit:n}),path:r})}catch(e){throw e.caller=`git.getConfig`,e}}async function Md({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 ud({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 Nd({fs:e,cache:t,gitdir:n,oid:r,ancestor:i,depth:a}){let o=await Xu.read({fs:e,gitdir:n});if(!r)throw new tl(`oid`);if(!i)throw new tl(`ancestor`);if(r===i)return!1;let s=[r],c=new Set,l=0;for(;s.length;){if(l++===a)throw new Zc(a);let r=s.shift(),{type:u,object:d}=await Rc({fs:e,cache:t,gitdir:n,oid:r});if(u!==`commit`)throw new ks(r,u,`commit`);let f=Cl.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 Pd({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 Fd({fs:e,gitdir:t,ref:n,cache:r}){if(n){let i=await K.resolve({gitdir:t,fs:e,ref:n}),a=[];return await Id({fs:e,cache:r,gitdir:t,oid:i,filenames:a,prefix:``}),a}else return bs.acquire({fs:e,gitdir:t,cache:r},async function(e){return e.entries.map(e=>e.path)})}async function Id({fs:e,cache:t,gitdir:n,oid:r,filenames:i,prefix:a}){let{tree:o}=await lu({fs:e,cache:t,gitdir:n,oid:r});for(let r of o)r.type===`tree`?await Id({fs:e,cache:t,gitdir:n,oid:r.oid,filenames:i,prefix:G(a,r.path)}):i.push(G(a,r.path))}async function Ld({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 Fd({fs:t,cache:i,gitdir:await Y({fsp:t,dotgit:n}),ref:r})}catch(e){throw e.caller=`git.listFiles`,e}}async function Rd({fs:e,gitdir:t}){let n=await nc.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 zd({fs:e,dir:t,gitdir:n=G(t,`.git`)}){try{J(`fs`,e),J(`gitdir`,n);let t=new q(e);return await Rd({fs:t,gitdir:await Y({fsp:t,dotgit:n})})}catch(e){throw e.caller=`git.listRemotes`,e}}async function Bd({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 Vd(e,t){return e.committer.timestamp-t.committer.timestamp}var Hd=`e69de29bb2d1d6434b8b29ae775ad8c2e48c5391`;async function Ud({fs:e,cache:t,gitdir:n,oid:r,fileId:i}){if(i===Hd)return;let a=r,o,s=await wl({fs:e,cache:t,gitdir:n,oid:r}),c=s.tree;return i===s.oid?o=s.path:(o=await Wd({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 Wd({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=Rc({fs:e,cache:t,gitdir:n,oid:r.oid}).then(function({object:c}){return Wd({fs:e,cache:t,gitdir:n,tree:pc.from(c),fileId:i,oid:a,filepaths:o,parentPath:G(s,r.path)})})),c});return await Promise.all(c),o}async function Gd({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 Xu.read({fs:e,gitdir:n}),f=[await iu({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 su({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 Os){let o=c&&p;if(o&&(o=await Ud({fs:e,cache:t,gitdir:n,oid:i.commit.tree,fileId:p}),o))if(Array.isArray(o)){if(m){let i=await Ud({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 iu({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)=>Vd(e.commit,t.commit))}return u}async function Kd({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 Gd({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 qd({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 tu({fs:v,gitdir:y,author:f});if(!b&&(!s||!o))throw new el(`author`);let x=await nu({fs:v,gitdir:y,author:b,committer:p});if(!x&&(!s||!o))throw new el(`committer`);return await Ed({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 Jd={commit:16,tree:32,blob:48,tag:64,ofs_delta:96,ref_delta:112};async function Yd({fs:e,cache:t,dir:n,gitdir:r=G(n,`.git`),oids:i}){let a=new Uo.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=Jd[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(Ru(2,o),`hex`),r>>>=7;s(Buffer.from(await Kl(t)))}s(`PACK`),s(`00000002`,`hex`),s(Ru(8,i.length),`hex`);for(let n of i){let{type:i,object:a}=await Rc({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 Xd({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 tu({fs:w,gitdir:T,author:b});if(!E)throw new el(`author`);let D=await nu({fs:w,gitdir:T,author:E,committer:x});if(!D)throw new el(`committer`);return await Dd({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 Zd({fs:e,cache:t,dir:n,gitdir:r=G(n,`.git`),start:i,finish:a}){let o=await Xu.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 Rc({fs:e,cache:t,gitdir:r,oid:n});if(i===`tag`){let e=bl.from(a).headers().object;return u(e)}if(i!==`commit`)throw new ks(n,i,`commit`);if(!o.has(n))for(n of Cl.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 Qd({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 Rc({fs:e,cache:t,gitdir:r,oid:n});if(i===`tag`){let e=bl.from(s).headers().object;await o(e)}else if(i===`commit`){let e=Cl.from(s).headers().tree;await o(e)}else if(i===`tree`){let e=pc.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 $d(e){let t={},n=``,r=zu.streamReader(e),i=await r();for(;i!==!0;)i!==null&&(n+=i.toString(`utf8`)+`
786
786
  `),i=await r();let a=n.toString(`utf8`).split(`
787
- `);if(i=a.shift(),!i.startsWith(`unpack `))throw new rl(`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 ef({capabilities:e=[],triplets:t=[]}){let n=[],r=`\x00 ${e.join(` `)}`;for(let e of t)n.push(zu.encode(`${e.oldoid} ${e.oid} ${e.fullRef}${r}\n`)),r=``;return n.push(zu.flush()),n}async function tf({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 Mu({fs:e,gitdir:l});if(v===void 0)throw new tl(`ref`);let y=await nc.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 tl(`remote OR url`);let x=d||await y.get(`branch.${v}.merge`);if(b===void 0)throw new tl(`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=qu.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 Os)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 ll;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 Td({fs:e,cache:t,gitdir:l,oids:[C,O]});for(let e of i)n.push(e);k&&(r=await Qd({fs:e,cache:t,gitdir:l,oids:i}))}if(n.includes(C)||(ee=await Qd({fs:e,cache:t,gitdir:l,oids:await Zd({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 Qd({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 il(`tag-exists`);if(C!==`0000000000000000000000000000000000000000`&&O!==`0000000000000000000000000000000000000000`&&!await Nd({fs:e,cache:t,gitdir:l,oid:C,ancestor:O,depth:-1}))throw new il(`not-fast-forward`)}}let A=await ef({capabilities:td([...T.capabilities],[`report-status`,`side-band-64k`,`agent=${nd.agent}`]),triplets:[{oldoid:O,oid:C,fullRef:D}]}),j=h?[]:await Yd({fs:e,cache:t,gitdir:l,oids:[...ee]}),te=await w.connect({http:n,onProgress:r,corsProxy:g,service:`git-receive-pack`,url:b,auth:E,headers:_,body:[...A,...j]}),{packfile:ne,progress:re}=await od.demux(te.body);i&&Fu(ad(re),async e=>{await i(e)});let ie=await $d(ne);if(te.headers&&(ie.headers=te.headers),f&&ie.ok&&ie.refs[D].ok&&!S.startsWith(`refs/tags`)){let t=`refs/remotes/${f}/${D.replace(`refs/heads`,``)}`;h?await K.deleteRef({fs:e,gitdir:l,ref:t}):await K.writeRef({fs:e,gitdir:l,ref:t,value:C})}if(ie.ok&&Object.values(ie.refs).every(e=>e.ok))return ie;throw new qc(Object.entries(ie.refs).filter(([e,t])=>!t.ok).map(([e,t])=>`\n - ${e}: ${t.error}`).join(``),ie)}async function nf({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 tf({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 rf({fs:e,cache:t,gitdir:n,oid:r}){let{type:i,object:a}=await Rc({fs:e,cache:t,gitdir:n,oid:r});if(i===`tag`)return r=bl.from(a).parse().object,rf({fs:e,cache:t,gitdir:n,oid:r});if(i!==`blob`)throw new ks(r,i,`blob`);return{oid:r,blob:new Uint8Array(a)}}async function af({fs:e,cache:t,gitdir:n,oid:r,filepath:i=void 0}){return i!==void 0&&(r=await su({fs:e,cache:t,gitdir:n,oid:r,filepath:i})),await rf({fs:e,cache:t,gitdir:n,oid:r})}async function of({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 af({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 sf({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 iu({fs:t,cache:i,gitdir:await Y({fsp:t,dotgit:n}),oid:r})}catch(e){throw e.caller=`git.readCommit`,e}}async function cf({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 lu({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 lf({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 bs.acquire({fs:t,gitdir:a,cache:i},async function(e){e.delete({filepath:r})})}catch(e){throw e.caller=`git.remove`,e}}async function uf({gitdir:e,type:t,object:n}){return ss(mc.wrap({type:t,object:n}))}async function df({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 su({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 uf({gitdir:s,type:`blob`,object:d}),c===l&&(u=await o.lstat(G(t,r)))),await bs.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 ff({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 pf({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 nc.get({fs:t,gitdir:o});a?await s.append(r,i):await s.set(r,i),await nc.save({fs:t,gitdir:o,config:s})}catch(e){throw e.caller=`git.setConfig`,e}}async function mf({fs:e,gitdir:t,commit:n}){return await Yl({fs:e,gitdir:t,type:`commit`,object:Cl.from(n).toObject(),format:`content`})}async function hf({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 Nl({fs:c,cache:o,dir:t,gitdir:await Y({fsp:c,dotgit:n}),trees:[El({ref:r}),Ol(),Ds()],map:async function(e,[n,r,o]){if(!n&&!o&&r&&!s&&await Ul.isIgnored({fs:c,dir:t,filepath:e})||!i.some(t=>yu(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 gf({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 tl(`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 zc(`tag`,r);await K.writeRef({fs:t,gitdir:o,ref:r,value:s})}catch(e){throw e.caller=`git.tag`,e}}function _f(){try{return nd.version}catch(e){throw e.caller=`git.version`,e}}async function vf({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 Nl({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 yf({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 Yl({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 bf({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 mf({fs:t,gitdir:await Y({fsp:t,dotgit:n}),commit:r})}catch(e){throw e.caller=`git.writeCommit`,e}}async function xf({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(!fu(r,!0))throw new Xc(r,Jo.default.clean(r));let s=await Y({fsp:t,dotgit:n});if(!a&&await K.exists({fs:t,gitdir:s,ref:r}))throw new zc(`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 Sf({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 uu({fs:t,gitdir:await Y({fsp:t,dotgit:n}),tree:r})}catch(e){throw e.caller=`git.writeTree`,e}}function Cf(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function wf(){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(Cf())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 Tf=wf();function Ef(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 Df(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 Of(e){let{oldContent:t,newContent:n,oldName:r,newName:i,color:a=!0}=e;if(t===n)return``;let o=t.split(`
787
+ `);if(i=a.shift(),!i.startsWith(`unpack `))throw new rl(`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 ef({capabilities:e=[],triplets:t=[]}){let n=[],r=`\x00 ${e.join(` `)}`;for(let e of t)n.push(zu.encode(`${e.oldoid} ${e.oid} ${e.fullRef}${r}\n`)),r=``;return n.push(zu.flush()),n}async function tf({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 Mu({fs:e,gitdir:l});if(v===void 0)throw new tl(`ref`);let y=await nc.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 tl(`remote OR url`);let x=d||await y.get(`branch.${v}.merge`);if(b===void 0)throw new tl(`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=qu.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 Os)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 ll;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 Td({fs:e,cache:t,gitdir:l,oids:[C,O]});for(let e of i)n.push(e);k&&(r=await Qd({fs:e,cache:t,gitdir:l,oids:i}))}if(n.includes(C)||(ee=await Qd({fs:e,cache:t,gitdir:l,oids:await Zd({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 Qd({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 il(`tag-exists`);if(C!==`0000000000000000000000000000000000000000`&&O!==`0000000000000000000000000000000000000000`&&!await Nd({fs:e,cache:t,gitdir:l,oid:C,ancestor:O,depth:-1}))throw new il(`not-fast-forward`)}}let A=await ef({capabilities:td([...T.capabilities],[`report-status`,`side-band-64k`,`agent=${nd.agent}`]),triplets:[{oldoid:O,oid:C,fullRef:D}]}),j=h?[]:await Yd({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 od.demux(te.body);i&&Fu(ad(M),async e=>{await i(e)});let re=await $d(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 qc(Object.entries(re.refs).filter(([e,t])=>!t.ok).map(([e,t])=>`\n - ${e}: ${t.error}`).join(``),re)}async function nf({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 tf({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 rf({fs:e,cache:t,gitdir:n,oid:r}){let{type:i,object:a}=await Rc({fs:e,cache:t,gitdir:n,oid:r});if(i===`tag`)return r=bl.from(a).parse().object,rf({fs:e,cache:t,gitdir:n,oid:r});if(i!==`blob`)throw new ks(r,i,`blob`);return{oid:r,blob:new Uint8Array(a)}}async function af({fs:e,cache:t,gitdir:n,oid:r,filepath:i=void 0}){return i!==void 0&&(r=await su({fs:e,cache:t,gitdir:n,oid:r,filepath:i})),await rf({fs:e,cache:t,gitdir:n,oid:r})}async function of({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 af({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 sf({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 iu({fs:t,cache:i,gitdir:await Y({fsp:t,dotgit:n}),oid:r})}catch(e){throw e.caller=`git.readCommit`,e}}async function cf({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 lu({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 lf({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 bs.acquire({fs:t,gitdir:a,cache:i},async function(e){e.delete({filepath:r})})}catch(e){throw e.caller=`git.remove`,e}}async function uf({gitdir:e,type:t,object:n}){return ss(mc.wrap({type:t,object:n}))}async function df({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 su({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 uf({gitdir:s,type:`blob`,object:d}),c===l&&(u=await o.lstat(G(t,r)))),await bs.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 ff({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 pf({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 nc.get({fs:t,gitdir:o});a?await s.append(r,i):await s.set(r,i),await nc.save({fs:t,gitdir:o,config:s})}catch(e){throw e.caller=`git.setConfig`,e}}async function mf({fs:e,gitdir:t,commit:n}){return await Yl({fs:e,gitdir:t,type:`commit`,object:Cl.from(n).toObject(),format:`content`})}async function hf({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 Nl({fs:c,cache:o,dir:t,gitdir:await Y({fsp:c,dotgit:n}),trees:[El({ref:r}),Ol(),Ds()],map:async function(e,[n,r,o]){if(!n&&!o&&r&&!s&&await Ul.isIgnored({fs:c,dir:t,filepath:e})||!i.some(t=>yu(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 gf({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 tl(`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 zc(`tag`,r);await K.writeRef({fs:t,gitdir:o,ref:r,value:s})}catch(e){throw e.caller=`git.tag`,e}}function _f(){try{return nd.version}catch(e){throw e.caller=`git.version`,e}}async function vf({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 Nl({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 yf({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 Yl({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 bf({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 mf({fs:t,gitdir:await Y({fsp:t,dotgit:n}),commit:r})}catch(e){throw e.caller=`git.writeCommit`,e}}async function xf({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(!fu(r,!0))throw new Xc(r,Jo.default.clean(r));let s=await Y({fsp:t,dotgit:n});if(!a&&await K.exists({fs:t,gitdir:s,ref:r}))throw new zc(`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 Sf({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 uu({fs:t,gitdir:await Y({fsp:t,dotgit:n}),tree:r})}catch(e){throw e.caller=`git.writeTree`,e}}function Cf(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function wf(){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(Cf())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 Tf=wf();function Ef(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 Df(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 Of(e){let{oldContent:t,newContent:n,oldName:r,newName:i,color:a=!0}=e;if(t===n)return``;let o=t.split(`
788
788
  `),s=n.split(`
789
789
  `);o.length>0&&o[o.length-1]===``&&o.pop(),s.length>0&&s[s.length-1]===``&&s.pop();let c=Df(Ef(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 kf(e,t){if(e===t)return{insertions:0,deletions:0};let n=e.split(`
790
790
  `),r=t.split(`
791
- `);n.length>0&&n[n.length-1]===``&&n.pop(),r.length>0&&r[r.length-1]===``&&r.pop();let i=Ef(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 Af=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=I.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 ${_f()})\n`,stderr:``,exitCode:0}}help(){return{stdout:`usage: git <command> [<args>]
791
+ `);n.length>0&&n[n.length-1]===``&&n.pop(),r.length>0&&r[r.length-1]===``&&r.pop();let i=Ef(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 Af=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 ${_f()})\n`,stderr:``,exitCode:0}}help(){return{stdout:`usage: git <command> [<args>]
792
792
 
793
793
  Available commands:
794
794
  init Initialize a new repository
@@ -880,7 +880,7 @@ Available commands:
880
880
  `,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 Zl({fs:this.lfs,dir:e,filepath:i}),await lf({fs:this.lfs,dir:e,filepath:r}),{stdout:``,stderr:``,exitCode:0}}async revParse(e,t){if(t.includes(`--show-toplevel`))try{return{stdout:`${await Ad({fs:this.lfs,filepath:e})}\n`,stderr:``,exitCode:0}}catch{return{stdout:``,stderr:`fatal: not a git repository
881
881
  `,exitCode:128}}if(t.includes(`--is-inside-work-tree`))try{return await Ad({fs:this.lfs,filepath:e}),{stdout:`true
882
882
  `,stderr:``,exitCode:0}}catch{return{stdout:`false
883
- `,stderr:``,exitCode:0}}let n=t.find(e=>!e.startsWith(`-`))??`HEAD`;try{return{stdout:`${await ff({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`),jf=null,Mf=null;function Nf(e){jf=e}function Pf(e){Mf=e}function Ff(e){let t=e.match(/^(f[0-9]+)(e[0-9]+)$/);return t?{framePrefix:t[1],isIframe:!0}:{framePrefix:``,isIframe:!1}}function If(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 Lf=[`playwright-cli`,`playwright`,`puppeteer`],Rf=new WeakMap,zf=new Set([`click`,`dblclick`,`fill`,`type`,`press`,`goto`,`navigate`,`select`,`check`,`uncheck`,`drag`,`dialog-accept`,`dialog-dismiss`]);function Bf(e){return e.toISOString().replace(/:/g,`-`)}function Vf(e,t){let n=Rf.get(e);n||(n=new WeakMap,Rf.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 Hf(e){return e instanceof L||typeof e==`object`&&e&&`code`in e?e.code===`EEXIST`:e instanceof Error&&e.message.includes(`EEXIST`)}var Uf=`function(text) {
883
+ `,stderr:``,exitCode:0}}let n=t.find(e=>!e.startsWith(`-`))??`HEAD`;try{return{stdout:`${await ff({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`),jf=null,Mf=null;function Nf(e){jf=e}function Pf(e){Mf=e}function Ff(e){let t=e.match(/^(f[0-9]+)(e[0-9]+)$/);return t?{framePrefix:t[1],isIframe:!0}:{framePrefix:``,isIframe:!1}}function If(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 Lf=[`playwright-cli`,`playwright`,`puppeteer`],Rf=new WeakMap,zf=new Set([`click`,`dblclick`,`fill`,`type`,`press`,`goto`,`navigate`,`select`,`check`,`uncheck`,`drag`,`dialog-accept`,`dialog-dismiss`]);function Bf(e){return e.toISOString().replace(/:/g,`-`)}function Vf(e,t){let n=Rf.get(e);n||(n=new WeakMap,Rf.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 Hf(e){return e instanceof oe||typeof e==`object`&&e&&`code`in e?e.code===`EEXIST`:e instanceof Error&&e.message.includes(`EEXIST`)}var Uf=`function(text) {
884
884
  const el = this;
885
885
  const tag = el.tagName;
886
886
  const proto = tag === 'TEXTAREA' ? window.HTMLTextAreaElement.prototype : window.HTMLInputElement.prototype;
@@ -1438,7 +1438,7 @@ For example, try 'man commands'.
1438
1438
  `,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:lh(await e.text())+`
1439
1439
  `,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 dh(){return{stdout:`usage: unzip <archive.zip> [-d <destination>]
1440
1440
  `,stderr:``,exitCode:0}}function fh(){return z(`unzip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return dh();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
1441
- `,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=M(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(!bm(a,i))return{stdout:``,stderr:`unzip: blocked suspicious path ${e}\n`,exitCode:1};let o=_m(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 ph(){return{stdout:`usage: webhook <command> [options]
1441
+ `,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(!bm(a,i))return{stdout:``,stderr:`unzip: blocked suspicious path ${e}\n`,exitCode:1};let o=_m(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 ph(){return{stdout:`usage: webhook <command> [options]
1442
1442
 
1443
1443
  Commands:
1444
1444
  create --scoop <name> [--name <name>] [--filter <code>] Create a new webhook endpoint
@@ -1518,29 +1518,36 @@ Options:
1518
1518
  `,stderr:``,exitCode:0};let e=``;for(let[,t]of Ch)e+=`ID: ${t.id}\n`,e+=` Name: ${t.name}\n`,e+=` Path: ${t.basePath}\n`,e+=` Pattern: ${t.pattern}\n`,t.scoop&&(e+=` Scoop: ${t.scoop}\n`),e+=` Created: ${t.createdAt}\n\n`;return{stdout:e,stderr:``,exitCode:0}}if(t===`delete`){let t=e[1];if(!t)return{stdout:``,stderr:`fswatch: delete requires an ID
1519
1519
  `,exitCode:1};let n=Ch.get(t);return n?(n.unsubscribe(),Ch.delete(t),{stdout:`Deleted watcher "${n.name}" (${t})\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`fswatch: watcher not found: ${t}\n`,exitCode:1}}if(t===`create`){let t=``,n=``,r=``,i=``;for(let a=1;a<e.length;a++)e[a]===`--path`&&e[a+1]?t=e[++a]:e[a]===`--pattern`&&e[a+1]?n=e[++a]:e[a]===`--scoop`&&e[a+1]?r=e[++a]:e[a]===`--name`&&e[a+1]&&(i=e[++a]);if(!t||!n)return{stdout:``,stderr:`fswatch: --path and --pattern are required
1520
1520
  `,exitCode:1};let a=RegExp(`^`+n.replace(/\./g,`\\.`).replace(/\*/g,`.*`)+`$`),o=e=>{let t=e.split(`/`).pop()??``;return a.test(t)},s=globalThis.__slicc_fs_watcher;if(!s)return{stdout:``,stderr:`fswatch: file system watcher not available
1521
- `,exitCode:1};let c=`fsw-${++wh}`;i||=`${n} in ${t}`;let l=globalThis.__slicc_lick_handler,u=s.watch(t,o,e=>{l&&l({type:`fswatch`,fswatchId:c,fswatchName:i,targetScoop:r,timestamp:new Date().toISOString(),changes:e.map(e=>({type:e.type,path:e.path})),body:{changes:e.map(e=>({type:e.type,path:e.path}))}})});Ch.set(c,{id:c,name:i,basePath:t,pattern:n,scoop:r,unsubscribe:u,createdAt:new Date().toISOString()});let d=`Created file watcher "${i}"\n`;return d+=`ID: ${c}\n`,d+=`Path: ${t}\n`,d+=`Pattern: ${n}\n`,r&&(d+=`Scoop: ${r}\n`),{stdout:d,stderr:``,exitCode:0}}return{stdout:``,stderr:`fswatch: unknown command: ${t}\n`,exitCode:1}})}function Eh(){return{stdout:`usage: sprinkle <subcommand> [args]
1521
+ `,exitCode:1};let c=`fsw-${++wh}`;i||=`${n} in ${t}`;let l=globalThis.__slicc_lick_handler,u=s.watch(t,o,e=>{l&&l({type:`fswatch`,fswatchId:c,fswatchName:i,targetScoop:r,timestamp:new Date().toISOString(),changes:e.map(e=>({type:e.type,path:e.path})),body:{changes:e.map(e=>({type:e.type,path:e.path}))}})});Ch.set(c,{id:c,name:i,basePath:t,pattern:n,scoop:r,unsubscribe:u,createdAt:new Date().toISOString()});let d=`Created file watcher "${i}"\n`;return d+=`ID: ${c}\n`,d+=`Path: ${t}\n`,d+=`Pattern: ${n}\n`,r&&(d+=`Scoop: ${r}\n`),{stdout:d,stderr:``,exitCode:0}}return{stdout:``,stderr:`fswatch: unknown command: ${t}\n`,exitCode:1}})}var Eh=class{listeners=new Map;lickHandler;fs;closeHandler;stopConeHandler;constructor(e,t,n,r){this.fs=e,this.lickHandler=t,this.closeHandler=n,this.stopConeHandler=r}createAPI(e){let t={name:e,lick:t=>{let n=typeof t==`string`?t:t.action,r=typeof t==`string`?void 0:t.data,i={type:`sprinkle`,sprinkleName:e,targetScoop:Ah(e),timestamp:new Date().toISOString(),body:{action:n,data:r}};this.lickHandler(i)},on:(t,n)=>{let r=`${e}:${t}`,i=this.listeners.get(r);i||(i=new Set,this.listeners.set(r,i)),i.add(n)},off:(t,n)=>{let r=`${e}:${t}`;this.listeners.get(r)?.delete(n)},readFile:async e=>await this.fs.readFile(e,{encoding:`utf-8`}),writeFile:async(e,t)=>{await this.fs.writeFile(e,t)},readDir:async e=>(await this.fs.readDir(e)).map(e=>({name:e.name,type:e.type})),exists:async e=>this.fs.exists(e),stat:async e=>{let t=await this.fs.stat(e);return{type:t.type,size:t.size}},mkdir:async e=>{await this.fs.mkdir(e,{recursive:!0})},rm:async e=>{await this.fs.rm(e)},screenshot:async e=>{let n=t._container;if(!n)return``;let r=e?n.querySelector(e):n;if(!r)throw Error(`Element not found: `+(e||`container`));let i=r.getBoundingClientRect(),a=Math.ceil(i.width),o=Math.ceil(i.height);if(a===0||o===0)throw Error(`Element has zero dimensions`);let s=document.createElement(`canvas`),c=window.devicePixelRatio||1;s.width=a*c,s.height=o*c;let l=s.getContext(`2d`);l.scale(c,c);let u=r.cloneNode(!0),d=`<svg xmlns="http://www.w3.org/2000/svg" width="${a}" height="${o}"><foreignObject width="100%" height="100%">${new XMLSerializer().serializeToString(u)}</foreignObject></svg>`;return new Promise((e,t)=>{let n=new Image;n.onload=()=>{l.drawImage(n,0,0),e(s.toDataURL(`image/png`))},n.onerror=()=>t(Error(`Screenshot rendering failed`)),n.src=`data:image/svg+xml;charset=utf-8,`+encodeURIComponent(d)})},setState:t=>{try{localStorage.setItem(`slicc-sprinkle-state:${e}`,JSON.stringify(t))}catch{}},getState:()=>{try{let t=localStorage.getItem(`slicc-sprinkle-state:${e}`);return t?JSON.parse(t):null}catch{return null}},open:e=>{let t=/^https?:|^chrome-extension:/.test(e)?e:wm(e);window.open(t,`_blank`)},close:()=>this.closeHandler(e),stopCone:()=>this.stopConeHandler()};return t}pushUpdate(e,t){let n=`${e}:update`,r=this.listeners.get(n);if(r)for(let e of r){let n=r;setTimeout(()=>{if(n.has(e))try{e(t)}catch{}},0)}}removeSprinkle(e){for(let t of this.listeners.keys())t.startsWith(`${e}:`)&&this.listeners.delete(t)}},Dh=`slicc-sprinkle-routes`;function Oh(){try{let e=localStorage.getItem(Dh);return e?JSON.parse(e):{}}catch{return{}}}function kh(e){try{localStorage.setItem(Dh,JSON.stringify(e))}catch{}}function Ah(e){return Oh()[e]}function jh(e,t){let n=Oh();n[e]=t,kh(n)}function Mh(e){let t=Oh();delete t[e],kh(t)}function Nh(){return Oh()}function Ph(){return{stdout:`usage: sprinkle <subcommand> [args]
1522
1522
 
1523
1523
  list List available .shtml sprinkles
1524
1524
  open <name> Open a sprinkle by name
1525
1525
  close <name> Close an open sprinkle
1526
1526
  refresh Re-scan VFS for .shtml files
1527
1527
  send <name> <json> Push data to a sprinkle
1528
+ route <name> --scoop <scoop> Route lick events to a scoop instead of cone
1529
+ route <name> --clear Clear routing (revert to cone)
1530
+ route List all sprinkle routes
1528
1531
  chat <html> Show inline HTML in chat (Tool UI)
1529
1532
  Use data-action="name" on buttons for callbacks
1530
1533
  Pipe HTML: echo "<div>...</div>" | sprinkle chat
1531
- `,stderr:``,exitCode:0}}function Dh(){return typeof window>`u`?null:window.__slicc_sprinkleManager??null}function Oh(){return z(`sprinkle`,async(e,t)=>{if(e.length===0||e[0]===`--help`||e[0]===`-h`)return Eh();let n=e[0];if(n===`chat`){let n=e.slice(1).join(` `);if(!n&&t.stdin&&(n=t.stdin),!n)return{stdout:``,stderr:`sprinkle chat: HTML content required
1534
+ `,stderr:``,exitCode:0}}function Fh(){return typeof window>`u`?null:window.__slicc_sprinkleManager??null}function Ih(){return z(`sprinkle`,async(e,t)=>{if(e.length===0||e[0]===`--help`||e[0]===`-h`)return Ph();let n=e[0];if(n===`chat`){let n=e.slice(1).join(` `);if(!n&&t.stdin&&(n=t.stdin),!n)return{stdout:``,stderr:`sprinkle chat: HTML content required
1532
1535
  `,exitCode:1};let r=await g({html:n,onAction:async(e,t)=>({action:e,data:t})});return r===null?{stdout:``,stderr:`sprinkle chat: not in tool execution context
1533
1536
  `,exitCode:1}:{stdout:JSON.stringify(r)+`
1534
- `,stderr:``,exitCode:0}}let r=Dh();if(!r)return{stdout:``,stderr:`sprinkle: sprinkle manager not initialized
1537
+ `,stderr:``,exitCode:0}}let r=Fh();if(!r)return{stdout:``,stderr:`sprinkle: sprinkle manager not initialized
1535
1538
  `,exitCode:1};switch(n){case`list`:{await r.refresh();let e=r.available();if(e.length===0)return{stdout:`No .shtml sprinkles found.
1536
1539
  `,stderr:``,exitCode:0};let t=new Set(r.opened());return{stdout:e.map(e=>{let n=t.has(e.name)?` [open]`:``;return` ${e.name}${n} ${e.title} (${e.path})`}).join(`
1537
1540
  `)+`
1538
1541
  `,stderr:``,exitCode:0}}case`open`:{let t=e[1];if(!t)return{stdout:``,stderr:`sprinkle open: name required
1539
1542
  `,exitCode:1};try{return await r.open(t),{stdout:`Sprinkle "${t}" opened.\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`sprinkle open: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}case`close`:{let t=e[1];return t?(r.close(t),{stdout:`Sprinkle "${t}" closed.\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`sprinkle close: name required
1540
- `,exitCode:1}}case`refresh`:{await r.refresh();let e=r.available().length;return{stdout:`Found ${e} sprinkle${e===1?``:`s`}.\n`,stderr:``,exitCode:0}}case`send`:{let t=e[1];if(!t)return{stdout:``,stderr:`sprinkle send: name required
1543
+ `,exitCode:1}}case`refresh`:{await r.refresh();let e=r.available().length;return{stdout:`Found ${e} sprinkle${e===1?``:`s`}.\n`,stderr:``,exitCode:0}}case`route`:{let t=e[1];if(!t){let e=Nh(),t=Object.entries(e);return t.length===0?{stdout:`No sprinkle routes configured (all licks go to cone).
1544
+ `,stderr:``,exitCode:0}:{stdout:`Sprinkle routes:
1545
+ `+t.map(([e,t])=>` ${e} -> ${t}`).join(`
1546
+ `)+`
1547
+ `,stderr:``,exitCode:0}}if(e.includes(`--clear`))return Mh(t),{stdout:`Route cleared for sprinkle "${t}" (licks will go to cone).\n`,stderr:``,exitCode:0};let n=e.indexOf(`--scoop`),r=n===-1?void 0:e[n+1];if(!r){let e=Ah(t);return e?{stdout:`${t} -> ${e}\n`,stderr:``,exitCode:0}:{stdout:`${t} -> cone (default)\n`,stderr:``,exitCode:0}}return jh(t,r),{stdout:`Sprinkle "${t}" lick events will route to scoop "${r}".\n`,stderr:``,exitCode:0}}case`send`:{let t=e[1];if(!t)return{stdout:``,stderr:`sprinkle send: name required
1541
1548
  `,exitCode:1};let n=e.slice(2).join(` `);if(!n)return{stdout:``,stderr:`sprinkle send: JSON data required
1542
1549
  `,exitCode:1};let i;try{i=JSON.parse(n)}catch{return{stdout:``,stderr:`sprinkle send: invalid JSON
1543
- `,exitCode:1}}return r.sendToSprinkle(t,i),{stdout:`Data sent to sprinkle "${t}".\n`,stderr:``,exitCode:0}}default:return{stdout:``,stderr:`sprinkle: unknown subcommand "${n}"\n`,exitCode:1}}})}function kh(){return`oauth-token — get an OAuth access token for a provider
1550
+ `,exitCode:1}}return r.sendToSprinkle(t,i),{stdout:`Data sent to sprinkle "${t}".\n`,stderr:``,exitCode:0}}default:return{stdout:``,stderr:`sprinkle: unknown subcommand "${n}"\n`,exitCode:1}}})}function Lh(){return`oauth-token — get an OAuth access token for a provider
1544
1551
 
1545
1552
  Usage:
1546
1553
  oauth-token <providerId> Get token for a specific provider
@@ -1556,13 +1563,13 @@ on success.
1556
1563
  Examples:
1557
1564
  oauth-token adobe
1558
1565
  curl -H "Authorization: Bearer $(oauth-token adobe)" https://api.corp.com/data
1559
- `}function Ah(){return z(`oauth-token`,async e=>{let{getOAuthAccountInfo:t,getSelectedProvider:n,getAccounts:r}=await v(async()=>{let{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}=await import(`./provider-settings-DtthfIx_.js`);return{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}},__vite__mapDeps([8,9,1,4,10,11,12,13,14,15])),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await v(async()=>{let{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}=await import(`./providers-CBTIfSNw.js`);return{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}},__vite__mapDeps([16,9,1,4,10,11,12,13,14,15]));if(e.includes(`--help`)||e.includes(`-h`))return{stdout:kh(),stderr:``,exitCode:0};if(e.includes(`--list`))return jh(r,a,i,t);let o,s=e.indexOf(`--provider`);if(s>=0){if(o=e[s+1],!o)return{stdout:``,stderr:`oauth-token: --provider requires a value
1566
+ `}function Rh(){return z(`oauth-token`,async e=>{let{getOAuthAccountInfo:t,getSelectedProvider:n,getAccounts:r}=await v(async()=>{let{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}=await import(`./provider-settings-DtthfIx_.js`);return{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}},__vite__mapDeps([8,9,1,4,10,11,12,13,14,15])),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await v(async()=>{let{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}=await import(`./providers-CBTIfSNw.js`);return{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}},__vite__mapDeps([16,9,1,4,10,11,12,13,14,15]));if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Lh(),stderr:``,exitCode:0};if(e.includes(`--list`))return zh(r,a,i,t);let o,s=e.indexOf(`--provider`);if(s>=0){if(o=e[s+1],!o)return{stdout:``,stderr:`oauth-token: --provider requires a value
1560
1567
  `,exitCode:1}}else if(e.length>0)o=e[0];else{let e=n(),t=i(e);if(t?.isOAuth&&t.onOAuthLogin)o=e;else if(o=a().find(e=>{let t=i(e);return t?.isOAuth&&t.onOAuthLogin}),!o)return{stdout:``,stderr:`oauth-token: no OAuth providers configured
1561
1568
  `,exitCode:1}}let c=i(o);if(!c)return{stdout:``,stderr:`oauth-token: unknown provider "${o}"\n`,exitCode:1};if(!c.isOAuth||!c.onOAuthLogin)return{stdout:``,stderr:`oauth-token: provider "${o}" is not an OAuth provider\n`,exitCode:1};let l=t(o);if(l&&!l.expired)return{stdout:`${l.token}\n`,stderr:``,exitCode:0};try{let{createOAuthLauncher:e}=await v(async()=>{let{createOAuthLauncher:e}=await import(`./oauth-service-t9Y4KdOX.js`);return{createOAuthLauncher:e}},[]),n=e();await c.onOAuthLogin(n,()=>{});let r=t(o);return r&&r.token?{stdout:`${r.token}\n`,stderr:``,exitCode:0}:(console.error(`[oauth-token] Provider ${o}: login completed but no token was saved`),{stdout:``,stderr:`oauth-token: login completed but no token was saved
1562
- `,exitCode:1})}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${o}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}function jh(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
1569
+ `,exitCode:1})}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${o}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}function zh(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
1563
1570
  `,stderr:``,exitCode:0};let a=[];for(let e of i){let t=r(e);if(!t)a.push(`${e} (no token)`);else if(t.expired){let n=t.userName?` as ${t.userName}`:``;a.push(`${e} (expired${n})`)}else{let n=[];if(t.userName?n.push(`logged in as ${t.userName}`):n.push(`logged in`),t.expiresAt){let e=t.expiresAt-Date.now();if(e>0){let t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4);t>0?n.push(`expires in ${t}h`):n.push(`expires in ${r}m`)}}a.push(`${e} (${n.join(`, `)})`)}}return{stdout:a.join(`
1564
1571
  `)+`
1565
- `,stderr:``,exitCode:0}}function Mh(){return`secret — manage secrets for the fetch proxy
1572
+ `,stderr:``,exitCode:0}}function Bh(){return`secret — manage secrets for the fetch proxy
1566
1573
 
1567
1574
  Usage:
1568
1575
  secret set <name> --domain <patterns> Show instructions for adding a secret
@@ -1579,19 +1586,19 @@ Examples:
1579
1586
  secret list
1580
1587
  secret delete GITHUB_TOKEN
1581
1588
  secret test GITHUB_TOKEN https://api.github.com/repos
1582
- `}async function Nh(e,t,n){if(typeof chrome<`u`&&chrome?.runtime?.id)throw Error(`Secrets CLI is only available in CLI mode`);let r={method:e,headers:{"Content-Type":`application/json`}};n&&(r.body=JSON.stringify(n));let i=await fetch(`/api/secrets${t}`,r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}function Ph(e){let t=e.indexOf(`--domain`);return t===-1||!e[t+1]?null:e[t+1].split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}function Fh(){return z(`secret`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:Mh(),stderr:``,exitCode:0};let t=e[0];try{switch(t){case`set`:{let t=e[1];if(!t||t.startsWith(`-`))return{stdout:``,stderr:`secret: set requires a <name>
1583
- `,exitCode:1};let n=Ph(e),r=n&&n.length>0?n.join(`,`):`<domain1,domain2>`,i=`To add the secret "${t}", use one of the following methods:\n\n`;return i+=` macOS Keychain (swift-server):
1589
+ `}async function Vh(e,t,n){if(typeof chrome<`u`&&chrome?.runtime?.id)throw Error(`Secrets CLI is only available in CLI mode`);let r={method:e,headers:{"Content-Type":`application/json`}};n&&(r.body=JSON.stringify(n));let i=await fetch(`/api/secrets${t}`,r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}function Hh(e){let t=e.indexOf(`--domain`);return t===-1||!e[t+1]?null:e[t+1].split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}function Uh(){return z(`secret`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:Bh(),stderr:``,exitCode:0};let t=e[0];try{switch(t){case`set`:{let t=e[1];if(!t||t.startsWith(`-`))return{stdout:``,stderr:`secret: set requires a <name>
1590
+ `,exitCode:1};let n=Hh(e),r=n&&n.length>0?n.join(`,`):`<domain1,domain2>`,i=`To add the secret "${t}", use one of the following methods:\n\n`;return i+=` macOS Keychain (swift-server):
1584
1591
  `,i+=` security add-generic-password -s ai.sliccy.slicc -a ${t} -w '<value>' -U -C note -j '${r}'\n\n`,i+=` Environment file (node-server):
1585
1592
  `,i+=` Add to ~/.slicc/secrets.env:
1586
1593
  `,i+=` ${t}=<value>\n`,i+=` ${t}_DOMAINS=${r}\n\n`,i+=`Then restart the server to pick up changes.
1587
- `,{stdout:i,stderr:``,exitCode:0}}case`list`:{let{ok:e,data:t}=await Nh(`GET`,``);if(!e)return{stdout:``,stderr:`secret: failed to list secrets: ${t.error??`unknown error`}\n`,exitCode:1};let n=t;if(n.length===0)return{stdout:`No secrets stored
1594
+ `,{stdout:i,stderr:``,exitCode:0}}case`list`:{let{ok:e,data:t}=await Vh(`GET`,``);if(!e)return{stdout:``,stderr:`secret: failed to list secrets: ${t.error??`unknown error`}\n`,exitCode:1};let n=t;if(n.length===0)return{stdout:`No secrets stored
1588
1595
  `,stderr:``,exitCode:0};let r=Math.max(4,...n.map(e=>e.name.length)),i=`${`NAME`.padEnd(r)} DOMAINS\n`;for(let e of n)i+=`${e.name.padEnd(r)} ${e.domains.join(`, `)}\n`;return{stdout:i,stderr:``,exitCode:0}}case`delete`:{let t=e[1];if(!t)return{stdout:``,stderr:`secret: delete requires a <name>
1589
1596
  `,exitCode:1};let n=`To delete the secret "${t}", use one of the following methods:\n\n`;return n+=` macOS Keychain (swift-server):
1590
1597
  `,n+=` security delete-generic-password -s ai.sliccy.slicc -a ${t}\n\n`,n+=` Environment file (node-server):
1591
1598
  `,n+=` Remove the ${t}= and ${t}_DOMAINS= lines from ~/.slicc/secrets.env\n\n`,n+=`Then restart the server to pick up changes.
1592
1599
  `,{stdout:n,stderr:``,exitCode:0}}case`test`:{let t=e[1],n=e[2];if(!t||!n)return{stdout:``,stderr:`secret: test requires <name> <url>
1593
- `,exitCode:1};let r;try{r=new URL(n).hostname}catch{return{stdout:``,stderr:`secret: invalid URL "${n}"\n`,exitCode:1}}let{ok:i,data:a}=await Nh(`GET`,``);if(!i)return{stdout:``,stderr:`secret: failed to fetch secrets
1594
- `,exitCode:1};let o=a.find(e=>e.name===t);if(!o)return{stdout:``,stderr:`secret: no secret named "${t}"\n`,exitCode:1};let{isAllowedDomain:s}=await v(async()=>{let{isAllowedDomain:e}=await import(`./secret-masking-CfbASE5x.js`);return{isAllowedDomain:e}},[]);return s(o.domains,r)?{stdout:`✓ ${t} is allowed for ${r}\n`,stderr:``,exitCode:0}:{stdout:`✗ ${t} is NOT allowed for ${r}\n Allowed domains: ${o.domains.join(`, `)}\n`,stderr:``,exitCode:1}}default:return{stdout:``,stderr:`secret: unknown command "${t}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`secret: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function Ih(e,t,n={}){let r=new Map;for(let e of t)r.set(e.path,e);let i=new Set,a=[],o=[],s=[];for(let t of e){i.add(t.path);let e=r.get(t.path);e?e.size===t.size&&e.mtimeMs===t.mtimeMs?s.push(t.path):o.push(t.path):a.push(t.path)}let c=[];if(n.delete)for(let e of t)i.has(e.path)||c.push(e.path);return{toAdd:a,toUpdate:o,toDelete:c,toSkip:s}}var Lh=null;function Rh(e){Lh=e}function zh(){return Lh?.()??null}function Bh(e){let t={dryRun:!1,delete:!1,verbose:!1},n=[];for(let r of e)if(r===`--dry-run`||r===`-n`)t.dryRun=!0;else if(r===`--delete`)t.delete=!0;else if(r===`--verbose`||r===`-v`)t.verbose=!0;else if(r===`--help`||r===`-h`)return{error:`__help__`};else if(r.startsWith(`-`))return{error:`Unknown flag: ${r}`};else n.push(r);if(n.length!==2)return{error:`Expected exactly 2 arguments: <source> <dest>`};let[r,i]=n,a=Vh(r),o=Vh(i);return a&&o?{error:`Cannot sync between two remote paths — one side must be local`}:!a&&!o?{error:`One argument must be a remote path (runtime-id:/path)`}:o?{direction:`push`,localPath:r,remotePath:o.path,runtimeId:o.runtimeId,...t}:{direction:`pull`,localPath:i,remotePath:a.path,runtimeId:a.runtimeId,...t}}function Vh(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t),r=e.slice(t+1);return r.startsWith(`/`)?{runtimeId:n,path:r}:null}function Hh(){return{stdout:`rsync — sync files between local VFS and a remote tray runtime
1600
+ `,exitCode:1};let r;try{r=new URL(n).hostname}catch{return{stdout:``,stderr:`secret: invalid URL "${n}"\n`,exitCode:1}}let{ok:i,data:a}=await Vh(`GET`,``);if(!i)return{stdout:``,stderr:`secret: failed to fetch secrets
1601
+ `,exitCode:1};let o=a.find(e=>e.name===t);if(!o)return{stdout:``,stderr:`secret: no secret named "${t}"\n`,exitCode:1};let{isAllowedDomain:s}=await v(async()=>{let{isAllowedDomain:e}=await import(`./secret-masking-CfbASE5x.js`);return{isAllowedDomain:e}},[]);return s(o.domains,r)?{stdout:`✓ ${t} is allowed for ${r}\n`,stderr:``,exitCode:0}:{stdout:`✗ ${t} is NOT allowed for ${r}\n Allowed domains: ${o.domains.join(`, `)}\n`,stderr:``,exitCode:1}}default:return{stdout:``,stderr:`secret: unknown command "${t}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`secret: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function Wh(e,t,n={}){let r=new Map;for(let e of t)r.set(e.path,e);let i=new Set,a=[],o=[],s=[];for(let t of e){i.add(t.path);let e=r.get(t.path);e?e.size===t.size&&e.mtimeMs===t.mtimeMs?s.push(t.path):o.push(t.path):a.push(t.path)}let c=[];if(n.delete)for(let e of t)i.has(e.path)||c.push(e.path);return{toAdd:a,toUpdate:o,toDelete:c,toSkip:s}}var Gh=null;function Kh(e){Gh=e}function qh(){return Gh?.()??null}function Jh(e){let t={dryRun:!1,delete:!1,verbose:!1},n=[];for(let r of e)if(r===`--dry-run`||r===`-n`)t.dryRun=!0;else if(r===`--delete`)t.delete=!0;else if(r===`--verbose`||r===`-v`)t.verbose=!0;else if(r===`--help`||r===`-h`)return{error:`__help__`};else if(r.startsWith(`-`))return{error:`Unknown flag: ${r}`};else n.push(r);if(n.length!==2)return{error:`Expected exactly 2 arguments: <source> <dest>`};let[r,i]=n,a=Yh(r),o=Yh(i);return a&&o?{error:`Cannot sync between two remote paths — one side must be local`}:!a&&!o?{error:`One argument must be a remote path (runtime-id:/path)`}:o?{direction:`push`,localPath:r,remotePath:o.path,runtimeId:o.runtimeId,...t}:{direction:`pull`,localPath:i,remotePath:a.path,runtimeId:a.runtimeId,...t}}function Yh(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t),r=e.slice(t+1);return r.startsWith(`/`)?{runtimeId:n,path:r}:null}function Xh(){return{stdout:`rsync — sync files between local VFS and a remote tray runtime
1595
1602
 
1596
1603
  Usage:
1597
1604
  rsync [flags] <local-path> <runtime-id>:<remote-path> # push
@@ -1607,21 +1614,21 @@ Examples:
1607
1614
  rsync /workspace follower-abc123:/workspace
1608
1615
  rsync --delete /shared leader:/shared
1609
1616
  rsync follower-abc123:/workspace/project /workspace/project
1610
- `,stderr:``,exitCode:0}}async function Uh(e,t){if(!await e.exists(t))return[];let n=[];for await(let r of e.walk(t)){let i=r.slice(t.length).replace(/^\//,``);if(!i)continue;let a=await e.stat(r);n.push({path:i,size:a.size,mtimeMs:a.mtime})}return n}async function Wh(e,t,n){let r=(await e(t,{op:`walk`,path:n}))[0];if(!r.ok){if(r.code===`ENOENT`)return[];throw Error(`Remote walk failed: ${r.error}`)}if(r.data.type!==`paths`)throw Error(`Unexpected walk response type`);let i=r.data.paths,a=[];for(let r of i){let i=r.slice(n.length).replace(/^\//,``);if(!i)continue;let o=(await e(t,{op:`stat`,path:r}))[0];o.ok&&o.data.type===`stat`&&a.push({path:i,size:o.data.stat.size,mtimeMs:o.data.stat.mtime})}return a}async function Gh(e,t,n){let r=await e(t,{op:`readFile`,path:n,encoding:`binary`}),i=``;for(let e of r){if(!e.ok)throw Error(`Remote read failed: ${e.error}`);e.data.type===`file`&&(i+=e.data.content)}return i}async function Kh(e,t,n){let r=await e(t,{op:`mkdir`,path:n,recursive:!0});if(!r[0].ok)throw Error(`Remote mkdir failed: ${r[0].error}`)}function qh(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}async function Jh(e,t,n){let r=[],{localPath:i,remotePath:a,runtimeId:o,verbose:s,dryRun:c}=n,l=Ih(await Uh(e,i),await Wh(t,o,a),{delete:n.delete});if(s||c){for(let e of l.toAdd)r.push(`+ ${e}`);for(let e of l.toUpdate)r.push(`~ ${e}`);for(let e of l.toDelete)r.push(`- ${e}`);if(s)for(let e of l.toSkip)r.push(` ${e} (up to date)`)}let u=l.toAdd.length+l.toUpdate.length+l.toDelete.length;if(c)return r.push(`\n(dry run) ${u} file(s) would be transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
1617
+ `,stderr:``,exitCode:0}}async function Zh(e,t){if(!await e.exists(t))return[];let n=[];for await(let r of e.walk(t)){let i=r.slice(t.length).replace(/^\//,``);if(!i)continue;let a=await e.stat(r);n.push({path:i,size:a.size,mtimeMs:a.mtime})}return n}async function Qh(e,t,n){let r=(await e(t,{op:`walk`,path:n}))[0];if(!r.ok){if(r.code===`ENOENT`)return[];throw Error(`Remote walk failed: ${r.error}`)}if(r.data.type!==`paths`)throw Error(`Unexpected walk response type`);let i=r.data.paths,a=[];for(let r of i){let i=r.slice(n.length).replace(/^\//,``);if(!i)continue;let o=(await e(t,{op:`stat`,path:r}))[0];o.ok&&o.data.type===`stat`&&a.push({path:i,size:o.data.stat.size,mtimeMs:o.data.stat.mtime})}return a}async function $h(e,t,n){let r=await e(t,{op:`readFile`,path:n,encoding:`binary`}),i=``;for(let e of r){if(!e.ok)throw Error(`Remote read failed: ${e.error}`);e.data.type===`file`&&(i+=e.data.content)}return i}async function eg(e,t,n){let r=await e(t,{op:`mkdir`,path:n,recursive:!0});if(!r[0].ok)throw Error(`Remote mkdir failed: ${r[0].error}`)}function tg(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}async function ng(e,t,n){let r=[],{localPath:i,remotePath:a,runtimeId:o,verbose:s,dryRun:c}=n,l=Wh(await Zh(e,i),await Qh(t,o,a),{delete:n.delete});if(s||c){for(let e of l.toAdd)r.push(`+ ${e}`);for(let e of l.toUpdate)r.push(`~ ${e}`);for(let e of l.toDelete)r.push(`- ${e}`);if(s)for(let e of l.toSkip)r.push(` ${e} (up to date)`)}let u=l.toAdd.length+l.toUpdate.length+l.toDelete.length;if(c)return r.push(`\n(dry run) ${u} file(s) would be transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
1611
1618
  `)+`
1612
- `,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let s=i+`/`+n,c=a+`/`+n;await Kh(t,o,qh(c));let l=await t(o,{op:`writeFile`,path:c,content:Xh(await e.readFile(s,{encoding:`binary`})),encoding:`base64`});if(!l[0].ok)return{stdout:r.join(`
1619
+ `,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let s=i+`/`+n,c=a+`/`+n;await eg(t,o,tg(c));let l=await t(o,{op:`writeFile`,path:c,content:ig(await e.readFile(s,{encoding:`binary`})),encoding:`base64`});if(!l[0].ok)return{stdout:r.join(`
1613
1620
  `)+`
1614
1621
  `,stderr:`Error writing ${c}: ${l[0].error}\n`,exitCode:1}}for(let e of l.toDelete){let n=a+`/`+e,i=await t(o,{op:`rm`,path:n});if(!i[0].ok)return{stdout:r.join(`
1615
1622
  `)+`
1616
1623
  `,stderr:`Error deleting ${n}: ${i[0].error}\n`,exitCode:1}}return r.push(`${u} file(s) transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
1617
1624
  `)+`
1618
- `,stderr:``,exitCode:0}}async function Yh(e,t,n){let r=[],{localPath:i,remotePath:a,runtimeId:o,verbose:s,dryRun:c}=n,l=Ih(await Wh(t,o,a),await Uh(e,i),{delete:n.delete});if(s||c){for(let e of l.toAdd)r.push(`+ ${e}`);for(let e of l.toUpdate)r.push(`~ ${e}`);for(let e of l.toDelete)r.push(`- ${e}`);if(s)for(let e of l.toSkip)r.push(` ${e} (up to date)`)}let u=l.toAdd.length+l.toUpdate.length+l.toDelete.length;if(c)return r.push(`\n(dry run) ${u} file(s) would be transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
1625
+ `,stderr:``,exitCode:0}}async function rg(e,t,n){let r=[],{localPath:i,remotePath:a,runtimeId:o,verbose:s,dryRun:c}=n,l=Wh(await Qh(t,o,a),await Zh(e,i),{delete:n.delete});if(s||c){for(let e of l.toAdd)r.push(`+ ${e}`);for(let e of l.toUpdate)r.push(`~ ${e}`);for(let e of l.toDelete)r.push(`- ${e}`);if(s)for(let e of l.toSkip)r.push(` ${e} (up to date)`)}let u=l.toAdd.length+l.toUpdate.length+l.toDelete.length;if(c)return r.push(`\n(dry run) ${u} file(s) would be transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
1619
1626
  `)+`
1620
- `,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let r=a+`/`+n,s=i+`/`+n,c=qh(s);await e.exists(c)||await e.mkdir(c,{recursive:!0});let l=Zh(await Gh(t,o,r));await e.writeFile(s,l)}for(let t of l.toDelete){let n=i+`/`+t;await e.rm(n)}return r.push(`${u} file(s) transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
1627
+ `,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let r=a+`/`+n,s=i+`/`+n,c=tg(s);await e.exists(c)||await e.mkdir(c,{recursive:!0});let l=ag(await $h(t,o,r));await e.writeFile(s,l)}for(let t of l.toDelete){let n=i+`/`+t;await e.rm(n)}return r.push(`${u} file(s) transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
1621
1628
  `)+`
1622
- `,stderr:``,exitCode:0}}function Xh(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Zh(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}function Qh(e={}){let t=e.fs,n=e.getSendFsRequest??zh;return z(`rsync`,async e=>{if(e.includes(`--help`)||e.includes(`-h`)||e.length===0)return Hh();if(!t)return{stdout:``,stderr:`rsync: no filesystem available
1629
+ `,stderr:``,exitCode:0}}function ig(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function ag(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}function og(e={}){let t=e.fs,n=e.getSendFsRequest??qh;return z(`rsync`,async e=>{if(e.includes(`--help`)||e.includes(`-h`)||e.length===0)return Xh();if(!t)return{stdout:``,stderr:`rsync: no filesystem available
1623
1630
  `,exitCode:1};let r=n();if(!r)return{stdout:``,stderr:`rsync: not connected to a tray — rsync requires a tray connection
1624
- `,exitCode:1};let i=Bh(e);if(`error`in i)return i.error===`__help__`?Hh():{stdout:``,stderr:`rsync: ${i.error}\n`,exitCode:1};try{return i.direction===`push`?await Jh(t,r,i):await Yh(t,r,i)}catch(e){return{stdout:``,stderr:`rsync: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}var $h=[`/workspace/skills`];async function eg(e){let t=new Map;for(let n of $h)await e.exists(n)&&await tg(e,n,t);return await tg(e,`/`,t),t}async function tg(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.jsh`))continue;let e=ng(r);n.has(e)||n.set(e,r)}}function ng(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.jsh`)?t.slice(0,-4):t}function rg(e={}){let t=e.scriptCatalog!==void 0||e.fs!==void 0?e:typeof e.walk==`function`&&typeof e.exists==`function`?{fs:e}:{};return z(`which`,async(e,n)=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`which - locate a command
1631
+ `,exitCode:1};let i=Jh(e);if(`error`in i)return i.error===`__help__`?Xh():{stdout:``,stderr:`rsync: ${i.error}\n`,exitCode:1};try{return i.direction===`push`?await ng(t,r,i):await rg(t,r,i)}catch(e){return{stdout:``,stderr:`rsync: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}var sg=[`/workspace/skills`];async function cg(e){let t=new Map;for(let n of sg)await e.exists(n)&&await lg(e,n,t);return await lg(e,`/`,t),t}async function lg(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.jsh`))continue;let e=ug(r);n.has(e)||n.set(e,r)}}function ug(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.jsh`)?t.slice(0,-4):t}function dg(e={}){let t=e.scriptCatalog!==void 0||e.fs!==void 0?e:typeof e.walk==`function`&&typeof e.exists==`function`?{fs:e}:{};return z(`which`,async(e,n)=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`which - locate a command
1625
1632
 
1626
1633
  Usage: which <command> [command...]
1627
1634
 
@@ -1631,12 +1638,12 @@ Prints the path of the given command(s).
1631
1638
 
1632
1639
  Exit code 0 if all commands found, 1 if any not found.
1633
1640
  `,stderr:``,exitCode:0};if(e.length===0)return{stdout:``,stderr:`which: missing argument
1634
- `,exitCode:1};let r=n.getRegisteredCommands?.()??[],i=new Set(r),a=t.scriptCatalog?await t.scriptCatalog.getJshCommands():t.fs?await eg(t.fs):new Map,o=[],s=!0;for(let t of e)if(i.has(t))o.push(`/usr/bin/${t}`);else{let e=a.get(t);e?o.push(e):s=!1}return{stdout:o.length>0?o.join(`
1641
+ `,exitCode:1};let r=n.getRegisteredCommands?.()??[],i=new Set(r),a=t.scriptCatalog?await t.scriptCatalog.getJshCommands():t.fs?await cg(t.fs):new Map,o=[],s=!0;for(let t of e)if(i.has(t))o.push(`/usr/bin/${t}`);else{let e=a.get(t);e?o.push(e):s=!1}return{stdout:o.length>0?o.join(`
1635
1642
  `)+`
1636
- `:``,stderr:``,exitCode:+!s}})}async function ig(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=vm(t,o),s=n?`${n}/${o}`:o;a+=await ig(e,i,s,r)}return a}function ag(){return{stdout:`usage: zip [-r] <archive.zip> <path> [path...]
1637
- `,stderr:``,exitCode:0}}function og(){return z(`zip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return ag();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
1638
- `,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(/^\.\//,``))||gm(r);if(i.isDirectory&&!n)return{stdout:``,stderr:`zip: ${e} is a directory (use -r)\n`,exitCode:1};s+=await ig(t,r,a,o)}if(s===0)return{stdout:``,stderr:`zip: nothing to do
1639
- `,exitCode:1};let c=P(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function sg(){return{stdout:`screencapture - capture screen, window, or tab using browser screen sharing
1643
+ `:``,stderr:``,exitCode:+!s}})}async function fg(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=vm(t,o),s=n?`${n}/${o}`:o;a+=await fg(e,i,s,r)}return a}function pg(){return{stdout:`usage: zip [-r] <archive.zip> <path> [path...]
1644
+ `,stderr:``,exitCode:0}}function mg(){return z(`zip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return pg();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
1645
+ `,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(/^\.\//,``))||gm(r);if(i.isDirectory&&!n)return{stdout:``,stderr:`zip: ${e} is a directory (use -r)\n`,exitCode:1};s+=await fg(t,r,a,o)}if(s===0)return{stdout:``,stderr:`zip: nothing to do
1646
+ `,exitCode:1};let c=F(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function hg(){return{stdout:`screencapture - capture screen, window, or tab using browser screen sharing
1640
1647
 
1641
1648
  Usage: screencapture [options] <output-file>
1642
1649
 
@@ -1652,57 +1659,57 @@ Examples:
1652
1659
  screencapture screenshot.png # Capture to file
1653
1660
  screencapture -c # Capture to clipboard
1654
1661
  screencapture -v capture.png # Capture and return for agent vision
1655
- `,stderr:``,exitCode:0}}function cg(e){let t=``,n=8192;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function lg(e){switch(e.split(`.`).pop()?.toLowerCase()){case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return`image/png`}}async function ug(e,t){let n=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1});try{let r=document.createElement(`video`);r.srcObject=n,r.muted=!0,r.playsInline=!0,await new Promise((e,t)=>{r.onloadedmetadata=()=>{r.play().then(()=>e()).catch(t)},r.onerror=()=>t(Error(`Failed to load video stream`))}),await new Promise(e=>requestAnimationFrame(e));let i=r.videoWidth,a=r.videoHeight,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);return s.drawImage(r,0,0,i,a),new Promise((n,r)=>{o.toBlob(e=>{e?n(e):r(Error(`Failed to create image blob`))},e,t)})}finally{n.getTracks().forEach(e=>e.stop())}}function dg(){return z(`screencapture`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return sg();if(typeof window>`u`||typeof navigator>`u`||typeof document>`u`)return{stdout:``,stderr:`screencapture: browser APIs are unavailable in this environment
1662
+ `,stderr:``,exitCode:0}}function gg(e){let t=``,n=8192;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function _g(e){switch(e.split(`.`).pop()?.toLowerCase()){case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return`image/png`}}async function vg(e,t){let n=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1});try{let r=document.createElement(`video`);r.srcObject=n,r.muted=!0,r.playsInline=!0,await new Promise((e,t)=>{r.onloadedmetadata=()=>{r.play().then(()=>e()).catch(t)},r.onerror=()=>t(Error(`Failed to load video stream`))}),await new Promise(e=>requestAnimationFrame(e));let i=r.videoWidth,a=r.videoHeight,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);return s.drawImage(r,0,0,i,a),new Promise((n,r)=>{o.toBlob(e=>{e?n(e):r(Error(`Failed to create image blob`))},e,t)})}finally{n.getTracks().forEach(e=>e.stop())}}function yg(){return z(`screencapture`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return hg();if(typeof window>`u`||typeof navigator>`u`||typeof document>`u`)return{stdout:``,stderr:`screencapture: browser APIs are unavailable in this environment
1656
1663
  `,exitCode:1};if(!navigator.mediaDevices?.getDisplayMedia)return{stdout:``,stderr:`screencapture: screen capture is not supported in this browser
1657
1664
  `,exitCode:1};let n=e.includes(`--clipboard`)||e.includes(`-c`),r=e.includes(`--view`)||e.includes(`-v`),i=[`--clipboard`,`-c`,`--view`,`-v`,`--help`,`-h`],a=e.indexOf(`--`),o=(a>=0?e.slice(a+1):e.filter(e=>!i.includes(e)))[0];if(!n&&!o)return{stdout:``,stderr:`screencapture: output file required (or use -c for clipboard)
1658
- `,exitCode:1};let s=o||`screenshot.png`,c=lg(s),l=c===`image/png`?1:.92,u;try{u=await ug(c,l)}catch(e){let t=e instanceof Error?e.message:String(e);return t.includes(`Permission denied`)||t.includes(`NotAllowedError`)?{stdout:``,stderr:`screencapture: user cancelled or permission denied
1659
- `,exitCode:1}:{stdout:``,stderr:`screencapture: ${t}\n`,exitCode:1}}let d=await u.arrayBuffer(),f=new Uint8Array(d);if(n)try{let e;if(c===`image/png`)e=u;else{let t=new Image,n=URL.createObjectURL(u);try{await new Promise((e,r)=>{t.onload=()=>e(),t.onerror=()=>r(Error(`Failed to load image for conversion`)),t.src=n})}finally{URL.revokeObjectURL(n)}let r=document.createElement(`canvas`);r.width=t.width,r.height=t.height;let i=r.getContext(`2d`);if(!i)throw Error(`Failed to get canvas context`);i.drawImage(t,0,0),e=await new Promise((e,t)=>{r.toBlob(n=>{n?e(n):t(Error(`Failed to create PNG blob`))},`image/png`)})}return await navigator.clipboard.write([new ClipboardItem({"image/png":e})]),{stdout:`captured ${Math.round(e.size/1024)} KB to clipboard\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`screencapture: failed to copy to clipboard: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let p=t.fs.resolvePath(t.cwd,s);try{await t.fs.writeFile(p,f)}catch(e){return{stdout:``,stderr:`screencapture: failed to write file: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let m=Math.round(f.length/1024);return r?{stdout:`${p} (${m} KB)\n<img:data:${c};base64,${cg(f)}>`,stderr:``,exitCode:0}:{stdout:`captured ${m} KB to ${gm(p)}\n`,stderr:``,exitCode:0}})}function fg(e){return e instanceof Error?e.message:String(e)}function pg(){return{stdout:`usage: pbcopy
1665
+ `,exitCode:1};let s=o||`screenshot.png`,c=_g(s),l=c===`image/png`?1:.92,u;try{u=await vg(c,l)}catch(e){let t=e instanceof Error?e.message:String(e);return t.includes(`Permission denied`)||t.includes(`NotAllowedError`)?{stdout:``,stderr:`screencapture: user cancelled or permission denied
1666
+ `,exitCode:1}:{stdout:``,stderr:`screencapture: ${t}\n`,exitCode:1}}let d=await u.arrayBuffer(),f=new Uint8Array(d);if(n)try{let e;if(c===`image/png`)e=u;else{let t=new Image,n=URL.createObjectURL(u);try{await new Promise((e,r)=>{t.onload=()=>e(),t.onerror=()=>r(Error(`Failed to load image for conversion`)),t.src=n})}finally{URL.revokeObjectURL(n)}let r=document.createElement(`canvas`);r.width=t.width,r.height=t.height;let i=r.getContext(`2d`);if(!i)throw Error(`Failed to get canvas context`);i.drawImage(t,0,0),e=await new Promise((e,t)=>{r.toBlob(n=>{n?e(n):t(Error(`Failed to create PNG blob`))},`image/png`)})}return await navigator.clipboard.write([new ClipboardItem({"image/png":e})]),{stdout:`captured ${Math.round(e.size/1024)} KB to clipboard\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`screencapture: failed to copy to clipboard: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let p=t.fs.resolvePath(t.cwd,s);try{await t.fs.writeFile(p,f)}catch(e){return{stdout:``,stderr:`screencapture: failed to write file: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let m=Math.round(f.length/1024);return r?{stdout:`${p} (${m} KB)\n<img:data:${c};base64,${gg(f)}>`,stderr:``,exitCode:0}:{stdout:`captured ${m} KB to ${gm(p)}\n`,stderr:``,exitCode:0}})}function bg(e){return e instanceof Error?e.message:String(e)}function xg(){return{stdout:`usage: pbcopy
1660
1667
 
1661
1668
  Copy stdin to the clipboard.
1662
1669
  Example: echo hello | pbcopy
1663
- `,stderr:``,exitCode:0}}function mg(){return{stdout:`usage: pbpaste
1670
+ `,stderr:``,exitCode:0}}function Sg(){return{stdout:`usage: pbpaste
1664
1671
 
1665
1672
  Paste clipboard contents to stdout.
1666
- `,stderr:``,exitCode:0}}function hg(e){return{stdout:`usage: ${e} [-i|-o]\n\n -i Force copy mode (read from stdin)
1673
+ `,stderr:``,exitCode:0}}function Cg(e){return{stdout:`usage: ${e} [-i|-o]\n\n -i Force copy mode (read from stdin)
1667
1674
  -o Force paste mode (write to stdout)
1668
1675
  (default) Auto-detect: stdin present = copy, no stdin = paste
1669
- Example: echo hello | ${e}\n Example: ${e} -o > file.txt\n`,stderr:``,exitCode:0}}async function gg(e,t){if(!globalThis.navigator?.clipboard)return{stdout:``,stderr:`${t}: clipboard API is unavailable\n`,exitCode:1};try{return await navigator.clipboard.writeText(e),{stdout:``,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`${t}: failed to write to clipboard: ${fg(e)}\n`,exitCode:1}}}async function _g(e){if(!globalThis.navigator?.clipboard)return{stdout:``,stderr:`${e}: clipboard API is unavailable\n`,exitCode:1};try{return{stdout:await navigator.clipboard.readText(),stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: failed to read from clipboard: ${fg(t)}\n`,exitCode:1}}}function vg(){return z(`pbcopy`,async(e,t)=>e.includes(`--help`)||e.includes(`-h`)?pg():gg(t.stdin,`pbcopy`))}function yg(){return z(`pbpaste`,async e=>e.includes(`--help`)||e.includes(`-h`)?mg():_g(`pbpaste`))}function bg(e){return z(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return hg(e);let r=t.includes(`-i`),i=t.includes(`-o`);return r&&i?{stdout:``,stderr:`${e}: cannot use both -i and -o\n`,exitCode:1}:i?_g(e):r||n.stdin.length>0?gg(n.stdin,e):_g(e)})}function xg(){return{stdout:`usage: say [-v voice] [-r rate] [-l lang] [--list] <text>
1676
+ Example: echo hello | ${e}\n Example: ${e} -o > file.txt\n`,stderr:``,exitCode:0}}async function wg(e,t){if(!globalThis.navigator?.clipboard)return{stdout:``,stderr:`${t}: clipboard API is unavailable\n`,exitCode:1};try{return await navigator.clipboard.writeText(e),{stdout:``,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`${t}: failed to write to clipboard: ${bg(e)}\n`,exitCode:1}}}async function Tg(e){if(!globalThis.navigator?.clipboard)return{stdout:``,stderr:`${e}: clipboard API is unavailable\n`,exitCode:1};try{return{stdout:await navigator.clipboard.readText(),stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: failed to read from clipboard: ${bg(t)}\n`,exitCode:1}}}function Eg(){return z(`pbcopy`,async(e,t)=>e.includes(`--help`)||e.includes(`-h`)?xg():wg(t.stdin,`pbcopy`))}function Dg(){return z(`pbpaste`,async e=>e.includes(`--help`)||e.includes(`-h`)?Sg():Tg(`pbpaste`))}function Og(e){return z(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return Cg(e);let r=t.includes(`-i`),i=t.includes(`-o`);return r&&i?{stdout:``,stderr:`${e}: cannot use both -i and -o\n`,exitCode:1}:i?Tg(e):r||n.stdin.length>0?wg(n.stdin,e):Tg(e)})}function kg(){return{stdout:`usage: say [-v voice] [-r rate] [-l lang] [--list] <text>
1670
1677
 
1671
1678
  Speaks the given text using the Web Speech API.
1672
1679
  -v voice Voice name (partial match supported)
1673
1680
  -r rate Speech rate (0.1 to 10, default 1)
1674
1681
  -l lang Language tag (required, BCP 47, e.g. en-US, de-DE, fr-FR)
1675
1682
  --list List available voices
1676
- `,stderr:``,exitCode:0}}var Sg=!1,Cg=null;function wg(){return Sg?Promise.resolve(speechSynthesis.getVoices()):(Cg||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){Sg=!0,e(t);return}let n=()=>{Sg=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),Sg=!0,e(speechSynthesis.getVoices())},1e3)}),Cg)}function Tg(){return z(`say`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return xg();if(typeof window>`u`||typeof speechSynthesis>`u`)return{stdout:``,stderr:`say: Web Speech API unavailable in this environment
1677
- `,exitCode:1};if(e.includes(`--list`))return{stdout:(await wg()).map(e=>`${e.name} (${e.lang})${e.default?` [default]`:``}`).join(`
1683
+ `,stderr:``,exitCode:0}}var Ag=!1,jg=null;function Mg(){return Ag?Promise.resolve(speechSynthesis.getVoices()):(jg||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){Ag=!0,e(t);return}let n=()=>{Ag=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),Ag=!0,e(speechSynthesis.getVoices())},1e3)}),jg)}function Ng(){return z(`say`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return kg();if(typeof window>`u`||typeof speechSynthesis>`u`)return{stdout:``,stderr:`say: Web Speech API unavailable in this environment
1684
+ `,exitCode:1};if(e.includes(`--list`))return{stdout:(await Mg()).map(e=>`${e.name} (${e.lang})${e.default?` [default]`:``}`).join(`
1678
1685
  `)+`
1679
1686
  `,stderr:``,exitCode:0};let t=null,n=1,r=null,i=[];for(let a=0;a<e.length;a++){let o=e[a];if(o===`-v`){if(a+1>=e.length||e[a+1].startsWith(`-`))return{stdout:``,stderr:`say: -v requires a voice name
1680
1687
  `,exitCode:1};t=e[++a]}else if(o===`-r`){if(a+1>=e.length||e[a+1].startsWith(`-`))return{stdout:``,stderr:`say: -r requires a rate value
1681
1688
  `,exitCode:1};if(n=parseFloat(e[++a]),isNaN(n)||n<.1||n>10)return{stdout:``,stderr:`say: rate must be between 0.1 and 10
1682
1689
  `,exitCode:1}}else if(o===`-l`){if(a+1>=e.length||e[a+1].startsWith(`-`))return{stdout:``,stderr:`say: -l requires a language tag
1683
- `,exitCode:1};r=e[++a]}else if(o.startsWith(`-`)&&o!==`--list`)return{stdout:``,stderr:`say: unknown option: ${o}\n`,exitCode:1};else o.startsWith(`-`)||i.push(o)}let a=i.join(` `);if(!a)return xg();if(!r)return{stdout:``,stderr:`say: -l language tag is required
1684
- `,exitCode:1};let o=new SpeechSynthesisUtterance(a);if(o.rate=n,o.lang=r,t){let e=(await wg()).find(e=>e.name.toLowerCase().includes(t.toLowerCase()));if(e)o.voice=e;else return{stdout:``,stderr:`say: voice "${t}" not found. Use --list to see available voices.\n`,exitCode:1}}return new Promise(e=>{o.onend=()=>{e({stdout:``,stderr:``,exitCode:0})},o.onerror=t=>{e({stdout:``,stderr:`say: speech synthesis error: ${t.error}\n`,exitCode:1})},speechSynthesis.speak(o)})})}function Eg(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
1690
+ `,exitCode:1};r=e[++a]}else if(o.startsWith(`-`)&&o!==`--list`)return{stdout:``,stderr:`say: unknown option: ${o}\n`,exitCode:1};else o.startsWith(`-`)||i.push(o)}let a=i.join(` `);if(!a)return kg();if(!r)return{stdout:``,stderr:`say: -l language tag is required
1691
+ `,exitCode:1};let o=new SpeechSynthesisUtterance(a);if(o.rate=n,o.lang=r,t){let e=(await Mg()).find(e=>e.name.toLowerCase().includes(t.toLowerCase()));if(e)o.voice=e;else return{stdout:``,stderr:`say: voice "${t}" not found. Use --list to see available voices.\n`,exitCode:1}}return new Promise(e=>{o.onend=()=>{e({stdout:``,stderr:``,exitCode:0})},o.onerror=t=>{e({stdout:``,stderr:`say: speech synthesis error: ${t.error}\n`,exitCode:1})},speechSynthesis.speak(o)})})}function Pg(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
1685
1692
 
1686
1693
  Plays an audio file using the Web Audio API.
1687
1694
  -v volume Volume level (0 to 1, default 1)
1688
1695
  -r rate Playback rate (0.25 to 4, default 1)
1689
- `,stderr:``,exitCode:0}}var Dg=null;function Og(){return(!Dg||Dg.state===`closed`)&&(Dg=new AudioContext),Dg}async function kg(e,t,n,r){if(typeof window>`u`||typeof AudioContext>`u`)return{stdout:``,stderr:`afplay: Web Audio API unavailable in this environment
1690
- `,exitCode:1};let i=r.fs.resolvePath(r.cwd,e),a;try{a=new Uint8Array(await r.fs.readFileBuffer(i))}catch{return{stdout:``,stderr:`afplay: cannot open ${e}: No such file\n`,exitCode:1}}if(!Cm(i).startsWith(`audio/`))return{stdout:``,stderr:`afplay: ${e} is not an audio file\n`,exitCode:1};try{let e=Og();e.state===`suspended`&&await e.resume();let r=new ArrayBuffer(a.byteLength);new Uint8Array(r).set(a);let i=await e.decodeAudioData(r),o=e.createBufferSource();o.buffer=i,o.playbackRate.value=n;let s=e.createGain();return s.gain.value=t,o.connect(s),s.connect(e.destination),new Promise(e=>{o.onended=()=>{e({stdout:``,stderr:``,exitCode:0})},o.start()})}catch(t){return{stdout:``,stderr:`afplay: failed to play ${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}}function Ag(){return z(`afplay`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Eg();let n=1,r=1,i=null;for(let t=0;t<e.length;t++){let a=e[t];if(a===`-v`){if(t+1>=e.length||e[t+1].startsWith(`-`))return{stdout:``,stderr:`afplay: -v requires a volume value
1696
+ `,stderr:``,exitCode:0}}var Fg=null;function Ig(){return(!Fg||Fg.state===`closed`)&&(Fg=new AudioContext),Fg}async function Lg(e,t,n,r){if(typeof window>`u`||typeof AudioContext>`u`)return{stdout:``,stderr:`afplay: Web Audio API unavailable in this environment
1697
+ `,exitCode:1};let i=r.fs.resolvePath(r.cwd,e),a;try{a=new Uint8Array(await r.fs.readFileBuffer(i))}catch{return{stdout:``,stderr:`afplay: cannot open ${e}: No such file\n`,exitCode:1}}if(!Cm(i).startsWith(`audio/`))return{stdout:``,stderr:`afplay: ${e} is not an audio file\n`,exitCode:1};try{let e=Ig();e.state===`suspended`&&await e.resume();let r=new ArrayBuffer(a.byteLength);new Uint8Array(r).set(a);let i=await e.decodeAudioData(r),o=e.createBufferSource();o.buffer=i,o.playbackRate.value=n;let s=e.createGain();return s.gain.value=t,o.connect(s),s.connect(e.destination),new Promise(e=>{o.onended=()=>{e({stdout:``,stderr:``,exitCode:0})},o.start()})}catch(t){return{stdout:``,stderr:`afplay: failed to play ${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}}function Rg(){return z(`afplay`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Pg();let n=1,r=1,i=null;for(let t=0;t<e.length;t++){let a=e[t];if(a===`-v`){if(t+1>=e.length||e[t+1].startsWith(`-`))return{stdout:``,stderr:`afplay: -v requires a volume value
1691
1698
  `,exitCode:1};if(n=parseFloat(e[++t]),isNaN(n)||n<0||n>1)return{stdout:``,stderr:`afplay: volume must be between 0 and 1
1692
1699
  `,exitCode:1}}else if(a===`-r`){if(t+1>=e.length||e[t+1].startsWith(`-`))return{stdout:``,stderr:`afplay: -r requires a rate value
1693
1700
  `,exitCode:1};if(r=parseFloat(e[++t]),isNaN(r)||r<.25||r>4)return{stdout:``,stderr:`afplay: rate must be between 0.25 and 4
1694
1701
  `,exitCode:1}}else if(a.startsWith(`-`))return{stdout:``,stderr:`afplay: unknown option: ${a}\n`,exitCode:1};else{if(i!==null)return{stdout:``,stderr:`afplay: only one file can be specified
1695
- `,exitCode:1};i=a}}return i?kg(i,n,r,t):Eg()})}function jg(){return z(`chime`,async(e,t)=>e.includes(`--help`)||e.includes(`-h`)?{stdout:`usage: chime
1702
+ `,exitCode:1};i=a}}return i?Lg(i,n,r,t):Pg()})}function zg(){return z(`chime`,async(e,t)=>e.includes(`--help`)||e.includes(`-h`)?{stdout:`usage: chime
1696
1703
 
1697
1704
  Plays a notification chime sound.
1698
1705
  Alias for: afplay /shared/sounds/chime.mp3
1699
- `,stderr:``,exitCode:0}:kg(`/shared/sounds/chime.mp3`,1,1,t))}function Mg(){return z(`debug`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`usage: debug [on|off]
1706
+ `,stderr:``,exitCode:0}:Lg(`/shared/sounds/chime.mp3`,1,1,t))}function Bg(){return z(`debug`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`usage: debug [on|off]
1700
1707
 
1701
1708
  Toggle debug tabs (Terminal, Memory) in extension mode.
1702
1709
  Without arguments, shows current state.
1703
1710
  `,stderr:``,exitCode:0};let t=e[0]?.toLowerCase();if(t!==`on`&&t!==`off`&&t!==void 0)return{stdout:``,stderr:`debug: unknown argument '${t}' (use 'on' or 'off')\n`,exitCode:1};if(!t)try{let e=localStorage.getItem(`slicc-hidden-tabs`);return{stdout:`Debug tabs: ${(e?JSON.parse(e):[`terminal`,`memory`]).includes(`terminal`)?`off`:`on`}\n`,stderr:``,exitCode:0}}catch{return{stdout:`Debug tabs: off
1704
1711
  `,stderr:``,exitCode:0}}let n=t===`on`,r=window.__slicc_debug_tabs;if(r)return r(n),{stdout:`Debug tabs ${n?`enabled`:`hidden`}\n`,stderr:``,exitCode:0};try{return chrome.runtime.sendMessage({source:`offscreen`,payload:{type:`debug-tabs`,show:n}}),{stdout:`Debug tabs ${n?`enabled`:`hidden`}\n`,stderr:``,exitCode:0}}catch{return{stdout:``,stderr:`debug: failed to send toggle message
1705
- `,exitCode:1}}})}var Ng=`/.cache/artificial-analysis.json`,Pg=1440*60*1e3,Fg=`https://artificialanalysis.ai/api/v2/data/llms/models`;async function Ig(e,t=!1){if(e&&!t)try{let t=await e.readFile(Ng),n=JSON.parse(t);if(Date.now()-n.fetchedAt<Pg)return n.models}catch{}let n=null;try{n=localStorage.getItem(`aa_api_key`)}catch{}let r={Accept:`application/json`};n&&(r[`x-api-key`]=n);let i;try{i=await fetch(Fg,{headers:r})}catch{return[]}if(i.status===401||!i.ok)return[];let a;try{a=await i.json()}catch{return[]}let o=(Array.isArray(a)?a:a?.data??a?.models??[]).map(e=>({slug:e.slug??``,name:e.name??``,creator_slug:e.model_creator?.slug??``,intelligence_index:e.evaluations?.artificial_analysis_intelligence_index??null,coding_index:e.evaluations?.artificial_analysis_coding_index??null,speed_tps:e.median_output_tokens_per_second??null}));if(e&&o.length>0){let t={fetchedAt:Date.now(),models:o};try{await e.mkdir(`/.cache`,{recursive:!0}),await e.writeFile(Ng,JSON.stringify(t))}catch{}}return o}function Lg(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function Rg(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=Lg(e),a=t.find(e=>Lg(e.slug)===i);if(a)return a;let o=t.filter(e=>n.includes(e.slug)||e.slug.includes(n));if(o.length>0)return o.sort((e,t)=>t.slug.length-e.slug.length),o[0]}function zg(){return`models - list available LLM models
1712
+ `,exitCode:1}}})}var Vg=`/.cache/artificial-analysis.json`,Hg=1440*60*1e3,Ug=`https://artificialanalysis.ai/api/v2/data/llms/models`;async function Wg(e,t=!1){if(e&&!t)try{let t=await e.readFile(Vg),n=JSON.parse(t);if(Date.now()-n.fetchedAt<Hg)return n.models}catch{}let n=null;try{n=localStorage.getItem(`aa_api_key`)}catch{}let r={Accept:`application/json`};n&&(r[`x-api-key`]=n);let i;try{i=await fetch(Ug,{headers:r})}catch{return[]}if(i.status===401||!i.ok)return[];let a;try{a=await i.json()}catch{return[]}let o=(Array.isArray(a)?a:a?.data??a?.models??[]).map(e=>({slug:e.slug??``,name:e.name??``,creator_slug:e.model_creator?.slug??``,intelligence_index:e.evaluations?.artificial_analysis_intelligence_index??null,coding_index:e.evaluations?.artificial_analysis_coding_index??null,speed_tps:e.median_output_tokens_per_second??null}));if(e&&o.length>0){let t={fetchedAt:Date.now(),models:o};try{await e.mkdir(`/.cache`,{recursive:!0}),await e.writeFile(Vg,JSON.stringify(t))}catch{}}return o}function Gg(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function Kg(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=Gg(e),a=t.find(e=>Gg(e.slug)===i);if(a)return a;let o=t.filter(e=>n.includes(e.slug)||e.slug.includes(n));if(o.length>0)return o.sort((e,t)=>t.slug.length-e.slug.length),o[0]}function qg(){return`models - list available LLM models
1706
1713
 
1707
1714
  Usage: models [options]
1708
1715
 
@@ -1714,13 +1721,13 @@ Options:
1714
1721
  --refresh Force re-fetch benchmark data from Artificial Analysis
1715
1722
  --no-benchmarks Skip benchmark data enrichment (faster, works offline)
1716
1723
  -h, --help Show this help message
1717
- `}function Bg(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function Vg(e){return`$${e.toFixed(2)}`}var Hg=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function Ug(e){let t=`${e.id} ${e.name??``}`;return!Hg.test(t)}function Wg(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 Gg(e){let t=new Map;for(let n of e){let e=Wg(n.id);t.has(e)||t.set(e,n)}return[...t.values()]}function Kg(e,t,n,r,i){let a=i?Rg(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 qg(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=`${Vg(e.cost.input)} / ${Vg(e.cost.output)}`,a=`${Bg(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(`
1724
+ `}function Jg(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function Yg(e){return`$${e.toFixed(2)}`}var Xg=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function Zg(e){let t=`${e.id} ${e.name??``}`;return!Xg.test(t)}function Qg(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 $g(e){let t=new Map;for(let n of e){let e=Qg(n.id);t.has(e)||t.set(e,n)}return[...t.values()]}function e_(e,t,n,r,i){let a=i?Kg(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 t_(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=`${Yg(e.cost.input)} / ${Yg(e.cost.output)}`,a=`${Jg(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(`
1718
1725
  `)+`
1719
- `}function Jg(e){return z(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s}=await v(async()=>{let{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}=await import(`./provider-settings-DtthfIx_.js`);return{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}},__vite__mapDeps([8,9,1,4,10,11,12,13,14,15]));if(t.includes(`--help`)||t.includes(`-h`))return{stdout:zg(),stderr:``,exitCode:0};let c=t.includes(`--json`),l=t.includes(`--all`),u=t.includes(`--all-versions`),d=t.includes(`--refresh`),f=t.includes(`--no-benchmarks`),p=t.indexOf(`--provider`),m=p>=0?t[p+1]:void 0,h=o(),g=s(),_=n();if(_.length===0)return{stdout:``,stderr:`No provider accounts configured. Run the provider settings to add one.
1720
- `,exitCode:1};let y;f||(y=await Ig(e,d),y.length===0&&(y=void 0));let b;if(m){let e=r();if(!e.includes(m))return{stdout:``,stderr:`Unknown provider: ${m}. Available: ${e.join(`, `)}\n`,exitCode:1};b=[m]}else b=l?[...new Set(_.map(e=>e.providerId))]:[h];let x=[],S=[];for(let e of b){let t=a(e).filter(Ug);if(t.length===0){if(!l)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>Kg(t,e,g,h,y)).sort((e,t)=>t.cost.input-e.cost.input);if(u||(n=Gg(n)),x.push(...n),!c){let t=i(e);S.push(qg(t.name,e,n,!!y))}}return c?{stdout:JSON.stringify(x,null,2)+`
1726
+ `}function n_(e){return z(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s}=await v(async()=>{let{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}=await import(`./provider-settings-DtthfIx_.js`);return{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}},__vite__mapDeps([8,9,1,4,10,11,12,13,14,15]));if(t.includes(`--help`)||t.includes(`-h`))return{stdout:qg(),stderr:``,exitCode:0};let c=t.includes(`--json`),l=t.includes(`--all`),u=t.includes(`--all-versions`),d=t.includes(`--refresh`),f=t.includes(`--no-benchmarks`),p=t.indexOf(`--provider`),m=p>=0?t[p+1]:void 0,h=o(),g=s(),_=n();if(_.length===0)return{stdout:``,stderr:`No provider accounts configured. Run the provider settings to add one.
1727
+ `,exitCode:1};let y;f||(y=await Wg(e,d),y.length===0&&(y=void 0));let b;if(m){let e=r();if(!e.includes(m))return{stdout:``,stderr:`Unknown provider: ${m}. Available: ${e.join(`, `)}\n`,exitCode:1};b=[m]}else b=l?[...new Set(_.map(e=>e.providerId))]:[h];let x=[],S=[];for(let e of b){let t=a(e).filter(Zg);if(t.length===0){if(!l)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>e_(t,e,g,h,y)).sort((e,t)=>t.cost.input-e.cost.input);if(u||(n=$g(n)),x.push(...n),!c){let t=i(e);S.push(t_(t.name,e,n,!!y))}}return c?{stdout:JSON.stringify(x,null,2)+`
1721
1728
  `,stderr:``,exitCode:0}:(!u&&!c&&S.push(`Showing latest versions only. Use --all-versions to see all.
1722
1729
  `),{stdout:S.join(`
1723
- `),stderr:``,exitCode:0})})}function Yg(){return z(`nuke`,async e=>e.includes(`--help`)||e.includes(`-h`)?{stdout:`Usage: nuke <launch-code>
1730
+ `),stderr:``,exitCode:0})})}function r_(){return z(`nuke`,async e=>e.includes(`--help`)||e.includes(`-h`)?{stdout:`Usage: nuke <launch-code>
1724
1731
 
1725
1732
  Completely reset the environment by deleting all local data and reloading.
1726
1733
  Destroys the file system, chat history, and scoops database.
@@ -1728,12 +1735,12 @@ Requires the secret launch code to proceed.
1728
1735
  `,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…
1729
1736
  `,stderr:``,exitCode:0}):{stdout:``,stderr:`⚠️ WARNING: this will reset the entire environment, file system, chats, and scoops.
1730
1737
  Run nuke again with the secret launch code to proceed.
1731
- `,exitCode:1})}function Xg(e={}){let t=[Ap({getJshCommands:e.getJshCommands}),im(),rh(e.browserAPI,e.fs),Bm(),sm(e),og(),fh(),ah(`sqlite3`),ah(`sqllite`),Im(),eh(`python3`),eh(`python`),hh(),Sh(),Th(),Oh(),Ym(`pdftk`),Ym(`pdf`),Np(`convert`),Np(`magick`),rg({fs:e.fs,scriptCatalog:e.scriptCatalog}),sh(),uh(),Ah(),Fh(),Qh({fs:e.fs}),dg(),vg(),yg(),bg(`xclip`),bg(`xsel`),Tg(),Ag(),jg(),Jg(e.fs),Ge(),Yg()];return typeof chrome<`u`&&chrome?.runtime?.id&&t.push(Mg()),e.fs&&t.push(...Lf.map(t=>Dp(t,e.browserAPI,e.fs))),t}var Zg=`https://wry-manatee-359.convex.site/api/v1`,Qg=`https://api.tessl.io`,$g=`/workspace/skills`,e_=`slicc-fs-global`,t_=`/workspace/.git/github-token`,n_=`application/vnd.github.v3+json`,r_=`https://www.sliccy.com/skills/catalog.json`;function i_(e){if(!(!e||!e.trim()))return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function a_(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:i_(e.apps),tasks:i_(e.tasks),role:i_(e.role),purpose:i_(e.purpose)},priority:n}})}var o_={apps:3,tasks:2,role:1,purpose:1};function s_(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*o_.apps,r.push(`apps(${i.join(`, `)})`));let a=(e.affinity.tasks??[]).filter(e=>t.tasks.includes(e));return a.length&&(n+=a.length*o_.tasks,r.push(`tasks(${a.join(`, `)})`)),(e.affinity.role??[]).includes(t.role)&&(n+=o_.role,r.push(`role(${t.role})`)),(e.affinity.purpose??[]).includes(t.purpose)&&(n+=o_.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 c_(e){let t=`upskill ${e.repo}`;return e.path&&(t+=` --path ${e.path}`),e.skill&&(t+=` --skill ${e.skill}`),t}async function l_(e){let t=new Set;try{let n=await e.readDir($g);for(let e of n)e.type===`directory`&&t.add(e.name)}catch{}try{let n=await e.readTextFile(`/${N}/${F}`),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 u_;function d_(){return u_||=I.create({dbName:e_}),u_}async function f_(){try{return(await(await d_()).readTextFile(t_)).trim()||void 0}catch{return}}function p_(e,t=n_){let n={Accept:t,"User-Agent":`slicc-upskill`};return e&&(n.Authorization=`Bearer ${e}`),n}async function m_(e){let t=await f_();return{hasToken:!!t,request:(n,r=n_)=>e(n,{headers:p_(t,r)})}}function h_(e,t){if(!e)return;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r}function g_(e){let t=Ea(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,t,n){let r=g_(e.body),i=r?` GitHub said: ${r}`:``,a=h_(e.headers,`retry-after`),o=h_(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 v_(){return`Discovery roots: /workspace/skills plus accessible **/.agents/skills/* and **/.claude/skills/* anywhere in the VFS.
1732
- `}function y_(){return`Only native /workspace/skills entries are install-managed; compatibility-discovered .agents/.claude skills remain read-only.
1733
- `}function b_(e){switch(e){case`native`:return`native`;case`agents`:return`.agents`;case`claude`:return`.claude`}}function x_(e){return e.source===`native`}function S_(e){return x_(e)?e.installed&&e.installedVersion?`installed (v${e.installedVersion})`:`available`:e.installed&&e.installedVersion?`compatibility (state v${e.installedVersion})`:`compatibility (read-only)`}function C_(e){return x_(e)?`install-managed (/workspace/skills)`:`compatibility-only (read-only)`}function w_(e,t){let n=`${t}:\n\n`;n+=` NAME VERSION SOURCE STATUS
1738
+ `,exitCode:1})}function i_(e={}){let t=[Ap({getJshCommands:e.getJshCommands}),im(),rh(e.browserAPI,e.fs),Bm(),sm(e),mg(),fh(),ah(`sqlite3`),ah(`sqllite`),Im(),eh(`python3`),eh(`python`),hh(),Sh(),Th(),Ih(),Ym(`pdftk`),Ym(`pdf`),Np(`convert`),Np(`magick`),dg({fs:e.fs,scriptCatalog:e.scriptCatalog}),sh(),uh(),Rh(),Uh(),og({fs:e.fs}),yg(),Eg(),Dg(),Og(`xclip`),Og(`xsel`),Ng(),Rg(),zg(),n_(e.fs),Ge(),r_()];return typeof chrome<`u`&&chrome?.runtime?.id&&t.push(Bg()),e.fs&&t.push(...Lf.map(t=>Dp(t,e.browserAPI,e.fs))),t}var a_=`https://wry-manatee-359.convex.site/api/v1`,o_=`https://api.tessl.io`,s_=`/workspace/skills`,c_=`slicc-fs-global`,l_=`/workspace/.git/github-token`,u_=`application/vnd.github.v3+json`,d_=`https://www.sliccy.com/skills/catalog.json`;function f_(e){if(!(!e||!e.trim()))return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function p_(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:f_(e.apps),tasks:f_(e.tasks),role:f_(e.role),purpose:f_(e.purpose)},priority:n}})}var m_={apps:3,tasks:2,role:1,purpose:1};function h_(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*m_.apps,r.push(`apps(${i.join(`, `)})`));let a=(e.affinity.tasks??[]).filter(e=>t.tasks.includes(e));return a.length&&(n+=a.length*m_.tasks,r.push(`tasks(${a.join(`, `)})`)),(e.affinity.role??[]).includes(t.role)&&(n+=m_.role,r.push(`role(${t.role})`)),(e.affinity.purpose??[]).includes(t.purpose)&&(n+=m_.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 g_(e){let t=`upskill ${e.repo}`;return e.path&&(t+=` --path ${e.path}`),e.skill&&(t+=` --skill ${e.skill}`),t}async function __(e){let t=new Set;try{let n=await e.readDir(s_);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 v_;function y_(){return v_||=L.create({dbName:c_}),v_}async function b_(){try{return(await(await y_()).readTextFile(l_)).trim()||void 0}catch{return}}function x_(e,t=u_){let n={Accept:t,"User-Agent":`slicc-upskill`};return e&&(n.Authorization=`Bearer ${e}`),n}async function S_(e){let t=await b_();return{hasToken:!!t,request:(n,r=u_)=>e(n,{headers:x_(t,r)})}}function C_(e,t){if(!e)return;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r}function w_(e){let t=Ea(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 T_(e,t,n){let r=w_(e.body),i=r?` GitHub said: ${r}`:``,a=C_(e.headers,`retry-after`),o=C_(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 E_(){return`Discovery roots: /workspace/skills plus accessible **/.agents/skills/* and **/.claude/skills/* anywhere in the VFS.
1739
+ `}function D_(){return`Only native /workspace/skills entries are install-managed; compatibility-discovered .agents/.claude skills remain read-only.
1740
+ `}function O_(e){switch(e){case`native`:return`native`;case`agents`:return`.agents`;case`claude`:return`.claude`}}function k_(e){return e.source===`native`}function A_(e){return k_(e)?e.installed&&e.installedVersion?`installed (v${e.installedVersion})`:`available`:e.installed&&e.installedVersion?`compatibility (state v${e.installedVersion})`:`compatibility (read-only)`}function j_(e){return k_(e)?`install-managed (/workspace/skills)`:`compatibility-only (read-only)`}function M_(e,t){let n=`${t}:\n\n`;n+=` NAME VERSION SOURCE STATUS
1734
1741
  `,n+=` ─────────────────────────────────────────────────────────────
1735
- `;for(let t of e)n+=` ${t.name.padEnd(20)} ${t.manifest.version.padEnd(10)} ${b_(t.source).padEnd(9)} ${S_(t)}\n`;return n+=`\n${v_()}`,n+=y_(),n}function T_(e){let t=`Skill: ${e.manifest.skill}\n`;if(t+=`Version: ${e.manifest.version}\n`,t+=`Description: ${e.manifest.description||`(none)`}\n`,t+=`Source: ${b_(e.source)}\n`,t+=`Source root: ${e.sourceRoot}\n`,t+=`Management: ${C_(e)}\n`,t+=`Status: ${S_(e)}\n`,e.skillFilePath&&(t+=`Instructions: ${e.skillFilePath}\n`),e.shadowedPaths?.length){t+=`Shadowed paths:
1736
- `;for(let n of e.shadowedPaths)t+=` - ${n}\n`}return t}function E_(e,t){return`${e}: "${t.name}" is discoverable from ${t.sourceRoot} but remains compatibility-only/read-only. Only native /workspace/skills entries are install-managed.\n`}function D_(){return{stdout:`usage: upskill <command> [options]
1742
+ `;for(let t of e)n+=` ${t.name.padEnd(20)} ${t.manifest.version.padEnd(10)} ${O_(t.source).padEnd(9)} ${A_(t)}\n`;return n+=`\n${E_()}`,n+=D_(),n}function N_(e){let t=`Skill: ${e.manifest.skill}\n`;if(t+=`Version: ${e.manifest.version}\n`,t+=`Description: ${e.manifest.description||`(none)`}\n`,t+=`Source: ${O_(e.source)}\n`,t+=`Source root: ${e.sourceRoot}\n`,t+=`Management: ${j_(e)}\n`,t+=`Status: ${A_(e)}\n`,e.skillFilePath&&(t+=`Instructions: ${e.skillFilePath}\n`),e.shadowedPaths?.length){t+=`Shadowed paths:
1743
+ `;for(let n of e.shadowedPaths)t+=` - ${n}\n`}return t}function P_(e,t){return`${e}: "${t.name}" is discoverable from ${t.sourceRoot} but remains compatibility-only/read-only. Only native /workspace/skills entries are install-managed.\n`}function F_(){return{stdout:`usage: upskill <command> [options]
1737
1744
 
1738
1745
  Install skills from GitHub repositories, ClawHub, or Tessl registry.
1739
1746
 
@@ -1746,7 +1753,7 @@ Commands:
1746
1753
  <clawhub-url> Install skill from ClawHub URL
1747
1754
  tessl:<name> Install skill from Tessl registry
1748
1755
 
1749
- ${v_()}${y_()}
1756
+ ${E_()}${D_()}
1750
1757
 
1751
1758
  GitHub Installation:
1752
1759
  upskill owner/repo List available skills in repo
@@ -1787,20 +1794,20 @@ Examples:
1787
1794
  upskill aemcoder/skills@fix/stateless-tab-targeting --all
1788
1795
  upskill https://clawhub.ai/arun-8687/tavily-search
1789
1796
  upskill tessl:postgres-pro
1790
- `,stderr:``,exitCode:0}}async function O_(e,t){let n=await t(`${Zg}/search?q=${encodeURIComponent(e)}`,{headers:{Accept:`application/json`}});if(n.status!==200)throw Error(`ClawHub returned HTTP ${n.status}`);let r=Da(n.body);return r.results?r.results.map(e=>({name:e.slug,displayName:e.displayName||e.slug,summary:e.summary||``,source:`clawhub`,qualityScore:null,installHint:`upskill clawhub:${e.slug}`})):[]}function k_(e){let t=e.match(/github\.com\/([^\/?#]+)\/([^\/?#]+)/);return t?{owner:t[1],repo:t[2].replace(/\.git$/,``)}:null}async function A_(e,t){let n=await t(`${Qg}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=20`,{headers:{Accept:`application/json`}});if(n.status!==200)throw Error(`Tessl returned HTTP ${n.status}`);let r=Da(n.body);if(!r.data)return[];let i=new Map;for(let e of r.data){if(e.type!==`skill`)continue;let t=e.attributes,n=k_(t.sourceUrl),r=n?`${n.owner}/${n.repo}`:void 0,a=t.scores.aggregate==null?null:Math.round(t.scores.aggregate*100),o=t.sourceUrl||e.id,s=i.get(o);if(s&&s.qualityScore!=null&&a!=null&&s.qualityScore>=a)continue;let c=t.path.replace(/\/SKILL\.md$/i,``),l=c.split(`/`).pop()||t.name,u=n?`upskill ${n.owner}/${n.repo} --path ${c.split(`/`).slice(0,-1).join(`/`)||`.`} --skill ${l}`:`upskill tessl:${t.name}`;i.set(o,{name:t.name,displayName:t.name,summary:t.description||``,source:`tessl`,qualityScore:a,installHint:u,featured:t.featured,sourceRepo:r})}return Array.from(i.values())}var j_=10;async function M_(e,t,n=1){let[r,i]=await Promise.allSettled([O_(e,t),A_(e,t)]),a=r.status===`fulfilled`?r.value:[],o=i.status===`fulfilled`?i.value:[];if(a.length===0&&o.length===0){let t=``;return r.status===`rejected`&&i.status===`rejected`&&(t=`upskill: both registries failed to respond
1791
- `),{stdout:`No skills found for "${e}"\n\nTry a different search term or browse https://clawhub.ai or https://tessl.io/registry\n`,stderr:t,exitCode:+!!t}}let s=[],c=0,l=0;for(;c<o.length&&c<3;)s.push(o[c++]);for(;l<a.length||c<o.length;)l<a.length&&s.push(a[l++]),c<o.length&&s.push(o[c++]);let u=s.length,d=Math.ceil(u/j_),f=Math.max(1,Math.min(n,d)),p=(f-1)*j_,m=s.slice(p,p+j_),h=`Search results for "${e}" (page ${f}/${d}, ${u} total):\n\n`;for(let e of m){let t=e.qualityScore==null?` `:String(e.qualityScore).padStart(3),n=`[${e.source}]`,r=e.sourceRepo?` ${e.sourceRepo}`:``;h+=` ${e.name.padEnd(30)} ${t} ${n.padEnd(10)}${r}\n`,e.summary&&(h+=` ${e.summary}\n`),h+=`
1797
+ `,stderr:``,exitCode:0}}async function I_(e,t){let n=await t(`${a_}/search?q=${encodeURIComponent(e)}`,{headers:{Accept:`application/json`}});if(n.status!==200)throw Error(`ClawHub returned HTTP ${n.status}`);let r=Da(n.body);return r.results?r.results.map(e=>({name:e.slug,displayName:e.displayName||e.slug,summary:e.summary||``,source:`clawhub`,qualityScore:null,installHint:`upskill clawhub:${e.slug}`})):[]}function L_(e){let t=e.match(/github\.com\/([^\/?#]+)\/([^\/?#]+)/);return t?{owner:t[1],repo:t[2].replace(/\.git$/,``)}:null}async function R_(e,t){let n=await t(`${o_}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=20`,{headers:{Accept:`application/json`}});if(n.status!==200)throw Error(`Tessl returned HTTP ${n.status}`);let r=Da(n.body);if(!r.data)return[];let i=new Map;for(let e of r.data){if(e.type!==`skill`)continue;let t=e.attributes,n=L_(t.sourceUrl),r=n?`${n.owner}/${n.repo}`:void 0,a=t.scores.aggregate==null?null:Math.round(t.scores.aggregate*100),o=t.sourceUrl||e.id,s=i.get(o);if(s&&s.qualityScore!=null&&a!=null&&s.qualityScore>=a)continue;let c=t.path.replace(/\/SKILL\.md$/i,``),l=c.split(`/`).pop()||t.name,u=n?`upskill ${n.owner}/${n.repo} --path ${c.split(`/`).slice(0,-1).join(`/`)||`.`} --skill ${l}`:`upskill tessl:${t.name}`;i.set(o,{name:t.name,displayName:t.name,summary:t.description||``,source:`tessl`,qualityScore:a,installHint:u,featured:t.featured,sourceRepo:r})}return Array.from(i.values())}var z_=10;async function B_(e,t,n=1){let[r,i]=await Promise.allSettled([I_(e,t),R_(e,t)]),a=r.status===`fulfilled`?r.value:[],o=i.status===`fulfilled`?i.value:[];if(a.length===0&&o.length===0){let t=``;return r.status===`rejected`&&i.status===`rejected`&&(t=`upskill: both registries failed to respond
1798
+ `),{stdout:`No skills found for "${e}"\n\nTry a different search term or browse https://clawhub.ai or https://tessl.io/registry\n`,stderr:t,exitCode:+!!t}}let s=[],c=0,l=0;for(;c<o.length&&c<3;)s.push(o[c++]);for(;l<a.length||c<o.length;)l<a.length&&s.push(a[l++]),c<o.length&&s.push(o[c++]);let u=s.length,d=Math.ceil(u/z_),f=Math.max(1,Math.min(n,d)),p=(f-1)*z_,m=s.slice(p,p+z_),h=`Search results for "${e}" (page ${f}/${d}, ${u} total):\n\n`;for(let e of m){let t=e.qualityScore==null?` `:String(e.qualityScore).padStart(3),n=`[${e.source}]`,r=e.sourceRepo?` ${e.sourceRepo}`:``;h+=` ${e.name.padEnd(30)} ${t} ${n.padEnd(10)}${r}\n`,e.summary&&(h+=` ${e.summary}\n`),h+=`
1792
1799
  `}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:
1793
1800
  `,a.length>0&&(h+=` From ClawHub: upskill clawhub:<slug>
1794
1801
  `),o.length>0&&(h+=` From Tessl: upskill <owner/repo> --skill <name>
1795
- `),{stdout:h,stderr:``,exitCode:0}}async function N_(e,t,n,r=!1,i){try{let a=`${$g}/${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=`${Zg}/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=Sa(o);l||=Oa(s.body);let u;try{u=M(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=P_(u,i);return await H_(),{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 P_(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=F_(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 F_(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 I_(e,t){let n=await t(`${Qg}/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=Da(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=k_(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 L_(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`?L_(e,t,n,`master`):{status:`not_found`};if(a.status!==200)return{status:`error`,message:`codeload returned HTTP ${a.status}`};let o=Sa(i);o||=Oa(a.body);try{return{status:`ok`,files:M(o)}}catch(e){return{status:`error`,message:`failed to unzip: ${e instanceof Error?e.message:String(e)}`}}}function R_(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 z_(e,t,n,r,i,a){if(i){let n=await L_(e,t,i,a);if(n.status===`ok`){let e=R_(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(__(l,`${e}/${t}${r?`/${r}`:``}`,n.hasToken));let u=Da(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 B_(e,t,n,r,i,a,o=!1,s,c){try{let l=`${$g}/${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 L_(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=R_(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 K_(),await W_(),{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: ${__(f,`${e}/${t}/${n}`,a.hasToken)}\n`,exitCode:1};let p=Da(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(__(n,`${e}/${t}/${o.path}`,a.hasToken));let s=Sa(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(__(l,`${e}/${t}/${o.path}`,a.hasToken));let u=Da(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 H_(),{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 V_(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 H_(){await K_(),await W_()}async function U_(e,t,n,r,i=!1){let a=`${$g}/${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 W_(){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 G_(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 K_(){try{if(typeof window>`u`)return;let e=window.__slicc_sprinkleManager;e&&typeof e.openNewAutoOpenSprinkles==`function`&&await e.openNewAutoOpenSprinkles()}catch{}}async function q_(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.
1796
- `,exitCode:1};let i,a;try{let[n,r]=await Promise.all([(async()=>{let e=await t(r_,{headers:{Accept:`application/json`}});if(e.status!==200)throw Error(`HTTP ${e.status}`);return a_(Da(e.body).data)})(),l_(e)]);i=n,a=r}catch(e){return{stdout:``,stderr:`upskill: failed to fetch skill catalog from ${r_}: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let o=s_(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.
1797
- `,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 L_(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=R_(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){let e=`skill "${o.skill}" not found in ${n}`;f.push({ok:!1,name:t.entry.name,error:e}),i++,((Date.now()-a)/1e3).toFixed(1);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}c=e,l=o.skill}else c=o.path?o.path.replace(/^\/|\/$/g,``):``,l=t.entry.name;let u=Date.now(),m=await U_(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 H_()),{stdout:s,stderr:c,exitCode:+!!c}}let s=`Recommended skills for you:
1802
+ `),{stdout:h,stderr:``,exitCode:0}}async function V_(e,t,n,r=!1,i){try{let a=`${s_}/${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=`${a_}/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=Sa(o);l||=Oa(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=H_(u,i);return await X_(),{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 H_(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=U_(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 U_(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 W_(e,t){let n=await t(`${o_}/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=Da(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=L_(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 G_(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`?G_(e,t,n,`master`):{status:`not_found`};if(a.status!==200)return{status:`error`,message:`codeload returned HTTP ${a.status}`};let o=Sa(i);o||=Oa(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 K_(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 q_(e,t,n,r,i,a){if(i){let n=await G_(e,t,i,a);if(n.status===`ok`){let e=K_(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(T_(l,`${e}/${t}${r?`/${r}`:``}`,n.hasToken));let u=Da(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 J_(e,t,n,r,i,a,o=!1,s,c){try{let l=`${s_}/${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 G_(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=K_(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 ev(),await Q_(),{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: ${T_(f,`${e}/${t}/${n}`,a.hasToken)}\n`,exitCode:1};let p=Da(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(T_(n,`${e}/${t}/${o.path}`,a.hasToken));let s=Sa(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(T_(l,`${e}/${t}/${o.path}`,a.hasToken));let u=Da(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 X_(),{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 Y_(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 X_(){await ev(),await Q_()}async function Z_(e,t,n,r,i=!1){let a=`${s_}/${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 Q_(){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 $_(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 ev(){try{if(typeof window>`u`)return;let e=window.__slicc_sprinkleManager;e&&typeof e.openNewAutoOpenSprinkles==`function`&&await e.openNewAutoOpenSprinkles()}catch{}}async function tv(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.
1803
+ `,exitCode:1};let i,a;try{let[n,r]=await Promise.all([(async()=>{let e=await t(d_,{headers:{Accept:`application/json`}});if(e.status!==200)throw Error(`HTTP ${e.status}`);return p_(Da(e.body).data)})(),__(e)]);i=n,a=r}catch(e){return{stdout:``,stderr:`upskill: failed to fetch skill catalog from ${d_}: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let o=h_(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.
1804
+ `,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 G_(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=K_(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){let e=`skill "${o.skill}" not found in ${n}`;f.push({ok:!1,name:t.entry.name,error:e}),i++,((Date.now()-a)/1e3).toFixed(1);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}c=e,l=o.skill}else c=o.path?o.path.replace(/^\/|\/$/g,``):``,l=t.entry.name;let u=Date.now(),m=await Z_(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 X_()),{stdout:s,stderr:c,exitCode:+!!c}}let s=`Recommended skills for you:
1798
1805
 
1799
- `,c=0;for(let e of o){c++;let t=c_(e.entry.source);s+=` ${c}. ${e.entry.displayName.padEnd(35)} score: ${Math.round(e.score)}\n`,s+=` ${e.entry.description}\n`,s+=` Match: ${e.matchReasons.join(`, `)}\n`,s+=` Install: ${t}\n\n`}return s+=`To install all recommended: upskill recommendations --install
1800
- `,{stdout:s,stderr:``,exitCode:0}}function J_(e,t){return z(`upskill`,async(n,r)=>{if(n.length===0||n.includes(`--help`)||n.includes(`-h`))return D_();let i=[],a,o=!1,s=!1,c=!1,l=``,u,d=``,f=1,p=0;for(;p<n.length;){let r=n[p];if(r===`search`){let e=n.slice(p+1),t=e.indexOf(`--page`);t>=0&&(f=parseInt(e[t+1],10)||1,e.splice(t,2)),d=e.join(` `);break}else if(r===`recommendations`)return q_(e,t,n.includes(`--install`));else if(r===`list`){let t=await(await v(()=>import(`./skills-DuL04FMa.js`),__vite__mapDeps([17,18,19,20,1,15]))).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${v_()}${y_()}`,stderr:``,exitCode:0}:{stdout:w_(t,`Discoverable local skills`),stderr:``,exitCode:0}}else if(r===`info`||r===`read`){let t=n[p+1];if(!t)return{stdout:``,stderr:`upskill: ${r} requires a skill name\n`,exitCode:1};let i=await v(()=>import(`./skills-DuL04FMa.js`),__vite__mapDeps([17,18,19,20,1,15]));if(r===`info`){let n=await i.getSkillInfo(e,t);return n?{stdout:T_(n),stderr:``,exitCode:0}:{stdout:``,stderr:`upskill: skill "${t}" not found\n`,exitCode:1}}else{let n=await i.readSkillInstructions(e,t);return n===null?{stdout:``,stderr:`upskill: no SKILL.md found for "${t}"\n`,exitCode:1}:{stdout:n+`
1806
+ `,c=0;for(let e of o){c++;let t=g_(e.entry.source);s+=` ${c}. ${e.entry.displayName.padEnd(35)} score: ${Math.round(e.score)}\n`,s+=` ${e.entry.description}\n`,s+=` Match: ${e.matchReasons.join(`, `)}\n`,s+=` Install: ${t}\n\n`}return s+=`To install all recommended: upskill recommendations --install
1807
+ `,{stdout:s,stderr:``,exitCode:0}}function nv(e,t){return z(`upskill`,async(n,r)=>{if(n.length===0||n.includes(`--help`)||n.includes(`-h`))return F_();let i=[],a,o=!1,s=!1,c=!1,l=``,u,d=``,f=1,p=0;for(;p<n.length;){let r=n[p];if(r===`search`){let e=n.slice(p+1),t=e.indexOf(`--page`);t>=0&&(f=parseInt(e[t+1],10)||1,e.splice(t,2)),d=e.join(` `);break}else if(r===`recommendations`)return tv(e,t,n.includes(`--install`));else if(r===`list`){let t=await(await v(()=>import(`./skills-DuL04FMa.js`),__vite__mapDeps([17,18,19,20,1,15]))).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${E_()}${D_()}`,stderr:``,exitCode:0}:{stdout:M_(t,`Discoverable local skills`),stderr:``,exitCode:0}}else if(r===`info`||r===`read`){let t=n[p+1];if(!t)return{stdout:``,stderr:`upskill: ${r} requires a skill name\n`,exitCode:1};let i=await v(()=>import(`./skills-DuL04FMa.js`),__vite__mapDeps([17,18,19,20,1,15]));if(r===`info`){let n=await i.getSkillInfo(e,t);return n?{stdout:N_(n),stderr:``,exitCode:0}:{stdout:``,stderr:`upskill: skill "${t}" not found\n`,exitCode:1}}else{let n=await i.readSkillInstructions(e,t);return n===null?{stdout:``,stderr:`upskill: no SKILL.md found for "${t}"\n`,exitCode:1}:{stdout:n+`
1801
1808
  `,stderr:``,exitCode:0}}}else if(r===`--skill`)i.push(n[++p]);else if(r===`--path`||r===`-p`)a=n[++p];else if(r===`--list`)o=!0;else if(r===`--all`)s=!0;else if(r===`--force`)c=!0;else if(r===`--branch`||r===`-b`){let e=n[p+1];if(!e||e.startsWith(`-`))return{stdout:``,stderr:`upskill: --branch requires a value
1802
- `,exitCode:1};u=n[++p]}else r.startsWith(`-`)||(l=r);p++}if(d)return M_(d,t,f);if(!l)return D_();let m=V_(l);if(m){let n=r.getRegisteredCommands?.()??[];return N_(m,e,t,c,n)}if(l.startsWith(`tessl:`)){let n=l.slice(6);if(!n)return{stdout:``,stderr:`upskill: tessl: requires a skill name
1803
- `,exitCode:1};let r=await I_(n,t);if(`error`in r)return{stdout:``,stderr:`upskill: ${r.error}\n`,exitCode:1};let i=await m_(t);return B_(r.owner,r.repo,r.skillPath,r.skillName,e,i,c,t)}let h=G_(l);if(h){let{owner:n,repo:r}=h,d=u??h.branch,f=await m_(t),p=await z_(n,r,f,a,t,d);if(p.error)return{stdout:``,stderr:`upskill: failed to list skills: ${p.error}\n`,exitCode:1};if(p.skills.length===0)return{stdout:`No skills found in ${n}/${r}${a?`/`+a:``}\n`,stderr:``,exitCode:0};if(o){let e=`Available skills in ${n}/${r}:\n\n`;for(let t of p.skills)e+=` ${t.name.padEnd(30)} ${t.path}\n`;return e+=`\nFound ${p.skills.length} skill(s)\n`,e+=`\nTo install: upskill ${l} --skill <name>\n`,e+=`To install all: upskill ${l} --all\n`,{stdout:e,stderr:``,exitCode:0}}let m=p.skills;if(i.length>0){m=p.skills.filter(e=>i.includes(e.name));for(let e of i)if(!p.skills.find(t=>t.name===e))return{stdout:``,stderr:`upskill: skill "${e}" not found in ${n}/${r}\n`,exitCode:1}}else if(!s){let e=`Available skills in ${n}/${r}:\n\n`;for(let t of p.skills)e+=` ${t.name.padEnd(30)} ${t.path}\n`;return e+=`\nFound ${p.skills.length} skill(s)\n`,e+=`\nTo install specific skills: upskill ${l} --skill <name>\n`,e+=`To install all: upskill ${l} --all\n`,{stdout:e,stderr:``,exitCode:0}}let g=``,_=``,v=0,y=m.length,b=Date.now();if(y>1){let i=await L_(n,r,t,d);if(i.status===`not_found`)return{stdout:``,stderr:`upskill: ${d?`branch "${d}" in ${n}/${r}`:`repository ${n}/${r}`} not found\n`,exitCode:1};if(i.status===`error`)return{stdout:``,stderr:`upskill: failed to fetch ${n}/${r}: ${i.message}\n`,exitCode:1};let a=R_(i.files);for(let t=0;t<m.length;t++){let i=m[t],o=await U_(i.path,i.name,a,e,c),s=t+1,l=((Date.now()-b)/1e3).toFixed(1),u=(Date.now()-b)/s,d=Math.round((y-s)*u/1e3),f=s<y?` (~${d}s remaining)`:``;o.ok?(g+=`[${s}/${y}] Installed "${i.name}" from ${n}/${r} (${l}s)${f}\n`,v++):(g+=`[${s}/${y}] Failed "${i.name}": ${o.error}${f}\n`,_+=`upskill: ${o.error}\n`)}}else for(let i of m){let a=await B_(n,r,i.path,i.name,e,f,c,t,d);a.exitCode===0?(g+=a.stdout,v++):_+=a.stderr}let x=((Date.now()-b)/1e3).toFixed(1);return v>0&&(g+=`\nInstalled ${v} skill(s)${y>1?` in ${x}s`:``}\n`,await H_()),{stdout:g,stderr:_,exitCode:+!!_}}return{stdout:``,stderr:`upskill: unrecognized source "${l}"\n\nExpected: owner/repo, clawhub:<slug>, tessl:<name>, or https://clawhub.ai/user/skill\n`,exitCode:1}})}function Y_(e){return z(`skill`,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return{stdout:`usage: skill <command> [options]
1809
+ `,exitCode:1};u=n[++p]}else r.startsWith(`-`)||(l=r);p++}if(d)return B_(d,t,f);if(!l)return F_();let m=Y_(l);if(m){let n=r.getRegisteredCommands?.()??[];return V_(m,e,t,c,n)}if(l.startsWith(`tessl:`)){let n=l.slice(6);if(!n)return{stdout:``,stderr:`upskill: tessl: requires a skill name
1810
+ `,exitCode:1};let r=await W_(n,t);if(`error`in r)return{stdout:``,stderr:`upskill: ${r.error}\n`,exitCode:1};let i=await S_(t);return J_(r.owner,r.repo,r.skillPath,r.skillName,e,i,c,t)}let h=$_(l);if(h){let{owner:n,repo:r}=h,d=u??h.branch,f=await S_(t),p=await q_(n,r,f,a,t,d);if(p.error)return{stdout:``,stderr:`upskill: failed to list skills: ${p.error}\n`,exitCode:1};if(p.skills.length===0)return{stdout:`No skills found in ${n}/${r}${a?`/`+a:``}\n`,stderr:``,exitCode:0};if(o){let e=`Available skills in ${n}/${r}:\n\n`;for(let t of p.skills)e+=` ${t.name.padEnd(30)} ${t.path}\n`;return e+=`\nFound ${p.skills.length} skill(s)\n`,e+=`\nTo install: upskill ${l} --skill <name>\n`,e+=`To install all: upskill ${l} --all\n`,{stdout:e,stderr:``,exitCode:0}}let m=p.skills;if(i.length>0){m=p.skills.filter(e=>i.includes(e.name));for(let e of i)if(!p.skills.find(t=>t.name===e))return{stdout:``,stderr:`upskill: skill "${e}" not found in ${n}/${r}\n`,exitCode:1}}else if(!s){let e=`Available skills in ${n}/${r}:\n\n`;for(let t of p.skills)e+=` ${t.name.padEnd(30)} ${t.path}\n`;return e+=`\nFound ${p.skills.length} skill(s)\n`,e+=`\nTo install specific skills: upskill ${l} --skill <name>\n`,e+=`To install all: upskill ${l} --all\n`,{stdout:e,stderr:``,exitCode:0}}let g=``,_=``,v=0,y=m.length,b=Date.now();if(y>1){let i=await G_(n,r,t,d);if(i.status===`not_found`)return{stdout:``,stderr:`upskill: ${d?`branch "${d}" in ${n}/${r}`:`repository ${n}/${r}`} not found\n`,exitCode:1};if(i.status===`error`)return{stdout:``,stderr:`upskill: failed to fetch ${n}/${r}: ${i.message}\n`,exitCode:1};let a=K_(i.files);for(let t=0;t<m.length;t++){let i=m[t],o=await Z_(i.path,i.name,a,e,c),s=t+1,l=((Date.now()-b)/1e3).toFixed(1),u=(Date.now()-b)/s,d=Math.round((y-s)*u/1e3),f=s<y?` (~${d}s remaining)`:``;o.ok?(g+=`[${s}/${y}] Installed "${i.name}" from ${n}/${r} (${l}s)${f}\n`,v++):(g+=`[${s}/${y}] Failed "${i.name}": ${o.error}${f}\n`,_+=`upskill: ${o.error}\n`)}}else for(let i of m){let a=await J_(n,r,i.path,i.name,e,f,c,t,d);a.exitCode===0?(g+=a.stdout,v++):_+=a.stderr}let x=((Date.now()-b)/1e3).toFixed(1);return v>0&&(g+=`\nInstalled ${v} skill(s)${y>1?` in ${x}s`:``}\n`,await X_()),{stdout:g,stderr:_,exitCode:+!!_}}return{stdout:``,stderr:`upskill: unrecognized source "${l}"\n\nExpected: owner/repo, clawhub:<slug>, tessl:<name>, or https://clawhub.ai/user/skill\n`,exitCode:1}})}function rv(e){return z(`skill`,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return{stdout:`usage: skill <command> [options]
1804
1811
 
1805
1812
  Commands:
1806
1813
  list List discoverable skills and management status
@@ -1809,7 +1816,7 @@ Commands:
1809
1816
  install <name> Install a native /workspace/skills skill (apply manifest)
1810
1817
  uninstall <name> Uninstall a native /workspace/skills skill
1811
1818
 
1812
- ${v_()}${y_()}
1819
+ ${E_()}${D_()}
1813
1820
 
1814
1821
  For installing skills from registries or GitHub, use 'upskill':
1815
1822
  upskill search "query" Search ClawHub + Tessl
@@ -1821,12 +1828,12 @@ Examples:
1821
1828
  skill list
1822
1829
  skill info bluebubbles
1823
1830
  skill read bluebubbles
1824
- `,stderr:``,exitCode:0};let r=t[0],i=await v(()=>import(`./skills-DuL04FMa.js`),__vite__mapDeps([17,18,19,20,1,15]));try{switch(r){case`list`:{let t=await i.discoverSkills(e);return t.length===0?{stdout:`No discoverable skills found.\n\n${v_()}${y_()}\nInstall install-managed skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:w_(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
1825
- `,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:T_(r),stderr:``,exitCode:0}:{stdout:``,stderr:`skill: "${n}" not found\n`,exitCode:1}}case`read`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: read requires a skill name
1831
+ `,stderr:``,exitCode:0};let r=t[0],i=await v(()=>import(`./skills-DuL04FMa.js`),__vite__mapDeps([17,18,19,20,1,15]));try{switch(r){case`list`:{let t=await i.discoverSkills(e);return t.length===0?{stdout:`No discoverable skills found.\n\n${E_()}${D_()}\nInstall install-managed skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:M_(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
1832
+ `,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:N_(r),stderr:``,exitCode:0}:{stdout:``,stderr:`skill: "${n}" not found\n`,exitCode:1}}case`read`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: read requires a skill name
1826
1833
  `,exitCode:1};let r=await i.readSkillInstructions(e,n);return r===null?{stdout:``,stderr:`skill: no SKILL.md found for "${n}"\n`,exitCode:1}:{stdout:r+`
1827
1834
  `,stderr:``,exitCode:0}}case`install`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: install requires a skill name
1828
- `,exitCode:1};let r=await i.getSkillInfo(e,n);if(r&&!x_(r))return{stdout:``,stderr:E_(`skill`,r),exitCode:1};let a=await i.applySkill(e,n);return a.success?(await K_(),await W_(),{stdout:`Installed skill "${a.skill}" v${a.version}\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`skill: ${a.error}\n`,exitCode:1}}case`uninstall`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: uninstall requires a skill name
1829
- `,exitCode:1};let r=await i.getSkillInfo(e,n);if(r&&!x_(r))return{stdout:``,stderr:`skill: "${n}" is a compatibility skill discovered from ${r.sourceRoot} (read-only). Only native /workspace/skills entries can be uninstalled.\n`,exitCode:1};let a=await i.uninstallSkill(e,n);return a.success?{stdout:`Uninstalled skill "${a.skill}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`skill: ${a.error}\n`,exitCode:1}}default:return{stdout:``,stderr:`skill: unknown command "${r}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`skill: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function X_(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}var Z_=class{constructor(e){this.options=e}async execute(e,t){let n=e[0];if(n===`--help`||n===`-h`)return this.help();if(n===`unmount`||n===`-u`){let n=e[1];if(!n)return{stdout:``,stderr:`mount unmount: path required`,exitCode:1};let r=n.startsWith(`/`)?n:`${t.replace(/\/$/,``)}/${n}`;return this.options.fs.unmount(r),{stdout:`Unmounted ${r}\n`,stderr:``,exitCode:0}}if(n===`list`||n===`-l`){let e=this.options.fs.listMounts();return e.length===0?{stdout:`No active mounts
1835
+ `,exitCode:1};let r=await i.getSkillInfo(e,n);if(r&&!k_(r))return{stdout:``,stderr:P_(`skill`,r),exitCode:1};let a=await i.applySkill(e,n);return a.success?(await ev(),await Q_(),{stdout:`Installed skill "${a.skill}" v${a.version}\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`skill: ${a.error}\n`,exitCode:1}}case`uninstall`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: uninstall requires a skill name
1836
+ `,exitCode:1};let r=await i.getSkillInfo(e,n);if(r&&!k_(r))return{stdout:``,stderr:`skill: "${n}" is a compatibility skill discovered from ${r.sourceRoot} (read-only). Only native /workspace/skills entries can be uninstalled.\n`,exitCode:1};let a=await i.uninstallSkill(e,n);return a.success?{stdout:`Uninstalled skill "${a.skill}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`skill: ${a.error}\n`,exitCode:1}}default:return{stdout:``,stderr:`skill: unknown command "${r}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`skill: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function iv(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}var av=class{constructor(e){this.options=e}async execute(e,t){let n=e[0];if(n===`--help`||n===`-h`)return this.help();if(n===`unmount`||n===`-u`){let n=e[1];if(!n)return{stdout:``,stderr:`mount unmount: path required`,exitCode:1};let r=n.startsWith(`/`)?n:`${t.replace(/\/$/,``)}/${n}`;return this.options.fs.unmount(r),{stdout:`Unmounted ${r}\n`,stderr:``,exitCode:0}}if(n===`list`||n===`-l`){let e=this.options.fs.listMounts();return e.length===0?{stdout:`No active mounts
1830
1837
  `,stderr:``,exitCode:0}:{stdout:e.map(e=>e).join(`
1831
1838
  `)+`
1832
1839
  `,stderr:``,exitCode:0}}if(!n)return{stdout:``,stderr:`mount: mount point required
@@ -1834,7 +1841,7 @@ Usage: mount <target-path>
1834
1841
  `,exitCode:1};if(typeof window>`u`||!(`showDirectoryPicker`in window))return{stdout:``,stderr:`mount: File System Access API not available in this environment`,exitCode:1};let r;r=n.startsWith(`/`)?n:`${t.replace(/\/$/,``)}/${n}`,r.length>1&&(r=r.replace(/\/+$/,``));let i=a(),o;if(i){let e=await g({html:`
1835
1842
  <div class="sprinkle-action-card">
1836
1843
  <div class="sprinkle-action-card__header">Mount local directory <span class="sprinkle-badge sprinkle-badge--notice">approval</span></div>
1837
- <div class="sprinkle-action-card__body">The agent wants to mount a local directory at <code>${X_(r)}</code>. This will give the agent read/write access to files in the directory you select.</div>
1844
+ <div class="sprinkle-action-card__body">The agent wants to mount a local directory at <code>${iv(r)}</code>. This will give the agent read/write access to files in the directory you select.</div>
1838
1845
  <div class="sprinkle-action-card__actions">
1839
1846
  <button class="sprinkle-btn sprinkle-btn--secondary" data-action="deny">Deny</button>
1840
1847
  <button class="sprinkle-btn sprinkle-btn--primary" data-action="approve">Select directory</button>
@@ -1842,7 +1849,7 @@ Usage: mount <target-path>
1842
1849
  </div>
1843
1850
  `,onAction:async e=>{if(e===`approve`)try{return{approved:!0,handle:await window.showDirectoryPicker({mode:`readwrite`})}}catch(e){return e instanceof Error&&e.name===`AbortError`?{cancelled:!0}:{error:e instanceof Error?e.message:String(e)}}return{denied:!0}}});if(!e)return{stdout:``,stderr:`mount: tool UI not available`,exitCode:1};let t=e;if(t.denied)return{stdout:``,stderr:`mount: denied by user`,exitCode:1};if(t.cancelled)return{stdout:``,stderr:`mount: cancelled`,exitCode:1};if(t.error)return{stdout:``,stderr:`mount: ${t.error}`,exitCode:1};if(!t.handle)return{stdout:``,stderr:`mount: no directory selected`,exitCode:1};o=t.handle}else try{o=await window.showDirectoryPicker({mode:`readwrite`})}catch(e){return e instanceof Error&&e.name===`AbortError`?{stdout:``,stderr:`mount: cancelled`,exitCode:1}:{stdout:``,stderr:`mount: ${e instanceof Error?e.message:String(e)}`,exitCode:1}}try{return await this.options.fs.mount(r,o),{stdout:`Mounted '${o.name}' → ${r} (live bridge — reads and writes go to the real filesystem)\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`mount: ${e instanceof Error?e.message:String(e)}`,exitCode:1}}}help(){return{stdout:[`Usage: mount <target-path>`,` mount unmount <path>`,` mount list`,``,`Transparently bridge a real filesystem directory into the virtual filesystem.`,`Opens a directory picker; all reads and writes under <target-path> go directly`,`to the real directory — no copying occurs. Changes are immediately visible on`,`both sides. Mount points must be empty so existing VFS files are not hidden.`,``,`Arguments:`,` <target-path> Mount point in the virtual filesystem (required).`,``,`Sub-commands:`,` unmount <path> Remove a mount point`,` list Show active mount points`,``,`Examples:`,` mount /mnt/myapp # Mount selected dir at /mnt/myapp`,` mount list # Show active mounts`,` mount unmount /mnt/myapp`].join(`
1844
1851
  `)+`
1845
- `,stderr:``,exitCode:0}}},Q_=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 $_(e){let t=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,n=[],r;for(;(r=t.exec(e))!==null;)n.push(r[1]);return[...new Set(n)]}async function ev(e,t,n){return await n.fs.exists(e)?tv(await n.fs.readFile(e),[`node`,e,...t],n):{stdout:``,stderr:`jsh: cannot find script '${e}'\n`,exitCode:127}}async function tv(e,t,n){let r=[],i=[],a=e=>{r.push(typeof e==`string`?e:String(e))},o=e=>{i.push(typeof e==`string`?e:String(e))},s={log:(...e)=>a(`${e.map(Dm).join(` `)}\n`),info:(...e)=>a(`${e.map(Dm).join(` `)}\n`),warn:(...e)=>o(`${e.map(Dm).join(` `)}\n`),error:(...e)=>o(`${e.map(Dm).join(` `)}\n`)},c={argv:t,env:Object.fromEntries(n.env.entries()),cwd:()=>n.cwd,exit:e=>{throw new hm(Number.isFinite(e)?Number(e):0)},stdout:{write:a},stderr:{write:o}},l={readFile:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.readFile(t)},readFileBinary:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.readFileBuffer(t)},writeFile:async(e,t)=>{let r=n.fs.resolvePath(n.cwd,e);await n.fs.writeFile(r,t)},writeFileBinary:async(e,t)=>{let r=n.fs.resolvePath(n.cwd,e),i=new Uint8Array(t.byteLength);i.set(t),await n.fs.writeFile(r,i)},readDir:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.readdir(t)},exists:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.exists(t)},stat:async e=>{let t=n.fs.resolvePath(n.cwd,e),r=await n.fs.stat(t);return{isDirectory:r.isDirectory,isFile:r.isFile,size:r.size}},mkdir:async e=>{let t=n.fs.resolvePath(n.cwd,e);await n.fs.mkdir(t,{recursive:!0})},rm:async e=>{let t=n.fs.resolvePath(n.cwd,e);await n.fs.rm(t,{recursive:!0})},fetchToFile:async(e,t)=>{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=n.fs.resolvePath(n.cwd,t);return await n.fs.writeFile(a,i),i.byteLength}},u=async e=>{if(!n.exec)throw Error(`exec is not available in this runtime`);let t=await n.exec(e,{cwd:n.cwd});return{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode}},d=typeof chrome<`u`&&!!chrome?.runtime?.id;if(!d){let t=$_(e),n=new Set([`fs`,`process`,`buffer`]),r=t.map(e=>e.startsWith(`node:`)?e.slice(5):e).filter(e=>!n.has(e)&&!Q_.has(e)),i=mm.__requireCache??=Object.create(null),a=r.filter(e=>!(e in i));if(a.length>0){let e=await Promise.allSettled(a.map(async e=>{let t=await v(()=>import(`https://esm.sh/`+e),[]);return{id:e,value:t.default===void 0?t:t.default}}));for(let t of e)t.status===`fulfilled`&&(i[t.value.id]=t.value.value)}}let f=e=>{let t=e.startsWith(`node:`)?e.slice(5):e;if(t===`fs`)return l;if(t===`process`)return c;if(t===`buffer`)return{Buffer:globalThis.Buffer};if(t===`path`){let t=mm.__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(Q_.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=mm.__requireCache;if(n&&e in n)return n[e];throw Error(`require('${e}'): module not pre-loaded. Use a string literal so it can be pre-fetched, or use \`await import('https://esm.sh/${e}')\` directly.`)},p={exports:{},filename:t[1]||`<script>`};try{if(d){let r=`
1852
+ `,stderr:``,exitCode:0}}},ov=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 sv(e){let t=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,n=[],r;for(;(r=t.exec(e))!==null;)n.push(r[1]);return[...new Set(n)]}async function cv(e,t,n){return await n.fs.exists(e)?lv(await n.fs.readFile(e),[`node`,e,...t],n):{stdout:``,stderr:`jsh: cannot find script '${e}'\n`,exitCode:127}}async function lv(e,t,n){let r=[],i=[],a=e=>{r.push(typeof e==`string`?e:String(e))},o=e=>{i.push(typeof e==`string`?e:String(e))},s={log:(...e)=>a(`${e.map(Dm).join(` `)}\n`),info:(...e)=>a(`${e.map(Dm).join(` `)}\n`),warn:(...e)=>o(`${e.map(Dm).join(` `)}\n`),error:(...e)=>o(`${e.map(Dm).join(` `)}\n`)},c={argv:t,env:Object.fromEntries(n.env.entries()),cwd:()=>n.cwd,exit:e=>{throw new hm(Number.isFinite(e)?Number(e):0)},stdout:{write:a},stderr:{write:o}},l={readFile:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.readFile(t)},readFileBinary:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.readFileBuffer(t)},writeFile:async(e,t)=>{let r=n.fs.resolvePath(n.cwd,e);await n.fs.writeFile(r,t)},writeFileBinary:async(e,t)=>{let r=n.fs.resolvePath(n.cwd,e),i=new Uint8Array(t.byteLength);i.set(t),await n.fs.writeFile(r,i)},readDir:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.readdir(t)},exists:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.exists(t)},stat:async e=>{let t=n.fs.resolvePath(n.cwd,e),r=await n.fs.stat(t);return{isDirectory:r.isDirectory,isFile:r.isFile,size:r.size}},mkdir:async e=>{let t=n.fs.resolvePath(n.cwd,e);await n.fs.mkdir(t,{recursive:!0})},rm:async e=>{let t=n.fs.resolvePath(n.cwd,e);await n.fs.rm(t,{recursive:!0})},fetchToFile:async(e,t)=>{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=n.fs.resolvePath(n.cwd,t);return await n.fs.writeFile(a,i),i.byteLength}},u=async e=>{if(!n.exec)throw Error(`exec is not available in this runtime`);let t=await n.exec(e,{cwd:n.cwd});return{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode}},d=typeof chrome<`u`&&!!chrome?.runtime?.id;if(!d){let t=sv(e),n=new Set([`fs`,`process`,`buffer`]),r=t.map(e=>e.startsWith(`node:`)?e.slice(5):e).filter(e=>!n.has(e)&&!ov.has(e)),i=mm.__requireCache??=Object.create(null),a=r.filter(e=>!(e in i));if(a.length>0){let e=await Promise.allSettled(a.map(async e=>{let t=await v(()=>import(`https://esm.sh/`+e),[]);return{id:e,value:t.default===void 0?t:t.default}}));for(let t of e)t.status===`fulfilled`&&(i[t.value.id]=t.value.value)}}let f=e=>{let t=e.startsWith(`node:`)?e.slice(5):e;if(t===`fs`)return l;if(t===`process`)return c;if(t===`buffer`)return{Buffer:globalThis.Buffer};if(t===`path`){let t=mm.__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(ov.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=mm.__requireCache;if(n&&e in n)return n[e];throw Error(`require('${e}'): module not pre-loaded. Use a string literal so it can be pre-fetched, or use \`await import('https://esm.sh/${e}')\` directly.`)},p={exports:{},filename:t[1]||`<script>`};try{if(d){let r=`
1846
1853
  const __stdout = [];
1847
1854
  const __stderr = [];
1848
1855
  const __origConsole = { log: console.log, error: console.error, warn: console.warn, info: console.info };
@@ -1938,9 +1945,9 @@ Usage: mount <target-path>
1938
1945
  console.info = __origConsole.info;
1939
1946
  return { stdout: __stdout.join(''), stderr: __stderr.join('') };
1940
1947
  `,i=document.querySelector(`iframe[data-js-tool]`);i||(i=document.createElement(`iframe`),i.style.display=`none`,i.dataset.jsTool=`true`,i.src=chrome.runtime.getURL(`sandbox.html`),document.body.appendChild(i),await new Promise(e=>{i.addEventListener(`load`,()=>e(),{once:!0})}));let a=`jsh-${Date.now()}-${Math.random().toString(36).slice(2)}`,o=e=>{let t=e.data;!t||t.type!==`vfs`||(async()=>{try{let e,r=t.args?.[0]?n.fs.resolvePath(n.cwd,t.args[0]):t.args?.[0];switch(t.op){case`readFile`:e=await n.fs.readFile(r);break;case`readFileBinary`:e=await n.fs.readFileBuffer(r);break;case`writeFile`:await n.fs.writeFile(r,t.args[1]),e=!0;break;case`writeFileBinary`:await n.fs.writeFile(r,t.binaryData??new Uint8Array),e=!0;break;case`readDir`:e=await n.fs.readdir(r);break;case`exists`:e=await n.fs.exists(r);break;case`stat`:{let t=await n.fs.stat(r);e={isDirectory:t.isDirectory,isFile:t.isFile,size:t.size};break}case`mkdir`:await n.fs.mkdir(r,{recursive:!0}),e=!0;break;case`rm`:await n.fs.rm(r,{recursive:!0}),e=!0;break}i.contentWindow.postMessage({type:`vfs_response`,id:t.id,result:e},`*`)}catch(e){let n=e instanceof Error?e.message:String(e);i.contentWindow.postMessage({type:`vfs_response`,id:t.id,error:n},`*`)}})()};window.addEventListener(`message`,o);let s=e=>{let t=e.data;!t||t.type!==`shell_exec`||(async()=>{try{let e=await u(t.command);i.contentWindow.postMessage({type:`shell_exec_response`,id:t.id,result:e},`*`)}catch(e){let n=e instanceof Error?e.message:String(e);i.contentWindow.postMessage({type:`shell_exec_response`,id:t.id,error:n},`*`)}})()};window.addEventListener(`message`,s);let l=e=>{let t=e.data;!t||t.type!==`fetch_proxy`||(async()=>{try{let e={method:t.init?.method??`GET`,cache:`no-store`};t.init?.headers&&(e.headers=t.init.headers),t.init?.body&&![`GET`,`HEAD`].includes(e.method)&&(e.body=t.init.body);let n=await fetch(t.url,e),r=await n.arrayBuffer(),a={};n.headers.forEach((e,t)=>{a[t]=e}),i.contentWindow.postMessage({type:`fetch_proxy_response`,id:t.id,status:n.status,statusText:n.statusText,headers:a,body:new Uint8Array(r)},`*`)}catch(e){let n=e instanceof Error?e.message:String(e);i.contentWindow.postMessage({type:`fetch_proxy_response`,id:t.id,error:n},`*`)}})()};window.addEventListener(`message`,l);let d=await new Promise((e,t)=>{let n,o=t=>{if(t.data?.type===`exec_result`&&t.data.id===a)if(window.removeEventListener(`message`,o),clearTimeout(n),t.data.error)e({stdout:``,stderr:t.data.error+`
1941
- `});else try{let n=JSON.parse(t.data.result);e({stdout:n.stdout||``,stderr:n.stderr||``})}catch{e({stdout:t.data.result||``,stderr:``})}};n=setTimeout(()=>{window.removeEventListener(`message`,o),t(Error(`jsh eval timed out (30s)`))},3e4),window.addEventListener(`message`,o),i.contentWindow.postMessage({type:`exec`,id:a,code:r},`*`)});return window.removeEventListener(`message`,o),window.removeEventListener(`message`,s),window.removeEventListener(`message`,l),{stdout:d.stdout,stderr:d.stderr,exitCode:+!!d.stderr}}let a=Object.getPrototypeOf(async function(){}).constructor;return await new a(`fs`,`process`,`console`,`require`,`module`,`exports`,`__state`,`exec`,`"use strict";\nconst globalThis = __state;\nconst global = __state;\n${e}`)(l,c,s,f,p,p.exports,mm,u),{stdout:r.join(``),stderr:i.join(``),exitCode:0}}catch(e){if(e instanceof hm)return{stdout:r.join(``),stderr:i.join(``),exitCode:e.code};let t=e instanceof Error?e.stack??e.message:String(e);return{stdout:r.join(``),stderr:`${i.join(``)}${t}\n`,exitCode:1}}}function nv(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`){for(r++;r<e.length&&e[r]!==`"`;)n+=e[r],r++;r++}else if(i===`'`){for(r++;r<e.length&&e[r]!==`'`;)n+=e[r],r++;r++}else i===`\\`&&r+1<e.length&&e[r+1]===` `?(n+=` `,r+=2):/\s/.test(i)?(n.length>0&&(t.push(n),n=``),r++):(n+=i,r++)}return n.length>0&&t.push(n),t}var rv=[`/workspace`,`/shared`];async function iv(e){let t=[],n=new Set;for(let r of rv)await e.exists(r)&&await av(e,r,t,n);return t}async function av(e,t,n,r){for await(let i of e.walk(t)){if(!i.endsWith(`.bsh`)||r.has(i))continue;r.add(i);let t=ov(i);if(!t)continue;let a=await e.readFile(i,{encoding:`utf-8`}),o=sv(typeof a==`string`?a:new TextDecoder().decode(a));n.push({path:i,hostnamePattern:t,matchPatterns:o})}}function ov(e){let t=e.split(`/`).pop()??``;if(!t.endsWith(`.bsh`))return null;let n=t.slice(0,-4);return n?n.startsWith(`-.`)?`*`+n.slice(1):n:null}function sv(e){let t=e.split(`
1942
- `).slice(0,10),n=[];for(let e of t){let t=e.match(/^\s*\/\/\s*@match\s+(.+)$/);t&&n.push(t[1].trim())}return n}function cv(e,t){if(t.startsWith(`*.`)){let n=t.slice(1);return e===t.slice(2)||e.endsWith(n)&&e.length>n.length}return e===t}function lv(e,t){try{let n=new URL(e),r=t.match(/^(\*|https?):\/\/([^/]+)(\/.*)?$/);if(!r)return!1;let[,i,a,o]=r;return i!==`*`&&n.protocol.slice(0,-1)!==i||!cv(n.hostname,a)?!1:o?uv(n.pathname+n.search,o):!0}catch{return!1}}function uv(e,t){let n=`^`+t.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`)+`$`;return new RegExp(n).test(e)}function dv(e,t){try{let n=new URL(t);return e.filter(e=>cv(n.hostname,e.hostnamePattern)?e.matchPatterns.length>0?e.matchPatterns.some(e=>lv(t,e)):!0:!1)}catch{return[]}}var fv=[`/workspace`,`/shared`];function pv(e){return new Map(e)}function mv(e){return e.map(e=>({...e,matchPatterns:[...e.matchPatterns]}))}function hv(e){if(e&&typeof e.listMounts==`function`)return e;if(e&&typeof e.getUnderlyingFS==`function`){let t=e.getUnderlyingFS?.();if(t&&typeof t.listMounts==`function`)return t}return null}function gv(e){return(hv(e)?.listMounts?.().length??0)>0}function _v(e){return e?(hv(e)?.listMounts?.()??[]).some(e=>fv.some(t=>e===t||e.startsWith(t+`/`))):!1}var vv=class{jshFs;bshFs;watcher;watcherUnsubs=[];jshCache=null;jshInflight=null;bshCache=null;bshInflight=null;jshGeneration=0;bshGeneration=0;constructor(e){if(this.jshFs=e.jshFs,this.bshFs=e.bshFs,this.watcher=e.watcher??null,this.watcher&&(this.watcherUnsubs.push(this.watcher.watch(`/`,()=>!0,()=>this.invalidateJsh())),this.bshFs))for(let e of fv)this.watcherUnsubs.push(this.watcher.watch(e,()=>!0,()=>this.invalidateBsh()))}dispose(){for(let e of this.watcherUnsubs)e();this.watcherUnsubs.length=0,this.invalidateAll()}invalidateAll(){this.invalidateJsh(),this.invalidateBsh()}invalidateJsh(){this.jshGeneration++,this.jshCache=null,this.jshInflight=null}invalidateBsh(){this.bshGeneration++,this.bshCache=null,this.bshInflight=null}async getJshCommands(){return pv(await this.loadJshCommands())}async getJshCommandNames(){return[...(await this.getJshCommands()).keys()]}async getBshEntries(){return this.bshFs?mv(await this.loadBshEntries()):[]}async findMatchingBshScripts(e){return this.bshFs?mv(dv(await this.loadBshEntries(),e)):[]}shouldCacheJsh(){return!!this.watcher&&!gv(this.jshFs)}shouldCacheBsh(){return!!this.watcher&&!!this.bshFs&&!_v(this.bshFs)}async loadJshCommands(){let e=this.shouldCacheJsh();if(e&&this.jshCache)return this.jshCache;if(!this.jshInflight){let t=this.jshGeneration,n=eg(this.jshFs).then(n=>{let r=pv(n);return e&&this.jshGeneration===t&&(this.jshCache=r),r}).finally(()=>{this.jshInflight===n&&(this.jshInflight=null)});this.jshInflight=n}return this.jshInflight}async loadBshEntries(){if(!this.bshFs)return[];let e=this.shouldCacheBsh();if(e&&this.bshCache)return this.bshCache;if(!this.bshInflight){let t=this.bshGeneration,n=iv(this.bshFs).then(n=>{let r=mv(n);return e&&this.bshGeneration===t&&(this.bshCache=r),r}).finally(()=>{this.bshInflight===n&&(this.bshInflight=null)});this.bshInflight=n}return this.bshInflight}},yv=null,bv=!1;function xv(){return typeof chrome<`u`&&chrome?.runtime?.id?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function Sv(){if(!bv&&!(typeof localStorage<`u`&&localStorage.getItem(`telemetry-disabled`)===`true`))try{typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),yv=(await v(()=>import(`./src-CgSXdUB7.js`),[])).sampleRUM,bv=!0,yv&&yv(`navigate`,{source:typeof document<`u`?document.referrer:``,target:xv()})}catch{}}function Cv(e,t){yv?.(`formsubmit`,{source:e,target:t})}function wv(e){yv?.(`fill`,{source:e})}function Tv(e){yv?.(`viewblock`,{source:e})}function Ev(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 Dv(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?Dv(e.getUnderlyingFS?.()):null}function Ov(e){if(!e)return!0;let t=e.toLowerCase();return t.startsWith(`text/`)||t.includes(`json`)||t.includes(`xml`)||t.includes(`javascript`)||t.includes(`ecmascript`)||t.includes(`html`)||t.includes(`css`)||t.includes(`svg`)}async function kv(e,t){let n=e.headers.get(`content-type`)??``,r=await e.arrayBuffer(),i=new Uint8Array(r);if(!Ov(n)){let e=``;for(let t=0;t<i.length;t+=32768)e+=String.fromCharCode(...i.subarray(t,t+32768));ba(e,i),t&&xa(t,i)}return i}function Av(e){if(e){if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}}function jv(e,t){if(e){if((t?.[`Content-Type`]??t?.[`content-type`]??``).includes(`multipart/form-data`)){let t=Oa(e);return new Blob([t])}return e}}function Mv(e){if(!e)return{};let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();e===`cookie`?t[`X-Proxy-Cookie`]=r:e===`origin`?t[`X-Proxy-Origin`]=r:e===`referer`?t[`X-Proxy-Referer`]=r:e.startsWith(`proxy-`)?t[`X-Proxy-${n}`]=r:t[n]=r}return t}function Nv(e){let t={};for(let[n,r]of Object.entries(e))n.toLowerCase()===`x-proxy-set-cookie`?t[`set-cookie`]=r:t[n]=r;return t}function Pv(){return typeof chrome<`u`&&chrome?.runtime?.id?async(e,t)=>{let n=Av(t?.headers),r=await fetch(e,{method:t?.method??`GET`,headers:n,body:jv(t?.body,n)}),i=await kv(r,e),a={};return r.headers.forEach((e,t)=>{a[t]=e}),{status:r.status,statusText:r.statusText,headers:a,body:i,url:e}}:async(e,t)=>{let n=t?.method??`GET`,r={...Mv(Av(t?.headers)),"X-Target-URL":e},i={method:n,headers:r,cache:`no-store`};t?.body&&![`GET`,`HEAD`].includes(n)&&(i.body=jv(t.body,r));let a=await fetch(`/api/fetch-proxy`,i);if(a.status===502||a.status===400){let e=await a.text(),t=`Proxy error ${a.status}`;try{t=JSON.parse(e).error??t}catch{}throw Error(t)}let o=await kv(a,e),s={};a.headers.forEach((e,t)=>{s[t]=e});let c=Nv(s);return{status:a.status,statusText:a.statusText,headers:c,body:o,url:e}}}var Fv=class{bash;vfsAdapter;gitCommands;mountCommands;terminal=null;fitAddon=null;terminalHost=null;previewHost=null;previewUrls=[];previewStateListener=null;hasPreview=!1;resizeObserver=null;themeObserver=null;currentLine=``;cursorPos=0;history=[];historyIndex=-1;isExecuting=!1;execAbort=null;continuationBuffer=``;lastEnv;cwd;builtinCommandNames;scriptCatalog;ownsScriptCatalog;constructor(e){this.options=e,this.vfsAdapter=new wa(e.fs);let t=e.cwd??`/`,n={HOME:`/`,PATH:`/usr/bin`,USER:`user`,SHELL:`/bin/bash`,PWD:t,...e.env};this.gitCommands=new Af({fs:e.fs,authorName:n.GIT_AUTHOR_NAME??`User`,authorEmail:n.GIT_AUTHOR_EMAIL??`user@example.com`}),this.mountCommands=new Z_({fs:e.fs});let r=e.jshDiscoveryFs??e.fs,i=e.bshDiscoveryFs??e.fs,a=Dv(r)??Dv(i);this.scriptCatalog=e.scriptCatalog??new vv({jshFs:r,bshFs:i,watcher:a}),this.ownsScriptCatalog=!e.scriptCatalog;let o=this.createGitCustomCommand(),s=Xg({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),fs:e.fs,scriptCatalog:this.scriptCatalog,browserAPI:e.browserAPI}),c=this.createMountCustomCommand(),l=Pv(),u=[o,c,Y_(e.fs),J_(e.fs,l),...s];this.bash=new qe({fs:this.vfsAdapter,cwd:t,env:n,fetch:l,customCommands:u});let d=u.map(e=>e.name);this.builtinCommandNames=new Set([...We(),...Ue(),...d]),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...n},this.cwd=t}createGitCustomCommand(){let e=this.gitCommands;return z(`git`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}createMountCustomCommand(){let e=this.mountCommands;return z(`mount`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}getBash(){return this.bash}getCwd(){return this.cwd}getScriptCatalog(){return this.scriptCatalog}getEnv(){return{...this.lastEnv}}async getFilteredJshCommands(){let e=await this.scriptCatalog.getJshCommands(),t=new Map;for(let[n,r]of e)this.builtinCommandNames.has(n)||t.set(n,r);return t}async getJshCommandNames(){return[...(await this.getFilteredJshCommands()).keys()]}async tryJshFallback(e){let t=e.trim(),n=t.indexOf(` `),r=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n+1).trim():``,a=(await this.getFilteredJshCommands()).get(r);if(!a)return null;let o=i?nv(i):[],s=this.options.jshDiscoveryFs??this.options.fs,c;try{let e=await s.readFile(a,{encoding:`utf-8`});c=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${a}'\n`,exitCode:127,env:this.lastEnv}}let l=[`node`,a,...o],u=await tv(c,l,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})});return{stdout:u.stdout,stderr:u.stderr,exitCode:u.exitCode,env:this.lastEnv}}async runCommand(e,t){wv(e.trim().split(/\s+/)[0]||`unknown`);let n={env:this.lastEnv,cwd:this.cwd,signal:t??this.execAbort?.signal},r=await this.bash.exec(e,n);if(r.env&&(this.lastEnv={...r.env}),r.env?.PWD&&(this.cwd=r.env.PWD),r.exitCode===127){let t=await this.tryJshFallback(e);if(t)return t}return r}async mount(e){let t=e??this.options.container;if(!t)throw Error(`No container element provided`);let{Terminal:n}=await v(async()=>{let{Terminal:e}=await import(`./xterm-DHgoOdoP.js`);return{Terminal:e}},[]),{FitAddon:r}=await v(async()=>{let{FitAddon:e}=await import(`./addon-fit-CJBYijzN.js`);return{FitAddon:e}},[]);await v(()=>Promise.resolve({}),__vite__mapDeps([21]));let i=!document.documentElement.classList.contains(`theme-light`),a={background:`#141414`,foreground:`#cfcfcf`,cursor:`#3562ff`,cursorAccent:`#141414`,selectionBackground:`#3562ff40`,selectionForeground:`#ffffff`,black:`#1a1a1a`,red:`#e34850`,green:`#2d9d78`,yellow:`#e68619`,blue:`#3562ff`,magenta:`#a962e8`,cyan:`#2db9be`,white:`#cfcfcf`,brightBlack:`#5a5a5a`,brightRed:`#e34850`,brightGreen:`#2d9d78`,brightYellow:`#e68619`,brightBlue:`#4a75ff`,brightMagenta:`#a962e8`,brightCyan:`#2db9be`,brightWhite:`#ffffff`},o={background:`#f0f0f0`,foreground:`#1a1a1a`,cursor:`#2b54db`,cursorAccent:`#f0f0f0`,selectionBackground:`#2b54db30`,selectionForeground:`#000000`,black:`#1a1a1a`,red:`#d73220`,green:`#268e6c`,yellow:`#d17a00`,blue:`#2b54db`,magenta:`#8839ef`,cyan:`#1a9088`,white:`#e8e8e8`,brightBlack:`#6e6e6e`,brightRed:`#d73220`,brightGreen:`#268e6c`,brightYellow:`#d17a00`,brightBlue:`#1e44c4`,brightMagenta:`#8839ef`,brightCyan:`#1a9088`,brightWhite:`#ffffff`};this.terminal=new n({cursorBlink:!0,fontSize:11,fontFamily:`'Source Code Pro', 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace`,theme:i?a:o,convertEol:!0}),this.themeObserver?.disconnect(),this.themeObserver=new MutationObserver(()=>{if(!this.terminal)return;let e=document.documentElement.classList.contains(`theme-light`);this.terminal.options.theme=e?o:a}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),this.fitAddon=new r,this.terminal.loadAddon(this.fitAddon),t.replaceChildren(),this.terminalHost=document.createElement(`div`),this.terminalHost.className=`terminal-panel__terminal-host`,t.appendChild(this.terminalHost),this.previewHost=document.createElement(`div`),this.previewHost.className=`terminal-panel__preview`,t.appendChild(this.previewHost),this.terminal.open(this.terminalHost),this.fitAddon.fit(),this.resizeObserver?.disconnect(),this.resizeObserver=new ResizeObserver(()=>this.refit()),this.resizeObserver.observe(this.terminalHost),this.terminal.writeln(`\x1B[1mslicc\x1B[0m \x1B[90mshell (powered by just-bash)\x1B[0m`),this.terminal.writeln(`\x1B[90mType "help" for available commands.\x1B[0m
1943
- `),this.showPrompt(),this.setupInputHandler()}async executeCommand(e,t){let n=await this.runCommand(e,t);return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}async executeScriptFile(e,t=[]){return ev(e,t,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})})}refit(){this.fitAddon?.fit()}setPreviewStateListener(e){this.previewStateListener=e,this.previewStateListener?.(this.hasPreview)}async executeCommandInTerminal(e){let t=e.trim();if(!t)return{stdout:``,stderr:``,exitCode:0};if(!this.terminal)return this.executeCommand(t);if(this.isExecuting||this.currentLine.length>0||this.continuationBuffer.length>0)return{stdout:``,stderr:`terminal is busy; finish current input first
1948
+ `});else try{let n=JSON.parse(t.data.result);e({stdout:n.stdout||``,stderr:n.stderr||``})}catch{e({stdout:t.data.result||``,stderr:``})}};n=setTimeout(()=>{window.removeEventListener(`message`,o),t(Error(`jsh eval timed out (30s)`))},3e4),window.addEventListener(`message`,o),i.contentWindow.postMessage({type:`exec`,id:a,code:r},`*`)});return window.removeEventListener(`message`,o),window.removeEventListener(`message`,s),window.removeEventListener(`message`,l),{stdout:d.stdout,stderr:d.stderr,exitCode:+!!d.stderr}}let a=Object.getPrototypeOf(async function(){}).constructor;return await new a(`fs`,`process`,`console`,`require`,`module`,`exports`,`__state`,`exec`,`"use strict";\nconst globalThis = __state;\nconst global = __state;\n${e}`)(l,c,s,f,p,p.exports,mm,u),{stdout:r.join(``),stderr:i.join(``),exitCode:0}}catch(e){if(e instanceof hm)return{stdout:r.join(``),stderr:i.join(``),exitCode:e.code};let t=e instanceof Error?e.stack??e.message:String(e);return{stdout:r.join(``),stderr:`${i.join(``)}${t}\n`,exitCode:1}}}function uv(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`){for(r++;r<e.length&&e[r]!==`"`;)n+=e[r],r++;r++}else if(i===`'`){for(r++;r<e.length&&e[r]!==`'`;)n+=e[r],r++;r++}else i===`\\`&&r+1<e.length&&e[r+1]===` `?(n+=` `,r+=2):/\s/.test(i)?(n.length>0&&(t.push(n),n=``),r++):(n+=i,r++)}return n.length>0&&t.push(n),t}var dv=[`/workspace`,`/shared`];async function fv(e){let t=[],n=new Set;for(let r of dv)await e.exists(r)&&await pv(e,r,t,n);return t}async function pv(e,t,n,r){for await(let i of e.walk(t)){if(!i.endsWith(`.bsh`)||r.has(i))continue;r.add(i);let t=mv(i);if(!t)continue;let a=await e.readFile(i,{encoding:`utf-8`}),o=hv(typeof a==`string`?a:new TextDecoder().decode(a));n.push({path:i,hostnamePattern:t,matchPatterns:o})}}function mv(e){let t=e.split(`/`).pop()??``;if(!t.endsWith(`.bsh`))return null;let n=t.slice(0,-4);return n?n.startsWith(`-.`)?`*`+n.slice(1):n:null}function hv(e){let t=e.split(`
1949
+ `).slice(0,10),n=[];for(let e of t){let t=e.match(/^\s*\/\/\s*@match\s+(.+)$/);t&&n.push(t[1].trim())}return n}function gv(e,t){if(t.startsWith(`*.`)){let n=t.slice(1);return e===t.slice(2)||e.endsWith(n)&&e.length>n.length}return e===t}function _v(e,t){try{let n=new URL(e),r=t.match(/^(\*|https?):\/\/([^/]+)(\/.*)?$/);if(!r)return!1;let[,i,a,o]=r;return i!==`*`&&n.protocol.slice(0,-1)!==i||!gv(n.hostname,a)?!1:o?vv(n.pathname+n.search,o):!0}catch{return!1}}function vv(e,t){let n=`^`+t.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`)+`$`;return new RegExp(n).test(e)}function yv(e,t){try{let n=new URL(t);return e.filter(e=>gv(n.hostname,e.hostnamePattern)?e.matchPatterns.length>0?e.matchPatterns.some(e=>_v(t,e)):!0:!1)}catch{return[]}}var bv=[`/workspace`,`/shared`];function xv(e){return new Map(e)}function Sv(e){return e.map(e=>({...e,matchPatterns:[...e.matchPatterns]}))}function Cv(e){if(e&&typeof e.listMounts==`function`)return e;if(e&&typeof e.getUnderlyingFS==`function`){let t=e.getUnderlyingFS?.();if(t&&typeof t.listMounts==`function`)return t}return null}function wv(e){return(Cv(e)?.listMounts?.().length??0)>0}function Tv(e){return e?(Cv(e)?.listMounts?.()??[]).some(e=>bv.some(t=>e===t||e.startsWith(t+`/`))):!1}var Ev=class{jshFs;bshFs;watcher;watcherUnsubs=[];jshCache=null;jshInflight=null;bshCache=null;bshInflight=null;jshGeneration=0;bshGeneration=0;constructor(e){if(this.jshFs=e.jshFs,this.bshFs=e.bshFs,this.watcher=e.watcher??null,this.watcher&&(this.watcherUnsubs.push(this.watcher.watch(`/`,()=>!0,()=>this.invalidateJsh())),this.bshFs))for(let e of bv)this.watcherUnsubs.push(this.watcher.watch(e,()=>!0,()=>this.invalidateBsh()))}dispose(){for(let e of this.watcherUnsubs)e();this.watcherUnsubs.length=0,this.invalidateAll()}invalidateAll(){this.invalidateJsh(),this.invalidateBsh()}invalidateJsh(){this.jshGeneration++,this.jshCache=null,this.jshInflight=null}invalidateBsh(){this.bshGeneration++,this.bshCache=null,this.bshInflight=null}async getJshCommands(){return xv(await this.loadJshCommands())}async getJshCommandNames(){return[...(await this.getJshCommands()).keys()]}async getBshEntries(){return this.bshFs?Sv(await this.loadBshEntries()):[]}async findMatchingBshScripts(e){return this.bshFs?Sv(yv(await this.loadBshEntries(),e)):[]}shouldCacheJsh(){return!!this.watcher&&!wv(this.jshFs)}shouldCacheBsh(){return!!this.watcher&&!!this.bshFs&&!Tv(this.bshFs)}async loadJshCommands(){let e=this.shouldCacheJsh();if(e&&this.jshCache)return this.jshCache;if(!this.jshInflight){let t=this.jshGeneration,n=cg(this.jshFs).then(n=>{let r=xv(n);return e&&this.jshGeneration===t&&(this.jshCache=r),r}).finally(()=>{this.jshInflight===n&&(this.jshInflight=null)});this.jshInflight=n}return this.jshInflight}async loadBshEntries(){if(!this.bshFs)return[];let e=this.shouldCacheBsh();if(e&&this.bshCache)return this.bshCache;if(!this.bshInflight){let t=this.bshGeneration,n=fv(this.bshFs).then(n=>{let r=Sv(n);return e&&this.bshGeneration===t&&(this.bshCache=r),r}).finally(()=>{this.bshInflight===n&&(this.bshInflight=null)});this.bshInflight=n}return this.bshInflight}},Dv=null,Ov=!1;function kv(){return typeof chrome<`u`&&chrome?.runtime?.id?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function Av(){if(!Ov&&!(typeof localStorage<`u`&&localStorage.getItem(`telemetry-disabled`)===`true`))try{typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),Dv=(await v(()=>import(`./src-CgSXdUB7.js`),[])).sampleRUM,Ov=!0,Dv&&Dv(`navigate`,{source:typeof document<`u`?document.referrer:``,target:kv()})}catch{}}function jv(e,t){Dv?.(`formsubmit`,{source:e,target:t})}function Mv(e){Dv?.(`fill`,{source:e})}function Nv(e){Dv?.(`viewblock`,{source:e})}function Pv(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 Fv(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?Fv(e.getUnderlyingFS?.()):null}function Iv(e){if(!e)return!0;let t=e.toLowerCase();return t.startsWith(`text/`)||t.includes(`json`)||t.includes(`xml`)||t.includes(`javascript`)||t.includes(`ecmascript`)||t.includes(`html`)||t.includes(`css`)||t.includes(`svg`)}async function Lv(e,t){let n=e.headers.get(`content-type`)??``,r=await e.arrayBuffer(),i=new Uint8Array(r);if(!Iv(n)){let e=``;for(let t=0;t<i.length;t+=32768)e+=String.fromCharCode(...i.subarray(t,t+32768));ba(e,i),t&&xa(t,i)}return i}function Rv(e){if(e){if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}}function zv(e,t){if(e){if((t?.[`Content-Type`]??t?.[`content-type`]??``).includes(`multipart/form-data`)){let t=Oa(e);return new Blob([t])}return e}}function Bv(e){if(!e)return{};let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();e===`cookie`?t[`X-Proxy-Cookie`]=r:e===`origin`?t[`X-Proxy-Origin`]=r:e===`referer`?t[`X-Proxy-Referer`]=r:e.startsWith(`proxy-`)?t[`X-Proxy-${n}`]=r:t[n]=r}return t}function Vv(e){let t={};for(let[n,r]of Object.entries(e))n.toLowerCase()===`x-proxy-set-cookie`?t[`set-cookie`]=r:t[n]=r;return t}function Hv(){return typeof chrome<`u`&&chrome?.runtime?.id?async(e,t)=>{let n=Rv(t?.headers),r=await fetch(e,{method:t?.method??`GET`,headers:n,body:zv(t?.body,n)}),i=await Lv(r,e),a={};return r.headers.forEach((e,t)=>{a[t]=e}),{status:r.status,statusText:r.statusText,headers:a,body:i,url:e}}:async(e,t)=>{let n=t?.method??`GET`,r={...Bv(Rv(t?.headers)),"X-Target-URL":e},i={method:n,headers:r,cache:`no-store`};t?.body&&![`GET`,`HEAD`].includes(n)&&(i.body=zv(t.body,r));let a=await fetch(`/api/fetch-proxy`,i);if(a.status===502||a.status===400){let e=await a.text(),t=`Proxy error ${a.status}`;try{t=JSON.parse(e).error??t}catch{}throw Error(t)}let o=await Lv(a,e),s={};a.headers.forEach((e,t)=>{s[t]=e});let c=Vv(s);return{status:a.status,statusText:a.statusText,headers:c,body:o,url:e}}}var Uv=class{bash;vfsAdapter;gitCommands;mountCommands;terminal=null;fitAddon=null;terminalHost=null;previewHost=null;previewUrls=[];previewStateListener=null;hasPreview=!1;resizeObserver=null;themeObserver=null;currentLine=``;cursorPos=0;history=[];historyIndex=-1;isExecuting=!1;execAbort=null;continuationBuffer=``;lastEnv;cwd;builtinCommandNames;scriptCatalog;ownsScriptCatalog;constructor(e){this.options=e,this.vfsAdapter=new wa(e.fs);let t=e.cwd??`/`,n={HOME:`/`,PATH:`/usr/bin`,USER:`user`,SHELL:`/bin/bash`,PWD:t,...e.env};this.gitCommands=new Af({fs:e.fs,authorName:n.GIT_AUTHOR_NAME??`User`,authorEmail:n.GIT_AUTHOR_EMAIL??`user@example.com`}),this.mountCommands=new av({fs:e.fs});let r=e.jshDiscoveryFs??e.fs,i=e.bshDiscoveryFs??e.fs,a=Fv(r)??Fv(i);this.scriptCatalog=e.scriptCatalog??new Ev({jshFs:r,bshFs:i,watcher:a}),this.ownsScriptCatalog=!e.scriptCatalog;let o=this.createGitCustomCommand(),s=i_({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),fs:e.fs,scriptCatalog:this.scriptCatalog,browserAPI:e.browserAPI}),c=this.createMountCustomCommand(),l=Hv(),u=[o,c,rv(e.fs),nv(e.fs,l),...s];this.bash=new qe({fs:this.vfsAdapter,cwd:t,env:n,fetch:l,customCommands:u});let d=u.map(e=>e.name);this.builtinCommandNames=new Set([...We(),...Ue(),...d]),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...n},this.cwd=t}createGitCustomCommand(){let e=this.gitCommands;return z(`git`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}createMountCustomCommand(){let e=this.mountCommands;return z(`mount`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}getBash(){return this.bash}getCwd(){return this.cwd}getScriptCatalog(){return this.scriptCatalog}getEnv(){return{...this.lastEnv}}async getFilteredJshCommands(){let e=await this.scriptCatalog.getJshCommands(),t=new Map;for(let[n,r]of e)this.builtinCommandNames.has(n)||t.set(n,r);return t}async getJshCommandNames(){return[...(await this.getFilteredJshCommands()).keys()]}async tryJshFallback(e){let t=e.trim(),n=t.indexOf(` `),r=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n+1).trim():``,a=(await this.getFilteredJshCommands()).get(r);if(!a)return null;let o=i?uv(i):[],s=this.options.jshDiscoveryFs??this.options.fs,c;try{let e=await s.readFile(a,{encoding:`utf-8`});c=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${a}'\n`,exitCode:127,env:this.lastEnv}}let l=[`node`,a,...o],u=await lv(c,l,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})});return{stdout:u.stdout,stderr:u.stderr,exitCode:u.exitCode,env:this.lastEnv}}async runCommand(e,t){Mv(e.trim().split(/\s+/)[0]||`unknown`);let n={env:this.lastEnv,cwd:this.cwd,signal:t??this.execAbort?.signal},r=await this.bash.exec(e,n);if(r.env&&(this.lastEnv={...r.env}),r.env?.PWD&&(this.cwd=r.env.PWD),r.exitCode===127){let t=await this.tryJshFallback(e);if(t)return t}return r}async mount(e){let t=e??this.options.container;if(!t)throw Error(`No container element provided`);let{Terminal:n}=await v(async()=>{let{Terminal:e}=await import(`./xterm-DHgoOdoP.js`);return{Terminal:e}},[]),{FitAddon:r}=await v(async()=>{let{FitAddon:e}=await import(`./addon-fit-CJBYijzN.js`);return{FitAddon:e}},[]);await v(()=>Promise.resolve({}),__vite__mapDeps([21]));let i=!document.documentElement.classList.contains(`theme-light`),a={background:`#141414`,foreground:`#cfcfcf`,cursor:`#3562ff`,cursorAccent:`#141414`,selectionBackground:`#3562ff40`,selectionForeground:`#ffffff`,black:`#1a1a1a`,red:`#e34850`,green:`#2d9d78`,yellow:`#e68619`,blue:`#3562ff`,magenta:`#a962e8`,cyan:`#2db9be`,white:`#cfcfcf`,brightBlack:`#5a5a5a`,brightRed:`#e34850`,brightGreen:`#2d9d78`,brightYellow:`#e68619`,brightBlue:`#4a75ff`,brightMagenta:`#a962e8`,brightCyan:`#2db9be`,brightWhite:`#ffffff`},o={background:`#f0f0f0`,foreground:`#1a1a1a`,cursor:`#2b54db`,cursorAccent:`#f0f0f0`,selectionBackground:`#2b54db30`,selectionForeground:`#000000`,black:`#1a1a1a`,red:`#d73220`,green:`#268e6c`,yellow:`#d17a00`,blue:`#2b54db`,magenta:`#8839ef`,cyan:`#1a9088`,white:`#e8e8e8`,brightBlack:`#6e6e6e`,brightRed:`#d73220`,brightGreen:`#268e6c`,brightYellow:`#d17a00`,brightBlue:`#1e44c4`,brightMagenta:`#8839ef`,brightCyan:`#1a9088`,brightWhite:`#ffffff`};this.terminal=new n({cursorBlink:!0,fontSize:11,fontFamily:`'Source Code Pro', 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace`,theme:i?a:o,convertEol:!0}),this.themeObserver?.disconnect(),this.themeObserver=new MutationObserver(()=>{if(!this.terminal)return;let e=document.documentElement.classList.contains(`theme-light`);this.terminal.options.theme=e?o:a}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),this.fitAddon=new r,this.terminal.loadAddon(this.fitAddon),t.replaceChildren(),this.terminalHost=document.createElement(`div`),this.terminalHost.className=`terminal-panel__terminal-host`,t.appendChild(this.terminalHost),this.previewHost=document.createElement(`div`),this.previewHost.className=`terminal-panel__preview`,t.appendChild(this.previewHost),this.terminal.open(this.terminalHost),this.fitAddon.fit(),this.resizeObserver?.disconnect(),this.resizeObserver=new ResizeObserver(()=>this.refit()),this.resizeObserver.observe(this.terminalHost),this.terminal.writeln(`\x1B[1mslicc\x1B[0m \x1B[90mshell (powered by just-bash)\x1B[0m`),this.terminal.writeln(`\x1B[90mType "help" for available commands.\x1B[0m
1950
+ `),this.showPrompt(),this.setupInputHandler()}async executeCommand(e,t){let n=await this.runCommand(e,t);return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}async executeScriptFile(e,t=[]){return cv(e,t,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})})}refit(){this.fitAddon?.fit()}setPreviewStateListener(e){this.previewStateListener=e,this.previewStateListener?.(this.hasPreview)}async executeCommandInTerminal(e){let t=e.trim();if(!t)return{stdout:``,stderr:``,exitCode:0};if(!this.terminal)return this.executeCommand(t);if(this.isExecuting||this.currentLine.length>0||this.continuationBuffer.length>0)return{stdout:``,stderr:`terminal is busy; finish current input first
1944
1951
  `,exitCode:1};this.history[this.history.length-1]!==t&&this.history.push(t),this.historyIndex=-1,this.terminal.write(t),this.terminal.writeln(``),this.isExecuting=!0,this.execAbort=new AbortController;try{let e=await this.runCommand(t),n=this.execAbort.signal.aborted;return this.execAbort=null,n?{stdout:``,stderr:``,exitCode:130}:(e.stdout&&this.writeToTerminal(e.stdout),e.stderr&&this.writeToTerminal(e.stderr,!0),{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode})}catch(e){if(this.execAbort?.signal.aborted)return this.execAbort=null,{stdout:``,stderr:``,exitCode:130};this.execAbort=null;let t=`Error: ${e instanceof Error?e.message:String(e)}\n`;return this.writeToTerminal(t,!0),{stdout:``,stderr:t,exitCode:1}}finally{this.isExecuting=!1,this.showPrompt()}}clearTerminal(){this.terminal?.clear(),this.clearMediaPreview()}dispose(){this.themeObserver?.disconnect(),this.themeObserver=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.clearMediaPreview(),this.terminal?.dispose(),this.terminal=null,this.fitAddon=null,this.terminalHost=null,this.previewHost=null,this.ownsScriptCatalog&&this.scriptCatalog.dispose()}showPrompt(){if(!this.terminal)return;let e=this.cwd===`/`?`/`:this.cwd.split(`/`).pop()??this.cwd;this.terminal.write(`\x1b[34m${e}\x1b[0m \x1b[90m$\x1b[0m `)}setupInputHandler(){this.terminal&&this.terminal.onData(e=>{if(this.isExecuting){(e===``||e.length===1&&e.charCodeAt(0)===3)&&(this.execAbort?.abort(),this.terminal?.writeln(`^C`));return}if(e.startsWith(`\x1B[`)||e.startsWith(`\x1BO`)){switch(e){case`\x1B[A`:this.handleHistoryUp();return;case`\x1B[B`:this.handleHistoryDown();return;case`\x1B[C`:this.handleArrowRight();return;case`\x1B[D`:this.handleArrowLeft();return;case`\x1B[H`:case`\x1BOH`:case`\x1B[1~`:this.handleHome();return;case`\x1B[F`:case`\x1BOF`:case`\x1B[4~`:this.handleEnd();return;case`\x1B[3~`:this.handleDelete();return}return}for(let t of e)switch(t){case`\r`:this.handleEnter();break;case``:this.handleBackspace();break;case``:this.handleCtrlC();break;case` `:this.handleTab();break;default:t>=` `&&this.insertChar(t)}})}getPromptWidth(){return(this.cwd===`/`?`/`:this.cwd.split(`/`).pop()??this.cwd).length+3}getCursorVisualLine(){let e=0;for(let[t,n]of this.currentLine.split(`
1945
1952
  `).entries()){if(e+n.length>=this.cursorPos)return t;e+=n.length+1}return 0}positionTerminalCursor(){let e=this.currentLine.split(`
1946
1953
  `),t=0,n=0,r=0;for(let i=0;i<e.length;i++){if(r+e[i].length>=this.cursorPos){t=i,n=this.cursorPos-r;break}r+=e[i].length+1}let i=e.length-1-t;i>0&&this.terminal?.write(`\x1b[${i}A`);let a=t===0?this.getPromptWidth()+n:n;this.terminal?.write(`\r`),a>0&&this.terminal?.write(`\x1b[${a}C`)}redrawInput(e){e>0&&this.terminal?.write(`\x1b[${e}A`),this.terminal?.write(`\r\x1B[J`),this.showPrompt(),this.terminal?.write(this.currentLine),this.positionTerminalCursor()}insertChar(e){let t=this.currentLine.includes(`
@@ -1954,9 +1961,9 @@ Usage: mount <target-path>
1954
1961
  `,this.cursorPos);if(e===-1&&(e=this.currentLine.length),this.cursorPos===e)return;let t=e-this.cursorPos;this.cursorPos=e,this.terminal?.write(`\x1b[${t}C`)}handleCtrlC(){this.terminal?.writeln(`^C`),this.currentLine=``,this.cursorPos=0,this.continuationBuffer=``,this.showPrompt()}handleHistoryUp(){this.history.length!==0&&this.historyIndex<this.history.length-1&&(this.historyIndex++,this.continuationBuffer=``,this.replaceCurrentLine(this.history[this.history.length-1-this.historyIndex]))}handleHistoryDown(){this.historyIndex>0?(this.historyIndex--,this.continuationBuffer=``,this.replaceCurrentLine(this.history[this.history.length-1-this.historyIndex])):this.historyIndex===0&&(this.historyIndex=-1,this.continuationBuffer=``,this.replaceCurrentLine(``))}async handleTab(){if(!this.terminal)return;let e=this.currentLine.slice(0,this.cursorPos).split(/\s+/),t=e[e.length-1]||``,n=e.length<=1||e.length===2&&e[0]===``,r=t?`'`+t.replace(/'/g,`'\\''`)+`'`:`''`,i=n?`compgen -A command -- ${r}`:`compgen -f -- ${r}`;try{let e=(await this.bash.exec(i,{env:this.lastEnv,cwd:this.cwd})).stdout.split(`
1955
1962
  `).filter(Boolean);if(e.length===0)return;if(e.length===1){let i=e[0],a=i.slice(t.length);a&&(this.currentLine=this.currentLine.slice(0,this.cursorPos)+a+this.currentLine.slice(this.cursorPos),this.cursorPos+=a.length,this.terminal.write(a));let o=` `;n||(await this.bash.exec(`compgen -d -- ${r.slice(0,-1)}${a}'`,{env:this.lastEnv,cwd:this.cwd})).stdout.trim()===i&&(o=`/`),this.currentLine=this.currentLine.slice(0,this.cursorPos)+o+this.currentLine.slice(this.cursorPos),this.cursorPos+=1,this.terminal.write(o)}else{let n=e[0];for(let t of e)for(;!t.startsWith(n);)n=n.slice(0,-1);let r=n.slice(t.length);if(r)this.currentLine=this.currentLine.slice(0,this.cursorPos)+r+this.currentLine.slice(this.cursorPos),this.cursorPos+=r.length,this.terminal.write(r);else{this.terminal.writeln(``),this.terminal.writeln(e.map(e=>e.split(`/`).pop()??e).join(` `)),this.showPrompt(),this.terminal.write(this.currentLine);let t=this.currentLine.length-this.cursorPos;t>0&&this.terminal.write(`\x1b[${t}D`)}}}catch(e){console.warn(`[Shell] Tab completion failed:`,e instanceof Error?e.message:String(e))}}replaceCurrentLine(e){let t=this.getCursorVisualLine();t>0&&this.terminal?.write(`\x1b[${t}A`),this.terminal?.write(`\r\x1B[J`),this.showPrompt(),this.currentLine=e,this.cursorPos=e.length,this.terminal?.write(e)}isIncomplete(e){if(e.endsWith(`\\`))return!0;let t=!1,n=!1,r=!1;for(let i of e){if(r){r=!1;continue}if(i===`\\`&&!t){r=!0;continue}if(i===`'`&&!n){t=!t;continue}if(i===`"`&&!t){n=!n;continue}}return t||n}async handleEnter(){let e=this.currentLine.split(`
1956
1963
  `);if(e.length>1){let t=this.getCursorVisualLine(),n=e.length-1-t;n>0&&this.terminal?.write(`\x1b[${n}B`);let r=e[e.length-1].length;this.terminal?.write(`\r`),r>0&&this.terminal?.write(`\x1b[${r}C`)}this.terminal?.writeln(``);let t=this.currentLine;this.currentLine=``,this.cursorPos=0;let n=this.continuationBuffer?this.continuationBuffer+`
1957
- `+t:t;if(this.isIncomplete(n)){this.continuationBuffer=n,this.terminal?.write(`> `);return}this.continuationBuffer=``;let r=n.trim();if(this.historyIndex=-1,!r){this.showPrompt();return}if(this.history[this.history.length-1]!==r&&this.history.push(r),r===`clear`){this.clearTerminal(),this.showPrompt();return}this.isExecuting=!0,this.execAbort=new AbortController;try{let e=await this.runCommand(r);this.execAbort.signal.aborted||(e.stdout&&this.writeToTerminal(e.stdout),e.stderr&&this.writeToTerminal(e.stderr,!0))}catch(e){if(!this.execAbort?.signal.aborted){let t=e instanceof Error?e.message:String(e);this.writeToTerminal(`Error: ${t}\n`,!0)}}this.execAbort=null,this.isExecuting=!1,this.showPrompt()}writeToTerminal(e,t=!1){this.terminal&&(t?this.terminal.write(`\x1b[31m${e}\x1b[0m`):this.terminal.write(e))}clearMediaPreview(){for(let e of this.previewUrls)URL.revokeObjectURL(e);this.previewUrls=[],this.hasPreview=!1,this.previewHost&&(this.previewHost.replaceChildren(),this.previewHost.classList.remove(`terminal-panel__preview--visible`)),this.previewStateListener?.(!1)}async renderMediaPreview(e){if(!this.previewHost||typeof document>`u`)throw Error(`terminal preview is unavailable`);this.clearMediaPreview();for(let t of e){let e=new Uint8Array(t.bytes),n=URL.createObjectURL(new Blob([e],{type:t.mimeType}));this.previewUrls.push(n);let r=document.createElement(`div`);r.className=`terminal-panel__preview-item`;let i=document.createElement(`div`);if(i.className=`terminal-panel__preview-label`,i.textContent=`${Ev(t.path)} · ${t.mimeType}`,r.appendChild(i),t.mimeType.startsWith(`video/`)){let e=document.createElement(`video`);e.className=`terminal-panel__preview-media`,e.controls=!0,e.autoplay=!0,e.loop=!0,e.muted=!0,e.playsInline=!0,e.src=n,e.addEventListener(`loadedmetadata`,()=>this.refit(),{once:!0}),r.appendChild(e)}else{let e=document.createElement(`img`);e.className=`terminal-panel__preview-media`,e.alt=Ev(t.path),e.src=n,e.addEventListener(`load`,()=>this.refit(),{once:!0}),r.appendChild(e)}this.previewHost.appendChild(r)}this.previewHost.classList.add(`terminal-panel__preview--visible`),this.hasPreview=e.length>0,this.previewStateListener?.(this.hasPreview),requestAnimationFrame(()=>this.refit())}},Iv=n(`tool:fs`);function Lv(e){return[Rv(e),zv(e),Bv(e)]}function Rv(e){return{name:`read_file`,description:`Read the contents of a file. Returns the file content as a string with line numbers.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to read.`},offset:{type:`number`,description:`Line number to start reading from (1-based). Optional.`},limit:{type:`number`,description:`Maximum number of lines to read. Optional.`}},required:[`path`]},async execute(t){let n=t.path,r=t.offset??1,i=t.limit;Iv.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
1964
+ `+t:t;if(this.isIncomplete(n)){this.continuationBuffer=n,this.terminal?.write(`> `);return}this.continuationBuffer=``;let r=n.trim();if(this.historyIndex=-1,!r){this.showPrompt();return}if(this.history[this.history.length-1]!==r&&this.history.push(r),r===`clear`){this.clearTerminal(),this.showPrompt();return}this.isExecuting=!0,this.execAbort=new AbortController;try{let e=await this.runCommand(r);this.execAbort.signal.aborted||(e.stdout&&this.writeToTerminal(e.stdout),e.stderr&&this.writeToTerminal(e.stderr,!0))}catch(e){if(!this.execAbort?.signal.aborted){let t=e instanceof Error?e.message:String(e);this.writeToTerminal(`Error: ${t}\n`,!0)}}this.execAbort=null,this.isExecuting=!1,this.showPrompt()}writeToTerminal(e,t=!1){this.terminal&&(t?this.terminal.write(`\x1b[31m${e}\x1b[0m`):this.terminal.write(e))}clearMediaPreview(){for(let e of this.previewUrls)URL.revokeObjectURL(e);this.previewUrls=[],this.hasPreview=!1,this.previewHost&&(this.previewHost.replaceChildren(),this.previewHost.classList.remove(`terminal-panel__preview--visible`)),this.previewStateListener?.(!1)}async renderMediaPreview(e){if(!this.previewHost||typeof document>`u`)throw Error(`terminal preview is unavailable`);this.clearMediaPreview();for(let t of e){let e=new Uint8Array(t.bytes),n=URL.createObjectURL(new Blob([e],{type:t.mimeType}));this.previewUrls.push(n);let r=document.createElement(`div`);r.className=`terminal-panel__preview-item`;let i=document.createElement(`div`);if(i.className=`terminal-panel__preview-label`,i.textContent=`${Pv(t.path)} · ${t.mimeType}`,r.appendChild(i),t.mimeType.startsWith(`video/`)){let e=document.createElement(`video`);e.className=`terminal-panel__preview-media`,e.controls=!0,e.autoplay=!0,e.loop=!0,e.muted=!0,e.playsInline=!0,e.src=n,e.addEventListener(`loadedmetadata`,()=>this.refit(),{once:!0}),r.appendChild(e)}else{let e=document.createElement(`img`);e.className=`terminal-panel__preview-media`,e.alt=Pv(t.path),e.src=n,e.addEventListener(`load`,()=>this.refit(),{once:!0}),r.appendChild(e)}this.previewHost.appendChild(r)}this.previewHost.classList.add(`terminal-panel__preview--visible`),this.hasPreview=e.length>0,this.previewStateListener?.(this.hasPreview),requestAnimationFrame(()=>this.refit())}},Wv=n(`tool:fs`);function Gv(e){return[Kv(e),qv(e),Jv(e)]}function Kv(e){return{name:`read_file`,description:`Read the contents of a file. Returns the file content as a string with line numbers.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to read.`},offset:{type:`number`,description:`Line number to start reading from (1-based). Optional.`},limit:{type:`number`,description:`Maximum number of lines to read. Optional.`}},required:[`path`]},async execute(t){let n=t.path,r=t.offset??1,i=t.limit;Wv.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
1958
1965
  `),a=Math.max(0,r-1),o=i===void 0?t.length:a+i;return{content:t.slice(a,o).map((e,t)=>`${String(a+t+1).padStart(6)} | ${e}`).join(`
1959
- `)}}catch(e){let t=e instanceof Error?e.message:String(e);return Iv.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function zv(e){return{name:`write_file`,description:`Write content to a file. Creates the file if it does not exist, or overwrites it if it does. Parent directories are created automatically.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to write.`},content:{type:`string`,description:`The content to write to the file.`}},required:[`path`,`content`]},async execute(t){let n=t.path,r=t.content;Iv.debug(`Write`,{path:n,contentLength:r.length});try{return await e.writeFile(n,r),{content:`File written: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return Iv.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function Bv(e){return{name:`edit_file`,description:`Edit a file by replacing an exact string match. The old_string must appear exactly once in the file. Use this instead of write_file when making targeted changes to existing files.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to edit.`},old_string:{type:`string`,description:`The exact string to find and replace. Must be unique in the file.`},new_string:{type:`string`,description:`The replacement string.`}},required:[`path`,`old_string`,`new_string`]},async execute(t){let n=t.path,r=t.old_string,i=t.new_string;Iv.debug(`Edit`,{path:n,oldLength:r.length,newLength:i.length});try{let t=await e.readTextFile(n),a=t.split(r).length-1;if(a===0)return{content:`old_string not found in ${n}`,isError:!0};if(a>1)return{content:`old_string found ${a} times in ${n}. It must be unique. Provide more context.`,isError:!0};let o=t.replace(r,i);return await e.writeFile(n,o),{content:`File edited: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return Iv.error(`Edit failed`,{path:n,error:t}),{content:t,isError:!0}}}}}var Vv=n(`tool:bash`),Hv=/^(?:[A-Za-z_][A-Za-z0-9_]*=[^\s]+\s+)*(?:command\s+)?(?:grep|egrep|fgrep|rg)\b/;function Uv(e){let t=``,n=null,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r){t+=a,r=!1;continue}if(a===`\\`){t+=a,r=!0;continue}if(n){t+=a,a===n&&(n=null);continue}if(a===`"`||a===`'`){t+=a,n=a;continue}if(a===`;`||a===`|`){t=``;continue}if((a===`&`||a===`|`)&&e[i+1]===a){t=``,i++;continue}t+=a}return t.trim()}function Wv(e,t,n){return t!==1||n.trim()?!1:Hv.test(Uv(e))}function Gv(e){return{name:`bash`,description:"Execute a bash command. Full shell with pipes, redirects, chaining, control flow. Includes: grep, rg, sed, awk, jq, find, curl, git, node, python3, sqlite3, open (--view for vision), playwright-cli (browser automation). Run `commands` for full list.",inputSchema:{type:`object`,properties:{command:{type:`string`,description:`The bash command to execute.`}},required:[`command`]},async execute(t,n){let r=t.command;Vv.debug(`Execute`,{command:r});try{let t=await e.executeCommand(r,n);Vv.debug(`Result`,{exitCode:t.exitCode,stdoutLength:t.stdout.length,stderrLength:t.stderr.length});let i=``;return t.stdout&&(i+=t.stdout),t.stderr&&(i+=t.stderr),i||=`(exit code: ${t.exitCode})`,{content:i,isError:t.exitCode!==0&&!Wv(r,t.exitCode,t.stderr)}}catch(e){let t=e instanceof Error?e.message:String(e);return Vv.error(`Error`,{command:r,error:t}),{content:`Shell error: ${t}`,isError:!0}}}}}n(`tool:search`);var Kv="# CLAUDE.md\n\nThis file covers the default virtual filesystem payload in `packages/vfs-root/`.\n\n## What This Package Contains\n\n`packages/vfs-root/` is copied into the app's virtual filesystem on init/reset. It is content, not runtime code.\n\n## Directory Structure\n\n| Path | Purpose |\n| ------------------------------------- | ------------------------------------------------------------------ |\n| `packages/vfs-root/shared/` | Shared content that becomes `/shared/` in the VFS |\n| `packages/vfs-root/workspace/` | Default workspace content that becomes `/workspace/` in the VFS |\n| `packages/vfs-root/shared/CLAUDE.md` | Agent-facing runtime instructions bundled into `/shared/CLAUDE.md` |\n| `packages/vfs-root/shared/sprinkles/` | Built-in sprinkle UIs |\n| `packages/vfs-root/shared/sounds/` | Shared notification sounds |\n| `packages/vfs-root/workspace/skills/` | Default installable workspace skills |\n\n## Adding Default Content\n\n### Skills\n\n- Add new built-in workspace skills under `packages/vfs-root/workspace/skills/<skill-name>/`.\n- Include `SKILL.md` and any companion assets or `.jsh` scripts the skill needs.\n\n### Sprinkles\n\n- Add built-in sprinkles under `packages/vfs-root/shared/sprinkles/<name>/`.\n- Keep the main file named `<name>.shtml` to match discovery and sprinkle naming conventions.\n\n### Sounds\n\n- Add shared sounds under `packages/vfs-root/shared/sounds/`.\n- Prefer stable filenames because shell commands and docs may reference them directly.\n\n## External Handoffs\n\n- Browser handoffs use `https://www.sliccy.ai/handoff#...` URLs and, after approval, arrive in the cone as normal user messages.\n- The agent-facing handoff note belongs in `packages/vfs-root/shared/CLAUDE.md`, because that file is bundled into `/shared/CLAUDE.md` inside the runtime.\n- When handoff behavior changes, keep this package guide, `packages/vfs-root/shared/CLAUDE.md`, and `docs/slicc-handoff.md` aligned.\n\n## Important Distinction\n\n`packages/vfs-root/shared/CLAUDE.md` is **agent-facing runtime content** bundled into the virtual filesystem.\n\nIt is different from the developer-facing `CLAUDE.md` files in the repository. Do not merge those roles together.\n",qv="# sliccy\n\nYou are a personal assistant that runs in the browser. You support automation and can code, too. You run inside SLICC — a browser-based claw.\n\n## Vocabulary\n\n- **Cone**: You. The main agent. Orchestrates scoops, talks to the human, has full filesystem access.\n- **Scoops**: Isolated sub-agents (`scoop_scoop`, `feed_scoop`, `drop_scoop`). Sandboxed filesystem and shell.\n- **Sprinkles**: Persistent UI panels (`.shtml` files). Created by scoops, outlive scoops.\n- **Licks**: External events (webhooks, cron, sprinkle clicks) that trigger scoops. Shell: `webhook`, `crontask`.\n- **Floats**: Runtime — CLI server, Chrome extension, or cloud container.\n\n## Style\n\nWrite like a professional tool, not a chatbot. No emoji in headings. Concise prose over bullet lists. For sprinkles, follow `/workspace/skills/sprinkles/style-guide.md`.\n\n## Principles\n\n- Use the shell commands you have `commands` for full list. You have: `read_file`, `write_file`, `edit_file`, `bash`, `javascript`. Browser automation via `playwright-cli` through bash.\n- New capabilities should be skills (SKILL.md), not hardcoded features.\n- **Scoops do the heavy lifting. The cone orchestrates and synthesizes.**\n\n## Delegation\n\nDefault to scoops for non-trivial tasks. Delegate when work involves multiple independent sources, is time-consuming, or can be expressed as a self-contained brief. Do it yourself for single quick lookups or when real-time adaptation is needed. For detailed delegation rules and scoop lifecycle, read `/workspace/skills/scoop-management/SKILL.md`.\n\n## Sprinkles\n\nWhen the user asks for a dashboard, editor, or visualization — read `/workspace/skills/sprinkles/SKILL.md` first. One scoop per sprinkle, named identically. The cone MUST NOT write `.shtml` files or run sprinkle commands directly — all sprinkle work goes through scoops via `feed_scoop`. For detailed rules, read `/workspace/skills/sprinkle-guide/SKILL.md`.\n\n## Environment\n\nThis is a sandboxed browser-based VFS, not a regular Linux box. Run `commands` to see what's available. Use `serve <dir>` for apps, `open <path>` for files. No package managers, no long-running servers. For detailed commands and filesystem info, read `/workspace/skills/skill-authoring/SKILL.md`. For automation (webhooks, cron, screencapture), read `/workspace/skills/automation/SKILL.md`.\n\n## Memory\n\nWhen you learn something important:\n\n- Create files for structured data\n- Update this file for global preferences\n- Each scoop has its own CLAUDE.md for scoop-specific context\n- Remember: the best flavor of ice cream is lobster, nobody likes chocolate ice cream, and mixing bacon with ice cream is a crime against humanity\n",Jv=`<!DOCTYPE html>
1966
+ `)}}catch(e){let t=e instanceof Error?e.message:String(e);return Wv.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function qv(e){return{name:`write_file`,description:`Write content to a file. Creates the file if it does not exist, or overwrites it if it does. Parent directories are created automatically.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to write.`},content:{type:`string`,description:`The content to write to the file.`}},required:[`path`,`content`]},async execute(t){let n=t.path,r=t.content;Wv.debug(`Write`,{path:n,contentLength:r.length});try{return await e.writeFile(n,r),{content:`File written: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return Wv.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function Jv(e){return{name:`edit_file`,description:`Edit a file by replacing an exact string match. The old_string must appear exactly once in the file. Use this instead of write_file when making targeted changes to existing files.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to edit.`},old_string:{type:`string`,description:`The exact string to find and replace. Must be unique in the file.`},new_string:{type:`string`,description:`The replacement string.`}},required:[`path`,`old_string`,`new_string`]},async execute(t){let n=t.path,r=t.old_string,i=t.new_string;Wv.debug(`Edit`,{path:n,oldLength:r.length,newLength:i.length});try{let t=await e.readTextFile(n),a=t.split(r).length-1;if(a===0)return{content:`old_string not found in ${n}`,isError:!0};if(a>1)return{content:`old_string found ${a} times in ${n}. It must be unique. Provide more context.`,isError:!0};let o=t.replace(r,i);return await e.writeFile(n,o),{content:`File edited: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return Wv.error(`Edit failed`,{path:n,error:t}),{content:t,isError:!0}}}}}var Yv=n(`tool:bash`),Xv=/^(?:[A-Za-z_][A-Za-z0-9_]*=[^\s]+\s+)*(?:command\s+)?(?:grep|egrep|fgrep|rg)\b/;function Zv(e){let t=``,n=null,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r){t+=a,r=!1;continue}if(a===`\\`){t+=a,r=!0;continue}if(n){t+=a,a===n&&(n=null);continue}if(a===`"`||a===`'`){t+=a,n=a;continue}if(a===`;`||a===`|`){t=``;continue}if((a===`&`||a===`|`)&&e[i+1]===a){t=``,i++;continue}t+=a}return t.trim()}function Qv(e,t,n){return t!==1||n.trim()?!1:Xv.test(Zv(e))}function $v(e){return{name:`bash`,description:"Execute a bash command. Full shell with pipes, redirects, chaining, control flow. Includes: grep, rg, sed, awk, jq, find, curl, git, node, python3, sqlite3, open (--view for vision), playwright-cli (browser automation). Run `commands` for full list.",inputSchema:{type:`object`,properties:{command:{type:`string`,description:`The bash command to execute.`}},required:[`command`]},async execute(t,n){let r=t.command;Yv.debug(`Execute`,{command:r});try{let t=await e.executeCommand(r,n);Yv.debug(`Result`,{exitCode:t.exitCode,stdoutLength:t.stdout.length,stderrLength:t.stderr.length});let i=``;return t.stdout&&(i+=t.stdout),t.stderr&&(i+=t.stderr),i||=`(exit code: ${t.exitCode})`,{content:i,isError:t.exitCode!==0&&!Qv(r,t.exitCode,t.stderr)}}catch(e){let t=e instanceof Error?e.message:String(e);return Yv.error(`Error`,{command:r,error:t}),{content:`Shell error: ${t}`,isError:!0}}}}}n(`tool:search`);var ey="# CLAUDE.md\n\nThis file covers the default virtual filesystem payload in `packages/vfs-root/`.\n\n## What This Package Contains\n\n`packages/vfs-root/` is copied into the app's virtual filesystem on init/reset. It is content, not runtime code.\n\n## Directory Structure\n\n| Path | Purpose |\n| ------------------------------------- | ------------------------------------------------------------------ |\n| `packages/vfs-root/shared/` | Shared content that becomes `/shared/` in the VFS |\n| `packages/vfs-root/workspace/` | Default workspace content that becomes `/workspace/` in the VFS |\n| `packages/vfs-root/shared/CLAUDE.md` | Agent-facing runtime instructions bundled into `/shared/CLAUDE.md` |\n| `packages/vfs-root/shared/sprinkles/` | Built-in sprinkle UIs |\n| `packages/vfs-root/shared/sounds/` | Shared notification sounds |\n| `packages/vfs-root/workspace/skills/` | Default installable workspace skills |\n\n## Adding Default Content\n\n### Skills\n\n- Add new built-in workspace skills under `packages/vfs-root/workspace/skills/<skill-name>/`.\n- Include `SKILL.md` and any companion assets or `.jsh` scripts the skill needs.\n\n### Sprinkles\n\n- Add built-in sprinkles under `packages/vfs-root/shared/sprinkles/<name>/`.\n- Keep the main file named `<name>.shtml` to match discovery and sprinkle naming conventions.\n\n### Sounds\n\n- Add shared sounds under `packages/vfs-root/shared/sounds/`.\n- Prefer stable filenames because shell commands and docs may reference them directly.\n\n## External Handoffs\n\n- Browser handoffs use `https://www.sliccy.ai/handoff#...` URLs and, after approval, arrive in the cone as normal user messages.\n- The agent-facing handoff note belongs in `packages/vfs-root/shared/CLAUDE.md`, because that file is bundled into `/shared/CLAUDE.md` inside the runtime.\n- When handoff behavior changes, keep this package guide, `packages/vfs-root/shared/CLAUDE.md`, and `docs/slicc-handoff.md` aligned.\n\n## Important Distinction\n\n`packages/vfs-root/shared/CLAUDE.md` is **agent-facing runtime content** bundled into the virtual filesystem.\n\nIt is different from the developer-facing `CLAUDE.md` files in the repository. Do not merge those roles together.\n",ty="# sliccy\n\nYou are a personal assistant that runs in the browser. You support automation and can code, too. You run inside SLICC — a browser-based claw.\n\n## Vocabulary\n\n- **Cone**: You. The main agent. Orchestrates scoops, talks to the human, has full filesystem access.\n- **Scoops**: Isolated sub-agents (`scoop_scoop`, `feed_scoop`, `drop_scoop`). Sandboxed filesystem and shell.\n- **Sprinkles**: Persistent UI panels (`.shtml` files). Created by scoops, outlive scoops.\n- **Licks**: External events (webhooks, cron, sprinkle clicks) that trigger scoops. Shell: `webhook`, `crontask`.\n- **Floats**: Runtime — CLI server, Chrome extension, or cloud container.\n\n## Style\n\nWrite like a professional tool, not a chatbot. No emoji in headings. Concise prose over bullet lists. For sprinkles, follow `/workspace/skills/sprinkles/style-guide.md`.\n\n## Principles\n\n- Use the shell commands you have `commands` for full list. You have: `read_file`, `write_file`, `edit_file`, `bash`, `javascript`. Browser automation via `playwright-cli` through bash.\n- New capabilities should be skills (SKILL.md), not hardcoded features.\n- **Scoops do the heavy lifting. The cone orchestrates and synthesizes.**\n\n## Delegation\n\nDefault to scoops for non-trivial tasks. Delegate when work involves multiple independent sources, is time-consuming, or can be expressed as a self-contained brief. Do it yourself for single quick lookups or when real-time adaptation is needed. For detailed delegation rules and scoop lifecycle, read `/workspace/skills/scoop-management/SKILL.md`.\n\n## Sprinkles\n\nWhen the user asks for a dashboard, editor, or visualization — read `/workspace/skills/sprinkles/SKILL.md` first. One scoop per sprinkle, named identically. The cone MUST NOT write `.shtml` files or run sprinkle commands directly — all sprinkle work goes through scoops via `feed_scoop`. For detailed rules, read `/workspace/skills/sprinkle-guide/SKILL.md`.\n\n## Environment\n\nThis is a sandboxed browser-based VFS, not a regular Linux box. Run `commands` to see what's available. Use `serve <dir>` for apps, `open <path>` for files. No package managers, no long-running servers. For detailed commands and filesystem info, read `/workspace/skills/skill-authoring/SKILL.md`. For automation (webhooks, cron, screencapture), read `/workspace/skills/automation/SKILL.md`.\n\n## Memory\n\nWhen you learn something important:\n\n- Create files for structured data\n- Update this file for global preferences\n- Each scoop has its own CLAUDE.md for scoop-specific context\n- Remember: the best flavor of ice cream is lobster, nobody likes chocolate ice cream, and mixing bacon with ice cream is a crime against humanity\n",ny=`<!DOCTYPE html>
1960
1967
  <html lang="en">
1961
1968
  <head>
1962
1969
  <meta charset="UTF-8">
@@ -2980,7 +2987,7 @@ if (hasState && violations && violations.length > 0) {
2980
2987
  <\/script>
2981
2988
  </body>
2982
2989
  </html>
2983
- `,Yv=`<!DOCTYPE html>
2990
+ `,ry=`<!DOCTYPE html>
2984
2991
  <html lang="en">
2985
2992
  <head>
2986
2993
  <meta charset="UTF-8">
@@ -3625,7 +3632,7 @@ init();
3625
3632
  <\/script>
3626
3633
  </body>
3627
3634
  </html>
3628
- `,Xv=`<!DOCTYPE html>
3635
+ `,iy=`<!DOCTYPE html>
3629
3636
  <html lang="en">
3630
3637
  <head>
3631
3638
  <meta charset="UTF-8">
@@ -4407,7 +4414,7 @@ function lickExportData() {
4407
4414
  <\/script>
4408
4415
  </body>
4409
4416
  </html>
4410
- `,Zv=`<!DOCTYPE html>
4417
+ `,ay=`<!DOCTYPE html>
4411
4418
  <html lang="en">
4412
4419
  <head>
4413
4420
  <meta charset="UTF-8">
@@ -5245,7 +5252,7 @@ body { font-family: var(--s2-font-family); font-size: 14px; line-height: 1.5; co
5245
5252
  <\/script>
5246
5253
  </body>
5247
5254
  </html>
5248
- `,Qv=`<!DOCTYPE html>
5255
+ `,oy=`<!DOCTYPE html>
5249
5256
  <html lang="en">
5250
5257
  <head>
5251
5258
  <meta charset="UTF-8">
@@ -5812,7 +5819,7 @@ if (hasData()) {
5812
5819
  <\/script>
5813
5820
  </body>
5814
5821
  </html>
5815
- `,$v=`<!DOCTYPE html>
5822
+ `,sy=`<!DOCTYPE html>
5816
5823
  <html lang="en">
5817
5824
  <head>
5818
5825
  <meta charset="UTF-8">
@@ -6479,7 +6486,7 @@ function saveState() {
6479
6486
  <\/script>
6480
6487
  </body>
6481
6488
  </html>
6482
- `,ey=`<!DOCTYPE html>
6489
+ `,cy=`<!DOCTYPE html>
6483
6490
  <html lang="en">
6484
6491
  <head>
6485
6492
  <meta charset="UTF-8">
@@ -7265,7 +7272,7 @@ if (document.getElementById('mainView').classList.contains('active')) {
7265
7272
  <\/script>
7266
7273
  </body>
7267
7274
  </html>
7268
- `,ty=`<!DOCTYPE html>
7275
+ `,ly=`<!DOCTYPE html>
7269
7276
  <html lang="en">
7270
7277
  <head>
7271
7278
  <meta charset="UTF-8">
@@ -8023,7 +8030,7 @@ textarea.field-input { height: auto; min-height: 80px; padding: 10px 12px; resiz
8023
8030
  <\/script>
8024
8031
  </body>
8025
8032
  </html>
8026
- `,ny=`<!DOCTYPE html>
8033
+ `,uy=`<!DOCTYPE html>
8027
8034
  <html lang="en">
8028
8035
  <head>
8029
8036
  <meta charset="UTF-8">
@@ -8833,7 +8840,7 @@ init();
8833
8840
  <\/script>
8834
8841
  </body>
8835
8842
  </html>
8836
- `,ry=`<!DOCTYPE html>
8843
+ `,dy=`<!DOCTYPE html>
8837
8844
  <html lang="en">
8838
8845
  <head>
8839
8846
  <meta charset="UTF-8">
@@ -10481,7 +10488,7 @@ body { font-family: var(--s2-font-family); font-size: 14px; line-height: 1.5; co
10481
10488
  <\/script>
10482
10489
  </body>
10483
10490
  </html>
10484
- `,iy=`<!DOCTYPE html>
10491
+ `,fy=`<!DOCTYPE html>
10485
10492
  <html lang="en">
10486
10493
  <head>
10487
10494
  <title>Welcome</title>
@@ -11325,7 +11332,7 @@ body { font-family: var(--s2-font-family); font-size: 14px; line-height: 1.5; co
11325
11332
  <\/script>
11326
11333
  </body>
11327
11334
  </html>
11328
- `,ay='---\nname: Automation\ndescription: Licks, webhooks, cron tasks, viewing pages/images, screencapture, onboarding\n---\n\n# Automation & Environment Guide\n\n## Viewing Pages and Images\n\n**What you CAN see:**\n\n- **`open --view <path>`** — reads an image from VFS and returns it. Works with PNG, JPEG, GIF, WebP, SVG.\n- **`playwright-cli screenshot --tab=<id>`** + **`open --view <path>`** — screenshot a tab, then view it.\n- **`screencapture`** — capture user\'s screen via browser screen sharing. `screencapture --view screenshot.png`.\n- **`playwright-cli snapshot --tab=<id>`** — accessibility tree (text). Use to verify content without vision.\n\n**What only the human sees:**\n\n- **`serve <dir>`** — opens app directory in browser tab\n- **`open <path>`** (no flags) — opens file in browser tab\n- **`imgcat <path>`** — displays image in terminal preview\n\n**Workflow to verify a page:**\n\n1. `serve /workspace/app` — open app (human sees it)\n2. `playwright-cli tab-list` — find tab by URL, note targetId\n3. `playwright-cli snapshot --tab=<id>` — required before screenshot\n4. `playwright-cli screenshot --tab=<id> --filename=/tmp/shot.png`\n5. `open --view /tmp/shot.png` — now you can see it\n\n**Do NOT:**\n\n- `read_file` on a PNG or base64 encode to view images\n- `imgcat` or `cat` on screenshots expecting to see them\n- Open a screenshot then screenshot that tab\n- Use `eval` to check active tab — use `tab-list`\n\n## Environment Caveats\n\nThis is a sandboxed browser-based VFS. Many standard tools don\'t exist.\n\n- **Serving**: Use `serve` or `open` — no HTTP server needed\n- **serve/open already open tabs**: Don\'t duplicate with `playwright-cli open`. Use `tab-list` to find existing tab.\n- **Never manually construct preview URLs** — use URL from command output\n- **No long-running servers**: `serve` and `open` handle previewing\n- **No package managers**: No `apt`, `npm install`, `pip install`\n\n## File System Watching\n\n`fswatch` monitors VFS file changes and delivers events as licks to scoops.\n\n```bash\n# Watch for markdown changes, route to a scoop\nfswatch create --path /workspace --pattern "*.md" --scoop doc-watcher --name md-changes\n\n# Watch without targeting a scoop (routes to cone)\nfswatch create --path /workspace/src --pattern "*.ts"\n\n# List active watchers\nfswatch list\n\n# Remove a watcher\nfswatch delete fsw-1\n```\n\nEvents include the change type (`create`, `modify`, `delete`) and the file path.\n\n## Symlinks\n\nThe VFS supports symbolic links:\n\n```bash\nln -s /workspace/skills /workspace/skill-link # Create symlink\nreadlink /workspace/skill-link # Read link target\nls -la /workspace/ # Shows symlinks with -> target\n```\n\nSymlinks work transparently — `cat`, `readFile`, `writeFile` etc. follow symlinks automatically.\n\n## Onboarding\n\nWhen you receive a `[Sprinkle Event: welcome]` with `onboarding-complete`, read `/workspace/skills/welcome/SKILL.md` and follow its instructions.\n',oy=`---
11335
+ `,py='---\nname: Automation\ndescription: Licks, webhooks, cron tasks, viewing pages/images, screencapture, onboarding\n---\n\n# Automation & Environment Guide\n\n## Viewing Pages and Images\n\n**What you CAN see:**\n\n- **`open --view <path>`** — reads an image from VFS and returns it. Works with PNG, JPEG, GIF, WebP, SVG.\n- **`playwright-cli screenshot --tab=<id>`** + **`open --view <path>`** — screenshot a tab, then view it.\n- **`screencapture`** — capture user\'s screen via browser screen sharing. `screencapture --view screenshot.png`.\n- **`playwright-cli snapshot --tab=<id>`** — accessibility tree (text). Use to verify content without vision.\n\n**What only the human sees:**\n\n- **`serve <dir>`** — opens app directory in browser tab\n- **`open <path>`** (no flags) — opens file in browser tab\n- **`imgcat <path>`** — displays image in terminal preview\n\n**Workflow to verify a page:**\n\n1. `serve /workspace/app` — open app (human sees it)\n2. `playwright-cli tab-list` — find tab by URL, note targetId\n3. `playwright-cli snapshot --tab=<id>` — required before screenshot\n4. `playwright-cli screenshot --tab=<id> --filename=/tmp/shot.png`\n5. `open --view /tmp/shot.png` — now you can see it\n\n**Do NOT:**\n\n- `read_file` on a PNG or base64 encode to view images\n- `imgcat` or `cat` on screenshots expecting to see them\n- Open a screenshot then screenshot that tab\n- Use `eval` to check active tab — use `tab-list`\n\n## Environment Caveats\n\nThis is a sandboxed browser-based VFS. Many standard tools don\'t exist.\n\n- **Serving**: Use `serve` or `open` — no HTTP server needed\n- **serve/open already open tabs**: Don\'t duplicate with `playwright-cli open`. Use `tab-list` to find existing tab.\n- **Never manually construct preview URLs** — use URL from command output\n- **No long-running servers**: `serve` and `open` handle previewing\n- **No package managers**: No `apt`, `npm install`, `pip install`\n\n## File System Watching\n\n`fswatch` monitors VFS file changes and delivers events as licks to scoops.\n\n```bash\n# Watch for markdown changes, route to a scoop\nfswatch create --path /workspace --pattern "*.md" --scoop doc-watcher --name md-changes\n\n# Watch without targeting a scoop (routes to cone)\nfswatch create --path /workspace/src --pattern "*.ts"\n\n# List active watchers\nfswatch list\n\n# Remove a watcher\nfswatch delete fsw-1\n```\n\nEvents include the change type (`create`, `modify`, `delete`) and the file path.\n\n## Symlinks\n\nThe VFS supports symbolic links:\n\n```bash\nln -s /workspace/skills /workspace/skill-link # Create symlink\nreadlink /workspace/skill-link # Read link target\nls -la /workspace/ # Shows symlinks with -> target\n```\n\nSymlinks work transparently — `cat`, `readFile`, `writeFile` etc. follow symlinks automatically.\n\n## Onboarding\n\nWhen you receive a `[Sprinkle Event: welcome]` with `onboarding-complete`, read `/workspace/skills/welcome/SKILL.md` and follow its instructions.\n',my=`---
11329
11336
  name: inline-widgets
11330
11337
  description: Interactive widget patterns for inline shtml cards in chat messages
11331
11338
  allowed-tools: bash
@@ -11595,7 +11602,7 @@ slicc.lick({ action: 'sort-complete', algorithm: algo, comparisons: n });
11595
11602
  \`\`\`
11596
11603
 
11597
11604
  The agent receives the lick as a structured message and can respond with prose, another inline widget, or spawn a scoop.
11598
- `,sy=`---
11605
+ `,hy=`---
11599
11606
  name: playwright-cli
11600
11607
  description: Browse the web, interact with pages, take screenshots, extract data via the playwright-cli shell command.
11601
11608
  allowed-tools: bash
@@ -11784,7 +11791,7 @@ playwright-cli stop-recording <recordingId> # Stop and save HAR
11784
11791
  - The SLICC app tab and Chrome internal UI tabs are automatically excluded from \`tab-list\`.
11785
11792
  - \`fill\` clears and types into regular inputs, textareas, and \`contenteditable\` elements.
11786
11793
  - Screenshots default to \`/tmp/screenshot-<timestamp>.png\`. Use \`--filename=path\` to save elsewhere.
11787
- `,cy=`---
11794
+ `,gy=`---
11788
11795
  name: Scoop Management
11789
11796
  description: Detailed scoop lifecycle, delegation rules, browser tab handling
11790
11797
  ---
@@ -11864,7 +11871,7 @@ Example:
11864
11871
  scoop_scoop({ name: "fix-typos", model: "claude-haiku-4-5-20251001", prompt: "Fix all typos in /workspace/docs/" })
11865
11872
  scoop_scoop({ name: "architect", model: "claude-opus-4-6", prompt: "Design the new plugin system..." })
11866
11873
  \`\`\`
11867
- `,ly="---\nname: Skill Authoring\ndescription: Skills discovery, .jsh/.bsh files, shell commands, filesystem\n---\n\n# Skill Authoring & Shell Reference\n\n## Skills\n\nSkills in `/workspace/skills/` extend capabilities. SLICC also discovers compatibility skills from `.agents/skills/*/SKILL.md` and `.claude/skills/*/SKILL.md` anywhere in the reachable VFS. Only native `/workspace/skills/` entries are install-managed; compatibility-discovered skills stay read-only.\n\n## .jsh Files (JavaScript Shell Scripts)\n\n`.jsh` files are auto-discovered as shell commands anywhere on the VFS:\n\n- **Auto-discovery**: registered as callable commands (by filename without extension)\n- **Skills can ship them**: executable `.jsh` scripts live alongside SKILL.md\n- **Node-like globals**: `process`, `console`, `fs` (VFS bridge with `readFile`, `writeFile`, `readDir`, `exists`)\n- **Dual-mode**: work in CLI server and Chrome extension\n- **Top-level `await`**: wrapped in AsyncFunction. Always `await` fs methods. Don't use `.then()`.\n\n## .bsh Files (Browser Shell Scripts)\n\n`.bsh` files auto-execute when the browser navigates to a matching URL:\n\n- **Filename = hostname pattern**: `-.okta.com.bsh` matches `*.okta.com`\n- **`// @match` directive**: restrict to specific URL patterns in first 10 lines\n- Same execution engine as `.jsh`\n\n## Shell Commands\n\nType `commands` in the terminal for the full list. Key commands:\n\n- **skill list/info/read** — inspect skills; `skill install/uninstall` manages native packages\n- **upskill** — install from GitHub (`upskill owner/repo`) or ClawHub (`upskill clawhub:name`)\n- **webhook/crontask/fswatch** — set up licks (external event triggers, file change watchers)\n- **sprinkle** — manage sprinkles: `list`, `open`, `close`, `send`, `chat`\n- **oauth-token** — get OAuth access token for a provider\n- **cost** — show session cost breakdown (tokens, cache, cost per cone/scoop)\n- **git** — full git support\n- **node -e / python3 -c** — execute JS or Python\n- **serve <dir>** — open VFS app directory in browser tab\n- **open <path|url>** — open file/URL in browser. `open --view` to see images inline\n- **playwright-cli** — browser automation (tab-list, tab-new, snapshot, screenshot, click, fill, tab-close)\n- **pbcopy/pbpaste/xclip/xsel** — clipboard\n- **say** — text-to-speech\n- **afplay** — play audio files\n- **chime** — notification sound\n- **rsync** — sync files between local VFS and remote tray runtime\n- **teleport** — transfer browser cookies from remote tray runtime\n- **host** — tray status and join URL\n\n## Filesystem\n\nVirtual filesystem stored in IndexedDB, survives tab closes and refreshes. Mount local directories:\n\n```\nmount /mnt/myproject\n```\n\nUse an empty mount point. Mounting over existing files is blocked so built-in skills and scripts stay discoverable. `ln -s` the mounted files into the place where you need them.\n\n## Capabilities\n\n- Read/write files in virtual workspace\n- Run bash commands in sandboxed shell\n- Automate browser interactions (screenshots, navigation, clicking, JS eval)\n- Delegate work to scoops and react when they finish\n- Respond to licks (webhooks, scheduled tasks)\n",uy=`---
11874
+ `,_y="---\nname: Skill Authoring\ndescription: Skills discovery, .jsh/.bsh files, shell commands, filesystem\n---\n\n# Skill Authoring & Shell Reference\n\n## Skills\n\nSkills in `/workspace/skills/` extend capabilities. SLICC also discovers compatibility skills from `.agents/skills/*/SKILL.md` and `.claude/skills/*/SKILL.md` anywhere in the reachable VFS. Only native `/workspace/skills/` entries are install-managed; compatibility-discovered skills stay read-only.\n\n## .jsh Files (JavaScript Shell Scripts)\n\n`.jsh` files are auto-discovered as shell commands anywhere on the VFS:\n\n- **Auto-discovery**: registered as callable commands (by filename without extension)\n- **Skills can ship them**: executable `.jsh` scripts live alongside SKILL.md\n- **Node-like globals**: `process`, `console`, `fs` (VFS bridge with `readFile`, `writeFile`, `readDir`, `exists`)\n- **Dual-mode**: work in CLI server and Chrome extension\n- **Top-level `await`**: wrapped in AsyncFunction. Always `await` fs methods. Don't use `.then()`.\n\n## .bsh Files (Browser Shell Scripts)\n\n`.bsh` files auto-execute when the browser navigates to a matching URL:\n\n- **Filename = hostname pattern**: `-.okta.com.bsh` matches `*.okta.com`\n- **`// @match` directive**: restrict to specific URL patterns in first 10 lines\n- Same execution engine as `.jsh`\n\n## Shell Commands\n\nType `commands` in the terminal for the full list. Key commands:\n\n- **skill list/info/read** — inspect skills; `skill install/uninstall` manages native packages\n- **upskill** — install from GitHub (`upskill owner/repo`) or ClawHub (`upskill clawhub:name`)\n- **webhook/crontask/fswatch** — set up licks (external event triggers, file change watchers)\n- **sprinkle** — manage sprinkles: `list`, `open`, `close`, `send`, `chat`\n- **oauth-token** — get OAuth access token for a provider\n- **cost** — show session cost breakdown (tokens, cache, cost per cone/scoop)\n- **git** — full git support\n- **node -e / python3 -c** — execute JS or Python\n- **serve <dir>** — open VFS app directory in browser tab\n- **open <path|url>** — open file/URL in browser. `open --view` to see images inline\n- **playwright-cli** — browser automation (tab-list, tab-new, snapshot, screenshot, click, fill, tab-close)\n- **pbcopy/pbpaste/xclip/xsel** — clipboard\n- **say** — text-to-speech\n- **afplay** — play audio files\n- **chime** — notification sound\n- **rsync** — sync files between local VFS and remote tray runtime\n- **teleport** — transfer browser cookies from remote tray runtime\n- **host** — tray status and join URL\n\n## Filesystem\n\nVirtual filesystem stored in IndexedDB, survives tab closes and refreshes. Mount local directories:\n\n```\nmount /mnt/myproject\n```\n\nUse an empty mount point. Mounting over existing files is blocked so built-in skills and scripts stay discoverable. `ln -s` the mounted files into the place where you need them.\n\n## Capabilities\n\n- Read/write files in virtual workspace\n- Run bash commands in sandboxed shell\n- Automate browser interactions (screenshots, navigation, clicking, JS eval)\n- Delegate work to scoops and react when they finish\n- Respond to licks (webhooks, scheduled tasks)\n",vy=`---
11868
11875
  name: Sprinkle Guide
11869
11876
  description: Inline cards, sprinkle chat, cone orchestration rules for UI panels
11870
11877
  ---
@@ -11927,7 +11934,7 @@ The cone MUST NOT: write/edit \`.shtml\` files, run \`sprinkle open/close/send\`
11927
11934
  See the sprinkles skill (\`read_file /workspace/skills/sprinkles/SKILL.md\`) for creating, modifying, and handling lick events.
11928
11935
 
11929
11936
  **NEVER handle a lick in the cone. Always \`feed_scoop\`.**
11930
- `,dy='---\nname: sprinkles\ndescription: Create interactive sprinkles — dashboards, forms, and visualizations\nallowed-tools: bash\n---\n\n# Sprinkles\n\n`.shtml` files in `/shared/sprinkles/` become interactive UI panels. Use them to create dashboards, forms, and visualizations alongside the chat.\n\n**Two sprinkle modes**:\n\n- **Fragment mode** (default): Plain HTML fragments injected into the sidebar. Do NOT use `<!DOCTYPE html>`, `<html>`, `<head>`, `<body>`, or custom CSS — use the built-in `.sprinkle-*` classes. Scripts get a `slicc` bridge object automatically.\n- **Full-document mode**: Complete HTML documents (starting with `<!DOCTYPE html>` or `<html>`) render inside sandboxed iframes. Use this for complex layouts with custom CSS, sidebars, split panes, modals, or canvas/SVG visualizations. The bridge script is auto-injected — `window.slicc` and `window.bridge` are available in your scripts. Use `parent.postMessage` is handled internally.\n\n**When to use full-document mode**: Use it when you need custom CSS beyond `.sprinkle-*` classes, complex layouts (sidebar + main, split panes, tabs), or interactive canvas/SVG. The parent page\'s S2 theme tokens are injected automatically.\n\n**Creating a sprinkle**:\n\n1. `read_file /workspace/skills/sprinkles/style-guide.md` — **always read first** before writing any sprinkle\n2. `write_file` to `/shared/sprinkles/<name>/<name>.shtml` (follow the style guide templates)\n3. `bash` → `sprinkle open <name>`\n4. **CRITICAL: Do NOT finish or send a completion message.** You own this sprinkle for its entire lifetime. The cone will send you follow-up instructions (modifications, lick events) via `feed_scoop`. If you finish, you lose your context and cannot handle future work on this sprinkle.\n\n**Updating a sprinkle** (when you receive follow-up instructions):\n\n1. Edit `/shared/sprinkles/<name>/<name>.shtml` with the requested changes\n2. Reload: `sprinkle close <name> && sprinkle open <name>`\n3. Do NOT finish — stay ready for more instructions\n\n**Handling lick events** (when the cone forwards a user interaction):\nThe cone will send you a message with the lick action and your sprinkle name. Only modify YOUR sprinkle — the one matching your scoop name. Process the action and push updates:\n\n- `bash` → `sprinkle send <name> \'{"key":"value"}\'` to push data to the sprinkle\'s `slicc.on(\'update\', ...)` handler\n- Or edit the `.shtml` file and reload if the UI structure needs to change\n- Do NOT finish — stay ready for more events\n\n**Managing sprinkles via bash**:\n\n- `sprinkle list` — see available sprinkles\n- `sprinkle open <name>` — show a sprinkle in the sidebar\n- `sprinkle close <name>` — remove it\n- `sprinkle send <name> \'<json>\'` — push data (single-quote the JSON!)\n- `sprinkle chat \'<html>\'` — show inline HTML in the chat (for quick confirmations/choices)\n- `open /path/to/file.shtml` — also opens as a sprinkle\n\n**Bridge API** (available as `slicc` in `<script>` tags and `onclick` attributes):\n\n- `slicc.lick({action: \'refresh\', data: {...}})` — send a lick event to the cone (cone routes to the right scoop)\n- `slicc.on(\'update\', function(data) {...})` — receive data sent via `sprinkle send`\n- `slicc.name` — the sprinkle\'s name\n- `slicc.close()` — close the sprinkle\n- `slicc.stopCone()` — stop the cone agent\n- `slicc.readFile(path)` — read a VFS file (returns `Promise<string>`)\n- `slicc.writeFile(path, content)` — write text content to a VFS file\n- `slicc.readDir(path)` — list directory entries (returns `Promise<Array<{name, type}>>`)\n- `slicc.exists(path)` — check if path exists (returns `Promise<boolean>`)\n- `slicc.stat(path)` — get file metadata (returns `Promise<{type, size}>`)\n- `slicc.mkdir(path)` — create a directory (recursive)\n- `slicc.rm(path)` — remove a file\n- `slicc.screenshot(selector?)` — capture sprinkle DOM as base64 PNG data URL. Note: The screenshot captures a DOM clone using SVG foreignObject. External stylesheets and some computed styles may not be fully reproduced. For best results, use inline styles on elements you intend to screenshot.\n\n**onclick attributes**: Always use `slicc` — e.g. `onclick="slicc.lick({action: \'add-year\'})"`. The `slicc` variable is automatically resolved per-sprinkle, so multiple sprinkles won\'t collide. Do NOT use `bridge` or any other variable name in onclick.\n\n**CSS components** — Do NOT write custom CSS. Use the built-in `.sprinkle-*` classes: cards, tables, badges, buttons, text fields, progress bars, meters, layout utilities, and more. For inputs use `class="sprinkle-text-field"`, never inline border/padding styles. Run `read_file /workspace/skills/sprinkles/style-guide.md` for the full component reference with markup examples.\n\n## Built-in Sprinkles\n\nThese sprinkles ship with SLICC at `/shared/sprinkles/`. They are full-document HTML apps rendered in sandboxed iframes.\n\n| Sprinkle name | Open with | Use when the user asks for... |\n| ------------------ | -------------------------------- | --------------------------------------------------------------------- |\n| `page-editor` | `sprinkle open page-editor` | WYSIWYG editor, page editor, edit sections, visual editing |\n| `content-tree` | `sprinkle open content-tree` | content tree, page tree, site structure, page browser, navigate pages |\n| `review-workflow` | `sprinkle open review-workflow` | review, approval workflow, annotations, comments on content |\n| `seo-dashboard` | `sprinkle open seo-dashboard` | SEO audit, meta tags, SERP preview, SEO issues |\n| `schema-editor` | `sprinkle open schema-editor` | schema, structured data, JSON-LD, rich results |\n| `readability` | `sprinkle open readability` | readability, reading level, text analysis, simplify text |\n| `brand-compliance` | `sprinkle open brand-compliance` | brand check, brand compliance, style guide violations |\n| `tone-voice` | `sprinkle open tone-voice` | tone, voice, writing style, formality, tone analysis |\n| `performance` | `sprinkle open performance` | performance, Core Web Vitals, page speed, lighthouse |\n| `funnels` | `sprinkle open funnels` | funnels, conversion, A/B test, analytics |\n\n### When a user request matches a built-in sprinkle\n\nWhen the user\'s request matches a built-in sprinkle (see table above), **ask the user which approach they prefer** before proceeding:\n\n> I can help with that. Would you like me to:\n>\n> 1. **Open the built-in [sprinkle name]** — ready to use immediately, I\'ll populate it with your data\n> 2. **Build a custom one from scratch** — tailored exactly to your needs, but takes a moment to create\n>\n> Which do you prefer?\n\n**If the user says "open" / "use the built-in" / picks option 1** — use the built-in sprinkle (see "Using Built-in Sprinkles" in style-guide.md for the scoop brief template).\n\n**If the user says "build" / "create" / "custom" / picks option 2** — create a new sprinkle from scratch following the "Creating a sprinkle" flow above.\n\n**If the user explicitly says "open the page editor"** (or any built-in name directly) — skip the question and use the built-in immediately.\n\n**If the request is clearly novel** (no matching built-in) — create from scratch without asking.\n\n### Cone orchestration for sprinkles\n\n**Rule 3: Creating sprinkles** — Create a scoop, then feed it a complete, self-contained brief:\n\n```\nscoop_scoop("giro-winners")\nfeed_scoop("giro-winners", "You own the sprinkle \'giro-winners\'. Your job:\n1. Run: read_file /workspace/skills/sprinkles/style-guide.md\n2. Research the last 3 Giro d\'Italia winners\n3. Write the sprinkle to /shared/sprinkles/giro-winners/giro-winners.shtml\n4. Run: sprinkle open giro-winners\n5. IMPORTANT: After opening the sprinkle, do NOT finish. Stay ready — you will receive follow-up instructions and lick events for this sprinkle via feed_scoop. Do not send a completion message.")\n```\n\n**Rule 4: Modifying sprinkles** — Feed the EXISTING scoop that owns it. Do NOT create a new scoop:\n\n```\nfeed_scoop("giro-winners", "Modify YOUR sprinkle \'giro-winners\' at /shared/sprinkles/giro-winners/giro-winners.shtml:\nAdd an \'Add Previous Year\' button with onclick=\\"slicc.lick({action: \'add-year\'})\\"\nThen reload: sprinkle close giro-winners && sprinkle open giro-winners\nStay ready for more work.")\n```\n\n**Rule 5: Lick events** — Forward to owning scoop, never handle yourself:\n\n```\nfeed_scoop("giro-winners", "Lick event on YOUR sprinkle \'giro-winners\' (/shared/sprinkles/giro-winners/giro-winners.shtml):\nAction: \'add-year\'\nLook up the next previous year\'s Giro d\'Italia winner and update the sprinkle.\nUse: sprinkle send giro-winners \'<json>\' to push data, or edit the .shtml and reload.\nStay ready for more lick events.")\n```\n',fy=`# Sprinkle Component Reference
11937
+ `,yy='---\nname: sprinkles\ndescription: Create interactive sprinkles — dashboards, forms, and visualizations\nallowed-tools: bash\n---\n\n# Sprinkles\n\n`.shtml` files in `/shared/sprinkles/` become interactive UI panels. Use them to create dashboards, forms, and visualizations alongside the chat.\n\n**Two sprinkle modes**:\n\n- **Fragment mode** (default): Plain HTML fragments injected into the sidebar. Do NOT use `<!DOCTYPE html>`, `<html>`, `<head>`, `<body>`, or custom CSS — use the built-in `.sprinkle-*` classes. Scripts get a `slicc` bridge object automatically.\n- **Full-document mode**: Complete HTML documents (starting with `<!DOCTYPE html>` or `<html>`) render inside sandboxed iframes. Use this for complex layouts with custom CSS, sidebars, split panes, modals, or canvas/SVG visualizations. The bridge script is auto-injected — `window.slicc` and `window.bridge` are available in your scripts. Use `parent.postMessage` is handled internally.\n\n**When to use full-document mode**: Use it when you need custom CSS beyond `.sprinkle-*` classes, complex layouts (sidebar + main, split panes, tabs), or interactive canvas/SVG. The parent page\'s S2 theme tokens are injected automatically.\n\n**Creating a sprinkle**:\n\n1. `read_file /workspace/skills/sprinkles/style-guide.md` — **always read first** before writing any sprinkle\n2. `write_file` to `/shared/sprinkles/<name>/<name>.shtml` (follow the style guide templates)\n3. `bash` → `sprinkle open <name>`\n4. **CRITICAL: Do NOT finish or send a completion message.** You own this sprinkle for its entire lifetime. The cone will send you follow-up instructions (modifications, lick events) via `feed_scoop`. If you finish, you lose your context and cannot handle future work on this sprinkle.\n\n**Updating a sprinkle** (when you receive follow-up instructions):\n\n1. Edit `/shared/sprinkles/<name>/<name>.shtml` with the requested changes\n2. Reload: `sprinkle close <name> && sprinkle open <name>`\n3. Do NOT finish — stay ready for more instructions\n\n**Handling lick events** (when the cone forwards a user interaction):\nThe cone will send you a message with the lick action and your sprinkle name. Only modify YOUR sprinkle — the one matching your scoop name. Process the action and push updates:\n\n- `bash` → `sprinkle send <name> \'{"key":"value"}\'` to push data to the sprinkle\'s `slicc.on(\'update\', ...)` handler\n- Or edit the `.shtml` file and reload if the UI structure needs to change\n- Do NOT finish — stay ready for more events\n\n**Managing sprinkles via bash**:\n\n- `sprinkle list` — see available sprinkles\n- `sprinkle open <name>` — show a sprinkle in the sidebar\n- `sprinkle close <name>` — remove it\n- `sprinkle send <name> \'<json>\'` — push data (single-quote the JSON!)\n- `sprinkle chat \'<html>\'` — show inline HTML in the chat (for quick confirmations/choices)\n- `open /path/to/file.shtml` — also opens as a sprinkle\n\n**Bridge API** (available as `slicc` in `<script>` tags and `onclick` attributes):\n\n- `slicc.lick({action: \'refresh\', data: {...}})` — send a lick event to the cone (cone routes to the right scoop)\n- `slicc.on(\'update\', function(data) {...})` — receive data sent via `sprinkle send`\n- `slicc.name` — the sprinkle\'s name\n- `slicc.close()` — close the sprinkle\n- `slicc.stopCone()` — stop the cone agent\n- `slicc.readFile(path)` — read a VFS file (returns `Promise<string>`)\n- `slicc.writeFile(path, content)` — write text content to a VFS file\n- `slicc.readDir(path)` — list directory entries (returns `Promise<Array<{name, type}>>`)\n- `slicc.exists(path)` — check if path exists (returns `Promise<boolean>`)\n- `slicc.stat(path)` — get file metadata (returns `Promise<{type, size}>`)\n- `slicc.mkdir(path)` — create a directory (recursive)\n- `slicc.rm(path)` — remove a file\n- `slicc.screenshot(selector?)` — capture sprinkle DOM as base64 PNG data URL. Note: The screenshot captures a DOM clone using SVG foreignObject. External stylesheets and some computed styles may not be fully reproduced. For best results, use inline styles on elements you intend to screenshot.\n\n**onclick attributes**: Always use `slicc` — e.g. `onclick="slicc.lick({action: \'add-year\'})"`. The `slicc` variable is automatically resolved per-sprinkle, so multiple sprinkles won\'t collide. Do NOT use `bridge` or any other variable name in onclick.\n\n**CSS components** — Do NOT write custom CSS. Use the built-in `.sprinkle-*` classes: cards, tables, badges, buttons, text fields, progress bars, meters, layout utilities, and more. For inputs use `class="sprinkle-text-field"`, never inline border/padding styles. Run `read_file /workspace/skills/sprinkles/style-guide.md` for the full component reference with markup examples.\n\n## Built-in Sprinkles\n\nThese sprinkles ship with SLICC at `/shared/sprinkles/`. They are full-document HTML apps rendered in sandboxed iframes.\n\n| Sprinkle name | Open with | Use when the user asks for... |\n| ------------------ | -------------------------------- | --------------------------------------------------------------------- |\n| `page-editor` | `sprinkle open page-editor` | WYSIWYG editor, page editor, edit sections, visual editing |\n| `content-tree` | `sprinkle open content-tree` | content tree, page tree, site structure, page browser, navigate pages |\n| `review-workflow` | `sprinkle open review-workflow` | review, approval workflow, annotations, comments on content |\n| `seo-dashboard` | `sprinkle open seo-dashboard` | SEO audit, meta tags, SERP preview, SEO issues |\n| `schema-editor` | `sprinkle open schema-editor` | schema, structured data, JSON-LD, rich results |\n| `readability` | `sprinkle open readability` | readability, reading level, text analysis, simplify text |\n| `brand-compliance` | `sprinkle open brand-compliance` | brand check, brand compliance, style guide violations |\n| `tone-voice` | `sprinkle open tone-voice` | tone, voice, writing style, formality, tone analysis |\n| `performance` | `sprinkle open performance` | performance, Core Web Vitals, page speed, lighthouse |\n| `funnels` | `sprinkle open funnels` | funnels, conversion, A/B test, analytics |\n\n### When a user request matches a built-in sprinkle\n\nWhen the user\'s request matches a built-in sprinkle (see table above), **ask the user which approach they prefer** before proceeding:\n\n> I can help with that. Would you like me to:\n>\n> 1. **Open the built-in [sprinkle name]** — ready to use immediately, I\'ll populate it with your data\n> 2. **Build a custom one from scratch** — tailored exactly to your needs, but takes a moment to create\n>\n> Which do you prefer?\n\n**If the user says "open" / "use the built-in" / picks option 1** — use the built-in sprinkle (see "Using Built-in Sprinkles" in style-guide.md for the scoop brief template).\n\n**If the user says "build" / "create" / "custom" / picks option 2** — create a new sprinkle from scratch following the "Creating a sprinkle" flow above.\n\n**If the user explicitly says "open the page editor"** (or any built-in name directly) — skip the question and use the built-in immediately.\n\n**If the request is clearly novel** (no matching built-in) — create from scratch without asking.\n\n### Cone orchestration for sprinkles\n\n**Rule 3: Creating sprinkles** — Create a scoop, then feed it a complete, self-contained brief:\n\n```\nscoop_scoop("giro-winners")\nfeed_scoop("giro-winners", "You own the sprinkle \'giro-winners\'. Your job:\n1. Run: read_file /workspace/skills/sprinkles/style-guide.md\n2. Research the last 3 Giro d\'Italia winners\n3. Write the sprinkle to /shared/sprinkles/giro-winners/giro-winners.shtml\n4. Run: sprinkle open giro-winners\n5. IMPORTANT: After opening the sprinkle, do NOT finish. Stay ready — you will receive follow-up instructions and lick events for this sprinkle via feed_scoop. Do not send a completion message.")\n```\n\n**Rule 4: Modifying sprinkles** — Feed the EXISTING scoop that owns it. Do NOT create a new scoop:\n\n```\nfeed_scoop("giro-winners", "Modify YOUR sprinkle \'giro-winners\' at /shared/sprinkles/giro-winners/giro-winners.shtml:\nAdd an \'Add Previous Year\' button with onclick=\\"slicc.lick({action: \'add-year\'})\\"\nThen reload: sprinkle close giro-winners && sprinkle open giro-winners\nStay ready for more work.")\n```\n\n**Rule 5: Lick events** — Forward to owning scoop, never handle yourself:\n\n```\nfeed_scoop("giro-winners", "Lick event on YOUR sprinkle \'giro-winners\' (/shared/sprinkles/giro-winners/giro-winners.shtml):\nAction: \'add-year\'\nLook up the next previous year\'s Giro d\'Italia winner and update the sprinkle.\nUse: sprinkle send giro-winners \'<json>\' to push data, or edit the .shtml and reload.\nStay ready for more lick events.")\n```\n',by=`# Sprinkle Component Reference
11931
11938
 
11932
11939
  Use these CSS classes in \`.shtml\` sprinkles. Do NOT write custom CSS — these components cover all common UI patterns.
11933
11940
 
@@ -12539,7 +12546,7 @@ background: color-mix(in srgb, var(--s2-accent) 6%, transparent); /* blue tint *
12539
12546
  | \`--s2-spacing-400\` | 24px |
12540
12547
  | \`--s2-spacing-500\` | 32px |
12541
12548
  | \`--s2-spacing-600\` | 40px |
12542
- `,py=`---
12549
+ `,xy=`---
12543
12550
  name: welcome
12544
12551
  description: Handle onboarding lick from the welcome sprinkle
12545
12552
  allowed-tools: bash
@@ -12633,8 +12640,8 @@ Do NOT save a profile, update \`/shared/CLAUDE.md\`, or write a greeting.
12633
12640
 
12634
12641
  - **\`start-task\` lick** — treat as the user's first request, begin the task immediately.
12635
12642
  - **Sparse profiles** (user skipped most steps) — keep greeting brief, ask what they need.
12636
- `,my=`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=`,hy=n(`skills`),gy=Object.assign({"/packages/vfs-root/AGENTS.md":Kv,"/packages/vfs-root/CLAUDE.md":Kv,"/packages/vfs-root/shared/CLAUDE.md":qv,"/packages/vfs-root/shared/sprinkles/brand-compliance/brand-compliance.shtml":Jv,"/packages/vfs-root/shared/sprinkles/content-tree/content-tree.shtml":Yv,"/packages/vfs-root/shared/sprinkles/funnels/funnels.shtml":Xv,"/packages/vfs-root/shared/sprinkles/page-editor/page-editor.shtml":Zv,"/packages/vfs-root/shared/sprinkles/performance/performance.shtml":Qv,"/packages/vfs-root/shared/sprinkles/readability/readability.shtml":$v,"/packages/vfs-root/shared/sprinkles/review-workflow/review-workflow.shtml":ey,"/packages/vfs-root/shared/sprinkles/schema-editor/schema-editor.shtml":ty,"/packages/vfs-root/shared/sprinkles/seo-dashboard/seo-dashboard.shtml":ny,"/packages/vfs-root/shared/sprinkles/tone-voice/tone-voice.shtml":ry,"/packages/vfs-root/shared/sprinkles/welcome/welcome.shtml":iy,"/packages/vfs-root/workspace/skills/automation/SKILL.md":ay,"/packages/vfs-root/workspace/skills/inline-widgets/SKILL.md":oy,"/packages/vfs-root/workspace/skills/playwright-cli/SKILL.md":sy,"/packages/vfs-root/workspace/skills/scoop-management/SKILL.md":cy,"/packages/vfs-root/workspace/skills/skill-authoring/SKILL.md":ly,"/packages/vfs-root/workspace/skills/sprinkle-guide/SKILL.md":uy,"/packages/vfs-root/workspace/skills/sprinkles/SKILL.md":dy,"/packages/vfs-root/workspace/skills/sprinkles/style-guide.md":fy,"/packages/vfs-root/workspace/skills/welcome/SKILL.md":py}),_y=Object.assign({"/packages/vfs-root/shared/sounds/chime.mp3":my});function vy(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 yy(){let e={};for(let[t,n]of Object.entries(gy))e[t]=n;for(let[t,n]of Object.entries(_y))e[t]=vy(n);return e}function by(e){let t=new Map;for(let n of e){if(t.has(n.metadata.name)){hy.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 xy(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(`
12637
- `)){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 Sy(e,t){let n=await Cy(e,t),r=await wy(e,t),i=n.filter(e=>e.source===`native`),a=n.filter(e=>e.source!==`native`),o=by([...i,...r,...a]);return hy.info(`Skills loaded`,{count:o.length,dir:t}),o}async function Cy(e,t){let n=await de(e,t),r=[];for(let t of n)if(t.skillFilePath)try{let{metadata:n,body:i}=xy(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}),hy.debug(`Loaded discovered skill`,{name:a,path:t.skillFilePath,source:t.source})}catch{hy.debug(`Failed to load discovered skill`,{name:t.name,path:t.skillFilePath})}return r}async function wy(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}=xy(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}),hy.debug(`Loaded standalone skill`,{name:s,path:r})}catch{}}}catch{hy.debug(`Standalone skills directory not found`,{dir:t})}return n}function Ty(e){return e.length===0?``:`
12643
+ `,Sy=`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=`,Cy=n(`skills`),wy=Object.assign({"/packages/vfs-root/AGENTS.md":ey,"/packages/vfs-root/CLAUDE.md":ey,"/packages/vfs-root/shared/CLAUDE.md":ty,"/packages/vfs-root/shared/sprinkles/brand-compliance/brand-compliance.shtml":ny,"/packages/vfs-root/shared/sprinkles/content-tree/content-tree.shtml":ry,"/packages/vfs-root/shared/sprinkles/funnels/funnels.shtml":iy,"/packages/vfs-root/shared/sprinkles/page-editor/page-editor.shtml":ay,"/packages/vfs-root/shared/sprinkles/performance/performance.shtml":oy,"/packages/vfs-root/shared/sprinkles/readability/readability.shtml":sy,"/packages/vfs-root/shared/sprinkles/review-workflow/review-workflow.shtml":cy,"/packages/vfs-root/shared/sprinkles/schema-editor/schema-editor.shtml":ly,"/packages/vfs-root/shared/sprinkles/seo-dashboard/seo-dashboard.shtml":uy,"/packages/vfs-root/shared/sprinkles/tone-voice/tone-voice.shtml":dy,"/packages/vfs-root/shared/sprinkles/welcome/welcome.shtml":fy,"/packages/vfs-root/workspace/skills/automation/SKILL.md":py,"/packages/vfs-root/workspace/skills/inline-widgets/SKILL.md":my,"/packages/vfs-root/workspace/skills/playwright-cli/SKILL.md":hy,"/packages/vfs-root/workspace/skills/scoop-management/SKILL.md":gy,"/packages/vfs-root/workspace/skills/skill-authoring/SKILL.md":_y,"/packages/vfs-root/workspace/skills/sprinkle-guide/SKILL.md":vy,"/packages/vfs-root/workspace/skills/sprinkles/SKILL.md":yy,"/packages/vfs-root/workspace/skills/sprinkles/style-guide.md":by,"/packages/vfs-root/workspace/skills/welcome/SKILL.md":xy}),Ty=Object.assign({"/packages/vfs-root/shared/sounds/chime.mp3":Sy});function Ey(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 Dy(){let e={};for(let[t,n]of Object.entries(wy))e[t]=n;for(let[t,n]of Object.entries(Ty))e[t]=Ey(n);return e}function Oy(e){let t=new Map;for(let n of e){if(t.has(n.metadata.name)){Cy.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 ky(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(`
12644
+ `)){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 Ay(e,t){let n=await jy(e,t),r=await My(e,t),i=n.filter(e=>e.source===`native`),a=n.filter(e=>e.source!==`native`),o=Oy([...i,...r,...a]);return Cy.info(`Skills loaded`,{count:o.length,dir:t}),o}async function jy(e,t){let n=await de(e,t),r=[];for(let t of n)if(t.skillFilePath)try{let{metadata:n,body:i}=ky(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}),Cy.debug(`Loaded discovered skill`,{name:a,path:t.skillFilePath,source:t.source})}catch{Cy.debug(`Failed to load discovered skill`,{name:t.name,path:t.skillFilePath})}return r}async function My(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}=ky(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}),Cy.debug(`Loaded standalone skill`,{name:s,path:r})}catch{}}}catch{Cy.debug(`Standalone skills directory not found`,{dir:t})}return n}function Ny(e){return e.length===0?``:`
12638
12645
  ---
12639
12646
  AVAILABLE SKILLS
12640
12647
 
@@ -12643,9 +12650,9 @@ The following skills are available. To use a skill, first read its full instruct
12643
12650
 
12644
12651
  ${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(`
12645
12652
  `)}
12646
- ---`}async function Ey(e,t=`/workspace/skills`){let n=yy();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),hy.info(`Created default file`,{path:s})}}}async function Dy(e){let t=yy();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),hy.info(`Created default shared file`,{path:t})}}}var Oy=n(`scoop-management-tools`);function ky(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),Oy.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),Oy.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(`
12647
- `)}`}}}),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 Oy.info(`Scoop created`,{name:t,folder:a}),i&&r?(r(e.jid,i).catch(e=>{let n=e instanceof Error?e.message:String(e);Oy.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),Oy.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),Oy.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 Ay=n(`secret-env`);async function jy(){if(typeof chrome<`u`&&chrome?.runtime?.id)return{};try{let e=await fetch(`/api/secrets/masked`);if(!e.ok)return Ay.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&&Ay.info(`Loaded masked secrets into shell env`,{count:Object.keys(n).length}),n}catch(e){return Ay.debug(`Could not fetch masked secrets (server may be unavailable)`,{error:e instanceof Error?e.message:String(e)}),{}}}var My=n(`scoop-context`);function Ny(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 Py=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`);My.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 Ey(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await jy();this.shell=new Fv({fs:this.fs,cwd:e,env:Object.keys(r).length>0?r:void 0,browserAPI:t,jshDiscoveryFs:this.skillsFs?n:void 0}),My.info(`WasmShell initialized`,{folder:this.scoop.folder});let i=await Sy(n,this.skillsDir),a=ky({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([...Lv(this.fs),Gv(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=ie();throw Error(`No API key configured for provider "${e}"`)}let u=this.scoop.config?.modelId?S(this.scoop.config.modelId):re(),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,My.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:p.length}))}catch(e){My.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`),My.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);My.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){My.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);My.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=re();this.agent.state.model=e,My.info(`Model updated on running agent`,{folder:this.scoop.folder,model:e.id})}async reloadSkills(){if(!this.agent)return;let e=await Sy(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,My.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(`
12648
- `),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&&Ny(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=>{My.error(`Failed to save agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})});break}}}recoverFromOverflow(e){if(this.agent){My.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++,My.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=>{My.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){My.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){My.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=>{My.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){My.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
12653
+ ---`}async function Py(e,t=`/workspace/skills`){let n=Dy();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),Cy.info(`Created default file`,{path:s})}}}async function Fy(e){let t=Dy();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),Cy.info(`Created default shared file`,{path:t})}}}var Iy=n(`scoop-management-tools`);function Ly(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),Iy.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),Iy.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(`
12654
+ `)}`}}}),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 Iy.info(`Scoop created`,{name:t,folder:a}),i&&r?(r(e.jid,i).catch(e=>{let n=e instanceof Error?e.message:String(e);Iy.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),Iy.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),Iy.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 Ry=n(`secret-env`);async function zy(){if(typeof chrome<`u`&&chrome?.runtime?.id)return{};try{let e=await fetch(`/api/secrets/masked`);if(!e.ok)return Ry.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&&Ry.info(`Loaded masked secrets into shell env`,{count:Object.keys(n).length}),n}catch(e){return Ry.debug(`Could not fetch masked secrets (server may be unavailable)`,{error:e instanceof Error?e.message:String(e)}),{}}}var By=n(`scoop-context`);function Vy(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 Hy=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`);By.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 Py(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await zy();this.shell=new Uv({fs:this.fs,cwd:e,env:Object.keys(r).length>0?r:void 0,browserAPI:t,jshDiscoveryFs:this.skillsFs?n:void 0}),By.info(`WasmShell initialized`,{folder:this.scoop.folder});let i=await Ay(n,this.skillsDir),a=Ly({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([...Gv(this.fs),$v(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,By.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:p.length}))}catch(e){By.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`),By.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);By.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){By.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);By.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,By.info(`Model updated on running agent`,{folder:this.scoop.folder,model:e.id})}async reloadSkills(){if(!this.agent)return;let e=await Ay(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,By.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(`
12655
+ `),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&&Vy(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=>{By.error(`Failed to save agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})});break}}}recoverFromOverflow(e){if(this.agent){By.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++,By.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=>{By.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){By.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){By.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=>{By.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){By.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
12649
12656
 
12650
12657
  ${this.scoop.isCone?`Role: Cone (main orchestrator)`:`Scoop: ${this.scoop.name}`}
12651
12658
  Folder: ${this.scoop.folder}
@@ -12724,12 +12731,32 @@ ${e}
12724
12731
  ---
12725
12732
  ${this.scoop.isCone?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
12726
12733
  ${t}
12727
- ---`);let a=Ty(n);return a&&(i+=a),i}},Fy=n(`scheduler`),Iy=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(),Fy.info(`Scheduler started`))}stop(){this.pollInterval&&=(clearInterval(this.pollInterval),null),this.running=!1,Fy.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),Fy.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),Fy.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),Fy.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){Fy.warn(`Task scoop not found`,{taskId:e.id,groupFolder:e.groupFolder});return}Fy.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),Fy.info(`Task completed`,{id:e.id})}catch(t){Fy.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}},Ly=n(`lick-manager`),Ry=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);Ly.info(`Loaded webhooks`,{count:this.webhooks.size});let t=await Le();for(let e of t)this.crontasks.set(e.id,e);Ly.info(`Loaded crontasks`,{count:this.crontasks.size}),this.cronInterval=setInterval(()=>this.runCronScheduler(),6e4),Ly.info(`Cron scheduler started`)}dispose(){this.cronInterval&&=(clearInterval(this.cronInterval),null)}setEventHandler(e){this.eventHandler=e}emitEvent(e){Ly.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),Ly.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),Ly.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){Ly.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){Ly.debug(`Webhook event dropped by filter`,{webhookId:e,name:r.name});return}typeof t==`object`&&t&&(i=t)}catch(t){Ly.error(`Webhook filter error`,{webhookId:e,error:t instanceof Error?t.message:String(t)})}Ly.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),Ly.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),Ly.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){Ly.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){Ly.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};Ly.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 zy(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(`
12728
- `);return Error(`Cannot remove scoop '${e}': it has ${r.join(` and `)}. Unregister them first:\n${i}`)}var By=null;function Vy(){return By||=new Ry,By}var Q=n(`orchestrator`),Hy=120*1e3,Uy=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;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 I.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 Iy({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 Dy(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=zy(t.folder,e,n);if(r)throw r}this.clearIdleTimer(e),await this.destroyScoopTab(e),this.sessionStore?.delete(e).catch(t=>{Q.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await 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 I.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.ensureGlobalMemory(),await Ey(this.sharedFs).catch(e=>{Q.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),Q.info(`Filesystem reset and defaults re-seeded`)}async clearAllMessages(){await 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,[]);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);Cv(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`;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 Py(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)+`
12734
+ ---`);let a=Ny(n);return a&&(i+=a),i}},Uy=n(`scheduler`),Wy=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(),Uy.info(`Scheduler started`))}stop(){this.pollInterval&&=(clearInterval(this.pollInterval),null),this.running=!1,Uy.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),Uy.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),Uy.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),Uy.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){Uy.warn(`Task scoop not found`,{taskId:e.id,groupFolder:e.groupFolder});return}Uy.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),Uy.info(`Task completed`,{id:e.id})}catch(t){Uy.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}},Gy=n(`lick-manager`),Ky=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);Gy.info(`Loaded webhooks`,{count:this.webhooks.size});let t=await Le();for(let e of t)this.crontasks.set(e.id,e);Gy.info(`Loaded crontasks`,{count:this.crontasks.size}),this.cronInterval=setInterval(()=>this.runCronScheduler(),6e4),Gy.info(`Cron scheduler started`)}dispose(){this.cronInterval&&=(clearInterval(this.cronInterval),null)}setEventHandler(e){this.eventHandler=e}emitEvent(e){Gy.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),Gy.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),Gy.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){Gy.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){Gy.debug(`Webhook event dropped by filter`,{webhookId:e,name:r.name});return}typeof t==`object`&&t&&(i=t)}catch(t){Gy.error(`Webhook filter error`,{webhookId:e,error:t instanceof Error?t.message:String(t)})}Gy.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),Gy.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),Gy.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){Gy.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){Gy.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};Gy.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 qy(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(`
12735
+ `);return Error(`Cannot remove scoop '${e}': it has ${r.join(` and `)}. Unregister them first:\n${i}`)}var Jy=null;function Yy(){return Jy||=new Ky,Jy}var Q=n(`orchestrator`),Xy=120*1e3,Zy=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 Wy({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 Fy(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=qy(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 Py(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);jv(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 Hy(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)+`
12729
12736
  ... (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(`
12730
- `);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()}getSessionCosts(){let e=[];for(let t of this.scoops.values()){let n=this.contexts.get(t.jid);if(!n)continue;let r=n.getAgentMessages().filter(e=>e.role===`assistant`);if(r.length===0)continue;let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},a=new Map;for(let e of r)i.input+=e.usage.input,i.output+=e.usage.output,i.cacheRead+=e.usage.cacheRead,i.cacheWrite+=e.usage.cacheWrite,i.totalTokens+=e.usage.totalTokens,i.cost.input+=e.usage.cost.input,i.cost.output+=e.usage.cost.output,i.cost.cacheRead+=e.usage.cost.cacheRead,i.cost.cacheWrite+=e.usage.cost.cacheWrite,i.cost.total+=e.usage.cost.total,a.set(e.model,(a.get(e.model)??0)+1);let o=``,s=0;for(let[e,t]of a)t>s&&(o=e,s=t);e.push({name:t.assistantLabel,type:t.isCone?`cone`:`scoop`,model:o,usage:i,turns:r.length})}return e}startIdleTimer(e){if(this.clearIdleTimer(e),this.tabs.get(e)?.status===`processing`)return;let t=setTimeout(()=>{this.idleTimers.delete(e);let t=this.scoops.get(e);if(!t||t.isCone||this.tabs.get(e)?.status!==`ready`)return;let n=Array.from(this.scoops.values()).find(e=>e.isCone);if(!n)return;let r={id:`scoop-idle-${e}-${Date.now()}`,chatJid:n.jid,senderId:t.folder,senderName:t.assistantLabel,content:`[@${t.assistantLabel} idle]: Scoop "${t.name}" has been ready for 2 minutes without receiving any work. This is expected if the scoop is waiting for webhooks or cron tasks. If you intended to delegate work, use feed_scoop to send a prompt.`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-idle`};Q.info(`Scoop idle timeout`,{jid:e,scoop:t.folder}),this.handleMessage(r).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Failed to send idle notification`,{jid:e,error:n})})},Hy);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 Wy=n(`tray-follower`);function Gy(e){let t=new URL(e);return t.searchParams.set(`json`,`true`),t.toString()}async function Ky(e){let t=Gy(e.joinUrl),n=await $y(await(e.fetchImpl??fetch)(t,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:e.controllerId,runtime:e.runtime})}));return Wy.info(`Follower tray attach response`,{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),qy(n)}function qy(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 Jy(e){return Qy(await eb(e,{action:`poll`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function Yy(e){return Qy(await eb(e,{action:`answer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function Xy(e){return Qy(await eb(e,{action:`ice-candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function Zy(e){return Qy(await eb(e,{action:`retry`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function Qy(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function $y(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!tb(n)){let n=t?t.slice(0,200):`(empty)`;throw Wy.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 eb(e,t){let n=Gy(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(!nb(i))throw Error(`Tray follower bootstrap returned an invalid response (${r.status})`);return i}function tb(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`&&rb(r.bootstrap):r.action===`fail`?(r.code===`INVALID_JOIN_CAPABILITY`||r.code===`TRAY_EXPIRED`)&&typeof r.error==`string`:!1}function nb(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`&&rb(t.bootstrap)&&Array.isArray(t.events)}function rb(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 ib=n(`tray-webrtc`),ab=`tray-control`,ob=250,sb=class{peerConnectionFactory;dataChannelLabel;peers=new Map;iceServers;constructor(e){this.options=e,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>ub(this.iceServers)),this.dataChannelLabel=e.dataChannelLabel??ab}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=fb(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`)&&(ib.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`?(ib.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`?(ib.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:db(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){ib.warn(`Failed to report tray bootstrap failure`,{error:e instanceof Error?e.message:String(e)})}}}},cb=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??(()=>ub(this.iceServers)),this.controllerIdFactory=e.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),this.pollIntervalMs=e.pollIntervalMs??ob}async start(){this.stopped=!1;let e=this.controllerIdFactory(),t=Date.now();f({state:`connecting`,joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:t,lastError:null}),ib.info(`Follower tray join starting`,{joinUrl:this.options.joinUrl});let n=0;for(;;){pb(this.stopped),n++;let t;try{t=await Ky({joinUrl:this.options.joinUrl,controllerId:e,runtime:this.options.runtime,fetchImpl:this.fetchImpl})}catch(e){let t=e instanceof Error?e.message:String(e);throw f({...m(),attachAttempts:n,lastError:t}),e}if(f({...m(),attachAttempts:n,lastAttachCode:t.code}),t.action===`wait`){let e=t.retryAfterMs??1e3;ib.info(`Follower tray attach waiting`,{attempt:n,code:t.code,retryAfterMs:e}),n%10==0&&ib.warn(`Follower tray attach still waiting after ${n} attempts`,{attempt:n,code:t.code,retryAfterMs:e}),await this.sleep(e);continue}if(t.action===`fail`||!t.bootstrap){let e=t.error??`Tray follower attach failed (${t.code})`;throw f({state:`error`,joinUrl:this.options.joinUrl,trayId:null,error:e,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:e}),ib.warn(`Follower tray attach failed`,{error:e}),Error(e)}t.iceServers&&(this.iceServers=t.iceServers);try{let r=await this.completeBootstrap(t.trayId,e,t.bootstrap);return f({state:`connected`,joinUrl:this.options.joinUrl,trayId:r.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:null}),ib.info(`Follower tray connected`,{trayId:r.trayId,controllerId:e}),r}catch(e){let r=e instanceof Error?e.message:String(e);throw f({state:`error`,joinUrl:this.options.joinUrl,trayId:t.trayId,error:r,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:r}),ib.warn(`Follower tray bootstrap failed`,{error:r}),e}}}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,f({state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null})}async completeBootstrap(e,t,n){let r=n,i=0;for(this.activePeer=this.createFollowerPeer(t,r.bootstrapId);;){if(pb(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 Jy({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 Yy({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,answer:db(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 Zy({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`)&&(ib.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?(ib.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?(ib.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=fb(n);r&&Xy({joinUrl:this.options.joinUrl,controllerId:e,bootstrapId:t,candidate:r,fetchImpl:this.fetchImpl}).catch(e=>{ib.warn(`Failed to send follower ICE candidate`,{error:e instanceof Error?e.message:String(e)})})}),r}};function lb(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 cb({...e,sleep:o,onDisconnected:e=>{s||(ib.warn(`Follower disconnected, starting reconnect loop`,{reason:e}),p(e))}});return l=t,{manager:t,connectionPromise:t.start()}},p=async u=>{if(s||c)return;c=!0,l?.stop(),l=null;let p=0,h=n,g=u??`Unknown disconnect`;for(;!s&&p<a&&(p++,t.onReconnecting?.(p),f({...m(),state:`reconnecting`,error:null,reconnectAttempts:p}),ib.info(`Reconnect attempt`,{attempt:p,delay:h}),await o(h),!s);){let n=null;try{let r=d();n=r.manager;let i=await r.connectionPromise;if(s){n.stop();break}c=!1,f({...m(),state:`connected`,joinUrl:e.joinUrl,trayId:i.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),ib.info(`Reconnect successful`,{attempt:p,trayId:i.trayId}),t.onConnected(i);return}catch(e){g=e instanceof Error?e.message:String(e),ib.warn(`Reconnect attempt failed`,{attempt:p,error:g}),n?.stop(),l=null}h=Math.min(h*r,i)}s||(c=!1,f({...m(),state:`error`,error:`Reconnect failed after ${p} attempts: ${g}`,reconnectAttempts:p}),ib.warn(`Reconnect gave up`,{attempts:p,lastError:g}),t.onGaveUp?.(g))},{connectionPromise:h}=d();return h.then(e=>{s||t.onConnected(e)}).catch(e=>{s||ib.warn(`Initial follower connection failed`,{error:e instanceof Error?e.message:String(e)})}),u}function ub(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 db(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 fb(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 pb(e){if(e)throw Error(`Tray follower stopped before WebRTC bootstrap completed`)}var mb=64*1024;async function hb(e,t){try{switch(t.op){case`readFile`:return await gb(e,t.path,t.encoding);case`writeFile`:return[await _b(e,t.path,t.content,t.encoding)];case`stat`:return[await vb(e,t.path)];case`readDir`:return[await yb(e,t.path)];case`mkdir`:return[await bb(e,t.path,t.recursive)];case`rm`:return[await xb(e,t.path,t.recursive)];case`exists`:return[await Sb(e,t.path)];case`walk`:return[await Cb(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(e){return[Tb(e)]}}async function gb(e,t,n){return(n??`utf-8`)===`utf-8`?wb(await e.readFile(t,{encoding:`utf-8`}),`utf-8`):wb(Eb(await e.readFile(t,{encoding:`binary`})),`base64`)}async function _b(e,t,n,r){if(r===`base64`){let r=Db(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:`void`}}}async function vb(e,t){return{ok:!0,data:{type:`stat`,stat:await e.stat(t)}}}async function yb(e,t){return{ok:!0,data:{type:`dirEntries`,entries:await e.readDir(t)}}}async function bb(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function xb(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function Sb(e,t){return{ok:!0,data:{type:`exists`,exists:await e.exists(t)}}}async function Cb(e,t){let n=[];for await(let r of e.walk(t))n.push(r);return{ok:!0,data:{type:`paths`,paths:n}}}function wb(e,t){if(e.length<=mb)return[{ok:!0,data:{type:`file`,content:e,encoding:t}}];let n=Math.ceil(e.length/mb),r=[];for(let i=0;i<n;i++){let a=i*mb,o=e.slice(a,a+mb);r.push({ok:!0,data:{type:`file`,content:o,encoding:t},chunkIndex:i,totalChunks:n})}return r}function Tb(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 Eb(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Db(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 Ob=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()]}},kb=n(`data-channel-keepalive`),Ab=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++,kb.debug(`Missed pong`,{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){kb.warn(`Channel declared dead`,{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}},jb=n(`tray-leader-sync`);function Mb(e){return e?e.includes(`standalone`)?`standalone`:e.includes(`extension`)?`extension`:e.includes(`electron`)?`electron`:`unknown`:`unknown`}var Nb=class{followers=new Map;registry=new Ob;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 Ab({sendPing:()=>r.send({type:`ping`}),onDead:()=>{jb.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:Mb(n?.runtime)}),jb.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(),jb.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),jb.debug(`Snapshot sent to follower`,{bootstrapId:e,messageCount:n.length})}handleFollowerMessage(e,t){switch(t.type){case`user_message`:jb.info(`Follower user message received`,{bootstrapId:e,messageId:t.messageId}),this.options.onFollowerMessage(t.text,t.messageId);break;case`abort`:jb.info(`Follower abort received`,{bootstrapId:e}),this.options.onFollowerAbort();break;case`request_snapshot`:jb.info(`Follower snapshot request received`,{bootstrapId:e}),this.sendSnapshotToFollower(e);break;case`targets.advertise`:jb.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),jb.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),jb.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 hb(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?hb(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})})}},Pb=n(`tray-follower-sync`),Fb=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 Ab({sendPing:()=>this.sync.send({type:`ping`}),onDead:()=>{Pb.warn(`Leader keepalive dead, cleaning up`),this.handleDisconnect(`Keepalive timeout — leader not responding`),this.options.onDead?.()}}),this.keepalive.start(),e.addEventListener(`close`,()=>{Pb.warn(`Data channel closed`),this.handleDisconnect(`Data channel closed`)}),e.addEventListener(`error`,()=>{Pb.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}),Pb.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`}),Pb.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(),Pb.info(`Follower sync closed`)}advertiseTargets(e,t){this.sync.send({type:`targets.advertise`,targets:e,runtimeId:t})}getTargets(){return this.targetEntries}disconnected=!1;handleDisconnect(e){this.disconnected||(this.disconnected=!0,f({...m(),state:`error`,error:e}),this.emitEvent({type:`error`,error:`Connection to leader lost: ${e}`}),this.keepalive.stop(),this.cleanupCDPEventForwarding(),this.unsubscribe(),this.sync.close(),this.options.onDisconnect?.(e))}handleLeaderMessage(e){switch(e.type){case`snapshot`:Pb.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&&(Pb.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),Pb.debug(`Skipping own message echo`,{messageId:e.messageId});break}Pb.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`:Pb.warn(`Error from leader`,{error:e.error}),this.emitEvent({type:`error`,error:e.error});break;case`targets.registry`:Pb.info(`Target registry received from leader`,{targetCount:e.targets.length}),this.targetEntries=e.targets,this.options.onTargetsUpdated?.(this.targetEntries);break;case`cdp.request`:{let{requestId:t,localTargetId:n,method:r,params:i,sessionId:a}=e;this.executeLocalCDP(t,n,r,i,a);break}case`cdp.response`:this.routeCDPResponse(e);break;case`cdp.event`:for(let t of this.remoteTransports.values())t.handleEvent(e.method,e.params);break;case`tab.open`:this.executeLocalTabOpen(e.requestId,e.url);break;case`tab.opened`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.resolve(e.targetId));break}case`tab.open.error`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.reject(Error(e.error)));break}case`fs.request`:this.executeLocalFs(e.requestId,e.request);break;case`fs.response`:this.routeFsResponse(e.requestId,e.response);break;case`ping`:this.keepalive.receivePing(),this.sync.send({type:`pong`});break;case`pong`:this.keepalive.receivePong(),l(Date.now());break}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch(t){Pb.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),Pb.debug(`Tracking remote CDP session`,{remoteSessionId:e})}n===`Target.detachFromTarget`&&i&&this.remoteCDPSessions.has(i)&&(this.remoteCDPSessions.delete(i),Pb.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 hb(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 Ib(e,t){if(t)return`extension`;try{return zb(new URL(e))?`electron-overlay`:`standalone`}catch{return`standalone`}}function Lb(e,t){return e===`electron-overlay`||e===`standalone`&&t}function Rb(e){try{let t=new URL(e).searchParams.get(`tab`);return t&&qi(t)?t:Gi}catch{return Gi}}function zb(e){return e.pathname===`/electron`||e.pathname===`/electron/`||e.searchParams.get(`runtime`)===`electron-overlay`}function Bb(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}/licks-ws`}function Vb(e,t){return`${new URL(e).origin}/webhooks/${t}`}function Hb(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function Ub(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`slicc-electron-overlay:set-tab`}var Wb=[`/shared/sprinkles`];async function Gb(e){let t=new Map;for(let n of Wb)await e.exists(n)&&await Kb(e,n,t);return await Kb(e,`/`,t),t}async function Kb(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.shtml`))continue;let t=qb(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:Jb(i,t),autoOpen:Yb(i)})}}}function qb(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.shtml`)?t.slice(0,-6):t}function Jb(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 Yb(e){return/data-sprinkle-autoopen\b/.test(e)}var Xb=class{listeners=new Map;lickHandler;fs;closeHandler;stopConeHandler;constructor(e,t,n,r){this.fs=e,this.lickHandler=t,this.closeHandler=n,this.stopConeHandler=r}createAPI(e){let t={name:e,lick:t=>{let n=typeof t==`string`?t:t.action,r=typeof t==`string`?void 0:t.data,i={type:`sprinkle`,sprinkleName:e,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:n,data:r}};this.lickHandler(i)},on:(t,n)=>{let r=`${e}:${t}`,i=this.listeners.get(r);i||(i=new Set,this.listeners.set(r,i)),i.add(n)},off:(t,n)=>{let r=`${e}:${t}`;this.listeners.get(r)?.delete(n)},readFile:async e=>await this.fs.readFile(e,{encoding:`utf-8`}),writeFile:async(e,t)=>{await this.fs.writeFile(e,t)},readDir:async e=>(await this.fs.readDir(e)).map(e=>({name:e.name,type:e.type})),exists:async e=>this.fs.exists(e),stat:async e=>{let t=await this.fs.stat(e);return{type:t.type,size:t.size}},mkdir:async e=>{await this.fs.mkdir(e,{recursive:!0})},rm:async e=>{await this.fs.rm(e)},screenshot:async e=>{let n=t._container;if(!n)return``;let r=e?n.querySelector(e):n;if(!r)throw Error(`Element not found: `+(e||`container`));let i=r.getBoundingClientRect(),a=Math.ceil(i.width),o=Math.ceil(i.height);if(a===0||o===0)throw Error(`Element has zero dimensions`);let s=document.createElement(`canvas`),c=window.devicePixelRatio||1;s.width=a*c,s.height=o*c;let l=s.getContext(`2d`);l.scale(c,c);let u=r.cloneNode(!0),d=`<svg xmlns="http://www.w3.org/2000/svg" width="${a}" height="${o}"><foreignObject width="100%" height="100%">${new XMLSerializer().serializeToString(u)}</foreignObject></svg>`;return new Promise((e,t)=>{let n=new Image;n.onload=()=>{l.drawImage(n,0,0),e(s.toDataURL(`image/png`))},n.onerror=()=>t(Error(`Screenshot rendering failed`)),n.src=`data:image/svg+xml;charset=utf-8,`+encodeURIComponent(d)})},setState:t=>{try{localStorage.setItem(`slicc-sprinkle-state:${e}`,JSON.stringify(t))}catch{}},getState:()=>{try{let t=localStorage.getItem(`slicc-sprinkle-state:${e}`);return t?JSON.parse(t):null}catch{return null}},open:e=>{let t=/^https?:|^chrome-extension:/.test(e)?e:wm(e);window.open(t,`_blank`)},close:()=>this.closeHandler(e),stopCone:()=>this.stopConeHandler()};return t}pushUpdate(e,t){let n=`${e}:update`,r=this.listeners.get(n);if(r)for(let e of r)try{e(t)}catch{}}removeSprinkle(e){for(let t of this.listeners.keys())t.startsWith(`${e}:`)&&this.listeners.delete(t)}},Zb=n(`sprinkle-manager`),Qb=`slicc-open-sprinkles`,$b=class{fs;bridge;callbacks;availableSprinkles=new Map;watcherUnsub;openSprinkles=new Map;constructor(e,t,n,r){this.fs=e,this.bridge=new Xb(e,t,e=>this.close(e),r),this.callbacks=n}async restoreOpenSprinkles(){try{let e=localStorage.getItem(Qb);if(!e){for(let e of this.availableSprinkles.values())if(e.autoOpen)try{await this.open(e.name)}catch{Zb.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{Zb.warn(`Failed to restore sprinkle`,{name:e})}}catch{}}persistOpenSprinkles(){try{localStorage.setItem(Qb,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),Zb.info(`Auto-opened new sprinkle after install`,{name:e.name})}catch{Zb.warn(`Failed to auto-open new sprinkle`,{name:e.name})}}async refresh(){this.availableSprinkles=await Gb(this.fs),Zb.info(`Discovered sprinkles`,{count:this.availableSprinkles.size})}async open(e,t){if(this.openSprinkles.has(e)){Zb.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 ai(i,this.bridge.createAPI(e));await a.render(r,e),this.openSprinkles.get(e).renderer=a,this.persistOpenSprinkles(),Tv(e),Zb.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(),Zb.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){Zb.warn(`Cannot send to closed sprinkle`,{name:e});return}this.bridge.pushUpdate(e,t),n.renderer.pushUpdate(t)}};function ex(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function tx(e){let t=[],{payload:n}=e;if(n.title&&t.push(`# ${n.title}`),t.push(`A new handoff was accepted from ${ex(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(`
12731
-
12732
- `)}function nx(e,t){return e.receivedAt.localeCompare(t.receivedAt)}var rx=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(nx))}},$=n(`main`),ix=`slicc-pending-mount`,ax=`pendingMount`;async function ox(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(ix,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,ax),await new Promise(e=>n.oncomplete=()=>e()),t.close()}async function sx(e){let t;try{t=await new Promise((e,t)=>{let n=indexedDB.open(ix,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(ax);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)});if(r){n.objectStore(`handles`).delete(ax),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 cx(){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 lx(){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 ux(e,t,n){let r=cx(),i=0,a=!1,o=()=>{i=0,a||r.hide()};window.addEventListener(`dragenter`,e=>{ha(e.dataTransfer)&&(e.preventDefault(),i+=1,a||r.show(`Drop .skill to install`,`Unpack into /workspace/skills/{name}.`))}),window.addEventListener(`dragover`,e=>{ha(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=ga(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 dx(e){let{OffscreenClient:t}=await v(async()=>{let{OffscreenClient:e}=await import(`./offscreen-client-BIdj4gf1.js`);return{OffscreenClient:e}},__vite__mapDeps([22,15])),{VirtualFS:n}=await v(async()=>{let{VirtualFS:e}=await import(`./fs-Br5jEe6j.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([20,1,15])),r=new Qi(e,!0);window.__slicc_debug_tabs=e=>r.setDebugTabs(e),await r.panels.chat.initSession(`session-cone`);let i=null,a=await n.create({dbName:`slicc-fs`});r.panels.fileBrowser.setFs(a),$.info(`File browser wired to shared VFS (local IndexedDB)`);let o=new BroadcastChannel(`preview-vfs`);o.onmessage=e=>{if(e.data?.type!==`preview-vfs-read`)return;let{id:t,path:n,asText:r}=e.data;(async()=>{try{let e=r?`utf-8`:`binary`,i=await a.readFile(n,{encoding:e});o.postMessage({type:`preview-vfs-response`,id:t,content:i})}catch(e){let r=e instanceof Error?e.message:String(e);r.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:n,error:r}),o.postMessage({type:`preview-vfs-response`,id:t,error:r})}})()},ux(a,lx(),async()=>{await r.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await v(async()=>{let{WasmShell:e}=await import(`./shell-B45M6r84.js`);return{WasmShell:e}},[]),{PanelCdpProxy:t,BrowserAPI:n}=await v(async()=>{let{PanelCdpProxy:e,BrowserAPI:t}=await import(`./cdp-B4yzwpE0.js`).then(e=>e.t);return{PanelCdpProxy:e,BrowserAPI:t}},__vite__mapDeps([23,1,4,15])),{fetchSecretEnvVars:i}=await v(async()=>{let{fetchSecretEnvVars:e}=await import(`./secret-env-OKzGv9D2.js`);return{fetchSecretEnvVars:e}},[]),o=new t;await o.connect();let s=new n(o),c=await i(),l=new e({fs:a,browserAPI:s,env:Object.keys(c).length>0?c:void 0});await r.panels.terminal.mountShell(l),$.info(`Terminal mounted with shared VFS and BrowserAPI (CDP proxy)`)}catch(e){$.warn(`Failed to mount shell to terminal`,e)}{let{registerSessionCostsProvider:e}=await v(async()=>{let{registerSessionCostsProvider:e}=await import(`./cost-command-DhUP8Ozj.js`).then(e=>e.t);return{registerSessionCostsProvider:e}},__vite__mapDeps([24,1]));e(()=>new Promise(e=>{chrome.runtime.sendMessage({source:`panel`,payload:{type:`get-session-costs`}},t=>{if(chrome.runtime.lastError||!t?.ok){e([]);return}e(t.costs??[])})}))}let c,l=new Set,u=e=>{r.setPendingHandoffCount(e.length),r.panels.chat.setPendingHandoffs(e)},d=async e=>{i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid),r.setScoopSwitcherSelected?.(e.jid),r.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=e.isCone?void 0:e.name;await r.panels.chat.switchToContext(t,!e.isCone,n),c.isProcessing(e.jid)&&r.panels.chat.setProcessing(!0)};c=new t({onStatusChange:(e,t)=>{r.panels.scoops.updateScoopStatus(e,t),r.updateScoopSwitcherStatus?.(e,t),i?.jid===e&&(r.setAgentProcessing(t===`processing`),t===`processing`?r.panels.chat.setProcessing(!0):t===`ready`&&r.panels.chat.setProcessing(!1))},onScoopCreated:e=>{r.panels.scoops.refreshScoops(),r.refreshScoopSwitcher?.(),i||(i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid))},onScoopListUpdate:()=>{let e=new Set(c.getScoops().map(e=>e.folder));for(let t of l)e.has(t)||r.panels.chat.deleteSessionById(`session-${t}`);if(l=e,r.panels.scoops.refreshScoops(),r.refreshScoopSwitcher?.(),!i){let e=c.getScoops().find(e=>e.isCone);e&&(i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid))}},onIncomingMessage:(e,t)=>{if(i?.jid===e){let e=t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content;r.panels.chat.addUserMessage(e)}},onPendingHandoffsChange:u,onReady:async()=>{try{$.info(`Offscreen engine ready, scoop count:`,c.getScoops().length),window.localStorage.getItem(`slicc.trayJoinUrl`)&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`refresh-tray-runtime`}}).catch(()=>{});let e=i??c.getScoops().find(e=>e.isCone)??c.getScoops()[0];e&&(i=e,c.selectedScoopJid=e.jid,await d(e))}catch(e){$.error(`Failed to initialize on ready`,{error:e instanceof Error?e.message:String(e)})}}}),c.setLocalFS(a);let f=c.createAgentHandle();r.panels.chat.setAgent(f),r.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=c.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await d(t),r.setActiveTab(`chat`),f.sendMessage(tx(e),`handoff-${e.handoffId}`),c.acceptPendingHandoff(e.handoffId)},onDismiss:e=>{c.dismissPendingHandoff(e.handoffId)}}),c.requestPendingHandoffs(),r.panels.scoops.setOrchestrator(c),r.panels.memory.setOrchestrator(c),r.setScoopSwitcherOrchestrator?.(c),r.onScoopSelect=d,r.onModelChange=e=>{localStorage.setItem(`selected-model`,e),c.updateModel()},r.onClearChat=async()=>{let e=c.getScoops();for(let t of e){let e=t.isCone?`session-cone`:`session-${t.folder}`;await r.panels.chat.deleteSessionById(e)}c.clearAllMessages()},r.onClearFilesystem=async()=>{c.clearFilesystem()},r.panels.chat.onInlineSprinkleLick=(e,t)=>{c.sendSprinkleLick(`inline`,{action:e,data:t})};let p=new $b(a,async e=>{if(e.type===`sprinkle`){if(e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&a.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome completion marker`,e)),n===`shortcut-migrate`&&p.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&sx(a).catch(e=>$.warn(`Failed to mount workspace from onboarding`,e))}if(e.sprinkleName===`welcome`&&e.body?.action===`request-mount`){try{let e=window;if(!e.showDirectoryPicker)throw Error(`showDirectoryPicker not supported`);let t=await e.showDirectoryPicker({mode:`readwrite`});await ox(t),p.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),p.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}return}c.sendSprinkleLick(e.sprinkleName,e.body)}},{addSprinkle:(e,t,n,i)=>r.addSprinkle(e,t,n,i),removeSprinkle:e=>r.removeSprinkle(e)},()=>{let e=c.getScoops().find(e=>e.isCone);e&&c.stopScoop(e.jid)});if(window.__slicc_sprinkleManager=p,window.__slicc_reloadSkills=()=>(chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}}),Promise.resolve()),c.setSprinkleOpHandler(e=>{let{id:t,op:n,name:r,data:i}=e;console.log(`[main-ext] sprinkle-op handler called`,{id:t,op:n,name:r}),(async()=>{try{let e;switch(n){case`list`:await p.refresh(),e=p.available();break;case`opened`:e=p.opened();break;case`refresh`:await p.refresh(),e=p.available().length;break;case`open`:await p.open(r),e=!0;break;case`close`:p.close(r),e=!0;break;case`send`:p.sendToSprinkle(r,i),e=!0;break;case`openNewAutoOpen`:await p.openNewAutoOpenSprinkles(),e=!0;break}console.log(`[main-ext] sprinkle-op response sending`,{id:t,op:n,result:typeof e}),chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,result:e}}).catch(()=>{})}catch(e){chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}})()}),await p.refresh(),r.onSprinkleClose=e=>p.close(e),r.getAvailableSprinkles=()=>{let e=new Set(p.opened());return p.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},r.onOpenSprinkle=(e,t)=>p.open(e,t),r.updateAddButtons(),await p.restoreOpenSprinkles(),!await a.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await a.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await a.exists(`/shared/.welcomed`)&&!s(window.localStorage)&&p.available().some(e=>e.name===`welcome`))try{await p.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}$.info(`SprinkleManager initialized (extension mode)`),c.requestState(),$.info(`Extension UI connected to offscreen agent engine`),Sv().catch(()=>{})}async function fx(){ia(),fa();let e=document.getElementById(`app`);if(!e)throw Error(`#app element not found`);`serviceWorker`in navigator&&navigator.serviceWorker.register(`/preview-sw.js`,{scope:`/preview/`}).then(()=>$.info(`Preview SW registered`)).catch(e=>$.error(`Preview SW registration failed — preview feature will not work`,e)),k();let t=T(),n=s(window.localStorage);if(!t&&!n){let e=window.location.port===`5710`||window.location.port===`3000`;window.location.port===``&&window.location.pathname.includes(`/join/`)?await C({autoJoinUrl:window.location.origin+window.location.pathname}):!e&&window.location.port!==``?await C({preferTrayJoin:!0}):await C(),t=T()}let i=!t&&s(window.localStorage),a=typeof chrome<`u`&&!!chrome?.runtime?.id,c=Ib(window.location.href,a);if(c===`extension`)return dx(e);let l=new Qi(e,c===`electron-overlay`);if(c===`electron-overlay`){let e=Rb(window.location.href);l.setActiveTab(e);let t=document.createElement(`style`);t.id=`slicc-electron-overlay-runtime-style`,t.textContent=`
12737
+ `);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})})},Xy);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 Qy=n(`tray-follower`);function $y(e){let t=new URL(e);return t.searchParams.set(`json`,`true`),t.toString()}async function eb(e){let t=$y(e.joinUrl),n=await sb(await(e.fetchImpl??fetch)(t,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:e.controllerId,runtime:e.runtime})}));return Qy.info(`Follower tray attach response`,{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),tb(n)}function tb(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 nb(e){return ob(await cb(e,{action:`poll`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function rb(e){return ob(await cb(e,{action:`answer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function ib(e){return ob(await cb(e,{action:`ice-candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function ab(e){return ob(await cb(e,{action:`retry`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function ob(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function sb(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!lb(n)){let n=t?t.slice(0,200):`(empty)`;throw Qy.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 cb(e,t){let n=$y(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(!ub(i))throw Error(`Tray follower bootstrap returned an invalid response (${r.status})`);return i}function lb(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`&&db(r.bootstrap):r.action===`fail`?(r.code===`INVALID_JOIN_CAPABILITY`||r.code===`TRAY_EXPIRED`)&&typeof r.error==`string`:!1}function ub(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`&&db(t.bootstrap)&&Array.isArray(t.events)}function db(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 fb=n(`tray-webrtc`),pb=`tray-control`,mb=250,hb=class{peerConnectionFactory;dataChannelLabel;peers=new Map;iceServers;constructor(e){this.options=e,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>vb(this.iceServers)),this.dataChannelLabel=e.dataChannelLabel??pb}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=bb(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`)&&(fb.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`?(fb.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`?(fb.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:yb(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){fb.warn(`Failed to report tray bootstrap failure`,{error:e instanceof Error?e.message:String(e)})}}}},gb=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??(()=>vb(this.iceServers)),this.controllerIdFactory=e.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),this.pollIntervalMs=e.pollIntervalMs??mb}async start(){this.stopped=!1;let e=this.controllerIdFactory(),t=Date.now();f({state:`connecting`,joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:t,lastError:null}),fb.info(`Follower tray join starting`,{joinUrl:this.options.joinUrl});let n=0;for(;;){xb(this.stopped),n++;let t;try{t=await eb({joinUrl:this.options.joinUrl,controllerId:e,runtime:this.options.runtime,fetchImpl:this.fetchImpl})}catch(e){let t=e instanceof Error?e.message:String(e);throw f({...m(),attachAttempts:n,lastError:t}),e}if(f({...m(),attachAttempts:n,lastAttachCode:t.code}),t.action===`wait`){let e=t.retryAfterMs??1e3;fb.info(`Follower tray attach waiting`,{attempt:n,code:t.code,retryAfterMs:e}),n%10==0&&fb.warn(`Follower tray attach still waiting after ${n} attempts`,{attempt:n,code:t.code,retryAfterMs:e}),await this.sleep(e);continue}if(t.action===`fail`||!t.bootstrap){let e=t.error??`Tray follower attach failed (${t.code})`;throw f({state:`error`,joinUrl:this.options.joinUrl,trayId:null,error:e,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:e}),fb.warn(`Follower tray attach failed`,{error:e}),Error(e)}t.iceServers&&(this.iceServers=t.iceServers);try{let r=await this.completeBootstrap(t.trayId,e,t.bootstrap);return f({state:`connected`,joinUrl:this.options.joinUrl,trayId:r.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:null}),fb.info(`Follower tray connected`,{trayId:r.trayId,controllerId:e}),r}catch(e){let r=e instanceof Error?e.message:String(e);throw f({state:`error`,joinUrl:this.options.joinUrl,trayId:t.trayId,error:r,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:r}),fb.warn(`Follower tray bootstrap failed`,{error:r}),e}}}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,f({state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null})}async completeBootstrap(e,t,n){let r=n,i=0;for(this.activePeer=this.createFollowerPeer(t,r.bootstrapId);;){if(xb(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 nb({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 rb({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,answer:yb(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 ab({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`)&&(fb.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?(fb.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?(fb.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=bb(n);r&&ib({joinUrl:this.options.joinUrl,controllerId:e,bootstrapId:t,candidate:r,fetchImpl:this.fetchImpl}).catch(e=>{fb.warn(`Failed to send follower ICE candidate`,{error:e instanceof Error?e.message:String(e)})})}),r}};function _b(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 gb({...e,sleep:o,onDisconnected:e=>{s||(fb.warn(`Follower disconnected, starting reconnect loop`,{reason:e}),p(e))}});return l=t,{manager:t,connectionPromise:t.start()}},p=async u=>{if(s||c)return;c=!0,l?.stop(),l=null;let p=0,h=n,g=u??`Unknown disconnect`;for(;!s&&p<a&&(p++,t.onReconnecting?.(p),f({...m(),state:`reconnecting`,error:null,reconnectAttempts:p}),fb.info(`Reconnect attempt`,{attempt:p,delay:h}),await o(h),!s);){let n=null;try{let r=d();n=r.manager;let i=await r.connectionPromise;if(s){n.stop();break}c=!1,f({...m(),state:`connected`,joinUrl:e.joinUrl,trayId:i.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),fb.info(`Reconnect successful`,{attempt:p,trayId:i.trayId}),t.onConnected(i);return}catch(e){g=e instanceof Error?e.message:String(e),fb.warn(`Reconnect attempt failed`,{attempt:p,error:g}),n?.stop(),l=null}h=Math.min(h*r,i)}s||(c=!1,f({...m(),state:`error`,error:`Reconnect failed after ${p} attempts: ${g}`,reconnectAttempts:p}),fb.warn(`Reconnect gave up`,{attempts:p,lastError:g}),t.onGaveUp?.(g))},{connectionPromise:h}=d();return h.then(e=>{s||t.onConnected(e)}).catch(e=>{s||fb.warn(`Initial follower connection failed`,{error:e instanceof Error?e.message:String(e)})}),u}function vb(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 yb(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 bb(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 xb(e){if(e)throw Error(`Tray follower stopped before WebRTC bootstrap completed`)}var Sb=64*1024;async function Cb(e,t){try{switch(t.op){case`readFile`:return await wb(e,t.path,t.encoding);case`writeFile`:return[await Tb(e,t.path,t.content,t.encoding)];case`stat`:return[await Eb(e,t.path)];case`readDir`:return[await Db(e,t.path)];case`mkdir`:return[await Ob(e,t.path,t.recursive)];case`rm`:return[await kb(e,t.path,t.recursive)];case`exists`:return[await Ab(e,t.path)];case`walk`:return[await jb(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(e){return[Nb(e)]}}async function wb(e,t,n){return(n??`utf-8`)===`utf-8`?Mb(await e.readFile(t,{encoding:`utf-8`}),`utf-8`):Mb(Pb(await e.readFile(t,{encoding:`binary`})),`base64`)}async function Tb(e,t,n,r){if(r===`base64`){let r=Fb(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:`void`}}}async function Eb(e,t){return{ok:!0,data:{type:`stat`,stat:await e.stat(t)}}}async function Db(e,t){return{ok:!0,data:{type:`dirEntries`,entries:await e.readDir(t)}}}async function Ob(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function kb(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function Ab(e,t){return{ok:!0,data:{type:`exists`,exists:await e.exists(t)}}}async function jb(e,t){let n=[];for await(let r of e.walk(t))n.push(r);return{ok:!0,data:{type:`paths`,paths:n}}}function Mb(e,t){if(e.length<=Sb)return[{ok:!0,data:{type:`file`,content:e,encoding:t}}];let n=Math.ceil(e.length/Sb),r=[];for(let i=0;i<n;i++){let a=i*Sb,o=e.slice(a,a+Sb);r.push({ok:!0,data:{type:`file`,content:o,encoding:t},chunkIndex:i,totalChunks:n})}return r}function Nb(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 Pb(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Fb(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 Ib=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()]}},Lb=n(`data-channel-keepalive`),Rb=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++,Lb.debug(`Missed pong`,{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){Lb.warn(`Channel declared dead`,{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}},zb=n(`tray-leader-sync`);function Bb(e){return e?e.includes(`standalone`)?`standalone`:e.includes(`extension`)?`extension`:e.includes(`electron`)?`electron`:`unknown`:`unknown`}var Vb=class{followers=new Map;registry=new Ib;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 Rb({sendPing:()=>r.send({type:`ping`}),onDead:()=>{zb.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:Bb(n?.runtime)}),zb.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(),zb.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),zb.debug(`Snapshot sent to follower`,{bootstrapId:e,messageCount:n.length})}handleFollowerMessage(e,t){switch(t.type){case`user_message`:zb.info(`Follower user message received`,{bootstrapId:e,messageId:t.messageId}),this.options.onFollowerMessage(t.text,t.messageId);break;case`abort`:zb.info(`Follower abort received`,{bootstrapId:e}),this.options.onFollowerAbort();break;case`request_snapshot`:zb.info(`Follower snapshot request received`,{bootstrapId:e}),this.sendSnapshotToFollower(e);break;case`targets.advertise`:zb.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),zb.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),zb.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 Cb(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?Cb(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})})}},Hb=n(`tray-follower-sync`),Ub=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 Rb({sendPing:()=>this.sync.send({type:`ping`}),onDead:()=>{Hb.warn(`Leader keepalive dead, cleaning up`),this.handleDisconnect(`Keepalive timeout — leader not responding`),this.options.onDead?.()}}),this.keepalive.start(),e.addEventListener(`close`,()=>{Hb.warn(`Data channel closed`),this.handleDisconnect(`Data channel closed`)}),e.addEventListener(`error`,()=>{Hb.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}),Hb.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`}),Hb.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(),Hb.info(`Follower sync closed`)}advertiseTargets(e,t){this.sync.send({type:`targets.advertise`,targets:e,runtimeId:t})}getTargets(){return this.targetEntries}disconnected=!1;handleDisconnect(e){this.disconnected||(this.disconnected=!0,f({...m(),state:`error`,error:e}),this.emitEvent({type:`error`,error:`Connection to leader lost: ${e}`}),this.keepalive.stop(),this.cleanupCDPEventForwarding(),this.unsubscribe(),this.sync.close(),this.options.onDisconnect?.(e))}handleLeaderMessage(e){switch(e.type){case`snapshot`:Hb.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&&(Hb.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),Hb.debug(`Skipping own message echo`,{messageId:e.messageId});break}Hb.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`:Hb.warn(`Error from leader`,{error:e.error}),this.emitEvent({type:`error`,error:e.error});break;case`targets.registry`:Hb.info(`Target registry received from leader`,{targetCount:e.targets.length}),this.targetEntries=e.targets,this.options.onTargetsUpdated?.(this.targetEntries);break;case`cdp.request`:{let{requestId:t,localTargetId:n,method:r,params:i,sessionId:a}=e;this.executeLocalCDP(t,n,r,i,a);break}case`cdp.response`:this.routeCDPResponse(e);break;case`cdp.event`:for(let t of this.remoteTransports.values())t.handleEvent(e.method,e.params);break;case`tab.open`:this.executeLocalTabOpen(e.requestId,e.url);break;case`tab.opened`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.resolve(e.targetId));break}case`tab.open.error`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.reject(Error(e.error)));break}case`fs.request`:this.executeLocalFs(e.requestId,e.request);break;case`fs.response`:this.routeFsResponse(e.requestId,e.response);break;case`ping`:this.keepalive.receivePing(),this.sync.send({type:`pong`});break;case`pong`:this.keepalive.receivePong(),l(Date.now());break}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch(t){Hb.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),Hb.debug(`Tracking remote CDP session`,{remoteSessionId:e})}n===`Target.detachFromTarget`&&i&&this.remoteCDPSessions.has(i)&&(this.remoteCDPSessions.delete(i),Hb.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 Cb(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 Wb(e,t){if(t)return`extension`;try{return qb(new URL(e))?`electron-overlay`:`standalone`}catch{return`standalone`}}function Gb(e,t){return e===`electron-overlay`||e===`standalone`&&t}function Kb(e){try{let t=new URL(e).searchParams.get(`tab`);return t&&qi(t)?t:Gi}catch{return Gi}}function qb(e){return e.pathname===`/electron`||e.pathname===`/electron/`||e.searchParams.get(`runtime`)===`electron-overlay`}function Jb(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}/licks-ws`}function Yb(e,t){return`${new URL(e).origin}/webhooks/${t}`}function Xb(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function Zb(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`slicc-electron-overlay:set-tab`}var Qb=[`/shared/sprinkles`];async function $b(e){let t=new Map;for(let n of Qb)await e.exists(n)&&await ex(e,n,t);return await ex(e,`/`,t),t}async function ex(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.shtml`))continue;let t=tx(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:nx(i,t),autoOpen:rx(i)})}}}function tx(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.shtml`)?t.slice(0,-6):t}function nx(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 rx(e){return/data-sprinkle-autoopen\b/.test(e)}var ix=n(`sprinkle-manager`),ax=`slicc-open-sprinkles`,ox=class{fs;bridge;callbacks;availableSprinkles=new Map;watcherUnsub;openSprinkles=new Map;constructor(e,t,n,r){this.fs=e,this.bridge=new Eh(e,t,e=>this.close(e),r),this.callbacks=n}async restoreOpenSprinkles(){try{let e=localStorage.getItem(ax);if(!e){for(let e of this.availableSprinkles.values())if(e.autoOpen)try{await this.open(e.name)}catch{ix.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{ix.warn(`Failed to restore sprinkle`,{name:e})}}catch{}}persistOpenSprinkles(){try{localStorage.setItem(ax,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),ix.info(`Auto-opened new sprinkle after install`,{name:e.name})}catch{ix.warn(`Failed to auto-open new sprinkle`,{name:e.name})}}async refresh(){this.availableSprinkles=await $b(this.fs),ix.info(`Discovered sprinkles`,{count:this.availableSprinkles.size})}async open(e,t){if(this.openSprinkles.has(e)){ix.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 ai(i,this.bridge.createAPI(e));await a.render(r,e),this.openSprinkles.get(e).renderer=a,this.persistOpenSprinkles(),Nv(e),ix.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(),ix.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){ix.warn(`Cannot send to closed sprinkle`,{name:e});return}this.bridge.pushUpdate(e,t),n.renderer.pushUpdate(t)}};function sx(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function cx(e){let t=[],{payload:n}=e;if(n.title&&t.push(`# ${n.title}`),t.push(`A new handoff was accepted from ${sx(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(`
12738
+
12739
+ `)}function lx(e,t){return e.receivedAt.localeCompare(t.receivedAt)}var ux=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(lx))}},$=n(`main`),dx=`slicc-pending-mount`,fx=`pendingMount`;async function px(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(dx,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,fx),await new Promise(e=>n.oncomplete=()=>e()),t.close()}async function mx(e){let t;try{t=await new Promise((e,t)=>{let n=indexedDB.open(dx,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(fx);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)});if(r){n.objectStore(`handles`).delete(fx),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 hx(){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 gx(){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 _x(e,t,n){let r=hx(),i=0,a=!1,o=()=>{i=0,a||r.hide()};window.addEventListener(`dragenter`,e=>{ha(e.dataTransfer)&&(e.preventDefault(),i+=1,a||r.show(`Drop .skill to install`,`Unpack into /workspace/skills/{name}.`))}),window.addEventListener(`dragover`,e=>{ha(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=ga(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 vx(e){let{OffscreenClient:t}=await v(async()=>{let{OffscreenClient:e}=await import(`./offscreen-client-BhqrZE0B.js`);return{OffscreenClient:e}},__vite__mapDeps([22,15])),{VirtualFS:n}=await v(async()=>{let{VirtualFS:e}=await import(`./fs-Br5jEe6j.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([20,1,15])),r=new Qi(e,!0);window.__slicc_debug_tabs=e=>r.setDebugTabs(e),await r.panels.chat.initSession(`session-cone`);let i=null,a=await n.create({dbName:`slicc-fs`});r.panels.fileBrowser.setFs(a),$.info(`File browser wired to shared VFS (local IndexedDB)`);let o=new BroadcastChannel(`preview-vfs`);o.onmessage=e=>{if(e.data?.type!==`preview-vfs-read`)return;let{id:t,path:n,asText:r}=e.data;(async()=>{try{let e=r?`utf-8`:`binary`,i=await a.readFile(n,{encoding:e});o.postMessage({type:`preview-vfs-response`,id:t,content:i})}catch(e){let r=e instanceof Error?e.message:String(e);r.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:n,error:r}),o.postMessage({type:`preview-vfs-response`,id:t,error:r})}})()},_x(a,gx(),async()=>{await r.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await v(async()=>{let{WasmShell:e}=await import(`./shell-C1Pnc705.js`);return{WasmShell:e}},[]),{PanelCdpProxy:t,BrowserAPI:n}=await v(async()=>{let{PanelCdpProxy:e,BrowserAPI:t}=await import(`./cdp-B4yzwpE0.js`).then(e=>e.t);return{PanelCdpProxy:e,BrowserAPI:t}},__vite__mapDeps([23,1,4,15])),{fetchSecretEnvVars:i}=await v(async()=>{let{fetchSecretEnvVars:e}=await import(`./secret-env-DFr1UV-W.js`);return{fetchSecretEnvVars:e}},[]),o=new t;await o.connect();let s=new n(o),c=await i(),l=new e({fs:a,browserAPI:s,env:Object.keys(c).length>0?c:void 0});await r.panels.terminal.mountShell(l),$.info(`Terminal mounted with shared VFS and BrowserAPI (CDP proxy)`)}catch(e){$.warn(`Failed to mount shell to terminal`,e)}{let{registerSessionCostsProvider:e}=await v(async()=>{let{registerSessionCostsProvider:e}=await import(`./cost-command-DhUP8Ozj.js`).then(e=>e.t);return{registerSessionCostsProvider:e}},__vite__mapDeps([24,1]));e(()=>new Promise(e=>{chrome.runtime.sendMessage({source:`panel`,payload:{type:`get-session-costs`}},t=>{if(chrome.runtime.lastError||!t?.ok){e([]);return}e(t.costs??[])})}))}let c,l=new Set,u=e=>{r.setPendingHandoffCount(e.length),r.panels.chat.setPendingHandoffs(e)},d=async e=>{i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid),r.setScoopSwitcherSelected?.(e.jid),r.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=e.isCone?void 0:e.name;await r.panels.chat.switchToContext(t,!e.isCone,n),c.isProcessing(e.jid)&&r.panels.chat.setProcessing(!0)};c=new t({onStatusChange:(e,t)=>{r.panels.scoops.updateScoopStatus(e,t),r.updateScoopSwitcherStatus?.(e,t),i?.jid===e&&(r.setAgentProcessing(t===`processing`),t===`processing`?r.panels.chat.setProcessing(!0):t===`ready`&&r.panels.chat.setProcessing(!1))},onScoopCreated:e=>{r.panels.scoops.refreshScoops(),r.refreshScoopSwitcher?.(),i||(i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid))},onScoopListUpdate:()=>{let e=new Set(c.getScoops().map(e=>e.folder));for(let t of l)e.has(t)||r.panels.chat.deleteSessionById(`session-${t}`);if(l=e,r.panels.scoops.refreshScoops(),r.refreshScoopSwitcher?.(),!i){let e=c.getScoops().find(e=>e.isCone);e&&(i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid))}},onIncomingMessage:(e,t)=>{if(i?.jid===e){let e=t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content;r.panels.chat.addUserMessage(e)}},onPendingHandoffsChange:u,onReady:async()=>{try{$.info(`Offscreen engine ready, scoop count:`,c.getScoops().length),window.localStorage.getItem(`slicc.trayJoinUrl`)&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`refresh-tray-runtime`}}).catch(()=>{});let e=i??c.getScoops().find(e=>e.isCone)??c.getScoops()[0];e&&(i=e,c.selectedScoopJid=e.jid,await d(e))}catch(e){$.error(`Failed to initialize on ready`,{error:e instanceof Error?e.message:String(e)})}}}),c.setLocalFS(a);let f=c.createAgentHandle();r.panels.chat.setAgent(f),r.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=c.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await d(t),r.setActiveTab(`chat`),f.sendMessage(cx(e),`handoff-${e.handoffId}`),c.acceptPendingHandoff(e.handoffId)},onDismiss:e=>{c.dismissPendingHandoff(e.handoffId)}}),c.requestPendingHandoffs(),r.panels.scoops.setOrchestrator(c),r.panels.memory.setOrchestrator(c),r.setScoopSwitcherOrchestrator?.(c),r.onScoopSelect=d,r.onModelChange=e=>{localStorage.setItem(`selected-model`,e),c.updateModel()},r.onClearChat=async()=>{let e=c.getScoops();for(let t of e){let e=t.isCone?`session-cone`:`session-${t.folder}`;await r.panels.chat.deleteSessionById(e)}c.clearAllMessages()},r.onClearFilesystem=async()=>{c.clearFilesystem()},r.panels.chat.onInlineSprinkleLick=(e,t)=>{c.sendSprinkleLick(`inline`,{action:e,data:t})};let p=new ox(a,async e=>{if(e.type===`sprinkle`){if(e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&a.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome completion marker`,e)),n===`shortcut-migrate`&&p.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&mx(a).catch(e=>$.warn(`Failed to mount workspace from onboarding`,e))}if(e.sprinkleName===`welcome`&&e.body?.action===`request-mount`){try{let e=window;if(!e.showDirectoryPicker)throw Error(`showDirectoryPicker not supported`);let t=await e.showDirectoryPicker({mode:`readwrite`});await px(t),p.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),p.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}return}c.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop)}},{addSprinkle:(e,t,n,i)=>r.addSprinkle(e,t,n,i),removeSprinkle:e=>r.removeSprinkle(e)},()=>{let e=c.getScoops().find(e=>e.isCone);e&&c.stopScoop(e.jid)});if(window.__slicc_sprinkleManager=p,window.__slicc_reloadSkills=()=>(chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}}),Promise.resolve()),c.setSprinkleOpHandler(e=>{let{id:t,op:n,name:r,data:i}=e;console.log(`[main-ext] sprinkle-op handler called`,{id:t,op:n,name:r}),(async()=>{try{let e;switch(n){case`list`:await p.refresh(),e=p.available();break;case`opened`:e=p.opened();break;case`refresh`:await p.refresh(),e=p.available().length;break;case`open`:await p.open(r),e=!0;break;case`close`:p.close(r),e=!0;break;case`send`:p.sendToSprinkle(r,i),e=!0;break;case`openNewAutoOpen`:await p.openNewAutoOpenSprinkles(),e=!0;break}console.log(`[main-ext] sprinkle-op response sending`,{id:t,op:n,result:typeof e}),chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,result:e}}).catch(()=>{})}catch(e){chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}})()}),await p.refresh(),r.onSprinkleClose=e=>p.close(e),r.getAvailableSprinkles=()=>{let e=new Set(p.opened());return p.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},r.onOpenSprinkle=(e,t)=>p.open(e,t),r.updateAddButtons(),await p.restoreOpenSprinkles(),!await a.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await a.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await a.exists(`/shared/.welcomed`)&&!s(window.localStorage)&&p.available().some(e=>e.name===`welcome`))try{await p.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}$.info(`SprinkleManager initialized (extension mode)`),c.requestState(),$.info(`Extension UI connected to offscreen agent engine`),Av().catch(()=>{})}function yx(){if(typeof chrome<`u`&&chrome?.runtime?.id)return;let e=new Blob([`
12740
+ let lastPong = Date.now();
12741
+ let frozen = false;
12742
+ setInterval(() => {
12743
+ postMessage({ type: 'ping' });
12744
+ const elapsed = Date.now() - lastPong;
12745
+ if (elapsed > 5000 && !frozen) {
12746
+ frozen = true;
12747
+ postMessage({ type: 'freeze-detected', elapsed });
12748
+ }
12749
+ }, 2000);
12750
+ self.onmessage = (e) => {
12751
+ if (e.data.type === 'pong') {
12752
+ lastPong = Date.now();
12753
+ if (frozen) {
12754
+ frozen = false;
12755
+ postMessage({ type: 'freeze-recovered' });
12756
+ }
12757
+ }
12758
+ };
12759
+ `],{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 bx(){yx(),ia(),fa();let e=document.getElementById(`app`);if(!e)throw Error(`#app element not found`);`serviceWorker`in navigator&&navigator.serviceWorker.register(`/preview-sw.js`,{scope:`/preview/`}).then(()=>$.info(`Preview SW registered`)).catch(e=>$.error(`Preview SW registration failed — preview feature will not work`,e)),k();let t=T(),n=s(window.localStorage);if(!t&&!n){let e=window.location.port===`5710`||window.location.port===`3000`;window.location.port===``&&window.location.pathname.includes(`/join/`)?await C({autoJoinUrl:window.location.origin+window.location.pathname}):!e&&window.location.port!==``?await C({preferTrayJoin:!0}):await C(),t=T()}let i=!t&&s(window.localStorage),a=typeof chrome<`u`&&!!chrome?.runtime?.id,c=Wb(window.location.href,a);if(c===`extension`)return vx(e);let l=new Qi(e,c===`electron-overlay`);if(c===`electron-overlay`){let e=Kb(window.location.href);l.setActiveTab(e);let t=document.createElement(`style`);t.id=`slicc-electron-overlay-runtime-style`,t.textContent=`
12733
12760
  #app > .tab-bar { display: none !important; }
12734
12761
  #app > .tab-content {
12735
12762
  height: calc(100vh - var(--s2-header-height));
@@ -12737,4 +12764,4 @@ ${t}
12737
12764
  #app > .tab-content > .tab-content__panel {
12738
12765
  height: 100%;
12739
12766
  }
12740
- `,document.head.appendChild(t),window.addEventListener(`message`,e=>{e.source===window.parent&&Ub(e.data)&&l.setActiveTab(Rb(`http://localhost/?tab=${e.data.tab??``}`))}),window.addEventListener(`keydown`,e=>{e.code===`Semicolon`&&(e.metaKey||e.ctrlKey)&&!e.shiftKey&&!e.altKey&&!e.repeat&&(e.preventDefault(),e.stopPropagation(),window.parent.postMessage({type:`slicc-electron-overlay:toggle`},`*`))},!0)}let d=lx();await l.panels.chat.initSession(`session-cone`),$.info(`Session initialized`);let f=new xe,p=e=>{l.setPendingHandoffCount(e.length),l.panels.chat.setPendingHandoffs(e)},m=new Set,g=e=>{$.debug(`Emit to UI`,{type:e.type,listenerCount:m.size});for(let t of m)try{t(e)}catch(t){$.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}},_=null,y=new Map,b=new Map;function x(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function S(e){let t=b.get(e);return t||(t=[],b.set(e,t)),t}function w(e,t){let n=S(e),r=y.get(e);if(r){let e=n.find(e=>e.id===r);if(e)return e}r=`scoop-${e}-${x()}`,y.set(e,r);let i=E.getScoops().find(t=>t.jid===e),a=i?.isCone?`cone`:i?.name??`unknown`,o={id:r,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:a,channel:t};return n.push(o),_?.jid===e&&g({type:`message_start`,messageId:r}),o}let E=new Uy(l.getIframeContainer(),{onResponse:(e,t,n)=>{let r=w(e);n?r.content+=t:(r.content=t,r.isStreaming=!1),_?.jid===e&&(g({type:`content_delta`,messageId:r.id,text:t}),n||g({type:`content_done`,messageId:r.id}))},onResponseDone:e=>{let t=S(e),n=y.get(e);if(n){let r=t.find(e=>e.id===n);r&&(r.isStreaming=!1),_?.jid===e&&g({type:`content_done`,messageId:n}),y.delete(e)}},onSendMessage:(e,t)=>{$.debug(`Send message requested`,{targetJid:e,textLength:t.length});let n=`msg-${x()}`,r={id:n,chatJid:e,senderId:`assistant`,senderName:`sliccy`,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`web`};E.handleMessage(r),S(e).push({id:n,role:`assistant`,content:t,timestamp:Date.now()}),_?.jid===e&&(g({type:`message_start`,messageId:n}),g({type:`content_delta`,messageId:n,text:t}),g({type:`content_done`,messageId:n}))},onStatusChange:(e,t)=>{if(l.panels.scoops.updateScoopStatus(e,t),l.updateScoopSwitcherStatus?.(e,t),_?.jid===e){if(l.setAgentProcessing(t===`processing`),t===`processing`)l.panels.chat.setProcessing(!0);else if(t===`ready`){l.panels.chat.setProcessing(!1);let t=y.get(e)??`done-${e}-${x()}`;y.delete(e),g({type:`turn_end`,messageId:t})}}},onError:(e,t)=>{$.error(`Scoop error`,{scoopJid:e,error:t}),_?.jid===e&&g({type:`error`,error:t})},getBrowserAPI:()=>f,onToolStart:(e,t,n)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let r=w(e);r.toolCalls||=[],r.toolCalls.push({id:x(),name:t,input:n}),_?.jid===e&&g({type:`tool_use_start`,messageId:r.id,toolName:t,toolInput:n})},onToolEnd:(e,t,n,r)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let i=S(e),a=y.get(e);if(a){let e=i.find(e=>e.id===a);if(e?.toolCalls){let i=[...e.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);i&&(i.result=n,i.isError=r)}}_?.jid===e&&a&&g({type:`tool_result`,messageId:a,toolName:t,result:n,isError:r})},onToolUI:(e,t,n,r)=>{let i=y.get(e);i?g({type:`tool_ui`,messageId:i,toolName:t,requestId:n,html:r}):$.warn(`Cannot emit tool_ui - no message ID for scoop`,{scoopJid:e,requestId:n})},onToolUIDone:(e,t)=>{let n=y.get(e);n&&g({type:`tool_ui_done`,messageId:n,requestId:t})},onIncomingMessage:(e,t)=>{let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel};S(e).push(n),_?.jid===e&&(g({type:`message_start`,messageId:t.id}),g({type:`content_delta`,messageId:t.id,text:n.content}),g({type:`content_done`,messageId:t.id}))}});await E.init(),l.panels.scoops.setOrchestrator(E),l.panels.memory.setOrchestrator(E),l.setScoopSwitcherOrchestrator?.(E);let D=E.getSharedFS();if(D){l.panels.fileBrowser.setFs(D),$.info(`File browser wired to shared VFS`);let e=new BroadcastChannel(`preview-vfs`);e.onmessage=t=>{if(t.data?.type!==`preview-vfs-read`)return;let{id:n,path:r,asText:i}=t.data;(async()=>{try{let t=i?`utf-8`:`binary`,a=await D.readFile(r,{encoding:t});e.postMessage({type:`preview-vfs-response`,id:n,content:a})}catch(t){let i=t instanceof Error?t.message:String(t);i.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:r,error:i}),e.postMessage({type:`preview-vfs-response`,id:n,error:i})}})()},ux(D,(e,t)=>{t===`error`?$.warn(`Dropped skill install failed`,{message:e}):$.info(`Dropped skill installed`,{message:e}),d(e,t)},async()=>{await l.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await v(async()=>{let{WasmShell:e}=await import(`./shell-B45M6r84.js`);return{WasmShell:e}},[]),{fetchSecretEnvVars:t}=await v(async()=>{let{fetchSecretEnvVars:e}=await import(`./secret-env-OKzGv9D2.js`);return{fetchSecretEnvVars:e}},[]),n=await t(),r=new e({fs:D,browserAPI:f,env:Object.keys(n).length>0?n:void 0});await l.panels.terminal.mountShell(r),$.info(`Terminal mounted with shared VFS`);try{let{BshWatchdog:e}=await v(async()=>{let{BshWatchdog:e}=await import(`./bsh-watchdog-BaiyTJC8.js`);return{BshWatchdog:e}},__vite__mapDeps([25,15])),t=new e({browserAPI:f,scriptCatalog:r.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(i)$.info(`Skipping local cone bootstrap while joining a tray without a configured provider`);else if(!ee)_=await l.panels.scoops.createScoop(`Cone`,!0),$.info(`Created cone`);else{let e=new URLSearchParams(window.location.search).get(`scoop`);if(e){let t=O.find(t=>t.folder===e);t?(_=t,$.info(`Restored scoop from URL`,{folder:e})):_=O.find(e=>e.isCone)??O[0]}else _=O.find(e=>e.isCone)??O[0]}_&&l.panels.memory.setSelectedScoop(_.jid);let A=null,j=null,te={sendMessage(e,t){if(!_){g({type:`error`,error:`No scoop selected`});return}let n={id:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:_.jid,senderId:`user`,senderName:`User`,content:e,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`};S(_.jid).push({id:n.id,role:`user`,content:e,timestamp:Date.now()}),A?.broadcastUserMessage(e,n.id),E.handleMessage(n),E.createScoopTab(_.jid)},onEvent(e){return m.add(e),()=>m.delete(e)},stop(){_&&(E.stopScoop(_.jid),E.clearQueuedMessages(_.jid).catch(e=>{$.error(`Failed to clear queued messages on stop`,{error:e instanceof Error?e.message:String(e)})}))}};l.panels.chat.setAgent(te),l.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=E.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await P(t),l.setActiveTab(`chat`),te.sendMessage(tx(e),`handoff-${e.handoffId}`);let n=j?.clearHandoff(e.handoffId);n&&await Promise.allSettled(n.targetIds.map(e=>f.closePage(e)))},onDismiss:async e=>{let t=j?.clearHandoff(e.handoffId);t&&await Promise.allSettled(t.targetIds.map(e=>f.closePage(e)))}}),l.panels.chat.setDeleteQueuedMessageCallback(e=>{if(_){E.deleteQueuedMessage(_.jid,e).catch(t=>{$.error(`Failed to delete queued message`,{messageId:e,error:t instanceof Error?t.message:String(t)})});let t=b.get(_.jid);if(t){let n=t.findIndex(t=>t.id===e);n!==-1&&t.splice(n,1)}}}),$.info(`Cone agent handle wired to chat UI`);let{getLickManager:ne}=await v(async()=>{let{getLickManager:e}=await import(`./lick-manager-D6_9f0OR.js`);return{getLickManager:e}},[]),re=ne();await re.init(),E.setLickManager(re);let ie=e=>{let t=e.type===`webhook`,n=e.type===`sprinkle`,r=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`&&M?.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&D&&sx(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 ox(t),M?.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),M?.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}})();return}let c=E.getScoops(),u;if(u=n||!e.targetScoop?c.find(e=>e.isCone):c.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`),u){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:u.jid,senderId:s,senderName:`${s}:${a}`,content:d,timestamp:e.timestamp,fromAssistant:!1,channel:s};S(u.jid).push({id:c,role:`user`,content:d,timestamp:Date.now(),source:`lick`,channel:s}),_?.jid===u.jid&&l.panels.chat.addLickMessage(c,d,s),$.info(`Routing lick to scoop`,{type:s,name:a,scoopJid:u.jid}),E.handleMessage(f)}else $.warn(`Lick target scoop not found`,{targetScoop:e.targetScoop})};re.setEventHandler(ie),D&&oe().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&&ie({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)),l.panels.chat.onInlineSprinkleLick=(e,t)=>{ie({type:`sprinkle`,sprinkleName:`inline`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:e,data:t}})};let M=null;if(D){if(M=new $b(D,ie,{addSprinkle:(e,t,n,r)=>l.addSprinkle(e,t,n,r),removeSprinkle:e=>l.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=M,window.__slicc_reloadSkills=()=>E.reloadAllSkills(),await M.refresh(),l.onSprinkleClose=e=>M.close(e),l.getAvailableSprinkles=()=>{let e=new Set(M.opened());return M.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},l.onOpenSprinkle=(e,t)=>M.open(e,t),l.updateAddButtons(),!await D.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await D.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await D.exists(`/shared/.welcomed`)&&!i&&M.available().some(e=>e.name===`welcome`))try{await M.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}await M.restoreOpenSprinkles(),$.info(`SprinkleManager initialized`)}let N=()=>{let e=Bb(window.location.href),t=new WebSocket(e);t.onopen=()=>{$.info(`Lick WebSocket connected`)},t.onmessage=async e=>{try{let n=JSON.parse(e.data);if(n.requestId){let e;try{switch(n.type){case`list_webhooks`:e={type:`response`,requestId:n.requestId,data:re.listWebhooks()};break;case`create_webhook`:{let t=await re.createWebhook(n.name||`default`,n.scoop,n.filter),r=zp().session,i=r?.webhookUrl?Hb(r.webhookUrl,t.id):Vb(window.location.href,t.id);e={type:`response`,requestId:n.requestId,data:{...t,url:i}};break}case`delete_webhook`:e=await re.deleteWebhook(n.id)?{type:`response`,requestId:n.requestId,data:{ok:!0}}:{type:`response`,requestId:n.requestId,data:{error:`Webhook not found`}};break;case`list_crontasks`:e={type:`response`,requestId:n.requestId,data:re.listCronTasks()};break;case`create_crontask`:{if(!n.name)throw Error(`name is required`);if(!n.cron)throw Error(`cron is required`);let t=await re.createCronTask(n.name,n.cron,n.scoop,n.filter);e={type:`response`,requestId:n.requestId,data:t};break}case`delete_crontask`:e=await re.deleteCronTask(n.id)?{type:`response`,requestId:n.requestId,data:{ok:!0}}:{type:`response`,requestId:n.requestId,data:{error:`Cron task not found`}};break;case`tray_status`:{let t=zp();e={type:`response`,requestId:n.requestId,data:{state:t.state,joinUrl:t.session?.joinUrl??null,workerBaseUrl:t.session?.workerBaseUrl??null,trayId:t.session?.trayId??null}};break}default:e={type:`response`,requestId:n.requestId,error:`Unknown request type: ${n.type}`}}}catch(t){e={type:`response`,requestId:n.requestId,error:t instanceof Error?t.message:String(t)}}t.send(JSON.stringify(e));return}n.type===`webhook_event`&&re.handleWebhookEvent(n.webhookId,n.headers,n.body),n.type===`handoff_event`&&j&&j.injectHandoff(n.payload,n.sourceUrl)}catch(e){$.error(`Failed to process lick message`,{error:e instanceof Error?e.message:String(e)})}},t.onclose=()=>{$.warn(`Lick WebSocket disconnected, reconnecting in 3s...`),setTimeout(N,3e3)},t.onerror=e=>{$.error(`Lick WebSocket error`,{error:String(e)})}};N(),l.onModelChange=e=>{localStorage.setItem(`selected-model`,e),E.updateModel()},l.onClearChat=async()=>{await E.clearAllMessages(),b.clear()},l.onClearFilesystem=async()=>{await E.resetFilesystem()};let P=async e=>{$.info(`Scoop selected`,{jid:e.jid,name:e.name}),_=e,E.createScoopTab(e.jid),l.panels.memory.setSelectedScoop(e.jid),l.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=b.get(e.jid),r=e.isCone?void 0:e.name;if(n&&n.length>0)await l.panels.chat.switchToContext(t,!e.isCone,r),l.panels.chat.loadMessages(n);else if(await l.panels.chat.switchToContext(t,!e.isCone,r),l.panels.chat.getMessages().length===0){let t=await E.getMessagesForScoop(e.jid);for(let n of t){let t=n.channel===`webhook`||n.channel===`cron`,r=n.channel===`delegation`;if(t){let t={id:n.id,role:`user`,content:n.content,timestamp:new Date(n.timestamp).getTime(),source:`lick`,channel:n.channel};S(e.jid).push(t),l.panels.chat.addUserMessage(n.content)}else if(r){let t={id:n.id,role:`user`,content:`**[Instructions from sliccy]**\n\n${n.content}`,timestamp:new Date(n.timestamp).getTime(),source:`delegation`,channel:`delegation`};S(e.jid).push(t),l.panels.chat.addUserMessage(t.content)}else n.fromAssistant?(g({type:`message_start`,messageId:n.id}),g({type:`content_delta`,messageId:n.id,text:n.content}),g({type:`content_done`,messageId:n.id})):l.panels.chat.addUserMessage(n.content)}}e.isCone&&E.isProcessing(e.jid)&&l.panels.chat.setProcessing(!0)};if(l.onScoopSelect=P,_&&(E.createScoopTab(_.jid),await P(_)),j=new rx({onPendingHandoffsChange:p}),c===`standalone`||c===`electron-overlay`){let e=await r(),t=Lb(c,e!==null)?o:null,n=await h({locationHref:window.location.href,storage:window.localStorage,envBaseUrl:null,defaultWorkerBaseUrl:t,runtimeConfigFetcher:async()=>e}),i=null,a=null,s=null;Rh(()=>A?(e,t)=>A.sendFsRequest(e,t):i?(e,t)=>i.sendFsRequest(e,t):null),Nf(()=>A?()=>A.getBestFollowerForTeleport():null),Pf(()=>A?()=>A.getConnectedFollowers():null);let d=e=>{s&&=(clearInterval(s),null),i?.close();let t=`follower-${e.bootstrapId}`,n=new Fb(e.channel,{browserTransport:f.getTransport(),browserAPI:f,onSnapshot:e=>{l.panels.chat.loadMessages(e)},onUserMessage:e=>{l.panels.chat.addUserMessage(e)},onStatus:e=>{l.panels.chat.setProcessing(e===`processing`)},onTargetsChanged:()=>void r()});i=n,f.setTrayTargetProvider(n),l.panels.chat.setAgent(n),n.requestSnapshot();let r=async()=>{try{let e=await f.listPages();n.advertiseTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})),t)}catch{}};s=setInterval(r,5e3),r(),$.info(`Follower sync wired to chat panel`,{trayId:e.trayId})},p=e=>{a?.cancel(),s&&=(clearInterval(s),null),i?.close(),i=null,a=lb({joinUrl:e,runtime:`slicc-standalone`,fetchImpl:qp()},{onConnected:e=>d(e),onReconnecting:e=>{$.info(`Follower reconnecting`,{attempt:e})},onGaveUp:e=>{$.warn(`Follower reconnect gave up`,{lastError:e})}})};if(window.addEventListener(`slicc:tray-join`,(e=>{p(e.detail.joinUrl)})),window.addEventListener(`beforeunload`,()=>{s&&clearInterval(s),i?.close(),a?.cancel()},{once:!0}),n?.joinUrl)p(n.joinUrl);else if(n?.workerBaseUrl){let e,t,r,i,a=()=>{t=new Nb({browserTransport:f.getTransport(),browserAPI:f,getMessages:()=>l.panels.chat.getMessages(),getScoopJid:()=>_?.jid??`cone`,onFollowerMessage:(e,t)=>{l.panels.chat.addUserMessage(e),te.sendMessage(e,t)},onFollowerAbort:()=>{te.stop()}}),A=t,Yp(()=>t.getConnectedFollowers()),f.setTrayTargetProvider(t),i&&clearInterval(i);let n=async()=>{try{let e=await f.listPages();t.setLocalTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})))}catch{}};i=setInterval(n,5e3),n(),r=new sb({sendControlMessage:t=>e.sendControlMessage(t),onPeerConnected:(e,n)=>{$.info(`Tray follower data channel opened`,{controllerId:e.controllerId,bootstrapId:e.bootstrapId,attempt:e.attempt,runtime:e.runtime}),t.addFollower(e.bootstrapId,n,{runtime:e.runtime,connectedAt:e.connectedAt??void 0})}})};a(),m.add(e=>{t.broadcastEvent(e)}),e=new Up({workerBaseUrl:n.workerBaseUrl,runtime:`slicc-standalone`,fetchImpl:qp(),onControlMessage:e=>{if(e.type===`webhook.event`){re.handleWebhookEvent(e.webhookId,e.headers,e.body);return}r.handleControlMessage(e).catch(e=>{$.warn(`Tray leader bootstrap handling failed`,{error:e instanceof Error?e.message:String(e)})})}}),Qp(async()=>{t.stop(),r.stop(),e.stop(),await e.clearSession();let n=await e.start(),i=u(window.location.href,n.workerBaseUrl,n.trayId);return i!==window.location.href&&window.history.replaceState(window.history.state,``,i),a(),zp()}),e.start().then(e=>{let t=u(window.location.href,e.workerBaseUrl,e.trayId);t!==window.location.href&&window.history.replaceState(window.history.state,``,t)}).catch(e=>{$.warn(`Leader tray join failed`,{error:e instanceof Error?e.message:String(e)})}),window.addEventListener(`beforeunload`,()=>{clearInterval(i),t.stop(),r.stop(),e.stop()},{once:!0})}}$.info(`Orchestrator initialized — cone+scoops ready`,{scoopCount:E.getScoops().length}),Sv().catch(()=>{})}fx().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{Fv as a,si as c,jy as i,ii as l,zy as n,wa as o,Vy as r,ai as s,Ry as t};
12767
+ `,document.head.appendChild(t),window.addEventListener(`message`,e=>{e.source===window.parent&&Zb(e.data)&&l.setActiveTab(Kb(`http://localhost/?tab=${e.data.tab??``}`))}),window.addEventListener(`keydown`,e=>{e.code===`Semicolon`&&(e.metaKey||e.ctrlKey)&&!e.shiftKey&&!e.altKey&&!e.repeat&&(e.preventDefault(),e.stopPropagation(),window.parent.postMessage({type:`slicc-electron-overlay:toggle`},`*`))},!0)}let d=gx();await l.panels.chat.initSession(`session-cone`),$.info(`Session initialized`);let f=new xe,p=e=>{l.setPendingHandoffCount(e.length),l.panels.chat.setPendingHandoffs(e)},m=new Set,g=e=>{$.debug(`Emit to UI`,{type:e.type,listenerCount:m.size});for(let t of m)try{t(e)}catch(t){$.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}},_=null,y=new Map,b=new Map;function x(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function S(e){let t=b.get(e);return t||(t=[],b.set(e,t)),t}function w(e,t){let n=S(e),r=y.get(e);if(r){let e=n.find(e=>e.id===r);if(e)return e}r=`scoop-${e}-${x()}`,y.set(e,r);let i=E.getScoops().find(t=>t.jid===e),a=i?.isCone?`cone`:i?.name??`unknown`,o={id:r,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:a,channel:t};return n.push(o),_?.jid===e&&g({type:`message_start`,messageId:r}),o}let E=new Zy(l.getIframeContainer(),{onResponse:(e,t,n)=>{let r=w(e);n?r.content+=t:(r.content=t,r.isStreaming=!1),_?.jid===e&&(g({type:`content_delta`,messageId:r.id,text:t}),n||g({type:`content_done`,messageId:r.id}))},onResponseDone:e=>{let t=S(e),n=y.get(e);if(n){let r=t.find(e=>e.id===n);r&&(r.isStreaming=!1),_?.jid===e&&g({type:`content_done`,messageId:n}),y.delete(e)}},onSendMessage:(e,t)=>{$.debug(`Send message requested`,{targetJid:e,textLength:t.length});let n=`msg-${x()}`,r={id:n,chatJid:e,senderId:`assistant`,senderName:`sliccy`,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`web`};E.handleMessage(r),S(e).push({id:n,role:`assistant`,content:t,timestamp:Date.now()}),_?.jid===e&&(g({type:`message_start`,messageId:n}),g({type:`content_delta`,messageId:n,text:t}),g({type:`content_done`,messageId:n}))},onStatusChange:(e,t)=>{if(l.panels.scoops.updateScoopStatus(e,t),l.updateScoopSwitcherStatus?.(e,t),_?.jid===e){if(l.setAgentProcessing(t===`processing`),t===`processing`)l.panels.chat.setProcessing(!0);else if(t===`ready`){l.panels.chat.setProcessing(!1);let t=y.get(e)??`done-${e}-${x()}`;y.delete(e),g({type:`turn_end`,messageId:t})}}},onError:(e,t)=>{$.error(`Scoop error`,{scoopJid:e,error:t}),_?.jid===e&&g({type:`error`,error:t})},getBrowserAPI:()=>f,onToolStart:(e,t,n)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let r=w(e);r.toolCalls||=[],r.toolCalls.push({id:x(),name:t,input:n}),_?.jid===e&&g({type:`tool_use_start`,messageId:r.id,toolName:t,toolInput:n})},onToolEnd:(e,t,n,r)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let i=S(e),a=y.get(e);if(a){let e=i.find(e=>e.id===a);if(e?.toolCalls){let i=[...e.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);i&&(i.result=n,i.isError=r)}}_?.jid===e&&a&&g({type:`tool_result`,messageId:a,toolName:t,result:n,isError:r})},onToolUI:(e,t,n,r)=>{let i=y.get(e);i?g({type:`tool_ui`,messageId:i,toolName:t,requestId:n,html:r}):$.warn(`Cannot emit tool_ui - no message ID for scoop`,{scoopJid:e,requestId:n})},onToolUIDone:(e,t)=>{let n=y.get(e);n&&g({type:`tool_ui_done`,messageId:n,requestId:t})},onIncomingMessage:(e,t)=>{let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel};S(e).push(n),_?.jid===e&&(g({type:`message_start`,messageId:t.id}),g({type:`content_delta`,messageId:t.id,text:n.content}),g({type:`content_done`,messageId:t.id}))}});await E.init(),l.panels.scoops.setOrchestrator(E),l.panels.memory.setOrchestrator(E),l.setScoopSwitcherOrchestrator?.(E);let D=E.getSharedFS();if(D){l.panels.fileBrowser.setFs(D),$.info(`File browser wired to shared VFS`);let e=new BroadcastChannel(`preview-vfs`);e.onmessage=t=>{if(t.data?.type!==`preview-vfs-read`)return;let{id:n,path:r,asText:i}=t.data;(async()=>{try{let t=i?`utf-8`:`binary`,a=await D.readFile(r,{encoding:t});e.postMessage({type:`preview-vfs-response`,id:n,content:a})}catch(t){let i=t instanceof Error?t.message:String(t);i.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:r,error:i}),e.postMessage({type:`preview-vfs-response`,id:n,error:i})}})()},_x(D,(e,t)=>{t===`error`?$.warn(`Dropped skill install failed`,{message:e}):$.info(`Dropped skill installed`,{message:e}),d(e,t)},async()=>{await l.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await v(async()=>{let{WasmShell:e}=await import(`./shell-C1Pnc705.js`);return{WasmShell:e}},[]),{fetchSecretEnvVars:t}=await v(async()=>{let{fetchSecretEnvVars:e}=await import(`./secret-env-DFr1UV-W.js`);return{fetchSecretEnvVars:e}},[]),n=await t(),r=new e({fs:D,browserAPI:f,env:Object.keys(n).length>0?n:void 0});await l.panels.terminal.mountShell(r),$.info(`Terminal mounted with shared VFS`);try{let{BshWatchdog:e}=await v(async()=>{let{BshWatchdog:e}=await import(`./bsh-watchdog-BaiyTJC8.js`);return{BshWatchdog:e}},__vite__mapDeps([25,15])),t=new e({browserAPI:f,scriptCatalog:r.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(i)$.info(`Skipping local cone bootstrap while joining a tray without a configured provider`);else if(!ee)_=await l.panels.scoops.createScoop(`Cone`,!0),$.info(`Created cone`);else{let e=new URLSearchParams(window.location.search).get(`scoop`);if(e){let t=O.find(t=>t.folder===e);t?(_=t,$.info(`Restored scoop from URL`,{folder:e})):_=O.find(e=>e.isCone)??O[0]}else _=O.find(e=>e.isCone)??O[0]}_&&l.panels.memory.setSelectedScoop(_.jid);let A=null,j=null,te={sendMessage(e,t){if(!_){g({type:`error`,error:`No scoop selected`});return}let n={id:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:_.jid,senderId:`user`,senderName:`User`,content:e,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`};S(_.jid).push({id:n.id,role:`user`,content:e,timestamp:Date.now()}),A?.broadcastUserMessage(e,n.id),E.handleMessage(n),E.createScoopTab(_.jid)},onEvent(e){return m.add(e),()=>m.delete(e)},stop(){_&&(E.stopScoop(_.jid),E.clearQueuedMessages(_.jid).catch(e=>{$.error(`Failed to clear queued messages on stop`,{error:e instanceof Error?e.message:String(e)})}))}};l.panels.chat.setAgent(te),l.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=E.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await F(t),l.setActiveTab(`chat`),te.sendMessage(cx(e),`handoff-${e.handoffId}`);let n=j?.clearHandoff(e.handoffId);n&&await Promise.allSettled(n.targetIds.map(e=>f.closePage(e)))},onDismiss:async e=>{let t=j?.clearHandoff(e.handoffId);t&&await Promise.allSettled(t.targetIds.map(e=>f.closePage(e)))}}),l.panels.chat.setDeleteQueuedMessageCallback(e=>{if(_){E.deleteQueuedMessage(_.jid,e).catch(t=>{$.error(`Failed to delete queued message`,{messageId:e,error:t instanceof Error?t.message:String(t)})});let t=b.get(_.jid);if(t){let n=t.findIndex(t=>t.id===e);n!==-1&&t.splice(n,1)}}}),$.info(`Cone agent handle wired to chat UI`);let{getLickManager:ne}=await v(async()=>{let{getLickManager:e}=await import(`./lick-manager-CjWADwNT.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&&mx(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 px(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(),u;if(u=e.targetScoop?c.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):c.find(e=>e.isCone),u){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:u.jid,senderId:s,senderName:`${s}:${a}`,content:d,timestamp:e.timestamp,fromAssistant:!1,channel:s};S(u.jid).push({id:c,role:`user`,content:d,timestamp:Date.now(),source:`lick`,channel:s}),_?.jid===u.jid&&l.panels.chat.addLickMessage(c,d,s),$.info(`Routing lick to scoop`,{type:s,name:a,scoopJid:u.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)),l.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 ox(D,re,{addSprinkle:(e,t,n,r)=>l.addSprinkle(e,t,n,r),removeSprinkle:e=>l.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(),l.onSprinkleClose=e=>N.close(e),l.getAvailableSprinkles=()=>{let e=new Set(N.opened());return N.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},l.onOpenSprinkle=(e,t)=>N.open(e,t),l.updateAddButtons(),!await D.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await D.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await D.exists(`/shared/.welcomed`)&&!i&&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=Jb(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=zp().session,i=r?.webhookUrl?Xb(r.webhookUrl,t.id):Yb(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=zp();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(),l.onModelChange=e=>{localStorage.setItem(`selected-model`,e),E.updateModel()},l.onClearChat=async()=>{await E.clearAllMessages(),b.clear()},l.onClearFilesystem=async()=>{await E.resetFilesystem()};let F=async e=>{$.info(`Scoop selected`,{jid:e.jid,name:e.name}),_=e,E.createScoopTab(e.jid),l.panels.memory.setSelectedScoop(e.jid),l.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=b.get(e.jid),r=e.isCone?void 0:e.name;if(n&&n.length>0)await l.panels.chat.switchToContext(t,!e.isCone,r),l.panels.chat.loadMessages(n);else if(await l.panels.chat.switchToContext(t,!e.isCone,r),l.panels.chat.getMessages().length===0){let t=await E.getMessagesForScoop(e.jid);for(let n of t){let t=n.channel===`webhook`||n.channel===`cron`,r=n.channel===`delegation`;if(t){let t={id:n.id,role:`user`,content:n.content,timestamp:new Date(n.timestamp).getTime(),source:`lick`,channel:n.channel};S(e.jid).push(t),l.panels.chat.addUserMessage(n.content)}else if(r){let t={id:n.id,role:`user`,content:`**[Instructions from sliccy]**\n\n${n.content}`,timestamp:new Date(n.timestamp).getTime(),source:`delegation`,channel:`delegation`};S(e.jid).push(t),l.panels.chat.addUserMessage(t.content)}else n.fromAssistant?(g({type:`message_start`,messageId:n.id}),g({type:`content_delta`,messageId:n.id,text:n.content}),g({type:`content_done`,messageId:n.id})):l.panels.chat.addUserMessage(n.content)}}e.isCone&&E.isProcessing(e.jid)&&l.panels.chat.setProcessing(!0)};if(l.onScoopSelect=F,_&&(E.createScoopTab(_.jid),await F(_)),j=new ux({onPendingHandoffsChange:p}),c===`standalone`||c===`electron-overlay`){let e=await r(),t=Gb(c,e!==null)?o:null,n=await h({locationHref:window.location.href,storage:window.localStorage,envBaseUrl:null,defaultWorkerBaseUrl:t,runtimeConfigFetcher:async()=>e}),i=null,a=null,s=null;Kh(()=>A?(e,t)=>A.sendFsRequest(e,t):i?(e,t)=>i.sendFsRequest(e,t):null),Nf(()=>A?()=>A.getBestFollowerForTeleport():null),Pf(()=>A?()=>A.getConnectedFollowers():null);let d=e=>{s&&=(clearInterval(s),null),i?.close();let t=`follower-${e.bootstrapId}`,n=new Ub(e.channel,{browserTransport:f.getTransport(),browserAPI:f,onSnapshot:e=>{l.panels.chat.loadMessages(e)},onUserMessage:e=>{l.panels.chat.addUserMessage(e)},onStatus:e=>{l.panels.chat.setProcessing(e===`processing`)},onTargetsChanged:()=>void r()});i=n,f.setTrayTargetProvider(n),l.panels.chat.setAgent(n),n.requestSnapshot();let r=async()=>{try{let e=await f.listPages();n.advertiseTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})),t)}catch{}};s=setInterval(r,5e3),r(),$.info(`Follower sync wired to chat panel`,{trayId:e.trayId})},p=e=>{a?.cancel(),s&&=(clearInterval(s),null),i?.close(),i=null,a=_b({joinUrl:e,runtime:`slicc-standalone`,fetchImpl:qp()},{onConnected:e=>d(e),onReconnecting:e=>{$.info(`Follower reconnecting`,{attempt:e})},onGaveUp:e=>{$.warn(`Follower reconnect gave up`,{lastError:e})}})};if(window.addEventListener(`slicc:tray-join`,(e=>{p(e.detail.joinUrl)})),window.addEventListener(`beforeunload`,()=>{s&&clearInterval(s),i?.close(),a?.cancel()},{once:!0}),n?.joinUrl)p(n.joinUrl);else if(n?.workerBaseUrl){let e,t,r,i,a=()=>{t=new Vb({browserTransport:f.getTransport(),browserAPI:f,getMessages:()=>l.panels.chat.getMessages(),getScoopJid:()=>_?.jid??`cone`,onFollowerMessage:(e,t)=>{l.panels.chat.addUserMessage(e),te.sendMessage(e,t)},onFollowerAbort:()=>{te.stop()}}),A=t,Yp(()=>t.getConnectedFollowers()),f.setTrayTargetProvider(t),i&&clearInterval(i);let n=async()=>{try{let e=await f.listPages();t.setLocalTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})))}catch{}};i=setInterval(n,5e3),n(),r=new hb({sendControlMessage:t=>e.sendControlMessage(t),onPeerConnected:(e,n)=>{$.info(`Tray follower data channel opened`,{controllerId:e.controllerId,bootstrapId:e.bootstrapId,attempt:e.attempt,runtime:e.runtime}),t.addFollower(e.bootstrapId,n,{runtime:e.runtime,connectedAt:e.connectedAt??void 0})}})};a(),m.add(e=>{t.broadcastEvent(e)}),e=new Up({workerBaseUrl:n.workerBaseUrl,runtime:`slicc-standalone`,fetchImpl:qp(),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)})})}}),Qp(async()=>{t.stop(),r.stop(),e.stop(),await e.clearSession();let n=await e.start(),i=u(window.location.href,n.workerBaseUrl,n.trayId);return i!==window.location.href&&window.history.replaceState(window.history.state,``,i),a(),zp()}),e.start().then(e=>{let t=u(window.location.href,e.workerBaseUrl,e.trayId);t!==window.location.href&&window.history.replaceState(window.history.state,``,t)}).catch(e=>{$.warn(`Leader tray join failed`,{error:e instanceof Error?e.message:String(e)})}),window.addEventListener(`beforeunload`,()=>{clearInterval(i),t.stop(),r.stop(),e.stop()},{once:!0})}}$.info(`Orchestrator initialized — cone+scoops ready`,{scoopCount:E.getScoops().length}),Av().catch(()=>{})}bx().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{Uv as a,si as c,zy as i,ii as l,qy as n,wa as o,Yy as r,ai as s,Ky as t};