sliccy 2.3.0 → 2.3.1

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.
Files changed (44) hide show
  1. package/dist/ui/assets/anthropic-BCyIsIaq.js +36 -0
  2. package/dist/ui/assets/azure-openai-responses-CSjq2stN.js +1 -0
  3. package/dist/ui/assets/{dist-CLNuUmSq.js → dist-DEO1hNOZ2.js} +2 -2
  4. package/dist/ui/assets/{es-B8PfOjm2.js → es-C70AgaBB.js} +1 -1
  5. package/dist/ui/assets/{google-DO7yvPO4.js → google-CHyDZd_T.js} +1 -1
  6. package/dist/ui/assets/google-gemini-cli-CLKrNaN2.js +2 -0
  7. package/dist/ui/assets/{google-shared-BWQFIy8i.js → google-shared-Dm8eVEiI.js} +3 -3
  8. package/dist/ui/assets/google-vertex-DO4sjUxJ.js +1 -0
  9. package/dist/ui/assets/headers-Dr-OH1-5.js +1 -0
  10. package/dist/ui/assets/{index-BHX7DMdz.js → index-oz1QVZKm.js} +14 -14
  11. package/dist/ui/assets/mistral-DZrYPR3L.js +46 -0
  12. package/dist/ui/assets/openai-codex-responses-BtjFHbjN.js +7 -0
  13. package/dist/ui/assets/openai-completions-CvOr92bY.js +5 -0
  14. package/dist/ui/assets/openai-responses-D1b_e2py.js +1 -0
  15. package/dist/ui/assets/{openai-responses-shared-CUFAAR--.js → openai-responses-shared-D0nL21GA.js} +2 -2
  16. package/dist/ui/assets/{provider-settings-DUchoI6k.js → provider-settings-BNHO2Tcv.js} +5 -5
  17. package/dist/ui/assets/simple-options-GPCv4BUJ.js +1 -0
  18. package/dist/ui/index.html +3 -3
  19. package/dist/ui/packages/webapp/index.html +3 -3
  20. package/package.json +1 -1
  21. package/dist/ui/assets/anthropic-CMlPlDIk.js +0 -36
  22. package/dist/ui/assets/azure-openai-responses-D8KcZhBl.js +0 -1
  23. package/dist/ui/assets/google-gemini-cli-DdA3nx6W.js +0 -2
  24. package/dist/ui/assets/google-vertex-C5s4LVmo.js +0 -1
  25. package/dist/ui/assets/mistral-BPcBoGoy.js +0 -7
  26. package/dist/ui/assets/openai-codex-responses-N7fKFsLN.js +0 -7
  27. package/dist/ui/assets/openai-completions-rv4ohN_x.js +0 -5
  28. package/dist/ui/assets/openai-responses-D4uieQSd.js +0 -1
  29. package/dist/ui/assets/simple-options-B6uouUxh.js +0 -1
  30. /package/dist/ui/assets/{addon-fit-CVV7fTw9.js → addon-fit-CnTv21Qe.js} +0 -0
  31. /package/dist/ui/assets/{bsh-watchdog-C8qkdGvF.js → bsh-watchdog-BXTi5bzs.js} +0 -0
  32. /package/dist/ui/assets/{chat-fixture-BVDDtJMz.js → chat-fixture-Nts2sMME.js} +0 -0
  33. /package/dist/ui/assets/{github-copilot-headers-C0FOlzjL.js → github-copilot-headers-BNWb_OCE.js} +0 -0
  34. /package/dist/ui/assets/{hash-CQjDwcjR.js → hash-CsofV07h.js} +0 -0
  35. /package/dist/ui/assets/{lick-manager-proxy-B2bMdplq.js → lick-manager-proxy-CogaR9kt.js} +0 -0
  36. /package/dist/ui/assets/{oauth-service-BoyG8vZW.js → oauth-service-CfTUWB9P.js} +0 -0
  37. /package/dist/ui/assets/{offscreen-client-CLgve4BY.js → offscreen-client-BlWuVmPl.js} +0 -0
  38. /package/dist/ui/assets/{pdfjs-kFXy8Q7j.js → pdfjs-DEEfCfSi.js} +0 -0
  39. /package/dist/ui/assets/{pyodide-Doh5i2Gj.js → pyodide-3PMN6X39.js} +0 -0
  40. /package/dist/ui/assets/{sanitize-unicode-BOCYaWok.js → sanitize-unicode-Dw-JFaZE.js} +0 -0
  41. /package/dist/ui/assets/{secret-masking-Bqg5RXZg.js → secret-masking-Bg1u5YcF.js} +0 -0
  42. /package/dist/ui/assets/{slicc-editor-Cgz0dhRS.js → slicc-editor-DmlPglrQ.js} +0 -0
  43. /package/dist/ui/assets/{sql-wasm-Dx6P9mA8.js → sql-wasm-yST8pDy6.js} +0 -0
  44. /package/dist/ui/assets/{xterm-ucbPh68r.js → xterm-CAZt1iF4.js} +0 -0
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/slicc-editor-Cgz0dhRS.js","assets/preload-helper-D4M6sveU.js","assets/dist-C43FKPek.js","assets/sql-wasm-Dx6P9mA8.js","assets/chunk-jRWAZmH_.js","assets/__vite-browser-external-BC516C8G.js","assets/pyodide-Doh5i2Gj.js","assets/es-B8PfOjm2.js","assets/dist-CLNuUmSq.js","assets/provider-settings-DUchoI6k.js","assets/env-api-keys-7VVTY3n7.js","assets/simple-options-B6uouUxh.js","assets/json-parse-Dn8fsQhn.js","assets/openai-CQsomflW.js","assets/tray-follower-status-BlQSlF6m.js","assets/logger-B-No_qN_.js","assets/skills-CTCIxQqH.js","assets/fs-bsu2i7du.js","assets/path-utils-CNNVZ3-O.js","assets/constants-DdIXxN9e.js","assets/xterm-BmfB5bmM.css","assets/offscreen-client-CLgve4BY.js","assets/cdp-CsCvDwW3.js","assets/cost-command-DBzah9S9.js","assets/bsh-watchdog-C8qkdGvF.js"])))=>i.map(i=>d[i]);
2
- import{o as e,r as t,t as n}from"./chunk-jRWAZmH_.js";import{t as r}from"./logger-B-No_qN_.js";import{t as i}from"./preload-helper-D4M6sveU.js";import{c as a,f as o,h as s,i as c,l,m as u,n as d,o as f,p,r as m,s as h,t as g,u as _,v,y}from"./tray-follower-status-BlQSlF6m.js";import{_ as b,a as x,b as S,c as C,d as w,f as T,g as E,i as D,m as O,n as k,o as A,p as ee,r as j,s as te,t as ne,u as re,v as M,y as N}from"./provider-settings-DUchoI6k.js";import{f as P,l as ie,p as ae,s as oe,u as se}from"./constants-DdIXxN9e.js";import{a as F,i as I,n as ce,o as le,r as ue}from"./fs-bsu2i7du.js";import{n as L,t as R}from"./path-utils-CNNVZ3-O.js";import{n as de,r as fe}from"./skills-CTCIxQqH.js";import{a as pe,c as z,d as B,f as me,i as he,l as V,n as ge,o as H,r as _e,s as U,u as W}from"./cdp-CsCvDwW3.js";import{_ as ve,a as ye,b as be,c as xe,d as G,f as Se,g as Ce,h as we,i as Te,l as Ee,m as De,n as Oe,o as ke,p as Ae,r as je,s as Me,t as Ne,u as Pe,v as Fe,x as Ie,y as Le}from"./db-CmHnV4DS.js";import{a as Re,i as ze,n as Be,o as Ve,r as He,s as Ue}from"./cost-command-DBzah9S9.js";import{t as We}from"./magick-wasm-DA8eLvGf.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 Ge(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ke=Ge();function qe(e){Ke=e}var Je={exec:()=>null};function Ye(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(Ze.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var Xe=(()=>{try{return!0}catch{return!1}})(),Ze={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,`i`),blockquoteBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}>`)},Qe=/^(?:[ \t]*(?:\n|$))+/,$e=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,et=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,tt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,nt=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,rt=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,it=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,at=Ye(it).replace(/bull/g,rt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),ot=Ye(it).replace(/bull/g,rt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),st=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ct=/^[^\n]+/,lt=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ut=Ye(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,lt).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),dt=Ye(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,rt).getRegex(),ft=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,pt=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,mt=Ye(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,pt).replace(`tag`,ft).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),ht=Ye(st).replace(`hr`,tt).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,ft).getRegex(),gt={blockquote:Ye(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,ht).getRegex(),code:$e,def:ut,fences:et,heading:nt,hr:tt,html:mt,lheading:at,list:dt,newline:Qe,paragraph:ht,table:Je,text:ct},_t=Ye(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,tt).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,ft).getRegex(),vt={...gt,lheading:ot,table:_t,paragraph:Ye(st).replace(`hr`,tt).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,_t).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,ft).getRegex()},yt={...gt,html:Ye(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,pt).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Je,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Ye(st).replace(`hr`,tt).replace(`heading`,` *#{1,6} *[^
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/slicc-editor-DmlPglrQ.js","assets/preload-helper-D4M6sveU.js","assets/dist-C43FKPek.js","assets/sql-wasm-yST8pDy6.js","assets/chunk-jRWAZmH_.js","assets/__vite-browser-external-BC516C8G.js","assets/pyodide-3PMN6X39.js","assets/es-C70AgaBB.js","assets/dist-DEO1hNOZ2.js","assets/provider-settings-BNHO2Tcv.js","assets/env-api-keys-7VVTY3n7.js","assets/simple-options-GPCv4BUJ.js","assets/json-parse-Dn8fsQhn.js","assets/openai-CQsomflW.js","assets/tray-follower-status-BlQSlF6m.js","assets/logger-B-No_qN_.js","assets/skills-CTCIxQqH.js","assets/fs-bsu2i7du.js","assets/path-utils-CNNVZ3-O.js","assets/constants-DdIXxN9e.js","assets/xterm-BmfB5bmM.css","assets/offscreen-client-BlWuVmPl.js","assets/cdp-CsCvDwW3.js","assets/cost-command-DBzah9S9.js","assets/bsh-watchdog-BXTi5bzs.js"])))=>i.map(i=>d[i]);
2
+ import{o as e,r as t,t as n}from"./chunk-jRWAZmH_.js";import{t as r}from"./logger-B-No_qN_.js";import{t as i}from"./preload-helper-D4M6sveU.js";import{c as a,f as o,h as s,i as c,l,m as u,n as d,o as f,p,r as m,s as h,t as g,u as _,v,y}from"./tray-follower-status-BlQSlF6m.js";import{_ as b,a as x,b as S,c as C,d as w,f as T,g as E,i as D,m as O,n as k,o as A,p as ee,r as j,s as te,t as ne,u as re,v as M,y as N}from"./provider-settings-BNHO2Tcv.js";import{f as P,l as ie,p as ae,s as oe,u as se}from"./constants-DdIXxN9e.js";import{a as F,i as I,n as ce,o as le,r as ue}from"./fs-bsu2i7du.js";import{n as L,t as R}from"./path-utils-CNNVZ3-O.js";import{n as de,r as fe}from"./skills-CTCIxQqH.js";import{a as pe,c as z,d as B,f as me,i as he,l as V,n as ge,o as H,r as _e,s as U,u as W}from"./cdp-CsCvDwW3.js";import{_ as ve,a as ye,b as be,c as xe,d as G,f as Se,g as Ce,h as we,i as Te,l as Ee,m as De,n as Oe,o as ke,p as Ae,r as je,s as Me,t as Ne,u as Pe,v as Fe,x as Ie,y as Le}from"./db-CmHnV4DS.js";import{a as Re,i as ze,n as Be,o as Ve,r as He,s as Ue}from"./cost-command-DBzah9S9.js";import{t as We}from"./magick-wasm-DA8eLvGf.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 Ge(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ke=Ge();function qe(e){Ke=e}var Je={exec:()=>null};function Ye(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(Ze.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var Xe=(()=>{try{return!0}catch{return!1}})(),Ze={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,`i`),blockquoteBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}>`)},Qe=/^(?:[ \t]*(?:\n|$))+/,$e=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,et=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,tt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,nt=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,rt=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,it=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,at=Ye(it).replace(/bull/g,rt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),ot=Ye(it).replace(/bull/g,rt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),st=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ct=/^[^\n]+/,lt=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ut=Ye(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,lt).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),dt=Ye(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,rt).getRegex(),ft=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,pt=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,mt=Ye(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,pt).replace(`tag`,ft).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),ht=Ye(st).replace(`hr`,tt).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,ft).getRegex(),gt={blockquote:Ye(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,ht).getRegex(),code:$e,def:ut,fences:et,heading:nt,hr:tt,html:mt,lheading:at,list:dt,newline:Qe,paragraph:ht,table:Je,text:ct},_t=Ye(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,tt).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,ft).getRegex(),vt={...gt,lheading:ot,table:_t,paragraph:Ye(st).replace(`hr`,tt).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,_t).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,ft).getRegex()},yt={...gt,html:Ye(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,pt).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Je,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Ye(st).replace(`hr`,tt).replace(`heading`,` *#{1,6} *[^
3
3
  ]`).replace(`lheading`,at).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},bt=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,xt=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,St=/^( {2,}|\\)\n(?!\s*$)/,Ct=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,wt=/[\p{P}\p{S}]/u,Tt=/[\s\p{P}\p{S}]/u,Et=/[^\s\p{P}\p{S}]/u,Dt=Ye(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,Tt).getRegex(),Ot=/(?!~)[\p{P}\p{S}]/u,kt=/(?!~)[\s\p{P}\p{S}]/u,At=/(?:[^\s\p{P}\p{S}]|~)/u,jt=Ye(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,Xe?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),Mt=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Nt=Ye(Mt,`u`).replace(/punct/g,wt).getRegex(),Pt=Ye(Mt,`u`).replace(/punct/g,Ot).getRegex(),Ft=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,It=Ye(Ft,`gu`).replace(/notPunctSpace/g,Et).replace(/punctSpace/g,Tt).replace(/punct/g,wt).getRegex(),Lt=Ye(Ft,`gu`).replace(/notPunctSpace/g,At).replace(/punctSpace/g,kt).replace(/punct/g,Ot).getRegex(),Rt=Ye(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,Et).replace(/punctSpace/g,Tt).replace(/punct/g,wt).getRegex(),zt=Ye(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,wt).getRegex(),Bt=Ye(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Et).replace(/punctSpace/g,Tt).replace(/punct/g,wt).getRegex(),Vt=Ye(/\\(punct)/,`gu`).replace(/punct/g,wt).getRegex(),Ht=Ye(/^<(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(),Ut=Ye(pt).replace(`(?:-->|$)`,`-->`).getRegex(),Wt=Ye(`^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`,Ut).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Gt=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Kt=Ye(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,Gt).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),qt=Ye(/^!?\[(label)\]\[(ref)\]/).replace(`label`,Gt).replace(`ref`,lt).getRegex(),Jt=Ye(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,lt).getRegex(),Yt=Ye(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,qt).replace(`nolink`,Jt).getRegex(),Xt=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Zt={_backpedal:Je,anyPunctuation:Vt,autolink:Ht,blockSkip:jt,br:St,code:xt,del:Je,delLDelim:Je,delRDelim:Je,emStrongLDelim:Nt,emStrongRDelimAst:It,emStrongRDelimUnd:Rt,escape:bt,link:Kt,nolink:Jt,punctuation:Dt,reflink:qt,reflinkSearch:Yt,tag:Wt,text:Ct,url:Je},Qt={...Zt,link:Ye(/^!?\[(label)\]\((.*?)\)/).replace(`label`,Gt).getRegex(),reflink:Ye(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,Gt).getRegex()},$t={...Zt,emStrongRDelimAst:Lt,emStrongLDelim:Pt,delLDelim:zt,delRDelim:Bt,url:Ye(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,Xt).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:Ye(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,Xt).getRegex()},en={...$t,br:Ye(St).replace(`{2,}`,`*`).getRegex(),text:Ye($t.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},tn={normal:gt,gfm:vt,pedantic:yt},nn={normal:Zt,gfm:$t,breaks:en,pedantic:Qt},rn={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},an=e=>rn[e];function on(e,t){if(t){if(Ze.escapeTest.test(e))return e.replace(Ze.escapeReplace,an)}else if(Ze.escapeTestNoEncode.test(e))return e.replace(Ze.escapeReplaceNoEncode,an);return e}function sn(e){try{e=encodeURI(e).replace(Ze.percentDecode,`%`)}catch{return null}return e}function cn(e,t){let n=e.replace(Ze.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(Ze.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``);for(;r<n.length;r++)n[r]=n[r].trim().replace(Ze.slashPipe,`|`);return n}function ln(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 un(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 dn(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 fn(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 pn(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 mn(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
@@ -165,7 +165,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
165
165
  };
166
166
  window.slicc = api;
167
167
  window.bridge = api;
168
- })();`}async renderFullDoc(e,t){let n=`<script>${this.generateBridgeScript()}<\/script>`,r=this.collectThemeCSS(),i=r?`<style>${r}</style>`:``,a=e.includes(`<slicc-editor`)?`<script src="/slicc-editor.js"><\/script>`:``,o=e.includes(`<slicc-diff`)?`<script src="/slicc-diff.js"><\/script>`:``,s=`<script>(function(){try{if(${ii()?`true`:`false`})document.documentElement.classList.add('theme-light');}catch(e){}})();<\/script>`+n+i+a+o+`<script src="/lucide-icons.js"><\/script>`,c,l=e.match(/<head\b[^>]*>/i);if(l){let t=l.index+l[0].length;c=e.slice(0,t)+s+e.slice(t)}else{let t=e.match(/<script\b/i);if(t)c=e.slice(0,t.index)+s+e.slice(t.index);else{let t=e.match(/<html\b[^>]*>/i);if(t){let n=t.index+t[0].length;c=e.slice(0,n)+s+e.slice(n)}else c=s+e}}let u=document.createElement(`iframe`);u.setAttribute(`sandbox`,`allow-scripts allow-same-origin`),u.style.cssText=`width: 100%; flex: 1; border: none; min-height: 0;`,u.srcdoc=c,this.iframe=u,await new Promise((e,n)=>{let r=setTimeout(()=>{n(Error(`full-doc iframe load timed out`))},5e3);u.addEventListener(`load`,()=>{clearTimeout(r),oi(u.contentWindow);let n=this.bridge.getState();u.contentWindow?.postMessage({type:`sprinkle-init`,name:t,savedState:n},`*`),e()},{once:!0}),u.addEventListener(`error`,e=>{clearTimeout(r),n(Error(`full-doc iframe failed to load`))},{once:!0}),this.container.appendChild(u)}),this.messageHandler=e=>{if(e.source!==u.contentWindow)return;let t=e.data;t?.type&&(t.type===`sprinkle-lick`?this.bridge.lick({action:t.action,data:t.data}):t.type===`sprinkle-set-state`?this.bridge.setState(t.data):t.type===`sprinkle-close`?this.bridge.close():t.type===`sprinkle-stop-cone`?this.bridge.stopCone():t.type===`sprinkle-readfile`?this.bridge.readFile(t.path).then(e=>u.contentWindow?.postMessage({type:`sprinkle-readfile-response`,id:t.id,content:e},`*`),e=>u.contentWindow?.postMessage({type:`sprinkle-readfile-response`,id:t.id,error:e instanceof Error?e.message:String(e)},`*`)):t.type===`sprinkle-writefile`?this.bridge.writeFile(t.path,t.content).then(()=>u.contentWindow?.postMessage({type:`sprinkle-writefile-response`,id:t.id},`*`),e=>u.contentWindow?.postMessage({type:`sprinkle-writefile-response`,id:t.id,error:e instanceof Error?e.message:String(e)},`*`)):t.type===`sprinkle-readdir`?this.bridge.readDir(t.path).then(e=>u.contentWindow?.postMessage({type:`sprinkle-readdir-response`,id:t.id,entries:e},`*`),e=>u.contentWindow?.postMessage({type:`sprinkle-readdir-response`,id:t.id,error:e instanceof Error?e.message:String(e)},`*`)):t.type===`sprinkle-exists`?this.bridge.exists(t.path).then(e=>u.contentWindow?.postMessage({type:`sprinkle-exists-response`,id:t.id,exists:e},`*`),e=>u.contentWindow?.postMessage({type:`sprinkle-exists-response`,id:t.id,error:e instanceof Error?e.message:String(e)},`*`)):t.type===`sprinkle-stat`?this.bridge.stat(t.path).then(e=>u.contentWindow?.postMessage({type:`sprinkle-stat-response`,id:t.id,stat:e},`*`),e=>u.contentWindow?.postMessage({type:`sprinkle-stat-response`,id:t.id,error:e instanceof Error?e.message:String(e)},`*`)):t.type===`sprinkle-mkdir`?this.bridge.mkdir(t.path).then(()=>u.contentWindow?.postMessage({type:`sprinkle-mkdir-response`,id:t.id},`*`),e=>u.contentWindow?.postMessage({type:`sprinkle-mkdir-response`,id:t.id,error:e instanceof Error?e.message:String(e)},`*`)):t.type===`sprinkle-rm`&&this.bridge.rm(t.path).then(()=>u.contentWindow?.postMessage({type:`sprinkle-rm-response`,id:t.id},`*`),e=>u.contentWindow?.postMessage({type:`sprinkle-rm-response`,id:t.id,error:e instanceof Error?e.message:String(e)},`*`)))},window.addEventListener(`message`,this.messageHandler)}renderInline(e,t){if(e.includes(`<slicc-editor`)&&!customElements.get(`slicc-editor`)&&i(()=>import(`./slicc-editor-Cgz0dhRS.js`),__vite__mapDeps([0,1,2])),e.includes(`<slicc-diff`)&&!customElements.get(`slicc-diff`)){let e=document.createElement(`script`);e.src=`/slicc-diff.js`,document.head.appendChild(e)}window.__slicc_sprinkles||(window.__slicc_sprinkles={}),window.__slicc_sprinkles[t]=this.bridge,this.bridge._container=this.container;let n=document.createElement(`div`);n.className=`sprinkle-content`,n.innerHTML=e,this.container.appendChild(n);for(let e of n.querySelectorAll(`.fill[data-value]`)){let t=parseFloat(e.dataset.value||`0`);t>=0&&t<=100&&(e.style.width=`${t}%`)}let r=`window.__slicc_sprinkles[${JSON.stringify(t)}]`;for(let e of n.querySelectorAll(`[onclick]`)){let t=e.getAttribute(`onclick`)||``;/\b(slicc|bridge)\b/.test(t)&&e.setAttribute(`onclick`,t.replace(/\b(slicc|bridge)\b/g,r))}let a=Array.from(n.querySelectorAll(`script`));for(let e of a){e.remove();let t=document.createElement(`script`);for(let n of e.attributes)t.setAttribute(n.name,n.value);if(!e.src){let i=new Set;for(let e of n.querySelectorAll(`[onclick]`)){let t=e.getAttribute(`onclick`)||``;for(let e of t.matchAll(/\b(\w+)\s*\(/g)){let t=e[1];[`slicc`,`bridge`,`lick`,`close`].includes(t)||i.add(t)}}let a=[...i].map(e=>`if (typeof ${e} === 'function') window.${e} = ${e};`).join(`
168
+ })();`}async renderFullDoc(e,t){let n=`<script>${this.generateBridgeScript()}<\/script>`,r=this.collectThemeCSS(),i=r?`<style>${r}</style>`:``,a=e.includes(`<slicc-editor`)?`<script src="/slicc-editor.js"><\/script>`:``,o=e.includes(`<slicc-diff`)?`<script src="/slicc-diff.js"><\/script>`:``,s=`<script>(function(){try{if(${ii()?`true`:`false`})document.documentElement.classList.add('theme-light');}catch(e){}})();<\/script>`+n+i+a+o+`<script src="/lucide-icons.js"><\/script>`,c,l=e.match(/<head\b[^>]*>/i);if(l){let t=l.index+l[0].length;c=e.slice(0,t)+s+e.slice(t)}else{let t=e.match(/<script\b/i);if(t)c=e.slice(0,t.index)+s+e.slice(t.index);else{let t=e.match(/<html\b[^>]*>/i);if(t){let n=t.index+t[0].length;c=e.slice(0,n)+s+e.slice(n)}else c=s+e}}let u=document.createElement(`iframe`);u.setAttribute(`sandbox`,`allow-scripts allow-same-origin`),u.style.cssText=`width: 100%; flex: 1; border: none; min-height: 0;`,u.srcdoc=c,this.iframe=u,await new Promise((e,n)=>{let r=setTimeout(()=>{n(Error(`full-doc iframe load timed out`))},5e3);u.addEventListener(`load`,()=>{clearTimeout(r),oi(u.contentWindow);let n=this.bridge.getState();u.contentWindow?.postMessage({type:`sprinkle-init`,name:t,savedState:n},`*`),e()},{once:!0}),u.addEventListener(`error`,e=>{clearTimeout(r),n(Error(`full-doc iframe failed to load`))},{once:!0}),this.container.appendChild(u)}),this.messageHandler=e=>{if(e.source!==u.contentWindow)return;let t=e.data;t?.type&&(t.type===`sprinkle-lick`?this.bridge.lick({action:t.action,data:t.data}):t.type===`sprinkle-set-state`?this.bridge.setState(t.data):t.type===`sprinkle-close`?this.bridge.close():t.type===`sprinkle-stop-cone`?this.bridge.stopCone():t.type===`sprinkle-readfile`?this.bridge.readFile(t.path).then(e=>u.contentWindow?.postMessage({type:`sprinkle-readfile-response`,id:t.id,content:e},`*`),e=>u.contentWindow?.postMessage({type:`sprinkle-readfile-response`,id:t.id,error:e instanceof Error?e.message:String(e)},`*`)):t.type===`sprinkle-writefile`?this.bridge.writeFile(t.path,t.content).then(()=>u.contentWindow?.postMessage({type:`sprinkle-writefile-response`,id:t.id},`*`),e=>u.contentWindow?.postMessage({type:`sprinkle-writefile-response`,id:t.id,error:e instanceof Error?e.message:String(e)},`*`)):t.type===`sprinkle-readdir`?this.bridge.readDir(t.path).then(e=>u.contentWindow?.postMessage({type:`sprinkle-readdir-response`,id:t.id,entries:e},`*`),e=>u.contentWindow?.postMessage({type:`sprinkle-readdir-response`,id:t.id,error:e instanceof Error?e.message:String(e)},`*`)):t.type===`sprinkle-exists`?this.bridge.exists(t.path).then(e=>u.contentWindow?.postMessage({type:`sprinkle-exists-response`,id:t.id,exists:e},`*`),e=>u.contentWindow?.postMessage({type:`sprinkle-exists-response`,id:t.id,error:e instanceof Error?e.message:String(e)},`*`)):t.type===`sprinkle-stat`?this.bridge.stat(t.path).then(e=>u.contentWindow?.postMessage({type:`sprinkle-stat-response`,id:t.id,stat:e},`*`),e=>u.contentWindow?.postMessage({type:`sprinkle-stat-response`,id:t.id,error:e instanceof Error?e.message:String(e)},`*`)):t.type===`sprinkle-mkdir`?this.bridge.mkdir(t.path).then(()=>u.contentWindow?.postMessage({type:`sprinkle-mkdir-response`,id:t.id},`*`),e=>u.contentWindow?.postMessage({type:`sprinkle-mkdir-response`,id:t.id,error:e instanceof Error?e.message:String(e)},`*`)):t.type===`sprinkle-rm`&&this.bridge.rm(t.path).then(()=>u.contentWindow?.postMessage({type:`sprinkle-rm-response`,id:t.id},`*`),e=>u.contentWindow?.postMessage({type:`sprinkle-rm-response`,id:t.id,error:e instanceof Error?e.message:String(e)},`*`)))},window.addEventListener(`message`,this.messageHandler)}renderInline(e,t){if(e.includes(`<slicc-editor`)&&!customElements.get(`slicc-editor`)&&i(()=>import(`./slicc-editor-DmlPglrQ.js`),__vite__mapDeps([0,1,2])),e.includes(`<slicc-diff`)&&!customElements.get(`slicc-diff`)){let e=document.createElement(`script`);e.src=`/slicc-diff.js`,document.head.appendChild(e)}window.__slicc_sprinkles||(window.__slicc_sprinkles={}),window.__slicc_sprinkles[t]=this.bridge,this.bridge._container=this.container;let n=document.createElement(`div`);n.className=`sprinkle-content`,n.innerHTML=e,this.container.appendChild(n);for(let e of n.querySelectorAll(`.fill[data-value]`)){let t=parseFloat(e.dataset.value||`0`);t>=0&&t<=100&&(e.style.width=`${t}%`)}let r=`window.__slicc_sprinkles[${JSON.stringify(t)}]`;for(let e of n.querySelectorAll(`[onclick]`)){let t=e.getAttribute(`onclick`)||``;/\b(slicc|bridge)\b/.test(t)&&e.setAttribute(`onclick`,t.replace(/\b(slicc|bridge)\b/g,r))}let a=Array.from(n.querySelectorAll(`script`));for(let e of a){e.remove();let t=document.createElement(`script`);for(let n of e.attributes)t.setAttribute(n.name,n.value);if(!e.src){let i=new Set;for(let e of n.querySelectorAll(`[onclick]`)){let t=e.getAttribute(`onclick`)||``;for(let e of t.matchAll(/\b(\w+)\s*\(/g)){let t=e[1];[`slicc`,`bridge`,`lick`,`close`].includes(t)||i.add(t)}}let a=[...i].map(e=>`if (typeof ${e} === 'function') window.${e} = ${e};`).join(`
169
169
  `);t.textContent=`(function() { var slicc = ${r}; var bridge = slicc;\n`+e.textContent+(a?`
170
170
  `+a:``)+`
171
171
  })();`}n.appendChild(t),this.scripts.push(t)}}dispose(){this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.iframe&&=(si(this.iframe.contentWindow),this.iframe.remove(),null);for(let e of this.scripts)e.remove();this.scripts=[];let e=this.container.querySelector(`.sprinkle-content`);e&&e.remove(),window.__slicc_sprinkles&&delete window.__slicc_sprinkles[this.bridge.name]}async getLucideScript(){return e.cachedLucideScript===null?(e.lucideScriptPromise===null&&(e.lucideScriptPromise=(async()=>{try{let t=await fetch(chrome.runtime.getURL(`lucide-icons.js`));if(t.ok){let n=await t.text();return e.cachedLucideScript=n,n}}catch{}return e.cachedLucideScript=``,``})()),e.lucideScriptPromise):e.cachedLucideScript}};function _i(e,t){return e.replace(/url\(\s*['"]?([^'")]+)['"]?\s*\)/g,(e,n)=>{if(/^(https?:|data:|blob:)/i.test(n))return`url('${n}')`;try{return`url('${new URL(n,t).href}')`}catch{return`url('${n}')`}})}function vi(){if(typeof getComputedStyle!=`function`)return``;let e=[],t=[],n=[],r=location.href,i=e=>e===`:root`||e===`:root.theme-light`||e.startsWith(`.theme-light `)||e===`.theme-light`||e.split(`,`).some(e=>{let t=e.trim();return t===`:root`||t===`:root.theme-light`||t.startsWith(`.theme-light `)||t===`.theme-light`});for(let a of document.styleSheets)try{for(let o of a.cssRules)if(o instanceof CSSFontFaceRule)e.push(_i(o.cssText,r));else if(o instanceof CSSStyleRule){let e=o.selectorText;i(e)&&t.push(o.cssText),(e.includes(`.sprinkle-`)||e.includes(`.fill`))&&n.push(o.cssText)}}catch{}return e.join(`
@@ -1290,7 +1290,7 @@ except SystemExit as exc:
1290
1290
  except BaseException:
1291
1291
  traceback.print_exc()
1292
1292
  __slicc_exit_code = 1
1293
- `,Lh=null,Rh=null,zh=Object.create(null),Bh=class extends Error{constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function Vh(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 Hh(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}function Uh(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function Wh(e){if(/^(https?:\/\/|about:|file:|chrome:)/i.test(e))return!0;try{return new URL(e).protocol.length>0}catch{return!1}}function Gh(e,t){return e===`/`?t.startsWith(`/`):t===e||t.startsWith(`${e}/`)}function Kh(e){return Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function qh(e){return e==null?``:e instanceof Uint8Array?`x'${Kh(e)}'`:String(e)}function Jh(e){return o(e)}function Yh(e){let t=typeof chrome<`u`&&!!chrome?.runtime?.id,n=`/preview${e}`;return t?chrome.runtime.getURL(n):`${typeof window<`u`&&window.location?.origin?window.location.origin:`http://localhost:5710`}${n}`}function Xh(e){return e.length===0||e.startsWith(`/`)?!1:!e.split(`/`).some(e=>e===`..`)}function Zh(e,t){return L(`${e}/${t}`)}function Qh(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function $h(e,t){let n=import.meta.resolve;if(typeof n==`function`)try{return new URL(`./`,n(e))}catch{}return new URL(t,import.meta.url)}async function eg(){return Lh||=(async()=>{let t=(await i(()=>import(`./sql-wasm-Dx6P9mA8.js`).then(t=>e(t.default,1)),__vite__mapDeps([3,4,5]))).default,n=typeof window>`u`?$h(`sql.js/dist/sql-wasm.js`,`../../../../../node_modules/sql.js/dist/`).toString():Nh;return t({locateFile:e=>`${n}${e}`})})(),Lh}var tg=typeof chrome<`u`&&!!chrome?.runtime?.id;async function ng(){return Rh||=(async()=>{let{loadPyodide:e}=await i(async()=>{let{loadPyodide:e}=await import(`./pyodide-Doh5i2Gj.js`);return{loadPyodide:e}},__vite__mapDeps([6,4,1])),t;return t=typeof window>`u`?decodeURIComponent($h(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname):tg?chrome.runtime.getURL(`pyodide/`):Ph,e({indexURL:t,fullStdLib:!1})})(),Rh}var rg=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 ig(e){let t=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,n=new Set,r;for(;(r=t.exec(e))!==null;)n.add(r[2]);return[...n]}function ag(){return{stdout:`usage: node -e <code> [args...]
1293
+ `,Lh=null,Rh=null,zh=Object.create(null),Bh=class extends Error{constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function Vh(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 Hh(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}function Uh(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function Wh(e){if(/^(https?:\/\/|about:|file:|chrome:)/i.test(e))return!0;try{return new URL(e).protocol.length>0}catch{return!1}}function Gh(e,t){return e===`/`?t.startsWith(`/`):t===e||t.startsWith(`${e}/`)}function Kh(e){return Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function qh(e){return e==null?``:e instanceof Uint8Array?`x'${Kh(e)}'`:String(e)}function Jh(e){return o(e)}function Yh(e){let t=typeof chrome<`u`&&!!chrome?.runtime?.id,n=`/preview${e}`;return t?chrome.runtime.getURL(n):`${typeof window<`u`&&window.location?.origin?window.location.origin:`http://localhost:5710`}${n}`}function Xh(e){return e.length===0||e.startsWith(`/`)?!1:!e.split(`/`).some(e=>e===`..`)}function Zh(e,t){return L(`${e}/${t}`)}function Qh(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function $h(e,t){let n=import.meta.resolve;if(typeof n==`function`)try{return new URL(`./`,n(e))}catch{}return new URL(t,import.meta.url)}async function eg(){return Lh||=(async()=>{let t=(await i(()=>import(`./sql-wasm-yST8pDy6.js`).then(t=>e(t.default,1)),__vite__mapDeps([3,4,5]))).default,n=typeof window>`u`?$h(`sql.js/dist/sql-wasm.js`,`../../../../../node_modules/sql.js/dist/`).toString():Nh;return t({locateFile:e=>`${n}${e}`})})(),Lh}var tg=typeof chrome<`u`&&!!chrome?.runtime?.id;async function ng(){return Rh||=(async()=>{let{loadPyodide:e}=await i(async()=>{let{loadPyodide:e}=await import(`./pyodide-3PMN6X39.js`);return{loadPyodide:e}},__vite__mapDeps([6,4,1])),t;return t=typeof window>`u`?decodeURIComponent($h(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname):tg?chrome.runtime.getURL(`pyodide/`):Ph,e({indexURL:t,fullStdLib:!1})})(),Rh}var rg=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 ig(e){let t=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,n=new Set,r;for(;(r=t.exec(e))!==null;)n.add(r[2]);return[...n]}function ag(){return{stdout:`usage: node -e <code> [args...]
1294
1294
  `,stderr:``,exitCode:0}}function og(){return{stdout:`${Fh}\n`,stderr:``,exitCode:0}}function sg(){return Ve(`node`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return ag();if(e.includes(`--version`)||e.includes(`-v`))return og();let n=``,r=`<stdin>`,a=[`node`];if(e.length>0&&(e[0]===`-e`||e[0]===`--eval`)){if(!e[1])return{stdout:``,stderr:`node: option requires an argument -- eval
1295
1295
  `,exitCode:9};n=e[1],r=`[eval]`,a=[`node`,...e.slice(2)]}else if(e.length>0&&!e[0].startsWith(`-`)){let i=e[0],o=t.fs.resolvePath(t.cwd,i);if(!await t.fs.exists(o))return{stdout:``,stderr:`node: cannot find module '${i}'\n`,exitCode:1};n=await t.fs.readFile(o),r=i,a=[`node`,i,...e.slice(1)]}else if(t.stdin.trim().length>0)n=t.stdin,r=`<stdin>`,a=[`node`];else if(e.length>0)return{stdout:``,stderr:`node: unsupported option '${e[0]}'\n`,exitCode:9};else return{stdout:``,stderr:`node: REPL mode is not supported in this environment; use node -e "code"
1296
1296
  `,exitCode:9};let o=[],s=[],c=e=>{o.push(typeof e==`string`?e:String(e))},l=e=>{s.push(typeof e==`string`?e:String(e))},u={log:(...e)=>c(`${e.map(Qh).join(` `)}\n`),info:(...e)=>c(`${e.map(Qh).join(` `)}\n`),warn:(...e)=>l(`${e.map(Qh).join(` `)}\n`),error:(...e)=>l(`${e.map(Qh).join(` `)}\n`)},d={argv:a,env:Object.fromEntries(t.env.entries()),cwd:()=>t.cwd,exit:e=>{throw new Bh(Number.isFinite(e)?Number(e):0)},stdout:{write:c},stderr:{write:l}},f={readFile:async e=>{let n=t.fs.resolvePath(t.cwd,e);return t.fs.readFile(n)},readFileBinary:async e=>{let n=t.fs.resolvePath(t.cwd,e);return t.fs.readFileBuffer(n)},writeFile:async(e,n)=>{let r=t.fs.resolvePath(t.cwd,e);await t.fs.writeFile(r,n)},writeFileBinary:async(e,n)=>{let r=t.fs.resolvePath(t.cwd,e),i=new Uint8Array(n.byteLength);i.set(n),await t.fs.writeFile(r,i)},readDir:async e=>{let n=t.fs.resolvePath(t.cwd,e);return t.fs.readdir(n)},exists:async e=>{let n=t.fs.resolvePath(t.cwd,e);return t.fs.exists(n)},fetchToFile:async(e,n)=>{if(typeof fetch>`u`)throw Error(`fetch is not available in this runtime`);let r=await fetch(e);if(!r.ok)throw Error(`fetch ${r.status} ${r.statusText}`);let i=new Uint8Array(await r.arrayBuffer()),a=t.fs.resolvePath(t.cwd,n);return await t.fs.writeFile(a,i),i.byteLength}},p=async e=>{if(!t.exec)throw Error(`exec is not available in this runtime`);let n=await t.exec(e,{cwd:t.cwd});return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}},m=typeof chrome<`u`&&!!chrome?.runtime?.id;if(!m){let e=ig(n),t=new Set([`fs`,`process`,`buffer`]),r=e.map(e=>e.startsWith(`node:`)?e.slice(5):e).filter(e=>!t.has(e)&&!rg.has(e)),a=zh.__requireCache??=Object.create(null),o=r.filter(e=>!(e in a));if(o.length>0){let e=await Promise.allSettled(o.map(async e=>{let t=await i(()=>import(`https://esm.sh/`+e),[]);a[e]=t&&typeof t==`object`&&`default`in t?t.default:t}));for(let t=0;t<e.length;t++)if(e[t].status===`rejected`){let n=e[t].reason;l(`Warning: failed to pre-load require('${o[t]}'): ${n instanceof Error?n.message:String(n)}\n`)}}}let h=e=>{let t=e.startsWith(`node:`)?e.slice(5):e;if(t===`fs`)return f;if(t===`process`)return d;if(t===`buffer`)return{Buffer:globalThis.Buffer};if(t===`path`){let t=zh.__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(rg.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=zh.__requireCache;if(n&&e in n)return n[e];throw Error(`require('${e}'): module not pre-loaded. Use a string literal or await import('https://esm.sh/${e}') directly.`)},g={exports:{},filename:r};try{if(m){let e=`
@@ -1408,7 +1408,7 @@ except BaseException:
1408
1408
  `,stderr:``,exitCode:0}}function ug(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 dg(){return Ve(`open`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return lg();if(typeof window>`u`||typeof document>`u`)return{stdout:``,stderr:`open: browser APIs are unavailable in this environment
1409
1409
  `,exitCode:1};let n=e.includes(`--download`)||e.includes(`-d`),r=e.includes(`--view`)||e.includes(`-v`),i=e.filter(e=>!cg.includes(e));if(i.length===0)return lg();let a=[];for(let e of i){if(Wh(e)){window.open(e,`_blank`,`noopener,noreferrer`),a.push(`opened ${e}`);continue}let i=t.fs.resolvePath(t.cwd,e);if(i.endsWith(`.shtml`)){let e=typeof window<`u`?window.__slicc_sprinkleManager:void 0;if(e){let t=(i.split(`/`).pop()??``).replace(/\.shtml$/,``);try{await e.open(t),a.push(`opened sprinkle ${t} from ${i}`)}catch(e){return{stdout:``,stderr:`open: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}else{let e=Yh(i);window.open(e,`_blank`,`noopener,noreferrer`),a.push(`opened ${i} → ${e}`)}continue}if(r){let n;try{n=await t.fs.stat(i)}catch{return{stdout:``,stderr:`open: no such file: ${e}\n`,exitCode:1}}if(!n.isFile)return{stdout:``,stderr:`open: not a file: ${e}\n`,exitCode:1};let r;try{r=await t.fs.readFileBuffer(i)}catch{return{stdout:``,stderr:`open: failed to read: ${e}\n`,exitCode:1}}let o=Jh(i),s=ug(new Uint8Array(r));a.push(`${i} (${Math.round(r.byteLength/1024)} KB)\n<img:data:${o};base64,${s}>`)}else if(n){let n;try{n=await t.fs.stat(i)}catch{return{stdout:``,stderr:`open: no such file: ${e}\n`,exitCode:1}}if(!n.isFile)return{stdout:``,stderr:`open: not a file: ${e}\n`,exitCode:1};let r;try{r=await t.fs.readFileBuffer(i)}catch{return{stdout:``,stderr:`open: failed to read: ${e}\n`,exitCode:1}}let o=new Uint8Array(r.byteLength);o.set(r);let s=new Blob([o.buffer],{type:Jh(i)}),c=URL.createObjectURL(s),l=document.createElement(`a`);l.href=c,l.download=Vh(i)||`download`,l.style.display=`none`,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(c),0),a.push(`downloaded ${i}`)}else{let e=Yh(i);window.open(e,`_blank`,`noopener,noreferrer`),a.push(`opened ${i} → ${e}`)}}return{stdout:a.join(`
1410
1410
  `)+`
1411
- `,stderr:``,exitCode:0}})}var fg=null,pg=null;async function mg(){return fg||=i(()=>import(`./es-B8PfOjm2.js`),__vite__mapDeps([7,4,5])),fg}async function hg(){return pg||=i(()=>import(`./dist-CLNuUmSq.js`),__vite__mapDeps([8,1])),pg}function gg(e){return e.endsWith(`right`)?{range:e.slice(0,-5),rotation:90}:e.endsWith(`left`)?{range:e.slice(0,-4),rotation:270}:e.endsWith(`down`)?{range:e.slice(0,-4),rotation:180}:{range:e}}function _g(e){let{range:t,rotation:n}=gg(e);if(/^\d+$/.test(t)){let e=parseInt(t,10);return{start:e,end:e,rotation:n}}let r=t.match(/^(\d+)-(\d+|end)$/);if(r)return{start:parseInt(r[1],10),end:r[2]===`end`?`end`:parseInt(r[2],10),rotation:n};throw Error(`Invalid page range: ${e}`)}function vg(e,t){let n=e.start,r=e.end;if(n<1||n>t)throw Error(`Page ${n} out of range (1-${t})`);let i=r===`end`?t:r;if(i<1||i>t)throw Error(`Page ${i} out of range (1-${t})`);if(i<n)throw Error(`Invalid range: ${n}-${i}`);let a=[];for(let e=n;e<=i;e++)a.push(e);return a}function yg(){return{stdout:`usage: pdftk <input.pdf> <operation> [args...]
1411
+ `,stderr:``,exitCode:0}})}var fg=null,pg=null;async function mg(){return fg||=i(()=>import(`./es-C70AgaBB.js`),__vite__mapDeps([7,4,5])),fg}async function hg(){return pg||=i(()=>import(`./dist-DEO1hNOZ2.js`),__vite__mapDeps([8,1])),pg}function gg(e){return e.endsWith(`right`)?{range:e.slice(0,-5),rotation:90}:e.endsWith(`left`)?{range:e.slice(0,-4),rotation:270}:e.endsWith(`down`)?{range:e.slice(0,-4),rotation:180}:{range:e}}function _g(e){let{range:t,rotation:n}=gg(e);if(/^\d+$/.test(t)){let e=parseInt(t,10);return{start:e,end:e,rotation:n}}let r=t.match(/^(\d+)-(\d+|end)$/);if(r)return{start:parseInt(r[1],10),end:r[2]===`end`?`end`:parseInt(r[2],10),rotation:n};throw Error(`Invalid page range: ${e}`)}function vg(e,t){let n=e.start,r=e.end;if(n<1||n>t)throw Error(`Page ${n} out of range (1-${t})`);let i=r===`end`?t:r;if(i<1||i>t)throw Error(`Page ${i} out of range (1-${t})`);if(i<n)throw Error(`Invalid range: ${n}-${i}`);let a=[];for(let e=n;e<=i;e++)a.push(e);return a}function yg(){return{stdout:`usage: pdftk <input.pdf> <operation> [args...]
1412
1412
 
1413
1413
  Operations:
1414
1414
  dump_data Print metadata (page count, title, author, etc.)
@@ -1519,10 +1519,10 @@ Examples:
1519
1519
  crontask create --name every-5min --scoop poller --cron "*/5 * * * *" --filter "() => ({ time: Date.now() })"
1520
1520
  crontask list
1521
1521
  crontask delete abc123
1522
- `,stderr:``,exitCode:0}}var Hg=typeof chrome<`u`&&!!chrome?.runtime?.id;function Ug(){return globalThis.__slicc_lickManager??null}var Wg=null;async function Gg(){if(Wg)return Wg;let{createLickManagerProxy:e}=await i(async()=>{let{createLickManagerProxy:e}=await import(`./lick-manager-proxy-B2bMdplq.js`);return{createLickManagerProxy:e}},[]);return Wg=e(),Wg}async function Kg(e,t,n){let r={method:e,headers:{"Content-Type":`application/json`}};n&&(r.body=JSON.stringify(n));let i=await fetch(`/api/crontasks${t}`,r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}function qg(){return Ve(`crontask`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Vg();let t=e[0];try{switch(t){case`create`:{let t,n,r,i,a=e.indexOf(`--name`);a!==-1&&e[a+1]&&(t=e[a+1]);let o=e.indexOf(`--cron`);o!==-1&&e[o+1]&&(n=e[o+1]);let s=e.indexOf(`--filter`);s!==-1&&e[s+1]&&(r=e[s+1]);let c=e.indexOf(`--scoop`);if(c!==-1&&e[c+1]&&(i=e[c+1]),!t)return{stdout:``,stderr:`crontask: --name is required
1522
+ `,stderr:``,exitCode:0}}var Hg=typeof chrome<`u`&&!!chrome?.runtime?.id;function Ug(){return globalThis.__slicc_lickManager??null}var Wg=null;async function Gg(){if(Wg)return Wg;let{createLickManagerProxy:e}=await i(async()=>{let{createLickManagerProxy:e}=await import(`./lick-manager-proxy-CogaR9kt.js`);return{createLickManagerProxy:e}},[]);return Wg=e(),Wg}async function Kg(e,t,n){let r={method:e,headers:{"Content-Type":`application/json`}};n&&(r.body=JSON.stringify(n));let i=await fetch(`/api/crontasks${t}`,r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}function qg(){return Ve(`crontask`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Vg();let t=e[0];try{switch(t){case`create`:{let t,n,r,i,a=e.indexOf(`--name`);a!==-1&&e[a+1]&&(t=e[a+1]);let o=e.indexOf(`--cron`);o!==-1&&e[o+1]&&(n=e[o+1]);let s=e.indexOf(`--filter`);s!==-1&&e[s+1]&&(r=e[s+1]);let c=e.indexOf(`--scoop`);if(c!==-1&&e[c+1]&&(i=e[c+1]),!t)return{stdout:``,stderr:`crontask: --name is required
1523
1523
  `,exitCode:1};if(!n)return{stdout:``,stderr:`crontask: --cron is required
1524
1524
  `,exitCode:1};if(Hg){if(r)return{stdout:``,stderr:`crontask: --filter is not supported in extension mode (CSP restriction)
1525
- `,exitCode:1};let e=Ug(),a=e?await e.createCronTask(t,n,i):await(await Gg()).createCronTask(t,n,i),o=`Created cron task "${a.name}"\n`;return o+=`ID: ${a.id}\n`,o+=`Cron: ${a.cron}\n`,a.scoop&&(o+=`Scoop: ${a.scoop}\n`),a.nextRun&&(o+=`Next run: ${new Date(a.nextRun).toLocaleString()}\n`),{stdout:o,stderr:``,exitCode:0}}let{ok:l,data:u}=await Kg(`POST`,``,{name:t,cron:n,filter:r,scoop:i});if(!l)return{stdout:``,stderr:`crontask: failed to create: ${u.error??`unknown error`}\n`,exitCode:1};let d=u,f=`Created cron task "${d.name}"\n`;return f+=`ID: ${d.id}\n`,f+=`Cron: ${d.cron}\n`,d.scoop&&(f+=`Scoop: ${d.scoop}\n`),d.filter&&(f+=`Filter: ${d.filter}\n`),d.nextRun&&(f+=`Next run: ${new Date(d.nextRun).toLocaleString()}\n`),{stdout:f,stderr:``,exitCode:0}}case`list`:{if(Hg){let e=Ug(),t=e?e.listCronTasks():await(async()=>{let{listCronTasksAsync:e}=await i(async()=>{let{listCronTasksAsync:e}=await import(`./lick-manager-proxy-B2bMdplq.js`);return{listCronTasksAsync:e}},[]);return e()})();if(t.length===0)return{stdout:`No active cron tasks
1525
+ `,exitCode:1};let e=Ug(),a=e?await e.createCronTask(t,n,i):await(await Gg()).createCronTask(t,n,i),o=`Created cron task "${a.name}"\n`;return o+=`ID: ${a.id}\n`,o+=`Cron: ${a.cron}\n`,a.scoop&&(o+=`Scoop: ${a.scoop}\n`),a.nextRun&&(o+=`Next run: ${new Date(a.nextRun).toLocaleString()}\n`),{stdout:o,stderr:``,exitCode:0}}let{ok:l,data:u}=await Kg(`POST`,``,{name:t,cron:n,filter:r,scoop:i});if(!l)return{stdout:``,stderr:`crontask: failed to create: ${u.error??`unknown error`}\n`,exitCode:1};let d=u,f=`Created cron task "${d.name}"\n`;return f+=`ID: ${d.id}\n`,f+=`Cron: ${d.cron}\n`,d.scoop&&(f+=`Scoop: ${d.scoop}\n`),d.filter&&(f+=`Filter: ${d.filter}\n`),d.nextRun&&(f+=`Next run: ${new Date(d.nextRun).toLocaleString()}\n`),{stdout:f,stderr:``,exitCode:0}}case`list`:{if(Hg){let e=Ug(),t=e?e.listCronTasks():await(async()=>{let{listCronTasksAsync:e}=await i(async()=>{let{listCronTasksAsync:e}=await import(`./lick-manager-proxy-CogaR9kt.js`);return{listCronTasksAsync:e}},[]);return e()})();if(t.length===0)return{stdout:`No active cron tasks
1526
1526
  `,stderr:``,exitCode:0};let n=`Active cron tasks:
1527
1527
  `;for(let e of t)n+=` ${e.id} ${e.name.padEnd(20)} ${e.cron.padEnd(15)}`,e.scoop&&(n+=` -> ${e.scoop}`),e.filter&&(n+=` [filtered]`),n+=` (${e.status})`,e.nextRun&&(n+=` next: ${new Date(e.nextRun).toLocaleString()}`),n+=`
1528
1528
  `;return{stdout:n,stderr:``,exitCode:0}}let{ok:e,data:t}=await Kg(`GET`,``);if(!e)return{stdout:``,stderr:`crontask: failed to list: ${t.error??`unknown error`}\n`,exitCode:1};let n=t;if(n.length===0)return{stdout:`No active cron tasks
@@ -1589,9 +1589,9 @@ on success.
1589
1589
  Examples:
1590
1590
  oauth-token adobe
1591
1591
  curl -H "Authorization: Bearer $(oauth-token adobe)" https://api.corp.com/data
1592
- `}function l_(){return Ve(`oauth-token`,async e=>{let{getOAuthAccountInfo:t,getSelectedProvider:n,getAccounts:r}=await i(async()=>{let{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}=await import(`./provider-settings-DUchoI6k.js`).then(e=>e.l);return{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}},__vite__mapDeps([9,4,1,10,11,12,13,14,15])),{getRegisteredProviderConfig:a,getRegisteredProviderIds:o}=await i(async()=>{let{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}=await import(`./provider-settings-DUchoI6k.js`).then(e=>e.h);return{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}},__vite__mapDeps([9,4,1,10,11,12,13,14,15]));if(e.includes(`--help`)||e.includes(`-h`))return{stdout:c_(),stderr:``,exitCode:0};if(e.includes(`--list`))return u_(r,o,a,t);let s,c=e.indexOf(`--provider`);if(c>=0){if(s=e[c+1],!s)return{stdout:``,stderr:`oauth-token: --provider requires a value
1592
+ `}function l_(){return Ve(`oauth-token`,async e=>{let{getOAuthAccountInfo:t,getSelectedProvider:n,getAccounts:r}=await i(async()=>{let{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}=await import(`./provider-settings-BNHO2Tcv.js`).then(e=>e.l);return{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}},__vite__mapDeps([9,4,1,10,11,12,13,14,15])),{getRegisteredProviderConfig:a,getRegisteredProviderIds:o}=await i(async()=>{let{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}=await import(`./provider-settings-BNHO2Tcv.js`).then(e=>e.h);return{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}},__vite__mapDeps([9,4,1,10,11,12,13,14,15]));if(e.includes(`--help`)||e.includes(`-h`))return{stdout:c_(),stderr:``,exitCode:0};if(e.includes(`--list`))return u_(r,o,a,t);let s,c=e.indexOf(`--provider`);if(c>=0){if(s=e[c+1],!s)return{stdout:``,stderr:`oauth-token: --provider requires a value
1593
1593
  `,exitCode:1}}else if(e.length>0)s=e[0];else{let e=n(),t=a(e);if(t?.isOAuth&&t.onOAuthLogin)s=e;else if(s=o().find(e=>{let t=a(e);return t?.isOAuth&&t.onOAuthLogin}),!s)return{stdout:``,stderr:`oauth-token: no OAuth providers configured
1594
- `,exitCode:1}}let l=a(s);if(!l)return{stdout:``,stderr:`oauth-token: unknown provider "${s}"\n`,exitCode:1};if(!l.isOAuth||!l.onOAuthLogin)return{stdout:``,stderr:`oauth-token: provider "${s}" is not an OAuth provider\n`,exitCode:1};let u=t(s);if(u&&!u.expired)return{stdout:`${u.token}\n`,stderr:``,exitCode:0};try{let{createOAuthLauncher:e}=await i(async()=>{let{createOAuthLauncher:e}=await import(`./oauth-service-BoyG8vZW.js`);return{createOAuthLauncher:e}},[]),n=e();await l.onOAuthLogin(n,()=>{});let r=t(s);return r&&r.token?{stdout:`${r.token}\n`,stderr:``,exitCode:0}:(console.error(`[oauth-token] Provider ${s}: login completed but no token was saved`),{stdout:``,stderr:`oauth-token: login completed but no token was saved
1594
+ `,exitCode:1}}let l=a(s);if(!l)return{stdout:``,stderr:`oauth-token: unknown provider "${s}"\n`,exitCode:1};if(!l.isOAuth||!l.onOAuthLogin)return{stdout:``,stderr:`oauth-token: provider "${s}" is not an OAuth provider\n`,exitCode:1};let u=t(s);if(u&&!u.expired)return{stdout:`${u.token}\n`,stderr:``,exitCode:0};try{let{createOAuthLauncher:e}=await i(async()=>{let{createOAuthLauncher:e}=await import(`./oauth-service-CfTUWB9P.js`);return{createOAuthLauncher:e}},[]),n=e();await l.onOAuthLogin(n,()=>{});let r=t(s);return r&&r.token?{stdout:`${r.token}\n`,stderr:``,exitCode:0}:(console.error(`[oauth-token] Provider ${s}: login completed but no token was saved`),{stdout:``,stderr:`oauth-token: login completed but no token was saved
1595
1595
  `,exitCode:1})}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${s}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}function u_(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
1596
1596
  `,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(`
1597
1597
  `)+`
@@ -1624,7 +1624,7 @@ Examples:
1624
1624
  `,n+=` Remove the ${t}= and ${t}_DOMAINS= lines from ~/.slicc/secrets.env\n\n`,n+=`Then restart the server to pick up changes.
1625
1625
  `,{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>
1626
1626
  `,exitCode:1};let r;try{r=new URL(n).hostname}catch{return{stdout:``,stderr:`secret: invalid URL "${n}"\n`,exitCode:1}}let{ok:a,data:o}=await f_(`GET`,``);if(!a)return{stdout:``,stderr:`secret: failed to fetch secrets
1627
- `,exitCode:1};let s=o.find(e=>e.name===t);if(!s)return{stdout:``,stderr:`secret: no secret named "${t}"\n`,exitCode:1};let{isAllowedDomain:c}=await i(async()=>{let{isAllowedDomain:e}=await import(`./secret-masking-Bqg5RXZg.js`);return{isAllowedDomain:e}},[]);return c(s.domains,r)?{stdout:`✓ ${t} is allowed for ${r}\n`,stderr:``,exitCode:0}:{stdout:`✗ ${t} is NOT allowed for ${r}\n Allowed domains: ${s.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 h_(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 g_=null;function __(e){g_=e}function v_(){return g_?.()??null}function y_(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=b_(r),o=b_(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 b_(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 x_(){return{stdout:`rsync — sync files between local VFS and a remote tray runtime
1627
+ `,exitCode:1};let s=o.find(e=>e.name===t);if(!s)return{stdout:``,stderr:`secret: no secret named "${t}"\n`,exitCode:1};let{isAllowedDomain:c}=await i(async()=>{let{isAllowedDomain:e}=await import(`./secret-masking-Bg1u5YcF.js`);return{isAllowedDomain:e}},[]);return c(s.domains,r)?{stdout:`✓ ${t} is allowed for ${r}\n`,stderr:``,exitCode:0}:{stdout:`✗ ${t} is NOT allowed for ${r}\n Allowed domains: ${s.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 h_(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 g_=null;function __(e){g_=e}function v_(){return g_?.()??null}function y_(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=b_(r),o=b_(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 b_(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 x_(){return{stdout:`rsync — sync files between local VFS and a remote tray runtime
1628
1628
 
1629
1629
  Usage:
1630
1630
  rsync [flags] <local-path> <runtime-id>:<remote-path> # push
@@ -1749,7 +1749,7 @@ Options:
1749
1749
  -h, --help Show this help message
1750
1750
  `}function yv(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function bv(e){return`$${e.toFixed(2)}`}var xv=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function Sv(e){let t=`${e.id} ${e.name??``}`;return!xv.test(t)}function Cv(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 wv(e){let t=new Map;for(let n of e){let e=Cv(n.id);t.has(e)||t.set(e,n)}return[...t.values()]}function Tv(e,t,n,r,i){let a=i?_v(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 Ev(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=`${bv(e.cost.input)} / ${bv(e.cost.output)}`,a=`${yv(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(`
1751
1751
  `)+`
1752
- `}function Dv(e){return Ve(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:a,getProviderModels:o,getSelectedProvider:s,getSelectedModelId:c}=await i(async()=>{let{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}=await import(`./provider-settings-DUchoI6k.js`).then(e=>e.l);return{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}},__vite__mapDeps([9,4,1,10,11,12,13,14,15]));if(t.includes(`--help`)||t.includes(`-h`))return{stdout:vv(),stderr:``,exitCode:0};let l=t.includes(`--json`),u=t.includes(`--all`),d=t.includes(`--all-versions`),f=t.includes(`--refresh`),p=t.includes(`--no-benchmarks`),m=t.indexOf(`--provider`),h=m>=0?t[m+1]:void 0,g=s(),_=c(),v=n();if(v.length===0)return{stdout:``,stderr:`No provider accounts configured. Run the provider settings to add one.
1752
+ `}function Dv(e){return Ve(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:a,getProviderModels:o,getSelectedProvider:s,getSelectedModelId:c}=await i(async()=>{let{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}=await import(`./provider-settings-BNHO2Tcv.js`).then(e=>e.l);return{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}},__vite__mapDeps([9,4,1,10,11,12,13,14,15]));if(t.includes(`--help`)||t.includes(`-h`))return{stdout:vv(),stderr:``,exitCode:0};let l=t.includes(`--json`),u=t.includes(`--all`),d=t.includes(`--all-versions`),f=t.includes(`--refresh`),p=t.includes(`--no-benchmarks`),m=t.indexOf(`--provider`),h=m>=0?t[m+1]:void 0,g=s(),_=c(),v=n();if(v.length===0)return{stdout:``,stderr:`No provider accounts configured. Run the provider settings to add one.
1753
1753
  `,exitCode:1};let y;p||(y=await hv(e,f),y.length===0&&(y=void 0));let b;if(h){let e=r();if(!e.includes(h))return{stdout:``,stderr:`Unknown provider: ${h}. Available: ${e.join(`, `)}\n`,exitCode:1};b=[h]}else b=u?[...new Set(v.map(e=>e.providerId))]:[g];let x=[],S=[];for(let e of b){let t=o(e).filter(Sv);if(t.length===0){if(!u)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>Tv(t,e,_,g,y)).sort((e,t)=>t.cost.input-e.cost.input);if(d||(n=wv(n)),x.push(...n),!l){let t=a(e);S.push(Ev(t.name,e,n,!!y))}}return l?{stdout:JSON.stringify(x,null,2)+`
1754
1754
  `,stderr:``,exitCode:0}:(!d&&!l&&S.push(`Showing latest versions only. Use --all-versions to see all.
1755
1755
  `),{stdout:S.join(`
@@ -2014,7 +2014,7 @@ Usage: mount <target-path>
2014
2014
  return { stdout: __stdout.join(''), stderr: __stderr.join('') };
2015
2015
  `,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 d(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 c=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`,c);let u=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+`
2016
2016
  `});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`,c),{stdout:u.stdout,stderr:u.stderr,exitCode:+!!u.stderr}}let i=Object.getPrototypeOf(async function(){}).constructor;return await new i(`fs`,`process`,`console`,`require`,`module`,`exports`,`__state`,`exec`,`"use strict";\nconst globalThis = __state;\nconst global = __state;\n${e}`)(u,l,c,p,m,m.exports,zh,d),{stdout:r.join(``),stderr:a.join(``),exitCode:0}}catch(e){if(e instanceof Bh)return{stdout:r.join(``),stderr:a.join(``),exitCode:e.code};let t=e instanceof Error?e.stack??e.message:String(e);return{stdout:r.join(``),stderr:`${a.join(``)}${t}\n`,exitCode:1}}}function Gy(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 Ky=[`/workspace`,`/shared`];async function qy(e){let t=[],n=new Set;for(let r of Ky)await e.exists(r)&&await Jy(e,r,t,n);return t}async function Jy(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=Yy(i);if(!t)continue;let a=await e.readFile(i,{encoding:`utf-8`}),o=Xy(typeof a==`string`?a:new TextDecoder().decode(a));n.push({path:i,hostnamePattern:t,matchPatterns:o})}}function Yy(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 Xy(e){let t=e.split(`
2017
- `).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 Zy(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 Qy(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||!Zy(n.hostname,a)?!1:o?$y(n.pathname+n.search,o):!0}catch{return!1}}function $y(e,t){let n=`^`+t.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`)+`$`;return new RegExp(n).test(e)}function eb(e,t){try{let n=new URL(t);return e.filter(e=>Zy(n.hostname,e.hostnamePattern)?e.matchPatterns.length>0?e.matchPatterns.some(e=>Qy(t,e)):!0:!1)}catch{return[]}}var tb=[`/workspace`,`/shared`];function nb(e){return new Map(e)}function rb(e){return e.map(e=>({...e,matchPatterns:[...e.matchPatterns]}))}function ib(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 ab(e){return(ib(e)?.listMounts?.().length??0)>0}function ob(e){return e?(ib(e)?.listMounts?.()??[]).some(e=>tb.some(t=>e===t||e.startsWith(t+`/`))):!1}var sb=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 tb)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 nb(await this.loadJshCommands())}async getJshCommandNames(){return[...(await this.getJshCommands()).keys()]}async getBshEntries(){return this.bshFs?rb(await this.loadBshEntries()):[]}async findMatchingBshScripts(e){return this.bshFs?rb(eb(await this.loadBshEntries(),e)):[]}shouldCacheJsh(){return!!this.watcher&&!ab(this.jshFs)}shouldCacheBsh(){return!!this.watcher&&!!this.bshFs&&!ob(this.bshFs)}async loadJshCommands(){let e=this.shouldCacheJsh();if(e&&this.jshCache)return this.jshCache;if(!this.jshInflight){let t=this.jshGeneration,n=N_(this.jshFs).then(n=>{let r=nb(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=qy(this.bshFs).then(n=>{let r=rb(n);return e&&this.bshGeneration===t&&(this.bshCache=r),r}).finally(()=>{this.bshInflight===n&&(this.bshInflight=null)});this.bshInflight=n}return this.bshInflight}},cb=null,lb=!1;function ub(){return typeof chrome<`u`&&chrome?.runtime?.id?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function db(){if(!lb&&!(typeof localStorage<`u`&&localStorage.getItem(`telemetry-disabled`)===`true`))try{typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),cb=(await i(()=>import(`./src-CNgmwAf5.js`),[])).sampleRUM,lb=!0,cb&&cb(`navigate`,{source:typeof document<`u`?document.referrer:``,target:ub()})}catch{}}function fb(e,t){cb?.(`formsubmit`,{source:e,target:t})}function pb(e){cb?.(`fill`,{source:e})}function mb(e){cb?.(`viewblock`,{source:e})}function hb(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 gb(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?gb(e.getUnderlyingFS?.()):null}function _b(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 vb(e,t){let n=e.headers.get(`content-type`)??``,r=await e.arrayBuffer(),i=new Uint8Array(r);if(!_b(n)){let e=``;for(let t=0;t<i.length;t+=32768)e+=String.fromCharCode(...i.subarray(t,t+32768));xo(e,i),t&&So(t,i)}return i}function yb(e){if(e){if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}}function bb(e,t){if(e){if((t?.[`Content-Type`]??t?.[`content-type`]??``).includes(`multipart/form-data`)){let t=ko(e);return new Blob([t])}return e}}function xb(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 Sb(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 Cb(){return typeof chrome<`u`&&chrome?.runtime?.id?async(e,t)=>{let n=yb(t?.headers),r=await fetch(e,{method:t?.method??`GET`,headers:n,body:bb(t?.body,n)}),i=await vb(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={...xb(yb(t?.headers)),"X-Target-URL":e},i={method:n,headers:r,cache:`no-store`};t?.body&&![`GET`,`HEAD`].includes(n)&&(i.body=bb(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 vb(a,e),s={};a.headers.forEach((e,t)=>{s[t]=e});let c=Sb(s);return{status:a.status,statusText:a.statusText,headers:c,body:o,url:e}}}var wb=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;allowedCommands;scriptCatalog;ownsScriptCatalog;registeredJshCommands=new Map;jshSyncInflight=null;jshSyncDirty=!1;constructor(e){this.options=e,this.vfsAdapter=new To(e.fs),this.allowedCommands=e.allowedCommands&&!e.allowedCommands.includes(`*`)?new Set(e.allowedCommands):null;let t=e.cwd??`/`,n={HOME:`/`,PATH:`/usr/bin`,USER:`user`,SHELL:`/bin/bash`,PWD:t,...e.env};this.gitCommands=new tm({fs:e.fs,authorName:n.GIT_AUTHOR_NAME??`User`,authorEmail:n.GIT_AUTHOR_EMAIL??`user@example.com`}),this.mountCommands=new By({fs:e.fs});let r=e.jshDiscoveryFs??e.fs,i=e.bshDiscoveryFs??e.fs,a=gb(r)??gb(i);this.scriptCatalog=e.scriptCatalog??new sb({jshFs:r,bshFs:i,watcher:a}),this.ownsScriptCatalog=!e.scriptCatalog,a&&a.watch(`/`,e=>e.endsWith(`.jsh`),()=>{this.syncJshCommands().catch(()=>void 0)});let o=this.createGitCustomCommand(),s=zv({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),fs:e.fs,scriptCatalog:this.scriptCatalog,browserAPI:e.browserAPI,getParentJid:e.getParentJid}),c=this.createMountCustomCommand(),l=Cb(),u=[o,c,Ry(e.fs),Ly(e.fs,l),...s].filter(e=>this.isCommandAllowed(e.name)),d=[...ze(),...Re()],f=this.allowedCommands?d.filter(e=>this.isCommandAllowed(e)):void 0;if(this.bash=new Ue({fs:this.vfsAdapter,cwd:t,env:n,fetch:l,commands:f,customCommands:u}),this.allowedCommands!==null){let e=this.bash;for(let t of Re())this.isCommandAllowed(t)||e.commands.delete(t)}let p=u.map(e=>e.name),m=f??[...ze(),...Re()];this.builtinCommandNames=new Set([...m,...p]),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...n},this.cwd=t,this.syncJshCommands().catch(()=>void 0)}isCommandAllowed(e){return this.allowedCommands===null||this.allowedCommands.has(e)}async syncJshCommands(){return this.jshSyncInflight?(this.jshSyncDirty=!0,this.jshSyncInflight):(this.jshSyncInflight=this.doSyncJshCommands(),this.jshSyncInflight)}async doSyncJshCommands(){try{let e=await this.scriptCatalog.getJshCommands(),t=this.options.jshDiscoveryFs??this.options.fs;for(let[n,r]of e){if(!this.isCommandAllowed(n)||this.builtinCommandNames.has(n)&&!this.registeredJshCommands.has(n)||this.registeredJshCommands.get(n)===r)continue;let e=this.scriptCatalog,i=this,a=n,o={name:n,async execute(n,r){let o=(await e.getJshCommands()).get(a);if(!o)return{stdout:``,stderr:`jsh: command '${a}' no longer exists\n`,exitCode:127};let s;try{let e=await t.readFile(o,{encoding:`utf-8`});s=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${o}'\n`,exitCode:127}}let c=[`node`,o,...n],l=r.exec??((e,t)=>i.bash.exec(e,{env:Object.fromEntries(r.env),cwd:t?.cwd??r.cwd}));return Wy(s,c,{fs:r.fs,cwd:r.cwd,env:r.env,stdin:r.stdin,exec:l})}};this.bash.registerCommand(o),this.registeredJshCommands.set(n,r),this.builtinCommandNames.add(n)}}finally{this.jshSyncInflight=null,this.jshSyncDirty&&(this.jshSyncDirty=!1,this.syncJshCommands().catch(()=>void 0))}}createGitCustomCommand(){let e=this.gitCommands;return Ve(`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 Ve(`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)||this.isCommandAllowed(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?Gy(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 Wy(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){pb(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 this.syncJshCommands().catch(()=>void 0),t}return r}async mount(e){let t=e??this.options.container;if(!t)throw Error(`No container element provided`);let{Terminal:n}=await i(async()=>{let{Terminal:e}=await import(`./xterm-ucbPh68r.js`);return{Terminal:e}},[]),{FitAddon:r}=await i(async()=>{let{FitAddon:e}=await import(`./addon-fit-CVV7fTw9.js`);return{FitAddon:e}},[]);await i(()=>Promise.resolve({}),__vite__mapDeps([20]));let a=!document.documentElement.classList.contains(`theme-light`),o={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`},s={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:a?o:s,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?s:o}),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
2017
+ `).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 Zy(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 Qy(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||!Zy(n.hostname,a)?!1:o?$y(n.pathname+n.search,o):!0}catch{return!1}}function $y(e,t){let n=`^`+t.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`)+`$`;return new RegExp(n).test(e)}function eb(e,t){try{let n=new URL(t);return e.filter(e=>Zy(n.hostname,e.hostnamePattern)?e.matchPatterns.length>0?e.matchPatterns.some(e=>Qy(t,e)):!0:!1)}catch{return[]}}var tb=[`/workspace`,`/shared`];function nb(e){return new Map(e)}function rb(e){return e.map(e=>({...e,matchPatterns:[...e.matchPatterns]}))}function ib(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 ab(e){return(ib(e)?.listMounts?.().length??0)>0}function ob(e){return e?(ib(e)?.listMounts?.()??[]).some(e=>tb.some(t=>e===t||e.startsWith(t+`/`))):!1}var sb=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 tb)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 nb(await this.loadJshCommands())}async getJshCommandNames(){return[...(await this.getJshCommands()).keys()]}async getBshEntries(){return this.bshFs?rb(await this.loadBshEntries()):[]}async findMatchingBshScripts(e){return this.bshFs?rb(eb(await this.loadBshEntries(),e)):[]}shouldCacheJsh(){return!!this.watcher&&!ab(this.jshFs)}shouldCacheBsh(){return!!this.watcher&&!!this.bshFs&&!ob(this.bshFs)}async loadJshCommands(){let e=this.shouldCacheJsh();if(e&&this.jshCache)return this.jshCache;if(!this.jshInflight){let t=this.jshGeneration,n=N_(this.jshFs).then(n=>{let r=nb(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=qy(this.bshFs).then(n=>{let r=rb(n);return e&&this.bshGeneration===t&&(this.bshCache=r),r}).finally(()=>{this.bshInflight===n&&(this.bshInflight=null)});this.bshInflight=n}return this.bshInflight}},cb=null,lb=!1;function ub(){return typeof chrome<`u`&&chrome?.runtime?.id?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function db(){if(!lb&&!(typeof localStorage<`u`&&localStorage.getItem(`telemetry-disabled`)===`true`))try{typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),cb=(await i(()=>import(`./src-CNgmwAf5.js`),[])).sampleRUM,lb=!0,cb&&cb(`navigate`,{source:typeof document<`u`?document.referrer:``,target:ub()})}catch{}}function fb(e,t){cb?.(`formsubmit`,{source:e,target:t})}function pb(e){cb?.(`fill`,{source:e})}function mb(e){cb?.(`viewblock`,{source:e})}function hb(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 gb(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?gb(e.getUnderlyingFS?.()):null}function _b(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 vb(e,t){let n=e.headers.get(`content-type`)??``,r=await e.arrayBuffer(),i=new Uint8Array(r);if(!_b(n)){let e=``;for(let t=0;t<i.length;t+=32768)e+=String.fromCharCode(...i.subarray(t,t+32768));xo(e,i),t&&So(t,i)}return i}function yb(e){if(e){if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}}function bb(e,t){if(e){if((t?.[`Content-Type`]??t?.[`content-type`]??``).includes(`multipart/form-data`)){let t=ko(e);return new Blob([t])}return e}}function xb(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 Sb(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 Cb(){return typeof chrome<`u`&&chrome?.runtime?.id?async(e,t)=>{let n=yb(t?.headers),r=await fetch(e,{method:t?.method??`GET`,headers:n,body:bb(t?.body,n)}),i=await vb(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={...xb(yb(t?.headers)),"X-Target-URL":e},i={method:n,headers:r,cache:`no-store`};t?.body&&![`GET`,`HEAD`].includes(n)&&(i.body=bb(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 vb(a,e),s={};a.headers.forEach((e,t)=>{s[t]=e});let c=Sb(s);return{status:a.status,statusText:a.statusText,headers:c,body:o,url:e}}}var wb=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;allowedCommands;scriptCatalog;ownsScriptCatalog;registeredJshCommands=new Map;jshSyncInflight=null;jshSyncDirty=!1;constructor(e){this.options=e,this.vfsAdapter=new To(e.fs),this.allowedCommands=e.allowedCommands&&!e.allowedCommands.includes(`*`)?new Set(e.allowedCommands):null;let t=e.cwd??`/`,n={HOME:`/`,PATH:`/usr/bin`,USER:`user`,SHELL:`/bin/bash`,PWD:t,...e.env};this.gitCommands=new tm({fs:e.fs,authorName:n.GIT_AUTHOR_NAME??`User`,authorEmail:n.GIT_AUTHOR_EMAIL??`user@example.com`}),this.mountCommands=new By({fs:e.fs});let r=e.jshDiscoveryFs??e.fs,i=e.bshDiscoveryFs??e.fs,a=gb(r)??gb(i);this.scriptCatalog=e.scriptCatalog??new sb({jshFs:r,bshFs:i,watcher:a}),this.ownsScriptCatalog=!e.scriptCatalog,a&&a.watch(`/`,e=>e.endsWith(`.jsh`),()=>{this.syncJshCommands().catch(()=>void 0)});let o=this.createGitCustomCommand(),s=zv({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),fs:e.fs,scriptCatalog:this.scriptCatalog,browserAPI:e.browserAPI,getParentJid:e.getParentJid}),c=this.createMountCustomCommand(),l=Cb(),u=[o,c,Ry(e.fs),Ly(e.fs,l),...s].filter(e=>this.isCommandAllowed(e.name)),d=[...ze(),...Re()],f=this.allowedCommands?d.filter(e=>this.isCommandAllowed(e)):void 0;if(this.bash=new Ue({fs:this.vfsAdapter,cwd:t,env:n,fetch:l,commands:f,customCommands:u}),this.allowedCommands!==null){let e=this.bash;for(let t of Re())this.isCommandAllowed(t)||e.commands.delete(t)}let p=u.map(e=>e.name),m=f??[...ze(),...Re()];this.builtinCommandNames=new Set([...m,...p]),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...n},this.cwd=t,this.syncJshCommands().catch(()=>void 0)}isCommandAllowed(e){return this.allowedCommands===null||this.allowedCommands.has(e)}async syncJshCommands(){return this.jshSyncInflight?(this.jshSyncDirty=!0,this.jshSyncInflight):(this.jshSyncInflight=this.doSyncJshCommands(),this.jshSyncInflight)}async doSyncJshCommands(){try{let e=await this.scriptCatalog.getJshCommands(),t=this.options.jshDiscoveryFs??this.options.fs;for(let[n,r]of e){if(!this.isCommandAllowed(n)||this.builtinCommandNames.has(n)&&!this.registeredJshCommands.has(n)||this.registeredJshCommands.get(n)===r)continue;let e=this.scriptCatalog,i=this,a=n,o={name:n,async execute(n,r){let o=(await e.getJshCommands()).get(a);if(!o)return{stdout:``,stderr:`jsh: command '${a}' no longer exists\n`,exitCode:127};let s;try{let e=await t.readFile(o,{encoding:`utf-8`});s=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${o}'\n`,exitCode:127}}let c=[`node`,o,...n],l=r.exec??((e,t)=>i.bash.exec(e,{env:Object.fromEntries(r.env),cwd:t?.cwd??r.cwd}));return Wy(s,c,{fs:r.fs,cwd:r.cwd,env:r.env,stdin:r.stdin,exec:l})}};this.bash.registerCommand(o),this.registeredJshCommands.set(n,r),this.builtinCommandNames.add(n)}}finally{this.jshSyncInflight=null,this.jshSyncDirty&&(this.jshSyncDirty=!1,this.syncJshCommands().catch(()=>void 0))}}createGitCustomCommand(){let e=this.gitCommands;return Ve(`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 Ve(`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)||this.isCommandAllowed(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?Gy(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 Wy(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){pb(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 this.syncJshCommands().catch(()=>void 0),t}return r}async mount(e){let t=e??this.options.container;if(!t)throw Error(`No container element provided`);let{Terminal:n}=await i(async()=>{let{Terminal:e}=await import(`./xterm-CAZt1iF4.js`);return{Terminal:e}},[]),{FitAddon:r}=await i(async()=>{let{FitAddon:e}=await import(`./addon-fit-CnTv21Qe.js`);return{FitAddon:e}},[]);await i(()=>Promise.resolve({}),__vite__mapDeps([20]));let a=!document.documentElement.classList.contains(`theme-light`),o={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`},s={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:a?o:s,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?s:o}),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
2018
2018
  `),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 Uy(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
2019
2019
  `,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(`
2020
2020
  `).entries()){if(e+n.length>=this.cursorPos)return t;e+=n.length+1}return 0}positionTerminalCursor(){let e=this.currentLine.split(`
@@ -13301,7 +13301,7 @@ ${t}
13301
13301
  `);return Error(`Cannot remove scoop '${e}': it has ${r.join(` and `)}. Unregister them first:\n${i}`)}var Px=null;function Fx(){return Px||=new Mx,Px}var Q=r(`orchestrator`),Ix=120*1e3,Lx=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=[];scoopObservers=new Map;constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n}async init(){await we(),this.sharedFs=await I.create({dbName:`slicc-fs`}),this.sessionStore=new M,this.fsWatcher=new ce,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure();let e=await xe();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.migrateScoopConfig(t),this.scoops.set(t.jid,t),this.messageQueues.set(t.jid,[]);let e=await Ae(`lastAgentTs_${t.jid}`);e&&this.lastAgentTimestamp.set(t.jid,e)}await this.ensureGlobalMemory(),this.scheduler=new kx({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);He(()=>this.getSessionCosts()),this.startMessageLoop()}migrateScoopConfig(e){if(e.isCone)return;let t=e.configSchemaVersion??0;t>=2||(t<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),t<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),e.configSchemaVersion=2)}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 yx(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}getSessionStore(){return this.sessionStore}setLickManager(e){this.lickManager=e,globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}observeScoop(e,t){let n=this.scoopObservers.get(e);return n||(n=new Set,this.scoopObservers.set(e,n)),n.add(t),()=>{let n=this.scoopObservers.get(e);n&&(n.delete(t),n.size===0&&this.scoopObservers.delete(e))}}maybeNotifyConeOnScoopComplete(e){let t=this.scoops.get(e);if(!t||t.isCone)return;let n=this.scoopResponseBuffer.get(e);if(this.scoopResponseBuffer.delete(e),!n||t.notifyOnComplete===!1)return;let r=Array.from(this.scoops.values()).find(e=>e.isCone);if(!r)return;let i=n.length>2e4?n.slice(0,2e4)+`
13302
13302
  ... (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}`)})}dispatchScoopEvent(e,t,...n){let r=this.scoopObservers.get(e);if(r)for(let i of r){let r=i[t];if(r)try{r(...n)}catch(n){Q.warn(`scoop observer threw`,{jid:e,event:t,error:n instanceof Error?n.message:String(n)})}}}async registerScoop(e){await Fe(e),this.scoops.set(e.jid,e),this.messageQueues.set(e.jid,[]),Q.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createScoopTab(e.jid)}catch(t){throw Q.error(`Scoop init failed`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)}),await this.destroyScoopTab(e.jid).catch(()=>{}),this.scoops.delete(e.jid),this.messageQueues.delete(e.jid),await Te(e.jid).catch(t=>{Q.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),t}}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=Nx(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 Te(e),this.scoops.delete(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.scoopResponseBuffer.delete(e),this.scoopObservers.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 vx(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 Ne(),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);fb(t?.isCone?`cone`:t?.name??`unknown`,localStorage.getItem(`selected-model`)??`unknown`),await ve(e),await this.routeToScoop(e)}async delegateToScoop(e,t,n){let r=this.scoops.get(e);if(!r)throw Error(`Scoop not found: ${e}`);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`delegation`};await ve(i),this.callbacks.onIncomingMessage?.(e,i),Q.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Delegation failed`,{scoopJid:e,error:n}),this.callbacks.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.scoops.get(e.chatJid);if(!t){Q.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}let n=e.channel===`webhook`||e.channel===`cron`||e.channel===`fswatch`||e.channel===`sprinkle`;if(!t.isCone&&t.requiresTrigger&&t.trigger&&!n&&!e.content.includes(t.trigger)){Q.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let r=this.messageQueues.get(e.chatJid)??[];r.push(e),this.messageQueues.set(e.chatJid,r);let i=this.tabs.get(e.chatJid);if(Q.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:i?.status??`no-tab`,queueLength:r.length}),i?.status===`error`){Q.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.createScoopTab(e.chatJid),i=this.tabs.get(e.chatJid)}catch{Q.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}i?.status===`ready`&&await this.processScoopQueue(e.chatJid)}async createScoopTab(e){let t=this.scoops.get(e);if(!t)throw Error(`Scoop not found: ${e}`);if(this.contexts.has(e))if(this.tabs.get(e)?.status===`error`)Q.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{Q.debug(`Context already exists`,{jid:e});return}if(!this.sharedFs)throw Error(`Shared filesystem not initialized`);let n=`scoop-${t.folder}-${Date.now()}`,r=t.isCone?this.sharedFs:new ue(this.sharedFs,t.config?.writablePaths?[...t.config.writablePaths]:[],t.config?.visiblePaths?[...t.config.visiblePaths]:[]),i=new Dx(t,{onResponse:(n,r)=>{if(this.scoops.has(e)&&(this.callbacks.onResponse(e,n,r),this.dispatchScoopEvent(e,`onResponse`,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`),this.dispatchScoopEvent(e,`onError`,t),this.dispatchScoopEvent(e,`onStatusChange`,`error`)},onStatusChange:n=>{if(!this.scoops.has(e))return;let r=this.tabs.get(e);r&&(r.status=n,r.lastActivity=new Date().toISOString(),this.tabs.set(e,r)),this.callbacks.onStatusChange(e,n),this.dispatchScoopEvent(e,`onStatusChange`,n),n===`ready`&&!t.isCone&&this.maybeNotifyConeOnScoopComplete(e)},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)=>{let r=`${n?`[${n}] `:``}${t}`;this.callbacks.onSendMessage(e,r),this.dispatchScoopEvent(e,`onSendMessage`,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`),this.dispatchScoopEvent(e,`onStatusChange`,`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),this.scoopObservers.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 je(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 je(t)}async getMessagesForScoop(e){return G(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`),this.dispatchScoopEvent(e,`onStatusChange`,`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 Se(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(`
13303
13303
  `);this.messageQueues.set(e,[]);let c=o[o.length-1];this.lastAgentTimestamp.set(e,c.timestamp),await Ie(`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);let s=n.map(e=>e.timestamp).sort((e,t)=>e-t),c=s[0],l=s[s.length-1],u=900*1e3,d=l-c,f=Math.max(1,Math.ceil(d/u))*u;return{name:e.assistantLabel,type:e.isCone?`cone`:`scoop`,model:a,usage:r,turns:n.length,firstActivity:c,lastActivity:l,activeTimeMs:f}}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})})},Ix);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`)}};r(`heartbeat`);var Rx=r(`tray-follower`);function zx(e){let t=new URL(e);return t.searchParams.set(`json`,`true`),t.toString()}async function Bx(e){let t=zx(e.joinUrl),n=await qx(await(e.fetchImpl??fetch)(t,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:e.controllerId,runtime:e.runtime})}));return Rx.info(`Follower tray attach response`,{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),Vx(n)}function Vx(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 Hx(e){return Kx(await Jx(e,{action:`poll`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function Ux(e){return Kx(await Jx(e,{action:`answer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function Wx(e){return Kx(await Jx(e,{action:`ice-candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function Gx(e){return Kx(await Jx(e,{action:`retry`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function Kx(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function qx(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!Yx(n)){let n=t?t.slice(0,200):`(empty)`;throw Rx.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 Jx(e,t){let n=zx(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(!Xx(i))throw Error(`Tray follower bootstrap returned an invalid response (${r.status})`);return i}function Yx(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`&&Zx(r.bootstrap):r.action===`fail`?(r.code===`INVALID_JOIN_CAPABILITY`||r.code===`TRAY_EXPIRED`)&&typeof r.error==`string`:!1}function Xx(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`&&Zx(t.bootstrap)&&Array.isArray(t.events)}function Zx(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 Qx=t({AGENT_BRIDGE_GLOBAL_KEY:()=>eS,AGENT_SPAWN_REQUEST_TYPE:()=>tS,createAgentBridge:()=>nS,publishAgentBridge:()=>rS,publishAgentBridgeProxy:()=>iS}),$x=r(`agent-bridge`),eS=`__slicc_agent`,tS=`agent-spawn-request`;function nS(e,t,n=null,r={}){let i=r.generateName??cS,a=r.generateUid??aS,o=r.resolveModel??uS;function s(){for(let t=0;t<8;t++){let t=i(),n=`agent_${lS(t)}`;if(!e.getScoops().some(e=>e.jid===n))return t}return a()}function c(t){if(t===void 0)return null;let n=e.getScoops().find(e=>e.jid===t);if(!n)return null;let r=n.config?.modelId;return r&&r.length>0?r:null}async function l(r){let i=r.modelId;if(i!==void 0&&(i===``||o(i)===null))return{finalText:`agent: unknown model: ${i}`,exitCode:1};let a=i??c(r.parentJid)??``,l=s(),u=`agent-${l}`,d=`agent_${lS(l)}`,f=`/scoops/${u}`,p=dS(r.cwd),m={visiblePaths:fS(r),writablePaths:pS([p,`/shared/`,`${f}/`,`/tmp/`]),allowedCommands:r.allowedCommands};a&&(m.modelId=a);let h={jid:d,name:u,folder:u,isCone:!1,type:`scoop`,requiresTrigger:!1,assistantLabel:u,addedAt:new Date().toISOString(),config:m,configSchemaVersion:2,notifyOnComplete:!1},g=[],_=``,v=null,y=e.observeScoop(d,{onSendMessage:e=>{g.push(e)},onResponse:(e,t)=>{t?_+=e:_=e},onError:e=>{v===null&&(v=e)}});try{try{await e.registerScoop(h)}catch(e){return{finalText:v??mS(e),exitCode:1}}return await e.sendPrompt(d,r.prompt,`agent`,`agent`),v===null?{finalText:g.length>0?g[g.length-1]:_,exitCode:0}:{finalText:v,exitCode:1}}catch(e){return{finalText:v??mS(e),exitCode:1}}finally{y();try{await e.unregisterScoop(d)}catch(e){$x.warn(`unregisterScoop failed`,{jid:d,error:mS(e)})}try{await t.rm(f,{recursive:!0})}catch(e){hS(e,`ENOENT`)||$x.warn(`scratch folder cleanup failed`,{folder:u,error:mS(e)})}if(n)try{await n.delete(d)}catch(e){$x.warn(`sessionStore.delete failed`,{jid:d,error:mS(e)})}}}return{spawn:l}}function rS(e,t,n=null,r={}){let i=nS(e,t,n,r);return globalThis[eS]=i,$x.info(`agent bridge published on globalThis.__slicc_agent`),i}function iS(){let e={spawn(e){return new Promise((t,n)=>{let r=globalThis.chrome?.runtime;if(!r||typeof r.sendMessage!=`function`){n(Error(`agent: chrome.runtime.sendMessage not available`));return}let i=e=>{let i=r.lastError;if(i){n(Error(i.message??`chrome.runtime error`));return}if(e==null){n(Error(`agent: empty response from offscreen bridge`));return}let a=e;if(!a.ok){n(Error(a.error??`agent: offscreen bridge error`));return}if(!a.result){n(Error(`agent: offscreen bridge returned no result`));return}t(a.result)};try{r.sendMessage({source:`panel`,payload:{type:tS,options:e}},i)}catch(e){n(e instanceof Error?e:Error(String(e)))}})}};return globalThis[eS]=e,$x.info(`agent bridge proxy published on globalThis.__slicc_agent`),e}function aS(){let e=globalThis;return typeof e.crypto?.randomUUID==`function`?e.crypto.randomUUID().replace(/-/g,``).slice(0,12):`${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}var oS=`amber.bouncy.breezy.bubbly.cheeky.chilly.cozy.dapper.dreamy.eager.exuberant.fluffy.frosty.gentle.giddy.glossy.jolly.lucky.mellow.merry.nimble.plucky.quirky.salty.sleepy.snappy.sparkly.spiffy.sunny.sweet.toasty.velvety.whimsy.zesty`.split(`.`),sS=`blueberry.butterscotch.caramel.cherry.chocolate.cinnamon.coconut.coffee.cookies.custard.espresso.fudge.gelato.hazelnut.honeycomb.lavender.lemon.mango.maple.marzipan.matcha.mint.mocha.neapolitan.nougat.peach.pecan.pistachio.praline.raspberry.sherbet.sorbet.stracciatella.strawberry.tiramisu.toffee.vanilla`.split(`.`);function cS(){return`${oS[Math.floor(Math.random()*oS.length)]}-${sS[Math.floor(Math.random()*sS.length)]}`}function lS(e){return e.replace(/-/g,`_`)}function uS(e){try{let t=D();for(let n of t)if(n.models.some(t=>t.id===e))return e;return null}catch{return null}}function dS(e){let t=L(e);return t.endsWith(`/`)?t:`${t}/`}function fS(e){if(e.visiblePaths!==void 0)return e.visiblePaths.map(dS);let t=[`/workspace/`];return e.invokingCwd&&e.invokingCwd.length>0&&t.push(dS(e.invokingCwd)),pS(t)}function pS(e){let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n}function mS(e){return e instanceof Error?e.message:String(e)}function hS(e,t){if(typeof e!=`object`||!e)return!1;let n=e.code;return typeof n==`string`&&n===t}var gS=r(`tray-webrtc`),_S=`tray-control`,vS=250,yS=class{peerConnectionFactory;dataChannelLabel;peers=new Map;iceServers;constructor(e){this.options=e,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>SS(this.iceServers)),this.dataChannelLabel=e.dataChannelLabel??_S}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=wS(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`)&&(gS.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`?(gS.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`?(gS.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:CS(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){gS.warn(`Failed to report tray bootstrap failure`,{error:e instanceof Error?e.message:String(e)})}}}},bS=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??(()=>SS(this.iceServers)),this.controllerIdFactory=e.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),this.pollIntervalMs=e.pollIntervalMs??vS}async start(){this.stopped=!1;let e=this.controllerIdFactory(),t=Date.now();m({state:`connecting`,joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:t,lastError:null}),gS.info(`Follower tray join starting`,{joinUrl:this.options.joinUrl});let n=0;for(;;){TS(this.stopped),n++;let t;try{t=await Bx({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 m({...g(),attachAttempts:n,lastError:t}),e}if(m({...g(),attachAttempts:n,lastAttachCode:t.code}),t.action===`wait`){let e=t.retryAfterMs??1e3;gS.info(`Follower tray attach waiting`,{attempt:n,code:t.code,retryAfterMs:e}),n%10==0&&gS.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 m({state:`error`,joinUrl:this.options.joinUrl,trayId:null,error:e,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:e}),gS.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 m({state:`connected`,joinUrl:this.options.joinUrl,trayId:r.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:null}),gS.info(`Follower tray connected`,{trayId:r.trayId,controllerId:e}),r}catch(e){let r=e instanceof Error?e.message:String(e);throw m({state:`error`,joinUrl:this.options.joinUrl,trayId:t.trayId,error:r,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:r}),gS.warn(`Follower tray bootstrap failed`,{error:r}),e}}}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,m({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(TS(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 Hx({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 Ux({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,answer:CS(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 Gx({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`)&&(gS.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?(gS.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?(gS.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=wS(n);r&&Wx({joinUrl:this.options.joinUrl,controllerId:e,bootstrapId:t,candidate:r,fetchImpl:this.fetchImpl}).catch(e=>{gS.warn(`Failed to send follower ICE candidate`,{error:e instanceof Error?e.message:String(e)})})}),r}};function xS(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 bS({...e,sleep:o,onDisconnected:e=>{s||(gS.warn(`Follower disconnected, starting reconnect loop`,{reason:e}),f(e))}});return l=t,{manager:t,connectionPromise:t.start()}},f=async u=>{if(s||c)return;c=!0,l?.stop(),l=null;let f=0,p=n,h=u??`Unknown disconnect`;for(;!s&&f<a&&(f++,t.onReconnecting?.(f),m({...g(),state:`reconnecting`,error:null,reconnectAttempts:f}),gS.info(`Reconnect attempt`,{attempt:f,delay:p}),await o(p),!s);){let n=null;try{let r=d();n=r.manager;let i=await r.connectionPromise;if(s){n.stop();break}c=!1,m({...g(),state:`connected`,joinUrl:e.joinUrl,trayId:i.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),gS.info(`Reconnect successful`,{attempt:f,trayId:i.trayId}),t.onConnected(i);return}catch(e){h=e instanceof Error?e.message:String(e),gS.warn(`Reconnect attempt failed`,{attempt:f,error:h}),n?.stop(),l=null}p=Math.min(p*r,i)}s||(c=!1,m({...g(),state:`error`,error:`Reconnect failed after ${f} attempts: ${h}`,reconnectAttempts:f}),gS.warn(`Reconnect gave up`,{attempts:f,lastError:h}),t.onGaveUp?.(h))},{connectionPromise:p}=d();return p.then(e=>{s||t.onConnected(e)}).catch(e=>{s||gS.warn(`Initial follower connection failed`,{error:e instanceof Error?e.message:String(e)})}),u}function SS(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 CS(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 wS(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 TS(e){if(e)throw Error(`Tray follower stopped before WebRTC bootstrap completed`)}var ES=64*1024;async function DS(e,t){try{switch(t.op){case`readFile`:return await OS(e,t.path,t.encoding);case`writeFile`:return[await kS(e,t.path,t.content,t.encoding)];case`stat`:return[await AS(e,t.path)];case`readDir`:return[await jS(e,t.path)];case`mkdir`:return[await MS(e,t.path,t.recursive)];case`rm`:return[await NS(e,t.path,t.recursive)];case`exists`:return[await PS(e,t.path)];case`walk`:return[await FS(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(e){return[LS(e)]}}async function OS(e,t,n){return(n??`utf-8`)===`utf-8`?IS(await e.readFile(t,{encoding:`utf-8`}),`utf-8`):IS(RS(await e.readFile(t,{encoding:`binary`})),`base64`)}async function kS(e,t,n,r){if(r===`base64`){let r=zS(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:`void`}}}async function AS(e,t){return{ok:!0,data:{type:`stat`,stat:await e.stat(t)}}}async function jS(e,t){return{ok:!0,data:{type:`dirEntries`,entries:await e.readDir(t)}}}async function MS(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function NS(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function PS(e,t){return{ok:!0,data:{type:`exists`,exists:await e.exists(t)}}}async function FS(e,t){let n=[];for await(let r of e.walk(t))n.push(r);return{ok:!0,data:{type:`paths`,paths:n}}}function IS(e,t){if(e.length<=ES)return[{ok:!0,data:{type:`file`,content:e,encoding:t}}];let n=Math.ceil(e.length/ES),r=[];for(let i=0;i<n;i++){let a=i*ES,o=e.slice(a,a+ES);r.push({ok:!0,data:{type:`file`,content:o,encoding:t},chunkIndex:i,totalChunks:n})}return r}function LS(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 RS(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function zS(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 BS=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()]}},VS=r(`data-channel-keepalive`),HS=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++,VS.debug(`Missed pong`,{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){VS.warn(`Channel declared dead`,{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}},US=r(`tray-leader-sync`);function WS(e){return e?e.includes(`standalone`)?`standalone`:e.includes(`extension`)?`extension`:e.includes(`electron`)?`electron`:`unknown`:`unknown`}var GS=class{followers=new Map;registry=new BS;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 HS({sendPing:()=>r.send({type:`ping`}),onDead:()=>{US.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:WS(n?.runtime)}),US.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(),US.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();z(t.sync,n,r),US.debug(`Snapshot sent to follower`,{bootstrapId:e,messageCount:n.length})}handleFollowerMessage(e,t){switch(t.type){case`user_message`:US.info(`Follower user message received`,{bootstrapId:e,messageId:t.messageId}),this.options.onFollowerMessage(t.text,t.messageId);break;case`abort`:US.info(`Follower abort received`,{bootstrapId:e}),this.options.onFollowerAbort();break;case`request_snapshot`:US.info(`Follower snapshot request received`,{bootstrapId:e}),this.sendSnapshotToFollower(e);break;case`targets.advertise`:US.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),US.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 ge({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),US.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);U(o.sync,e,t)}catch(t){o.sync.send({type:`cdp.response`,requestId:e,error:t instanceof Error?t.message:String(t)})}}forwardCDPRequest(e,t,n,r,i,a,o){let s=this.runtimeToBootstrap.get(t),c=s?this.followers.get(s):void 0,l=this.followers.get(o);if(!c){l&&l.sync.send({type:`cdp.response`,requestId:e,error:`Target runtime "${t}" not connected`});return}this.pendingCDPRoutes.set(e,{requesterBootstrapId:o,requestId:e}),c.sync.send({type:`cdp.request`,requestId:e,localTargetId:n,method:r,params:i,sessionId:a})}handleCDPResponse(e){let{requestId:t,result:n,error:r,chunkData:i,chunkIndex:a,totalChunks:o}=e,s=this.pendingCDPRoutes.get(t);if(!s)return;let c=pe(this.cdpChunkBuffers,e);if(!c)return;if(this.pendingCDPRoutes.delete(t),s.requesterBootstrapId===`__leader__`){for(let e of this.remoteTransports.values())e.handleResponse(t,c.result,c.error);return}let l=this.followers.get(s.requesterBootstrapId);l&&U(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 DS(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?DS(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})})}},KS=r(`tray-follower-sync`),qS=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=_e(e),this.unsubscribe=this.sync.onMessage(e=>{this.handleLeaderMessage(e)}),this.keepalive=new HS({sendPing:()=>this.sync.send({type:`ping`}),onDead:()=>{KS.warn(`Leader keepalive dead, cleaning up`),this.handleDisconnect(`Keepalive timeout — leader not responding`),this.options.onDead?.()}}),this.keepalive.start(),e.addEventListener(`close`,()=>{KS.warn(`Data channel closed`),this.handleDisconnect(`Data channel closed`)}),e.addEventListener(`error`,()=>{KS.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}),KS.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`}),KS.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(),KS.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,m({...g(),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`:KS.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=H(this.snapshotChunkBuffer,e);this.snapshotChunkBuffer=t.buffer,t.result&&(KS.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),KS.debug(`Skipping own message echo`,{messageId:e.messageId});break}KS.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`:KS.warn(`Error from leader`,{error:e.error}),this.emitEvent({type:`error`,error:e.error});break;case`targets.registry`:KS.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(),d(Date.now());break}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch(t){KS.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}}createRemoteTransport(e,t){let n=new ge({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),KS.debug(`Tracking remote CDP session`,{remoteSessionId:e})}n===`Target.detachFromTarget`&&i&&this.remoteCDPSessions.has(i)&&(this.remoteCDPSessions.delete(i),KS.debug(`Removed remote CDP session on detach`,{sessionId:i})),U(this.sync,e,t)}catch(t){this.sync.send({type:`cdp.response`,requestId:e,error:t instanceof Error?t.message:String(t)})}}setupCDPEventForwarding(e,t){for(let n of[`Page.frameNavigated`,`Page.loadEventFired`,`Page.domContentEventFired`,`Network.responseReceived`,`Network.loadingFinished`,`Network.requestWillBeSent`]){let r=e=>{if(e.sessionId!==t||!this.remoteCDPSessions.has(t))return;let{sessionId:r,...i}=e;this.sync.send({type:`cdp.event`,method:n,params:i,sessionId:t})};e.on(n,r),this.cdpEventCleanups.push(()=>e.off(n,r))}}cleanupCDPEventForwarding(){for(let e of this.cdpEventCleanups)e();this.cdpEventCleanups.length=0,this.remoteCDPSessions.clear()}routeCDPResponse(e){let t=pe(this.cdpChunkBuffers,e);if(t)for(let n of this.remoteTransports.values())n.handleResponse(e.requestId,t.result,t.error)}async executeLocalFs(e,t){let n=this.options.vfs;if(!n){this.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:`Follower has no VFS`}});return}let r=await DS(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 JS(e,t){if(t)return`extension`;try{return ZS(new URL(e))?`electron-overlay`:`standalone`}catch{return`standalone`}}function YS(e,t){return e===`electron-overlay`||e===`standalone`&&t}function XS(e){try{let t=new URL(e).searchParams.get(`tab`);return t&&$a(t)?t:Za}catch{return Za}}function ZS(e){return e.pathname===`/electron`||e.pathname===`/electron/`||e.searchParams.get(`runtime`)===`electron-overlay`}function QS(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}/licks-ws`}function $S(e,t){return`${new URL(e).origin}/webhooks/${t}`}function eC(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function tC(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`slicc-electron-overlay:set-tab`}var nC=[`/shared/sprinkles`];async function rC(e){let t=new Map;for(let n of nC)await e.exists(n)&&await iC(e,n,t);return await iC(e,`/`,t),t}async function iC(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.shtml`))continue;let t=aC(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:oC(i,t),autoOpen:sC(i)})}}}function aC(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.shtml`)?t.slice(0,-6):t}function oC(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 sC(e){return/data-sprinkle-autoopen\b/.test(e)}var cC=r(`sprinkle-manager`),lC=`slicc-open-sprinkles`,uC=class{fs;bridge;callbacks;availableSprinkles=new Map;watcherUnsub;openSprinkles=new Map;constructor(e,t,n,r){this.fs=e,this.bridge=new Zg(e,t,e=>this.close(e),r),this.callbacks=n}async restoreOpenSprinkles(){try{let e=localStorage.getItem(lC);if(!e){for(let e of this.availableSprinkles.values())if(e.autoOpen)try{await this.open(e.name)}catch{cC.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{cC.warn(`Failed to restore sprinkle`,{name:e})}}catch{}}persistOpenSprinkles(){try{localStorage.setItem(lC,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),cC.info(`Auto-opened new sprinkle after install`,{name:e.name})}catch{cC.warn(`Failed to auto-open new sprinkle`,{name:e.name})}}async refresh(){this.availableSprinkles=await rC(this.fs),cC.info(`Discovered sprinkles`,{count:this.availableSprinkles.size})}async open(e,t){if(this.openSprinkles.has(e)){cC.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 gi(i,this.bridge.createAPI(e));await a.render(r,e),this.openSprinkles.get(e).renderer=a,this.persistOpenSprinkles(),mb(e),cC.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(),cC.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){cC.warn(`Cannot send to closed sprinkle`,{name:e});return}this.bridge.pushUpdate(e,t),n.renderer.pushUpdate(t)}};async function dC(e,t,n){let r=[],i=[];for(let{path:a,handle:o}of e){let e=typeof o?.name==`string`?o.name:``;if(!o||!(`queryPermission`in o)){i.push({path:a,dirName:e});continue}let s;try{s=await o.queryPermission({mode:`readwrite`})}catch(t){n?.warn?.(`queryPermission threw on persisted handle`,{path:a,error:t instanceof Error?t.message:String(t)}),i.push({path:a,dirName:e});continue}if(s!==`granted`){i.push({path:a,dirName:e});continue}try{await t.mount(a,o),n?.info?.(`Restored mount from previous session`,{path:a,name:e}),r.push({path:a,dirName:e})}catch(t){n?.warn?.(`Failed to re-mount persisted handle`,{path:a,error:t instanceof Error?t.message:String(t)}),i.push({path:a,dirName:e})}}return{restored:r,needsRecovery:i}}function fC(e){return`'${e.replace(/'/g,`'\\''`)}'`}function pC(e){let t=e.replace(/\r\n|[\r\n]/g,` `),n=t.match(/`+/g),r=n?Math.max(...n.map(e=>e.length))+1:1,i="`".repeat(r);return`${i}${t.startsWith("`")||t.endsWith("`")?` ${t} `:t}${i}`}function mC(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.map(({path:e,dirName:t})=>{let n=t?` (previously mounted from ${pC(t)})`:``;return`- ${pC(e)}${n}`}),n=e.map(({path:e})=>` mount ${fC(e)}`),r=e.length===1?`mount point`:`mount points`,i=e.length===1?`it`:`them`;return[`[Session Reload] Mount recovery required for ${e.length} ${r}.`,``,`The page was reloaded and the following ${r} lost filesystem permission. The browser cannot restore access without a fresh user gesture, so ${i} cannot be used until the user re-authorizes:`,``,...t,``,`Please tell the user what happened and ask whether they want to re-mount. If yes, run the corresponding command(s) so the folder picker opens and they can re-select the same directory:`,``,...n,``,"If the user no longer needs a mount, run `mount unmount <path>` (with the path shell-quoted the same way) to clear the stale entry instead."].join(`
13304
- `)}var $=r(`main`),hC=`slicc-pending-mount`,gC=`pendingMount`,_C=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`]);function vC(e){return e!=null&&_C.has(e)}function yC(){try{let e=new URLSearchParams(window.location.search).get(`ui-fixture`);return e===null?!1:e===``||e===`1`||e.toLowerCase()===`true`}catch{return!1}}async function bC(e){let[{createChatFixture:t,FIXTURE_SESSION_ID:n,FIXTURE_SCOOP_NAME:r}]=await Promise.all([i(()=>import(`./chat-fixture-BVDDtJMz.js`),[])]);await e.switchToContext(n,!0,r),e.loadMessages(t()),$.info(`Loaded UI fixture session for design iteration`)}async function xC(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(hC,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,gC),await new Promise(e=>n.oncomplete=()=>e()),t.close()}async function SC(e){let t;try{t=await new Promise((e,t)=>{let n=indexedDB.open(hC,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(gC);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)});if(r){n.objectStore(`handles`).delete(gC),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 CC(){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 wC(){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 TC(e,t,n){let r=CC(),i=0,a=!1,o=()=>{i=0,a||r.hide()};window.addEventListener(`dragenter`,e=>{go(e.dataTransfer)&&(e.preventDefault(),i+=1,a||r.show(`Drop .skill to install`,`Unpack into /workspace/skills/{name}.`))}),window.addEventListener(`dragover`,e=>{go(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=_o(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 fe(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 EC(e){let{OffscreenClient:t}=await i(async()=>{let{OffscreenClient:e}=await import(`./offscreen-client-CLgve4BY.js`);return{OffscreenClient:e}},__vite__mapDeps([21,15])),{VirtualFS:n}=await i(async()=>{let{VirtualFS:e}=await import(`./fs-bsu2i7du.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([17,4,15,18])),{publishAgentBridgeProxy:r}=await i(async()=>{let{publishAgentBridgeProxy:e}=await Promise.resolve().then(()=>Qx);return{publishAgentBridgeProxy:e}},void 0),a=new io(e,!0);window.__slicc_debug_tabs=e=>a.setDebugTabs(e),await a.panels.chat.initSession(`session-cone`),r();let o=null,s=await n.create({dbName:`slicc-fs`});a.panels.fileBrowser.setFs(s),$.info(`File browser wired to shared VFS (local IndexedDB)`);let c=new BroadcastChannel(`preview-vfs`);c.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 s.readFile(n,{encoding:e});c.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}),c.postMessage({type:`preview-vfs-response`,id:t,error:r})}})()},TC(s,wC(),async()=>{await a.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await i(async()=>{let{WasmShell:e}=await Promise.resolve().then(()=>Tb);return{WasmShell:e}},void 0),{PanelCdpProxy:t,BrowserAPI:n}=await i(async()=>{let{PanelCdpProxy:e,BrowserAPI:t}=await import(`./cdp-CsCvDwW3.js`).then(e=>e.t);return{PanelCdpProxy:e,BrowserAPI:t}},__vite__mapDeps([22,4,1,15])),{fetchSecretEnvVars:r}=await i(async()=>{let{fetchSecretEnvVars:e}=await Promise.resolve().then(()=>Sx);return{fetchSecretEnvVars:e}},void 0),o=new t;await o.connect();let c=new n(o),l=await r(),u=new e({fs:s,browserAPI:c,env:Object.keys(l).length>0?l:void 0});await a.panels.terminal.mountShell(u),$.info(`Terminal mounted with shared VFS and BrowserAPI (CDP proxy)`)}catch(e){$.warn(`Failed to mount shell to terminal`,e)}{let{registerSessionCostsProvider:e}=await i(async()=>{let{registerSessionCostsProvider:e}=await import(`./cost-command-DBzah9S9.js`).then(e=>e.t);return{registerSessionCostsProvider:e}},__vite__mapDeps([23,4]));e(()=>new Promise(e=>{chrome.runtime.sendMessage({source:`panel`,payload:{type:`get-session-costs`}},t=>{if(chrome.runtime.lastError||!t?.ok){e([]);return}e(t.costs??[])})}))}let u,d=new Set,f=async e=>{o=e,u.selectedScoopJid=e.jid,a.panels.memory.setSelectedScoop(e.jid),a.setScoopSwitcherSelected?.(e.jid),a.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=e.isCone?void 0:e.name;await a.panels.chat.switchToContext(t,!e.isCone,n),u.isProcessing(e.jid)&&a.panels.chat.setProcessing(!0)};u=new t({onStatusChange:(e,t)=>{a.panels.scoops.updateScoopStatus(e,t),a.updateScoopSwitcherStatus?.(e,t),o?.jid===e&&(a.setAgentProcessing(t===`processing`),t===`processing`?a.panels.chat.setProcessing(!0):t===`ready`&&a.panels.chat.setProcessing(!1))},onScoopCreated:e=>{a.panels.scoops.refreshScoops(),a.refreshScoopSwitcher?.(),o||(o=e,u.selectedScoopJid=e.jid,a.panels.memory.setSelectedScoop(e.jid))},onScoopListUpdate:()=>{let e=new Set(u.getScoops().map(e=>e.folder));for(let t of d)e.has(t)||a.panels.chat.deleteSessionById(`session-${t}`);if(d=e,a.panels.scoops.refreshScoops(),a.refreshScoopSwitcher?.(),!o){let e=u.getScoops().find(e=>e.isCone);e&&(o=e,u.selectedScoopJid=e.jid,a.panels.memory.setSelectedScoop(e.jid))}},onIncomingMessage:(e,t)=>{if(o?.jid===e){let e=t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content;a.panels.chat.addUserMessage(e)}},onReady:async()=>{try{$.info(`Offscreen engine ready, scoop count:`,u.getScoops().length),window.localStorage.getItem(`slicc.trayJoinUrl`)&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`refresh-tray-runtime`}}).catch(()=>{});let e=o??u.getScoops().find(e=>e.isCone)??u.getScoops()[0];e&&(o=e,u.selectedScoopJid=e.jid,await f(e))}catch(e){$.error(`Failed to initialize on ready`,{error:e instanceof Error?e.message:String(e)})}}}),u.setLocalFS(s);let p=u.createAgentHandle();a.panels.chat.setAgent(p),a.panels.scoops.setOrchestrator(u),a.panels.memory.setOrchestrator(u),a.setScoopSwitcherOrchestrator?.(u),a.onScoopSelect=f,a.onModelChange=e=>{localStorage.setItem(`selected-model`,e),u.updateModel()},a.onClearChat=async()=>{let e=u.getScoops();for(let t of e){let e=t.isCone?`session-cone`:`session-${t.folder}`;await a.panels.chat.deleteSessionById(e)}u.clearAllMessages()},a.onClearFilesystem=async()=>{u.clearFilesystem()},a.panels.chat.onInlineSprinkleLick=(e,t)=>{u.sendSprinkleLick(`inline`,{action:e,data:t})};let m=new uC(s,async e=>{if(e.type===`sprinkle`){if(e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&s.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome completion marker`,e)),n===`shortcut-migrate`&&m.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&SC(s).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 xC(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}u.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop)}},{addSprinkle:(e,t,n,r)=>a.addSprinkle(e,t,n,r),removeSprinkle:e=>a.removeSprinkle(e)},()=>{let e=u.getScoops().find(e=>e.isCone);e&&u.stopScoop(e.jid)});if(window.__slicc_sprinkleManager=m,window.__slicc_reloadSkills=()=>(chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}}),Promise.resolve()),u.setSprinkleOpHandler(e=>{let{id:t,op:n,name:r,data:i}=e;console.log(`[main-ext] sprinkle-op handler called`,{id:t,op:n,name:r}),(async()=>{try{let e;switch(n){case`list`:await m.refresh(),e=m.available();break;case`opened`:e=m.opened();break;case`refresh`:await m.refresh(),e=m.available().length;break;case`open`:await m.open(r),e=!0;break;case`close`:m.close(r),e=!0;break;case`send`:m.sendToSprinkle(r,i),e=!0;break;case`openNewAutoOpen`:await m.openNewAutoOpenSprinkles(),e=!0;break}console.log(`[main-ext] sprinkle-op response sending`,{id:t,op:n,result:typeof e}),chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,result:e}}).catch(()=>{})}catch(e){chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}})()}),await m.refresh(),a.onSprinkleClose=e=>m.close(e),a.getAvailableSprinkles=()=>{let e=new Set(m.opened());return m.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},a.onOpenSprinkle=(e,t)=>m.open(e,t),a.updateAddButtons(),await m.restoreOpenSprinkles(),!await s.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await s.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await s.exists(`/shared/.welcomed`)&&!l(window.localStorage)&&m.available().some(e=>e.name===`welcome`))try{await m.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}$.info(`SprinkleManager initialized (extension mode)`),u.requestState(),$.info(`Extension UI connected to offscreen agent engine`),yC()&&await bC(a.panels.chat),db().catch(()=>{})}function DC(){if(typeof chrome<`u`&&chrome?.runtime?.id)return;let e=new Blob([`
13304
+ `)}var $=r(`main`),hC=`slicc-pending-mount`,gC=`pendingMount`,_C=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`]);function vC(e){return e!=null&&_C.has(e)}function yC(){try{let e=new URLSearchParams(window.location.search).get(`ui-fixture`);return e===null?!1:e===``||e===`1`||e.toLowerCase()===`true`}catch{return!1}}async function bC(e){let[{createChatFixture:t,FIXTURE_SESSION_ID:n,FIXTURE_SCOOP_NAME:r}]=await Promise.all([i(()=>import(`./chat-fixture-Nts2sMME.js`),[])]);await e.switchToContext(n,!0,r),e.loadMessages(t()),$.info(`Loaded UI fixture session for design iteration`)}async function xC(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(hC,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,gC),await new Promise(e=>n.oncomplete=()=>e()),t.close()}async function SC(e){let t;try{t=await new Promise((e,t)=>{let n=indexedDB.open(hC,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(gC);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)});if(r){n.objectStore(`handles`).delete(gC),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 CC(){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 wC(){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 TC(e,t,n){let r=CC(),i=0,a=!1,o=()=>{i=0,a||r.hide()};window.addEventListener(`dragenter`,e=>{go(e.dataTransfer)&&(e.preventDefault(),i+=1,a||r.show(`Drop .skill to install`,`Unpack into /workspace/skills/{name}.`))}),window.addEventListener(`dragover`,e=>{go(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=_o(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 fe(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 EC(e){let{OffscreenClient:t}=await i(async()=>{let{OffscreenClient:e}=await import(`./offscreen-client-BlWuVmPl.js`);return{OffscreenClient:e}},__vite__mapDeps([21,15])),{VirtualFS:n}=await i(async()=>{let{VirtualFS:e}=await import(`./fs-bsu2i7du.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([17,4,15,18])),{publishAgentBridgeProxy:r}=await i(async()=>{let{publishAgentBridgeProxy:e}=await Promise.resolve().then(()=>Qx);return{publishAgentBridgeProxy:e}},void 0),a=new io(e,!0);window.__slicc_debug_tabs=e=>a.setDebugTabs(e),await a.panels.chat.initSession(`session-cone`),r();let o=null,s=await n.create({dbName:`slicc-fs`});a.panels.fileBrowser.setFs(s),$.info(`File browser wired to shared VFS (local IndexedDB)`);let c=new BroadcastChannel(`preview-vfs`);c.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 s.readFile(n,{encoding:e});c.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}),c.postMessage({type:`preview-vfs-response`,id:t,error:r})}})()},TC(s,wC(),async()=>{await a.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await i(async()=>{let{WasmShell:e}=await Promise.resolve().then(()=>Tb);return{WasmShell:e}},void 0),{PanelCdpProxy:t,BrowserAPI:n}=await i(async()=>{let{PanelCdpProxy:e,BrowserAPI:t}=await import(`./cdp-CsCvDwW3.js`).then(e=>e.t);return{PanelCdpProxy:e,BrowserAPI:t}},__vite__mapDeps([22,4,1,15])),{fetchSecretEnvVars:r}=await i(async()=>{let{fetchSecretEnvVars:e}=await Promise.resolve().then(()=>Sx);return{fetchSecretEnvVars:e}},void 0),o=new t;await o.connect();let c=new n(o),l=await r(),u=new e({fs:s,browserAPI:c,env:Object.keys(l).length>0?l:void 0});await a.panels.terminal.mountShell(u),$.info(`Terminal mounted with shared VFS and BrowserAPI (CDP proxy)`)}catch(e){$.warn(`Failed to mount shell to terminal`,e)}{let{registerSessionCostsProvider:e}=await i(async()=>{let{registerSessionCostsProvider:e}=await import(`./cost-command-DBzah9S9.js`).then(e=>e.t);return{registerSessionCostsProvider:e}},__vite__mapDeps([23,4]));e(()=>new Promise(e=>{chrome.runtime.sendMessage({source:`panel`,payload:{type:`get-session-costs`}},t=>{if(chrome.runtime.lastError||!t?.ok){e([]);return}e(t.costs??[])})}))}let u,d=new Set,f=async e=>{o=e,u.selectedScoopJid=e.jid,a.panels.memory.setSelectedScoop(e.jid),a.setScoopSwitcherSelected?.(e.jid),a.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=e.isCone?void 0:e.name;await a.panels.chat.switchToContext(t,!e.isCone,n),u.isProcessing(e.jid)&&a.panels.chat.setProcessing(!0)};u=new t({onStatusChange:(e,t)=>{a.panels.scoops.updateScoopStatus(e,t),a.updateScoopSwitcherStatus?.(e,t),o?.jid===e&&(a.setAgentProcessing(t===`processing`),t===`processing`?a.panels.chat.setProcessing(!0):t===`ready`&&a.panels.chat.setProcessing(!1))},onScoopCreated:e=>{a.panels.scoops.refreshScoops(),a.refreshScoopSwitcher?.(),o||(o=e,u.selectedScoopJid=e.jid,a.panels.memory.setSelectedScoop(e.jid))},onScoopListUpdate:()=>{let e=new Set(u.getScoops().map(e=>e.folder));for(let t of d)e.has(t)||a.panels.chat.deleteSessionById(`session-${t}`);if(d=e,a.panels.scoops.refreshScoops(),a.refreshScoopSwitcher?.(),!o){let e=u.getScoops().find(e=>e.isCone);e&&(o=e,u.selectedScoopJid=e.jid,a.panels.memory.setSelectedScoop(e.jid))}},onIncomingMessage:(e,t)=>{if(o?.jid===e){let e=t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content;a.panels.chat.addUserMessage(e)}},onReady:async()=>{try{$.info(`Offscreen engine ready, scoop count:`,u.getScoops().length),window.localStorage.getItem(`slicc.trayJoinUrl`)&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`refresh-tray-runtime`}}).catch(()=>{});let e=o??u.getScoops().find(e=>e.isCone)??u.getScoops()[0];e&&(o=e,u.selectedScoopJid=e.jid,await f(e))}catch(e){$.error(`Failed to initialize on ready`,{error:e instanceof Error?e.message:String(e)})}}}),u.setLocalFS(s);let p=u.createAgentHandle();a.panels.chat.setAgent(p),a.panels.scoops.setOrchestrator(u),a.panels.memory.setOrchestrator(u),a.setScoopSwitcherOrchestrator?.(u),a.onScoopSelect=f,a.onModelChange=e=>{localStorage.setItem(`selected-model`,e),u.updateModel()},a.onClearChat=async()=>{let e=u.getScoops();for(let t of e){let e=t.isCone?`session-cone`:`session-${t.folder}`;await a.panels.chat.deleteSessionById(e)}u.clearAllMessages()},a.onClearFilesystem=async()=>{u.clearFilesystem()},a.panels.chat.onInlineSprinkleLick=(e,t)=>{u.sendSprinkleLick(`inline`,{action:e,data:t})};let m=new uC(s,async e=>{if(e.type===`sprinkle`){if(e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&s.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome completion marker`,e)),n===`shortcut-migrate`&&m.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&SC(s).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 xC(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}u.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop)}},{addSprinkle:(e,t,n,r)=>a.addSprinkle(e,t,n,r),removeSprinkle:e=>a.removeSprinkle(e)},()=>{let e=u.getScoops().find(e=>e.isCone);e&&u.stopScoop(e.jid)});if(window.__slicc_sprinkleManager=m,window.__slicc_reloadSkills=()=>(chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}}),Promise.resolve()),u.setSprinkleOpHandler(e=>{let{id:t,op:n,name:r,data:i}=e;console.log(`[main-ext] sprinkle-op handler called`,{id:t,op:n,name:r}),(async()=>{try{let e;switch(n){case`list`:await m.refresh(),e=m.available();break;case`opened`:e=m.opened();break;case`refresh`:await m.refresh(),e=m.available().length;break;case`open`:await m.open(r),e=!0;break;case`close`:m.close(r),e=!0;break;case`send`:m.sendToSprinkle(r,i),e=!0;break;case`openNewAutoOpen`:await m.openNewAutoOpenSprinkles(),e=!0;break}console.log(`[main-ext] sprinkle-op response sending`,{id:t,op:n,result:typeof e}),chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,result:e}}).catch(()=>{})}catch(e){chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}})()}),await m.refresh(),a.onSprinkleClose=e=>m.close(e),a.getAvailableSprinkles=()=>{let e=new Set(m.opened());return m.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},a.onOpenSprinkle=(e,t)=>m.open(e,t),a.updateAddButtons(),await m.restoreOpenSprinkles(),!await s.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await s.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await s.exists(`/shared/.welcomed`)&&!l(window.localStorage)&&m.available().some(e=>e.name===`welcome`))try{await m.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}$.info(`SprinkleManager initialized (extension mode)`),u.requestState(),$.info(`Extension UI connected to offscreen agent engine`),yC()&&await bC(a.panels.chat),db().catch(()=>{})}function DC(){if(typeof chrome<`u`&&chrome?.runtime?.id)return;let e=new Blob([`
13305
13305
  let lastPong = Date.now();
13306
13306
  let frozen = false;
13307
13307
  setInterval(() => {
@@ -13329,4 +13329,4 @@ ${t}
13329
13329
  #app > .tab-content > .tab-content__panel {
13330
13330
  height: 100%;
13331
13331
  }
13332
- `,document.head.appendChild(t),window.addEventListener(`message`,e=>{e.source===window.parent&&tC(e.data)&&u.setActiveTab(XS(`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=wC();await u.panels.chat.initSession(`session-cone`),$.info(`Session initialized`);let p=new B,m=new Set,h=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)})}},g=null,v=new Map,y=new Map;function b(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function S(e){let t=y.get(e);return t||(t=[],y.set(e,t)),t}function C(e,t){let n=S(e),r=v.get(e);if(r){let e=n.find(e=>e.id===r);if(e)return e}r=`scoop-${e}-${b()}`,v.set(e,r);let i=w.getScoops().find(t=>t.jid===e),a=i?.isCone?`cone`:i?.name??`unknown`,o={id:r,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:a,channel:t};return n.push(o),g?.jid===e&&h({type:`message_start`,messageId:r}),o}let w=new Lx(u.getIframeContainer(),{onResponse:(e,t,n)=>{let r=C(e);n?r.content+=t:(r.content=t,r.isStreaming=!1),g?.jid===e&&(h({type:`content_delta`,messageId:r.id,text:t}),n||h({type:`content_done`,messageId:r.id}))},onResponseDone:e=>{let t=S(e),n=v.get(e);if(n){let r=t.find(e=>e.id===n);r&&(r.isStreaming=!1),g?.jid===e&&h({type:`content_done`,messageId:n}),v.delete(e)}},onSendMessage:(e,t)=>{$.debug(`Send message requested`,{targetJid:e,textLength:t.length});let n=`msg-${b()}`,r={id:n,chatJid:e,senderId:`assistant`,senderName:`sliccy`,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`web`};w.handleMessage(r),S(e).push({id:n,role:`assistant`,content:t,timestamp:Date.now()}),g?.jid===e&&(h({type:`message_start`,messageId:n}),h({type:`content_delta`,messageId:n,text:t}),h({type:`content_done`,messageId:n}))},onStatusChange:(e,t)=>{if(u.panels.scoops.updateScoopStatus(e,t),u.updateScoopSwitcherStatus?.(e,t),g?.jid===e){if(u.setAgentProcessing(t===`processing`),t===`processing`)u.panels.chat.setProcessing(!0);else if(t===`ready`){u.panels.chat.setProcessing(!1);let t=v.get(e)??`done-${e}-${b()}`;v.delete(e),h({type:`turn_end`,messageId:t})}}},onError:(e,t)=>{$.error(`Scoop error`,{scoopJid:e,error:t}),g?.jid===e&&h({type:`error`,error:t})},getBrowserAPI:()=>p,onToolStart:(e,t,n)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let r=C(e);r.toolCalls||=[],r.toolCalls.push({id:b(),name:t,input:n}),g?.jid===e&&h({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=v.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)}}g?.jid===e&&a&&h({type:`tool_result`,messageId:a,toolName:t,result:n,isError:r})},onToolUI:(e,t,n,r)=>{let i=v.get(e);i?h({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=v.get(e);n&&h({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),g?.jid===e&&(h({type:`message_start`,messageId:t.id}),h({type:`content_delta`,messageId:t.id,text:n.content}),h({type:`content_done`,messageId:t.id}))}});await w.init(),u.panels.scoops.setOrchestrator(w),u.panels.memory.setOrchestrator(w),u.setScoopSwitcherOrchestrator?.(w);{let e=w.getSharedFS();e?rS(w,e,w.getSessionStore()):$.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`)}let T=w.getSharedFS();if(T){u.panels.fileBrowser.setFs(T),$.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 T.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})}})()},TC(T,(e,t)=>{t===`error`?$.warn(`Dropped skill install failed`,{message:e}):$.info(`Dropped skill installed`,{message:e}),d(e,t)},async()=>{await u.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await i(async()=>{let{WasmShell:e}=await Promise.resolve().then(()=>Tb);return{WasmShell:e}},void 0),{fetchSecretEnvVars:t}=await i(async()=>{let{fetchSecretEnvVars:e}=await Promise.resolve().then(()=>Sx);return{fetchSecretEnvVars:e}},void 0),n=await t(),r=new e({fs:T,browserAPI:p,env:Object.keys(n).length>0?n:void 0});await u.panels.terminal.mountShell(r),$.info(`Terminal mounted with shared VFS`);try{let{BshWatchdog:e}=await i(async()=>{let{BshWatchdog:e}=await import(`./bsh-watchdog-C8qkdGvF.js`);return{BshWatchdog:e}},__vite__mapDeps([24,15])),t=new e({browserAPI:p,scriptCatalog:r.getScriptCatalog(),fs:T});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 E=w.getScoops(),D=E.some(e=>e.isCone);if(r)$.info(`Skipping local cone bootstrap while joining a tray without a configured provider`);else if(!D)g=await u.panels.scoops.createCone(),$.info(`Created cone`);else{let e=new URLSearchParams(window.location.search).get(`scoop`);if(e){let t=E.find(t=>t.folder===e);t?(g=t,$.info(`Restored scoop from URL`,{folder:e})):g=E.find(e=>e.isCone)??E[0]}else g=E.find(e=>e.isCone)??E[0]}g&&u.panels.memory.setSelectedScoop(g.jid);let k=null,A={sendMessage(e,t){if(!g){h({type:`error`,error:`No scoop selected`});return}let n={id:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:g.jid,senderId:`user`,senderName:`User`,content:e,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`};S(g.jid).push({id:n.id,role:`user`,content:e,timestamp:Date.now()}),k?.broadcastUserMessage(e,n.id),w.handleMessage(n),w.createScoopTab(g.jid)},onEvent(e){return m.add(e),()=>m.delete(e)},stop(){g&&(w.stopScoop(g.jid),w.clearQueuedMessages(g.jid).catch(e=>{$.error(`Failed to clear queued messages on stop`,{error:e instanceof Error?e.message:String(e)})}))}};u.panels.chat.setAgent(A),u.panels.chat.setDeleteQueuedMessageCallback(e=>{if(g){w.deleteQueuedMessage(g.jid,e).catch(t=>{$.error(`Failed to delete queued message`,{messageId:e,error:t instanceof Error?t.message:String(t)})});let t=y.get(g.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:ee}=await i(async()=>{let{getLickManager:e}=await Promise.resolve().then(()=>Ax);return{getLickManager:e}},void 0),j=ee();await j.init(),w.setLickManager(j);let te=e=>{let t=e.type===`webhook`,n=e.type===`sprinkle`,r=e.type===`fswatch`,i=e.type===`session-reload`,a=e.type===`navigate`,o=t?e.webhookName:n?e.sprinkleName:r?e.fswatchName:i?`session-reload`:a?e.navigateUrl:e.cronName,s=t?e.webhookId:n?e.sprinkleName:r?e.fswatchId:i?`session-reload`:a?e.navigateUrl:e.cronId,c=e.type;if($.debug(`Lick event`,{type:e.type,name:o,targetScoop:e.targetScoop}),n&&e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&T?.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&&T&&SC(T).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 xC(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 l=w.getScoops(),d;if(d=e.targetScoop?l.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):l.find(e=>e.isCone),d){let l=`${c}-${s}-${Date.now()}`,f=t?`Webhook Event`:n?`Sprinkle Event`:r?`File Watch Event`:i?`Session Reload`:a?`Navigate Event`:`Cron Event`,p=null;if(i){let t=e.body;if(t?.reason===`mount-recovery`&&(p=mC(t.mounts??[]),p===null)){$.debug(`Dropping session-reload lick with empty mount-recovery list`);return}}p===null&&(p=`[${f}: ${o}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``);let m={id:l,chatJid:d.jid,senderId:c,senderName:`${c}:${o}`,content:p,timestamp:e.timestamp,fromAssistant:!1,channel:c},h=Date.now();if(S(d.jid).push({id:l,role:`user`,content:p,timestamp:h,source:`lick`,channel:c}),g?.jid===d.jid)u.panels.chat.addLickMessage(l,p,c,h);else{let e=d.isCone?`session-cone`:`session-${d.folder}`;u.panels.chat.persistLickToSession(e,{id:l,content:p,channel:c,timestamp:h})}$.info(`Routing lick to scoop`,{type:c,name:o,scoopJid:d.jid}),w.handleMessage(m)}else $.warn(`Lick target scoop not found`,{targetScoop:e.targetScoop})};j.setEventHandler(te);let re=new V(p.getTransport(),e=>{j.emitEvent({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:new Date().toISOString(),body:{url:e.url,sliccHeader:e.sliccHeader,title:e.title}})});(async()=>{try{await p.connect(),await re.start(),$.info(`Navigation watcher started`)}catch(e){$.warn(`Failed to start navigation watcher`,{error:e instanceof Error?e.message:String(e)})}})(),T&&F().then(async e=>{if(e.length===0)return;let{needsRecovery:t}=await dC(e,T,$);t.length!==0&&te({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:t}})}).catch(e=>$.warn(`Failed to restore persisted mounts`,e)),u.panels.chat.onInlineSprinkleLick=(e,t)=>{te({type:`sprinkle`,sprinkleName:`inline`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:e,data:t}})};let M=null;if(T){if(M=new uC(T,te,{addSprinkle:(e,t,n,r)=>u.addSprinkle(e,t,n,r),removeSprinkle:e=>u.removeSprinkle(e)},()=>{let e=w.getScoops().find(e=>e.isCone);e&&(w.stopScoop(e.jid),w.clearQueuedMessages(e.jid).catch(e=>{$.error(`Failed to clear queued messages on sprinkle stopCone`,{error:e instanceof Error?e.message:String(e)})}))}),window.__slicc_sprinkleManager=M,window.__slicc_reloadSkills=()=>w.reloadAllSkills(),await M.refresh(),u.onSprinkleClose=e=>M.close(e),u.getAvailableSprinkles=()=>{let e=new Set(M.opened());return M.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},u.onOpenSprinkle=(e,t)=>M.open(e,t),u.updateAddButtons(),!await T.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await T.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await T.exists(`/shared/.welcomed`)&&!r&&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=QS(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:j.listWebhooks()};break;case`create_webhook`:{let t=await j.createWebhook(n.name||`default`,n.scoop,n.filter),r=uh().session,i=r?.webhookUrl?eC(r.webhookUrl,t.id):$S(window.location.href,t.id);e={type:`response`,requestId:n.requestId,data:{...t,url:i}};break}case`delete_webhook`:e=await j.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:j.listCronTasks()};break;case`create_crontask`:{if(!n.name)throw Error(`name is required`);if(!n.cron)throw Error(`cron is required`);let t=await j.createCronTask(n.name,n.cron,n.scoop,n.filter);e={type:`response`,requestId:n.requestId,data:t};break}case`delete_crontask`:e=await j.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=uh();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}if(n.type===`webhook_event`&&j.handleWebhookEvent(n.webhookId,n.headers,n.body),n.type===`navigate_event`){let e=typeof n.sliccHeader==`string`?n.sliccHeader:``,t=typeof n.url==`string`&&n.url.length>0?n.url:``;e&&t&&j.emitEvent({type:`navigate`,navigateUrl:t,targetScoop:void 0,timestamp:typeof n.timestamp==`string`?n.timestamp:new Date().toISOString(),body:{url:t,sliccHeader:e,title:typeof n.title==`string`?n.title:void 0}})}}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(),u.onModelChange=e=>{localStorage.setItem(`selected-model`,e),w.updateModel()};let P=new Set;u.onClearChat=async()=>{await w.clearAllMessages(),y.clear(),P.clear()},u.onClearFilesystem=async()=>{await w.resetFilesystem()};let ie=async e=>{$.info(`Scoop selected`,{jid:e.jid,name:e.name}),g=e,w.createScoopTab(e.jid),u.panels.memory.setSelectedScoop(e.jid),u.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=y.get(e.jid),r=!P.has(e.jid),i=e.isCone?void 0:e.name;if(!r&&n&&n.length>0)await u.panels.chat.switchToContext(t,!e.isCone,i),u.panels.chat.loadMessages(n);else{if(await u.panels.chat.switchToContext(t,!e.isCone,i),u.panels.chat.getMessages().length===0){let t=await w.getMessagesForScoop(e.jid);for(let e of t){let t=e.channel===`delegation`;vC(e.channel)?u.panels.chat.addLickMessage(e.id,e.content,e.channel,new Date(e.timestamp).getTime()):t?u.panels.chat.addUserMessage(`**[Instructions from sliccy]**\n\n${e.content}`):e.fromAssistant?(h({type:`message_start`,messageId:e.id}),h({type:`content_delta`,messageId:e.id,text:e.content}),h({type:`content_done`,messageId:e.id})):u.panels.chat.addUserMessage(e.content)}}let n=u.panels.chat.getMessages(),r=new Set(n.map(e=>e.id)),a=S(e.jid),o=a.filter(e=>!r.has(e.id));a.length=0,a.push(...n,...o),o.length>0&&u.panels.chat.loadMessages(a)}e.isCone&&w.isProcessing(e.jid)&&u.panels.chat.setProcessing(!0),P.add(e.jid)};if(u.onScoopSelect=ie,g&&(w.createScoopTab(g.jid),await ie(g)),yC()&&await bC(u.panels.chat),s===`standalone`||s===`electron-overlay`){let e=await a(),t=YS(s,e!==null)?c:null,n=await _({locationHref:window.location.href,storage:window.localStorage,envBaseUrl:null,defaultWorkerBaseUrl:t,runtimeConfigFetcher:async()=>e}),r=null,i=null,o=null;__(()=>k?(e,t)=>k.sendFsRequest(e,t):r?(e,t)=>r.sendFsRequest(e,t):null),im(()=>k?()=>k.getBestFollowerForTeleport():null),am(()=>k?()=>k.getConnectedFollowers():null);let l=e=>{o&&=(clearInterval(o),null),r?.close();let t=`follower-${e.bootstrapId}`,n=new qS(e.channel,{browserTransport:p.getTransport(),browserAPI:p,onSnapshot:e=>{u.panels.chat.loadMessages(e)},onUserMessage:e=>{u.panels.chat.addUserMessage(e)},onStatus:e=>{u.panels.chat.setProcessing(e===`processing`)},onTargetsChanged:()=>void i()});r=n,p.setTrayTargetProvider(n),u.panels.chat.setAgent(n),n.requestSnapshot();let i=async()=>{try{let e=await p.listPages();n.advertiseTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})),t)}catch{}};o=setInterval(i,5e3),i(),$.info(`Follower sync wired to chat panel`,{trayId:e.trayId})},d=e=>{i?.cancel(),o&&=(clearInterval(o),null),r?.close(),r=null,i=xS({joinUrl:e,runtime:`slicc-standalone`,fetchImpl:vh()},{onConnected:e=>l(e),onReconnecting:e=>{$.info(`Follower reconnecting`,{attempt:e})},onGaveUp:e=>{$.warn(`Follower reconnect gave up`,{lastError:e})}})};if(window.addEventListener(`slicc:tray-join`,(e=>{d(e.detail.joinUrl)})),window.addEventListener(`beforeunload`,()=>{o&&clearInterval(o),r?.close(),i?.cancel()},{once:!0}),n?.joinUrl)d(n.joinUrl);else if(n?.workerBaseUrl){let e,t,r,i,a=()=>{t=new GS({browserTransport:p.getTransport(),browserAPI:p,getMessages:()=>u.panels.chat.getMessages(),getScoopJid:()=>g?.jid??`cone`,onFollowerMessage:(e,t)=>{u.panels.chat.addUserMessage(e),A.sendMessage(e,t)},onFollowerAbort:()=>{A.stop()}}),k=t,bh(()=>t.getConnectedFollowers()),p.setTrayTargetProvider(t),i&&clearInterval(i);let n=async()=>{try{let e=await p.listPages();t.setLocalTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})))}catch{}};i=setInterval(n,5e3),n(),r=new yS({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 mh({workerBaseUrl:n.workerBaseUrl,runtime:`slicc-standalone`,fetchImpl:vh(),onControlMessage:e=>{if(e.type===`webhook.event`){j.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)})})}}),Ch(async()=>{t.stop(),r.stop(),e.stop(),await e.clearSession();let n=await e.start(),i=f(window.location.href,n.workerBaseUrl,n.trayId);return i!==window.location.href&&window.history.replaceState(window.history.state,``,i),a(),uh()}),e.start().then(e=>{let t=f(window.location.href,e.workerBaseUrl,e.trayId);t!==window.location.href&&window.history.replaceState(window.history.state,``,t)}).catch(e=>{$.warn(`Leader tray join failed`,{error:e instanceof Error?e.message:String(e)})}),window.addEventListener(`beforeunload`,()=>{clearInterval(i),t.stop(),r.stop(),e.stop()},{once:!0})}}$.info(`Orchestrator initialized — cone+scoops ready`,{scoopCount:w.getScoops().length}),db().catch(()=>{})}OC().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{Qs as t};
13332
+ `,document.head.appendChild(t),window.addEventListener(`message`,e=>{e.source===window.parent&&tC(e.data)&&u.setActiveTab(XS(`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=wC();await u.panels.chat.initSession(`session-cone`),$.info(`Session initialized`);let p=new B,m=new Set,h=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)})}},g=null,v=new Map,y=new Map;function b(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function S(e){let t=y.get(e);return t||(t=[],y.set(e,t)),t}function C(e,t){let n=S(e),r=v.get(e);if(r){let e=n.find(e=>e.id===r);if(e)return e}r=`scoop-${e}-${b()}`,v.set(e,r);let i=w.getScoops().find(t=>t.jid===e),a=i?.isCone?`cone`:i?.name??`unknown`,o={id:r,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:a,channel:t};return n.push(o),g?.jid===e&&h({type:`message_start`,messageId:r}),o}let w=new Lx(u.getIframeContainer(),{onResponse:(e,t,n)=>{let r=C(e);n?r.content+=t:(r.content=t,r.isStreaming=!1),g?.jid===e&&(h({type:`content_delta`,messageId:r.id,text:t}),n||h({type:`content_done`,messageId:r.id}))},onResponseDone:e=>{let t=S(e),n=v.get(e);if(n){let r=t.find(e=>e.id===n);r&&(r.isStreaming=!1),g?.jid===e&&h({type:`content_done`,messageId:n}),v.delete(e)}},onSendMessage:(e,t)=>{$.debug(`Send message requested`,{targetJid:e,textLength:t.length});let n=`msg-${b()}`,r={id:n,chatJid:e,senderId:`assistant`,senderName:`sliccy`,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`web`};w.handleMessage(r),S(e).push({id:n,role:`assistant`,content:t,timestamp:Date.now()}),g?.jid===e&&(h({type:`message_start`,messageId:n}),h({type:`content_delta`,messageId:n,text:t}),h({type:`content_done`,messageId:n}))},onStatusChange:(e,t)=>{if(u.panels.scoops.updateScoopStatus(e,t),u.updateScoopSwitcherStatus?.(e,t),g?.jid===e){if(u.setAgentProcessing(t===`processing`),t===`processing`)u.panels.chat.setProcessing(!0);else if(t===`ready`){u.panels.chat.setProcessing(!1);let t=v.get(e)??`done-${e}-${b()}`;v.delete(e),h({type:`turn_end`,messageId:t})}}},onError:(e,t)=>{$.error(`Scoop error`,{scoopJid:e,error:t}),g?.jid===e&&h({type:`error`,error:t})},getBrowserAPI:()=>p,onToolStart:(e,t,n)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let r=C(e);r.toolCalls||=[],r.toolCalls.push({id:b(),name:t,input:n}),g?.jid===e&&h({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=v.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)}}g?.jid===e&&a&&h({type:`tool_result`,messageId:a,toolName:t,result:n,isError:r})},onToolUI:(e,t,n,r)=>{let i=v.get(e);i?h({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=v.get(e);n&&h({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),g?.jid===e&&(h({type:`message_start`,messageId:t.id}),h({type:`content_delta`,messageId:t.id,text:n.content}),h({type:`content_done`,messageId:t.id}))}});await w.init(),u.panels.scoops.setOrchestrator(w),u.panels.memory.setOrchestrator(w),u.setScoopSwitcherOrchestrator?.(w);{let e=w.getSharedFS();e?rS(w,e,w.getSessionStore()):$.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`)}let T=w.getSharedFS();if(T){u.panels.fileBrowser.setFs(T),$.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 T.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})}})()},TC(T,(e,t)=>{t===`error`?$.warn(`Dropped skill install failed`,{message:e}):$.info(`Dropped skill installed`,{message:e}),d(e,t)},async()=>{await u.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await i(async()=>{let{WasmShell:e}=await Promise.resolve().then(()=>Tb);return{WasmShell:e}},void 0),{fetchSecretEnvVars:t}=await i(async()=>{let{fetchSecretEnvVars:e}=await Promise.resolve().then(()=>Sx);return{fetchSecretEnvVars:e}},void 0),n=await t(),r=new e({fs:T,browserAPI:p,env:Object.keys(n).length>0?n:void 0});await u.panels.terminal.mountShell(r),$.info(`Terminal mounted with shared VFS`);try{let{BshWatchdog:e}=await i(async()=>{let{BshWatchdog:e}=await import(`./bsh-watchdog-BXTi5bzs.js`);return{BshWatchdog:e}},__vite__mapDeps([24,15])),t=new e({browserAPI:p,scriptCatalog:r.getScriptCatalog(),fs:T});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 E=w.getScoops(),D=E.some(e=>e.isCone);if(r)$.info(`Skipping local cone bootstrap while joining a tray without a configured provider`);else if(!D)g=await u.panels.scoops.createCone(),$.info(`Created cone`);else{let e=new URLSearchParams(window.location.search).get(`scoop`);if(e){let t=E.find(t=>t.folder===e);t?(g=t,$.info(`Restored scoop from URL`,{folder:e})):g=E.find(e=>e.isCone)??E[0]}else g=E.find(e=>e.isCone)??E[0]}g&&u.panels.memory.setSelectedScoop(g.jid);let k=null,A={sendMessage(e,t){if(!g){h({type:`error`,error:`No scoop selected`});return}let n={id:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:g.jid,senderId:`user`,senderName:`User`,content:e,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`};S(g.jid).push({id:n.id,role:`user`,content:e,timestamp:Date.now()}),k?.broadcastUserMessage(e,n.id),w.handleMessage(n),w.createScoopTab(g.jid)},onEvent(e){return m.add(e),()=>m.delete(e)},stop(){g&&(w.stopScoop(g.jid),w.clearQueuedMessages(g.jid).catch(e=>{$.error(`Failed to clear queued messages on stop`,{error:e instanceof Error?e.message:String(e)})}))}};u.panels.chat.setAgent(A),u.panels.chat.setDeleteQueuedMessageCallback(e=>{if(g){w.deleteQueuedMessage(g.jid,e).catch(t=>{$.error(`Failed to delete queued message`,{messageId:e,error:t instanceof Error?t.message:String(t)})});let t=y.get(g.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:ee}=await i(async()=>{let{getLickManager:e}=await Promise.resolve().then(()=>Ax);return{getLickManager:e}},void 0),j=ee();await j.init(),w.setLickManager(j);let te=e=>{let t=e.type===`webhook`,n=e.type===`sprinkle`,r=e.type===`fswatch`,i=e.type===`session-reload`,a=e.type===`navigate`,o=t?e.webhookName:n?e.sprinkleName:r?e.fswatchName:i?`session-reload`:a?e.navigateUrl:e.cronName,s=t?e.webhookId:n?e.sprinkleName:r?e.fswatchId:i?`session-reload`:a?e.navigateUrl:e.cronId,c=e.type;if($.debug(`Lick event`,{type:e.type,name:o,targetScoop:e.targetScoop}),n&&e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&T?.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&&T&&SC(T).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 xC(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 l=w.getScoops(),d;if(d=e.targetScoop?l.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):l.find(e=>e.isCone),d){let l=`${c}-${s}-${Date.now()}`,f=t?`Webhook Event`:n?`Sprinkle Event`:r?`File Watch Event`:i?`Session Reload`:a?`Navigate Event`:`Cron Event`,p=null;if(i){let t=e.body;if(t?.reason===`mount-recovery`&&(p=mC(t.mounts??[]),p===null)){$.debug(`Dropping session-reload lick with empty mount-recovery list`);return}}p===null&&(p=`[${f}: ${o}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``);let m={id:l,chatJid:d.jid,senderId:c,senderName:`${c}:${o}`,content:p,timestamp:e.timestamp,fromAssistant:!1,channel:c},h=Date.now();if(S(d.jid).push({id:l,role:`user`,content:p,timestamp:h,source:`lick`,channel:c}),g?.jid===d.jid)u.panels.chat.addLickMessage(l,p,c,h);else{let e=d.isCone?`session-cone`:`session-${d.folder}`;u.panels.chat.persistLickToSession(e,{id:l,content:p,channel:c,timestamp:h})}$.info(`Routing lick to scoop`,{type:c,name:o,scoopJid:d.jid}),w.handleMessage(m)}else $.warn(`Lick target scoop not found`,{targetScoop:e.targetScoop})};j.setEventHandler(te);let re=new V(p.getTransport(),e=>{j.emitEvent({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:new Date().toISOString(),body:{url:e.url,sliccHeader:e.sliccHeader,title:e.title}})});(async()=>{try{await p.connect(),await re.start(),$.info(`Navigation watcher started`)}catch(e){$.warn(`Failed to start navigation watcher`,{error:e instanceof Error?e.message:String(e)})}})(),T&&F().then(async e=>{if(e.length===0)return;let{needsRecovery:t}=await dC(e,T,$);t.length!==0&&te({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:t}})}).catch(e=>$.warn(`Failed to restore persisted mounts`,e)),u.panels.chat.onInlineSprinkleLick=(e,t)=>{te({type:`sprinkle`,sprinkleName:`inline`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:e,data:t}})};let M=null;if(T){if(M=new uC(T,te,{addSprinkle:(e,t,n,r)=>u.addSprinkle(e,t,n,r),removeSprinkle:e=>u.removeSprinkle(e)},()=>{let e=w.getScoops().find(e=>e.isCone);e&&(w.stopScoop(e.jid),w.clearQueuedMessages(e.jid).catch(e=>{$.error(`Failed to clear queued messages on sprinkle stopCone`,{error:e instanceof Error?e.message:String(e)})}))}),window.__slicc_sprinkleManager=M,window.__slicc_reloadSkills=()=>w.reloadAllSkills(),await M.refresh(),u.onSprinkleClose=e=>M.close(e),u.getAvailableSprinkles=()=>{let e=new Set(M.opened());return M.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},u.onOpenSprinkle=(e,t)=>M.open(e,t),u.updateAddButtons(),!await T.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await T.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await T.exists(`/shared/.welcomed`)&&!r&&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=QS(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:j.listWebhooks()};break;case`create_webhook`:{let t=await j.createWebhook(n.name||`default`,n.scoop,n.filter),r=uh().session,i=r?.webhookUrl?eC(r.webhookUrl,t.id):$S(window.location.href,t.id);e={type:`response`,requestId:n.requestId,data:{...t,url:i}};break}case`delete_webhook`:e=await j.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:j.listCronTasks()};break;case`create_crontask`:{if(!n.name)throw Error(`name is required`);if(!n.cron)throw Error(`cron is required`);let t=await j.createCronTask(n.name,n.cron,n.scoop,n.filter);e={type:`response`,requestId:n.requestId,data:t};break}case`delete_crontask`:e=await j.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=uh();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}if(n.type===`webhook_event`&&j.handleWebhookEvent(n.webhookId,n.headers,n.body),n.type===`navigate_event`){let e=typeof n.sliccHeader==`string`?n.sliccHeader:``,t=typeof n.url==`string`&&n.url.length>0?n.url:``;e&&t&&j.emitEvent({type:`navigate`,navigateUrl:t,targetScoop:void 0,timestamp:typeof n.timestamp==`string`?n.timestamp:new Date().toISOString(),body:{url:t,sliccHeader:e,title:typeof n.title==`string`?n.title:void 0}})}}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(),u.onModelChange=e=>{localStorage.setItem(`selected-model`,e),w.updateModel()};let P=new Set;u.onClearChat=async()=>{await w.clearAllMessages(),y.clear(),P.clear()},u.onClearFilesystem=async()=>{await w.resetFilesystem()};let ie=async e=>{$.info(`Scoop selected`,{jid:e.jid,name:e.name}),g=e,w.createScoopTab(e.jid),u.panels.memory.setSelectedScoop(e.jid),u.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=y.get(e.jid),r=!P.has(e.jid),i=e.isCone?void 0:e.name;if(!r&&n&&n.length>0)await u.panels.chat.switchToContext(t,!e.isCone,i),u.panels.chat.loadMessages(n);else{if(await u.panels.chat.switchToContext(t,!e.isCone,i),u.panels.chat.getMessages().length===0){let t=await w.getMessagesForScoop(e.jid);for(let e of t){let t=e.channel===`delegation`;vC(e.channel)?u.panels.chat.addLickMessage(e.id,e.content,e.channel,new Date(e.timestamp).getTime()):t?u.panels.chat.addUserMessage(`**[Instructions from sliccy]**\n\n${e.content}`):e.fromAssistant?(h({type:`message_start`,messageId:e.id}),h({type:`content_delta`,messageId:e.id,text:e.content}),h({type:`content_done`,messageId:e.id})):u.panels.chat.addUserMessage(e.content)}}let n=u.panels.chat.getMessages(),r=new Set(n.map(e=>e.id)),a=S(e.jid),o=a.filter(e=>!r.has(e.id));a.length=0,a.push(...n,...o),o.length>0&&u.panels.chat.loadMessages(a)}e.isCone&&w.isProcessing(e.jid)&&u.panels.chat.setProcessing(!0),P.add(e.jid)};if(u.onScoopSelect=ie,g&&(w.createScoopTab(g.jid),await ie(g)),yC()&&await bC(u.panels.chat),s===`standalone`||s===`electron-overlay`){let e=await a(),t=YS(s,e!==null)?c:null,n=await _({locationHref:window.location.href,storage:window.localStorage,envBaseUrl:null,defaultWorkerBaseUrl:t,runtimeConfigFetcher:async()=>e}),r=null,i=null,o=null;__(()=>k?(e,t)=>k.sendFsRequest(e,t):r?(e,t)=>r.sendFsRequest(e,t):null),im(()=>k?()=>k.getBestFollowerForTeleport():null),am(()=>k?()=>k.getConnectedFollowers():null);let l=e=>{o&&=(clearInterval(o),null),r?.close();let t=`follower-${e.bootstrapId}`,n=new qS(e.channel,{browserTransport:p.getTransport(),browserAPI:p,onSnapshot:e=>{u.panels.chat.loadMessages(e)},onUserMessage:e=>{u.panels.chat.addUserMessage(e)},onStatus:e=>{u.panels.chat.setProcessing(e===`processing`)},onTargetsChanged:()=>void i()});r=n,p.setTrayTargetProvider(n),u.panels.chat.setAgent(n),n.requestSnapshot();let i=async()=>{try{let e=await p.listPages();n.advertiseTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})),t)}catch{}};o=setInterval(i,5e3),i(),$.info(`Follower sync wired to chat panel`,{trayId:e.trayId})},d=e=>{i?.cancel(),o&&=(clearInterval(o),null),r?.close(),r=null,i=xS({joinUrl:e,runtime:`slicc-standalone`,fetchImpl:vh()},{onConnected:e=>l(e),onReconnecting:e=>{$.info(`Follower reconnecting`,{attempt:e})},onGaveUp:e=>{$.warn(`Follower reconnect gave up`,{lastError:e})}})};if(window.addEventListener(`slicc:tray-join`,(e=>{d(e.detail.joinUrl)})),window.addEventListener(`beforeunload`,()=>{o&&clearInterval(o),r?.close(),i?.cancel()},{once:!0}),n?.joinUrl)d(n.joinUrl);else if(n?.workerBaseUrl){let e,t,r,i,a=()=>{t=new GS({browserTransport:p.getTransport(),browserAPI:p,getMessages:()=>u.panels.chat.getMessages(),getScoopJid:()=>g?.jid??`cone`,onFollowerMessage:(e,t)=>{u.panels.chat.addUserMessage(e),A.sendMessage(e,t)},onFollowerAbort:()=>{A.stop()}}),k=t,bh(()=>t.getConnectedFollowers()),p.setTrayTargetProvider(t),i&&clearInterval(i);let n=async()=>{try{let e=await p.listPages();t.setLocalTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})))}catch{}};i=setInterval(n,5e3),n(),r=new yS({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 mh({workerBaseUrl:n.workerBaseUrl,runtime:`slicc-standalone`,fetchImpl:vh(),onControlMessage:e=>{if(e.type===`webhook.event`){j.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)})})}}),Ch(async()=>{t.stop(),r.stop(),e.stop(),await e.clearSession();let n=await e.start(),i=f(window.location.href,n.workerBaseUrl,n.trayId);return i!==window.location.href&&window.history.replaceState(window.history.state,``,i),a(),uh()}),e.start().then(e=>{let t=f(window.location.href,e.workerBaseUrl,e.trayId);t!==window.location.href&&window.history.replaceState(window.history.state,``,t)}).catch(e=>{$.warn(`Leader tray join failed`,{error:e instanceof Error?e.message:String(e)})}),window.addEventListener(`beforeunload`,()=>{clearInterval(i),t.stop(),r.stop(),e.stop()},{once:!0})}}$.info(`Orchestrator initialized — cone+scoops ready`,{scoopCount:w.getScoops().length}),db().catch(()=>{})}OC().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{Qs as t};