sliccy 1.55.2 → 1.55.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/ui/assets/{anthropic-Ctm13Y4z.js → anthropic-Boy3af-y.js} +1 -1
- package/dist/ui/assets/{azure-openai-responses-C0Fcf6OA.js → azure-openai-responses-G5rlwrl5.js} +1 -1
- package/dist/ui/assets/bsh-watchdog-BaiyTJC8.js +42 -0
- package/dist/ui/assets/{fs-BAlzVbQY.js → fs-udwNbj6g.js} +1 -1
- package/dist/ui/assets/{google-D_JFv6N-.js → google-CiqbbNbH.js} +1 -1
- package/dist/ui/assets/{google-gemini-cli-BjwSjH_H.js → google-gemini-cli-3AIzUCEY.js} +1 -1
- package/dist/ui/assets/{google-shared-1MEdugC3.js → google-shared-BQIq1jLR.js} +1 -1
- package/dist/ui/assets/{google-vertex-MzEI1-me.js → google-vertex-CYEauGk8.js} +1 -1
- package/dist/ui/assets/{index-l6Ye92eW.js → index-C2ORW6FF.js} +46 -45
- package/dist/ui/assets/lick-manager-SqoZzrt5.js +1 -0
- package/dist/ui/assets/{mistral-DcpebUMg.js → mistral-DlH9JH9-.js} +1 -1
- package/dist/ui/assets/openai-codex-responses-BAgPA0HP.js +7 -0
- package/dist/ui/assets/{openai-completions-CTyIshQV.js → openai-completions-CD0ojk0e.js} +1 -1
- package/dist/ui/assets/{openai-responses-DEGSelVp.js → openai-responses-CUf4U6xB.js} +1 -1
- package/dist/ui/assets/{openai-responses-shared-DQA10qMf.js → openai-responses-shared-DcVKlc8e.js} +1 -1
- package/dist/ui/assets/{provider-settings-ZCf9cqx-.js → provider-settings-B3VwS5n4.js} +2 -2
- package/dist/ui/assets/{provider-settings-ZR6mRmU_.js → provider-settings-DtthfIx_.js} +1 -1
- package/dist/ui/assets/providers-CBTIfSNw.js +1 -0
- package/dist/ui/assets/secret-env-C4IwrDk1.js +1 -0
- package/dist/ui/assets/shell-BvugiBi7.js +1 -0
- package/dist/ui/assets/{simple-options-FPdEz6rB.js → simple-options-DZXt61Q2.js} +1 -1
- package/dist/ui/assets/{skills-1dwuOQLz.js → skills-BQCgGxAq.js} +1 -1
- package/dist/ui/assets/{skills-Ojk3qFM4.js → skills-BU359a2n.js} +1 -1
- package/dist/ui/assets/sprinkle-renderer-Ci3F_XSt.js +1 -0
- package/dist/ui/index.html +5 -5
- package/dist/ui/packages/webapp/index.html +5 -5
- package/package.json +1 -1
- package/dist/ui/assets/bsh-watchdog-Dfc2Sii6.js +0 -43
- package/dist/ui/assets/lick-manager-CjiK3pMV.js +0 -1
- package/dist/ui/assets/openai-codex-responses-g4roCtlP.js +0 -7
- package/dist/ui/assets/providers-B1EDWfDV.js +0 -1
- package/dist/ui/assets/secret-env-CZ1iNnfN.js +0 -1
- package/dist/ui/assets/shell-CEWm93pE.js +0 -1
- package/dist/ui/assets/sprinkle-renderer-CoVBjTaw.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/sql-wasm-Cx-UtEsl.js","assets/chunk-zsgVPwQN.js","assets/__vite-browser-external-fVHSRdZ9.js","assets/pyodide-CDyS-YOW.js","assets/preload-helper-ca-nBW7U.js","assets/es-DlWKrNhH.js","assets/pako-djzWUVJp.js","assets/dist-B3JYrjq2.js","assets/provider-settings-
|
|
2
|
-
import{o as e,t}from"./chunk-zsgVPwQN.js";import{t as n}from"./logger-B-No_qN_.js";import{c as r,f as i,h as a,i as o,l as s,m as c,n as l,o as u,p as d,r as f,s as p,t as m,u as h,v as g,y as _}from"./tray-follower-status-BlQSlF6m.js";import{t as v}from"./preload-helper-ca-nBW7U.js";import{A as y,M as b,N as x,S,T as C,b as w,c as T,g as E,j as D,k as O,n as k,o as ee,r as A,s as j,v as te,w as ne,x as re,y as ie}from"./provider-settings-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/sql-wasm-Cx-UtEsl.js","assets/chunk-zsgVPwQN.js","assets/__vite-browser-external-fVHSRdZ9.js","assets/pyodide-CDyS-YOW.js","assets/preload-helper-ca-nBW7U.js","assets/es-DlWKrNhH.js","assets/pako-djzWUVJp.js","assets/dist-B3JYrjq2.js","assets/provider-settings-DtthfIx_.js","assets/provider-settings-B3VwS5n4.js","assets/env-api-keys-DlVZ9FrG.js","assets/simple-options-DZXt61Q2.js","assets/json-parse-JW3qhabb.js","assets/openai-Cn7eGqwa.js","assets/tray-follower-status-BlQSlF6m.js","assets/logger-B-No_qN_.js","assets/providers-CBTIfSNw.js","assets/skills-BQCgGxAq.js","assets/constants-Dqhmtsws.js","assets/skills-BU359a2n.js","assets/fs-udwNbj6g.js","assets/xterm-BmfB5bmM.css","assets/offscreen-client-BIdj4gf1.js","assets/cdp-B4yzwpE0.js","assets/cost-command-Bipyal__.js","assets/bsh-watchdog-BaiyTJC8.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{o as e,t}from"./chunk-zsgVPwQN.js";import{t as n}from"./logger-B-No_qN_.js";import{c as r,f as i,h as a,i as o,l as s,m as c,n as l,o as u,p as d,r as f,s as p,t as m,u as h,v as g,y as _}from"./tray-follower-status-BlQSlF6m.js";import{t as v}from"./preload-helper-ca-nBW7U.js";import{A as y,M as b,N as x,S,T as C,b as w,c as T,g as E,j as D,k as O,n as k,o as ee,r as A,s as j,v as te,w as ne,x as re,y as ie}from"./provider-settings-B3VwS5n4.js";import{f as M,l as N,p as P,s as ae,u as F}from"./constants-Dqhmtsws.js";import{a as oe,c as I,i as L,n as se,o as R,r as ce}from"./fs-udwNbj6g.js";import{d as le,n as ue}from"./skills-BU359a2n.js";import{a as de,c as fe,d as pe,i as me,l as he,n as ge,o as _e,r as ve,s as ye,u as be}from"./cdp-B4yzwpE0.js";import{_ as xe,a as Se,b as Ce,c as we,d as Te,f as Ee,g as De,h as Oe,i as ke,l as Ae,m as je,n as Me,o as Ne,p as Pe,r as Fe,s as Ie,t as Le,u as Re,v as ze,x as Be,y as Ve}from"./db-QbwB670D.js";import{a as He,i as z,n as Ue,o as We,r as Ge,s as Ke}from"./cost-command-Bipyal__.js";import{t as qe}from"./pako-djzWUVJp.js";import{t as Je}from"./magick-wasm-cJ5msdlA.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function Ye(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Xe=Ye();function Ze(e){Xe=e}var Qe={exec:()=>null};function B(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(et.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var $e=(()=>{try{return!0}catch{return!1}})(),et={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)}}>`)},tt=/^(?:[ \t]*(?:\n|$))+/,nt=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,rt=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,it=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,at=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ot=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,st=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ct=B(st).replace(/bull/g,ot).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(),lt=B(st).replace(/bull/g,ot).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(),ut=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,dt=/^[^\n]+/,ft=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,pt=B(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,ft).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),mt=B(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,ot).getRegex(),ht=`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`,gt=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,_t=B(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,gt).replace(`tag`,ht).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),vt=B(ut).replace(`hr`,it).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`,ht).getRegex(),yt={blockquote:B(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,vt).getRegex(),code:nt,def:pt,fences:rt,heading:at,hr:it,html:_t,lheading:ct,list:mt,newline:tt,paragraph:vt,table:Qe,text:dt},bt=B(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,it).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`,ht).getRegex(),xt={...yt,lheading:lt,table:bt,paragraph:B(ut).replace(`hr`,it).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,bt).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`,ht).getRegex()},St={...yt,html:B(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,gt).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:Qe,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:B(ut).replace(`hr`,it).replace(`heading`,` *#{1,6} *[^
|
|
3
3
|
]`).replace(`lheading`,ct).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},Ct=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,wt=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Tt=/^( {2,}|\\)\n(?!\s*$)/,Et=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Dt=/[\p{P}\p{S}]/u,Ot=/[\s\p{P}\p{S}]/u,kt=/[^\s\p{P}\p{S}]/u,At=B(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,Ot).getRegex(),jt=/(?!~)[\p{P}\p{S}]/u,Mt=/(?!~)[\s\p{P}\p{S}]/u,Nt=/(?:[^\s\p{P}\p{S}]|~)/u,Pt=B(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,$e?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),Ft=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,It=B(Ft,`u`).replace(/punct/g,Dt).getRegex(),Lt=B(Ft,`u`).replace(/punct/g,jt).getRegex(),Rt=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,zt=B(Rt,`gu`).replace(/notPunctSpace/g,kt).replace(/punctSpace/g,Ot).replace(/punct/g,Dt).getRegex(),Bt=B(Rt,`gu`).replace(/notPunctSpace/g,Nt).replace(/punctSpace/g,Mt).replace(/punct/g,jt).getRegex(),Vt=B(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,kt).replace(/punctSpace/g,Ot).replace(/punct/g,Dt).getRegex(),Ht=B(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,Dt).getRegex(),Ut=B(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,kt).replace(/punctSpace/g,Ot).replace(/punct/g,Dt).getRegex(),Wt=B(/\\(punct)/,`gu`).replace(/punct/g,Dt).getRegex(),Gt=B(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Kt=B(gt).replace(`(?:-->|$)`,`-->`).getRegex(),qt=B(`^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,Kt).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Jt=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Yt=B(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,Jt).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Xt=B(/^!?\[(label)\]\[(ref)\]/).replace(`label`,Jt).replace(`ref`,ft).getRegex(),Zt=B(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,ft).getRegex(),Qt=B(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,Xt).replace(`nolink`,Zt).getRegex(),$t=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,en={_backpedal:Qe,anyPunctuation:Wt,autolink:Gt,blockSkip:Pt,br:Tt,code:wt,del:Qe,delLDelim:Qe,delRDelim:Qe,emStrongLDelim:It,emStrongRDelimAst:zt,emStrongRDelimUnd:Vt,escape:Ct,link:Yt,nolink:Zt,punctuation:At,reflink:Xt,reflinkSearch:Qt,tag:qt,text:Et,url:Qe},tn={...en,link:B(/^!?\[(label)\]\((.*?)\)/).replace(`label`,Jt).getRegex(),reflink:B(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,Jt).getRegex()},nn={...en,emStrongRDelimAst:Bt,emStrongLDelim:Lt,delLDelim:Ht,delRDelim:Ut,url:B(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,$t).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:B(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,$t).getRegex()},rn={...nn,br:B(Tt).replace(`{2,}`,`*`).getRegex(),text:B(nn.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},an={normal:yt,gfm:xt,pedantic:St},on={normal:en,gfm:nn,breaks:rn,pedantic:tn},sn={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},cn=e=>sn[e];function ln(e,t){if(t){if(et.escapeTest.test(e))return e.replace(et.escapeReplace,cn)}else if(et.escapeTestNoEncode.test(e))return e.replace(et.escapeReplaceNoEncode,cn);return e}function un(e){try{e=encodeURI(e).replace(et.percentDecode,`%`)}catch{return null}return e}function dn(e,t){let n=e.replace(et.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(et.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(et.slashPipe,`|`);return n}function fn(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 pn(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 mn(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 hn(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 gn(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 _n(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
@@ -236,7 +236,7 @@ mark{background:color-mix(in srgb,var(--s2-accent) 25%,transparent);color:inheri
|
|
|
236
236
|
</style>
|
|
237
237
|
<script>${ci}<\/script>
|
|
238
238
|
</head>
|
|
239
|
-
<body class="sprinkle-inline">${t}</body></html>`;if(si)return fi(e,r,n);let i=document.createElement(`iframe`);i.setAttribute(`sandbox`,`allow-scripts allow-same-origin`),i.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,i.srcdoc=r,e.appendChild(i);let a=e=>{if(e.source!==i.contentWindow)return;let t=e.data;t?.type&&(t.type===`inline-sprinkle-lick`?n(t.action,t.data):t.type===`inline-sprinkle-height`&&(i.style.height=t.height+`px`))};return window.addEventListener(`message`,a),{dispose(){window.removeEventListener(`message`,a),i.remove()}}}function ui(e,t){let n=e.querySelectorAll(`pre > code.language-shtml`);if(n.length===0)return[];let r=[];for(let e of n){let n=e.parentElement,i=e.textContent??``,a=document.createElement(`div`);a.className=`msg__inline-sprinkle`,n.replaceWith(a),r.push(li(a,i,t))}return r}function di(e){for(let t of e)try{t.dispose()}catch{}e.length=0}function fi(e,t,n){let r=document.createElement(`iframe`);r.src=chrome.runtime.getURL(`sprinkle-sandbox.html`),r.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,e.appendChild(r);let i=e=>{if(e.source!==r.contentWindow)return;let t=e.data;t?.type&&(t.type===`inline-sprinkle-lick`?n(t.action,t.data):t.type===`inline-sprinkle-height`&&(r.style.height=t.height+`px`))};return window.addEventListener(`message`,i),r.addEventListener(`load`,()=>{r.contentWindow?.postMessage({type:`inline-sprinkle-render`,srcdoc:t},`*`)},{once:!0}),{dispose(){window.removeEventListener(`message`,i),r.remove()}}}var pi=n(`tool-ui-renderer`),mi=typeof chrome<`u`&&!!chrome?.runtime?.id,hi=class{container;iframe=null;inlineSprinkle=null;messageHandler=null;requestId;nonce;constructor(e,t){this.container=e,this.requestId=t,this.nonce=crypto.randomUUID()}async render(e){mi?await this.renderInSandbox(e):this.renderWithInlineSprinkle(e)}async renderInSandbox(e){let t=document.createElement(`iframe`);t.src=chrome.runtime.getURL(`tool-ui-sandbox.html`),t.style.cssText=`width: 100%; border: none; min-height: 60px;`,this.iframe=t,await new Promise((e,n)=>{let r=setTimeout(()=>{pi.error(`Tool UI iframe load timed out`),t.remove(),this.iframe=null,n(Error(`tool-ui sandbox iframe load timed out`))},5e3);t.addEventListener(`load`,()=>{clearTimeout(r),e()},{once:!0}),t.addEventListener(`error`,()=>{clearTimeout(r),t.remove(),this.iframe=null,n(Error(`tool-ui sandbox iframe failed to load`))},{once:!0}),this.container.appendChild(t)}),this.messageHandler=e=>{if(e.source!==t.contentWindow)return;let n=e.data;if(n?.type){if(n.nonce!==this.nonce){pi.warn(`Tool UI message nonce mismatch`,{expected:this.nonce,received:n.nonce});return}n.type===`tool-ui-action`&&n.id===this.requestId?(pi.info(`Tool UI action received`,{id:n.id,action:n.action}),_.handleAction(n.id,{action:n.action,data:n.data})):n.type===`tool-ui-rendered`&&n.id===this.requestId?n.height&&this.iframe&&(this.iframe.style.height=`${Math.max(60,n.height)}px`):n.type===`tool-ui-resize`&&n.id===this.requestId&&n.height&&this.iframe&&(this.iframe.style.height=`${Math.max(60,n.height)}px`)}},window.addEventListener(`message`,this.messageHandler);let{collectThemeCSS:n}=await v(async()=>{let{collectThemeCSS:e}=await import(`./sprinkle-renderer-CoVBjTaw.js`);return{collectThemeCSS:e}},[]),r=n();t.contentWindow.postMessage({type:`tool-ui-render`,id:this.requestId,nonce:this.nonce,html:e,themeCSS:r},`*`)}renderWithInlineSprinkle(e){let t=document.createElement(`div`);t.className=`msg__inline-sprinkle`,this.container.appendChild(t),this.inlineSprinkle=li(t,e,(e,t)=>{pi.info(`Tool UI action (inline sprinkle)`,{id:this.requestId,action:e}),_.handleAction(this.requestId,{action:e,data:t})})}dispose(){this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.iframe&&=(this.iframe.remove(),null),this.inlineSprinkle&&=(this.inlineSprinkle.dispose(),null)}},gi=new Map;function _i(e,t,n){let r=gi.get(t);r&&r.dispose();let i=new hi(e,t);return gi.set(t,i),i.render(n).catch(e=>{pi.error(`Failed to render tool UI`,{requestId:t,error:e.message})}),i}function vi(e){let t=gi.get(e);t&&(t.dispose(),gi.delete(e))}var yi=n(`chat-panel`);function bi(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var xi={bash:`$`,browser:`B`,read_file:`R`,write_file:`W`,edit_file:`E`,javascript:`JS`,delegate_to_scoop:`D`,send_message:`M`,schedule_task:`T`,list_scoops:`LS`,list_tasks:`LT`,register_scoop:`RS`,update_global_memory:`GM`};function Si(e){return xi[e]??`?`}function Ci(e){return e.role===`assistant`?Ur(e.content):Hr(e.content)}var wi=class{container;messagesEl;messagesInner;inputArea;textarea;sendBtn;stopBtn;micBtn;voiceInput=null;voiceMode=!1;keydownListener=null;messages=[];agent=null;unsubscribe=null;isStreaming=!1;currentStreamId=null;sessionStore;sessionId;readOnly=!1;terminalOutputCallback=null;currentScoopName=null;autoScrollAttached=!0;lastScrollTop=0;jumpPill;onDeleteQueuedMessage=null;pendingDeltaText=``;streamingRafId=null;inlineSprinkles=new Map;onInlineSprinkleLick;modelSelectorEl;handoffsEl;pendingHandoffs=[];onAcceptPendingHandoff=null;onDismissPendingHandoff=null;onModelChange;constructor(e){this.container=e,this.sessionStore=new Yr,this.sessionId=`default`,this.render()}setAgent(e){this.unsubscribe?.(),this.agent=e,this.unsubscribe=e.onEvent(e=>this.handleAgentEvent(e))}onTerminalOutput(e){this.terminalOutputCallback=e}setDeleteQueuedMessageCallback(e){this.onDeleteQueuedMessage=e}async initSession(e){await this.sessionStore.init(),this.sessionId=e??`default`;let t=await this.sessionStore.load(this.sessionId);t&&t.messages.length>0&&(this.messages=t.messages.map(e=>({...e,isStreaming:!1})),this.renderMessages())}async clearSession(){this.messages=[],this.renderMessages(),await this.sessionStore.delete(this.sessionId)}async deleteSessionById(e){await this.sessionStore.delete(e)}async switchToContext(e,t,n){await this.persistSessionAsync(),this.setStreamingState(!1),this.currentStreamId=null,this.cancelPendingDelta(),this.sessionId=e,this.currentScoopName=n??null,this.setReadOnly(t);let r=await this.sessionStore.load(this.sessionId);r&&r.messages.length>0?this.messages=r.messages.map(e=>({...e,isStreaming:!1})):this.messages=[],this.renderMessages()}setReadOnly(e){this.readOnly=e,this.inputArea&&(this.inputArea.style.display=e?`none`:``)}async persistSessionAsync(){try{await this.sessionStore.saveMessages(this.sessionId,this.messages)}catch{}}setProcessing(e){e?this.setStreamingState(!0):this.setStreamingState(!1)}addSystemMessage(e){let t={id:bi(),role:`assistant`,content:e,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t),this.persistSession()}addLickMessage(e,t,n){let r={id:e,role:`user`,content:t,timestamp:Date.now(),source:`lick`,channel:n};this.messages.push(r),this.appendMessageEl(r),this.persistSession()}getMessages(){return[...this.messages]}loadMessages(e){this.messages=e.map(e=>({...e,isStreaming:!1})),this.renderMessages(),this.persistSession(),this.renderModelSelector()}clear(){this.messages=[],this.renderMessages(),this.renderModelSelector()}setPendingHandoffs(e){this.pendingHandoffs=[...e],this.renderPendingHandoffs()}setPendingHandoffActions(e){this.onAcceptPendingHandoff=e.onAccept,this.onDismissPendingHandoff=e.onDismiss,this.renderPendingHandoffs()}addUserMessage(e){let t={id:bi(),role:`user`,content:e,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t)}deleteQueuedMessage(e){let t=this.messages.findIndex(t=>t.id===e);if(t===-1)return;this.messages.splice(t,1);let n=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);n&&n.remove(),this.persistSession(),this.onDeleteQueuedMessage?.(e)}render(){this.container.innerHTML=``,this.container.classList.add(`chat`),this.messagesEl=document.createElement(`div`),this.messagesEl.className=`chat__messages`,this.messagesInner=document.createElement(`div`),this.messagesInner.className=`chat__messages-inner`,this.messagesEl.appendChild(this.messagesInner),this.handoffsEl=document.createElement(`div`),this.handoffsEl.className=`chat__handoffs`,this.handoffsEl.hidden=!0,this.messagesEl.appendChild(this.handoffsEl),this.container.appendChild(this.messagesEl),this.renderPendingHandoffs(),this.messagesEl.addEventListener(`scroll`,()=>{let{scrollTop:e,scrollHeight:t,clientHeight:n}=this.messagesEl;t-e-n<=250?(this.autoScrollAttached=!0,this.hideJumpPill()):e<this.lastScrollTop&&(this.autoScrollAttached=!1),this.lastScrollTop=e},{passive:!0}),this.inputArea=document.createElement(`div`);let e=this.inputArea;e.className=`chat__input-area`;let t=document.createElement(`div`);t.className=`chat__input-area-inner`,this.textarea=document.createElement(`textarea`),this.textarea.className=`chat__textarea`,this.textarea.placeholder=`What shall we build?`,this.textarea.rows=1,this.sendBtn=document.createElement(`button`),this.sendBtn.className=`chat__send-btn`,this.sendBtn.innerHTML=`<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M10 1.25C5.167 1.25 1.25 5.167 1.25 10s3.917 8.75 8.75 8.75 8.75-3.918 8.75-8.75S14.833 1.25 10 1.25zm3.527 8.284a.75.75 0 0 1-1.06 0L10.75 7.82v6.172a.75.75 0 0 1-1.5 0V7.812L7.527 9.534a.75.75 0 1 1-1.06-1.06l2.998-2.998a.75.75 0 0 1 1.06-.001l3.002 2.998a.75.75 0 0 1 0 1.061z"/></svg>`,this.sendBtn.dataset.tooltip=`Send message`,this.sendBtn.dataset.tooltipPos=`top`,this.stopBtn=document.createElement(`button`),this.stopBtn.className=`chat__stop-btn`,this.stopBtn.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M13.75 4H6.25A2.25 2.25 0 0 0 4 6.25v7.5A2.25 2.25 0 0 0 6.25 16h7.5A2.25 2.25 0 0 0 16 13.75v-7.5A2.25 2.25 0 0 0 13.75 4z"/></svg>`,this.stopBtn.dataset.tooltip=`Stop generation`,this.stopBtn.style.display=`none`,this.micBtn=document.createElement(`button`),this.micBtn.className=`chat__mic-btn`;let n=`http://www.w3.org/2000/svg`,r=document.createElementNS(n,`svg`);r.setAttribute(`width`,`16`),r.setAttribute(`height`,`16`),r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`2`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`);let i=document.createElementNS(n,`path`);i.setAttribute(`d`,`M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z`);let a=document.createElementNS(n,`path`);a.setAttribute(`d`,`M19 10v2a7 7 0 0 1-14 0v-2`);let o=document.createElementNS(n,`line`);o.setAttribute(`x1`,`12`),o.setAttribute(`y1`,`19`),o.setAttribute(`x2`,`12`),o.setAttribute(`y2`,`23`);let s=document.createElementNS(n,`line`);s.setAttribute(`x1`,`8`),s.setAttribute(`y1`,`23`),s.setAttribute(`x2`,`16`),s.setAttribute(`y2`,`23`),r.append(i,a,o,s),this.micBtn.appendChild(r),this.micBtn.dataset.tooltip=`Voice (Ctrl+Shift+V)`;let c=document.createElement(`div`);c.className=`chat__input-wrapper`,c.appendChild(this.textarea);let l=document.createElement(`div`);l.className=`chat__action-bar`;let u=document.createElement(`div`);u.className=`chat__action-bar-left`,u.appendChild(this.micBtn),l.appendChild(u),this.modelSelectorEl=document.createElement(`div`),this.modelSelectorEl.className=`chat__model-selector`,this.renderModelSelector(),l.appendChild(this.modelSelectorEl);let d=document.createElement(`div`);d.className=`chat__action-bar-right`,d.appendChild(this.sendBtn),d.appendChild(this.stopBtn),l.appendChild(d),c.appendChild(l),t.appendChild(c),e.appendChild(t),this.container.appendChild(e),this.jumpPill=document.createElement(`button`),this.jumpPill.className=`chat__jump-pill`,this.jumpPill.textContent=`↓ New activity`,this.jumpPill.addEventListener(`click`,()=>{this.autoScrollAttached=!0,this.hideJumpPill(),this.scrollToBottom(!0)}),this.container.appendChild(this.jumpPill),this.textarea.addEventListener(`keydown`,e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.sendMessage())}),this.textarea.addEventListener(`input`,()=>{this.textarea.style.height=`auto`,this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+`px`}),this.sendBtn.addEventListener(`click`,()=>this.sendMessage()),this.stopBtn.addEventListener(`click`,()=>{this.agent?.stop();for(let e of this.messages)e.queued&&(e.queued=!1,this.updateMessageEl(e.id));this.setStreamingState(!1)}),this.voiceInput=new $r({onTranscript:(e,t)=>{this.textarea.value=e,this.textarea.style.height=`auto`,this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+`px`},onStateChange:e=>{e===`error`?(this.voiceMode=!1,this.micBtn.classList.remove(`chat__mic-btn--active`,`chat__mic-btn--listening`)):this.voiceMode?e===`listening`&&this.micBtn.classList.add(`chat__mic-btn--listening`):this.micBtn.classList.toggle(`chat__mic-btn--listening`,e===`listening`)},onError:e=>{yi.debug(`Voice input error`,{error:e}),!(this.voiceMode&&e.includes(`No speech detected`))&&this.addSystemMessage(e)},autoSend:!0,onAutoSend:e=>{this.textarea.value=e,this.sendMessage()},onAutoDisable:()=>{this.voiceMode=!1,this.micBtn.classList.remove(`chat__mic-btn--active`,`chat__mic-btn--listening`),this.addSystemMessage(`Voice mode disabled after 2 minutes of inactivity.`)},lang:ti()}),this.micBtn.addEventListener(`click`,()=>{this.toggleVoiceMode()}),this.keydownListener=e=>{e.shiftKey&&(e.ctrlKey||e.metaKey)&&e.key===`V`&&(e.preventDefault(),this.toggleVoiceMode())},document.addEventListener(`keydown`,this.keydownListener)}renderPendingHandoffs(){if(!this.handoffsEl)return;if(this.pendingHandoffs.length===0){this.handoffsEl.hidden=!0,this.handoffsEl.innerHTML=``;return}let e=this.pendingHandoffs.length===1?`1 pending handoff`:`${this.pendingHandoffs.length} pending handoffs`;this.handoffsEl.hidden=!1,this.handoffsEl.innerHTML=`
|
|
239
|
+
<body class="sprinkle-inline">${t}</body></html>`;if(si)return fi(e,r,n);let i=document.createElement(`iframe`);i.setAttribute(`sandbox`,`allow-scripts allow-same-origin`),i.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,i.srcdoc=r,e.appendChild(i);let a=e=>{if(e.source!==i.contentWindow)return;let t=e.data;t?.type&&(t.type===`inline-sprinkle-lick`?n(t.action,t.data):t.type===`inline-sprinkle-height`&&(i.style.height=t.height+`px`))};return window.addEventListener(`message`,a),{dispose(){window.removeEventListener(`message`,a),i.remove()}}}function ui(e,t){let n=e.querySelectorAll(`pre > code.language-shtml`);if(n.length===0)return[];let r=[];for(let e of n){let n=e.parentElement,i=e.textContent??``,a=document.createElement(`div`);a.className=`msg__inline-sprinkle`,n.replaceWith(a),r.push(li(a,i,t))}return r}function di(e){for(let t of e)try{t.dispose()}catch{}e.length=0}function fi(e,t,n){let r=document.createElement(`iframe`);r.src=chrome.runtime.getURL(`sprinkle-sandbox.html`),r.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,e.appendChild(r);let i=e=>{if(e.source!==r.contentWindow)return;let t=e.data;t?.type&&(t.type===`inline-sprinkle-lick`?n(t.action,t.data):t.type===`inline-sprinkle-height`&&(r.style.height=t.height+`px`))};return window.addEventListener(`message`,i),r.addEventListener(`load`,()=>{r.contentWindow?.postMessage({type:`inline-sprinkle-render`,srcdoc:t},`*`)},{once:!0}),{dispose(){window.removeEventListener(`message`,i),r.remove()}}}var pi=n(`tool-ui-renderer`),mi=typeof chrome<`u`&&!!chrome?.runtime?.id,hi=class{container;iframe=null;inlineSprinkle=null;messageHandler=null;requestId;nonce;constructor(e,t){this.container=e,this.requestId=t,this.nonce=crypto.randomUUID()}async render(e){mi?await this.renderInSandbox(e):this.renderWithInlineSprinkle(e)}async renderInSandbox(e){let t=document.createElement(`iframe`);t.src=chrome.runtime.getURL(`tool-ui-sandbox.html`),t.style.cssText=`width: 100%; border: none; min-height: 60px;`,this.iframe=t,await new Promise((e,n)=>{let r=setTimeout(()=>{pi.error(`Tool UI iframe load timed out`),t.remove(),this.iframe=null,n(Error(`tool-ui sandbox iframe load timed out`))},5e3);t.addEventListener(`load`,()=>{clearTimeout(r),e()},{once:!0}),t.addEventListener(`error`,()=>{clearTimeout(r),t.remove(),this.iframe=null,n(Error(`tool-ui sandbox iframe failed to load`))},{once:!0}),this.container.appendChild(t)}),this.messageHandler=e=>{if(e.source!==t.contentWindow)return;let n=e.data;if(n?.type){if(n.nonce!==this.nonce){pi.warn(`Tool UI message nonce mismatch`,{expected:this.nonce,received:n.nonce});return}n.type===`tool-ui-action`&&n.id===this.requestId?(pi.info(`Tool UI action received`,{id:n.id,action:n.action}),_.handleAction(n.id,{action:n.action,data:n.data})):n.type===`tool-ui-rendered`&&n.id===this.requestId?n.height&&this.iframe&&(this.iframe.style.height=`${Math.max(60,n.height)}px`):n.type===`tool-ui-resize`&&n.id===this.requestId&&n.height&&this.iframe&&(this.iframe.style.height=`${Math.max(60,n.height)}px`)}},window.addEventListener(`message`,this.messageHandler);let{collectThemeCSS:n}=await v(async()=>{let{collectThemeCSS:e}=await import(`./sprinkle-renderer-Ci3F_XSt.js`);return{collectThemeCSS:e}},[]),r=n();t.contentWindow.postMessage({type:`tool-ui-render`,id:this.requestId,nonce:this.nonce,html:e,themeCSS:r},`*`)}renderWithInlineSprinkle(e){let t=document.createElement(`div`);t.className=`msg__inline-sprinkle`,this.container.appendChild(t),this.inlineSprinkle=li(t,e,(e,t)=>{pi.info(`Tool UI action (inline sprinkle)`,{id:this.requestId,action:e}),_.handleAction(this.requestId,{action:e,data:t})})}dispose(){this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.iframe&&=(this.iframe.remove(),null),this.inlineSprinkle&&=(this.inlineSprinkle.dispose(),null)}},gi=new Map;function _i(e,t,n){let r=gi.get(t);r&&r.dispose();let i=new hi(e,t);return gi.set(t,i),i.render(n).catch(e=>{pi.error(`Failed to render tool UI`,{requestId:t,error:e.message})}),i}function vi(e){let t=gi.get(e);t&&(t.dispose(),gi.delete(e))}var yi=n(`chat-panel`);function bi(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var xi={bash:`$`,browser:`B`,read_file:`R`,write_file:`W`,edit_file:`E`,javascript:`JS`,delegate_to_scoop:`D`,send_message:`M`,schedule_task:`T`,list_scoops:`LS`,list_tasks:`LT`,register_scoop:`RS`,update_global_memory:`GM`};function Si(e){return xi[e]??`?`}function Ci(e){return e.role===`assistant`?Ur(e.content):Hr(e.content)}var wi=class{container;messagesEl;messagesInner;inputArea;textarea;sendBtn;stopBtn;micBtn;voiceInput=null;voiceMode=!1;keydownListener=null;messages=[];agent=null;unsubscribe=null;isStreaming=!1;currentStreamId=null;sessionStore;sessionId;readOnly=!1;terminalOutputCallback=null;currentScoopName=null;autoScrollAttached=!0;lastScrollTop=0;jumpPill;onDeleteQueuedMessage=null;pendingDeltaText=``;streamingRafId=null;inlineSprinkles=new Map;onInlineSprinkleLick;modelSelectorEl;handoffsEl;pendingHandoffs=[];onAcceptPendingHandoff=null;onDismissPendingHandoff=null;onModelChange;constructor(e){this.container=e,this.sessionStore=new Yr,this.sessionId=`default`,this.render()}setAgent(e){this.unsubscribe?.(),this.agent=e,this.unsubscribe=e.onEvent(e=>this.handleAgentEvent(e))}onTerminalOutput(e){this.terminalOutputCallback=e}setDeleteQueuedMessageCallback(e){this.onDeleteQueuedMessage=e}async initSession(e){await this.sessionStore.init(),this.sessionId=e??`default`;let t=await this.sessionStore.load(this.sessionId);t&&t.messages.length>0&&(this.messages=t.messages.map(e=>({...e,isStreaming:!1})),this.renderMessages())}async clearSession(){this.messages=[],this.renderMessages(),await this.sessionStore.delete(this.sessionId)}async deleteSessionById(e){await this.sessionStore.delete(e)}async switchToContext(e,t,n){await this.persistSessionAsync(),this.setStreamingState(!1),this.currentStreamId=null,this.cancelPendingDelta(),this.sessionId=e,this.currentScoopName=n??null,this.setReadOnly(t);let r=await this.sessionStore.load(this.sessionId);r&&r.messages.length>0?this.messages=r.messages.map(e=>({...e,isStreaming:!1})):this.messages=[],this.renderMessages()}setReadOnly(e){this.readOnly=e,this.inputArea&&(this.inputArea.style.display=e?`none`:``)}async persistSessionAsync(){try{await this.sessionStore.saveMessages(this.sessionId,this.messages)}catch{}}setProcessing(e){e?this.setStreamingState(!0):this.setStreamingState(!1)}addSystemMessage(e){let t={id:bi(),role:`assistant`,content:e,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t),this.persistSession()}addLickMessage(e,t,n){let r={id:e,role:`user`,content:t,timestamp:Date.now(),source:`lick`,channel:n};this.messages.push(r),this.appendMessageEl(r),this.persistSession()}getMessages(){return[...this.messages]}loadMessages(e){this.messages=e.map(e=>({...e,isStreaming:!1})),this.renderMessages(),this.persistSession(),this.renderModelSelector()}clear(){this.messages=[],this.renderMessages(),this.renderModelSelector()}setPendingHandoffs(e){this.pendingHandoffs=[...e],this.renderPendingHandoffs()}setPendingHandoffActions(e){this.onAcceptPendingHandoff=e.onAccept,this.onDismissPendingHandoff=e.onDismiss,this.renderPendingHandoffs()}addUserMessage(e){let t={id:bi(),role:`user`,content:e,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t)}deleteQueuedMessage(e){let t=this.messages.findIndex(t=>t.id===e);if(t===-1)return;this.messages.splice(t,1);let n=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);n&&n.remove(),this.persistSession(),this.onDeleteQueuedMessage?.(e)}render(){this.container.innerHTML=``,this.container.classList.add(`chat`),this.messagesEl=document.createElement(`div`),this.messagesEl.className=`chat__messages`,this.messagesInner=document.createElement(`div`),this.messagesInner.className=`chat__messages-inner`,this.messagesEl.appendChild(this.messagesInner),this.handoffsEl=document.createElement(`div`),this.handoffsEl.className=`chat__handoffs`,this.handoffsEl.hidden=!0,this.messagesEl.appendChild(this.handoffsEl),this.container.appendChild(this.messagesEl),this.renderPendingHandoffs(),this.messagesEl.addEventListener(`scroll`,()=>{let{scrollTop:e,scrollHeight:t,clientHeight:n}=this.messagesEl;t-e-n<=250?(this.autoScrollAttached=!0,this.hideJumpPill()):e<this.lastScrollTop&&(this.autoScrollAttached=!1),this.lastScrollTop=e},{passive:!0}),this.inputArea=document.createElement(`div`);let e=this.inputArea;e.className=`chat__input-area`;let t=document.createElement(`div`);t.className=`chat__input-area-inner`,this.textarea=document.createElement(`textarea`),this.textarea.className=`chat__textarea`,this.textarea.placeholder=`What shall we build?`,this.textarea.rows=1,this.sendBtn=document.createElement(`button`),this.sendBtn.className=`chat__send-btn`,this.sendBtn.innerHTML=`<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M10 1.25C5.167 1.25 1.25 5.167 1.25 10s3.917 8.75 8.75 8.75 8.75-3.918 8.75-8.75S14.833 1.25 10 1.25zm3.527 8.284a.75.75 0 0 1-1.06 0L10.75 7.82v6.172a.75.75 0 0 1-1.5 0V7.812L7.527 9.534a.75.75 0 1 1-1.06-1.06l2.998-2.998a.75.75 0 0 1 1.06-.001l3.002 2.998a.75.75 0 0 1 0 1.061z"/></svg>`,this.sendBtn.dataset.tooltip=`Send message`,this.sendBtn.dataset.tooltipPos=`top`,this.stopBtn=document.createElement(`button`),this.stopBtn.className=`chat__stop-btn`,this.stopBtn.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="M13.75 4H6.25A2.25 2.25 0 0 0 4 6.25v7.5A2.25 2.25 0 0 0 6.25 16h7.5A2.25 2.25 0 0 0 16 13.75v-7.5A2.25 2.25 0 0 0 13.75 4z"/></svg>`,this.stopBtn.dataset.tooltip=`Stop generation`,this.stopBtn.style.display=`none`,this.micBtn=document.createElement(`button`),this.micBtn.className=`chat__mic-btn`;let n=`http://www.w3.org/2000/svg`,r=document.createElementNS(n,`svg`);r.setAttribute(`width`,`16`),r.setAttribute(`height`,`16`),r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`2`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`);let i=document.createElementNS(n,`path`);i.setAttribute(`d`,`M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z`);let a=document.createElementNS(n,`path`);a.setAttribute(`d`,`M19 10v2a7 7 0 0 1-14 0v-2`);let o=document.createElementNS(n,`line`);o.setAttribute(`x1`,`12`),o.setAttribute(`y1`,`19`),o.setAttribute(`x2`,`12`),o.setAttribute(`y2`,`23`);let s=document.createElementNS(n,`line`);s.setAttribute(`x1`,`8`),s.setAttribute(`y1`,`23`),s.setAttribute(`x2`,`16`),s.setAttribute(`y2`,`23`),r.append(i,a,o,s),this.micBtn.appendChild(r),this.micBtn.dataset.tooltip=`Voice (Ctrl+Shift+V)`;let c=document.createElement(`div`);c.className=`chat__input-wrapper`,c.appendChild(this.textarea);let l=document.createElement(`div`);l.className=`chat__action-bar`;let u=document.createElement(`div`);u.className=`chat__action-bar-left`,u.appendChild(this.micBtn),l.appendChild(u),this.modelSelectorEl=document.createElement(`div`),this.modelSelectorEl.className=`chat__model-selector`,this.renderModelSelector(),l.appendChild(this.modelSelectorEl);let d=document.createElement(`div`);d.className=`chat__action-bar-right`,d.appendChild(this.sendBtn),d.appendChild(this.stopBtn),l.appendChild(d),c.appendChild(l),t.appendChild(c),e.appendChild(t),this.container.appendChild(e),this.jumpPill=document.createElement(`button`),this.jumpPill.className=`chat__jump-pill`,this.jumpPill.textContent=`↓ New activity`,this.jumpPill.addEventListener(`click`,()=>{this.autoScrollAttached=!0,this.hideJumpPill(),this.scrollToBottom(!0)}),this.container.appendChild(this.jumpPill),this.textarea.addEventListener(`keydown`,e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.sendMessage())}),this.textarea.addEventListener(`input`,()=>{this.textarea.style.height=`auto`,this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+`px`}),this.sendBtn.addEventListener(`click`,()=>this.sendMessage()),this.stopBtn.addEventListener(`click`,()=>{this.agent?.stop();for(let e of this.messages)e.queued&&(e.queued=!1,this.updateMessageEl(e.id));this.setStreamingState(!1)}),this.voiceInput=new $r({onTranscript:(e,t)=>{this.textarea.value=e,this.textarea.style.height=`auto`,this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+`px`},onStateChange:e=>{e===`error`?(this.voiceMode=!1,this.micBtn.classList.remove(`chat__mic-btn--active`,`chat__mic-btn--listening`)):this.voiceMode?e===`listening`&&this.micBtn.classList.add(`chat__mic-btn--listening`):this.micBtn.classList.toggle(`chat__mic-btn--listening`,e===`listening`)},onError:e=>{yi.debug(`Voice input error`,{error:e}),!(this.voiceMode&&e.includes(`No speech detected`))&&this.addSystemMessage(e)},autoSend:!0,onAutoSend:e=>{this.textarea.value=e,this.sendMessage()},onAutoDisable:()=>{this.voiceMode=!1,this.micBtn.classList.remove(`chat__mic-btn--active`,`chat__mic-btn--listening`),this.addSystemMessage(`Voice mode disabled after 2 minutes of inactivity.`)},lang:ti()}),this.micBtn.addEventListener(`click`,()=>{this.toggleVoiceMode()}),this.keydownListener=e=>{e.shiftKey&&(e.ctrlKey||e.metaKey)&&e.key===`V`&&(e.preventDefault(),this.toggleVoiceMode())},document.addEventListener(`keydown`,this.keydownListener)}renderPendingHandoffs(){if(!this.handoffsEl)return;if(this.pendingHandoffs.length===0){this.handoffsEl.hidden=!0,this.handoffsEl.innerHTML=``;return}let e=this.pendingHandoffs.length===1?`1 pending handoff`:`${this.pendingHandoffs.length} pending handoffs`;this.handoffsEl.hidden=!1,this.handoffsEl.innerHTML=`
|
|
240
240
|
<div class="chat__handoffs-inner">
|
|
241
241
|
<div class="chat__handoffs-header">${Ar(e)}</div>
|
|
242
242
|
${this.pendingHandoffs.map(e=>this.renderPendingHandoffCard(e)).join(``)}
|
|
@@ -1434,10 +1434,10 @@ Page ranges:
|
|
|
1434
1434
|
`,exitCode:1}:{stdout:`${t}\n`,stderr:``,exitCode:0}})}function rh(){return{stdout:`usage: man <topic>
|
|
1435
1435
|
|
|
1436
1436
|
Fetches documentation for a given topic from sliccy.com.
|
|
1437
|
-
`,stderr:``,exitCode:0}}function ih(e){return e.replace(/<[^>]*>/g,``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/ /g,` `).trimEnd()}function ah(
|
|
1437
|
+
`,stderr:``,exitCode:0}}function ih(e){return e.replace(/<[^>]*>/g,``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/ /g,` `).trimEnd()}function ah(){return z(`man`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return rh();if(e.length===0)return{stdout:``,stderr:`What manual page do you want?
|
|
1438
1438
|
For example, try 'man commands'.
|
|
1439
|
-
`,exitCode:1};let
|
|
1440
|
-
`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`man: ${e.message||String(e)}\n`,exitCode:1}}})}function oh(){return{stdout:`usage: unzip <archive.zip> [-d <destination>]
|
|
1439
|
+
`,exitCode:1};let t=e.join(`-`),n=`https://www.sliccy.com/man/${t}.plain.html`;try{let e=await fetch(n);return e.status===404?{stdout:``,stderr:`No manual entry for ${t}\n`,exitCode:1}:e.ok?{stdout:ih(await e.text())+`
|
|
1440
|
+
`,stderr:``,exitCode:0}:{stdout:``,stderr:`man: failed to fetch manual page for ${t}: ${e.status} ${e.statusText}\n`,exitCode:1}}catch(e){return{stdout:``,stderr:`man: ${e.message||String(e)}\n`,exitCode:1}}})}function oh(){return{stdout:`usage: unzip <archive.zip> [-d <destination>]
|
|
1441
1441
|
`,stderr:``,exitCode:0}}function sh(){return z(`unzip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return oh();let n=`.`,r=[];for(let t=0;t<e.length;t++){let i=e[t];if(i===`-d`){n=e[t+1]??``,t++;continue}if(i.startsWith(`-`))return{stdout:``,stderr:`unzip: unsupported option ${i}\n`,exitCode:1};r.push(i)}if(r.length<1)return{stdout:``,stderr:`unzip: expected archive path
|
|
1442
1442
|
`,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=t.fs.resolvePath(t.cwd,n||`.`);await t.fs.mkdir(a,{recursive:!0});let o=M(await t.fs.readFileBuffer(i)),s=0;for(let[e,n]of Object.entries(o)){let r=e.replace(/\\/g,`/`);if(!r||r.endsWith(`/`))continue;let i=t.fs.resolvePath(a,r);if(!hm(a,i))return{stdout:``,stderr:`unzip: blocked suspicious path ${e}\n`,exitCode:1};let o=fm(i);o!==`/`&&await t.fs.mkdir(o,{recursive:!0}),await t.fs.writeFile(i,n),s++}return{stdout:`extracted ${s} file(s) to ${a}\n`,stderr:``,exitCode:0}})}function ch(){return{stdout:`usage: webhook <command> [options]
|
|
1443
1443
|
|
|
@@ -1557,7 +1557,7 @@ on success.
|
|
|
1557
1557
|
Examples:
|
|
1558
1558
|
oauth-token adobe
|
|
1559
1559
|
curl -H "Authorization: Bearer $(oauth-token adobe)" https://api.corp.com/data
|
|
1560
|
-
`}function Th(){return z(`oauth-token`,async e=>{let{getOAuthAccountInfo:t,getSelectedProvider:n,getAccounts:r}=await v(async()=>{let{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}=await import(`./provider-settings-
|
|
1560
|
+
`}function Th(){return z(`oauth-token`,async e=>{let{getOAuthAccountInfo:t,getSelectedProvider:n,getAccounts:r}=await v(async()=>{let{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}=await import(`./provider-settings-DtthfIx_.js`);return{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}},__vite__mapDeps([8,9,1,4,10,11,12,13,14,15])),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await v(async()=>{let{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}=await import(`./providers-CBTIfSNw.js`);return{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}},__vite__mapDeps([16,9,1,4,10,11,12,13,14,15]));if(e.includes(`--help`)||e.includes(`-h`))return{stdout:wh(),stderr:``,exitCode:0};if(e.includes(`--list`))return Eh(r,a,i,t);let o,s=e.indexOf(`--provider`);if(s>=0){if(o=e[s+1],!o)return{stdout:``,stderr:`oauth-token: --provider requires a value
|
|
1561
1561
|
`,exitCode:1}}else if(e.length>0)o=e[0];else{let e=n(),t=i(e);if(t?.isOAuth&&t.onOAuthLogin)o=e;else if(o=a().find(e=>{let t=i(e);return t?.isOAuth&&t.onOAuthLogin}),!o)return{stdout:``,stderr:`oauth-token: no OAuth providers configured
|
|
1562
1562
|
`,exitCode:1}}let c=i(o);if(!c)return{stdout:``,stderr:`oauth-token: unknown provider "${o}"\n`,exitCode:1};if(!c.isOAuth||!c.onOAuthLogin)return{stdout:``,stderr:`oauth-token: provider "${o}" is not an OAuth provider\n`,exitCode:1};let l=t(o);if(l&&!l.expired)return{stdout:`${l.token}\n`,stderr:``,exitCode:0};try{let{createOAuthLauncher:e}=await v(async()=>{let{createOAuthLauncher:e}=await import(`./oauth-service-t9Y4KdOX.js`);return{createOAuthLauncher:e}},[]),n=e();await c.onOAuthLogin(n,()=>{});let r=t(o);return r&&r.token?{stdout:`${r.token}\n`,stderr:``,exitCode:0}:(console.error(`[oauth-token] Provider ${o}: login completed but no token was saved`),{stdout:``,stderr:`oauth-token: login completed but no token was saved
|
|
1563
1563
|
`,exitCode:1})}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${o}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}function Eh(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
|
|
@@ -1622,7 +1622,7 @@ Examples:
|
|
|
1622
1622
|
`)+`
|
|
1623
1623
|
`,stderr:``,exitCode:0}}function Gh(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Kh(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function qh(e={}){let t=e.fs,n=e.getSendFsRequest??Ph;return z(`rsync`,async e=>{if(e.includes(`--help`)||e.includes(`-h`)||e.length===0)return Lh();if(!t)return{stdout:``,stderr:`rsync: no filesystem available
|
|
1624
1624
|
`,exitCode:1};let r=n();if(!r)return{stdout:``,stderr:`rsync: not connected to a tray — rsync requires a tray connection
|
|
1625
|
-
`,exitCode:1};let i=Fh(e);if(`error`in i)return i.error===`__help__`?Lh():{stdout:``,stderr:`rsync: ${i.error}\n`,exitCode:1};try{return i.direction===`push`?await Uh(t,r,i):await Wh(t,r,i)}catch(e){return{stdout:``,stderr:`rsync: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}var Jh=[`/workspace/skills`];async function Yh(e){let t=new Map;for(let n of Jh)await e.exists(n)&&await Xh(e,n,t);return await Xh(e,`/`,t),t}async function Xh(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.jsh`))continue;let e=Zh(r);n.has(e)||n.set(e,r)}}function Zh(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.jsh`)?t.slice(0,-4):t}function Qh(e){return z(`which`,async(
|
|
1625
|
+
`,exitCode:1};let i=Fh(e);if(`error`in i)return i.error===`__help__`?Lh():{stdout:``,stderr:`rsync: ${i.error}\n`,exitCode:1};try{return i.direction===`push`?await Uh(t,r,i):await Wh(t,r,i)}catch(e){return{stdout:``,stderr:`rsync: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}var Jh=[`/workspace/skills`];async function Yh(e){let t=new Map;for(let n of Jh)await e.exists(n)&&await Xh(e,n,t);return await Xh(e,`/`,t),t}async function Xh(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.jsh`))continue;let e=Zh(r);n.has(e)||n.set(e,r)}}function Zh(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.jsh`)?t.slice(0,-4):t}function Qh(e={}){let t=e.scriptCatalog!==void 0||e.fs!==void 0?e:typeof e.walk==`function`&&typeof e.exists==`function`?{fs:e}:{};return z(`which`,async(e,n)=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`which - locate a command
|
|
1626
1626
|
|
|
1627
1627
|
Usage: which <command> [command...]
|
|
1628
1628
|
|
|
@@ -1631,8 +1631,8 @@ Prints the path of the given command(s).
|
|
|
1631
1631
|
- .jsh scripts resolve to their actual VFS path
|
|
1632
1632
|
|
|
1633
1633
|
Exit code 0 if all commands found, 1 if any not found.
|
|
1634
|
-
`,stderr:``,exitCode:0};if(
|
|
1635
|
-
`,exitCode:1};let r=n.getRegisteredCommands?.()??[],i=new Set(r),a=
|
|
1634
|
+
`,stderr:``,exitCode:0};if(e.length===0)return{stdout:``,stderr:`which: missing argument
|
|
1635
|
+
`,exitCode:1};let r=n.getRegisteredCommands?.()??[],i=new Set(r),a=t.scriptCatalog?await t.scriptCatalog.getJshCommands():t.fs?await Yh(t.fs):new Map,o=[],s=!0;for(let t of e)if(i.has(t))o.push(`/usr/bin/${t}`);else{let e=a.get(t);e?o.push(e):s=!1}return{stdout:o.length>0?o.join(`
|
|
1636
1636
|
`)+`
|
|
1637
1637
|
`:``,stderr:``,exitCode:+!s}})}async function $h(e,t,n,r){if((await e.fs.stat(t)).isFile)return r[n]=await e.fs.readFileBuffer(t),1;let i=await e.fs.readdir(t),a=0;for(let o of i){let i=pm(t,o),s=n?`${n}/${o}`:o;a+=await $h(e,i,s,r)}return a}function eg(){return{stdout:`usage: zip [-r] <archive.zip> <path> [path...]
|
|
1638
1638
|
`,stderr:``,exitCode:0}}function tg(){return z(`zip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return eg();let n=!1,r=[];for(let t of e){if(t===`-r`){n=!0;continue}if(t.startsWith(`-`))return{stdout:``,stderr:`zip: unsupported option ${t}\n`,exitCode:1};r.push(t)}if(r.length<2)return{stdout:``,stderr:`zip: expected archive path and at least one input path
|
|
@@ -1717,7 +1717,7 @@ Options:
|
|
|
1717
1717
|
-h, --help Show this help message
|
|
1718
1718
|
`}function Fg(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function Ig(e){return`$${e.toFixed(2)}`}var Lg=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function Rg(e){let t=`${e.id} ${e.name??``}`;return!Lg.test(t)}function zg(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 Bg(e){let t=new Map;for(let n of e){let e=zg(n.id);t.has(e)||t.set(e,n)}return[...t.values()]}function Vg(e,t,n,r,i){let a=i?Ng(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 Hg(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=`${Ig(e.cost.input)} / ${Ig(e.cost.output)}`,a=`${Fg(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(`
|
|
1719
1719
|
`)+`
|
|
1720
|
-
`}function Ug(e){return z(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s}=await v(async()=>{let{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}=await import(`./provider-settings-
|
|
1720
|
+
`}function Ug(e){return z(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s}=await v(async()=>{let{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}=await import(`./provider-settings-DtthfIx_.js`);return{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}},__vite__mapDeps([8,9,1,4,10,11,12,13,14,15]));if(t.includes(`--help`)||t.includes(`-h`))return{stdout:Pg(),stderr:``,exitCode:0};let c=t.includes(`--json`),l=t.includes(`--all`),u=t.includes(`--all-versions`),d=t.includes(`--refresh`),f=t.includes(`--no-benchmarks`),p=t.indexOf(`--provider`),m=p>=0?t[p+1]:void 0,h=o(),g=s(),_=n();if(_.length===0)return{stdout:``,stderr:`No provider accounts configured. Run the provider settings to add one.
|
|
1721
1721
|
`,exitCode:1};let y;f||(y=await jg(e,d),y.length===0&&(y=void 0));let b;if(m){let e=r();if(!e.includes(m))return{stdout:``,stderr:`Unknown provider: ${m}. Available: ${e.join(`, `)}\n`,exitCode:1};b=[m]}else b=l?[...new Set(_.map(e=>e.providerId))]:[h];let x=[],S=[];for(let e of b){let t=a(e).filter(Rg);if(t.length===0){if(!l)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>Vg(t,e,g,h,y)).sort((e,t)=>t.cost.input-e.cost.input);if(u||(n=Bg(n)),x.push(...n),!c){let t=i(e);S.push(Hg(t.name,e,n,!!y))}}return c?{stdout:JSON.stringify(x,null,2)+`
|
|
1722
1722
|
`,stderr:``,exitCode:0}:(!u&&!c&&S.push(`Showing latest versions only. Use --all-versions to see all.
|
|
1723
1723
|
`),{stdout:S.join(`
|
|
@@ -1729,7 +1729,7 @@ Requires the secret launch code to proceed.
|
|
|
1729
1729
|
`,stderr:``,exitCode:0}:e.join(``).includes(`1234`)?(indexedDB.databases().then(e=>{for(let t of e)t.name&&indexedDB.deleteDatabase(t.name)}),setTimeout(()=>location.reload(),0),{stdout:`Nuking everything…
|
|
1730
1730
|
`,stderr:``,exitCode:0}):{stdout:``,stderr:`⚠️ WARNING: this will reset the entire environment, file system, chats, and scoops.
|
|
1731
1731
|
Run nuke again with the secret launch code to proceed.
|
|
1732
|
-
`,exitCode:1})}function Gg(e={}){let t=[Tp({getJshCommands:e.getJshCommands}),$p(),Qm(e.browserAPI,e.fs),Fm(),nm(e),tg(),sh(),eh(`sqlite3`),eh(`sqllite`),jm(),Ym(`python3`),Ym(`python`),uh(),_h(),bh(),Ch(),Wm(`pdftk`),Wm(`pdf`),Op(`convert`),Op(`magick`),Qh(e.fs),nh(),ah(
|
|
1732
|
+
`,exitCode:1})}function Gg(e={}){let t=[Tp({getJshCommands:e.getJshCommands}),$p(),Qm(e.browserAPI,e.fs),Fm(),nm(e),tg(),sh(),eh(`sqlite3`),eh(`sqllite`),jm(),Ym(`python3`),Ym(`python`),uh(),_h(),bh(),Ch(),Wm(`pdftk`),Wm(`pdf`),Op(`convert`),Op(`magick`),Qh({fs:e.fs,scriptCatalog:e.scriptCatalog}),nh(),ah(),Th(),Ah(),qh({fs:e.fs}),og(),pg(),mg(),hg(`xclip`),hg(`xsel`),bg(),Tg(),Eg(),Ug(e.fs),Ue(),Wg()];return typeof chrome<`u`&&chrome?.runtime?.id&&t.push(Dg()),e.fs&&t.push(...Mf.map(t=>Sp(t,e.browserAPI,e.fs))),t}var Kg=`https://wry-manatee-359.convex.site/api/v1`,qg=`https://api.tessl.io`,Jg=`/workspace/skills`,Yg=`slicc-fs-global`,Xg=`/workspace/.git/github-token`,Zg=`application/vnd.github.v3+json`,Qg=`https://www.sliccy.com/skills/catalog.json`;function $g(e){if(!(!e||!e.trim()))return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function e_(e){return e.map(e=>{let t=e.boost?parseFloat(e.boost):NaN,n=Number.isFinite(t)?t:void 0;return{name:e.name,displayName:e.displayName||e.name,description:e.description||``,source:{repo:e.repo,path:e.path||void 0,skill:e.skill||void 0},affinity:{apps:$g(e.apps),tasks:$g(e.tasks),role:$g(e.role),purpose:$g(e.purpose)},priority:n}})}var t_={apps:3,tasks:2,role:1,purpose:1};function n_(e,t){return e.map(e=>{let n=0,r=[],i=(e.affinity.apps??[]).filter(e=>t.apps.includes(e));i.length&&(n+=i.length*t_.apps,r.push(`apps(${i.join(`, `)})`));let a=(e.affinity.tasks??[]).filter(e=>t.tasks.includes(e));return a.length&&(n+=a.length*t_.tasks,r.push(`tasks(${a.join(`, `)})`)),(e.affinity.role??[]).includes(t.role)&&(n+=t_.role,r.push(`role(${t.role})`)),(e.affinity.purpose??[]).includes(t.purpose)&&(n+=t_.purpose,r.push(`purpose(${t.purpose})`)),n*=e.priority??1,{entry:e,score:n,matchReasons:r}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score)}function r_(e){let t=`upskill ${e.repo}`;return e.path&&(t+=` --path ${e.path}`),e.skill&&(t+=` --skill ${e.skill}`),t}async function i_(e){let t=new Set;try{let n=await e.readDir(Jg);for(let e of n)e.type===`directory`&&t.add(e.name)}catch{}try{let n=await e.readTextFile(`/${N}/${F}`),r=JSON.parse(n);for(let e of r.applied_skills??[])t.add(e.name)}catch{}let n=[`.agents`,`.claude`];try{let r=await e.readDir(`/`);for(let i of r)if(i.type===`directory`)for(let r of n)try{let n=`/${i.name}/${r}/skills`,a=await e.readDir(n);for(let e of a)e.type===`directory`&&t.add(e.name)}catch{}}catch{}return t}var a_;function o_(){return a_||=L.create({dbName:Yg}),a_}async function s_(){try{return(await(await o_()).readTextFile(Xg)).trim()||void 0}catch{return}}function c_(e,t=Zg){let n={Accept:t,"User-Agent":`slicc-upskill`};return e&&(n.Authorization=`Bearer ${e}`),n}async function l_(e){let t=await s_();return{hasToken:!!t,request:(n,r=Zg)=>e(n,{headers:c_(t,r)})}}function u_(e,t){if(!e)return;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r}function d_(e){if(!e)return;try{let t=JSON.parse(e);if(typeof t.message==`string`&&t.message.trim())return t.message.trim()}catch{}let t=e.trim();if(t)return t.slice(0,200)}function f_(e,t,n){let r=d_(e.body),i=r?` GitHub said: ${r}`:``,a=u_(e.headers,`retry-after`),o=u_(e.headers,`x-ratelimit-remaining`),s=r?.toLowerCase()??``;if(e.status===429||o===`0`||s.includes(`rate limit`))return n?`GitHub rate-limited access to ${t} (HTTP ${e.status}). The configured github.token was used, so retry later${a?` after about ${a} seconds`:``}.${i}`:`GitHub rate-limited anonymous access to ${t} (HTTP ${e.status}). This often happens on shared VPNs or corporate egress IPs because unauthenticated GitHub API requests are limited per IP. Configure a token with: git config github.token <PAT>, then retry. You can also retry off VPN or later.${i}`;if(e.status===401)return n?`GitHub rejected the configured github.token while accessing ${t} (HTTP 401). Update it with: git config github.token <PAT>, then retry.${i}`:`GitHub requires authentication to access ${t} (HTTP 401). Configure a token with: git config github.token <PAT>, then retry.${i}`;if(e.status===404)return`GitHub could not find ${t} (HTTP 404). Check the repository, path, and permissions.${i}`;if(e.status===403)return n?`GitHub denied access to ${t} (HTTP 403). Check that your github.token can access this repository or retry later if GitHub is throttling requests.${i}`:`GitHub denied anonymous access to ${t} (HTTP 403). If this repo is public on a shared VPN, you may have hit GitHub's shared IP limit; otherwise the repository or path may require authentication. Configure a token with: git config github.token <PAT>, then retry.${i}`;let c=e.statusText?` ${e.statusText}`:``;return`GitHub request for ${t} failed (HTTP ${e.status}${c}).${i}`}function p_(){return`Discovery roots: /workspace/skills plus accessible **/.agents/skills/* and **/.claude/skills/* anywhere in the VFS.
|
|
1733
1733
|
`}function m_(){return`Only native /workspace/skills entries are install-managed; compatibility-discovered .agents/.claude skills remain read-only.
|
|
1734
1734
|
`}function h_(e){switch(e){case`native`:return`native`;case`agents`:return`.agents`;case`claude`:return`.claude`}}function g_(e){return e.source===`native`}function __(e){return g_(e)?e.installed&&e.installedVersion?`installed (v${e.installedVersion})`:`available`:e.installed&&e.installedVersion?`compatibility (state v${e.installedVersion})`:`compatibility (read-only)`}function v_(e){return g_(e)?`install-managed (/workspace/skills)`:`compatibility-only (read-only)`}function y_(e,t){let n=`${t}:\n\n`;n+=` NAME VERSION SOURCE STATUS
|
|
1735
1735
|
`,n+=` ─────────────────────────────────────────────────────────────
|
|
@@ -1798,7 +1798,7 @@ Examples:
|
|
|
1798
1798
|
`,stderr:``,exitCode:0};if(n){let n=new Map;for(let e of o){let t=e.entry.source.repo,r=n.get(t);r?r.push(e):n.set(t,[e])}let r=o.length,i=0,a=Date.now(),s=``,c=``,l=0,u=await Promise.allSettled(Array.from(n.entries()).map(async([n,o])=>{let[c,l]=n.split(`/`),u=await M_(c,l,t);if(u.status===`not_found`||u.status===`error`){let e=u.status===`not_found`?`upskill: repository ${n} not found\n`:`upskill: failed to fetch ${n}: ${u.message}\n`,t=[];for(let e of o){i++,((Date.now()-a)/1e3).toFixed(1);let o=i<r?` (~${Math.round((r-i)*(Date.now()-a)/i/1e3)}s remaining)`:``;s+=`[${i}/${r}] Failed "${e.entry.name}" from ${n}: repo fetch failed${o}\n`,t.push({ok:!1,name:e.entry.name,error:`repo fetch failed for ${n}`})}return{errors:e,results:t}}let d=N_(u.files),f=[],p=new Map;for(let e of Object.keys(d))if(e.endsWith(`/SKILL.md`)){let t=e.replace(/\/SKILL\.md$/,``),n=t.split(`/`).pop()||t;p.set(n,t)}for(let t of o){let o=t.entry.source,c,l;if(o.skill){let e=p.get(o.skill);if(!e){let e=`skill "${o.skill}" not found in ${n}`;f.push({ok:!1,name:t.entry.name,error:e}),i++,((Date.now()-a)/1e3).toFixed(1);let c=i<r?` (~${Math.round((r-i)*(Date.now()-a)/i/1e3)}s remaining)`:``;s+=`[${i}/${r}] Failed "${t.entry.name}" from ${n}: ${e}${c}\n`;continue}c=e,l=o.skill}else c=o.path?o.path.replace(/^\/|\/$/g,``):``,l=t.entry.name;let u=Date.now(),m=await R_(c,l,d,e,!1);i++;let h=((Date.now()-u)/1e3).toFixed(1),g=(Date.now()-a)/i,_=Math.round((r-i)*g/1e3),v=i<r?` (~${_}s remaining)`:``;m.ok?(f.push({ok:!0,name:l}),s+=`[${i}/${r}] Installed "${l}" from ${n} (${h}s)${v}\n`):(f.push({ok:!1,name:l,error:m.error}),s+=`[${i}/${r}] Failed "${l}" from ${n}: ${m.error}${v}\n`)}return{errors:``,results:f}}));for(let e of u){if(e.status===`rejected`){c+=`upskill: unexpected error: ${e.reason}\n`;continue}e.value.errors&&(c+=e.value.errors);for(let t of e.value.results)t.ok?l++:t.error&&(c+=`upskill: ${t.error}\n`)}let d=((Date.now()-a)/1e3).toFixed(1);return l>0&&(s+=`\nInstalled ${l} recommended skill(s) in ${d}s\n`,await L_()),{stdout:s,stderr:c,exitCode:+!!c}}let s=`Recommended skills for you:
|
|
1799
1799
|
|
|
1800
1800
|
`,c=0;for(let e of o){c++;let t=r_(e.entry.source);s+=` ${c}. ${e.entry.displayName.padEnd(35)} score: ${Math.round(e.score)}\n`,s+=` ${e.entry.description}\n`,s+=` Match: ${e.matchReasons.join(`, `)}\n`,s+=` Install: ${t}\n\n`}return s+=`To install all recommended: upskill recommendations --install
|
|
1801
|
-
`,{stdout:s,stderr:``,exitCode:0}}function U_(e,t){return z(`upskill`,async(n,r)=>{if(n.length===0||n.includes(`--help`)||n.includes(`-h`))return S_();let i=[],a,o=!1,s=!1,c=!1,l=``,u,d=``,f=1,p=0;for(;p<n.length;){let r=n[p];if(r===`search`){let e=n.slice(p+1),t=e.indexOf(`--page`);t>=0&&(f=parseInt(e[t+1],10)||1,e.splice(t,2)),d=e.join(` `);break}else if(r===`recommendations`)return H_(e,t,n.includes(`--install`));else if(r===`list`){let t=await(await v(()=>import(`./skills-
|
|
1801
|
+
`,{stdout:s,stderr:``,exitCode:0}}function U_(e,t){return z(`upskill`,async(n,r)=>{if(n.length===0||n.includes(`--help`)||n.includes(`-h`))return S_();let i=[],a,o=!1,s=!1,c=!1,l=``,u,d=``,f=1,p=0;for(;p<n.length;){let r=n[p];if(r===`search`){let e=n.slice(p+1),t=e.indexOf(`--page`);t>=0&&(f=parseInt(e[t+1],10)||1,e.splice(t,2)),d=e.join(` `);break}else if(r===`recommendations`)return H_(e,t,n.includes(`--install`));else if(r===`list`){let t=await(await v(()=>import(`./skills-BQCgGxAq.js`),__vite__mapDeps([17,18,19,20,1,15]))).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${p_()}${m_()}`,stderr:``,exitCode:0}:{stdout:y_(t,`Discoverable local skills`),stderr:``,exitCode:0}}else if(r===`info`||r===`read`){let t=n[p+1];if(!t)return{stdout:``,stderr:`upskill: ${r} requires a skill name\n`,exitCode:1};let i=await v(()=>import(`./skills-BQCgGxAq.js`),__vite__mapDeps([17,18,19,20,1,15]));if(r===`info`){let n=await i.getSkillInfo(e,t);return n?{stdout:b_(n),stderr:``,exitCode:0}:{stdout:``,stderr:`upskill: skill "${t}" not found\n`,exitCode:1}}else{let n=await i.readSkillInstructions(e,t);return n===null?{stdout:``,stderr:`upskill: no SKILL.md found for "${t}"\n`,exitCode:1}:{stdout:n+`
|
|
1802
1802
|
`,stderr:``,exitCode:0}}}else if(r===`--skill`)i.push(n[++p]);else if(r===`--path`||r===`-p`)a=n[++p];else if(r===`--list`)o=!0;else if(r===`--all`)s=!0;else if(r===`--force`)c=!0;else if(r===`--branch`||r===`-b`){let e=n[p+1];if(!e||e.startsWith(`-`))return{stdout:``,stderr:`upskill: --branch requires a value
|
|
1803
1803
|
`,exitCode:1};u=n[++p]}else r.startsWith(`-`)||(l=r);p++}if(d)return D_(d,t,f);if(!l)return S_();let m=I_(l);if(m){let n=r.getRegisteredCommands?.()??[];return O_(m,e,t,c,n)}if(l.startsWith(`tessl:`)){let n=l.slice(6);if(!n)return{stdout:``,stderr:`upskill: tessl: requires a skill name
|
|
1804
1804
|
`,exitCode:1};let r=await j_(n,t);if(`error`in r)return{stdout:``,stderr:`upskill: ${r.error}\n`,exitCode:1};let i=await l_(t);return F_(r.owner,r.repo,r.skillPath,r.skillName,e,i,c,t)}let h=B_(l);if(h){let{owner:n,repo:r}=h,d=u??h.branch,f=await l_(t),p=await P_(n,r,f,a,t,d);if(p.error)return{stdout:``,stderr:`upskill: failed to list skills: ${p.error}\n`,exitCode:1};if(p.skills.length===0)return{stdout:`No skills found in ${n}/${r}${a?`/`+a:``}\n`,stderr:``,exitCode:0};if(o){let e=`Available skills in ${n}/${r}:\n\n`;for(let t of p.skills)e+=` ${t.name.padEnd(30)} ${t.path}\n`;return e+=`\nFound ${p.skills.length} skill(s)\n`,e+=`\nTo install: upskill ${l} --skill <name>\n`,e+=`To install all: upskill ${l} --all\n`,{stdout:e,stderr:``,exitCode:0}}let m=p.skills;if(i.length>0){m=p.skills.filter(e=>i.includes(e.name));for(let e of i)if(!p.skills.find(t=>t.name===e))return{stdout:``,stderr:`upskill: skill "${e}" not found in ${n}/${r}\n`,exitCode:1}}else if(!s){let e=`Available skills in ${n}/${r}:\n\n`;for(let t of p.skills)e+=` ${t.name.padEnd(30)} ${t.path}\n`;return e+=`\nFound ${p.skills.length} skill(s)\n`,e+=`\nTo install specific skills: upskill ${l} --skill <name>\n`,e+=`To install all: upskill ${l} --all\n`,{stdout:e,stderr:``,exitCode:0}}let g=``,_=``,v=0,y=m.length,b=Date.now();if(y>1){let i=await M_(n,r,t,d);if(i.status===`not_found`)return{stdout:``,stderr:`upskill: ${d?`branch "${d}" in ${n}/${r}`:`repository ${n}/${r}`} not found\n`,exitCode:1};if(i.status===`error`)return{stdout:``,stderr:`upskill: failed to fetch ${n}/${r}: ${i.message}\n`,exitCode:1};let a=N_(i.files);for(let t=0;t<m.length;t++){let i=m[t],o=await R_(i.path,i.name,a,e,c),s=t+1,l=((Date.now()-b)/1e3).toFixed(1),u=(Date.now()-b)/s,d=Math.round((y-s)*u/1e3),f=s<y?` (~${d}s remaining)`:``;o.ok?(g+=`[${s}/${y}] Installed "${i.name}" from ${n}/${r} (${l}s)${f}\n`,v++):(g+=`[${s}/${y}] Failed "${i.name}": ${o.error}${f}\n`,_+=`upskill: ${o.error}\n`)}}else for(let i of m){let a=await F_(n,r,i.path,i.name,e,f,c,t,d);a.exitCode===0?(g+=a.stdout,v++):_+=a.stderr}let x=((Date.now()-b)/1e3).toFixed(1);return v>0&&(g+=`\nInstalled ${v} skill(s)${y>1?` in ${x}s`:``}\n`,await L_()),{stdout:g,stderr:_,exitCode:+!!_}}return{stdout:``,stderr:`upskill: unrecognized source "${l}"\n\nExpected: owner/repo, clawhub:<slug>, tessl:<name>, or https://clawhub.ai/user/skill\n`,exitCode:1}})}function W_(e){return z(`skill`,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return{stdout:`usage: skill <command> [options]
|
|
@@ -1822,7 +1822,7 @@ Examples:
|
|
|
1822
1822
|
skill list
|
|
1823
1823
|
skill info bluebubbles
|
|
1824
1824
|
skill read bluebubbles
|
|
1825
|
-
`,stderr:``,exitCode:0};let r=t[0],i=await v(()=>import(`./skills-
|
|
1825
|
+
`,stderr:``,exitCode:0};let r=t[0],i=await v(()=>import(`./skills-BQCgGxAq.js`),__vite__mapDeps([17,18,19,20,1,15]));try{switch(r){case`list`:{let t=await i.discoverSkills(e);return t.length===0?{stdout:`No discoverable skills found.\n\n${p_()}${m_()}\nInstall install-managed skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:y_(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
|
|
1826
1826
|
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:b_(r),stderr:``,exitCode:0}:{stdout:``,stderr:`skill: "${n}" not found\n`,exitCode:1}}case`read`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: read requires a skill name
|
|
1827
1827
|
`,exitCode:1};let r=await i.readSkillInstructions(e,n);return r===null?{stdout:``,stderr:`skill: no SKILL.md found for "${n}"\n`,exitCode:1}:{stdout:r+`
|
|
1828
1828
|
`,stderr:``,exitCode:0}}case`install`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: install requires a skill name
|
|
@@ -1841,7 +1841,7 @@ Usage: mount <target-path>
|
|
|
1841
1841
|
<button class="sprinkle-btn sprinkle-btn--primary" data-action="approve">Select directory</button>
|
|
1842
1842
|
</div>
|
|
1843
1843
|
</div>
|
|
1844
|
-
`,onAction:async e=>{if(e===`approve`)try{return{approved:!0,handle:await window.showDirectoryPicker({mode:`readwrite`})}}catch(e){return e instanceof Error&&e.name===`AbortError`?{cancelled:!0}:{error:e instanceof Error?e.message:String(e)}}return{denied:!0}}});if(!e)return{stdout:``,stderr:`mount: tool UI not available`,exitCode:1};let t=e;if(t.denied)return{stdout:``,stderr:`mount: denied by user`,exitCode:1};if(t.cancelled)return{stdout:``,stderr:`mount: cancelled`,exitCode:1};if(t.error)return{stdout:``,stderr:`mount: ${t.error}`,exitCode:1};if(!t.handle)return{stdout:``,stderr:`mount: no directory selected`,exitCode:1};o=t.handle}else try{o=await window.showDirectoryPicker({mode:`readwrite`})}catch(e){return e instanceof Error&&e.name===`AbortError`?{stdout:``,stderr:`mount: cancelled`,exitCode:1}:{stdout:``,stderr:`mount: ${e instanceof Error?e.message:String(e)}`,exitCode:1}}try{return await this.options.fs.mount(r,o),{stdout:`Mounted '${o.name}' → ${r} (live bridge — reads and writes go to the real filesystem)\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`mount: ${e instanceof Error?e.message:String(e)}`,exitCode:1}}}help(){return{stdout:[`Usage: mount <target-path>`,` mount unmount <path>`,` mount list`,``,`Transparently bridge a real filesystem directory into the virtual filesystem.`,`Opens a directory picker; all reads and writes under <target-path> go directly`,`to the real directory — no copying occurs. Changes are immediately visible on`,`both sides.`,``,`Arguments:`,` <target-path> Mount point in the virtual filesystem (required).`,``,`Sub-commands:`,` unmount <path> Remove a mount point`,` list Show active mount points`,``,`Examples:`,` mount /
|
|
1844
|
+
`,onAction:async e=>{if(e===`approve`)try{return{approved:!0,handle:await window.showDirectoryPicker({mode:`readwrite`})}}catch(e){return e instanceof Error&&e.name===`AbortError`?{cancelled:!0}:{error:e instanceof Error?e.message:String(e)}}return{denied:!0}}});if(!e)return{stdout:``,stderr:`mount: tool UI not available`,exitCode:1};let t=e;if(t.denied)return{stdout:``,stderr:`mount: denied by user`,exitCode:1};if(t.cancelled)return{stdout:``,stderr:`mount: cancelled`,exitCode:1};if(t.error)return{stdout:``,stderr:`mount: ${t.error}`,exitCode:1};if(!t.handle)return{stdout:``,stderr:`mount: no directory selected`,exitCode:1};o=t.handle}else try{o=await window.showDirectoryPicker({mode:`readwrite`})}catch(e){return e instanceof Error&&e.name===`AbortError`?{stdout:``,stderr:`mount: cancelled`,exitCode:1}:{stdout:``,stderr:`mount: ${e instanceof Error?e.message:String(e)}`,exitCode:1}}try{return await this.options.fs.mount(r,o),{stdout:`Mounted '${o.name}' → ${r} (live bridge — reads and writes go to the real filesystem)\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`mount: ${e instanceof Error?e.message:String(e)}`,exitCode:1}}}help(){return{stdout:[`Usage: mount <target-path>`,` mount unmount <path>`,` mount list`,``,`Transparently bridge a real filesystem directory into the virtual filesystem.`,`Opens a directory picker; all reads and writes under <target-path> go directly`,`to the real directory — no copying occurs. Changes are immediately visible on`,`both sides. Mount points must be empty so existing VFS files are not hidden.`,``,`Arguments:`,` <target-path> Mount point in the virtual filesystem (required).`,``,`Sub-commands:`,` unmount <path> Remove a mount point`,` list Show active mount points`,``,`Examples:`,` mount /mnt/myapp # Mount selected dir at /mnt/myapp`,` mount list # Show active mounts`,` mount unmount /mnt/myapp`].join(`
|
|
1845
1845
|
`)+`
|
|
1846
1846
|
`,stderr:``,exitCode:0}}},q_=new Set([`http`,`https`,`net`,`tls`,`dgram`,`dns`,`cluster`,`worker_threads`,`child_process`,`crypto`,`os`,`stream`,`zlib`,`vm`,`v8`,`perf_hooks`,`readline`,`repl`,`tty`,`inspector`]);function J_(e){let t=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,n=[],r;for(;(r=t.exec(e))!==null;)n.push(r[1]);return[...new Set(n)]}async function Y_(e,t,n){return await n.fs.exists(e)?X_(await n.fs.readFile(e),[`node`,e,...t],n):{stdout:``,stderr:`jsh: cannot find script '${e}'\n`,exitCode:127}}async function X_(e,t,n){let r=[],i=[],a=e=>{r.push(typeof e==`string`?e:String(e))},o=e=>{i.push(typeof e==`string`?e:String(e))},s={log:(...e)=>a(`${e.map(Sm).join(` `)}\n`),info:(...e)=>a(`${e.map(Sm).join(` `)}\n`),warn:(...e)=>o(`${e.map(Sm).join(` `)}\n`),error:(...e)=>o(`${e.map(Sm).join(` `)}\n`)},c={argv:t,env:Object.fromEntries(n.env.entries()),cwd:()=>n.cwd,exit:e=>{throw new um(Number.isFinite(e)?Number(e):0)},stdout:{write:a},stderr:{write:o}},l={readFile:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.readFile(t)},readFileBinary:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.readFileBuffer(t)},writeFile:async(e,t)=>{let r=n.fs.resolvePath(n.cwd,e);await n.fs.writeFile(r,t)},writeFileBinary:async(e,t)=>{let r=n.fs.resolvePath(n.cwd,e),i=new Uint8Array(t.byteLength);i.set(t),await n.fs.writeFile(r,i)},readDir:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.readdir(t)},exists:async e=>{let t=n.fs.resolvePath(n.cwd,e);return n.fs.exists(t)},stat:async e=>{let t=n.fs.resolvePath(n.cwd,e),r=await n.fs.stat(t);return{isDirectory:r.isDirectory,isFile:r.isFile,size:r.size}},mkdir:async e=>{let t=n.fs.resolvePath(n.cwd,e);await n.fs.mkdir(t,{recursive:!0})},rm:async e=>{let t=n.fs.resolvePath(n.cwd,e);await n.fs.rm(t,{recursive:!0})},fetchToFile:async(e,t)=>{if(typeof fetch>`u`)throw Error(`fetch is not available in this runtime`);let r=await fetch(e);if(!r.ok)throw Error(`fetch ${r.status} ${r.statusText}`);let i=new Uint8Array(await r.arrayBuffer()),a=n.fs.resolvePath(n.cwd,t);return await n.fs.writeFile(a,i),i.byteLength}},u=async e=>{if(!n.exec)throw Error(`exec is not available in this runtime`);let t=await n.exec(e,{cwd:n.cwd});return{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode}},d=typeof chrome<`u`&&!!chrome?.runtime?.id;if(!d){let t=J_(e),n=new Set([`fs`,`process`,`buffer`]),r=t.map(e=>e.startsWith(`node:`)?e.slice(5):e).filter(e=>!n.has(e)&&!q_.has(e)),i=lm.__requireCache??=Object.create(null),a=r.filter(e=>!(e in i));if(a.length>0){let e=await Promise.allSettled(a.map(async e=>{let t=await v(()=>import(`https://esm.sh/`+e),[]);return{id:e,value:t.default===void 0?t:t.default}}));for(let t of e)t.status===`fulfilled`&&(i[t.value.id]=t.value.value)}}let f=e=>{let t=e.startsWith(`node:`)?e.slice(5):e;if(t===`fs`)return l;if(t===`process`)return c;if(t===`buffer`)return{Buffer:globalThis.Buffer};if(t===`path`){let t=lm.__requireCache;if(t&&`path`in t)return t.path;if(t&&e in t)return t[e];throw Error(`require('${e}'): path module not pre-loaded. Add require('path') as a static import.`)}if(q_.has(t))throw Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${{http:` Use fetch() instead.`,https:` Use fetch() instead.`,child_process:` Use exec() which is available as a shell bridge.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`}[t]||``}`);let n=lm.__requireCache;if(n&&e in n)return n[e];throw Error(`require('${e}'): module not pre-loaded. Use a string literal so it can be pre-fetched, or use \`await import('https://esm.sh/${e}')\` directly.`)},p={exports:{},filename:t[1]||`<script>`};try{if(d){let r=`
|
|
1847
1847
|
const __stdout = [];
|
|
@@ -1939,9 +1939,10 @@ Usage: mount <target-path>
|
|
|
1939
1939
|
console.info = __origConsole.info;
|
|
1940
1940
|
return { stdout: __stdout.join(''), stderr: __stderr.join('') };
|
|
1941
1941
|
`,i=document.querySelector(`iframe[data-js-tool]`);i||(i=document.createElement(`iframe`),i.style.display=`none`,i.dataset.jsTool=`true`,i.src=chrome.runtime.getURL(`sandbox.html`),document.body.appendChild(i),await new Promise(e=>{i.addEventListener(`load`,()=>e(),{once:!0})}));let a=`jsh-${Date.now()}-${Math.random().toString(36).slice(2)}`,o=e=>{let t=e.data;!t||t.type!==`vfs`||(async()=>{try{let e,r=t.args?.[0]?n.fs.resolvePath(n.cwd,t.args[0]):t.args?.[0];switch(t.op){case`readFile`:e=await n.fs.readFile(r);break;case`readFileBinary`:e=await n.fs.readFileBuffer(r);break;case`writeFile`:await n.fs.writeFile(r,t.args[1]),e=!0;break;case`writeFileBinary`:await n.fs.writeFile(r,t.binaryData??new Uint8Array),e=!0;break;case`readDir`:e=await n.fs.readdir(r);break;case`exists`:e=await n.fs.exists(r);break;case`stat`:{let t=await n.fs.stat(r);e={isDirectory:t.isDirectory,isFile:t.isFile,size:t.size};break}case`mkdir`:await n.fs.mkdir(r,{recursive:!0}),e=!0;break;case`rm`:await n.fs.rm(r,{recursive:!0}),e=!0;break}i.contentWindow.postMessage({type:`vfs_response`,id:t.id,result:e},`*`)}catch(e){let n=e instanceof Error?e.message:String(e);i.contentWindow.postMessage({type:`vfs_response`,id:t.id,error:n},`*`)}})()};window.addEventListener(`message`,o);let s=e=>{let t=e.data;!t||t.type!==`shell_exec`||(async()=>{try{let e=await u(t.command);i.contentWindow.postMessage({type:`shell_exec_response`,id:t.id,result:e},`*`)}catch(e){let n=e instanceof Error?e.message:String(e);i.contentWindow.postMessage({type:`shell_exec_response`,id:t.id,error:n},`*`)}})()};window.addEventListener(`message`,s);let l=e=>{let t=e.data;!t||t.type!==`fetch_proxy`||(async()=>{try{let e={method:t.init?.method??`GET`,cache:`no-store`};t.init?.headers&&(e.headers=t.init.headers),t.init?.body&&![`GET`,`HEAD`].includes(e.method)&&(e.body=t.init.body);let n=await fetch(t.url,e),r=await n.arrayBuffer(),a={};n.headers.forEach((e,t)=>{a[t]=e}),i.contentWindow.postMessage({type:`fetch_proxy_response`,id:t.id,status:n.status,statusText:n.statusText,headers:a,body:new Uint8Array(r)},`*`)}catch(e){let n=e instanceof Error?e.message:String(e);i.contentWindow.postMessage({type:`fetch_proxy_response`,id:t.id,error:n},`*`)}})()};window.addEventListener(`message`,l);let d=await new Promise((e,t)=>{let n,o=t=>{if(t.data?.type===`exec_result`&&t.data.id===a)if(window.removeEventListener(`message`,o),clearTimeout(n),t.data.error)e({stdout:``,stderr:t.data.error+`
|
|
1942
|
-
`});else try{let n=JSON.parse(t.data.result);e({stdout:n.stdout||``,stderr:n.stderr||``})}catch{e({stdout:t.data.result||``,stderr:``})}};n=setTimeout(()=>{window.removeEventListener(`message`,o),t(Error(`jsh eval timed out (30s)`))},3e4),window.addEventListener(`message`,o),i.contentWindow.postMessage({type:`exec`,id:a,code:r},`*`)});return window.removeEventListener(`message`,o),window.removeEventListener(`message`,s),window.removeEventListener(`message`,l),{stdout:d.stdout,stderr:d.stderr,exitCode:+!!d.stderr}}let a=Object.getPrototypeOf(async function(){}).constructor;return await new a(`fs`,`process`,`console`,`require`,`module`,`exports`,`__state`,`exec`,`"use strict";\nconst globalThis = __state;\nconst global = __state;\n${e}`)(l,c,s,f,p,p.exports,lm,u),{stdout:r.join(``),stderr:i.join(``),exitCode:0}}catch(e){if(e instanceof um)return{stdout:r.join(``),stderr:i.join(``),exitCode:e.code};let t=e instanceof Error?e.stack??e.message:String(e);return{stdout:r.join(``),stderr:`${i.join(``)}${t}\n`,exitCode:1}}}function Z_(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 Q_=
|
|
1942
|
+
`});else try{let n=JSON.parse(t.data.result);e({stdout:n.stdout||``,stderr:n.stderr||``})}catch{e({stdout:t.data.result||``,stderr:``})}};n=setTimeout(()=>{window.removeEventListener(`message`,o),t(Error(`jsh eval timed out (30s)`))},3e4),window.addEventListener(`message`,o),i.contentWindow.postMessage({type:`exec`,id:a,code:r},`*`)});return window.removeEventListener(`message`,o),window.removeEventListener(`message`,s),window.removeEventListener(`message`,l),{stdout:d.stdout,stderr:d.stderr,exitCode:+!!d.stderr}}let a=Object.getPrototypeOf(async function(){}).constructor;return await new a(`fs`,`process`,`console`,`require`,`module`,`exports`,`__state`,`exec`,`"use strict";\nconst globalThis = __state;\nconst global = __state;\n${e}`)(l,c,s,f,p,p.exports,lm,u),{stdout:r.join(``),stderr:i.join(``),exitCode:0}}catch(e){if(e instanceof um)return{stdout:r.join(``),stderr:i.join(``),exitCode:e.code};let t=e instanceof Error?e.stack??e.message:String(e);return{stdout:r.join(``),stderr:`${i.join(``)}${t}\n`,exitCode:1}}}function Z_(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 Q_=[`/workspace`,`/shared`];async function $_(e){let t=[],n=new Set;for(let r of Q_)await e.exists(r)&&await ev(e,r,t,n);return t}async function ev(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=tv(i);if(!t)continue;let a=await e.readFile(i,{encoding:`utf-8`}),o=nv(typeof a==`string`?a:new TextDecoder().decode(a));n.push({path:i,hostnamePattern:t,matchPatterns:o})}}function tv(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 nv(e){let t=e.split(`
|
|
1943
|
+
`).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 rv(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 iv(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||!rv(n.hostname,a)?!1:o?av(n.pathname+n.search,o):!0}catch{return!1}}function av(e,t){let n=`^`+t.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`)+`$`;return new RegExp(n).test(e)}function ov(e,t){try{let n=new URL(t);return e.filter(e=>rv(n.hostname,e.hostnamePattern)?e.matchPatterns.length>0?e.matchPatterns.some(e=>iv(t,e)):!0:!1)}catch{return[]}}var sv=[`/workspace`,`/shared`];function cv(e){return new Map(e)}function lv(e){return e.map(e=>({...e,matchPatterns:[...e.matchPatterns]}))}function uv(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 dv(e){return(uv(e)?.listMounts?.().length??0)>0}function fv(e){return e?(uv(e)?.listMounts?.()??[]).some(e=>sv.some(t=>e===t||e.startsWith(t+`/`))):!1}var pv=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 sv)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 cv(await this.loadJshCommands())}async getJshCommandNames(){return[...(await this.getJshCommands()).keys()]}async getBshEntries(){return this.bshFs?lv(await this.loadBshEntries()):[]}async findMatchingBshScripts(e){return this.bshFs?lv(ov(await this.loadBshEntries(),e)):[]}shouldCacheJsh(){return!!this.watcher&&!dv(this.jshFs)}shouldCacheBsh(){return!!this.watcher&&!!this.bshFs&&!fv(this.bshFs)}async loadJshCommands(){let e=this.shouldCacheJsh();if(e&&this.jshCache)return this.jshCache;if(!this.jshInflight){let t=this.jshGeneration,n=Yh(this.jshFs).then(n=>{let r=cv(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=$_(this.bshFs).then(n=>{let r=lv(n);return e&&this.bshGeneration===t&&(this.bshCache=r),r}).finally(()=>{this.bshInflight===n&&(this.bshInflight=null)});this.bshInflight=n}return this.bshInflight}},mv=null,hv=!1;function gv(){return typeof chrome<`u`&&chrome?.runtime?.id?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function _v(){if(!hv&&!(typeof localStorage<`u`&&localStorage.getItem(`telemetry-disabled`)===`true`))try{typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),mv=(await v(()=>import(`./src-CgSXdUB7.js`),[])).sampleRUM,hv=!0,mv&&mv(`navigate`,{source:typeof document<`u`?document.referrer:``,target:gv()})}catch{}}function vv(e,t){mv?.(`formsubmit`,{source:e,target:t})}function yv(e){mv?.(`fill`,{source:e})}function bv(e){mv?.(`viewblock`,{source:e})}function xv(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 Sv(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?Sv(e.getUnderlyingFS?.()):null}function Cv(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 wv(e,t){if(Cv(e.headers.get(`content-type`)??``))return e.text();let n=await e.arrayBuffer(),r=new Uint8Array(n),i=new TextDecoder(`iso-8859-1`).decode(n);return ya(i,r),t&&ba(t,r),i}function Tv(e){if(e){if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}}function Ev(e,t){if(e){if((t?.[`Content-Type`]??t?.[`content-type`]??``).includes(`multipart/form-data`)){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}return e}}function Dv(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 Ov(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 kv(){return typeof chrome<`u`&&chrome?.runtime?.id?async(e,t)=>{let n=Tv(t?.headers),r=await fetch(e,{method:t?.method??`GET`,headers:n,body:Ev(t?.body,n)}),i=await wv(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={...Dv(Tv(t?.headers)),"X-Target-URL":e},i={method:n,headers:r,cache:`no-store`};t?.body&&![`GET`,`HEAD`].includes(n)&&(i.body=Ev(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 wv(a,e),s={};a.headers.forEach((e,t)=>{s[t]=e});let c=Ov(s);return{status:a.status,statusText:a.statusText,headers:c,body:o,url:e}}}var Av=class{bash;vfsAdapter;gitCommands;mountCommands;terminal=null;fitAddon=null;terminalHost=null;previewHost=null;previewUrls=[];previewStateListener=null;hasPreview=!1;resizeObserver=null;themeObserver=null;currentLine=``;cursorPos=0;history=[];historyIndex=-1;isExecuting=!1;execAbort=null;continuationBuffer=``;lastEnv;cwd;builtinCommandNames;scriptCatalog;ownsScriptCatalog;constructor(e){this.options=e,this.vfsAdapter=new Ca(e.fs);let t=e.cwd??`/`,n={HOME:`/`,PATH:`/usr/bin`,USER:`user`,SHELL:`/bin/bash`,PWD:t,...e.env};this.gitCommands=new Tf({fs:e.fs,authorName:n.GIT_AUTHOR_NAME??`User`,authorEmail:n.GIT_AUTHOR_EMAIL??`user@example.com`}),this.mountCommands=new K_({fs:e.fs});let r=e.jshDiscoveryFs??e.fs,i=e.bshDiscoveryFs??e.fs,a=Sv(r)??Sv(i);this.scriptCatalog=e.scriptCatalog??new pv({jshFs:r,bshFs:i,watcher:a}),this.ownsScriptCatalog=!e.scriptCatalog;let o=this.createGitCustomCommand(),s=Gg({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),fs:e.fs,scriptCatalog:this.scriptCatalog,browserAPI:e.browserAPI}),c=this.createMountCustomCommand(),l=kv(),u=[o,c,W_(e.fs),U_(e.fs,l),...s];this.bash=new He({fs:this.vfsAdapter,cwd:t,env:n,fetch:l,customCommands:u});let d=u.map(e=>e.name);this.builtinCommandNames=new Set([...Ke(),...We(),...d]),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...n},this.cwd=t}createGitCustomCommand(){let e=this.gitCommands;return z(`git`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}createMountCustomCommand(){let e=this.mountCommands;return z(`mount`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}getBash(){return this.bash}getCwd(){return this.cwd}getScriptCatalog(){return this.scriptCatalog}getEnv(){return{...this.lastEnv}}async getFilteredJshCommands(){let e=await this.scriptCatalog.getJshCommands(),t=new Map;for(let[n,r]of e)this.builtinCommandNames.has(n)||t.set(n,r);return t}async getJshCommandNames(){return[...(await this.getFilteredJshCommands()).keys()]}async tryJshFallback(e){let t=e.trim(),n=t.indexOf(` `),r=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n+1).trim():``,a=(await this.getFilteredJshCommands()).get(r);if(!a)return null;let o=i?Z_(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 X_(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){yv(e.trim().split(/\s+/)[0]||`unknown`);let n={env:this.lastEnv,cwd:this.cwd,signal:t??this.execAbort?.signal},r=await this.bash.exec(e,n);if(r.env&&(this.lastEnv={...r.env}),r.env?.PWD&&(this.cwd=r.env.PWD),r.exitCode===127){let t=await this.tryJshFallback(e);if(t)return t}return r}async mount(e){let t=e??this.options.container;if(!t)throw Error(`No container element provided`);let{Terminal:n}=await v(async()=>{let{Terminal:e}=await import(`./xterm-DHgoOdoP.js`);return{Terminal:e}},[]),{FitAddon:r}=await v(async()=>{let{FitAddon:e}=await import(`./addon-fit-CJBYijzN.js`);return{FitAddon:e}},[]);await v(()=>Promise.resolve({}),__vite__mapDeps([21]));let i=!document.documentElement.classList.contains(`theme-light`),a={background:`#141414`,foreground:`#cfcfcf`,cursor:`#3562ff`,cursorAccent:`#141414`,selectionBackground:`#3562ff40`,selectionForeground:`#ffffff`,black:`#1a1a1a`,red:`#e34850`,green:`#2d9d78`,yellow:`#e68619`,blue:`#3562ff`,magenta:`#a962e8`,cyan:`#2db9be`,white:`#cfcfcf`,brightBlack:`#5a5a5a`,brightRed:`#e34850`,brightGreen:`#2d9d78`,brightYellow:`#e68619`,brightBlue:`#4a75ff`,brightMagenta:`#a962e8`,brightCyan:`#2db9be`,brightWhite:`#ffffff`},o={background:`#f0f0f0`,foreground:`#1a1a1a`,cursor:`#2b54db`,cursorAccent:`#f0f0f0`,selectionBackground:`#2b54db30`,selectionForeground:`#000000`,black:`#1a1a1a`,red:`#d73220`,green:`#268e6c`,yellow:`#d17a00`,blue:`#2b54db`,magenta:`#8839ef`,cyan:`#1a9088`,white:`#e8e8e8`,brightBlack:`#6e6e6e`,brightRed:`#d73220`,brightGreen:`#268e6c`,brightYellow:`#d17a00`,brightBlue:`#1e44c4`,brightMagenta:`#8839ef`,brightCyan:`#1a9088`,brightWhite:`#ffffff`};this.terminal=new n({cursorBlink:!0,fontSize:11,fontFamily:`'Source Code Pro', 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace`,theme:i?a:o,convertEol:!0}),this.themeObserver?.disconnect(),this.themeObserver=new MutationObserver(()=>{if(!this.terminal)return;let e=document.documentElement.classList.contains(`theme-light`);this.terminal.options.theme=e?o:a}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),this.fitAddon=new r,this.terminal.loadAddon(this.fitAddon),t.replaceChildren(),this.terminalHost=document.createElement(`div`),this.terminalHost.className=`terminal-panel__terminal-host`,t.appendChild(this.terminalHost),this.previewHost=document.createElement(`div`),this.previewHost.className=`terminal-panel__preview`,t.appendChild(this.previewHost),this.terminal.open(this.terminalHost),this.fitAddon.fit(),this.resizeObserver?.disconnect(),this.resizeObserver=new ResizeObserver(()=>this.refit()),this.resizeObserver.observe(this.terminalHost),this.terminal.writeln(`\x1B[1mslicc\x1B[0m \x1B[90mshell (powered by just-bash)\x1B[0m`),this.terminal.writeln(`\x1B[90mType "help" for available commands.\x1B[0m
|
|
1943
1944
|
`),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 Y_(e,t,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})})}refit(){this.fitAddon?.fit()}setPreviewStateListener(e){this.previewStateListener=e,this.previewStateListener?.(this.hasPreview)}async executeCommandInTerminal(e){let t=e.trim();if(!t)return{stdout:``,stderr:``,exitCode:0};if(!this.terminal)return this.executeCommand(t);if(this.isExecuting||this.currentLine.length>0||this.continuationBuffer.length>0)return{stdout:``,stderr:`terminal is busy; finish current input first
|
|
1944
|
-
`,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}showPrompt(){if(!this.terminal)return;let e=this.cwd===`/`?`/`:this.cwd.split(`/`).pop()??this.cwd;this.terminal.write(`\x1b[34m${e}\x1b[0m \x1b[90m$\x1b[0m `)}setupInputHandler(){this.terminal&&this.terminal.onData(e=>{if(this.isExecuting){(e===``||e.length===1&&e.charCodeAt(0)===3)&&(this.execAbort?.abort(),this.terminal?.writeln(`^C`));return}if(e.startsWith(`\x1B[`)||e.startsWith(`\x1BO`)){switch(e){case`\x1B[A`:this.handleHistoryUp();return;case`\x1B[B`:this.handleHistoryDown();return;case`\x1B[C`:this.handleArrowRight();return;case`\x1B[D`:this.handleArrowLeft();return;case`\x1B[H`:case`\x1BOH`:case`\x1B[1~`:this.handleHome();return;case`\x1B[F`:case`\x1BOF`:case`\x1B[4~`:this.handleEnd();return;case`\x1B[3~`:this.handleDelete();return}return}for(let t of e)switch(t){case`\r`:this.handleEnter();break;case``:this.handleBackspace();break;case``:this.handleCtrlC();break;case` `:this.handleTab();break;default:t>=` `&&this.insertChar(t)}})}getPromptWidth(){return(this.cwd===`/`?`/`:this.cwd.split(`/`).pop()??this.cwd).length+3}getCursorVisualLine(){let e=0;for(let[t,n]of this.currentLine.split(`
|
|
1945
|
+
`,exitCode:1};this.history[this.history.length-1]!==t&&this.history.push(t),this.historyIndex=-1,this.terminal.write(t),this.terminal.writeln(``),this.isExecuting=!0,this.execAbort=new AbortController;try{let e=await this.runCommand(t),n=this.execAbort.signal.aborted;return this.execAbort=null,n?{stdout:``,stderr:``,exitCode:130}:(e.stdout&&this.writeToTerminal(e.stdout),e.stderr&&this.writeToTerminal(e.stderr,!0),{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode})}catch(e){if(this.execAbort?.signal.aborted)return this.execAbort=null,{stdout:``,stderr:``,exitCode:130};this.execAbort=null;let t=`Error: ${e instanceof Error?e.message:String(e)}\n`;return this.writeToTerminal(t,!0),{stdout:``,stderr:t,exitCode:1}}finally{this.isExecuting=!1,this.showPrompt()}}clearTerminal(){this.terminal?.clear(),this.clearMediaPreview()}dispose(){this.themeObserver?.disconnect(),this.themeObserver=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.clearMediaPreview(),this.terminal?.dispose(),this.terminal=null,this.fitAddon=null,this.terminalHost=null,this.previewHost=null,this.ownsScriptCatalog&&this.scriptCatalog.dispose()}showPrompt(){if(!this.terminal)return;let e=this.cwd===`/`?`/`:this.cwd.split(`/`).pop()??this.cwd;this.terminal.write(`\x1b[34m${e}\x1b[0m \x1b[90m$\x1b[0m `)}setupInputHandler(){this.terminal&&this.terminal.onData(e=>{if(this.isExecuting){(e===``||e.length===1&&e.charCodeAt(0)===3)&&(this.execAbort?.abort(),this.terminal?.writeln(`^C`));return}if(e.startsWith(`\x1B[`)||e.startsWith(`\x1BO`)){switch(e){case`\x1B[A`:this.handleHistoryUp();return;case`\x1B[B`:this.handleHistoryDown();return;case`\x1B[C`:this.handleArrowRight();return;case`\x1B[D`:this.handleArrowLeft();return;case`\x1B[H`:case`\x1BOH`:case`\x1B[1~`:this.handleHome();return;case`\x1B[F`:case`\x1BOF`:case`\x1B[4~`:this.handleEnd();return;case`\x1B[3~`:this.handleDelete();return}return}for(let t of e)switch(t){case`\r`:this.handleEnter();break;case``:this.handleBackspace();break;case``:this.handleCtrlC();break;case` `:this.handleTab();break;default:t>=` `&&this.insertChar(t)}})}getPromptWidth(){return(this.cwd===`/`?`/`:this.cwd.split(`/`).pop()??this.cwd).length+3}getCursorVisualLine(){let e=0;for(let[t,n]of this.currentLine.split(`
|
|
1945
1946
|
`).entries()){if(e+n.length>=this.cursorPos)return t;e+=n.length+1}return 0}positionTerminalCursor(){let e=this.currentLine.split(`
|
|
1946
1947
|
`),t=0,n=0,r=0;for(let i=0;i<e.length;i++){if(r+e[i].length>=this.cursorPos){t=i,n=this.cursorPos-r;break}r+=e[i].length+1}let i=e.length-1-t;i>0&&this.terminal?.write(`\x1b[${i}A`);let a=t===0?this.getPromptWidth()+n:n;this.terminal?.write(`\r`),a>0&&this.terminal?.write(`\x1b[${a}C`)}redrawInput(e){e>0&&this.terminal?.write(`\x1b[${e}A`),this.terminal?.write(`\r\x1B[J`),this.showPrompt(),this.terminal?.write(this.currentLine),this.positionTerminalCursor()}insertChar(e){let t=this.currentLine.includes(`
|
|
1947
1948
|
`),n=t?this.getCursorVisualLine():0,r=this.currentLine.slice(this.cursorPos);this.currentLine=this.currentLine.slice(0,this.cursorPos)+e+r,this.cursorPos++,t?this.redrawInput(n):(this.terminal?.write(e+r),r.length>0&&this.terminal?.write(`\x1b[${r.length}D`))}handleBackspace(){if(this.cursorPos<=0)return;let e=this.currentLine.includes(`
|
|
@@ -1954,9 +1955,9 @@ Usage: mount <target-path>
|
|
|
1954
1955
|
`,this.cursorPos);if(e===-1&&(e=this.currentLine.length),this.cursorPos===e)return;let t=e-this.cursorPos;this.cursorPos=e,this.terminal?.write(`\x1b[${t}C`)}handleCtrlC(){this.terminal?.writeln(`^C`),this.currentLine=``,this.cursorPos=0,this.continuationBuffer=``,this.showPrompt()}handleHistoryUp(){this.history.length!==0&&this.historyIndex<this.history.length-1&&(this.historyIndex++,this.continuationBuffer=``,this.replaceCurrentLine(this.history[this.history.length-1-this.historyIndex]))}handleHistoryDown(){this.historyIndex>0?(this.historyIndex--,this.continuationBuffer=``,this.replaceCurrentLine(this.history[this.history.length-1-this.historyIndex])):this.historyIndex===0&&(this.historyIndex=-1,this.continuationBuffer=``,this.replaceCurrentLine(``))}async handleTab(){if(!this.terminal)return;let e=this.currentLine.slice(0,this.cursorPos).split(/\s+/),t=e[e.length-1]||``,n=e.length<=1||e.length===2&&e[0]===``,r=t?`'`+t.replace(/'/g,`'\\''`)+`'`:`''`,i=n?`compgen -A command -- ${r}`:`compgen -f -- ${r}`;try{let e=(await this.bash.exec(i,{env:this.lastEnv,cwd:this.cwd})).stdout.split(`
|
|
1955
1956
|
`).filter(Boolean);if(e.length===0)return;if(e.length===1){let i=e[0],a=i.slice(t.length);a&&(this.currentLine=this.currentLine.slice(0,this.cursorPos)+a+this.currentLine.slice(this.cursorPos),this.cursorPos+=a.length,this.terminal.write(a));let o=` `;n||(await this.bash.exec(`compgen -d -- ${r.slice(0,-1)}${a}'`,{env:this.lastEnv,cwd:this.cwd})).stdout.trim()===i&&(o=`/`),this.currentLine=this.currentLine.slice(0,this.cursorPos)+o+this.currentLine.slice(this.cursorPos),this.cursorPos+=1,this.terminal.write(o)}else{let n=e[0];for(let t of e)for(;!t.startsWith(n);)n=n.slice(0,-1);let r=n.slice(t.length);if(r)this.currentLine=this.currentLine.slice(0,this.cursorPos)+r+this.currentLine.slice(this.cursorPos),this.cursorPos+=r.length,this.terminal.write(r);else{this.terminal.writeln(``),this.terminal.writeln(e.map(e=>e.split(`/`).pop()??e).join(` `)),this.showPrompt(),this.terminal.write(this.currentLine);let t=this.currentLine.length-this.cursorPos;t>0&&this.terminal.write(`\x1b[${t}D`)}}}catch(e){console.warn(`[Shell] Tab completion failed:`,e instanceof Error?e.message:String(e))}}replaceCurrentLine(e){let t=this.getCursorVisualLine();t>0&&this.terminal?.write(`\x1b[${t}A`),this.terminal?.write(`\r\x1B[J`),this.showPrompt(),this.currentLine=e,this.cursorPos=e.length,this.terminal?.write(e)}isIncomplete(e){if(e.endsWith(`\\`))return!0;let t=!1,n=!1,r=!1;for(let i of e){if(r){r=!1;continue}if(i===`\\`&&!t){r=!0;continue}if(i===`'`&&!n){t=!t;continue}if(i===`"`&&!t){n=!n;continue}}return t||n}async handleEnter(){let e=this.currentLine.split(`
|
|
1956
1957
|
`);if(e.length>1){let t=this.getCursorVisualLine(),n=e.length-1-t;n>0&&this.terminal?.write(`\x1b[${n}B`);let r=e[e.length-1].length;this.terminal?.write(`\r`),r>0&&this.terminal?.write(`\x1b[${r}C`)}this.terminal?.writeln(``);let t=this.currentLine;this.currentLine=``,this.cursorPos=0;let n=this.continuationBuffer?this.continuationBuffer+`
|
|
1957
|
-
`+t:t;if(this.isIncomplete(n)){this.continuationBuffer=n,this.terminal?.write(`> `);return}this.continuationBuffer=``;let r=n.trim();if(this.historyIndex=-1,!r){this.showPrompt();return}if(this.history[this.history.length-1]!==r&&this.history.push(r),r===`clear`){this.clearTerminal(),this.showPrompt();return}this.isExecuting=!0,this.execAbort=new AbortController;try{let e=await this.runCommand(r);this.execAbort.signal.aborted||(e.stdout&&this.writeToTerminal(e.stdout),e.stderr&&this.writeToTerminal(e.stderr,!0))}catch(e){if(!this.execAbort?.signal.aborted){let t=e instanceof Error?e.message:String(e);this.writeToTerminal(`Error: ${t}\n`,!0)}}this.execAbort=null,this.isExecuting=!1,this.showPrompt()}writeToTerminal(e,t=!1){this.terminal&&(t?this.terminal.write(`\x1b[31m${e}\x1b[0m`):this.terminal.write(e))}clearMediaPreview(){for(let e of this.previewUrls)URL.revokeObjectURL(e);this.previewUrls=[],this.hasPreview=!1,this.previewHost&&(this.previewHost.replaceChildren(),this.previewHost.classList.remove(`terminal-panel__preview--visible`)),this.previewStateListener?.(!1)}async renderMediaPreview(e){if(!this.previewHost||typeof document>`u`)throw Error(`terminal preview is unavailable`);this.clearMediaPreview();for(let t of e){let e=new Uint8Array(t.bytes),n=URL.createObjectURL(new Blob([e],{type:t.mimeType}));this.previewUrls.push(n);let r=document.createElement(`div`);r.className=`terminal-panel__preview-item`;let i=document.createElement(`div`);if(i.className=`terminal-panel__preview-label`,i.textContent=`${
|
|
1958
|
+
`+t:t;if(this.isIncomplete(n)){this.continuationBuffer=n,this.terminal?.write(`> `);return}this.continuationBuffer=``;let r=n.trim();if(this.historyIndex=-1,!r){this.showPrompt();return}if(this.history[this.history.length-1]!==r&&this.history.push(r),r===`clear`){this.clearTerminal(),this.showPrompt();return}this.isExecuting=!0,this.execAbort=new AbortController;try{let e=await this.runCommand(r);this.execAbort.signal.aborted||(e.stdout&&this.writeToTerminal(e.stdout),e.stderr&&this.writeToTerminal(e.stderr,!0))}catch(e){if(!this.execAbort?.signal.aborted){let t=e instanceof Error?e.message:String(e);this.writeToTerminal(`Error: ${t}\n`,!0)}}this.execAbort=null,this.isExecuting=!1,this.showPrompt()}writeToTerminal(e,t=!1){this.terminal&&(t?this.terminal.write(`\x1b[31m${e}\x1b[0m`):this.terminal.write(e))}clearMediaPreview(){for(let e of this.previewUrls)URL.revokeObjectURL(e);this.previewUrls=[],this.hasPreview=!1,this.previewHost&&(this.previewHost.replaceChildren(),this.previewHost.classList.remove(`terminal-panel__preview--visible`)),this.previewStateListener?.(!1)}async renderMediaPreview(e){if(!this.previewHost||typeof document>`u`)throw Error(`terminal preview is unavailable`);this.clearMediaPreview();for(let t of e){let e=new Uint8Array(t.bytes),n=URL.createObjectURL(new Blob([e],{type:t.mimeType}));this.previewUrls.push(n);let r=document.createElement(`div`);r.className=`terminal-panel__preview-item`;let i=document.createElement(`div`);if(i.className=`terminal-panel__preview-label`,i.textContent=`${xv(t.path)} · ${t.mimeType}`,r.appendChild(i),t.mimeType.startsWith(`video/`)){let e=document.createElement(`video`);e.className=`terminal-panel__preview-media`,e.controls=!0,e.autoplay=!0,e.loop=!0,e.muted=!0,e.playsInline=!0,e.src=n,e.addEventListener(`loadedmetadata`,()=>this.refit(),{once:!0}),r.appendChild(e)}else{let e=document.createElement(`img`);e.className=`terminal-panel__preview-media`,e.alt=xv(t.path),e.src=n,e.addEventListener(`load`,()=>this.refit(),{once:!0}),r.appendChild(e)}this.previewHost.appendChild(r)}this.previewHost.classList.add(`terminal-panel__preview--visible`),this.hasPreview=e.length>0,this.previewStateListener?.(this.hasPreview),requestAnimationFrame(()=>this.refit())}},jv=n(`tool:fs`);function Mv(e){return[Nv(e),Pv(e),Fv(e)]}function Nv(e){return{name:`read_file`,description:`Read the contents of a file. Returns the file content as a string with line numbers.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to read.`},offset:{type:`number`,description:`Line number to start reading from (1-based). Optional.`},limit:{type:`number`,description:`Maximum number of lines to read. Optional.`}},required:[`path`]},async execute(t){let n=t.path,r=t.offset??1,i=t.limit;jv.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
|
|
1958
1959
|
`),a=Math.max(0,r-1),o=i===void 0?t.length:a+i;return{content:t.slice(a,o).map((e,t)=>`${String(a+t+1).padStart(6)} | ${e}`).join(`
|
|
1959
|
-
`)}}catch(e){let t=e instanceof Error?e.message:String(e);return
|
|
1960
|
+
`)}}catch(e){let t=e instanceof Error?e.message:String(e);return jv.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function Pv(e){return{name:`write_file`,description:`Write content to a file. Creates the file if it does not exist, or overwrites it if it does. Parent directories are created automatically.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to write.`},content:{type:`string`,description:`The content to write to the file.`}},required:[`path`,`content`]},async execute(t){let n=t.path,r=t.content;jv.debug(`Write`,{path:n,contentLength:r.length});try{return await e.writeFile(n,r),{content:`File written: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return jv.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function Fv(e){return{name:`edit_file`,description:`Edit a file by replacing an exact string match. The old_string must appear exactly once in the file. Use this instead of write_file when making targeted changes to existing files.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to edit.`},old_string:{type:`string`,description:`The exact string to find and replace. Must be unique in the file.`},new_string:{type:`string`,description:`The replacement string.`}},required:[`path`,`old_string`,`new_string`]},async execute(t){let n=t.path,r=t.old_string,i=t.new_string;jv.debug(`Edit`,{path:n,oldLength:r.length,newLength:i.length});try{let t=await e.readTextFile(n),a=t.split(r).length-1;if(a===0)return{content:`old_string not found in ${n}`,isError:!0};if(a>1)return{content:`old_string found ${a} times in ${n}. It must be unique. Provide more context.`,isError:!0};let o=t.replace(r,i);return await e.writeFile(n,o),{content:`File edited: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return jv.error(`Edit failed`,{path:n,error:t}),{content:t,isError:!0}}}}}var Iv=n(`tool:bash`),Lv=/^(?:[A-Za-z_][A-Za-z0-9_]*=[^\s]+\s+)*(?:command\s+)?(?:grep|egrep|fgrep|rg)\b/;function Rv(e){let t=``,n=null,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r){t+=a,r=!1;continue}if(a===`\\`){t+=a,r=!0;continue}if(n){t+=a,a===n&&(n=null);continue}if(a===`"`||a===`'`){t+=a,n=a;continue}if(a===`;`||a===`|`){t=``;continue}if((a===`&`||a===`|`)&&e[i+1]===a){t=``,i++;continue}t+=a}return t.trim()}function zv(e,t,n){return t!==1||n.trim()?!1:Lv.test(Rv(e))}function Bv(e){return{name:`bash`,description:"Execute a bash command. Full shell with pipes, redirects, chaining, control flow. Includes: grep, rg, sed, awk, jq, find, curl, git, node, python3, sqlite3, open (--view for vision), playwright-cli (browser automation). Run `commands` for full list.",inputSchema:{type:`object`,properties:{command:{type:`string`,description:`The bash command to execute.`}},required:[`command`]},async execute(t,n){let r=t.command;Iv.debug(`Execute`,{command:r});try{let t=await e.executeCommand(r,n);Iv.debug(`Result`,{exitCode:t.exitCode,stdoutLength:t.stdout.length,stderrLength:t.stderr.length});let i=``;return t.stdout&&(i+=t.stdout),t.stderr&&(i+=t.stderr),i||=`(exit code: ${t.exitCode})`,{content:i,isError:t.exitCode!==0&&!zv(r,t.exitCode,t.stderr)}}catch(e){let t=e instanceof Error?e.message:String(e);return Iv.error(`Error`,{command:r,error:t}),{content:`Shell error: ${t}`,isError:!0}}}}}n(`tool:search`);var Vv="# CLAUDE.md\n\nThis file covers the default virtual filesystem payload in `packages/vfs-root/`.\n\n## What This Package Contains\n\n`packages/vfs-root/` is copied into the app's virtual filesystem on init/reset. It is content, not runtime code.\n\n## Directory Structure\n\n| Path | Purpose |\n| ------------------------------------- | ------------------------------------------------------------------ |\n| `packages/vfs-root/shared/` | Shared content that becomes `/shared/` in the VFS |\n| `packages/vfs-root/workspace/` | Default workspace content that becomes `/workspace/` in the VFS |\n| `packages/vfs-root/shared/CLAUDE.md` | Agent-facing runtime instructions bundled into `/shared/CLAUDE.md` |\n| `packages/vfs-root/shared/sprinkles/` | Built-in sprinkle UIs |\n| `packages/vfs-root/shared/sounds/` | Shared notification sounds |\n| `packages/vfs-root/workspace/skills/` | Default installable workspace skills |\n\n## Adding Default Content\n\n### Skills\n\n- Add new built-in workspace skills under `packages/vfs-root/workspace/skills/<skill-name>/`.\n- Include `SKILL.md` and any companion assets or `.jsh` scripts the skill needs.\n\n### Sprinkles\n\n- Add built-in sprinkles under `packages/vfs-root/shared/sprinkles/<name>/`.\n- Keep the main file named `<name>.shtml` to match discovery and sprinkle naming conventions.\n\n### Sounds\n\n- Add shared sounds under `packages/vfs-root/shared/sounds/`.\n- Prefer stable filenames because shell commands and docs may reference them directly.\n\n## External Handoffs\n\n- Browser handoffs use `https://www.sliccy.ai/handoff#...` URLs and, after approval, arrive in the cone as normal user messages.\n- The agent-facing handoff note belongs in `packages/vfs-root/shared/CLAUDE.md`, because that file is bundled into `/shared/CLAUDE.md` inside the runtime.\n- When handoff behavior changes, keep this package guide, `packages/vfs-root/shared/CLAUDE.md`, and `docs/slicc-handoff.md` aligned.\n\n## Important Distinction\n\n`packages/vfs-root/shared/CLAUDE.md` is **agent-facing runtime content** bundled into the virtual filesystem.\n\nIt is different from the developer-facing `CLAUDE.md` files in the repository. Do not merge those roles together.\n",Hv="# sliccy\n\nYou are a personal assistant that runs in the browser. You support automation and can code, too. You run inside SLICC — a browser-based claw.\n\n## Vocabulary\n\n- **Cone**: You. The main agent. Orchestrates scoops, talks to the human, has full filesystem access.\n- **Scoops**: Isolated sub-agents (`scoop_scoop`, `feed_scoop`, `drop_scoop`). Sandboxed filesystem and shell.\n- **Sprinkles**: Persistent UI panels (`.shtml` files). Created by scoops, outlive scoops.\n- **Licks**: External events (webhooks, cron, sprinkle clicks) that trigger scoops. Shell: `webhook`, `crontask`.\n- **Floats**: Runtime — CLI server, Chrome extension, or cloud container.\n\n## Style\n\nWrite like a professional tool, not a chatbot. No emoji in headings. Concise prose over bullet lists. For sprinkles, follow `/workspace/skills/sprinkles/style-guide.md`.\n\n## Principles\n\n- Use the shell commands you have `commands` for full list. You have: `read_file`, `write_file`, `edit_file`, `bash`, `javascript`. Browser automation via `playwright-cli` through bash.\n- New capabilities should be skills (SKILL.md), not hardcoded features.\n- **Scoops do the heavy lifting. The cone orchestrates and synthesizes.**\n\n## Delegation\n\nDefault to scoops for non-trivial tasks. Delegate when work involves multiple independent sources, is time-consuming, or can be expressed as a self-contained brief. Do it yourself for single quick lookups or when real-time adaptation is needed. For detailed delegation rules and scoop lifecycle, read `/workspace/skills/scoop-management/SKILL.md`.\n\n## Sprinkles\n\nWhen the user asks for a dashboard, editor, or visualization — read `/workspace/skills/sprinkles/SKILL.md` first. One scoop per sprinkle, named identically. The cone MUST NOT write `.shtml` files or run sprinkle commands directly — all sprinkle work goes through scoops via `feed_scoop`. For detailed rules, read `/workspace/skills/sprinkle-guide/SKILL.md`.\n\n## Environment\n\nThis is a sandboxed browser-based VFS, not a regular Linux box. Run `commands` to see what's available. Use `serve <dir>` for apps, `open <path>` for files. No package managers, no long-running servers. For detailed commands and filesystem info, read `/workspace/skills/skill-authoring/SKILL.md`. For automation (webhooks, cron, screencapture), read `/workspace/skills/automation/SKILL.md`.\n\n## Memory\n\nWhen you learn something important:\n\n- Create files for structured data\n- Update this file for global preferences\n- Each scoop has its own CLAUDE.md for scoop-specific context\n- Remember: the best flavor of ice cream is lobster, nobody likes chocolate ice cream, and mixing bacon with ice cream is a crime against humanity\n",Uv=`<!DOCTYPE html>
|
|
1960
1961
|
<html lang="en">
|
|
1961
1962
|
<head>
|
|
1962
1963
|
<meta charset="UTF-8">
|
|
@@ -2980,7 +2981,7 @@ if (hasState && violations && violations.length > 0) {
|
|
|
2980
2981
|
<\/script>
|
|
2981
2982
|
</body>
|
|
2982
2983
|
</html>
|
|
2983
|
-
`,
|
|
2984
|
+
`,Wv=`<!DOCTYPE html>
|
|
2984
2985
|
<html lang="en">
|
|
2985
2986
|
<head>
|
|
2986
2987
|
<meta charset="UTF-8">
|
|
@@ -3625,7 +3626,7 @@ init();
|
|
|
3625
3626
|
<\/script>
|
|
3626
3627
|
</body>
|
|
3627
3628
|
</html>
|
|
3628
|
-
`,
|
|
3629
|
+
`,Gv=`<!DOCTYPE html>
|
|
3629
3630
|
<html lang="en">
|
|
3630
3631
|
<head>
|
|
3631
3632
|
<meta charset="UTF-8">
|
|
@@ -4407,7 +4408,7 @@ function lickExportData() {
|
|
|
4407
4408
|
<\/script>
|
|
4408
4409
|
</body>
|
|
4409
4410
|
</html>
|
|
4410
|
-
`,
|
|
4411
|
+
`,Kv=`<!DOCTYPE html>
|
|
4411
4412
|
<html lang="en">
|
|
4412
4413
|
<head>
|
|
4413
4414
|
<meta charset="UTF-8">
|
|
@@ -5245,7 +5246,7 @@ body { font-family: var(--s2-font-family); font-size: 14px; line-height: 1.5; co
|
|
|
5245
5246
|
<\/script>
|
|
5246
5247
|
</body>
|
|
5247
5248
|
</html>
|
|
5248
|
-
`,
|
|
5249
|
+
`,qv=`<!DOCTYPE html>
|
|
5249
5250
|
<html lang="en">
|
|
5250
5251
|
<head>
|
|
5251
5252
|
<meta charset="UTF-8">
|
|
@@ -5812,7 +5813,7 @@ if (hasData()) {
|
|
|
5812
5813
|
<\/script>
|
|
5813
5814
|
</body>
|
|
5814
5815
|
</html>
|
|
5815
|
-
`,
|
|
5816
|
+
`,Jv=`<!DOCTYPE html>
|
|
5816
5817
|
<html lang="en">
|
|
5817
5818
|
<head>
|
|
5818
5819
|
<meta charset="UTF-8">
|
|
@@ -6479,7 +6480,7 @@ function saveState() {
|
|
|
6479
6480
|
<\/script>
|
|
6480
6481
|
</body>
|
|
6481
6482
|
</html>
|
|
6482
|
-
`,
|
|
6483
|
+
`,Yv=`<!DOCTYPE html>
|
|
6483
6484
|
<html lang="en">
|
|
6484
6485
|
<head>
|
|
6485
6486
|
<meta charset="UTF-8">
|
|
@@ -7265,7 +7266,7 @@ if (document.getElementById('mainView').classList.contains('active')) {
|
|
|
7265
7266
|
<\/script>
|
|
7266
7267
|
</body>
|
|
7267
7268
|
</html>
|
|
7268
|
-
`,
|
|
7269
|
+
`,Xv=`<!DOCTYPE html>
|
|
7269
7270
|
<html lang="en">
|
|
7270
7271
|
<head>
|
|
7271
7272
|
<meta charset="UTF-8">
|
|
@@ -8023,7 +8024,7 @@ textarea.field-input { height: auto; min-height: 80px; padding: 10px 12px; resiz
|
|
|
8023
8024
|
<\/script>
|
|
8024
8025
|
</body>
|
|
8025
8026
|
</html>
|
|
8026
|
-
`,
|
|
8027
|
+
`,Zv=`<!DOCTYPE html>
|
|
8027
8028
|
<html lang="en">
|
|
8028
8029
|
<head>
|
|
8029
8030
|
<meta charset="UTF-8">
|
|
@@ -8833,7 +8834,7 @@ init();
|
|
|
8833
8834
|
<\/script>
|
|
8834
8835
|
</body>
|
|
8835
8836
|
</html>
|
|
8836
|
-
`,
|
|
8837
|
+
`,Qv=`<!DOCTYPE html>
|
|
8837
8838
|
<html lang="en">
|
|
8838
8839
|
<head>
|
|
8839
8840
|
<meta charset="UTF-8">
|
|
@@ -10481,7 +10482,7 @@ body { font-family: var(--s2-font-family); font-size: 14px; line-height: 1.5; co
|
|
|
10481
10482
|
<\/script>
|
|
10482
10483
|
</body>
|
|
10483
10484
|
</html>
|
|
10484
|
-
|
|
10485
|
+
`,$v=`<!DOCTYPE html>
|
|
10485
10486
|
<html lang="en">
|
|
10486
10487
|
<head>
|
|
10487
10488
|
<title>Welcome</title>
|
|
@@ -11325,7 +11326,7 @@ body { font-family: var(--s2-font-family); font-size: 14px; line-height: 1.5; co
|
|
|
11325
11326
|
<\/script>
|
|
11326
11327
|
</body>
|
|
11327
11328
|
</html>
|
|
11328
|
-
`,
|
|
11329
|
+
`,ey='---\nname: Automation\ndescription: Licks, webhooks, cron tasks, viewing pages/images, screencapture, onboarding\n---\n\n# Automation & Environment Guide\n\n## Viewing Pages and Images\n\n**What you CAN see:**\n\n- **`open --view <path>`** — reads an image from VFS and returns it. Works with PNG, JPEG, GIF, WebP, SVG.\n- **`playwright-cli screenshot --tab=<id>`** + **`open --view <path>`** — screenshot a tab, then view it.\n- **`screencapture`** — capture user\'s screen via browser screen sharing. `screencapture --view screenshot.png`.\n- **`playwright-cli snapshot --tab=<id>`** — accessibility tree (text). Use to verify content without vision.\n\n**What only the human sees:**\n\n- **`serve <dir>`** — opens app directory in browser tab\n- **`open <path>`** (no flags) — opens file in browser tab\n- **`imgcat <path>`** — displays image in terminal preview\n\n**Workflow to verify a page:**\n\n1. `serve /workspace/app` — open app (human sees it)\n2. `playwright-cli tab-list` — find tab by URL, note targetId\n3. `playwright-cli snapshot --tab=<id>` — required before screenshot\n4. `playwright-cli screenshot --tab=<id> --filename=/tmp/shot.png`\n5. `open --view /tmp/shot.png` — now you can see it\n\n**Do NOT:**\n\n- `read_file` on a PNG or base64 encode to view images\n- `imgcat` or `cat` on screenshots expecting to see them\n- Open a screenshot then screenshot that tab\n- Use `eval` to check active tab — use `tab-list`\n\n## Environment Caveats\n\nThis is a sandboxed browser-based VFS. Many standard tools don\'t exist.\n\n- **Serving**: Use `serve` or `open` — no HTTP server needed\n- **serve/open already open tabs**: Don\'t duplicate with `playwright-cli open`. Use `tab-list` to find existing tab.\n- **Never manually construct preview URLs** — use URL from command output\n- **No long-running servers**: `serve` and `open` handle previewing\n- **No package managers**: No `apt`, `npm install`, `pip install`\n\n## File System Watching\n\n`fswatch` monitors VFS file changes and delivers events as licks to scoops.\n\n```bash\n# Watch for markdown changes, route to a scoop\nfswatch create --path /workspace --pattern "*.md" --scoop doc-watcher --name md-changes\n\n# Watch without targeting a scoop (routes to cone)\nfswatch create --path /workspace/src --pattern "*.ts"\n\n# List active watchers\nfswatch list\n\n# Remove a watcher\nfswatch delete fsw-1\n```\n\nEvents include the change type (`create`, `modify`, `delete`) and the file path.\n\n## Symlinks\n\nThe VFS supports symbolic links:\n\n```bash\nln -s /workspace/skills /workspace/skill-link # Create symlink\nreadlink /workspace/skill-link # Read link target\nls -la /workspace/ # Shows symlinks with -> target\n```\n\nSymlinks work transparently — `cat`, `readFile`, `writeFile` etc. follow symlinks automatically.\n\n## Onboarding\n\nWhen you receive a `[Sprinkle Event: welcome]` with `onboarding-complete`, read `/workspace/skills/welcome/SKILL.md` and follow its instructions.\n',ty=`---
|
|
11329
11330
|
name: inline-widgets
|
|
11330
11331
|
description: Interactive widget patterns for inline shtml cards in chat messages
|
|
11331
11332
|
allowed-tools: bash
|
|
@@ -11595,7 +11596,7 @@ slicc.lick({ action: 'sort-complete', algorithm: algo, comparisons: n });
|
|
|
11595
11596
|
\`\`\`
|
|
11596
11597
|
|
|
11597
11598
|
The agent receives the lick as a structured message and can respond with prose, another inline widget, or spawn a scoop.
|
|
11598
|
-
`,
|
|
11599
|
+
`,ny=`---
|
|
11599
11600
|
name: playwright-cli
|
|
11600
11601
|
description: Browse the web, interact with pages, take screenshots, extract data via the playwright-cli shell command.
|
|
11601
11602
|
allowed-tools: bash
|
|
@@ -11784,7 +11785,7 @@ playwright-cli stop-recording <recordingId> # Stop and save HAR
|
|
|
11784
11785
|
- The SLICC app tab and Chrome internal UI tabs are automatically excluded from \`tab-list\`.
|
|
11785
11786
|
- \`fill\` clears and types into regular inputs, textareas, and \`contenteditable\` elements.
|
|
11786
11787
|
- Screenshots default to \`/tmp/screenshot-<timestamp>.png\`. Use \`--filename=path\` to save elsewhere.
|
|
11787
|
-
`,
|
|
11788
|
+
`,ry=`---
|
|
11788
11789
|
name: Scoop Management
|
|
11789
11790
|
description: Detailed scoop lifecycle, delegation rules, browser tab handling
|
|
11790
11791
|
---
|
|
@@ -11864,7 +11865,7 @@ Example:
|
|
|
11864
11865
|
scoop_scoop({ name: "fix-typos", model: "claude-haiku-4-5-20251001", prompt: "Fix all typos in /workspace/docs/" })
|
|
11865
11866
|
scoop_scoop({ name: "architect", model: "claude-opus-4-6", prompt: "Design the new plugin system..." })
|
|
11866
11867
|
\`\`\`
|
|
11867
|
-
`,
|
|
11868
|
+
`,iy="---\nname: Skill Authoring\ndescription: Skills discovery, .jsh/.bsh files, shell commands, filesystem\n---\n\n# Skill Authoring & Shell Reference\n\n## Skills\n\nSkills in `/workspace/skills/` extend capabilities. SLICC also discovers compatibility skills from `.agents/skills/*/SKILL.md` and `.claude/skills/*/SKILL.md` anywhere in the reachable VFS. Only native `/workspace/skills/` entries are install-managed; compatibility-discovered skills stay read-only.\n\n## .jsh Files (JavaScript Shell Scripts)\n\n`.jsh` files are auto-discovered as shell commands anywhere on the VFS:\n\n- **Auto-discovery**: registered as callable commands (by filename without extension)\n- **Skills can ship them**: executable `.jsh` scripts live alongside SKILL.md\n- **Node-like globals**: `process`, `console`, `fs` (VFS bridge with `readFile`, `writeFile`, `readDir`, `exists`)\n- **Dual-mode**: work in CLI server and Chrome extension\n- **Top-level `await`**: wrapped in AsyncFunction. Always `await` fs methods. Don't use `.then()`.\n\n## .bsh Files (Browser Shell Scripts)\n\n`.bsh` files auto-execute when the browser navigates to a matching URL:\n\n- **Filename = hostname pattern**: `-.okta.com.bsh` matches `*.okta.com`\n- **`// @match` directive**: restrict to specific URL patterns in first 10 lines\n- Same execution engine as `.jsh`\n\n## Shell Commands\n\nType `commands` in the terminal for the full list. Key commands:\n\n- **skill list/info/read** — inspect skills; `skill install/uninstall` manages native packages\n- **upskill** — install from GitHub (`upskill owner/repo`) or ClawHub (`upskill clawhub:name`)\n- **webhook/crontask/fswatch** — set up licks (external event triggers, file change watchers)\n- **sprinkle** — manage sprinkles: `list`, `open`, `close`, `send`, `chat`\n- **oauth-token** — get OAuth access token for a provider\n- **cost** — show session cost breakdown (tokens, cache, cost per cone/scoop)\n- **git** — full git support\n- **node -e / python3 -c** — execute JS or Python\n- **serve <dir>** — open VFS app directory in browser tab\n- **open <path|url>** — open file/URL in browser. `open --view` to see images inline\n- **playwright-cli** — browser automation (tab-list, tab-new, snapshot, screenshot, click, fill, tab-close)\n- **pbcopy/pbpaste/xclip/xsel** — clipboard\n- **say** — text-to-speech\n- **afplay** — play audio files\n- **chime** — notification sound\n- **rsync** — sync files between local VFS and remote tray runtime\n- **teleport** — transfer browser cookies from remote tray runtime\n- **host** — tray status and join URL\n\n## Filesystem\n\nVirtual filesystem stored in IndexedDB, survives tab closes and refreshes. Mount local directories:\n\n```\nmount /mnt/myproject\n```\n\nUse an empty mount point. Mounting over existing files is blocked so built-in skills and scripts stay discoverable. `ln -s` the mounted files into the place where you need them.\n\n## Capabilities\n\n- Read/write files in virtual workspace\n- Run bash commands in sandboxed shell\n- Automate browser interactions (screenshots, navigation, clicking, JS eval)\n- Delegate work to scoops and react when they finish\n- Respond to licks (webhooks, scheduled tasks)\n",ay=`---
|
|
11868
11869
|
name: Sprinkle Guide
|
|
11869
11870
|
description: Inline cards, sprinkle chat, cone orchestration rules for UI panels
|
|
11870
11871
|
---
|
|
@@ -11927,7 +11928,7 @@ The cone MUST NOT: write/edit \`.shtml\` files, run \`sprinkle open/close/send\`
|
|
|
11927
11928
|
See the sprinkles skill (\`read_file /workspace/skills/sprinkles/SKILL.md\`) for creating, modifying, and handling lick events.
|
|
11928
11929
|
|
|
11929
11930
|
**NEVER handle a lick in the cone. Always \`feed_scoop\`.**
|
|
11930
|
-
`,
|
|
11931
|
+
`,oy='---\nname: sprinkles\ndescription: Create interactive sprinkles — dashboards, forms, and visualizations\nallowed-tools: bash\n---\n\n# Sprinkles\n\n`.shtml` files in `/shared/sprinkles/` become interactive UI panels. Use them to create dashboards, forms, and visualizations alongside the chat.\n\n**Two sprinkle modes**:\n\n- **Fragment mode** (default): Plain HTML fragments injected into the sidebar. Do NOT use `<!DOCTYPE html>`, `<html>`, `<head>`, `<body>`, or custom CSS — use the built-in `.sprinkle-*` classes. Scripts get a `slicc` bridge object automatically.\n- **Full-document mode**: Complete HTML documents (starting with `<!DOCTYPE html>` or `<html>`) render inside sandboxed iframes. Use this for complex layouts with custom CSS, sidebars, split panes, modals, or canvas/SVG visualizations. The bridge script is auto-injected — `window.slicc` and `window.bridge` are available in your scripts. Use `parent.postMessage` is handled internally.\n\n**When to use full-document mode**: Use it when you need custom CSS beyond `.sprinkle-*` classes, complex layouts (sidebar + main, split panes, tabs), or interactive canvas/SVG. The parent page\'s S2 theme tokens are injected automatically.\n\n**Creating a sprinkle**:\n\n1. `read_file /workspace/skills/sprinkles/style-guide.md` — **always read first** before writing any sprinkle\n2. `write_file` to `/shared/sprinkles/<name>/<name>.shtml` (follow the style guide templates)\n3. `bash` → `sprinkle open <name>`\n4. **CRITICAL: Do NOT finish or send a completion message.** You own this sprinkle for its entire lifetime. The cone will send you follow-up instructions (modifications, lick events) via `feed_scoop`. If you finish, you lose your context and cannot handle future work on this sprinkle.\n\n**Updating a sprinkle** (when you receive follow-up instructions):\n\n1. Edit `/shared/sprinkles/<name>/<name>.shtml` with the requested changes\n2. Reload: `sprinkle close <name> && sprinkle open <name>`\n3. Do NOT finish — stay ready for more instructions\n\n**Handling lick events** (when the cone forwards a user interaction):\nThe cone will send you a message with the lick action and your sprinkle name. Only modify YOUR sprinkle — the one matching your scoop name. Process the action and push updates:\n\n- `bash` → `sprinkle send <name> \'{"key":"value"}\'` to push data to the sprinkle\'s `slicc.on(\'update\', ...)` handler\n- Or edit the `.shtml` file and reload if the UI structure needs to change\n- Do NOT finish — stay ready for more events\n\n**Managing sprinkles via bash**:\n\n- `sprinkle list` — see available sprinkles\n- `sprinkle open <name>` — show a sprinkle in the sidebar\n- `sprinkle close <name>` — remove it\n- `sprinkle send <name> \'<json>\'` — push data (single-quote the JSON!)\n- `sprinkle chat \'<html>\'` — show inline HTML in the chat (for quick confirmations/choices)\n- `open /path/to/file.shtml` — also opens as a sprinkle\n\n**Bridge API** (available as `slicc` in `<script>` tags and `onclick` attributes):\n\n- `slicc.lick({action: \'refresh\', data: {...}})` — send a lick event to the cone (cone routes to the right scoop)\n- `slicc.on(\'update\', function(data) {...})` — receive data sent via `sprinkle send`\n- `slicc.name` — the sprinkle\'s name\n- `slicc.close()` — close the sprinkle\n- `slicc.stopCone()` — stop the cone agent\n- `slicc.readFile(path)` — read a VFS file (returns `Promise<string>`)\n- `slicc.writeFile(path, content)` — write text content to a VFS file\n- `slicc.readDir(path)` — list directory entries (returns `Promise<Array<{name, type}>>`)\n- `slicc.exists(path)` — check if path exists (returns `Promise<boolean>`)\n- `slicc.stat(path)` — get file metadata (returns `Promise<{type, size}>`)\n- `slicc.mkdir(path)` — create a directory (recursive)\n- `slicc.rm(path)` — remove a file\n- `slicc.screenshot(selector?)` — capture sprinkle DOM as base64 PNG data URL. Note: The screenshot captures a DOM clone using SVG foreignObject. External stylesheets and some computed styles may not be fully reproduced. For best results, use inline styles on elements you intend to screenshot.\n\n**onclick attributes**: Always use `slicc` — e.g. `onclick="slicc.lick({action: \'add-year\'})"`. The `slicc` variable is automatically resolved per-sprinkle, so multiple sprinkles won\'t collide. Do NOT use `bridge` or any other variable name in onclick.\n\n**CSS components** — Do NOT write custom CSS. Use the built-in `.sprinkle-*` classes: cards, tables, badges, buttons, text fields, progress bars, meters, layout utilities, and more. For inputs use `class="sprinkle-text-field"`, never inline border/padding styles. Run `read_file /workspace/skills/sprinkles/style-guide.md` for the full component reference with markup examples.\n\n## Built-in Sprinkles\n\nThese sprinkles ship with SLICC at `/shared/sprinkles/`. They are full-document HTML apps rendered in sandboxed iframes.\n\n| Sprinkle name | Open with | Use when the user asks for... |\n| ------------------ | -------------------------------- | --------------------------------------------------------------------- |\n| `page-editor` | `sprinkle open page-editor` | WYSIWYG editor, page editor, edit sections, visual editing |\n| `content-tree` | `sprinkle open content-tree` | content tree, page tree, site structure, page browser, navigate pages |\n| `review-workflow` | `sprinkle open review-workflow` | review, approval workflow, annotations, comments on content |\n| `seo-dashboard` | `sprinkle open seo-dashboard` | SEO audit, meta tags, SERP preview, SEO issues |\n| `schema-editor` | `sprinkle open schema-editor` | schema, structured data, JSON-LD, rich results |\n| `readability` | `sprinkle open readability` | readability, reading level, text analysis, simplify text |\n| `brand-compliance` | `sprinkle open brand-compliance` | brand check, brand compliance, style guide violations |\n| `tone-voice` | `sprinkle open tone-voice` | tone, voice, writing style, formality, tone analysis |\n| `performance` | `sprinkle open performance` | performance, Core Web Vitals, page speed, lighthouse |\n| `funnels` | `sprinkle open funnels` | funnels, conversion, A/B test, analytics |\n\n### When a user request matches a built-in sprinkle\n\nWhen the user\'s request matches a built-in sprinkle (see table above), **ask the user which approach they prefer** before proceeding:\n\n> I can help with that. Would you like me to:\n>\n> 1. **Open the built-in [sprinkle name]** — ready to use immediately, I\'ll populate it with your data\n> 2. **Build a custom one from scratch** — tailored exactly to your needs, but takes a moment to create\n>\n> Which do you prefer?\n\n**If the user says "open" / "use the built-in" / picks option 1** — use the built-in sprinkle (see "Using Built-in Sprinkles" in style-guide.md for the scoop brief template).\n\n**If the user says "build" / "create" / "custom" / picks option 2** — create a new sprinkle from scratch following the "Creating a sprinkle" flow above.\n\n**If the user explicitly says "open the page editor"** (or any built-in name directly) — skip the question and use the built-in immediately.\n\n**If the request is clearly novel** (no matching built-in) — create from scratch without asking.\n\n### Cone orchestration for sprinkles\n\n**Rule 3: Creating sprinkles** — Create a scoop, then feed it a complete, self-contained brief:\n\n```\nscoop_scoop("giro-winners")\nfeed_scoop("giro-winners", "You own the sprinkle \'giro-winners\'. Your job:\n1. Run: read_file /workspace/skills/sprinkles/style-guide.md\n2. Research the last 3 Giro d\'Italia winners\n3. Write the sprinkle to /shared/sprinkles/giro-winners/giro-winners.shtml\n4. Run: sprinkle open giro-winners\n5. IMPORTANT: After opening the sprinkle, do NOT finish. Stay ready — you will receive follow-up instructions and lick events for this sprinkle via feed_scoop. Do not send a completion message.")\n```\n\n**Rule 4: Modifying sprinkles** — Feed the EXISTING scoop that owns it. Do NOT create a new scoop:\n\n```\nfeed_scoop("giro-winners", "Modify YOUR sprinkle \'giro-winners\' at /shared/sprinkles/giro-winners/giro-winners.shtml:\nAdd an \'Add Previous Year\' button with onclick=\\"slicc.lick({action: \'add-year\'})\\"\nThen reload: sprinkle close giro-winners && sprinkle open giro-winners\nStay ready for more work.")\n```\n\n**Rule 5: Lick events** — Forward to owning scoop, never handle yourself:\n\n```\nfeed_scoop("giro-winners", "Lick event on YOUR sprinkle \'giro-winners\' (/shared/sprinkles/giro-winners/giro-winners.shtml):\nAction: \'add-year\'\nLook up the next previous year\'s Giro d\'Italia winner and update the sprinkle.\nUse: sprinkle send giro-winners \'<json>\' to push data, or edit the .shtml and reload.\nStay ready for more lick events.")\n```\n',sy=`# Sprinkle Component Reference
|
|
11931
11932
|
|
|
11932
11933
|
Use these CSS classes in \`.shtml\` sprinkles. Do NOT write custom CSS — these components cover all common UI patterns.
|
|
11933
11934
|
|
|
@@ -12539,7 +12540,7 @@ background: color-mix(in srgb, var(--s2-accent) 6%, transparent); /* blue tint *
|
|
|
12539
12540
|
| \`--s2-spacing-400\` | 24px |
|
|
12540
12541
|
| \`--s2-spacing-500\` | 32px |
|
|
12541
12542
|
| \`--s2-spacing-600\` | 40px |
|
|
12542
|
-
`,
|
|
12543
|
+
`,cy=`---
|
|
12543
12544
|
name: welcome
|
|
12544
12545
|
description: Handle onboarding lick from the welcome sprinkle
|
|
12545
12546
|
allowed-tools: bash
|
|
@@ -12633,8 +12634,8 @@ Do NOT save a profile, update \`/shared/CLAUDE.md\`, or write a greeting.
|
|
|
12633
12634
|
|
|
12634
12635
|
- **\`start-task\` lick** — treat as the user's first request, begin the task immediately.
|
|
12635
12636
|
- **Sparse profiles** (user skipped most steps) — keep greeting brief, ask what they need.
|
|
12636
|
-
`,
|
|
12637
|
-
`)){let t=e.match(/^(\w[\w-]*):\s*(.*)$/);if(!t)continue;let[,n,r]=t,a=r.trim();switch(n){case`name`:i.name=a;break;case`description`:i.description=a;break;case`allowed-tools`:i.allowedTools=a.split(`,`).map(e=>e.trim());break}}return{metadata:i,body:r}}async function
|
|
12637
|
+
`,ly=`data:audio/mpeg;base64,SUQzBAAAAAAAIlRTU0UAAAAOAAADTGF2ZjYyLjMuMTAwAAAAAAAAAAAAAAD/+0DAAAAAAAAAAAAAAAAAAAAAAABYaW5nAAAADwAAAAcAAAYbAJWVlZWVlZWVlZWVlZWVqqqqqqqqqqqqqqqqqqq7u7u7u7u7u7u7u7u7u8zMzMzMzMzMzMzMzMzMzN3d3d3d3d3d3d3d3d3d7u7u7u7u7u7u7u7u7u7//////////////////wAAAABMYXZjNjIuMTEAAAAAAAAAAAAAAAAkA2kAAAAAAAAGG+gbtfQAAAAAAP/7wMQAAAv4N1B0ZIAqHxVpvznQgAr9rb7PJkyd34smDgMBk078/BAKAoGBQw+OHn/gAGf4eHv/wB3mf/gb/+OAf/AMf/h4A78AMP/oeAGfAAw/+h4AZ8BGH/48AM/iMf/+AAAAAAYeHh4eAAAAAAYeHh48AQMIAMGIBMXNwtEAoEAwAAQFAIBXCQKu8YAEJgcFBQtl1DXh6g4LDYWQ0TAcKGhAZbDTOWxGG4ECgfmRFLtKMFhAMNgLYEsYxXEXG8YqgB/V3RF/XZhqJUcp//99nKcqIv7vmWv///4zWppVVpf///////5TWpqarS0v8RBUFREe/1gqIgqCoiXfkTAVAAwAAMY6g6nK2AAgTCmlJdBcQAwEcSQmFALZslhoW7uNZ4gSBAGEM6A0KbEqs5LgGh4TzAuMFNh9L4FA2JwwsRBsKsxbGrvVd4Ah/AtwTpu046oAoLB7MBAHAAAuQSQgTSmJa2mO8ncaGTeyJsz3wn9TbdBmuCWkp8D8E//+gA4/C9YFwCq9RAA7S+AQNicISCx60KQy7HHeq7wBD0BcwnTfOPUM5NC/UFgAAAA6uQ6OhMlAQIF6e9CTI2Vyp7bkY0xyAhvA8Zp848zYQBSgCAONoPJlh0OM6j8g0QAE5IcEu49m0ZsbxZWX6cQwG6gzS0dl1wT//6UO9sCfUFoAAAAziH7QUEI6FiQEQGYIOeVMMQXnACAteiQWVmmckZbEXG1w7KCMN9bB7QFyC3ELRigOQJdCo56zhEjAgXAlbcHreLLGmdkZTD2m1w6ygjUO98CeUH4AAAAziH/QkCMDzpmjj44B3nBC54YUDZoxbLGmdEdERly9qyhjDfixayBkA2cGE4UKrxIIhgz8HwBS3YlbIGxt21jWiK0hatrEYEjVTEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVB3aABwAfwAAAMj7DgFUgDBxFLY4XWT6pcoZrVtbqPGBB//sgxO8Axmw5Qd29gCiLCCg4DdB0oi1tkrKwMMFBV000qkxBTUUzLjEwMKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqv/7EMT6AEVwQTPgcEPgk4goOA3QdKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq//sQxPsARMRBQ+Dqg2C2iCa8Pgh8qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqr/+xDE+oDFuEFD4Whj4KMIKDgtDHyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqv/7EMT4gMVgQUXhYGPgmgan+AHgBaqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq//sQxO0DxaRHKeDgY+gAAD/AAAAEqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqo=`,uy=n(`skills`),dy=Object.assign({"/packages/vfs-root/AGENTS.md":Vv,"/packages/vfs-root/CLAUDE.md":Vv,"/packages/vfs-root/shared/CLAUDE.md":Hv,"/packages/vfs-root/shared/sprinkles/brand-compliance/brand-compliance.shtml":Uv,"/packages/vfs-root/shared/sprinkles/content-tree/content-tree.shtml":Wv,"/packages/vfs-root/shared/sprinkles/funnels/funnels.shtml":Gv,"/packages/vfs-root/shared/sprinkles/page-editor/page-editor.shtml":Kv,"/packages/vfs-root/shared/sprinkles/performance/performance.shtml":qv,"/packages/vfs-root/shared/sprinkles/readability/readability.shtml":Jv,"/packages/vfs-root/shared/sprinkles/review-workflow/review-workflow.shtml":Yv,"/packages/vfs-root/shared/sprinkles/schema-editor/schema-editor.shtml":Xv,"/packages/vfs-root/shared/sprinkles/seo-dashboard/seo-dashboard.shtml":Zv,"/packages/vfs-root/shared/sprinkles/tone-voice/tone-voice.shtml":Qv,"/packages/vfs-root/shared/sprinkles/welcome/welcome.shtml":$v,"/packages/vfs-root/workspace/skills/automation/SKILL.md":ey,"/packages/vfs-root/workspace/skills/inline-widgets/SKILL.md":ty,"/packages/vfs-root/workspace/skills/playwright-cli/SKILL.md":ny,"/packages/vfs-root/workspace/skills/scoop-management/SKILL.md":ry,"/packages/vfs-root/workspace/skills/skill-authoring/SKILL.md":iy,"/packages/vfs-root/workspace/skills/sprinkle-guide/SKILL.md":ay,"/packages/vfs-root/workspace/skills/sprinkles/SKILL.md":oy,"/packages/vfs-root/workspace/skills/sprinkles/style-guide.md":sy,"/packages/vfs-root/workspace/skills/welcome/SKILL.md":cy}),fy=Object.assign({"/packages/vfs-root/shared/sounds/chime.mp3":ly});function py(e){let t=e.split(`,`)[1],n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}function my(){let e={};for(let[t,n]of Object.entries(dy))e[t]=n;for(let[t,n]of Object.entries(fy))e[t]=py(n);return e}function hy(e){let t=new Map;for(let n of e){if(t.has(n.metadata.name)){uy.debug(`Skipped shadowed runtime skill`,{name:n.metadata.name,path:n.path,winnerPath:t.get(n.metadata.name)?.path});continue}t.set(n.metadata.name,n)}return Array.from(t.values())}function gy(e){let t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);if(!t)return{metadata:{},body:e};let[,n,r]=t,i={};for(let e of n.split(`
|
|
12638
|
+
`)){let t=e.match(/^(\w[\w-]*):\s*(.*)$/);if(!t)continue;let[,n,r]=t,a=r.trim();switch(n){case`name`:i.name=a;break;case`description`:i.description=a;break;case`allowed-tools`:i.allowedTools=a.split(`,`).map(e=>e.trim());break}}return{metadata:i,body:r}}async function _y(e,t){let n=await vy(e,t),r=await yy(e,t),i=n.filter(e=>e.source===`native`),a=n.filter(e=>e.source!==`native`),o=hy([...i,...r,...a]);return uy.info(`Skills loaded`,{count:o.length,dir:t}),o}async function vy(e,t){let n=await ue(e,t),r=[];for(let t of n)if(t.skillFilePath)try{let{metadata:n,body:i}=gy(await e.readTextFile(t.skillFilePath)),a=n.name||t.name;r.push({metadata:{name:a,description:n.description||t.manifest.description||``,allowedTools:n.allowedTools},content:i,path:t.skillFilePath,source:t.source}),uy.debug(`Loaded discovered skill`,{name:a,path:t.skillFilePath,source:t.source})}catch{uy.debug(`Failed to load discovered skill`,{name:t.name,path:t.skillFilePath})}return r}async function yy(e,t){let n=[];try{let r=await e.readDir(t);for(let i of r)if(i.type===`file`&&i.name.endsWith(`.md`)){let r=`${t}/${i.name}`;try{let t=await e.readFile(r,{encoding:`utf-8`}),{metadata:a,body:o}=gy(typeof t==`string`?t:new TextDecoder().decode(t)),s=a.name||i.name.replace(`.md`,``);n.push({metadata:{name:s,description:a.description||``,allowedTools:a.allowedTools},content:o,path:r}),uy.debug(`Loaded standalone skill`,{name:s,path:r})}catch{}}}catch{uy.debug(`Standalone skills directory not found`,{dir:t})}return n}function by(e){return e.length===0?``:`
|
|
12638
12639
|
---
|
|
12639
12640
|
AVAILABLE SKILLS
|
|
12640
12641
|
|
|
@@ -12643,9 +12644,9 @@ The following skills are available. To use a skill, first read its full instruct
|
|
|
12643
12644
|
|
|
12644
12645
|
${e.map(e=>{let t=e.metadata.allowedTools?` Allowed tools: ${e.metadata.allowedTools.join(`, `)}\n`:``;return`- **${e.metadata.name}**: ${e.metadata.description}\n${t} Path: ${e.path}`}).join(`
|
|
12645
12646
|
`)}
|
|
12646
|
-
---`}async function
|
|
12647
|
-
`)}`}}}),o&&u.push({name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model and/or a prompt. If prompt is provided, the scoop starts working immediately after creation (no separate feed_scoop needed).`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Display name for the scoop (e.g., "hero-block")`},model:{type:`string`,description:`Model ID for this scoop (e.g., "claude-sonnet-4-6"). If omitted, uses the same model as the cone.`},prompt:{type:`string`,description:`Task prompt for the scoop. If provided, the scoop starts working immediately after creation.`}},required:[`name`]},execute:async e=>{let{name:t,model:n,prompt:i}=e,a=t.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,50)+`-scoop`;try{let e=await o({name:t,folder:a,trigger:`@${a}`,isCone:!1,type:`scoop`,requiresTrigger:!0,assistantLabel:a,addedAt:new Date().toISOString(),config:n?{modelId:n}:void 0});return
|
|
12648
|
-
`),e.isError);break}case`message_end`:if(e.message.role===`assistant`){let t=e.message.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);t&&!this.didStreamDeltas&&this.callbacks.onResponse(t,!1)}break;case`turn_end`:this.callbacks.onResponseDone();break;case`agent_end`:{let t=e.messages;if(t.length>0){let e=t[t.length-1];if(e.role===`assistant`&&e.errorMessage){let n=e.errorMessage;if(!this.isRecovering&&
|
|
12647
|
+
---`}async function xy(e,t=`/workspace/skills`){let n=my();for(let[r,i]of Object.entries(n)){let n=r.slice(18),a=n.startsWith(`/workspace/skills`),o=n.startsWith(`/workspace/scripts`);if(!a&&!o)continue;let s=n;a&&t!==`/workspace/skills`&&(s=n.replace(`/workspace/skills`,t)),o&&t!==`/workspace/skills`&&(s=t.replace(`/workspace/skills`,``)+n);try{await e.stat(s)}catch{let t=s.substring(0,s.lastIndexOf(`/`));try{await e.mkdir(t,{recursive:!0})}catch{}await e.writeFile(s,i),uy.info(`Created default file`,{path:s})}}}async function Sy(e){let t=my();for(let[n,r]of Object.entries(t)){let t=n.slice(18);if(t.startsWith(`/shared/`))try{await e.stat(t)}catch{let n=t.substring(0,t.lastIndexOf(`/`));try{await e.mkdir(n,{recursive:!0})}catch{}await e.writeFile(t,r),uy.info(`Created default shared file`,{path:t})}}}var Cy=n(`scoop-management-tools`);function wy(e){let{scoop:t,onSendMessage:n,onFeedScoop:r,getScoops:i,getScoopTabState:a,onScoopScoop:o,onDropScoop:s,onSetGlobalMemory:c,getGlobalMemory:l}=e,u=[];return u.push({name:`send_message`,description:`Send a progress message while still working. Your final output is also sent.`,inputSchema:{type:`object`,properties:{text:{type:`string`,description:`The message text to send`},sender:{type:`string`,description:`Optional sender name/role (e.g., "Researcher"). Defaults to assistant name.`}},required:[`text`]},execute:async e=>{let{text:r,sender:i}=e;return n(r,i),Cy.info(`Message sent`,{scoopFolder:t.folder,textLength:r.length}),{content:`Message sent.`}}}),t.isCone&&r&&u.push({name:`feed_scoop`,description:`Give a scoop a task. Provide a complete, self-contained prompt — the scoop has no access to your conversation. You'll be notified when it finishes.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Use list_scoops to see available scoops.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`}},required:[`scoop_name`,`prompt`]},execute:async e=>{let{scoop_name:t,prompt:n}=e,a=i().find(e=>e.folder===t||e.name===t);if(!a)return{content:`Scoop "${t}" not found. Available: ${i().filter(e=>!e.isCone).map(e=>e.folder).join(`, `)}`,isError:!0};if(a.isCone)return{content:`Cannot feed the cone (yourself).`,isError:!0};try{return await r(a.jid,n),Cy.info(`Fed scoop`,{target:a.folder,promptLength:n.length}),{content:`Task sent to ${a.folder}. You will be notified when it completes.`}}catch(e){return{content:`Failed to feed scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}}),t.isCone&&(u.push({name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:async()=>{let e=i();return e.length===0?{content:`No scoops registered.`}:{content:`Registered scoops:\n${e.map(e=>{let t=a?.(e.jid),n=t?.status??`unknown`,r=t?.lastActivity?new Date(t.lastActivity).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0}):``,i=r?` — ${n} (since ${r})`:` — ${n}`;return e.isCone?`- ${e.assistantLabel} (${e.folder}) [CONE]${i}`:`- ${e.name} (${e.folder})${i}`}).join(`
|
|
12648
|
+
`)}`}}}),o&&u.push({name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model and/or a prompt. If prompt is provided, the scoop starts working immediately after creation (no separate feed_scoop needed).`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Display name for the scoop (e.g., "hero-block")`},model:{type:`string`,description:`Model ID for this scoop (e.g., "claude-sonnet-4-6"). If omitted, uses the same model as the cone.`},prompt:{type:`string`,description:`Task prompt for the scoop. If provided, the scoop starts working immediately after creation.`}},required:[`name`]},execute:async e=>{let{name:t,model:n,prompt:i}=e,a=t.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,50)+`-scoop`;try{let e=await o({name:t,folder:a,trigger:`@${a}`,isCone:!1,type:`scoop`,requiresTrigger:!0,assistantLabel:a,addedAt:new Date().toISOString(),config:n?{modelId:n}:void 0});return Cy.info(`Scoop created`,{name:t,folder:a}),i&&r?(r(e.jid,i).catch(e=>{let n=e instanceof Error?e.message:String(e);Cy.error(`Auto-feed failed`,{name:t,error:n})}),{content:`Scoop "${t}" created as "${a}" and task sent. It will start working as soon as initialization completes.`}):{content:`Scoop "${t}" created as "${a}". Use feed_scoop to give it a task.`}}catch(e){return{content:`Failed to create scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}}),s&&u.push({name:`drop_scoop`,description:`Remove a scoop and stop its work. The scoop will be unregistered and its context destroyed.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Use list_scoops to see available scoops.`}},required:[`scoop_name`]},execute:async e=>{let{scoop_name:t}=e,n=i().find(e=>e.folder===t||e.name===t);if(!n)return{content:`Scoop "${t}" not found. Available: ${i().filter(e=>!e.isCone).map(e=>e.folder).join(`, `)}`,isError:!0};if(n.isCone)return{content:`Cannot drop the cone (yourself).`,isError:!0};try{return await s(n.jid),Cy.info(`Scoop dropped`,{name:n.name,folder:n.folder}),{content:`Scoop "${n.name}" (${n.folder}) has been dropped.`}}catch(e){return{content:`Failed to drop scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}}),c&&l&&u.push({name:`update_global_memory`,description:`Update the global CLAUDE.md memory file that is shared across all scoops. Use this instead of write_file for /shared/CLAUDE.md.`,inputSchema:{type:`object`,properties:{content:{type:`string`,description:`The new content for the global memory file`}},required:[`content`]},execute:async e=>{let{content:t}=e;try{return await c(t),Cy.info(`Global memory updated`),{content:`Global memory updated successfully.`}}catch(e){return{content:`Failed to update global memory: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}})),u}var Ty=n(`secret-env`);async function Ey(){if(typeof chrome<`u`&&chrome?.runtime?.id)return{};try{let e=await fetch(`/api/secrets/masked`);if(!e.ok)return Ty.warn(`Failed to fetch masked secrets`,{status:e.status}),{};let t=await e.json();if(!Array.isArray(t)||t.length===0)return{};let n={};for(let e of t)e.name&&e.maskedValue&&(n[e.name]=e.maskedValue);return Object.keys(n).length>0&&Ty.info(`Loaded masked secrets into shell env`,{count:Object.keys(n).length}),n}catch(e){return Ty.debug(`Could not fetch masked secrets (server may be unavailable)`,{error:e instanceof Error?e.message:String(e)}),{}}}var Dy=n(`scoop-context`);function Oy(e){return/image exceeds.*maximum/i.test(e)||/Could not process image/i.test(e)||/invalid.*image/i.test(e)||/image.*too (large|big)/i.test(e)}var ky=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;didStreamDeltas=!1;unsubscribe=null;sessionStore=null;sessionId;sessionCreatedAt=0;isRecovering=!1;skillsFs=null;skillsDir=`/workspace/skills`;constructor(e,t,n,r,i){this.scoop=e,this.callbacks=t,this.fs=n,this.sessionStore=r??null,this.skillsFs=i??null,this.sessionId=e.jid}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);Dy.info(`Filesystem ready`,{folder:this.scoop.folder}),await this.ensureDirectoryStructure();let e=this.scoop.isCone?`/`:`/scoops/${this.scoop.folder}/workspace`,t=this.callbacks.getBrowserAPI();this.skillsDir=`/workspace/skills`,this.scoop.isCone&&await xy(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await Ey();this.shell=new Av({fs:this.fs,cwd:e,env:Object.keys(r).length>0?r:void 0,browserAPI:t,jshDiscoveryFs:this.skillsFs?n:void 0}),Dy.info(`WasmShell initialized`,{folder:this.scoop.folder});let i=await _y(n,this.skillsDir),a=wy({scoop:this.scoop,onSendMessage:this.callbacks.onSendMessage,getScoops:this.callbacks.getScoops,getScoopTabState:this.callbacks.getScoopTabState,onFeedScoop:this.callbacks.onFeedScoop,onScoopScoop:this.callbacks.onScoopScoop,onDropScoop:this.callbacks.onDropScoop,onSetGlobalMemory:this.callbacks.setGlobalMemory,getGlobalMemory:this.callbacks.getGlobalMemory}),o=y([...Mv(this.fs),Bv(this.shell),...a]),s=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`,c=``;try{let e=await this.fs.readFile(s,{encoding:`utf-8`});c=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let l=await this.callbacks.getGlobalMemory();if(l)try{this.scoop.isCone&&await(`getUnderlyingFS`in this.fs?this.fs.getUnderlyingFS():this.fs).writeFile(`/shared/CLAUDE.md`,l)}catch{}if(!T()){let e=ie();throw Error(`No API key configured for provider "${e}"`)}let u=this.scoop.config?.modelId?S(this.scoop.config.modelId):re(),d=this.scoop.isCone?`Cone`:`Scoop "${this.scoop.name}"`;console.log(`[model] ${d} using model: ${u.id} (provider: ${u.provider})`);let f=this.buildSystemPrompt(l,c,i),p=[];if(this.sessionStore)try{let e=await this.sessionStore.load(this.sessionId);e&&(p=e.messages,this.sessionCreatedAt=e.createdAt,Dy.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:p.length}))}catch(e){Dy.error(`Failed to restore agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.callbacks.onError(`Conversation history could not be restored. Starting fresh.`)}let m=O({model:u,getApiKey:()=>T()??void 0});this.agent=new b({initialState:{model:u,tools:o,systemPrompt:f,messages:p},getApiKey:()=>T()??void 0,transformContext:m}),this.unsubscribe=this.agent.subscribe(e=>this.handleAgentEvent(e)),this.setStatus(`ready`),Dy.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:o.length})}catch(e){let t=e instanceof Error?e.message:String(e);Dy.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async prompt(e){if(!this.agent){this.callbacks.onError(`Agent not initialized`);return}let t=this.agent.state?.isStreaming??!1;if(this.isProcessing||t){Dy.info(`Queueing prompt via followUp while processing`,{folder:this.scoop.folder,isProcessing:this.isProcessing,agentIsStreaming:t}),this.agent.followUp({role:`user`,content:[{type:`text`,text:e}],timestamp:Date.now()});return}this.isProcessing=!0,this.didStreamDeltas=!1,this.setStatus(`processing`);try{await this.agent.prompt(e)}catch(e){let t=e instanceof Error?e.message:String(e);Dy.error(`Agent error`,{folder:this.scoop.folder,error:t}),this.callbacks.onError(t)}finally{this.isProcessing=!1,this.setStatus(`ready`)}}stop(){this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.isProcessing=!1,this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getSessionId(){return this.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){if(!this.agent)return;let e=re();this.agent.state.model=e,Dy.info(`Model updated on running agent`,{folder:this.scoop.folder,model:e.id})}async reloadSkills(){if(!this.agent)return;let e=await _y(this.skillsFs??this.fs,this.skillsDir),t=``,n=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{let e=await this.fs.readFile(n,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let r=await this.callbacks.getGlobalMemory(),i=this.buildSystemPrompt(r,t,e);this.agent.state.systemPrompt=i,Dy.info(`Skills reloaded`,{folder:this.scoop.folder,skillCount:e.length})}dispose(){this.unsubscribe?.(),this.shell?.dispose(),this.agent=null,this.shell=null,this.fs=null}setStatus(e){this.status=e,this.callbacks.onStatusChange(e)}handleAgentEvent(e){switch(e.type){case`message_update`:{let t=e.assistantMessageEvent;t.type===`text_delta`&&(this.didStreamDeltas=!0,this.callbacks.onResponse(t.delta,!0));break}case`tool_execution_start`:this.callbacks.onToolStart?.(e.toolName,e.args);break;case`tool_execution_update`:{let t=e.partialResult;for(let n of t?.content??[])n.type===`tool_ui`&&n.requestId&&n.html?this.callbacks.onToolUI?.(e.toolName,n.requestId,n.html):n.type===`tool_ui_done`&&n.requestId&&this.callbacks.onToolUIDone?.(n.requestId);break}case`tool_execution_end`:{let t=e.result,n=[];for(let e of t?.content??[])e.type===`text`&&e.text&&n.push(e.text),e.type===`image`&&e.data&&e.mimeType&&n.push(`<img:data:${e.mimeType};base64,${e.data}>`);this.callbacks.onToolEnd?.(e.toolName,n.join(`
|
|
12649
|
+
`),e.isError);break}case`message_end`:if(e.message.role===`assistant`){let t=e.message.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);t&&!this.didStreamDeltas&&this.callbacks.onResponse(t,!1)}break;case`turn_end`:this.callbacks.onResponseDone();break;case`agent_end`:{let t=e.messages;if(t.length>0){let e=t[t.length-1];if(e.role===`assistant`&&e.errorMessage){let n=e.errorMessage;if(!this.isRecovering&&Oy(n)){this.recoverFromImageError(t);break}if(!this.isRecovering&&x(e)){this.recoverFromOverflow(t);break}this.isRecovering=!1,this.callbacks.onError(n)}else this.isRecovering=!1}let n=this.agent?.state?.messages??e.messages;this.sessionStore&&n.length>0&&this.sessionStore.save({id:this.sessionId,messages:n,config:{},createdAt:this.sessionCreatedAt||Date.now(),updatedAt:Date.now()}).catch(e=>{Dy.error(`Failed to save agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})});break}}}recoverFromOverflow(e){if(this.agent){Dy.warn(`Context overflow detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length}),this.isRecovering=`overflow`,this.callbacks.onResponse(`Context window exceeded — recovering by trimming oversized messages...`,!1);try{let t=e.slice(0,-1),n=0;for(let e=t.length-1;e>=0&&n<5;e--){let r=t[e];if(!Array.isArray(r.content))continue;let i=0;for(let e of r.content)e.type===`text`&&e.text&&(i+=e.text.length),e.type===`image`&&e.data&&(i+=e.data.length);if(i>4e4){let a={type:`text`,text:`[Content removed: ${r.role===`toolResult`?`tool result`:r.role} was too large for context window (${Math.round(i/1e3)}K chars). The operation completed but output could not be retained.]`};if(r.role===`assistant`){let n=r.content.filter(e=>e.type===`toolCall`);t[e]={...r,content:[a,...n]}}else t[e]={...r,content:[a]};n++,Dy.info(`Replaced oversized message`,{index:e,role:r.role,size:i,preservedToolCalls:r.role===`assistant`?r.content.filter(e=>e.type===`toolCall`).length:0})}}this.agent.state.messages=t;let r=n>0?`[System: Context overflow recovered. ${n} oversized message(s) were replaced with placeholders to fit within the context window. The conversation continues — you may need to re-read files or re-run commands if their output was removed.]`:`[System: Context overflow recovered. Older messages were trimmed. The conversation continues — compaction will summarize history on the next turn.]`;this.agent.prompt(r).catch(e=>{Dy.error(`Recovery re-prompt failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Context overflow recovery failed: ${e instanceof Error?e.message:String(e)}`)})}catch(e){Dy.error(`Recovery failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Context overflow recovery failed: ${e instanceof Error?e.message:String(e)}`)}}}recoverFromImageError(e){if(this.agent){Dy.warn(`Image processing error detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length}),this.isRecovering=`image`,this.callbacks.onResponse(`Image rejected by API — removing problematic images and continuing...`,!1);try{let t=e.slice(0,-1),n=0,r=Math.max(0,t.length-10);for(let e=t.length-1;e>=r;e--){let r=t[e];if(!Array.isArray(r.content)||!r.content.some(e=>e.type===`image`))continue;let i=r.content.filter(e=>e.type!==`image`);i.length===0?t[e]={...r,content:[{type:`text`,text:`[Image removed: rejected by API]`}]}:t[e]={...r,content:i},n++}this.agent.state.messages=t;let i=`[System: An image was rejected by the API and has been removed from the conversation (${n} message(s) affected). The conversation continues without the image.]`;this.agent.prompt(i).catch(e=>{Dy.error(`Image recovery re-prompt failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)})}catch(e){Dy.error(`Image recovery failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)}}}async ensureDirectoryStructure(){if(!this.fs)return;let e=this.scoop.isCone?[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`]:[`/scoops/${this.scoop.folder}`,`/scoops/${this.scoop.folder}/workspace`,`/scoops/${this.scoop.folder}/home`,`/scoops/${this.scoop.folder}/tmp`,`/shared`];for(let t of e)try{await this.fs.mkdir(t,{recursive:!0})}catch{}let t=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{await this.fs.readFile(t)}catch{let e=`# ${this.scoop.assistantLabel} Memory
|
|
12649
12650
|
|
|
12650
12651
|
${this.scoop.isCone?`Role: Cone (main orchestrator)`:`Scoop: ${this.scoop.name}`}
|
|
12651
12652
|
Folder: ${this.scoop.folder}
|
|
@@ -12724,12 +12725,12 @@ ${e}
|
|
|
12724
12725
|
---
|
|
12725
12726
|
${this.scoop.isCone?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
|
|
12726
12727
|
${t}
|
|
12727
|
-
---`);let a=
|
|
12728
|
-
`);return Error(`Cannot remove scoop '${e}': it has ${r.join(` and `)}. Unregister them first:\n${i}`)}var
|
|
12728
|
+
---`);let a=by(n);return a&&(i+=a),i}},Ay=n(`scheduler`),jy=class{callbacks;pollInterval=null;running=!1;constructor(e){this.callbacks=e}start(){this.running||(this.running=!0,this.pollInterval=window.setInterval(()=>this.checkTasks(),6e4),this.checkTasks(),Ay.info(`Scheduler started`))}stop(){this.pollInterval&&=(clearInterval(this.pollInterval),null),this.running=!1,Ay.info(`Scheduler stopped`)}async createTask(e,t,n,r){let i={id:`task-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,groupFolder:e,prompt:t,scheduleType:n,scheduleValue:r,status:`active`,nextRun:this.calculateNextRun(n,r),lastRun:null,createdAt:new Date().toISOString()};return await Ve(i),Ay.info(`Task created`,{id:i.id,groupFolder:e,scheduleType:n}),i}async updateTask(e,t){let n=await je(e);if(!n)return null;let r={...n,...t};return(t.scheduleType||t.scheduleValue)&&(r.nextRun=this.calculateNextRun(r.scheduleType,r.scheduleValue)),await Ve(r),Ay.info(`Task updated`,{id:e,updates:Object.keys(t)}),r}async pauseTask(e){return await this.updateTask(e,{status:`paused`})!==null}async resumeTask(e){return await je(e)?(await this.updateTask(e,{status:`active`}),!0):!1}async deleteTask(e){return await je(e)?(await Se(e),Ay.info(`Task deleted`,{id:e}),!0):!1}async getTasksByScoop(e){return(await Ae()).filter(t=>t.groupFolder===e)}async getAllTasks(){return Ae()}async checkTasks(){let e=await Ae(),t=new Date;for(let n of e)n.status===`active`&&n.nextRun&&(new Date(n.nextRun)>t||await this.runTask(n))}async runTask(e){let t=this.callbacks.getScoop(e.groupFolder);if(!t){Ay.warn(`Task scoop not found`,{taskId:e.id,groupFolder:e.groupFolder});return}Ay.info(`Running task`,{id:e.id,groupFolder:e.groupFolder});try{let n=new Date().toISOString(),r=this.calculateNextRun(e.scheduleType,e.scheduleValue),i=e.scheduleType===`once`?`completed`:e.status;await Ve({...e,lastRun:n,nextRun:r,status:i}),await this.callbacks.onTaskRun(e,t),Ay.info(`Task completed`,{id:e.id})}catch(t){Ay.error(`Task execution failed`,{id:e.id,error:t instanceof Error?t.message:String(t)})}}calculateNextRun(e,t){let n=new Date;switch(e){case`cron`:return this.getNextCronTime(t,n)?.toISOString()??null;case`interval`:{let e=parseInt(t,10);return isNaN(e)||e<=0?null:new Date(n.getTime()+e).toISOString()}case`once`:return new Date(t)>n?t:null;default:return null}}getNextCronTime(e,t){let n=e.trim().split(/\s+/);if(n.length!==5)return null;let[r,i,a,o,s]=n,c=new Date(t);c.setSeconds(0),c.setMilliseconds(0),c.setMinutes(c.getMinutes()+1);for(let e=0;e<527040;e++){if(this.cronMatches(c,r,i,a,o,s))return c;c.setMinutes(c.getMinutes()+1)}return null}cronMatches(e,t,n,r,i,a){return this.cronFieldMatches(e.getMinutes(),t)&&this.cronFieldMatches(e.getHours(),n)&&this.cronFieldMatches(e.getDate(),r)&&this.cronFieldMatches(e.getMonth()+1,i)&&this.cronFieldMatches(e.getDay(),a)}cronFieldMatches(e,t){if(t===`*`)return!0;if(t.includes(`,`))return t.split(`,`).some(t=>this.cronFieldMatches(e,t.trim()));if(t.includes(`-`)){let[n,r]=t.split(`-`).map(e=>parseInt(e,10));return e>=n&&e<=r}if(t.includes(`/`)){let[n,r]=t.split(`/`),i=parseInt(r,10);if(n===`*`)return e%i===0;let a=parseInt(n,10);return e>=a&&(e-a)%i===0}return parseInt(t,10)===e}},My=n(`lick-manager`),Ny=class{webhooks=new Map;crontasks=new Map;cronInterval=null;eventHandler=null;async init(){await Oe();let e=await Re();for(let t of e)this.webhooks.set(t.id,t);My.info(`Loaded webhooks`,{count:this.webhooks.size});let t=await Ie();for(let e of t)this.crontasks.set(e.id,e);My.info(`Loaded crontasks`,{count:this.crontasks.size}),this.cronInterval=setInterval(()=>this.runCronScheduler(),6e4),My.info(`Cron scheduler started`)}dispose(){this.cronInterval&&=(clearInterval(this.cronInterval),null)}setEventHandler(e){this.eventHandler=e}emitEvent(e){My.info(`External lick event`,{type:e.type,target:e.targetScoop}),this.eventHandler?.(e)}async createWebhook(e,t,n){let r=this.generateId(),i={id:r,name:e,createdAt:new Date().toISOString(),filter:n,scoop:t};return n&&this.compileFilter(n,!0),this.webhooks.set(r,i),await Ce(i),My.info(`Webhook created`,{id:r,name:e,scoop:t}),i}async deleteWebhook(e){return this.webhooks.has(e)?(this.webhooks.delete(e),await Ne(e),My.info(`Webhook deleted`,{id:e}),!0):!1}listWebhooks(){return Array.from(this.webhooks.values())}getWebhook(e){return this.webhooks.get(e)}handleWebhookEvent(e,t,n){let r=this.webhooks.get(e);if(!r){My.warn(`Webhook not found`,{webhookId:e});return}let i={type:`webhook`,webhookId:e,webhookName:r.name,targetScoop:r.scoop,timestamp:new Date().toISOString(),headers:t,body:n};if(r.filter)try{let t=this.compileFilter(r.filter,!0)(i);if(t===!1){My.debug(`Webhook event dropped by filter`,{webhookId:e,name:r.name});return}typeof t==`object`&&t&&(i=t)}catch(t){My.error(`Webhook filter error`,{webhookId:e,error:t instanceof Error?t.message:String(t)})}My.info(`Webhook event received`,{webhookId:e,name:r.name,targetScoop:r.scoop}),this.eventHandler?.(i)}async createCronTask(e,t,n,r){let i=this.getNextCronTime(t,new Date);if(!i)throw Error(`Invalid cron expression`);r&&this.compileFilter(r,!1);let a=this.generateId(),o={id:a,name:e,cron:t,scoop:n,filter:r,nextRun:i.toISOString(),lastRun:null,status:`active`,createdAt:new Date().toISOString()};return this.crontasks.set(a,o),await De(o),My.info(`Cron task created`,{id:a,name:e,cron:t,scoop:n}),o}async deleteCronTask(e){return this.crontasks.has(e)?(this.crontasks.delete(e),await Me(e),My.info(`Cron task deleted`,{id:e}),!0):!1}listCronTasks(){return Array.from(this.crontasks.values())}getCronTask(e){return this.crontasks.get(e)}getLicksForScoop(e,t){let n=n=>n===e||n===t||`${n}-scoop`===t;return{webhooks:Array.from(this.webhooks.values()).filter(e=>n(e.scoop)),cronTasks:Array.from(this.crontasks.values()).filter(e=>n(e.scoop))}}async runCronScheduler(){let e=new Date;for(let t of this.crontasks.values()){if(t.status!==`active`||!t.nextRun||new Date(t.nextRun)>e)continue;let n={time:e.toISOString()};if(t.filter)try{let r=this.compileFilter(t.filter,!1)(null);if(r===!1){My.debug(`Cron task skipped by filter`,{id:t.id,name:t.name}),t.nextRun=this.getNextCronTime(t.cron,e)?.toISOString()??null,t.lastRun=e.toISOString(),await De(t);continue}typeof r==`object`&&r&&(n=r)}catch(e){My.error(`Cron filter error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}let r={type:`cron`,cronId:t.id,cronName:t.name,targetScoop:t.scoop,timestamp:e.toISOString(),body:n};My.info(`Cron task running`,{id:t.id,name:t.name}),this.eventHandler?.(r),t.nextRun=this.getNextCronTime(t.cron,e)?.toISOString()??null,t.lastRun=e.toISOString(),await De(t)}}generateId(){let e=``;for(let t=0;t<12;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`[Math.floor(Math.random()*36)];return e}compileFilter(e,t){try{return t?Function(`event`,`return (${e})(event);`):Function(`return (${e})();`)}catch(e){throw Error(`Invalid filter function: ${e instanceof Error?e.message:String(e)}`)}}getNextCronTime(e,t){let n=e.trim().split(/\s+/);if(n.length!==5)return null;let[r,i,a,o,s]=n,c=new Date(t);c.setSeconds(0),c.setMilliseconds(0),c.setMinutes(c.getMinutes()+1);let l=(e,t)=>{if(t===`*`)return!0;if(t.includes(`,`))return t.split(`,`).some(t=>l(e,t.trim()));if(t.includes(`-`)){let[n,r]=t.split(`-`).map(e=>parseInt(e,10));return e>=n&&e<=r}if(t.includes(`/`)){let[n,r]=t.split(`/`),i=parseInt(r,10);if(n===`*`)return e%i===0;let a=parseInt(n,10);return e>=a&&(e-a)%i===0}return parseInt(t,10)===e};for(let e=0;e<527040;e++){if(l(c.getMinutes(),r)&&l(c.getHours(),i)&&l(c.getDate(),a)&&l(c.getMonth()+1,o)&&l(c.getDay(),s))return c;c.setMinutes(c.getMinutes()+1)}return null}};function Py(e,t,n){if(t.length===0&&n.length===0)return null;let r=[];t.length>0&&r.push(`${t.length} active webhook${t.length>1?`s`:``}`),n.length>0&&r.push(`${n.length} active cron task${n.length>1?`s`:``}`);let i=[...t.map(e=>` webhook delete ${e.id}`),...n.map(e=>` crontask delete ${e.id}`)].join(`
|
|
12729
|
+
`);return Error(`Cannot remove scoop '${e}': it has ${r.join(` and `)}. Unregister them first:\n${i}`)}var Fy=null;function Iy(){return Fy||=new Ny,Fy}var Q=n(`orchestrator`),Ly=120*1e3,Ry=class{scoops=new Map;tabs=new Map;contexts=new Map;messageQueues=new Map;lastAgentTimestamp=new Map;container;callbacks;config;pollInterval=null;scheduler=null;globalMemoryCache=``;sharedFs=null;scoopResponseBuffer=new Map;lickManager=null;sessionStore=null;fsWatcher=null;idleTimers=new Map;constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n}async init(){await Oe(),this.sharedFs=await L.create({dbName:`slicc-fs`}),this.sessionStore=new D,this.fsWatcher=new se,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure();let e=await we();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.scoops.set(t.jid,t),this.messageQueues.set(t.jid,[]);let e=await Pe(`lastAgentTs_${t.jid}`);e&&this.lastAgentTimestamp.set(t.jid,e)}await this.ensureGlobalMemory(),this.scheduler=new jy({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);Ge(()=>this.getSessionCosts()),this.startMessageLoop()}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}async ensureGlobalMemory(){if(this.sharedFs){await Sy(this.sharedFs);try{let e=await this.sharedFs.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});this.globalMemoryCache=typeof e==`string`?e:new TextDecoder().decode(e)}catch{Q.warn(`Global memory file not found after creating defaults`)}}}async getGlobalMemory(){if(this.globalMemoryCache)return this.globalMemoryCache;if(this.sharedFs)try{let e=await this.sharedFs.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});this.globalMemoryCache=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}return this.globalMemoryCache}async setGlobalMemory(e){this.sharedFs&&(await this.sharedFs.writeFile(`/shared/CLAUDE.md`,e),this.globalMemoryCache=e,Q.info(`Global memory updated`))}getSharedFS(){return this.sharedFs}setLickManager(e){this.lickManager=e,globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}async registerScoop(e){await ze(e),this.scoops.set(e.jid,e),this.messageQueues.set(e.jid,[]),Q.info(`Scoop registered`,{jid:e.jid,name:e.name}),this.createScoopTab(e.jid).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Scoop init failed`,{jid:e.jid,error:n})})}async unregisterScoop(e){let t=this.scoops.get(e);if(t&&this.lickManager){let{webhooks:e,cronTasks:n}=this.lickManager.getLicksForScoop(t.name,t.folder),r=Py(t.folder,e,n);if(r)throw r}this.clearIdleTimer(e),await this.destroyScoopTab(e),this.sessionStore?.delete(e).catch(t=>{Q.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await ke(e),this.scoops.delete(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),Q.info(`Scoop unregistered`,{jid:e})}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}async resetFilesystem(){for(let[e,t]of this.contexts.entries())this.clearIdleTimer(e),t.stop(),this.contexts.delete(e);this.sharedFs=await L.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.ensureGlobalMemory(),await xy(this.sharedFs).catch(e=>{Q.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),Q.info(`Filesystem reset and defaults re-seeded`)}async clearAllMessages(){await Le(),this.sessionStore&&await this.sessionStore.clearAll().catch(e=>{Q.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.contexts.values())e.clearMessages();this.lastAgentTimestamp.clear();for(let e of this.scoops.keys())this.messageQueues.set(e,[]);Q.info(`All messages cleared`)}async handleMessage(e){Q.info(`handleMessage`,{id:e.id,chatJid:e.chatJid,sender:e.senderName,channel:e.channel,contentPreview:e.content.slice(0,80)});let t=this.scoops.get(e.chatJid);vv(t?.isCone?`cone`:t?.name??`unknown`,localStorage.getItem(`selected-model`)??`unknown`),await xe(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 xe(i),this.callbacks.onIncomingMessage?.(e,i),Q.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Delegation failed`,{scoopJid:e,error:n}),this.callbacks.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.scoops.get(e.chatJid);if(!t){Q.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}let n=e.channel===`webhook`||e.channel===`cron`||e.channel===`fswatch`;if(!t.isCone&&t.requiresTrigger&&t.trigger&&!n&&!e.content.includes(t.trigger)){Q.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let r=this.messageQueues.get(e.chatJid)??[];r.push(e),this.messageQueues.set(e.chatJid,r);let i=this.tabs.get(e.chatJid);if(Q.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:i?.status??`no-tab`,queueLength:r.length}),i?.status===`error`){Q.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.createScoopTab(e.chatJid),i=this.tabs.get(e.chatJid)}catch{Q.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}i?.status===`ready`&&await this.processScoopQueue(e.chatJid)}async createScoopTab(e){let t=this.scoops.get(e);if(!t)throw Error(`Scoop not found: ${e}`);if(this.contexts.has(e))if(this.tabs.get(e)?.status===`error`)Q.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{Q.debug(`Context already exists`,{jid:e});return}if(!this.sharedFs)throw Error(`Shared filesystem not initialized`);let n=`scoop-${t.folder}-${Date.now()}`,r=t.isCone?this.sharedFs:new ce(this.sharedFs,[`/scoops/${t.folder}/`,`/shared/`],[`/workspace/`]),i=new ky(t,{onResponse:(n,r)=>{if(this.callbacks.onResponse(e,n,r),!t.isCone)if(r){let t=this.scoopResponseBuffer.get(e)??``;this.scoopResponseBuffer.set(e,t+n)}else this.scoopResponseBuffer.set(e,n)},onResponseDone:()=>{let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),this.callbacks.onResponseDone(e)},onError:t=>{let n=this.tabs.get(e);n&&(n.status=`error`,n.error=t,this.tabs.set(e,n)),this.callbacks.onError(e,t),this.callbacks.onStatusChange(e,`error`)},onStatusChange:n=>{let r=this.tabs.get(e);if(r&&(r.status=n,r.lastActivity=new Date().toISOString(),this.tabs.set(e,r)),this.callbacks.onStatusChange(e,n),n===`ready`&&!t.isCone){let n=this.scoopResponseBuffer.get(e);if(this.scoopResponseBuffer.delete(e),n){let r=Array.from(this.scoops.values()).find(e=>e.isCone);if(r){let i=n.length>2e3?n.slice(0,2e3)+`
|
|
12729
12730
|
... (truncated)`:n,a={id:`scoop-done-${e}-${Date.now()}`,chatJid:r.jid,senderId:t.folder,senderName:t.assistantLabel,content:`[@${t.assistantLabel} completed]:\n${i}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-notify`};Q.info(`Routing scoop completion to cone`,{scoop:t.folder,responseLength:n.length}),this.handleMessage(a).catch(e=>{let n=e instanceof Error?e.message:String(e);Q.error(`Failed to route scoop completion to cone`,{scoop:t.folder,error:n}),this.callbacks.onError(r.jid,`Scoop ${t.folder} completed but notification failed: ${n}`)})}}}},onToolStart:(t,n)=>{this.callbacks.onToolStart?.(e,t,n)},onToolEnd:(t,n,r)=>{this.callbacks.onToolEnd?.(e,t,n,r)},onToolUI:(t,n,r)=>{this.callbacks.onToolUI?.(e,t,n,r)},onToolUIDone:t=>{this.callbacks.onToolUIDone?.(e,t)},onSendMessage:(t,n)=>{this.callbacks.onSendMessage(e,`${n?`[${n}] `:``}${t}`)},getScoops:()=>this.getScoops(),getScoopTabState:t.isCone?e=>this.tabs.get(e):void 0,onFeedScoop:t.isCone?(e,n)=>this.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:t.isCone?async e=>{let t={...e,jid:`scoop_${e.folder}_${Date.now()}`};return await this.registerScoop(t),t}:void 0,onDropScoop:t.isCone?async e=>{await this.unregisterScoop(e)}:void 0,getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:t.isCone?e=>this.setGlobalMemory(e):void 0,getBrowserAPI:()=>this.callbacks.getBrowserAPI()},r,this.sessionStore??void 0,this.sharedFs??void 0);this.contexts.set(e,i),this.tabs.set(e,{jid:e,contextId:n,status:`initializing`,lastActivity:new Date().toISOString()}),await i.init();let a=this.tabs.get(e);a&&a.status===`initializing`&&(a.status=`ready`,this.tabs.set(e,a),this.callbacks.onStatusChange(e,`ready`));let o=this.scoops.get(e);o&&!o.isCone&&this.startIdleTimer(e),Q.info(`Scoop context created`,{jid:e,contextId:n})}async destroyScoopTab(e){this.clearIdleTimer(e);let t=this.contexts.get(e);t&&(t.dispose(),this.contexts.delete(e),this.tabs.delete(e),Q.info(`Scoop context destroyed`,{jid:e}))}isProcessing(e){return this.tabs.get(e)?.status===`processing`}getScoopContext(e){return this.contexts.get(e)}async clearQueuedMessages(e){let t=this.messageQueues.get(e);if(t&&t.length>0){for(let e of t)await Fe(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 Fe(t)}async getMessagesForScoop(e){return Te(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.tabs.get(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return Q.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r){let i=this.contexts.get(e);i||=(await this.createScoopTab(e),this.contexts.get(e));let a=this.tabs.get(e);if(a?.status===`initializing`){if(Q.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){Q.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}i=this.contexts.get(e),a=this.tabs.get(e)}if(!i){Q.error(`Context not found after creation`,{jid:e});return}this.clearIdleTimer(e),this.scoopResponseBuffer.delete(e),a&&(a.status=`processing`,a.lastActivity=new Date().toISOString(),this.tabs.set(e,a),this.callbacks.onStatusChange(e,`processing`)),Q.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length}),await i.prompt(t)}async processScoopQueue(e){let t=this.messageQueues.get(e);if(!t||t.length===0){Q.debug(`processScoopQueue: empty queue`,{jid:e});return}let n=this.tabs.get(e);if(n?.status!==`ready`){Q.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.scoops.get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await Ee(e,a,i);if(Q.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,queueLength:t.length}),o.length===0){Q.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]);return}let s=o.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${e.content}`).join(`
|
|
12730
|
-
`);this.messageQueues.set(e,[]);let c=o[o.length-1];this.lastAgentTimestamp.set(e,c.timestamp),await Be(`lastAgentTs_${e}`,c.timestamp),await this.sendPrompt(e,s,c.senderId,c.senderName)}startMessageLoop(){this.pollInterval||=window.setInterval(()=>{for(let e of this.scoops.keys())this.tabs.get(e)?.status===`ready`&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Message queue processing failed`,{jid:e,error:n}),this.callbacks.onError(e,`Queue processing failed: ${n}`)})},2e3)}stopMessageLoop(){this.pollInterval&&=(clearInterval(this.pollInterval),null)}updateModel(){for(let e of this.contexts.values())e.updateModel();Q.info(`Model updated on all active contexts`,{contextCount:this.contexts.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.contexts){let r=this.tabs.get(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{Q.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),Q.info(`Skills reloaded across all contexts`,{count:e.length})}stopScoop(e){let t=this.contexts.get(e);t&&t.stop()}getSessionCosts(){let e=[];for(let t of this.scoops.values()){let n=this.contexts.get(t.jid);if(!n)continue;let r=n.getAgentMessages().filter(e=>e.role===`assistant`);if(r.length===0)continue;let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},a=new Map;for(let e of r)i.input+=e.usage.input,i.output+=e.usage.output,i.cacheRead+=e.usage.cacheRead,i.cacheWrite+=e.usage.cacheWrite,i.totalTokens+=e.usage.totalTokens,i.cost.input+=e.usage.cost.input,i.cost.output+=e.usage.cost.output,i.cost.cacheRead+=e.usage.cost.cacheRead,i.cost.cacheWrite+=e.usage.cost.cacheWrite,i.cost.total+=e.usage.cost.total,a.set(e.model,(a.get(e.model)??0)+1);let o=``,s=0;for(let[e,t]of a)t>s&&(o=e,s=t);e.push({name:t.assistantLabel,type:t.isCone?`cone`:`scoop`,model:o,usage:i,turns:r.length})}return e}startIdleTimer(e){if(this.clearIdleTimer(e),this.tabs.get(e)?.status===`processing`)return;let t=setTimeout(()=>{this.idleTimers.delete(e);let t=this.scoops.get(e);if(!t||t.isCone||this.tabs.get(e)?.status!==`ready`)return;let n=Array.from(this.scoops.values()).find(e=>e.isCone);if(!n)return;let r={id:`scoop-idle-${e}-${Date.now()}`,chatJid:n.jid,senderId:t.folder,senderName:t.assistantLabel,content:`[@${t.assistantLabel} idle]: Scoop "${t.name}" has been ready for 2 minutes without receiving any work. This is expected if the scoop is waiting for webhooks or cron tasks. If you intended to delegate work, use feed_scoop to send a prompt.`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-idle`};Q.info(`Scoop idle timeout`,{jid:e,scoop:t.folder}),this.handleMessage(r).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Failed to send idle notification`,{jid:e,error:n})})},by);this.idleTimers.set(e,t)}clearIdleTimer(e){let t=this.idleTimers.get(e);t&&(clearTimeout(t),this.idleTimers.delete(e))}async shutdown(){this.stopMessageLoop();for(let e of this.idleTimers.keys())this.clearIdleTimer(e);this.scheduler?.stop(),this.scheduler=null;for(let e of this.contexts.keys())await this.destroyScoopTab(e);Q.info(`Orchestrator shutdown`)}};n(`heartbeat`);var Sy=n(`tray-follower`);function Cy(e){let t=new URL(e);return t.searchParams.set(`json`,`true`),t.toString()}async function wy(e){let t=Cy(e.joinUrl),n=await jy(await(e.fetchImpl??fetch)(t,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:e.controllerId,runtime:e.runtime})}));return Sy.info(`Follower tray attach response`,{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),Ty(n)}function Ty(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 Ey(e){return Ay(await My(e,{action:`poll`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function Dy(e){return Ay(await My(e,{action:`answer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function Oy(e){return Ay(await My(e,{action:`ice-candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function ky(e){return Ay(await My(e,{action:`retry`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function Ay(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function jy(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!Ny(n)){let n=t?t.slice(0,200):`(empty)`;throw Sy.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 My(e,t){let n=Cy(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(!Py(i))throw Error(`Tray follower bootstrap returned an invalid response (${r.status})`);return i}function Ny(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`&&Fy(r.bootstrap):r.action===`fail`?(r.code===`INVALID_JOIN_CAPABILITY`||r.code===`TRAY_EXPIRED`)&&typeof r.error==`string`:!1}function Py(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`&&Fy(t.bootstrap)&&Array.isArray(t.events)}function Fy(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 Iy=n(`tray-webrtc`),Ly=`tray-control`,Ry=250,zy=class{peerConnectionFactory;dataChannelLabel;peers=new Map;iceServers;constructor(e){this.options=e,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>Hy(this.iceServers)),this.dataChannelLabel=e.dataChannelLabel??Ly}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=Wy(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`)&&(Iy.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`?(Iy.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`?(Iy.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:Uy(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){Iy.warn(`Failed to report tray bootstrap failure`,{error:e instanceof Error?e.message:String(e)})}}}},By=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??(()=>Hy(this.iceServers)),this.controllerIdFactory=e.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),this.pollIntervalMs=e.pollIntervalMs??Ry}async start(){this.stopped=!1;let e=this.controllerIdFactory(),t=Date.now();f({state:`connecting`,joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:t,lastError:null}),Iy.info(`Follower tray join starting`,{joinUrl:this.options.joinUrl});let n=0;for(;;){Gy(this.stopped),n++;let t;try{t=await wy({joinUrl:this.options.joinUrl,controllerId:e,runtime:this.options.runtime,fetchImpl:this.fetchImpl})}catch(e){let t=e instanceof Error?e.message:String(e);throw f({...m(),attachAttempts:n,lastError:t}),e}if(f({...m(),attachAttempts:n,lastAttachCode:t.code}),t.action===`wait`){let e=t.retryAfterMs??1e3;Iy.info(`Follower tray attach waiting`,{attempt:n,code:t.code,retryAfterMs:e}),n%10==0&&Iy.warn(`Follower tray attach still waiting after ${n} attempts`,{attempt:n,code:t.code,retryAfterMs:e}),await this.sleep(e);continue}if(t.action===`fail`||!t.bootstrap){let e=t.error??`Tray follower attach failed (${t.code})`;throw f({state:`error`,joinUrl:this.options.joinUrl,trayId:null,error:e,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:e}),Iy.warn(`Follower tray attach failed`,{error:e}),Error(e)}t.iceServers&&(this.iceServers=t.iceServers);try{let r=await this.completeBootstrap(t.trayId,e,t.bootstrap);return f({state:`connected`,joinUrl:this.options.joinUrl,trayId:r.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:null}),Iy.info(`Follower tray connected`,{trayId:r.trayId,controllerId:e}),r}catch(e){let r=e instanceof Error?e.message:String(e);throw f({state:`error`,joinUrl:this.options.joinUrl,trayId:t.trayId,error:r,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:r}),Iy.warn(`Follower tray bootstrap failed`,{error:r}),e}}}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,f({state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null})}async completeBootstrap(e,t,n){let r=n,i=0;for(this.activePeer=this.createFollowerPeer(t,r.bootstrapId);;){if(Gy(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 Ey({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 Dy({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,answer:Uy(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 ky({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`)&&(Iy.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?(Iy.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?(Iy.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=Wy(n);r&&Oy({joinUrl:this.options.joinUrl,controllerId:e,bootstrapId:t,candidate:r,fetchImpl:this.fetchImpl}).catch(e=>{Iy.warn(`Failed to send follower ICE candidate`,{error:e instanceof Error?e.message:String(e)})})}),r}};function Vy(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 By({...e,sleep:o,onDisconnected:e=>{s||(Iy.warn(`Follower disconnected, starting reconnect loop`,{reason:e}),p(e))}});return l=t,{manager:t,connectionPromise:t.start()}},p=async u=>{if(s||c)return;c=!0,l?.stop(),l=null;let p=0,h=n,g=u??`Unknown disconnect`;for(;!s&&p<a&&(p++,t.onReconnecting?.(p),f({...m(),state:`reconnecting`,error:null,reconnectAttempts:p}),Iy.info(`Reconnect attempt`,{attempt:p,delay:h}),await o(h),!s);){let n=null;try{let r=d();n=r.manager;let i=await r.connectionPromise;if(s){n.stop();break}c=!1,f({...m(),state:`connected`,joinUrl:e.joinUrl,trayId:i.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),Iy.info(`Reconnect successful`,{attempt:p,trayId:i.trayId}),t.onConnected(i);return}catch(e){g=e instanceof Error?e.message:String(e),Iy.warn(`Reconnect attempt failed`,{attempt:p,error:g}),n?.stop(),l=null}h=Math.min(h*r,i)}s||(c=!1,f({...m(),state:`error`,error:`Reconnect failed after ${p} attempts: ${g}`,reconnectAttempts:p}),Iy.warn(`Reconnect gave up`,{attempts:p,lastError:g}),t.onGaveUp?.(g))},{connectionPromise:h}=d();return h.then(e=>{s||t.onConnected(e)}).catch(e=>{s||Iy.warn(`Initial follower connection failed`,{error:e instanceof Error?e.message:String(e)})}),u}function Hy(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 Uy(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 Wy(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 Gy(e){if(e)throw Error(`Tray follower stopped before WebRTC bootstrap completed`)}var Ky=64*1024;async function qy(e,t){try{switch(t.op){case`readFile`:return await Jy(e,t.path,t.encoding);case`writeFile`:return[await Yy(e,t.path,t.content,t.encoding)];case`stat`:return[await Xy(e,t.path)];case`readDir`:return[await Zy(e,t.path)];case`mkdir`:return[await Qy(e,t.path,t.recursive)];case`rm`:return[await $y(e,t.path,t.recursive)];case`exists`:return[await eb(e,t.path)];case`walk`:return[await tb(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(e){return[rb(e)]}}async function Jy(e,t,n){return(n??`utf-8`)===`utf-8`?nb(await e.readFile(t,{encoding:`utf-8`}),`utf-8`):nb(ib(await e.readFile(t,{encoding:`binary`})),`base64`)}async function Yy(e,t,n,r){if(r===`base64`){let r=ab(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:`void`}}}async function Xy(e,t){return{ok:!0,data:{type:`stat`,stat:await e.stat(t)}}}async function Zy(e,t){return{ok:!0,data:{type:`dirEntries`,entries:await e.readDir(t)}}}async function Qy(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function $y(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function eb(e,t){return{ok:!0,data:{type:`exists`,exists:await e.exists(t)}}}async function tb(e,t){let n=[];for await(let r of e.walk(t))n.push(r);return{ok:!0,data:{type:`paths`,paths:n}}}function nb(e,t){if(e.length<=Ky)return[{ok:!0,data:{type:`file`,content:e,encoding:t}}];let n=Math.ceil(e.length/Ky),r=[];for(let i=0;i<n;i++){let a=i*Ky,o=e.slice(a,a+Ky);r.push({ok:!0,data:{type:`file`,content:o,encoding:t},chunkIndex:i,totalChunks:n})}return r}function rb(e){return e instanceof Error&&`code`in e?{ok:!1,error:e.message,code:e.code}:{ok:!1,error:e instanceof Error?e.message:String(e)}}function ib(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function ab(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var ob=class{runtimes=new Map;dirty=!1;setTargets(e,t){this.runtimes.set(e,t),this.dirty=!0}removeRuntime(e){this.runtimes.delete(e)&&(this.dirty=!0)}getEntries(){this.dirty=!1;let e=[];for(let[t,n]of this.runtimes)for(let r of n)e.push({targetId:`${t}:${r.targetId}`,localTargetId:r.targetId,runtimeId:t,title:r.title,url:r.url,isLocal:!1});return e}hasChanged(){return this.dirty}getRuntimeIds(){return[...this.runtimes.keys()]}},sb=n(`data-channel-keepalive`),cb=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++,sb.debug(`Missed pong`,{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){sb.warn(`Channel declared dead`,{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}},lb=n(`tray-leader-sync`);function ub(e){return e?e.includes(`standalone`)?`standalone`:e.includes(`extension`)?`extension`:e.includes(`electron`)?`electron`:`unknown`:`unknown`}var db=class{followers=new Map;registry=new ob;runtimeToBootstrap=new Map;pendingCDPRoutes=new Map;cdpChunkBuffers=new Map;remoteTransports=new Map;pendingTabOpenRoutes=new Map;tabOpenResolvers=new Map;pendingFsRoutes=new Map;fsResolvers=new Map;constructor(e){this.options=e}addFollower(e,t,n){this.removeFollower(e);let r=me(t),i=r.onMessage(t=>{this.handleFollowerMessage(e,t)}),a=new cb({sendPing:()=>r.send({type:`ping`}),onDead:()=>{lb.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:ub(n?.runtime)}),lb.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(),lb.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();fe(t.sync,n,r),lb.debug(`Snapshot sent to follower`,{bootstrapId:e,messageCount:n.length})}handleFollowerMessage(e,t){switch(t.type){case`user_message`:lb.info(`Follower user message received`,{bootstrapId:e,messageId:t.messageId}),this.options.onFollowerMessage(t.text,t.messageId);break;case`abort`:lb.info(`Follower abort received`,{bootstrapId:e}),this.options.onFollowerAbort();break;case`request_snapshot`:lb.info(`Follower snapshot request received`,{bootstrapId:e}),this.sendSnapshotToFollower(e);break;case`targets.advertise`:lb.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),lb.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),lb.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);ye(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=de(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&&ye(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 qy(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?qy(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})})}},fb=n(`tray-follower-sync`),pb=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=ve(e),this.unsubscribe=this.sync.onMessage(e=>{this.handleLeaderMessage(e)}),this.keepalive=new cb({sendPing:()=>this.sync.send({type:`ping`}),onDead:()=>{fb.warn(`Leader keepalive dead, cleaning up`),this.handleDisconnect(`Keepalive timeout — leader not responding`),this.options.onDead?.()}}),this.keepalive.start(),e.addEventListener(`close`,()=>{fb.warn(`Data channel closed`),this.handleDisconnect(`Data channel closed`)}),e.addEventListener(`error`,()=>{fb.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}),fb.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`}),fb.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(),fb.info(`Follower sync closed`)}advertiseTargets(e,t){this.sync.send({type:`targets.advertise`,targets:e,runtimeId:t})}getTargets(){return this.targetEntries}disconnected=!1;handleDisconnect(e){this.disconnected||(this.disconnected=!0,f({...m(),state:`error`,error:e}),this.emitEvent({type:`error`,error:`Connection to leader lost: ${e}`}),this.keepalive.stop(),this.cleanupCDPEventForwarding(),this.unsubscribe(),this.sync.close(),this.options.onDisconnect?.(e))}handleLeaderMessage(e){switch(e.type){case`snapshot`:fb.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=_e(this.snapshotChunkBuffer,e);this.snapshotChunkBuffer=t.buffer,t.result&&(fb.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),fb.debug(`Skipping own message echo`,{messageId:e.messageId});break}fb.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`:fb.warn(`Error from leader`,{error:e.error}),this.emitEvent({type:`error`,error:e.error});break;case`targets.registry`:fb.info(`Target registry received from leader`,{targetCount:e.targets.length}),this.targetEntries=e.targets,this.options.onTargetsUpdated?.(this.targetEntries);break;case`cdp.request`:{let{requestId:t,localTargetId:n,method:r,params:i,sessionId:a}=e;this.executeLocalCDP(t,n,r,i,a);break}case`cdp.response`:this.routeCDPResponse(e);break;case`cdp.event`:for(let t of this.remoteTransports.values())t.handleEvent(e.method,e.params);break;case`tab.open`:this.executeLocalTabOpen(e.requestId,e.url);break;case`tab.opened`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.resolve(e.targetId));break}case`tab.open.error`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.reject(Error(e.error)));break}case`fs.request`:this.executeLocalFs(e.requestId,e.request);break;case`fs.response`:this.routeFsResponse(e.requestId,e.response);break;case`ping`:this.keepalive.receivePing(),this.sync.send({type:`pong`});break;case`pong`:this.keepalive.receivePong(),l(Date.now());break}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch(t){fb.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),fb.debug(`Tracking remote CDP session`,{remoteSessionId:e})}n===`Target.detachFromTarget`&&i&&this.remoteCDPSessions.has(i)&&(this.remoteCDPSessions.delete(i),fb.debug(`Removed remote CDP session on detach`,{sessionId:i})),ye(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=de(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 qy(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 mb(e,t){if(t)return`extension`;try{return _b(new URL(e))?`electron-overlay`:`standalone`}catch{return`standalone`}}function hb(e,t){return e===`electron-overlay`||e===`standalone`&&t}function gb(e){try{let t=new URL(e).searchParams.get(`tab`);return t&&Ki(t)?t:Wi}catch{return Wi}}function _b(e){return e.pathname===`/electron`||e.pathname===`/electron/`||e.searchParams.get(`runtime`)===`electron-overlay`}function vb(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}/licks-ws`}function yb(e,t){return`${new URL(e).origin}/webhooks/${t}`}function bb(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function xb(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`slicc-electron-overlay:set-tab`}var Sb=[`/shared/sprinkles`];async function Cb(e){let t=new Map;for(let n of Sb)await e.exists(n)&&await wb(e,n,t);return await wb(e,`/`,t),t}async function wb(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.shtml`))continue;let t=Tb(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:Eb(i,t),autoOpen:Db(i)})}}}function Tb(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.shtml`)?t.slice(0,-6):t}function Eb(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 Db(e){return/data-sprinkle-autoopen\b/.test(e)}var Ob=class{listeners=new Map;lickHandler;fs;closeHandler;stopConeHandler;constructor(e,t,n,r){this.fs=e,this.lickHandler=t,this.closeHandler=n,this.stopConeHandler=r}createAPI(e){let t={name:e,lick:t=>{let n=typeof t==`string`?t:t.action,r=typeof t==`string`?void 0:t.data,i={type:`sprinkle`,sprinkleName:e,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:n,data:r}};this.lickHandler(i)},on:(t,n)=>{let r=`${e}:${t}`,i=this.listeners.get(r);i||(i=new Set,this.listeners.set(r,i)),i.add(n)},off:(t,n)=>{let r=`${e}:${t}`;this.listeners.get(r)?.delete(n)},readFile:async e=>await this.fs.readFile(e,{encoding:`utf-8`}),writeFile:async(e,t)=>{await this.fs.writeFile(e,t)},readDir:async e=>(await this.fs.readDir(e)).map(e=>({name:e.name,type:e.type})),exists:async e=>this.fs.exists(e),stat:async e=>{let t=await this.fs.stat(e);return{type:t.type,size:t.size}},mkdir:async e=>{await this.fs.mkdir(e,{recursive:!0})},rm:async e=>{await this.fs.rm(e)},screenshot:async e=>{let n=t._container;if(!n)return``;let r=e?n.querySelector(e):n;if(!r)throw Error(`Element not found: `+(e||`container`));let i=r.getBoundingClientRect(),a=Math.ceil(i.width),o=Math.ceil(i.height);if(a===0||o===0)throw Error(`Element has zero dimensions`);let s=document.createElement(`canvas`),c=window.devicePixelRatio||1;s.width=a*c,s.height=o*c;let l=s.getContext(`2d`);l.scale(c,c);let u=r.cloneNode(!0),d=`<svg xmlns="http://www.w3.org/2000/svg" width="${a}" height="${o}"><foreignObject width="100%" height="100%">${new XMLSerializer().serializeToString(u)}</foreignObject></svg>`;return new Promise((e,t)=>{let n=new Image;n.onload=()=>{l.drawImage(n,0,0),e(s.toDataURL(`image/png`))},n.onerror=()=>t(Error(`Screenshot rendering failed`)),n.src=`data:image/svg+xml;charset=utf-8,`+encodeURIComponent(d)})},setState:t=>{try{localStorage.setItem(`slicc-sprinkle-state:${e}`,JSON.stringify(t))}catch{}},getState:()=>{try{let t=localStorage.getItem(`slicc-sprinkle-state:${e}`);return t?JSON.parse(t):null}catch{return null}},open:e=>{let t=/^https?:|^chrome-extension:/.test(e)?e:ym(e);window.open(t,`_blank`)},close:()=>this.closeHandler(e),stopCone:()=>this.stopConeHandler()};return t}pushUpdate(e,t){let n=`${e}:update`,r=this.listeners.get(n);if(r)for(let e of r)try{e(t)}catch{}}removeSprinkle(e){for(let t of this.listeners.keys())t.startsWith(`${e}:`)&&this.listeners.delete(t)}},kb=n(`sprinkle-manager`),Ab=`slicc-open-sprinkles`,jb=class{fs;bridge;callbacks;availableSprinkles=new Map;watcherUnsub;openSprinkles=new Map;constructor(e,t,n,r){this.fs=e,this.bridge=new Ob(e,t,e=>this.close(e),r),this.callbacks=n}async restoreOpenSprinkles(){try{let e=localStorage.getItem(Ab);if(!e){for(let e of this.availableSprinkles.values())if(e.autoOpen)try{await this.open(e.name)}catch{kb.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{kb.warn(`Failed to restore sprinkle`,{name:e})}}catch{}}persistOpenSprinkles(){try{localStorage.setItem(Ab,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),kb.info(`Auto-opened new sprinkle after install`,{name:e.name})}catch{kb.warn(`Failed to auto-open new sprinkle`,{name:e.name})}}async refresh(){this.availableSprinkles=await Cb(this.fs),kb.info(`Discovered sprinkles`,{count:this.availableSprinkles.size})}async open(e,t){if(this.openSprinkles.has(e)){kb.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 ii(i,this.bridge.createAPI(e));await a.render(r,e),this.openSprinkles.get(e).renderer=a,this.persistOpenSprinkles(),iv(e),kb.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(),kb.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){kb.warn(`Cannot send to closed sprinkle`,{name:e});return}this.bridge.pushUpdate(e,t),n.renderer.pushUpdate(t)}};function Mb(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function Nb(e){let t=[],{payload:n}=e;if(n.title&&t.push(`# ${n.title}`),t.push(`A new handoff was accepted from ${Mb(e.sourceUrl)}.`),t.push(`## Instruction`),t.push(n.instruction),n.urls&&n.urls.length>0){t.push(`## URLs`);for(let e of n.urls)t.push(`- ${e}`)}if(n.context&&(t.push(`## Context`),t.push(n.context)),n.acceptanceCriteria&&n.acceptanceCriteria.length>0){t.push(`## Acceptance Criteria`);for(let e of n.acceptanceCriteria)t.push(`- ${e}`)}return n.notes&&(t.push(`## Notes`),t.push(n.notes)),t.join(`
|
|
12731
|
+
`);this.messageQueues.set(e,[]);let c=o[o.length-1];this.lastAgentTimestamp.set(e,c.timestamp),await Be(`lastAgentTs_${e}`,c.timestamp),await this.sendPrompt(e,s,c.senderId,c.senderName)}startMessageLoop(){this.pollInterval||=window.setInterval(()=>{for(let e of this.scoops.keys())this.tabs.get(e)?.status===`ready`&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Message queue processing failed`,{jid:e,error:n}),this.callbacks.onError(e,`Queue processing failed: ${n}`)})},2e3)}stopMessageLoop(){this.pollInterval&&=(clearInterval(this.pollInterval),null)}updateModel(){for(let e of this.contexts.values())e.updateModel();Q.info(`Model updated on all active contexts`,{contextCount:this.contexts.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.contexts){let r=this.tabs.get(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{Q.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),Q.info(`Skills reloaded across all contexts`,{count:e.length})}stopScoop(e){let t=this.contexts.get(e);t&&t.stop()}getSessionCosts(){let e=[];for(let t of this.scoops.values()){let n=this.contexts.get(t.jid);if(!n)continue;let r=n.getAgentMessages().filter(e=>e.role===`assistant`);if(r.length===0)continue;let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},a=new Map;for(let e of r)i.input+=e.usage.input,i.output+=e.usage.output,i.cacheRead+=e.usage.cacheRead,i.cacheWrite+=e.usage.cacheWrite,i.totalTokens+=e.usage.totalTokens,i.cost.input+=e.usage.cost.input,i.cost.output+=e.usage.cost.output,i.cost.cacheRead+=e.usage.cost.cacheRead,i.cost.cacheWrite+=e.usage.cost.cacheWrite,i.cost.total+=e.usage.cost.total,a.set(e.model,(a.get(e.model)??0)+1);let o=``,s=0;for(let[e,t]of a)t>s&&(o=e,s=t);e.push({name:t.assistantLabel,type:t.isCone?`cone`:`scoop`,model:o,usage:i,turns:r.length})}return e}startIdleTimer(e){if(this.clearIdleTimer(e),this.tabs.get(e)?.status===`processing`)return;let t=setTimeout(()=>{this.idleTimers.delete(e);let t=this.scoops.get(e);if(!t||t.isCone||this.tabs.get(e)?.status!==`ready`)return;let n=Array.from(this.scoops.values()).find(e=>e.isCone);if(!n)return;let r={id:`scoop-idle-${e}-${Date.now()}`,chatJid:n.jid,senderId:t.folder,senderName:t.assistantLabel,content:`[@${t.assistantLabel} idle]: Scoop "${t.name}" has been ready for 2 minutes without receiving any work. This is expected if the scoop is waiting for webhooks or cron tasks. If you intended to delegate work, use feed_scoop to send a prompt.`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-idle`};Q.info(`Scoop idle timeout`,{jid:e,scoop:t.folder}),this.handleMessage(r).catch(t=>{let n=t instanceof Error?t.message:String(t);Q.error(`Failed to send idle notification`,{jid:e,error:n})})},Ly);this.idleTimers.set(e,t)}clearIdleTimer(e){let t=this.idleTimers.get(e);t&&(clearTimeout(t),this.idleTimers.delete(e))}async shutdown(){this.stopMessageLoop();for(let e of this.idleTimers.keys())this.clearIdleTimer(e);this.scheduler?.stop(),this.scheduler=null;for(let e of this.contexts.keys())await this.destroyScoopTab(e);Q.info(`Orchestrator shutdown`)}};n(`heartbeat`);var zy=n(`tray-follower`);function By(e){let t=new URL(e);return t.searchParams.set(`json`,`true`),t.toString()}async function Vy(e){let t=By(e.joinUrl),n=await Jy(await(e.fetchImpl??fetch)(t,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:e.controllerId,runtime:e.runtime})}));return zy.info(`Follower tray attach response`,{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),Hy(n)}function Hy(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 Uy(e){return qy(await Yy(e,{action:`poll`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function Wy(e){return qy(await Yy(e,{action:`answer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function Gy(e){return qy(await Yy(e,{action:`ice-candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function Ky(e){return qy(await Yy(e,{action:`retry`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function qy(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function Jy(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!Xy(n)){let n=t?t.slice(0,200):`(empty)`;throw zy.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 Yy(e,t){let n=By(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(!Zy(i))throw Error(`Tray follower bootstrap returned an invalid response (${r.status})`);return i}function Xy(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`&&Qy(r.bootstrap):r.action===`fail`?(r.code===`INVALID_JOIN_CAPABILITY`||r.code===`TRAY_EXPIRED`)&&typeof r.error==`string`:!1}function Zy(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`&&Qy(t.bootstrap)&&Array.isArray(t.events)}function Qy(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 $y=n(`tray-webrtc`),eb=`tray-control`,tb=250,nb=class{peerConnectionFactory;dataChannelLabel;peers=new Map;iceServers;constructor(e){this.options=e,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>ab(this.iceServers)),this.dataChannelLabel=e.dataChannelLabel??eb}setIceServers(e){this.iceServers=e}async handleControlMessage(e){e.type===`follower.join_requested`?(e.iceServers&&!this.iceServers&&(this.iceServers=e.iceServers),await this.handleJoinRequested(e)):e.type===`bootstrap.answer`?await this.peers.get(e.bootstrapId)?.peer.setRemoteDescription(e.answer):e.type===`bootstrap.ice_candidate`&&await this.peers.get(e.bootstrapId)?.peer.addIceCandidate(e.candidate)}getPeers(){return Array.from(this.peers.values()).map(({state:e})=>({...e}))}getChannel(e){return this.peers.get(e)?.channel??null}stop(){for(let e of this.peers.values())e.peer.close();this.peers.clear()}async handleJoinRequested(e){this.closeControllerPeers(e.controllerId);let t=this.peerConnectionFactory(),n={controllerId:e.controllerId,bootstrapId:e.bootstrapId,attempt:e.attempt,state:`connecting`,connectedAt:null,runtime:e.runtime},r=t.createDataChannel(this.dataChannelLabel);this.peers.set(e.bootstrapId,{state:n,peer:t,channel:r}),t.addEventListener(`icecandidate`,({candidate:t})=>{let n=sb(t);n&&this.options.sendControlMessage({type:`bootstrap.ice_candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:n})}),t.addEventListener(`connectionstatechange`,()=>{let n=this.peers.get(e.bootstrapId);n&&(n.state.state===`connected`?(t.connectionState===`disconnected`||t.connectionState===`failed`)&&($y.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`?($y.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`?($y.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:ob(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){$y.warn(`Failed to report tray bootstrap failure`,{error:e instanceof Error?e.message:String(e)})}}}},rb=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??(()=>ab(this.iceServers)),this.controllerIdFactory=e.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),this.pollIntervalMs=e.pollIntervalMs??tb}async start(){this.stopped=!1;let e=this.controllerIdFactory(),t=Date.now();f({state:`connecting`,joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:t,lastError:null}),$y.info(`Follower tray join starting`,{joinUrl:this.options.joinUrl});let n=0;for(;;){cb(this.stopped),n++;let t;try{t=await Vy({joinUrl:this.options.joinUrl,controllerId:e,runtime:this.options.runtime,fetchImpl:this.fetchImpl})}catch(e){let t=e instanceof Error?e.message:String(e);throw f({...m(),attachAttempts:n,lastError:t}),e}if(f({...m(),attachAttempts:n,lastAttachCode:t.code}),t.action===`wait`){let e=t.retryAfterMs??1e3;$y.info(`Follower tray attach waiting`,{attempt:n,code:t.code,retryAfterMs:e}),n%10==0&&$y.warn(`Follower tray attach still waiting after ${n} attempts`,{attempt:n,code:t.code,retryAfterMs:e}),await this.sleep(e);continue}if(t.action===`fail`||!t.bootstrap){let e=t.error??`Tray follower attach failed (${t.code})`;throw f({state:`error`,joinUrl:this.options.joinUrl,trayId:null,error:e,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:e}),$y.warn(`Follower tray attach failed`,{error:e}),Error(e)}t.iceServers&&(this.iceServers=t.iceServers);try{let r=await this.completeBootstrap(t.trayId,e,t.bootstrap);return f({state:`connected`,joinUrl:this.options.joinUrl,trayId:r.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:null}),$y.info(`Follower tray connected`,{trayId:r.trayId,controllerId:e}),r}catch(e){let r=e instanceof Error?e.message:String(e);throw f({state:`error`,joinUrl:this.options.joinUrl,trayId:t.trayId,error:r,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:r}),$y.warn(`Follower tray bootstrap failed`,{error:r}),e}}}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,f({state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null})}async completeBootstrap(e,t,n){let r=n,i=0;for(this.activePeer=this.createFollowerPeer(t,r.bootstrapId);;){if(cb(this.stopped),this.activePeer.open&&this.activePeer.channel)return{trayId:e,controllerId:t,bootstrapId:r.bootstrapId,channel:this.activePeer.channel};if(this.activePeer.openError)throw Error(this.activePeer.openError);let n=await Uy({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 Wy({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,answer:ob(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 Ky({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`)&&($y.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?($y.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?($y.warn(`Follower data channel error post-connect`,{bootstrapId:t}),this.options.onDisconnected?.(`Data channel error`)):r.openError=`Follower data channel failed before opening`})}),n.addEventListener(`icecandidate`,({candidate:n})=>{let r=sb(n);r&&Gy({joinUrl:this.options.joinUrl,controllerId:e,bootstrapId:t,candidate:r,fetchImpl:this.fetchImpl}).catch(e=>{$y.warn(`Failed to send follower ICE candidate`,{error:e instanceof Error?e.message:String(e)})})}),r}};function ib(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 rb({...e,sleep:o,onDisconnected:e=>{s||($y.warn(`Follower disconnected, starting reconnect loop`,{reason:e}),p(e))}});return l=t,{manager:t,connectionPromise:t.start()}},p=async u=>{if(s||c)return;c=!0,l?.stop(),l=null;let p=0,h=n,g=u??`Unknown disconnect`;for(;!s&&p<a&&(p++,t.onReconnecting?.(p),f({...m(),state:`reconnecting`,error:null,reconnectAttempts:p}),$y.info(`Reconnect attempt`,{attempt:p,delay:h}),await o(h),!s);){let n=null;try{let r=d();n=r.manager;let i=await r.connectionPromise;if(s){n.stop();break}c=!1,f({...m(),state:`connected`,joinUrl:e.joinUrl,trayId:i.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),$y.info(`Reconnect successful`,{attempt:p,trayId:i.trayId}),t.onConnected(i);return}catch(e){g=e instanceof Error?e.message:String(e),$y.warn(`Reconnect attempt failed`,{attempt:p,error:g}),n?.stop(),l=null}h=Math.min(h*r,i)}s||(c=!1,f({...m(),state:`error`,error:`Reconnect failed after ${p} attempts: ${g}`,reconnectAttempts:p}),$y.warn(`Reconnect gave up`,{attempts:p,lastError:g}),t.onGaveUp?.(g))},{connectionPromise:h}=d();return h.then(e=>{s||t.onConnected(e)}).catch(e=>{s||$y.warn(`Initial follower connection failed`,{error:e instanceof Error?e.message:String(e)})}),u}function ab(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 ob(e,t){if(!e||e.type!==t||typeof e.sdp!=`string`)throw Error(`Expected a local ${t} description before signaling`);return{type:e.type,sdp:e.sdp}}function sb(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.candidate==`string`?{candidate:t.candidate,sdpMid:typeof t.sdpMid==`string`?t.sdpMid:null,sdpMLineIndex:typeof t.sdpMLineIndex==`number`?t.sdpMLineIndex:null,usernameFragment:typeof t.usernameFragment==`string`?t.usernameFragment:null}:null}function cb(e){if(e)throw Error(`Tray follower stopped before WebRTC bootstrap completed`)}var lb=64*1024;async function ub(e,t){try{switch(t.op){case`readFile`:return await db(e,t.path,t.encoding);case`writeFile`:return[await fb(e,t.path,t.content,t.encoding)];case`stat`:return[await pb(e,t.path)];case`readDir`:return[await mb(e,t.path)];case`mkdir`:return[await hb(e,t.path,t.recursive)];case`rm`:return[await gb(e,t.path,t.recursive)];case`exists`:return[await _b(e,t.path)];case`walk`:return[await vb(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(e){return[bb(e)]}}async function db(e,t,n){return(n??`utf-8`)===`utf-8`?yb(await e.readFile(t,{encoding:`utf-8`}),`utf-8`):yb(xb(await e.readFile(t,{encoding:`binary`})),`base64`)}async function fb(e,t,n,r){if(r===`base64`){let r=Sb(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:`void`}}}async function pb(e,t){return{ok:!0,data:{type:`stat`,stat:await e.stat(t)}}}async function mb(e,t){return{ok:!0,data:{type:`dirEntries`,entries:await e.readDir(t)}}}async function hb(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function gb(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function _b(e,t){return{ok:!0,data:{type:`exists`,exists:await e.exists(t)}}}async function vb(e,t){let n=[];for await(let r of e.walk(t))n.push(r);return{ok:!0,data:{type:`paths`,paths:n}}}function yb(e,t){if(e.length<=lb)return[{ok:!0,data:{type:`file`,content:e,encoding:t}}];let n=Math.ceil(e.length/lb),r=[];for(let i=0;i<n;i++){let a=i*lb,o=e.slice(a,a+lb);r.push({ok:!0,data:{type:`file`,content:o,encoding:t},chunkIndex:i,totalChunks:n})}return r}function bb(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 xb(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Sb(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 Cb=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()]}},wb=n(`data-channel-keepalive`),Tb=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++,wb.debug(`Missed pong`,{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){wb.warn(`Channel declared dead`,{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}},Eb=n(`tray-leader-sync`);function Db(e){return e?e.includes(`standalone`)?`standalone`:e.includes(`extension`)?`extension`:e.includes(`electron`)?`electron`:`unknown`:`unknown`}var Ob=class{followers=new Map;registry=new Cb;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=me(t),i=r.onMessage(t=>{this.handleFollowerMessage(e,t)}),a=new Tb({sendPing:()=>r.send({type:`ping`}),onDead:()=>{Eb.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:Db(n?.runtime)}),Eb.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(),Eb.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();fe(t.sync,n,r),Eb.debug(`Snapshot sent to follower`,{bootstrapId:e,messageCount:n.length})}handleFollowerMessage(e,t){switch(t.type){case`user_message`:Eb.info(`Follower user message received`,{bootstrapId:e,messageId:t.messageId}),this.options.onFollowerMessage(t.text,t.messageId);break;case`abort`:Eb.info(`Follower abort received`,{bootstrapId:e}),this.options.onFollowerAbort();break;case`request_snapshot`:Eb.info(`Follower snapshot request received`,{bootstrapId:e}),this.sendSnapshotToFollower(e);break;case`targets.advertise`:Eb.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),Eb.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),Eb.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);ye(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=de(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&&ye(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 ub(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?ub(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})})}},kb=n(`tray-follower-sync`),Ab=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=ve(e),this.unsubscribe=this.sync.onMessage(e=>{this.handleLeaderMessage(e)}),this.keepalive=new Tb({sendPing:()=>this.sync.send({type:`ping`}),onDead:()=>{kb.warn(`Leader keepalive dead, cleaning up`),this.handleDisconnect(`Keepalive timeout — leader not responding`),this.options.onDead?.()}}),this.keepalive.start(),e.addEventListener(`close`,()=>{kb.warn(`Data channel closed`),this.handleDisconnect(`Data channel closed`)}),e.addEventListener(`error`,()=>{kb.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}),kb.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`}),kb.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(),kb.info(`Follower sync closed`)}advertiseTargets(e,t){this.sync.send({type:`targets.advertise`,targets:e,runtimeId:t})}getTargets(){return this.targetEntries}disconnected=!1;handleDisconnect(e){this.disconnected||(this.disconnected=!0,f({...m(),state:`error`,error:e}),this.emitEvent({type:`error`,error:`Connection to leader lost: ${e}`}),this.keepalive.stop(),this.cleanupCDPEventForwarding(),this.unsubscribe(),this.sync.close(),this.options.onDisconnect?.(e))}handleLeaderMessage(e){switch(e.type){case`snapshot`:kb.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=_e(this.snapshotChunkBuffer,e);this.snapshotChunkBuffer=t.buffer,t.result&&(kb.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),kb.debug(`Skipping own message echo`,{messageId:e.messageId});break}kb.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`:kb.warn(`Error from leader`,{error:e.error}),this.emitEvent({type:`error`,error:e.error});break;case`targets.registry`:kb.info(`Target registry received from leader`,{targetCount:e.targets.length}),this.targetEntries=e.targets,this.options.onTargetsUpdated?.(this.targetEntries);break;case`cdp.request`:{let{requestId:t,localTargetId:n,method:r,params:i,sessionId:a}=e;this.executeLocalCDP(t,n,r,i,a);break}case`cdp.response`:this.routeCDPResponse(e);break;case`cdp.event`:for(let t of this.remoteTransports.values())t.handleEvent(e.method,e.params);break;case`tab.open`:this.executeLocalTabOpen(e.requestId,e.url);break;case`tab.opened`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.resolve(e.targetId));break}case`tab.open.error`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.reject(Error(e.error)));break}case`fs.request`:this.executeLocalFs(e.requestId,e.request);break;case`fs.response`:this.routeFsResponse(e.requestId,e.response);break;case`ping`:this.keepalive.receivePing(),this.sync.send({type:`pong`});break;case`pong`:this.keepalive.receivePong(),l(Date.now());break}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch(t){kb.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),kb.debug(`Tracking remote CDP session`,{remoteSessionId:e})}n===`Target.detachFromTarget`&&i&&this.remoteCDPSessions.has(i)&&(this.remoteCDPSessions.delete(i),kb.debug(`Removed remote CDP session on detach`,{sessionId:i})),ye(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=de(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 ub(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 jb(e,t){if(t)return`extension`;try{return Pb(new URL(e))?`electron-overlay`:`standalone`}catch{return`standalone`}}function Mb(e,t){return e===`electron-overlay`||e===`standalone`&&t}function Nb(e){try{let t=new URL(e).searchParams.get(`tab`);return t&&Ki(t)?t:Wi}catch{return Wi}}function Pb(e){return e.pathname===`/electron`||e.pathname===`/electron/`||e.searchParams.get(`runtime`)===`electron-overlay`}function Fb(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}/licks-ws`}function Ib(e,t){return`${new URL(e).origin}/webhooks/${t}`}function Lb(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function Rb(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`slicc-electron-overlay:set-tab`}var zb=[`/shared/sprinkles`];async function Bb(e){let t=new Map;for(let n of zb)await e.exists(n)&&await Vb(e,n,t);return await Vb(e,`/`,t),t}async function Vb(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.shtml`))continue;let t=Hb(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:Ub(i,t),autoOpen:Wb(i)})}}}function Hb(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.shtml`)?t.slice(0,-6):t}function Ub(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 Wb(e){return/data-sprinkle-autoopen\b/.test(e)}var Gb=class{listeners=new Map;lickHandler;fs;closeHandler;stopConeHandler;constructor(e,t,n,r){this.fs=e,this.lickHandler=t,this.closeHandler=n,this.stopConeHandler=r}createAPI(e){let t={name:e,lick:t=>{let n=typeof t==`string`?t:t.action,r=typeof t==`string`?void 0:t.data,i={type:`sprinkle`,sprinkleName:e,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:n,data:r}};this.lickHandler(i)},on:(t,n)=>{let r=`${e}:${t}`,i=this.listeners.get(r);i||(i=new Set,this.listeners.set(r,i)),i.add(n)},off:(t,n)=>{let r=`${e}:${t}`;this.listeners.get(r)?.delete(n)},readFile:async e=>await this.fs.readFile(e,{encoding:`utf-8`}),writeFile:async(e,t)=>{await this.fs.writeFile(e,t)},readDir:async e=>(await this.fs.readDir(e)).map(e=>({name:e.name,type:e.type})),exists:async e=>this.fs.exists(e),stat:async e=>{let t=await this.fs.stat(e);return{type:t.type,size:t.size}},mkdir:async e=>{await this.fs.mkdir(e,{recursive:!0})},rm:async e=>{await this.fs.rm(e)},screenshot:async e=>{let n=t._container;if(!n)return``;let r=e?n.querySelector(e):n;if(!r)throw Error(`Element not found: `+(e||`container`));let i=r.getBoundingClientRect(),a=Math.ceil(i.width),o=Math.ceil(i.height);if(a===0||o===0)throw Error(`Element has zero dimensions`);let s=document.createElement(`canvas`),c=window.devicePixelRatio||1;s.width=a*c,s.height=o*c;let l=s.getContext(`2d`);l.scale(c,c);let u=r.cloneNode(!0),d=`<svg xmlns="http://www.w3.org/2000/svg" width="${a}" height="${o}"><foreignObject width="100%" height="100%">${new XMLSerializer().serializeToString(u)}</foreignObject></svg>`;return new Promise((e,t)=>{let n=new Image;n.onload=()=>{l.drawImage(n,0,0),e(s.toDataURL(`image/png`))},n.onerror=()=>t(Error(`Screenshot rendering failed`)),n.src=`data:image/svg+xml;charset=utf-8,`+encodeURIComponent(d)})},setState:t=>{try{localStorage.setItem(`slicc-sprinkle-state:${e}`,JSON.stringify(t))}catch{}},getState:()=>{try{let t=localStorage.getItem(`slicc-sprinkle-state:${e}`);return t?JSON.parse(t):null}catch{return null}},open:e=>{let t=/^https?:|^chrome-extension:/.test(e)?e:ym(e);window.open(t,`_blank`)},close:()=>this.closeHandler(e),stopCone:()=>this.stopConeHandler()};return t}pushUpdate(e,t){let n=`${e}:update`,r=this.listeners.get(n);if(r)for(let e of r)try{e(t)}catch{}}removeSprinkle(e){for(let t of this.listeners.keys())t.startsWith(`${e}:`)&&this.listeners.delete(t)}},Kb=n(`sprinkle-manager`),qb=`slicc-open-sprinkles`,Jb=class{fs;bridge;callbacks;availableSprinkles=new Map;watcherUnsub;openSprinkles=new Map;constructor(e,t,n,r){this.fs=e,this.bridge=new Gb(e,t,e=>this.close(e),r),this.callbacks=n}async restoreOpenSprinkles(){try{let e=localStorage.getItem(qb);if(!e){for(let e of this.availableSprinkles.values())if(e.autoOpen)try{await this.open(e.name)}catch{Kb.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{Kb.warn(`Failed to restore sprinkle`,{name:e})}}catch{}}persistOpenSprinkles(){try{localStorage.setItem(qb,JSON.stringify([...this.openSprinkles.keys()]))}catch{}}async openNewAutoOpenSprinkles(){await this.refresh();for(let e of this.availableSprinkles.values())if(e.autoOpen&&!this.openSprinkles.has(e.name))try{await this.open(e.name),Kb.info(`Auto-opened new sprinkle after install`,{name:e.name})}catch{Kb.warn(`Failed to auto-open new sprinkle`,{name:e.name})}}async refresh(){this.availableSprinkles=await Bb(this.fs),Kb.info(`Discovered sprinkles`,{count:this.availableSprinkles.size})}async open(e,t){if(this.openSprinkles.has(e)){Kb.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 ii(i,this.bridge.createAPI(e));await a.render(r,e),this.openSprinkles.get(e).renderer=a,this.persistOpenSprinkles(),bv(e),Kb.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(),Kb.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){Kb.warn(`Cannot send to closed sprinkle`,{name:e});return}this.bridge.pushUpdate(e,t),n.renderer.pushUpdate(t)}};function Yb(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function Xb(e){let t=[],{payload:n}=e;if(n.title&&t.push(`# ${n.title}`),t.push(`A new handoff was accepted from ${Yb(e.sourceUrl)}.`),t.push(`## Instruction`),t.push(n.instruction),n.urls&&n.urls.length>0){t.push(`## URLs`);for(let e of n.urls)t.push(`- ${e}`)}if(n.context&&(t.push(`## Context`),t.push(n.context)),n.acceptanceCriteria&&n.acceptanceCriteria.length>0){t.push(`## Acceptance Criteria`);for(let e of n.acceptanceCriteria)t.push(`- ${e}`)}return n.notes&&(t.push(`## Notes`),t.push(n.notes)),t.join(`
|
|
12731
12732
|
|
|
12732
|
-
`)}function Pb(e,t){return e.receivedAt.localeCompare(t.receivedAt)}var Fb=class{onPendingHandoffsChange;pendingByHandoffId=new Map;constructor(e){this.onPendingHandoffsChange=e.onPendingHandoffsChange}injectHandoff(e,t=`local`){let n=`injected-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.pendingByHandoffId.set(n,{handoffId:n,sourceUrl:t,payload:e,receivedAt:new Date().toISOString()}),this.emitChange(),n}clearHandoff(e){let t=this.pendingByHandoffId.get(e)??null;return this.pendingByHandoffId.delete(e),t&&this.emitChange(),{handoff:t,targetIds:[]}}emitChange(){this.onPendingHandoffsChange?.([...this.pendingByHandoffId.values()].sort(Pb))}},$=n(`main`),Ib=`slicc-pending-mount`,Lb=`pendingMount`;async function Rb(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(Ib,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,Lb),await new Promise(e=>n.oncomplete=()=>e()),t.close()}async function zb(e){let t;try{t=await new Promise((e,t)=>{let n=indexedDB.open(Ib,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(Lb);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)});if(r){n.objectStore(`handles`).delete(Lb),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 Bb(){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 Vb(){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 Hb(e,t,n){let r=Bb(),i=0,a=!1,o=()=>{i=0,a||r.hide()};window.addEventListener(`dragenter`,e=>{ma(e.dataTransfer)&&(e.preventDefault(),i+=1,a||r.show(`Drop .skill to install`,`Unpack into /workspace/skills/{name}.`))}),window.addEventListener(`dragover`,e=>{ma(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=ha(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 le(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 Ub(e){let{OffscreenClient:t}=await v(async()=>{let{OffscreenClient:e}=await import(`./offscreen-client-BIdj4gf1.js`);return{OffscreenClient:e}},__vite__mapDeps([22,15])),{VirtualFS:n}=await v(async()=>{let{VirtualFS:e}=await import(`./fs-BAlzVbQY.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([20,1,15])),r=new Zi(e,!0);window.__slicc_debug_tabs=e=>r.setDebugTabs(e),await r.panels.chat.initSession(`session-cone`);let i=null,a=await n.create({dbName:`slicc-fs`});r.panels.fileBrowser.setFs(a),$.info(`File browser wired to shared VFS (local IndexedDB)`);let o=new BroadcastChannel(`preview-vfs`);o.onmessage=e=>{if(e.data?.type!==`preview-vfs-read`)return;let{id:t,path:n,asText:r}=e.data;(async()=>{try{let e=r?`utf-8`:`binary`,i=await a.readFile(n,{encoding:e});o.postMessage({type:`preview-vfs-response`,id:t,content:i})}catch(e){let r=e instanceof Error?e.message:String(e);r.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:n,error:r}),o.postMessage({type:`preview-vfs-response`,id:t,error:r})}})()},Hb(a,Vb(),async()=>{await r.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await v(async()=>{let{WasmShell:e}=await import(`./shell-CEWm93pE.js`);return{WasmShell:e}},[]),{PanelCdpProxy:t,BrowserAPI:n}=await v(async()=>{let{PanelCdpProxy:e,BrowserAPI:t}=await import(`./cdp-B4yzwpE0.js`).then(e=>e.t);return{PanelCdpProxy:e,BrowserAPI:t}},__vite__mapDeps([23,1,4,15])),{fetchSecretEnvVars:i}=await v(async()=>{let{fetchSecretEnvVars:e}=await import(`./secret-env-CZ1iNnfN.js`);return{fetchSecretEnvVars:e}},[]),o=new t;await o.connect();let s=new n(o),c=await i(),l=new e({fs:a,browserAPI:s,env:Object.keys(c).length>0?c:void 0});await r.panels.terminal.mountShell(l),$.info(`Terminal mounted with shared VFS and BrowserAPI (CDP proxy)`)}catch(e){$.warn(`Failed to mount shell to terminal`,e)}{let{registerSessionCostsProvider:e}=await v(async()=>{let{registerSessionCostsProvider:e}=await import(`./cost-command-Bipyal__.js`).then(e=>e.t);return{registerSessionCostsProvider:e}},__vite__mapDeps([24,1]));e(()=>new Promise(e=>{chrome.runtime.sendMessage({source:`panel`,payload:{type:`get-session-costs`}},t=>{if(chrome.runtime.lastError||!t?.ok){e([]);return}e(t.costs??[])})}))}let c,l=new Set,u=e=>{r.setPendingHandoffCount(e.length),r.panels.chat.setPendingHandoffs(e)},d=async e=>{i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid),r.setScoopSwitcherSelected?.(e.jid),r.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=e.isCone?void 0:e.name;await r.panels.chat.switchToContext(t,!e.isCone,n),c.isProcessing(e.jid)&&r.panels.chat.setProcessing(!0)};c=new t({onStatusChange:(e,t)=>{r.panels.scoops.updateScoopStatus(e,t),r.updateScoopSwitcherStatus?.(e,t),i?.jid===e&&(r.setAgentProcessing(t===`processing`),t===`processing`?r.panels.chat.setProcessing(!0):t===`ready`&&r.panels.chat.setProcessing(!1))},onScoopCreated:e=>{r.panels.scoops.refreshScoops(),r.refreshScoopSwitcher?.(),i||(i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid))},onScoopListUpdate:()=>{let e=new Set(c.getScoops().map(e=>e.folder));for(let t of l)e.has(t)||r.panels.chat.deleteSessionById(`session-${t}`);if(l=e,r.panels.scoops.refreshScoops(),r.refreshScoopSwitcher?.(),!i){let e=c.getScoops().find(e=>e.isCone);e&&(i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid))}},onIncomingMessage:(e,t)=>{if(i?.jid===e){let e=t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content;r.panels.chat.addUserMessage(e)}},onPendingHandoffsChange:u,onReady:async()=>{try{$.info(`Offscreen engine ready, scoop count:`,c.getScoops().length),window.localStorage.getItem(`slicc.trayJoinUrl`)&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`refresh-tray-runtime`}}).catch(()=>{});let e=i??c.getScoops().find(e=>e.isCone)??c.getScoops()[0];e&&(i=e,c.selectedScoopJid=e.jid,await d(e))}catch(e){$.error(`Failed to initialize on ready`,{error:e instanceof Error?e.message:String(e)})}}}),c.setLocalFS(a);let f=c.createAgentHandle();r.panels.chat.setAgent(f),r.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=c.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await d(t),r.setActiveTab(`chat`),f.sendMessage(Nb(e),`handoff-${e.handoffId}`),c.acceptPendingHandoff(e.handoffId)},onDismiss:e=>{c.dismissPendingHandoff(e.handoffId)}}),c.requestPendingHandoffs(),r.panels.scoops.setOrchestrator(c),r.panels.memory.setOrchestrator(c),r.setScoopSwitcherOrchestrator?.(c),r.onScoopSelect=d,r.onModelChange=e=>{localStorage.setItem(`selected-model`,e),c.updateModel()},r.onClearChat=async()=>{let e=c.getScoops();for(let t of e){let e=t.isCone?`session-cone`:`session-${t.folder}`;await r.panels.chat.deleteSessionById(e)}c.clearAllMessages()},r.onClearFilesystem=async()=>{c.clearFilesystem()},r.panels.chat.onInlineSprinkleLick=(e,t)=>{c.sendSprinkleLick(`inline`,{action:e,data:t})};let p=new jb(a,async e=>{if(e.type===`sprinkle`){if(e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&a.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome completion marker`,e)),n===`shortcut-migrate`&&p.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&zb(a).catch(e=>$.warn(`Failed to mount workspace from onboarding`,e))}if(e.sprinkleName===`welcome`&&e.body?.action===`request-mount`){try{let e=window;if(!e.showDirectoryPicker)throw Error(`showDirectoryPicker not supported`);let t=await e.showDirectoryPicker({mode:`readwrite`});await Rb(t),p.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),p.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}return}c.sendSprinkleLick(e.sprinkleName,e.body)}},{addSprinkle:(e,t,n,i)=>r.addSprinkle(e,t,n,i),removeSprinkle:e=>r.removeSprinkle(e)},()=>{let e=c.getScoops().find(e=>e.isCone);e&&c.stopScoop(e.jid)});if(window.__slicc_sprinkleManager=p,window.__slicc_reloadSkills=()=>(chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}}),Promise.resolve()),c.setSprinkleOpHandler(e=>{let{id:t,op:n,name:r,data:i}=e;console.log(`[main-ext] sprinkle-op handler called`,{id:t,op:n,name:r}),(async()=>{try{let e;switch(n){case`list`:await p.refresh(),e=p.available();break;case`opened`:e=p.opened();break;case`refresh`:await p.refresh(),e=p.available().length;break;case`open`:await p.open(r),e=!0;break;case`close`:p.close(r),e=!0;break;case`send`:p.sendToSprinkle(r,i),e=!0;break;case`openNewAutoOpen`:await p.openNewAutoOpenSprinkles(),e=!0;break}console.log(`[main-ext] sprinkle-op response sending`,{id:t,op:n,result:typeof e}),chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,result:e}}).catch(()=>{})}catch(e){chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}})()}),await p.refresh(),r.onSprinkleClose=e=>p.close(e),r.getAvailableSprinkles=()=>{let e=new Set(p.opened());return p.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},r.onOpenSprinkle=(e,t)=>p.open(e,t),r.updateAddButtons(),await p.restoreOpenSprinkles(),!await a.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await a.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await a.exists(`/shared/.welcomed`)&&!s(window.localStorage)&&p.available().some(e=>e.name===`welcome`))try{await p.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}$.info(`SprinkleManager initialized (extension mode)`),c.requestState(),$.info(`Extension UI connected to offscreen agent engine`),tv().catch(()=>{})}async function Wb(){ra(),da();let e=document.getElementById(`app`);if(!e)throw Error(`#app element not found`);`serviceWorker`in navigator&&navigator.serviceWorker.register(`/preview-sw.js`,{scope:`/preview/`}).then(()=>$.info(`Preview SW registered`)).catch(e=>$.error(`Preview SW registration failed — preview feature will not work`,e)),k();let t=T(),n=s(window.localStorage);if(!t&&!n){let e=window.location.port===`5710`||window.location.port===`3000`;window.location.port===``&&window.location.pathname.includes(`/join/`)?await C({autoJoinUrl:window.location.origin+window.location.pathname}):!e&&window.location.port!==``?await C({preferTrayJoin:!0}):await C(),t=T()}let i=!t&&s(window.localStorage),a=typeof chrome<`u`&&!!chrome?.runtime?.id,c=mb(window.location.href,a);if(c===`extension`)return Ub(e);let l=new Zi(e,c===`electron-overlay`);if(c===`electron-overlay`){let e=gb(window.location.href);l.setActiveTab(e);let t=document.createElement(`style`);t.id=`slicc-electron-overlay-runtime-style`,t.textContent=`
|
|
12733
|
+
`)}function Zb(e,t){return e.receivedAt.localeCompare(t.receivedAt)}var Qb=class{onPendingHandoffsChange;pendingByHandoffId=new Map;constructor(e){this.onPendingHandoffsChange=e.onPendingHandoffsChange}injectHandoff(e,t=`local`){let n=`injected-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.pendingByHandoffId.set(n,{handoffId:n,sourceUrl:t,payload:e,receivedAt:new Date().toISOString()}),this.emitChange(),n}clearHandoff(e){let t=this.pendingByHandoffId.get(e)??null;return this.pendingByHandoffId.delete(e),t&&this.emitChange(),{handoff:t,targetIds:[]}}emitChange(){this.onPendingHandoffsChange?.([...this.pendingByHandoffId.values()].sort(Zb))}},$=n(`main`),$b=`slicc-pending-mount`,ex=`pendingMount`;async function tx(e){let t=await new Promise((e,t)=>{let n=indexedDB.open($b,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,ex),await new Promise(e=>n.oncomplete=()=>e()),t.close()}async function nx(e){let t;try{t=await new Promise((e,t)=>{let n=indexedDB.open($b,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(ex);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)});if(r){n.objectStore(`handles`).delete(ex),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 rx(){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 ix(){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 ax(e,t,n){let r=rx(),i=0,a=!1,o=()=>{i=0,a||r.hide()};window.addEventListener(`dragenter`,e=>{ma(e.dataTransfer)&&(e.preventDefault(),i+=1,a||r.show(`Drop .skill to install`,`Unpack into /workspace/skills/{name}.`))}),window.addEventListener(`dragover`,e=>{ma(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=ha(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 le(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 ox(e){let{OffscreenClient:t}=await v(async()=>{let{OffscreenClient:e}=await import(`./offscreen-client-BIdj4gf1.js`);return{OffscreenClient:e}},__vite__mapDeps([22,15])),{VirtualFS:n}=await v(async()=>{let{VirtualFS:e}=await import(`./fs-udwNbj6g.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([20,1,15])),r=new Zi(e,!0);window.__slicc_debug_tabs=e=>r.setDebugTabs(e),await r.panels.chat.initSession(`session-cone`);let i=null,a=await n.create({dbName:`slicc-fs`});r.panels.fileBrowser.setFs(a),$.info(`File browser wired to shared VFS (local IndexedDB)`);let o=new BroadcastChannel(`preview-vfs`);o.onmessage=e=>{if(e.data?.type!==`preview-vfs-read`)return;let{id:t,path:n,asText:r}=e.data;(async()=>{try{let e=r?`utf-8`:`binary`,i=await a.readFile(n,{encoding:e});o.postMessage({type:`preview-vfs-response`,id:t,content:i})}catch(e){let r=e instanceof Error?e.message:String(e);r.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:n,error:r}),o.postMessage({type:`preview-vfs-response`,id:t,error:r})}})()},ax(a,ix(),async()=>{await r.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await v(async()=>{let{WasmShell:e}=await import(`./shell-BvugiBi7.js`);return{WasmShell:e}},[]),{PanelCdpProxy:t,BrowserAPI:n}=await v(async()=>{let{PanelCdpProxy:e,BrowserAPI:t}=await import(`./cdp-B4yzwpE0.js`).then(e=>e.t);return{PanelCdpProxy:e,BrowserAPI:t}},__vite__mapDeps([23,1,4,15])),{fetchSecretEnvVars:i}=await v(async()=>{let{fetchSecretEnvVars:e}=await import(`./secret-env-C4IwrDk1.js`);return{fetchSecretEnvVars:e}},[]),o=new t;await o.connect();let s=new n(o),c=await i(),l=new e({fs:a,browserAPI:s,env:Object.keys(c).length>0?c:void 0});await r.panels.terminal.mountShell(l),$.info(`Terminal mounted with shared VFS and BrowserAPI (CDP proxy)`)}catch(e){$.warn(`Failed to mount shell to terminal`,e)}{let{registerSessionCostsProvider:e}=await v(async()=>{let{registerSessionCostsProvider:e}=await import(`./cost-command-Bipyal__.js`).then(e=>e.t);return{registerSessionCostsProvider:e}},__vite__mapDeps([24,1]));e(()=>new Promise(e=>{chrome.runtime.sendMessage({source:`panel`,payload:{type:`get-session-costs`}},t=>{if(chrome.runtime.lastError||!t?.ok){e([]);return}e(t.costs??[])})}))}let c,l=new Set,u=e=>{r.setPendingHandoffCount(e.length),r.panels.chat.setPendingHandoffs(e)},d=async e=>{i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid),r.setScoopSwitcherSelected?.(e.jid),r.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=e.isCone?void 0:e.name;await r.panels.chat.switchToContext(t,!e.isCone,n),c.isProcessing(e.jid)&&r.panels.chat.setProcessing(!0)};c=new t({onStatusChange:(e,t)=>{r.panels.scoops.updateScoopStatus(e,t),r.updateScoopSwitcherStatus?.(e,t),i?.jid===e&&(r.setAgentProcessing(t===`processing`),t===`processing`?r.panels.chat.setProcessing(!0):t===`ready`&&r.panels.chat.setProcessing(!1))},onScoopCreated:e=>{r.panels.scoops.refreshScoops(),r.refreshScoopSwitcher?.(),i||(i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid))},onScoopListUpdate:()=>{let e=new Set(c.getScoops().map(e=>e.folder));for(let t of l)e.has(t)||r.panels.chat.deleteSessionById(`session-${t}`);if(l=e,r.panels.scoops.refreshScoops(),r.refreshScoopSwitcher?.(),!i){let e=c.getScoops().find(e=>e.isCone);e&&(i=e,c.selectedScoopJid=e.jid,r.panels.memory.setSelectedScoop(e.jid))}},onIncomingMessage:(e,t)=>{if(i?.jid===e){let e=t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content;r.panels.chat.addUserMessage(e)}},onPendingHandoffsChange:u,onReady:async()=>{try{$.info(`Offscreen engine ready, scoop count:`,c.getScoops().length),window.localStorage.getItem(`slicc.trayJoinUrl`)&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`refresh-tray-runtime`}}).catch(()=>{});let e=i??c.getScoops().find(e=>e.isCone)??c.getScoops()[0];e&&(i=e,c.selectedScoopJid=e.jid,await d(e))}catch(e){$.error(`Failed to initialize on ready`,{error:e instanceof Error?e.message:String(e)})}}}),c.setLocalFS(a);let f=c.createAgentHandle();r.panels.chat.setAgent(f),r.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=c.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await d(t),r.setActiveTab(`chat`),f.sendMessage(Xb(e),`handoff-${e.handoffId}`),c.acceptPendingHandoff(e.handoffId)},onDismiss:e=>{c.dismissPendingHandoff(e.handoffId)}}),c.requestPendingHandoffs(),r.panels.scoops.setOrchestrator(c),r.panels.memory.setOrchestrator(c),r.setScoopSwitcherOrchestrator?.(c),r.onScoopSelect=d,r.onModelChange=e=>{localStorage.setItem(`selected-model`,e),c.updateModel()},r.onClearChat=async()=>{let e=c.getScoops();for(let t of e){let e=t.isCone?`session-cone`:`session-${t.folder}`;await r.panels.chat.deleteSessionById(e)}c.clearAllMessages()},r.onClearFilesystem=async()=>{c.clearFilesystem()},r.panels.chat.onInlineSprinkleLick=(e,t)=>{c.sendSprinkleLick(`inline`,{action:e,data:t})};let p=new Jb(a,async e=>{if(e.type===`sprinkle`){if(e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&a.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome completion marker`,e)),n===`shortcut-migrate`&&p.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&nx(a).catch(e=>$.warn(`Failed to mount workspace from onboarding`,e))}if(e.sprinkleName===`welcome`&&e.body?.action===`request-mount`){try{let e=window;if(!e.showDirectoryPicker)throw Error(`showDirectoryPicker not supported`);let t=await e.showDirectoryPicker({mode:`readwrite`});await tx(t),p.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),p.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}return}c.sendSprinkleLick(e.sprinkleName,e.body)}},{addSprinkle:(e,t,n,i)=>r.addSprinkle(e,t,n,i),removeSprinkle:e=>r.removeSprinkle(e)},()=>{let e=c.getScoops().find(e=>e.isCone);e&&c.stopScoop(e.jid)});if(window.__slicc_sprinkleManager=p,window.__slicc_reloadSkills=()=>(chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}}),Promise.resolve()),c.setSprinkleOpHandler(e=>{let{id:t,op:n,name:r,data:i}=e;console.log(`[main-ext] sprinkle-op handler called`,{id:t,op:n,name:r}),(async()=>{try{let e;switch(n){case`list`:await p.refresh(),e=p.available();break;case`opened`:e=p.opened();break;case`refresh`:await p.refresh(),e=p.available().length;break;case`open`:await p.open(r),e=!0;break;case`close`:p.close(r),e=!0;break;case`send`:p.sendToSprinkle(r,i),e=!0;break;case`openNewAutoOpen`:await p.openNewAutoOpenSprinkles(),e=!0;break}console.log(`[main-ext] sprinkle-op response sending`,{id:t,op:n,result:typeof e}),chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,result:e}}).catch(()=>{})}catch(e){chrome.runtime.sendMessage({source:`panel`,payload:{type:`sprinkle-op-response`,id:t,error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}})()}),await p.refresh(),r.onSprinkleClose=e=>p.close(e),r.getAvailableSprinkles=()=>{let e=new Set(p.opened());return p.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},r.onOpenSprinkle=(e,t)=>p.open(e,t),r.updateAddButtons(),await p.restoreOpenSprinkles(),!await a.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await a.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await a.exists(`/shared/.welcomed`)&&!s(window.localStorage)&&p.available().some(e=>e.name===`welcome`))try{await p.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}$.info(`SprinkleManager initialized (extension mode)`),c.requestState(),$.info(`Extension UI connected to offscreen agent engine`),_v().catch(()=>{})}async function sx(){ra(),da();let e=document.getElementById(`app`);if(!e)throw Error(`#app element not found`);`serviceWorker`in navigator&&navigator.serviceWorker.register(`/preview-sw.js`,{scope:`/preview/`}).then(()=>$.info(`Preview SW registered`)).catch(e=>$.error(`Preview SW registration failed — preview feature will not work`,e)),k();let t=T(),n=s(window.localStorage);if(!t&&!n){let e=window.location.port===`5710`||window.location.port===`3000`;window.location.port===``&&window.location.pathname.includes(`/join/`)?await C({autoJoinUrl:window.location.origin+window.location.pathname}):!e&&window.location.port!==``?await C({preferTrayJoin:!0}):await C(),t=T()}let i=!t&&s(window.localStorage),a=typeof chrome<`u`&&!!chrome?.runtime?.id,c=jb(window.location.href,a);if(c===`extension`)return ox(e);let l=new Zi(e,c===`electron-overlay`);if(c===`electron-overlay`){let e=Nb(window.location.href);l.setActiveTab(e);let t=document.createElement(`style`);t.id=`slicc-electron-overlay-runtime-style`,t.textContent=`
|
|
12733
12734
|
#app > .tab-bar { display: none !important; }
|
|
12734
12735
|
#app > .tab-content {
|
|
12735
12736
|
height: calc(100vh - var(--s2-header-height));
|
|
@@ -12737,4 +12738,4 @@ ${t}
|
|
|
12737
12738
|
#app > .tab-content > .tab-content__panel {
|
|
12738
12739
|
height: 100%;
|
|
12739
12740
|
}
|
|
12740
|
-
`,document.head.appendChild(t),window.addEventListener(`message`,e=>{e.source===window.parent&&xb(e.data)&&l.setActiveTab(gb(`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=Vb();await l.panels.chat.initSession(`session-cone`),$.info(`Session initialized`);let f=new be,p=e=>{l.setPendingHandoffCount(e.length),l.panels.chat.setPendingHandoffs(e)},m=new Set,g=e=>{$.debug(`Emit to UI`,{type:e.type,listenerCount:m.size});for(let t of m)try{t(e)}catch(t){$.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}},_=null,y=new Map,b=new Map;function x(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function S(e){let t=b.get(e);return t||(t=[],b.set(e,t)),t}function w(e,t){let n=S(e),r=y.get(e);if(r){let e=n.find(e=>e.id===r);if(e)return e}r=`scoop-${e}-${x()}`,y.set(e,r);let i=E.getScoops().find(t=>t.jid===e),a=i?.isCone?`cone`:i?.name??`unknown`,o={id:r,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:a,channel:t};return n.push(o),_?.jid===e&&g({type:`message_start`,messageId:r}),o}let E=new xy(l.getIframeContainer(),{onResponse:(e,t,n)=>{let r=w(e);n?r.content+=t:(r.content=t,r.isStreaming=!1),_?.jid===e&&(g({type:`content_delta`,messageId:r.id,text:t}),n||g({type:`content_done`,messageId:r.id}))},onResponseDone:e=>{let t=S(e),n=y.get(e);if(n){let r=t.find(e=>e.id===n);r&&(r.isStreaming=!1),_?.jid===e&&g({type:`content_done`,messageId:n}),y.delete(e)}},onSendMessage:(e,t)=>{$.debug(`Send message requested`,{targetJid:e,textLength:t.length});let n=`msg-${x()}`,r={id:n,chatJid:e,senderId:`assistant`,senderName:`sliccy`,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`web`};E.handleMessage(r),S(e).push({id:n,role:`assistant`,content:t,timestamp:Date.now()}),_?.jid===e&&(g({type:`message_start`,messageId:n}),g({type:`content_delta`,messageId:n,text:t}),g({type:`content_done`,messageId:n}))},onStatusChange:(e,t)=>{if(l.panels.scoops.updateScoopStatus(e,t),l.updateScoopSwitcherStatus?.(e,t),_?.jid===e){if(l.setAgentProcessing(t===`processing`),t===`processing`)l.panels.chat.setProcessing(!0);else if(t===`ready`){l.panels.chat.setProcessing(!1);let t=y.get(e)??`done-${e}-${x()}`;y.delete(e),g({type:`turn_end`,messageId:t})}}},onError:(e,t)=>{$.error(`Scoop error`,{scoopJid:e,error:t}),_?.jid===e&&g({type:`error`,error:t})},getBrowserAPI:()=>f,onToolStart:(e,t,n)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let r=w(e);r.toolCalls||=[],r.toolCalls.push({id:x(),name:t,input:n}),_?.jid===e&&g({type:`tool_use_start`,messageId:r.id,toolName:t,toolInput:n})},onToolEnd:(e,t,n,r)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let i=S(e),a=y.get(e);if(a){let e=i.find(e=>e.id===a);if(e?.toolCalls){let i=[...e.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);i&&(i.result=n,i.isError=r)}}_?.jid===e&&a&&g({type:`tool_result`,messageId:a,toolName:t,result:n,isError:r})},onToolUI:(e,t,n,r)=>{let i=y.get(e);i?g({type:`tool_ui`,messageId:i,toolName:t,requestId:n,html:r}):$.warn(`Cannot emit tool_ui - no message ID for scoop`,{scoopJid:e,requestId:n})},onToolUIDone:(e,t)=>{let n=y.get(e);n&&g({type:`tool_ui_done`,messageId:n,requestId:t})},onIncomingMessage:(e,t)=>{let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel};S(e).push(n),_?.jid===e&&(g({type:`message_start`,messageId:t.id}),g({type:`content_delta`,messageId:t.id,text:n.content}),g({type:`content_done`,messageId:t.id}))}});await E.init(),l.panels.scoops.setOrchestrator(E),l.panels.memory.setOrchestrator(E),l.setScoopSwitcherOrchestrator?.(E);let D=E.getSharedFS();if(D){l.panels.fileBrowser.setFs(D),$.info(`File browser wired to shared VFS`);let e=new BroadcastChannel(`preview-vfs`);e.onmessage=t=>{if(t.data?.type!==`preview-vfs-read`)return;let{id:n,path:r,asText:i}=t.data;(async()=>{try{let t=i?`utf-8`:`binary`,a=await D.readFile(r,{encoding:t});e.postMessage({type:`preview-vfs-response`,id:n,content:a})}catch(t){let i=t instanceof Error?t.message:String(t);i.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:r,error:i}),e.postMessage({type:`preview-vfs-response`,id:n,error:i})}})()},Hb(D,(e,t)=>{t===`error`?$.warn(`Dropped skill install failed`,{message:e}):$.info(`Dropped skill installed`,{message:e}),d(e,t)},async()=>{await l.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await v(async()=>{let{WasmShell:e}=await import(`./shell-CEWm93pE.js`);return{WasmShell:e}},[]),{fetchSecretEnvVars:t}=await v(async()=>{let{fetchSecretEnvVars:e}=await import(`./secret-env-CZ1iNnfN.js`);return{fetchSecretEnvVars:e}},[]),n=await t(),r=new e({fs:D,browserAPI:f,env:Object.keys(n).length>0?n:void 0});await l.panels.terminal.mountShell(r),$.info(`Terminal mounted with shared VFS`);try{let{BshWatchdog:e}=await v(async()=>{let{BshWatchdog:e}=await import(`./bsh-watchdog-Dfc2Sii6.js`);return{BshWatchdog:e}},__vite__mapDeps([25,15])),t=new e({browserAPI:f,fs:D});t.start(),window.addEventListener(`beforeunload`,()=>t.stop(),{once:!0}),$.info(`BSH navigation watchdog started`)}catch(e){$.warn(`Failed to start BSH watchdog`,e)}}catch(e){$.warn(`Failed to mount shell to terminal`,e)}}let O=E.getScoops(),ee=O.some(e=>e.isCone);if(i)$.info(`Skipping local cone bootstrap while joining a tray without a configured provider`);else if(!ee)_=await l.panels.scoops.createScoop(`Cone`,!0),$.info(`Created cone`);else{let e=new URLSearchParams(window.location.search).get(`scoop`);if(e){let t=O.find(t=>t.folder===e);t?(_=t,$.info(`Restored scoop from URL`,{folder:e})):_=O.find(e=>e.isCone)??O[0]}else _=O.find(e=>e.isCone)??O[0]}_&&l.panels.memory.setSelectedScoop(_.jid);let A=null,j=null,te={sendMessage(e,t){if(!_){g({type:`error`,error:`No scoop selected`});return}let n={id:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:_.jid,senderId:`user`,senderName:`User`,content:e,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`};S(_.jid).push({id:n.id,role:`user`,content:e,timestamp:Date.now()}),A?.broadcastUserMessage(e,n.id),E.handleMessage(n),E.createScoopTab(_.jid)},onEvent(e){return m.add(e),()=>m.delete(e)},stop(){_&&(E.stopScoop(_.jid),E.clearQueuedMessages(_.jid).catch(e=>{$.error(`Failed to clear queued messages on stop`,{error:e instanceof Error?e.message:String(e)})}))}};l.panels.chat.setAgent(te),l.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=E.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await P(t),l.setActiveTab(`chat`),te.sendMessage(Nb(e),`handoff-${e.handoffId}`);let n=j?.clearHandoff(e.handoffId);n&&await Promise.allSettled(n.targetIds.map(e=>f.closePage(e)))},onDismiss:async e=>{let t=j?.clearHandoff(e.handoffId);t&&await Promise.allSettled(t.targetIds.map(e=>f.closePage(e)))}}),l.panels.chat.setDeleteQueuedMessageCallback(e=>{if(_){E.deleteQueuedMessage(_.jid,e).catch(t=>{$.error(`Failed to delete queued message`,{messageId:e,error:t instanceof Error?t.message:String(t)})});let t=b.get(_.jid);if(t){let n=t.findIndex(t=>t.id===e);n!==-1&&t.splice(n,1)}}}),$.info(`Cone agent handle wired to chat UI`);let{getLickManager:ne}=await v(async()=>{let{getLickManager:e}=await import(`./lick-manager-CjiK3pMV.js`);return{getLickManager:e}},[]),re=ne();await re.init(),E.setLickManager(re);let ie=e=>{let t=e.type===`webhook`,n=e.type===`sprinkle`,r=e.type===`fswatch`,i=t?e.webhookName:n?e.sprinkleName:r?e.fswatchName:e.cronName,a=t?e.webhookId:n?e.sprinkleName:r?e.fswatchId:e.cronId,o=e.type;if($.debug(`Lick event`,{type:e.type,name:i,targetScoop:e.targetScoop}),n&&e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&D?.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome marker`,e)),n===`shortcut-migrate`&&M?.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&D&&zb(D).catch(e=>$.warn(`Failed to mount workspace from onboarding`,e))}if(n&&e.sprinkleName===`welcome`&&e.body?.action===`request-mount`){(async()=>{try{let e=window;if(!e.showDirectoryPicker)throw Error(`showDirectoryPicker not supported`);let t=await e.showDirectoryPicker({mode:`readwrite`});await Rb(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 s=E.getScoops(),c;if(c=n||!e.targetScoop?s.find(e=>e.isCone):s.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`),c){let s=`${o}-${a}-${Date.now()}`,u=`[${t?`Webhook Event`:n?`Sprinkle Event`:r?`File Watch Event`:`Cron Event`}: ${i}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``,d={id:s,chatJid:c.jid,senderId:o,senderName:`${o}:${i}`,content:u,timestamp:e.timestamp,fromAssistant:!1,channel:o};S(c.jid).push({id:s,role:`user`,content:u,timestamp:Date.now(),source:`lick`,channel:o}),_?.jid===c.jid&&l.panels.chat.addLickMessage(s,u,o),$.info(`Routing lick to scoop`,{type:o,name:i,scoopJid:c.jid}),E.handleMessage(d)}else $.warn(`Lick target scoop not found`,{targetScoop:e.targetScoop})};re.setEventHandler(ie),l.panels.chat.onInlineSprinkleLick=(e,t)=>{ie({type:`sprinkle`,sprinkleName:`inline`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:e,data:t}})};let M=null;if(D){if(M=new jb(D,ie,{addSprinkle:(e,t,n,r)=>l.addSprinkle(e,t,n,r),removeSprinkle:e=>l.removeSprinkle(e)},()=>{let e=E.getScoops().find(e=>e.isCone);e&&(E.stopScoop(e.jid),E.clearQueuedMessages(e.jid).catch(e=>{$.error(`Failed to clear queued messages on sprinkle stopCone`,{error:e instanceof Error?e.message:String(e)})}))}),window.__slicc_sprinkleManager=M,window.__slicc_reloadSkills=()=>E.reloadAllSkills(),await M.refresh(),l.onSprinkleClose=e=>M.close(e),l.getAvailableSprinkles=()=>{let e=new Set(M.opened());return M.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},l.onOpenSprinkle=(e,t)=>M.open(e,t),l.updateAddButtons(),!await D.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await D.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await D.exists(`/shared/.welcomed`)&&!i&&M.available().some(e=>e.name===`welcome`))try{await M.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}await M.restoreOpenSprinkles(),$.info(`SprinkleManager initialized`)}let N=()=>{let e=vb(window.location.href),t=new WebSocket(e);t.onopen=()=>{$.info(`Lick WebSocket connected`)},t.onmessage=async e=>{try{let n=JSON.parse(e.data);if(n.requestId){let e;try{switch(n.type){case`list_webhooks`:e={type:`response`,requestId:n.requestId,data:re.listWebhooks()};break;case`create_webhook`:{let t=await re.createWebhook(n.name||`default`,n.scoop,n.filter),r=Pp().session,i=r?.webhookUrl?bb(r.webhookUrl,t.id):yb(window.location.href,t.id);e={type:`response`,requestId:n.requestId,data:{...t,url:i}};break}case`delete_webhook`:e=await re.deleteWebhook(n.id)?{type:`response`,requestId:n.requestId,data:{ok:!0}}:{type:`response`,requestId:n.requestId,data:{error:`Webhook not found`}};break;case`list_crontasks`:e={type:`response`,requestId:n.requestId,data:re.listCronTasks()};break;case`create_crontask`:{if(!n.name)throw Error(`name is required`);if(!n.cron)throw Error(`cron is required`);let t=await re.createCronTask(n.name,n.cron,n.scoop,n.filter);e={type:`response`,requestId:n.requestId,data:t};break}case`delete_crontask`:e=await re.deleteCronTask(n.id)?{type:`response`,requestId:n.requestId,data:{ok:!0}}:{type:`response`,requestId:n.requestId,data:{error:`Cron task not found`}};break;case`tray_status`:{let t=Pp();e={type:`response`,requestId:n.requestId,data:{state:t.state,joinUrl:t.session?.joinUrl??null,workerBaseUrl:t.session?.workerBaseUrl??null,trayId:t.session?.trayId??null}};break}default:e={type:`response`,requestId:n.requestId,error:`Unknown request type: ${n.type}`}}}catch(t){e={type:`response`,requestId:n.requestId,error:t instanceof Error?t.message:String(t)}}t.send(JSON.stringify(e));return}n.type===`webhook_event`&&re.handleWebhookEvent(n.webhookId,n.headers,n.body),n.type===`handoff_event`&&j&&j.injectHandoff(n.payload,n.sourceUrl)}catch(e){$.error(`Failed to process lick message`,{error:e instanceof Error?e.message:String(e)})}},t.onclose=()=>{$.warn(`Lick WebSocket disconnected, reconnecting in 3s...`),setTimeout(N,3e3)},t.onerror=e=>{$.error(`Lick WebSocket error`,{error:String(e)})}};N(),l.onModelChange=e=>{localStorage.setItem(`selected-model`,e),E.updateModel()},l.onClearChat=async()=>{await E.clearAllMessages(),b.clear()},l.onClearFilesystem=async()=>{await E.resetFilesystem()};let P=async e=>{$.info(`Scoop selected`,{jid:e.jid,name:e.name}),_=e,E.createScoopTab(e.jid),l.panels.memory.setSelectedScoop(e.jid),l.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=b.get(e.jid),r=e.isCone?void 0:e.name;if(n&&n.length>0)await l.panels.chat.switchToContext(t,!e.isCone,r),l.panels.chat.loadMessages(n);else if(await l.panels.chat.switchToContext(t,!e.isCone,r),l.panels.chat.getMessages().length===0){let t=await E.getMessagesForScoop(e.jid);for(let n of t){let t=n.channel===`webhook`||n.channel===`cron`,r=n.channel===`delegation`;if(t){let t={id:n.id,role:`user`,content:n.content,timestamp:new Date(n.timestamp).getTime(),source:`lick`,channel:n.channel};S(e.jid).push(t),l.panels.chat.addUserMessage(n.content)}else if(r){let t={id:n.id,role:`user`,content:`**[Instructions from sliccy]**\n\n${n.content}`,timestamp:new Date(n.timestamp).getTime(),source:`delegation`,channel:`delegation`};S(e.jid).push(t),l.panels.chat.addUserMessage(t.content)}else n.fromAssistant?(g({type:`message_start`,messageId:n.id}),g({type:`content_delta`,messageId:n.id,text:n.content}),g({type:`content_done`,messageId:n.id})):l.panels.chat.addUserMessage(n.content)}}e.isCone&&E.isProcessing(e.jid)&&l.panels.chat.setProcessing(!0)};if(l.onScoopSelect=P,_&&(E.createScoopTab(_.jid),await P(_)),j=new Fb({onPendingHandoffsChange:p}),c===`standalone`||c===`electron-overlay`){let e=await r(),t=hb(c,e!==null)?o:null,n=await h({locationHref:window.location.href,storage:window.localStorage,envBaseUrl:null,defaultWorkerBaseUrl:t,runtimeConfigFetcher:async()=>e}),i=null,a=null,s=null;Nh(()=>A?(e,t)=>A.sendFsRequest(e,t):i?(e,t)=>i.sendFsRequest(e,t):null),Of(()=>A?()=>A.getBestFollowerForTeleport():null),kf(()=>A?()=>A.getConnectedFollowers():null);let d=e=>{s&&=(clearInterval(s),null),i?.close();let t=`follower-${e.bootstrapId}`,n=new pb(e.channel,{browserTransport:f.getTransport(),browserAPI:f,onSnapshot:e=>{l.panels.chat.loadMessages(e)},onUserMessage:e=>{l.panels.chat.addUserMessage(e)},onStatus:e=>{l.panels.chat.setProcessing(e===`processing`)},onTargetsChanged:()=>void r()});i=n,f.setTrayTargetProvider(n),l.panels.chat.setAgent(n),n.requestSnapshot();let r=async()=>{try{let e=await f.listPages();n.advertiseTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})),t)}catch{}};s=setInterval(r,5e3),r(),$.info(`Follower sync wired to chat panel`,{trayId:e.trayId})},p=e=>{a?.cancel(),s&&=(clearInterval(s),null),i?.close(),i=null,a=Vy({joinUrl:e,runtime:`slicc-standalone`,fetchImpl:Hp()},{onConnected:e=>d(e),onReconnecting:e=>{$.info(`Follower reconnecting`,{attempt:e})},onGaveUp:e=>{$.warn(`Follower reconnect gave up`,{lastError:e})}})};if(window.addEventListener(`slicc:tray-join`,(e=>{p(e.detail.joinUrl)})),window.addEventListener(`beforeunload`,()=>{s&&clearInterval(s),i?.close(),a?.cancel()},{once:!0}),n?.joinUrl)p(n.joinUrl);else if(n?.workerBaseUrl){let e,t,r,i,a=()=>{t=new db({browserTransport:f.getTransport(),browserAPI:f,getMessages:()=>l.panels.chat.getMessages(),getScoopJid:()=>_?.jid??`cone`,onFollowerMessage:(e,t)=>{l.panels.chat.addUserMessage(e),te.sendMessage(e,t)},onFollowerAbort:()=>{te.stop()}}),A=t,Wp(()=>t.getConnectedFollowers()),f.setTrayTargetProvider(t),i&&clearInterval(i);let n=async()=>{try{let e=await f.listPages();t.setLocalTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})))}catch{}};i=setInterval(n,5e3),n(),r=new zy({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 Rp({workerBaseUrl:n.workerBaseUrl,runtime:`slicc-standalone`,fetchImpl:Hp(),onControlMessage:e=>{if(e.type===`webhook.event`){re.handleWebhookEvent(e.webhookId,e.headers,e.body);return}r.handleControlMessage(e).catch(e=>{$.warn(`Tray leader bootstrap handling failed`,{error:e instanceof Error?e.message:String(e)})})}}),qp(async()=>{t.stop(),r.stop(),e.stop(),await e.clearSession();let n=await e.start(),i=u(window.location.href,n.workerBaseUrl,n.trayId);return i!==window.location.href&&window.history.replaceState(window.history.state,``,i),a(),Pp()}),e.start().then(e=>{let t=u(window.location.href,e.workerBaseUrl,e.trayId);t!==window.location.href&&window.history.replaceState(window.history.state,``,t)}).catch(e=>{$.warn(`Leader tray join failed`,{error:e instanceof Error?e.message:String(e)})}),window.addEventListener(`beforeunload`,()=>{clearInterval(i),t.stop(),r.stop(),e.stop()},{once:!0})}}$.info(`Orchestrator initialized — cone+scoops ready`,{scoopCount:E.getScoops().length}),tv().catch(()=>{})}Wb().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{pv as a,oi as c,ly as i,ri as l,_y as n,Ca as o,yy as r,ii as s,gy as t};
|
|
12741
|
+
`,document.head.appendChild(t),window.addEventListener(`message`,e=>{e.source===window.parent&&Rb(e.data)&&l.setActiveTab(Nb(`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=ix();await l.panels.chat.initSession(`session-cone`),$.info(`Session initialized`);let f=new be,p=e=>{l.setPendingHandoffCount(e.length),l.panels.chat.setPendingHandoffs(e)},m=new Set,g=e=>{$.debug(`Emit to UI`,{type:e.type,listenerCount:m.size});for(let t of m)try{t(e)}catch(t){$.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}},_=null,y=new Map,b=new Map;function x(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function S(e){let t=b.get(e);return t||(t=[],b.set(e,t)),t}function w(e,t){let n=S(e),r=y.get(e);if(r){let e=n.find(e=>e.id===r);if(e)return e}r=`scoop-${e}-${x()}`,y.set(e,r);let i=E.getScoops().find(t=>t.jid===e),a=i?.isCone?`cone`:i?.name??`unknown`,o={id:r,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:a,channel:t};return n.push(o),_?.jid===e&&g({type:`message_start`,messageId:r}),o}let E=new Ry(l.getIframeContainer(),{onResponse:(e,t,n)=>{let r=w(e);n?r.content+=t:(r.content=t,r.isStreaming=!1),_?.jid===e&&(g({type:`content_delta`,messageId:r.id,text:t}),n||g({type:`content_done`,messageId:r.id}))},onResponseDone:e=>{let t=S(e),n=y.get(e);if(n){let r=t.find(e=>e.id===n);r&&(r.isStreaming=!1),_?.jid===e&&g({type:`content_done`,messageId:n}),y.delete(e)}},onSendMessage:(e,t)=>{$.debug(`Send message requested`,{targetJid:e,textLength:t.length});let n=`msg-${x()}`,r={id:n,chatJid:e,senderId:`assistant`,senderName:`sliccy`,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`web`};E.handleMessage(r),S(e).push({id:n,role:`assistant`,content:t,timestamp:Date.now()}),_?.jid===e&&(g({type:`message_start`,messageId:n}),g({type:`content_delta`,messageId:n,text:t}),g({type:`content_done`,messageId:n}))},onStatusChange:(e,t)=>{if(l.panels.scoops.updateScoopStatus(e,t),l.updateScoopSwitcherStatus?.(e,t),_?.jid===e){if(l.setAgentProcessing(t===`processing`),t===`processing`)l.panels.chat.setProcessing(!0);else if(t===`ready`){l.panels.chat.setProcessing(!1);let t=y.get(e)??`done-${e}-${x()}`;y.delete(e),g({type:`turn_end`,messageId:t})}}},onError:(e,t)=>{$.error(`Scoop error`,{scoopJid:e,error:t}),_?.jid===e&&g({type:`error`,error:t})},getBrowserAPI:()=>f,onToolStart:(e,t,n)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let r=w(e);r.toolCalls||=[],r.toolCalls.push({id:x(),name:t,input:n}),_?.jid===e&&g({type:`tool_use_start`,messageId:r.id,toolName:t,toolInput:n})},onToolEnd:(e,t,n,r)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let i=S(e),a=y.get(e);if(a){let e=i.find(e=>e.id===a);if(e?.toolCalls){let i=[...e.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);i&&(i.result=n,i.isError=r)}}_?.jid===e&&a&&g({type:`tool_result`,messageId:a,toolName:t,result:n,isError:r})},onToolUI:(e,t,n,r)=>{let i=y.get(e);i?g({type:`tool_ui`,messageId:i,toolName:t,requestId:n,html:r}):$.warn(`Cannot emit tool_ui - no message ID for scoop`,{scoopJid:e,requestId:n})},onToolUIDone:(e,t)=>{let n=y.get(e);n&&g({type:`tool_ui_done`,messageId:n,requestId:t})},onIncomingMessage:(e,t)=>{let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel};S(e).push(n),_?.jid===e&&(g({type:`message_start`,messageId:t.id}),g({type:`content_delta`,messageId:t.id,text:n.content}),g({type:`content_done`,messageId:t.id}))}});await E.init(),l.panels.scoops.setOrchestrator(E),l.panels.memory.setOrchestrator(E),l.setScoopSwitcherOrchestrator?.(E);let D=E.getSharedFS();if(D){l.panels.fileBrowser.setFs(D),$.info(`File browser wired to shared VFS`);let e=new BroadcastChannel(`preview-vfs`);e.onmessage=t=>{if(t.data?.type!==`preview-vfs-read`)return;let{id:n,path:r,asText:i}=t.data;(async()=>{try{let t=i?`utf-8`:`binary`,a=await D.readFile(r,{encoding:t});e.postMessage({type:`preview-vfs-response`,id:n,content:a})}catch(t){let i=t instanceof Error?t.message:String(t);i.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:r,error:i}),e.postMessage({type:`preview-vfs-response`,id:n,error:i})}})()},ax(D,(e,t)=>{t===`error`?$.warn(`Dropped skill install failed`,{message:e}):$.info(`Dropped skill installed`,{message:e}),d(e,t)},async()=>{await l.panels.fileBrowser.refresh()});try{let{WasmShell:e}=await v(async()=>{let{WasmShell:e}=await import(`./shell-BvugiBi7.js`);return{WasmShell:e}},[]),{fetchSecretEnvVars:t}=await v(async()=>{let{fetchSecretEnvVars:e}=await import(`./secret-env-C4IwrDk1.js`);return{fetchSecretEnvVars:e}},[]),n=await t(),r=new e({fs:D,browserAPI:f,env:Object.keys(n).length>0?n:void 0});await l.panels.terminal.mountShell(r),$.info(`Terminal mounted with shared VFS`);try{let{BshWatchdog:e}=await v(async()=>{let{BshWatchdog:e}=await import(`./bsh-watchdog-BaiyTJC8.js`);return{BshWatchdog:e}},__vite__mapDeps([25,15])),t=new e({browserAPI:f,scriptCatalog:r.getScriptCatalog(),fs:D});t.start(),window.addEventListener(`beforeunload`,()=>t.stop(),{once:!0}),$.info(`BSH navigation watchdog started`)}catch(e){$.warn(`Failed to start BSH watchdog`,e)}}catch(e){$.warn(`Failed to mount shell to terminal`,e)}}let O=E.getScoops(),ee=O.some(e=>e.isCone);if(i)$.info(`Skipping local cone bootstrap while joining a tray without a configured provider`);else if(!ee)_=await l.panels.scoops.createScoop(`Cone`,!0),$.info(`Created cone`);else{let e=new URLSearchParams(window.location.search).get(`scoop`);if(e){let t=O.find(t=>t.folder===e);t?(_=t,$.info(`Restored scoop from URL`,{folder:e})):_=O.find(e=>e.isCone)??O[0]}else _=O.find(e=>e.isCone)??O[0]}_&&l.panels.memory.setSelectedScoop(_.jid);let A=null,j=null,te={sendMessage(e,t){if(!_){g({type:`error`,error:`No scoop selected`});return}let n={id:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:_.jid,senderId:`user`,senderName:`User`,content:e,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`};S(_.jid).push({id:n.id,role:`user`,content:e,timestamp:Date.now()}),A?.broadcastUserMessage(e,n.id),E.handleMessage(n),E.createScoopTab(_.jid)},onEvent(e){return m.add(e),()=>m.delete(e)},stop(){_&&(E.stopScoop(_.jid),E.clearQueuedMessages(_.jid).catch(e=>{$.error(`Failed to clear queued messages on stop`,{error:e instanceof Error?e.message:String(e)})}))}};l.panels.chat.setAgent(te),l.panels.chat.setPendingHandoffActions({onAccept:async e=>{let t=E.getScoops().find(e=>e.isCone);if(!t){$.warn(`Cannot accept handoff without a cone scoop`,{handoffId:e.handoffId});return}await P(t),l.setActiveTab(`chat`),te.sendMessage(Xb(e),`handoff-${e.handoffId}`);let n=j?.clearHandoff(e.handoffId);n&&await Promise.allSettled(n.targetIds.map(e=>f.closePage(e)))},onDismiss:async e=>{let t=j?.clearHandoff(e.handoffId);t&&await Promise.allSettled(t.targetIds.map(e=>f.closePage(e)))}}),l.panels.chat.setDeleteQueuedMessageCallback(e=>{if(_){E.deleteQueuedMessage(_.jid,e).catch(t=>{$.error(`Failed to delete queued message`,{messageId:e,error:t instanceof Error?t.message:String(t)})});let t=b.get(_.jid);if(t){let n=t.findIndex(t=>t.id===e);n!==-1&&t.splice(n,1)}}}),$.info(`Cone agent handle wired to chat UI`);let{getLickManager:ne}=await v(async()=>{let{getLickManager:e}=await import(`./lick-manager-SqoZzrt5.js`);return{getLickManager:e}},[]),re=ne();await re.init(),E.setLickManager(re);let ie=e=>{let t=e.type===`webhook`,n=e.type===`sprinkle`,r=e.type===`fswatch`,i=t?e.webhookName:n?e.sprinkleName:r?e.fswatchName:e.cronName,a=t?e.webhookId:n?e.sprinkleName:r?e.fswatchId:e.cronId,o=e.type;if($.debug(`Lick event`,{type:e.type,name:i,targetScoop:e.targetScoop}),n&&e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&D?.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome marker`,e)),n===`shortcut-migrate`&&M?.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&D&&nx(D).catch(e=>$.warn(`Failed to mount workspace from onboarding`,e))}if(n&&e.sprinkleName===`welcome`&&e.body?.action===`request-mount`){(async()=>{try{let e=window;if(!e.showDirectoryPicker)throw Error(`showDirectoryPicker not supported`);let t=await e.showDirectoryPicker({mode:`readwrite`});await tx(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 s=E.getScoops(),c;if(c=n||!e.targetScoop?s.find(e=>e.isCone):s.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`),c){let s=`${o}-${a}-${Date.now()}`,u=`[${t?`Webhook Event`:n?`Sprinkle Event`:r?`File Watch Event`:`Cron Event`}: ${i}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``,d={id:s,chatJid:c.jid,senderId:o,senderName:`${o}:${i}`,content:u,timestamp:e.timestamp,fromAssistant:!1,channel:o};S(c.jid).push({id:s,role:`user`,content:u,timestamp:Date.now(),source:`lick`,channel:o}),_?.jid===c.jid&&l.panels.chat.addLickMessage(s,u,o),$.info(`Routing lick to scoop`,{type:o,name:i,scoopJid:c.jid}),E.handleMessage(d)}else $.warn(`Lick target scoop not found`,{targetScoop:e.targetScoop})};re.setEventHandler(ie),l.panels.chat.onInlineSprinkleLick=(e,t)=>{ie({type:`sprinkle`,sprinkleName:`inline`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:e,data:t}})};let M=null;if(D){if(M=new Jb(D,ie,{addSprinkle:(e,t,n,r)=>l.addSprinkle(e,t,n,r),removeSprinkle:e=>l.removeSprinkle(e)},()=>{let e=E.getScoops().find(e=>e.isCone);e&&(E.stopScoop(e.jid),E.clearQueuedMessages(e.jid).catch(e=>{$.error(`Failed to clear queued messages on sprinkle stopCone`,{error:e instanceof Error?e.message:String(e)})}))}),window.__slicc_sprinkleManager=M,window.__slicc_reloadSkills=()=>E.reloadAllSkills(),await M.refresh(),l.onSprinkleClose=e=>M.close(e),l.getAvailableSprinkles=()=>{let e=new Set(M.opened());return M.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},l.onOpenSprinkle=(e,t)=>M.open(e,t),l.updateAddButtons(),!await D.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await D.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await D.exists(`/shared/.welcomed`)&&!i&&M.available().some(e=>e.name===`welcome`))try{await M.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}await M.restoreOpenSprinkles(),$.info(`SprinkleManager initialized`)}let N=()=>{let e=Fb(window.location.href),t=new WebSocket(e);t.onopen=()=>{$.info(`Lick WebSocket connected`)},t.onmessage=async e=>{try{let n=JSON.parse(e.data);if(n.requestId){let e;try{switch(n.type){case`list_webhooks`:e={type:`response`,requestId:n.requestId,data:re.listWebhooks()};break;case`create_webhook`:{let t=await re.createWebhook(n.name||`default`,n.scoop,n.filter),r=Pp().session,i=r?.webhookUrl?Lb(r.webhookUrl,t.id):Ib(window.location.href,t.id);e={type:`response`,requestId:n.requestId,data:{...t,url:i}};break}case`delete_webhook`:e=await re.deleteWebhook(n.id)?{type:`response`,requestId:n.requestId,data:{ok:!0}}:{type:`response`,requestId:n.requestId,data:{error:`Webhook not found`}};break;case`list_crontasks`:e={type:`response`,requestId:n.requestId,data:re.listCronTasks()};break;case`create_crontask`:{if(!n.name)throw Error(`name is required`);if(!n.cron)throw Error(`cron is required`);let t=await re.createCronTask(n.name,n.cron,n.scoop,n.filter);e={type:`response`,requestId:n.requestId,data:t};break}case`delete_crontask`:e=await re.deleteCronTask(n.id)?{type:`response`,requestId:n.requestId,data:{ok:!0}}:{type:`response`,requestId:n.requestId,data:{error:`Cron task not found`}};break;case`tray_status`:{let t=Pp();e={type:`response`,requestId:n.requestId,data:{state:t.state,joinUrl:t.session?.joinUrl??null,workerBaseUrl:t.session?.workerBaseUrl??null,trayId:t.session?.trayId??null}};break}default:e={type:`response`,requestId:n.requestId,error:`Unknown request type: ${n.type}`}}}catch(t){e={type:`response`,requestId:n.requestId,error:t instanceof Error?t.message:String(t)}}t.send(JSON.stringify(e));return}n.type===`webhook_event`&&re.handleWebhookEvent(n.webhookId,n.headers,n.body),n.type===`handoff_event`&&j&&j.injectHandoff(n.payload,n.sourceUrl)}catch(e){$.error(`Failed to process lick message`,{error:e instanceof Error?e.message:String(e)})}},t.onclose=()=>{$.warn(`Lick WebSocket disconnected, reconnecting in 3s...`),setTimeout(N,3e3)},t.onerror=e=>{$.error(`Lick WebSocket error`,{error:String(e)})}};N(),l.onModelChange=e=>{localStorage.setItem(`selected-model`,e),E.updateModel()},l.onClearChat=async()=>{await E.clearAllMessages(),b.clear()},l.onClearFilesystem=async()=>{await E.resetFilesystem()};let P=async e=>{$.info(`Scoop selected`,{jid:e.jid,name:e.name}),_=e,E.createScoopTab(e.jid),l.panels.memory.setSelectedScoop(e.jid),l.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=b.get(e.jid),r=e.isCone?void 0:e.name;if(n&&n.length>0)await l.panels.chat.switchToContext(t,!e.isCone,r),l.panels.chat.loadMessages(n);else if(await l.panels.chat.switchToContext(t,!e.isCone,r),l.panels.chat.getMessages().length===0){let t=await E.getMessagesForScoop(e.jid);for(let n of t){let t=n.channel===`webhook`||n.channel===`cron`,r=n.channel===`delegation`;if(t){let t={id:n.id,role:`user`,content:n.content,timestamp:new Date(n.timestamp).getTime(),source:`lick`,channel:n.channel};S(e.jid).push(t),l.panels.chat.addUserMessage(n.content)}else if(r){let t={id:n.id,role:`user`,content:`**[Instructions from sliccy]**\n\n${n.content}`,timestamp:new Date(n.timestamp).getTime(),source:`delegation`,channel:`delegation`};S(e.jid).push(t),l.panels.chat.addUserMessage(t.content)}else n.fromAssistant?(g({type:`message_start`,messageId:n.id}),g({type:`content_delta`,messageId:n.id,text:n.content}),g({type:`content_done`,messageId:n.id})):l.panels.chat.addUserMessage(n.content)}}e.isCone&&E.isProcessing(e.jid)&&l.panels.chat.setProcessing(!0)};if(l.onScoopSelect=P,_&&(E.createScoopTab(_.jid),await P(_)),j=new Qb({onPendingHandoffsChange:p}),c===`standalone`||c===`electron-overlay`){let e=await r(),t=Mb(c,e!==null)?o:null,n=await h({locationHref:window.location.href,storage:window.localStorage,envBaseUrl:null,defaultWorkerBaseUrl:t,runtimeConfigFetcher:async()=>e}),i=null,a=null,s=null;Nh(()=>A?(e,t)=>A.sendFsRequest(e,t):i?(e,t)=>i.sendFsRequest(e,t):null),Of(()=>A?()=>A.getBestFollowerForTeleport():null),kf(()=>A?()=>A.getConnectedFollowers():null);let d=e=>{s&&=(clearInterval(s),null),i?.close();let t=`follower-${e.bootstrapId}`,n=new Ab(e.channel,{browserTransport:f.getTransport(),browserAPI:f,onSnapshot:e=>{l.panels.chat.loadMessages(e)},onUserMessage:e=>{l.panels.chat.addUserMessage(e)},onStatus:e=>{l.panels.chat.setProcessing(e===`processing`)},onTargetsChanged:()=>void r()});i=n,f.setTrayTargetProvider(n),l.panels.chat.setAgent(n),n.requestSnapshot();let r=async()=>{try{let e=await f.listPages();n.advertiseTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})),t)}catch{}};s=setInterval(r,5e3),r(),$.info(`Follower sync wired to chat panel`,{trayId:e.trayId})},p=e=>{a?.cancel(),s&&=(clearInterval(s),null),i?.close(),i=null,a=ib({joinUrl:e,runtime:`slicc-standalone`,fetchImpl:Hp()},{onConnected:e=>d(e),onReconnecting:e=>{$.info(`Follower reconnecting`,{attempt:e})},onGaveUp:e=>{$.warn(`Follower reconnect gave up`,{lastError:e})}})};if(window.addEventListener(`slicc:tray-join`,(e=>{p(e.detail.joinUrl)})),window.addEventListener(`beforeunload`,()=>{s&&clearInterval(s),i?.close(),a?.cancel()},{once:!0}),n?.joinUrl)p(n.joinUrl);else if(n?.workerBaseUrl){let e,t,r,i,a=()=>{t=new Ob({browserTransport:f.getTransport(),browserAPI:f,getMessages:()=>l.panels.chat.getMessages(),getScoopJid:()=>_?.jid??`cone`,onFollowerMessage:(e,t)=>{l.panels.chat.addUserMessage(e),te.sendMessage(e,t)},onFollowerAbort:()=>{te.stop()}}),A=t,Wp(()=>t.getConnectedFollowers()),f.setTrayTargetProvider(t),i&&clearInterval(i);let n=async()=>{try{let e=await f.listPages();t.setLocalTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})))}catch{}};i=setInterval(n,5e3),n(),r=new nb({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 Rp({workerBaseUrl:n.workerBaseUrl,runtime:`slicc-standalone`,fetchImpl:Hp(),onControlMessage:e=>{if(e.type===`webhook.event`){re.handleWebhookEvent(e.webhookId,e.headers,e.body);return}r.handleControlMessage(e).catch(e=>{$.warn(`Tray leader bootstrap handling failed`,{error:e instanceof Error?e.message:String(e)})})}}),qp(async()=>{t.stop(),r.stop(),e.stop(),await e.clearSession();let n=await e.start(),i=u(window.location.href,n.workerBaseUrl,n.trayId);return i!==window.location.href&&window.history.replaceState(window.history.state,``,i),a(),Pp()}),e.start().then(e=>{let t=u(window.location.href,e.workerBaseUrl,e.trayId);t!==window.location.href&&window.history.replaceState(window.history.state,``,t)}).catch(e=>{$.warn(`Leader tray join failed`,{error:e instanceof Error?e.message:String(e)})}),window.addEventListener(`beforeunload`,()=>{clearInterval(i),t.stop(),r.stop(),e.stop()},{once:!0})}}$.info(`Orchestrator initialized — cone+scoops ready`,{scoopCount:E.getScoops().length}),_v().catch(()=>{})}sx().catch(e=>{$.error(`Fatal error`,e);let t=document.getElementById(`app`);if(t){let n=document.createElement(`div`);n.style.cssText=`padding: 2rem; text-align: center;`;let r=document.createElement(`h1`);r.style.color=`var(--s2-negative, #e34850)`,r.textContent=`Failed to start`;let i=document.createElement(`p`);i.style.color=`var(--s2-content-tertiary, #717171)`,i.textContent=e.message,n.appendChild(r),n.appendChild(i);let a=document.createElement(`button`);for(a.textContent=`Reset all data & reload`,a.style.cssText=`margin-top: 1rem; padding: 0.5rem 1.5rem; background: var(--s2-negative, #e34850); color: #fff; border: none; border-radius: 6px; cursor: pointer; font-size: 14px;`,a.addEventListener(`click`,async()=>{a.disabled=!0,a.textContent=`Resetting…`;let e=await indexedDB.databases();await Promise.all(e.map(e=>e.name?new Promise(t=>{let n=indexedDB.deleteDatabase(e.name);n.onsuccess=()=>t(),n.onerror=()=>t(),n.onblocked=()=>t()}):Promise.resolve())),location.reload()}),n.appendChild(a);t.firstChild;)t.removeChild(t.firstChild);t.appendChild(n)}});export{Av as a,oi as c,Ey as i,ri as l,Py as n,Ca as o,Iy as r,ii as s,Ny as t};
|