sliccy 2.15.0 → 2.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ui/assets/{anthropic-CgrNQy5t.js → anthropic-xHpjdD0Q.js} +1 -1
- package/dist/ui/assets/{azure-openai-responses-Ce44ZoKF.js → azure-openai-responses-9veFClVj.js} +1 -1
- package/dist/ui/assets/{es-DHfq8v7f.js → es-COR0hHNS.js} +1 -1
- package/dist/ui/assets/{google-DekoRCNX.js → google-C6mG8wc6.js} +1 -1
- package/dist/ui/assets/{index-CEjDWU2e.js → index-BUtSuwcx.js} +14 -14
- package/dist/ui/assets/index-C6L2cW9t.css +1 -0
- package/dist/ui/assets/{mistral-_hJD9dSZ.js → mistral-DkB8Y0Vx.js} +1 -1
- package/dist/ui/assets/{openai-codex-responses-DMitBXSK.js → openai-codex-responses-u7kVQry5.js} +1 -1
- package/dist/ui/assets/{openai-completions-BZjvVA-R.js → openai-completions-B4yUuCmv.js} +1 -1
- package/dist/ui/assets/{openai-responses-DtWK4aDP.js → openai-responses-DPDNRmjl.js} +1 -1
- package/dist/ui/assets/{openai-responses-shared-DDeA7nXy.js → openai-responses-shared-Djn4u9ch.js} +1 -1
- package/dist/ui/assets/{provider-settings-D10JQNhM.js → provider-settings-DvtaGASm.js} +3 -3
- package/dist/ui/index.html +4 -4
- package/dist/ui/packages/webapp/index.html +4 -4
- package/package.json +1 -1
- package/dist/ui/assets/index-CmU_sX20.css +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/slicc-editor-DqjxtQn6.js","assets/preload-helper-rov5CBGT.js","assets/dist-CEBWSFtw.js","assets/magick-wasm-frXbjDiE.js","assets/chunk-jRWAZmH_.js","assets/sql-wasm-CNZ88Vcf.js","assets/__vite-browser-external-MxCBxUMe.js","assets/pyodide-B0c5k_as.js","assets/es-
|
|
2
|
-
import{i as e,o as t,r as n,t as r}from"./chunk-jRWAZmH_.js";import{t as i}from"./logger-B-No_qN_.js";import{C as a,D as o,E as s,O as c,S as l,T as u,_ as d,a as f,b as p,c as m,d as h,f as g,g as _,i as v,m as y,n as b,o as x,p as S,r as C,s as w,t as T,u as E,v as D,w as O,x as ee,y as te}from"./provider-settings-D10JQNhM.js";import{t as k}from"./preload-helper-rov5CBGT.js";import{f as A,l as ne,p as re,s as ie,u as ae}from"./constants-BnzYaC4L.js";import{a as oe,i as se,n as ce,o as le,r as ue}from"./fs-Bs8Vlxfm.js";import{n as de,t as j}from"./path-utils-DFPXxD-4.js";import{n as fe,r as pe}from"./skills-DOSaN1J0.js";import{_ as me,a as he,b as ge,c as _e,d as ve,f as ye,g as be,h as M,i as xe,l as Se,m as Ce,n as we,o as Te,p as N,r as Ee,s as P,t as F,u as De,v as Oe,x as ke,y as Ae}from"./db-CJnk7hWr.js";import{t as je}from"./magick-wasm-frXbjDiE.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)}})();var Me=[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`}]],Ne=[[`path`,{d:`m10.852 14.772-.383.923`}],[`path`,{d:`m10.852 9.228-.383-.923`}],[`path`,{d:`m13.148 14.772.382.924`}],[`path`,{d:`m13.531 8.305-.383.923`}],[`path`,{d:`m14.772 10.852.923-.383`}],[`path`,{d:`m14.772 13.148.923.383`}],[`path`,{d:`M17.598 6.5A3 3 0 1 0 12 5a3 3 0 0 0-5.63-1.446 3 3 0 0 0-.368 1.571 4 4 0 0 0-2.525 5.771`}],[`path`,{d:`M17.998 5.125a4 4 0 0 1 2.525 5.771`}],[`path`,{d:`M19.505 10.294a4 4 0 0 1-1.5 7.706`}],[`path`,{d:`M4.032 17.483A4 4 0 0 0 11.464 20c.18-.311.892-.311 1.072 0a4 4 0 0 0 7.432-2.516`}],[`path`,{d:`M4.5 10.291A4 4 0 0 0 6 18`}],[`path`,{d:`M6.002 5.125a3 3 0 0 0 .4 1.375`}],[`path`,{d:`m9.228 10.852-.923-.383`}],[`path`,{d:`m9.228 13.148-.923.383`}],[`circle`,{cx:`12`,cy:`12`,r:`3`}]],Pe=[[`path`,{d:`M16 14v2.2l1.6 1`}],[`path`,{d:`M16 2v4`}],[`path`,{d:`M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5`}],[`path`,{d:`M3 10h5`}],[`path`,{d:`M8 2v4`}],[`circle`,{cx:`16`,cy:`16`,r:`6`}]],Fe=[[`circle`,{cx:`12`,cy:`12`,r:`10`}],[`path`,{d:`M12 6v6l4 2`}]],Ie=[[`path`,{d:`m18 16 4-4-4-4`}],[`path`,{d:`m6 8-4 4 4 4`}],[`path`,{d:`m14.5 4-5 16`}]],Le=[[`circle`,{cx:`12`,cy:`12`,r:`10`}],[`path`,{d:`m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z`}]],Re=[[`path`,{d:`M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`}],[`path`,{d:`M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z`}]],ze=[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`}],[`path`,{d:`M9 15h6`}],[`path`,{d:`M12 18v-6`}]],Be=[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`}],[`path`,{d:`M10 9H8`}],[`path`,{d:`M16 13H8`}],[`path`,{d:`M16 17H8`}]],Ve=[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`}]],He=[[`path`,{d:`M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v.5`}],[`path`,{d:`M12 10v4h4`}],[`path`,{d:`m12 14 1.535-1.605a5 5 0 0 1 8 1.5`}],[`path`,{d:`M22 22v-4h-4`}],[`path`,{d:`m22 18-1.535 1.605a5 5 0 0 1-8-1.5`}]],Ue=[[`circle`,{cx:`12`,cy:`12`,r:`10`}],[`path`,{d:`M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20`}],[`path`,{d:`M2 12h20`}]],We=[[`path`,{d:`M5 22h14`}],[`path`,{d:`M5 2h14`}],[`path`,{d:`M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22`}],[`path`,{d:`M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2`}]],Ge=[[`path`,{d:`m7 11 4.08 10.35a1 1 0 0 0 1.84 0L17 11`}],[`path`,{d:`M17 7A5 5 0 0 0 7 7`}],[`path`,{d:`M17 7a2 2 0 0 1 0 4H7a2 2 0 0 1 0-4`}]],Ke=[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`}],[`circle`,{cx:`9`,cy:`9`,r:`2`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`}]],qe=[[`path`,{d:`M13 5h8`}],[`path`,{d:`M13 12h8`}],[`path`,{d:`M13 19h8`}],[`path`,{d:`m3 17 2 2 4-4`}],[`path`,{d:`m3 7 2 2 4-4`}]],Je=[[`path`,{d:`M3 5h.01`}],[`path`,{d:`M3 12h.01`}],[`path`,{d:`M3 19h.01`}],[`path`,{d:`M8 5h13`}],[`path`,{d:`M8 12h13`}],[`path`,{d:`M8 19h13`}]],Ye=[[`path`,{d:`M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719`}]],Xe=[[`path`,{d:`m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551`}]],Ze=[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`}],[`path`,{d:`M3 3v5h5`}]],Qe=[[`path`,{d:`M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z`}],[`path`,{d:`m21.854 2.147-10.94 10.939`}]],$e=[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`}],[`path`,{d:`M20 2v4`}],[`path`,{d:`M22 4h-4`}],[`circle`,{cx:`4`,cy:`20`,r:`2`}]],et=[[`path`,{d:`M12 19h8`}],[`path`,{d:`m4 17 6-6-6-6`}]],tt=[[`path`,{d:`M10 11v6`}],[`path`,{d:`M14 11v6`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`}],[`path`,{d:`M3 6h18`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`}]],nt=[[`path`,{d:`M2 21a8 8 0 0 1 13.292-6`}],[`circle`,{cx:`10`,cy:`8`,r:`5`}],[`path`,{d:`M19 16v6`}],[`path`,{d:`M22 19h-6`}]],rt=[[`path`,{d:`m16 2-2.3 2.3a3 3 0 0 0 0 4.2l1.8 1.8a3 3 0 0 0 4.2 0L22 8`}],[`path`,{d:`M15 15 3.3 3.3a4.2 4.2 0 0 0 0 6l7.3 7.3c.7.7 2 .7 2.8 0L15 15Zm0 0 7 7`}],[`path`,{d:`m2.1 21.8 6.4-6.3`}],[`path`,{d:`m19 5-7 7`}]],it=[[`path`,{d:`M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z`}],[`path`,{d:`M16 9a5 5 0 0 1 0 6`}],[`path`,{d:`M19.364 18.364a9 9 0 0 0 0-12.728`}]],at=[[`path`,{d:`M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z`}],[`line`,{x1:`22`,x2:`16`,y1:`9`,y2:`15`}],[`line`,{x1:`16`,x2:`22`,y1:`9`,y2:`15`}]],ot=[[`path`,{d:`M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2`}],[`path`,{d:`m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06`}],[`path`,{d:`m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8`}]],st=[[`path`,{d:`M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z`}]],ct=[[`path`,{d:`M18 6 6 18`}],[`path`,{d:`m6 6 12 12`}]];function lt(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ut=lt();function dt(e){ut=e}var ft={exec:()=>null};function pt(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(ht.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var mt=(()=>{try{return!0}catch{return!1}})(),ht={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)}}>`)},gt=/^(?:[ \t]*(?:\n|$))+/,_t=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,vt=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,yt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,bt=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,xt=/ {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=pt(St).replace(/bull/g,xt).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(),wt=pt(St).replace(/bull/g,xt).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(),Tt=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Et=/^[^\n]+/,Dt=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Ot=pt(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,Dt).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),kt=pt(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,xt).getRegex(),At=`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`,jt=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Mt=pt(`^ {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`,jt).replace(`tag`,At).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Nt=pt(Tt).replace(`hr`,yt).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`,At).getRegex(),Pt={blockquote:pt(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,Nt).getRegex(),code:_t,def:Ot,fences:vt,heading:bt,hr:yt,html:Mt,lheading:Ct,list:kt,newline:gt,paragraph:Nt,table:ft,text:Et},Ft=pt(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,yt).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`,At).getRegex(),It={...Pt,lheading:wt,table:Ft,paragraph:pt(Tt).replace(`hr`,yt).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,Ft).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`,At).getRegex()},Lt={...Pt,html:pt(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,jt).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:ft,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:pt(Tt).replace(`hr`,yt).replace(`heading`,` *#{1,6} *[^
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/slicc-editor-DqjxtQn6.js","assets/preload-helper-rov5CBGT.js","assets/dist-CEBWSFtw.js","assets/magick-wasm-frXbjDiE.js","assets/chunk-jRWAZmH_.js","assets/sql-wasm-CNZ88Vcf.js","assets/__vite-browser-external-MxCBxUMe.js","assets/pyodide-B0c5k_as.js","assets/es-COR0hHNS.js","assets/dist-Ehp5JdjU2.js","assets/provider-settings-DvtaGASm.js","assets/simple-options-CP_5aL7H.js","assets/openai-CuiHR4mv.js","assets/logger-B-No_qN_.js","assets/skills-DOSaN1J0.js","assets/fs-Bs8Vlxfm.js","assets/path-utils-DFPXxD-4.js","assets/constants-BnzYaC4L.js","assets/xterm-BmfB5bmM.css","assets/offscreen-client-CsH6V__l.js","assets/bsh-watchdog-BofJVeV-.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{i as e,o as t,r as n,t as r}from"./chunk-jRWAZmH_.js";import{t as i}from"./logger-B-No_qN_.js";import{C as a,D as o,E as s,O as c,S as l,T as u,_ as d,a as f,b as p,c as m,d as h,f as g,g as _,i as v,m as y,n as b,o as x,p as S,r as C,s as w,t as T,u as E,v as D,w as O,x as ee,y as te}from"./provider-settings-DvtaGASm.js";import{t as k}from"./preload-helper-rov5CBGT.js";import{f as A,l as ne,p as re,s as ie,u as ae}from"./constants-BnzYaC4L.js";import{a as oe,i as se,n as ce,o as le,r as ue}from"./fs-Bs8Vlxfm.js";import{n as de,t as j}from"./path-utils-DFPXxD-4.js";import{n as fe,r as pe}from"./skills-DOSaN1J0.js";import{_ as me,a as he,b as ge,c as _e,d as ve,f as ye,g as be,h as M,i as xe,l as Se,m as Ce,n as we,o as Te,p as N,r as Ee,s as P,t as F,u as De,v as Oe,x as ke,y as Ae}from"./db-CJnk7hWr.js";import{t as je}from"./magick-wasm-frXbjDiE.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)}})();var Me=[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`}]],Ne=[[`path`,{d:`m10.852 14.772-.383.923`}],[`path`,{d:`m10.852 9.228-.383-.923`}],[`path`,{d:`m13.148 14.772.382.924`}],[`path`,{d:`m13.531 8.305-.383.923`}],[`path`,{d:`m14.772 10.852.923-.383`}],[`path`,{d:`m14.772 13.148.923.383`}],[`path`,{d:`M17.598 6.5A3 3 0 1 0 12 5a3 3 0 0 0-5.63-1.446 3 3 0 0 0-.368 1.571 4 4 0 0 0-2.525 5.771`}],[`path`,{d:`M17.998 5.125a4 4 0 0 1 2.525 5.771`}],[`path`,{d:`M19.505 10.294a4 4 0 0 1-1.5 7.706`}],[`path`,{d:`M4.032 17.483A4 4 0 0 0 11.464 20c.18-.311.892-.311 1.072 0a4 4 0 0 0 7.432-2.516`}],[`path`,{d:`M4.5 10.291A4 4 0 0 0 6 18`}],[`path`,{d:`M6.002 5.125a3 3 0 0 0 .4 1.375`}],[`path`,{d:`m9.228 10.852-.923-.383`}],[`path`,{d:`m9.228 13.148-.923.383`}],[`circle`,{cx:`12`,cy:`12`,r:`3`}]],Pe=[[`path`,{d:`M16 14v2.2l1.6 1`}],[`path`,{d:`M16 2v4`}],[`path`,{d:`M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5`}],[`path`,{d:`M3 10h5`}],[`path`,{d:`M8 2v4`}],[`circle`,{cx:`16`,cy:`16`,r:`6`}]],Fe=[[`circle`,{cx:`12`,cy:`12`,r:`10`}],[`path`,{d:`M12 6v6l4 2`}]],Ie=[[`path`,{d:`m18 16 4-4-4-4`}],[`path`,{d:`m6 8-4 4 4 4`}],[`path`,{d:`m14.5 4-5 16`}]],Le=[[`circle`,{cx:`12`,cy:`12`,r:`10`}],[`path`,{d:`m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z`}]],Re=[[`path`,{d:`M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`}],[`path`,{d:`M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z`}]],ze=[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`}],[`path`,{d:`M9 15h6`}],[`path`,{d:`M12 18v-6`}]],Be=[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`}],[`path`,{d:`M10 9H8`}],[`path`,{d:`M16 13H8`}],[`path`,{d:`M16 17H8`}]],Ve=[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`}]],He=[[`path`,{d:`M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v.5`}],[`path`,{d:`M12 10v4h4`}],[`path`,{d:`m12 14 1.535-1.605a5 5 0 0 1 8 1.5`}],[`path`,{d:`M22 22v-4h-4`}],[`path`,{d:`m22 18-1.535 1.605a5 5 0 0 1-8-1.5`}]],Ue=[[`circle`,{cx:`12`,cy:`12`,r:`10`}],[`path`,{d:`M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20`}],[`path`,{d:`M2 12h20`}]],We=[[`path`,{d:`M5 22h14`}],[`path`,{d:`M5 2h14`}],[`path`,{d:`M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22`}],[`path`,{d:`M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2`}]],Ge=[[`path`,{d:`m7 11 4.08 10.35a1 1 0 0 0 1.84 0L17 11`}],[`path`,{d:`M17 7A5 5 0 0 0 7 7`}],[`path`,{d:`M17 7a2 2 0 0 1 0 4H7a2 2 0 0 1 0-4`}]],Ke=[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`}],[`circle`,{cx:`9`,cy:`9`,r:`2`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`}]],qe=[[`path`,{d:`M13 5h8`}],[`path`,{d:`M13 12h8`}],[`path`,{d:`M13 19h8`}],[`path`,{d:`m3 17 2 2 4-4`}],[`path`,{d:`m3 7 2 2 4-4`}]],Je=[[`path`,{d:`M3 5h.01`}],[`path`,{d:`M3 12h.01`}],[`path`,{d:`M3 19h.01`}],[`path`,{d:`M8 5h13`}],[`path`,{d:`M8 12h13`}],[`path`,{d:`M8 19h13`}]],Ye=[[`path`,{d:`M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719`}]],Xe=[[`path`,{d:`m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551`}]],Ze=[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`}],[`path`,{d:`M3 3v5h5`}]],Qe=[[`path`,{d:`M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z`}],[`path`,{d:`m21.854 2.147-10.94 10.939`}]],$e=[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`}],[`path`,{d:`M20 2v4`}],[`path`,{d:`M22 4h-4`}],[`circle`,{cx:`4`,cy:`20`,r:`2`}]],et=[[`path`,{d:`M12 19h8`}],[`path`,{d:`m4 17 6-6-6-6`}]],tt=[[`path`,{d:`M10 11v6`}],[`path`,{d:`M14 11v6`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`}],[`path`,{d:`M3 6h18`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`}]],nt=[[`path`,{d:`M2 21a8 8 0 0 1 13.292-6`}],[`circle`,{cx:`10`,cy:`8`,r:`5`}],[`path`,{d:`M19 16v6`}],[`path`,{d:`M22 19h-6`}]],rt=[[`path`,{d:`m16 2-2.3 2.3a3 3 0 0 0 0 4.2l1.8 1.8a3 3 0 0 0 4.2 0L22 8`}],[`path`,{d:`M15 15 3.3 3.3a4.2 4.2 0 0 0 0 6l7.3 7.3c.7.7 2 .7 2.8 0L15 15Zm0 0 7 7`}],[`path`,{d:`m2.1 21.8 6.4-6.3`}],[`path`,{d:`m19 5-7 7`}]],it=[[`path`,{d:`M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z`}],[`path`,{d:`M16 9a5 5 0 0 1 0 6`}],[`path`,{d:`M19.364 18.364a9 9 0 0 0 0-12.728`}]],at=[[`path`,{d:`M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z`}],[`line`,{x1:`22`,x2:`16`,y1:`9`,y2:`15`}],[`line`,{x1:`16`,x2:`22`,y1:`9`,y2:`15`}]],ot=[[`path`,{d:`M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2`}],[`path`,{d:`m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06`}],[`path`,{d:`m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8`}]],st=[[`path`,{d:`M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z`}]],ct=[[`path`,{d:`M18 6 6 18`}],[`path`,{d:`m6 6 12 12`}]];function lt(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ut=lt();function dt(e){ut=e}var ft={exec:()=>null};function pt(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(ht.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var mt=(()=>{try{return!0}catch{return!1}})(),ht={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)}}>`)},gt=/^(?:[ \t]*(?:\n|$))+/,_t=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,vt=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,yt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,bt=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,xt=/ {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=pt(St).replace(/bull/g,xt).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(),wt=pt(St).replace(/bull/g,xt).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(),Tt=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Et=/^[^\n]+/,Dt=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Ot=pt(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,Dt).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),kt=pt(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,xt).getRegex(),At=`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`,jt=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Mt=pt(`^ {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`,jt).replace(`tag`,At).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Nt=pt(Tt).replace(`hr`,yt).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`,At).getRegex(),Pt={blockquote:pt(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,Nt).getRegex(),code:_t,def:Ot,fences:vt,heading:bt,hr:yt,html:Mt,lheading:Ct,list:kt,newline:gt,paragraph:Nt,table:ft,text:Et},Ft=pt(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,yt).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`,At).getRegex(),It={...Pt,lheading:wt,table:Ft,paragraph:pt(Tt).replace(`hr`,yt).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,Ft).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`,At).getRegex()},Lt={...Pt,html:pt(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,jt).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:ft,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:pt(Tt).replace(`hr`,yt).replace(`heading`,` *#{1,6} *[^
|
|
3
3
|
]`).replace(`lheading`,Ct).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},Rt=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,zt=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Bt=/^( {2,}|\\)\n(?!\s*$)/,Vt=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ht=/[\p{P}\p{S}]/u,Ut=/[\s\p{P}\p{S}]/u,Wt=/[^\s\p{P}\p{S}]/u,Gt=pt(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,Ut).getRegex(),Kt=/(?!~)[\p{P}\p{S}]/u,qt=/(?!~)[\s\p{P}\p{S}]/u,Jt=/(?:[^\s\p{P}\p{S}]|~)/u,Yt=pt(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,mt?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),Xt=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Zt=pt(Xt,`u`).replace(/punct/g,Ht).getRegex(),Qt=pt(Xt,`u`).replace(/punct/g,Kt).getRegex(),$t=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,en=pt($t,`gu`).replace(/notPunctSpace/g,Wt).replace(/punctSpace/g,Ut).replace(/punct/g,Ht).getRegex(),tn=pt($t,`gu`).replace(/notPunctSpace/g,Jt).replace(/punctSpace/g,qt).replace(/punct/g,Kt).getRegex(),nn=pt(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,Wt).replace(/punctSpace/g,Ut).replace(/punct/g,Ht).getRegex(),rn=pt(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,Ht).getRegex(),an=pt(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Wt).replace(/punctSpace/g,Ut).replace(/punct/g,Ht).getRegex(),on=pt(/\\(punct)/,`gu`).replace(/punct/g,Ht).getRegex(),sn=pt(/^<(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(),cn=pt(jt).replace(`(?:-->|$)`,`-->`).getRegex(),ln=pt(`^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`,cn).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),un=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,dn=pt(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,un).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),fn=pt(/^!?\[(label)\]\[(ref)\]/).replace(`label`,un).replace(`ref`,Dt).getRegex(),pn=pt(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,Dt).getRegex(),mn=pt(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,fn).replace(`nolink`,pn).getRegex(),hn=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,gn={_backpedal:ft,anyPunctuation:on,autolink:sn,blockSkip:Yt,br:Bt,code:zt,del:ft,delLDelim:ft,delRDelim:ft,emStrongLDelim:Zt,emStrongRDelimAst:en,emStrongRDelimUnd:nn,escape:Rt,link:dn,nolink:pn,punctuation:Gt,reflink:fn,reflinkSearch:mn,tag:ln,text:Vt,url:ft},_n={...gn,link:pt(/^!?\[(label)\]\((.*?)\)/).replace(`label`,un).getRegex(),reflink:pt(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,un).getRegex()},vn={...gn,emStrongRDelimAst:tn,emStrongLDelim:Qt,delLDelim:rn,delRDelim:an,url:pt(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,hn).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:pt(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,hn).getRegex()},yn={...vn,br:pt(Bt).replace(`{2,}`,`*`).getRegex(),text:pt(vn.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},bn={normal:Pt,gfm:It,pedantic:Lt},xn={normal:gn,gfm:vn,breaks:yn,pedantic:_n},Sn={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},Cn=e=>Sn[e];function wn(e,t){if(t){if(ht.escapeTest.test(e))return e.replace(ht.escapeReplace,Cn)}else if(ht.escapeTestNoEncode.test(e))return e.replace(ht.escapeReplaceNoEncode,Cn);return e}function Tn(e){try{e=encodeURI(e).replace(ht.percentDecode,`%`)}catch{return null}return e}function En(e,t){let n=e.replace(ht.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(ht.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(ht.slashPipe,`|`);return n}function Dn(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 On(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 kn(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 An(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 jn(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function Mn(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
@@ -63,7 +63,7 @@ ${e}</tr>
|
|
|
63
63
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
64
64
|
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${wn(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=Tn(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+wn(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Tn(e);if(i===null)return wn(n);e=i;let a=`<img src="${e}" alt="${wn(n)}"`;return t&&(a+=` title="${wn(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:wn(e.text)}},In=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},Ln=class e{options;renderer;textRenderer;constructor(e){this.options=e||ut,this.options.renderer=this.options.renderer||new Fn,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new In}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},Rn=class{options;block;constructor(e){this.options=e||ut}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Pn.lex:Pn.lexInline}provideParser(e=this.block){return e?Ln.parse:Ln.parseInline}},zn=class{defaults=lt();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Ln;Renderer=Fn;TextRenderer=In;Lexer=Pn;Tokenizer=Nn;Hooks=Rn;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new Fn(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new Nn(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new Rn;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];Rn.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&Rn.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:t[r]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Pn.lex(e,t??this.defaults)}parser(e,t){return Ln.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?Pn.lex:Pn.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?Ln.parse:Ln.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?Pn.lex:Pn.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?Ln.parse:Ln.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
|
|
65
65
|
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+wn(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}},Bn=new zn;function Vn(e,t){return Bn.parse(e,t)}Vn.options=Vn.setOptions=function(e){return Bn.setOptions(e),Vn.defaults=Bn.defaults,dt(Vn.defaults),Vn},Vn.getDefaults=lt,Vn.defaults=ut,Vn.use=function(...e){return Bn.use(...e),Vn.defaults=Bn.defaults,dt(Vn.defaults),Vn},Vn.walkTokens=function(e,t){return Bn.walkTokens(e,t)},Vn.parseInline=Bn.parseInline,Vn.Parser=Ln,Vn.parser=Ln.parse,Vn.Renderer=Fn,Vn.TextRenderer=In,Vn.Lexer=Pn,Vn.lexer=Pn.lex,Vn.Tokenizer=Nn,Vn.Hooks=Rn,Vn.parse=Vn,Vn.options,Vn.setOptions,Vn.use,Vn.walkTokens,Vn.parseInline,Ln.parse,Pn.lex;var{entries:Hn,setPrototypeOf:Un,isFrozen:Wn,getPrototypeOf:Gn,getOwnPropertyDescriptor:Kn}=Object,{freeze:qn,seal:Jn,create:Yn}=Object,{apply:Xn,construct:Zn}=typeof Reflect<`u`&&Reflect;qn||=function(e){return e},Jn||=function(e){return e},Xn||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},Zn||=function(e){return new e(...[...arguments].slice(1))};var Qn=fr(Array.prototype.forEach),$n=fr(Array.prototype.lastIndexOf),er=fr(Array.prototype.pop),tr=fr(Array.prototype.push),nr=fr(Array.prototype.splice),rr=fr(String.prototype.toLowerCase),ir=fr(String.prototype.toString),ar=fr(String.prototype.match),or=fr(String.prototype.replace),sr=fr(String.prototype.indexOf),cr=fr(String.prototype.trim),lr=fr(Object.prototype.hasOwnProperty),ur=fr(RegExp.prototype.test),dr=pr(TypeError);function fr(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return Xn(e,t,n)}}function pr(e){return function(){return Zn(e,[...arguments])}}function mr(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:rr;Un&&Un(e,null);let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(Wn(t)||(t[r]=e),i=e)}e[i]=!0}return e}function hr(e){for(let t=0;t<e.length;t++)lr(e,t)||(e[t]=null);return e}function gr(e){let t=Yn(null);for(let[n,r]of Hn(e))lr(e,n)&&(Array.isArray(r)?t[n]=hr(r):r&&typeof r==`object`&&r.constructor===Object?t[n]=gr(r):t[n]=r);return t}function _r(e,t){for(;e!==null;){let n=Kn(e,t);if(n){if(n.get)return fr(n.get);if(typeof n.value==`function`)return fr(n.value)}e=Gn(e)}function n(){return null}return n}var vr=qn(`a.abbr.acronym.address.area.article.aside.audio.b.bdi.bdo.big.blink.blockquote.body.br.button.canvas.caption.center.cite.code.col.colgroup.content.data.datalist.dd.decorator.del.details.dfn.dialog.dir.div.dl.dt.element.em.fieldset.figcaption.figure.font.footer.form.h1.h2.h3.h4.h5.h6.head.header.hgroup.hr.html.i.img.input.ins.kbd.label.legend.li.main.map.mark.marquee.menu.menuitem.meter.nav.nobr.ol.optgroup.option.output.p.picture.pre.progress.q.rp.rt.ruby.s.samp.search.section.select.shadow.slot.small.source.spacer.span.strike.strong.style.sub.summary.sup.table.tbody.td.template.textarea.tfoot.th.thead.time.tr.track.tt.u.ul.var.video.wbr`.split(`.`)),yr=qn(`svg.a.altglyph.altglyphdef.altglyphitem.animatecolor.animatemotion.animatetransform.circle.clippath.defs.desc.ellipse.enterkeyhint.exportparts.filter.font.g.glyph.glyphref.hkern.image.inputmode.line.lineargradient.marker.mask.metadata.mpath.part.path.pattern.polygon.polyline.radialgradient.rect.stop.style.switch.symbol.text.textpath.title.tref.tspan.view.vkern`.split(`.`)),br=qn([`feBlend`,`feColorMatrix`,`feComponentTransfer`,`feComposite`,`feConvolveMatrix`,`feDiffuseLighting`,`feDisplacementMap`,`feDistantLight`,`feDropShadow`,`feFlood`,`feFuncA`,`feFuncB`,`feFuncG`,`feFuncR`,`feGaussianBlur`,`feImage`,`feMerge`,`feMergeNode`,`feMorphology`,`feOffset`,`fePointLight`,`feSpecularLighting`,`feSpotLight`,`feTile`,`feTurbulence`]),xr=qn([`animate`,`color-profile`,`cursor`,`discard`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`foreignobject`,`hatch`,`hatchpath`,`mesh`,`meshgradient`,`meshpatch`,`meshrow`,`missing-glyph`,`script`,`set`,`solidcolor`,`unknown`,`use`]),Sr=qn(`math.menclose.merror.mfenced.mfrac.mglyph.mi.mlabeledtr.mmultiscripts.mn.mo.mover.mpadded.mphantom.mroot.mrow.ms.mspace.msqrt.mstyle.msub.msup.msubsup.mtable.mtd.mtext.mtr.munder.munderover.mprescripts`.split(`.`)),Cr=qn([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),wr=qn([`#text`]),Tr=qn(`accept.action.align.alt.autocapitalize.autocomplete.autopictureinpicture.autoplay.background.bgcolor.border.capture.cellpadding.cellspacing.checked.cite.class.clear.color.cols.colspan.controls.controlslist.coords.crossorigin.datetime.decoding.default.dir.disabled.disablepictureinpicture.disableremoteplayback.download.draggable.enctype.enterkeyhint.exportparts.face.for.headers.height.hidden.high.href.hreflang.id.inert.inputmode.integrity.ismap.kind.label.lang.list.loading.loop.low.max.maxlength.media.method.min.minlength.multiple.muted.name.nonce.noshade.novalidate.nowrap.open.optimum.part.pattern.placeholder.playsinline.popover.popovertarget.popovertargetaction.poster.preload.pubdate.radiogroup.readonly.rel.required.rev.reversed.role.rows.rowspan.spellcheck.scope.selected.shape.size.sizes.slot.span.srclang.start.src.srcset.step.style.summary.tabindex.title.translate.type.usemap.valign.value.width.wrap.xmlns.slot`.split(`.`)),Er=qn(`accent-height.accumulate.additive.alignment-baseline.amplitude.ascent.attributename.attributetype.azimuth.basefrequency.baseline-shift.begin.bias.by.class.clip.clippathunits.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.cx.cy.d.dx.dy.diffuseconstant.direction.display.divisor.dur.edgemode.elevation.end.exponent.fill.fill-opacity.fill-rule.filter.filterunits.flood-color.flood-opacity.font-family.font-size.font-size-adjust.font-stretch.font-style.font-variant.font-weight.fx.fy.g1.g2.glyph-name.glyphref.gradientunits.gradienttransform.height.href.id.image-rendering.in.in2.intercept.k.k1.k2.k3.k4.kerning.keypoints.keysplines.keytimes.lang.lengthadjust.letter-spacing.kernelmatrix.kernelunitlength.lighting-color.local.marker-end.marker-mid.marker-start.markerheight.markerunits.markerwidth.maskcontentunits.maskunits.max.mask.mask-type.media.method.mode.min.name.numoctaves.offset.operator.opacity.order.orient.orientation.origin.overflow.paint-order.path.pathlength.patterncontentunits.patterntransform.patternunits.points.preservealpha.preserveaspectratio.primitiveunits.r.rx.ry.radius.refx.refy.repeatcount.repeatdur.restart.result.rotate.scale.seed.shape-rendering.slope.specularconstant.specularexponent.spreadmethod.startoffset.stddeviation.stitchtiles.stop-color.stop-opacity.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke.stroke-width.style.surfacescale.systemlanguage.tabindex.tablevalues.targetx.targety.transform.transform-origin.text-anchor.text-decoration.text-rendering.textlength.type.u1.u2.unicode.values.viewbox.visibility.version.vert-adv-y.vert-origin-x.vert-origin-y.width.word-spacing.wrap.writing-mode.xchannelselector.ychannelselector.x.x1.x2.xmlns.y.y1.y2.z.zoomandpan`.split(`.`)),Dr=qn(`accent.accentunder.align.bevelled.close.columnsalign.columnlines.columnspan.denomalign.depth.dir.display.displaystyle.encoding.fence.frame.height.href.id.largeop.length.linethickness.lspace.lquote.mathbackground.mathcolor.mathsize.mathvariant.maxsize.minsize.movablelimits.notation.numalign.open.rowalign.rowlines.rowspacing.rowspan.rspace.rquote.scriptlevel.scriptminsize.scriptsizemultiplier.selection.separator.separators.stretchy.subscriptshift.supscriptshift.symmetric.voffset.width.xmlns`.split(`.`)),Or=qn([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),kr=Jn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Ar=Jn(/<%[\w\W]*|[\w\W]*%>/gm),jr=Jn(/\$\{[\w\W]*/gm),Mr=Jn(/^data-[\-\w.\u00B7-\uFFFF]+$/),Nr=Jn(/^aria-[\-\w]+$/),Pr=Jn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Fr=Jn(/^(?:\w+script|data):/i),Ir=Jn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Lr=Jn(/^html$/i),Rr=Jn(/^[a-z][.\w]*(-[.\w]+)+$/i),zr=Object.freeze({__proto__:null,ARIA_ATTR:Nr,ATTR_WHITESPACE:Ir,CUSTOM_ELEMENT:Rr,DATA_ATTR:Mr,DOCTYPE_NAME:Lr,ERB_EXPR:Ar,IS_ALLOWED_URI:Pr,IS_SCRIPT_OR_DATA:Fr,MUSTACHE_EXPR:kr,TMPLIT_EXPR:jr}),Br={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Vr=function(){return typeof window>`u`?null:window},Hr=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch{return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},Ur=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Wr(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Vr(),t=e=>Wr(e);if(t.version=`3.3.3`,t.removed=[],!e||!e.document||e.document.nodeType!==Br.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e,r=n,i=r.currentScript,{DocumentFragment:a,HTMLTemplateElement:o,Node:s,Element:c,NodeFilter:l,NamedNodeMap:u=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:d,DOMParser:f,trustedTypes:p}=e,m=c.prototype,h=_r(m,`cloneNode`),g=_r(m,`remove`),_=_r(m,`nextSibling`),v=_r(m,`childNodes`),y=_r(m,`parentNode`);if(typeof o==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let b,x=``,{implementation:S,createNodeIterator:C,createDocumentFragment:w,getElementsByTagName:T}=n,{importNode:E}=r,D=Ur();t.isSupported=typeof Hn==`function`&&typeof y==`function`&&S&&S.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:O,ERB_EXPR:ee,TMPLIT_EXPR:te,DATA_ATTR:k,ARIA_ATTR:A,IS_SCRIPT_OR_DATA:ne,ATTR_WHITESPACE:re,CUSTOM_ELEMENT:ie}=zr,{IS_ALLOWED_URI:ae}=zr,oe=null,se=mr({},[...vr,...yr,...br,...Sr,...wr]),ce=null,le=mr({},[...Tr,...Er,...Dr,...Or]),ue=Object.seal(Yn(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),de=null,j=null,fe=Object.seal(Yn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),pe=!0,me=!0,he=!1,ge=!0,_e=!1,ve=!0,ye=!1,be=!1,M=!1,xe=!1,Se=!1,Ce=!1,we=!0,Te=!1,N=!0,Ee=!1,P={},F=null,De=mr({},[`annotation-xml`,`audio`,`colgroup`,`desc`,`foreignobject`,`head`,`iframe`,`math`,`mi`,`mn`,`mo`,`ms`,`mtext`,`noembed`,`noframes`,`noscript`,`plaintext`,`script`,`style`,`svg`,`template`,`thead`,`title`,`video`,`xmp`]),Oe=null,ke=mr({},[`audio`,`video`,`img`,`source`,`image`,`track`]),Ae=null,je=mr({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),Me=`http://www.w3.org/1998/Math/MathML`,Ne=`http://www.w3.org/2000/svg`,Pe=`http://www.w3.org/1999/xhtml`,Fe=Pe,Ie=!1,Le=null,Re=mr({},[Me,Ne,Pe],ir),ze=mr({},[`mi`,`mo`,`mn`,`ms`,`mtext`]),Be=mr({},[`annotation-xml`]),Ve=mr({},[`title`,`style`,`font`,`a`,`script`]),He=null,Ue=[`application/xhtml+xml`,`text/html`],We=null,Ge=null,Ke=n.createElement(`form`),qe=function(e){return e instanceof RegExp||e instanceof Function},Je=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Ge&&Ge===e)){if((!e||typeof e!=`object`)&&(e={}),e=gr(e),He=Ue.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,We=He===`application/xhtml+xml`?ir:rr,oe=lr(e,`ALLOWED_TAGS`)?mr({},e.ALLOWED_TAGS,We):se,ce=lr(e,`ALLOWED_ATTR`)?mr({},e.ALLOWED_ATTR,We):le,Le=lr(e,`ALLOWED_NAMESPACES`)?mr({},e.ALLOWED_NAMESPACES,ir):Re,Ae=lr(e,`ADD_URI_SAFE_ATTR`)?mr(gr(je),e.ADD_URI_SAFE_ATTR,We):je,Oe=lr(e,`ADD_DATA_URI_TAGS`)?mr(gr(ke),e.ADD_DATA_URI_TAGS,We):ke,F=lr(e,`FORBID_CONTENTS`)?mr({},e.FORBID_CONTENTS,We):De,de=lr(e,`FORBID_TAGS`)?mr({},e.FORBID_TAGS,We):gr({}),j=lr(e,`FORBID_ATTR`)?mr({},e.FORBID_ATTR,We):gr({}),P=lr(e,`USE_PROFILES`)?e.USE_PROFILES:!1,pe=e.ALLOW_ARIA_ATTR!==!1,me=e.ALLOW_DATA_ATTR!==!1,he=e.ALLOW_UNKNOWN_PROTOCOLS||!1,ge=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,_e=e.SAFE_FOR_TEMPLATES||!1,ve=e.SAFE_FOR_XML!==!1,ye=e.WHOLE_DOCUMENT||!1,xe=e.RETURN_DOM||!1,Se=e.RETURN_DOM_FRAGMENT||!1,Ce=e.RETURN_TRUSTED_TYPE||!1,M=e.FORCE_BODY||!1,we=e.SANITIZE_DOM!==!1,Te=e.SANITIZE_NAMED_PROPS||!1,N=e.KEEP_CONTENT!==!1,Ee=e.IN_PLACE||!1,ae=e.ALLOWED_URI_REGEXP||Pr,Fe=e.NAMESPACE||Pe,ze=e.MATHML_TEXT_INTEGRATION_POINTS||ze,Be=e.HTML_INTEGRATION_POINTS||Be,ue=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&qe(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(ue.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&qe(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(ue.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements==`boolean`&&(ue.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),_e&&(me=!1),Se&&(xe=!0),P&&(oe=mr({},wr),ce=Yn(null),P.html===!0&&(mr(oe,vr),mr(ce,Tr)),P.svg===!0&&(mr(oe,yr),mr(ce,Er),mr(ce,Or)),P.svgFilters===!0&&(mr(oe,br),mr(ce,Er),mr(ce,Or)),P.mathMl===!0&&(mr(oe,Sr),mr(ce,Dr),mr(ce,Or))),lr(e,`ADD_TAGS`)||(fe.tagCheck=null),lr(e,`ADD_ATTR`)||(fe.attributeCheck=null),e.ADD_TAGS&&(typeof e.ADD_TAGS==`function`?fe.tagCheck=e.ADD_TAGS:(oe===se&&(oe=gr(oe)),mr(oe,e.ADD_TAGS,We))),e.ADD_ATTR&&(typeof e.ADD_ATTR==`function`?fe.attributeCheck=e.ADD_ATTR:(ce===le&&(ce=gr(ce)),mr(ce,e.ADD_ATTR,We))),e.ADD_URI_SAFE_ATTR&&mr(Ae,e.ADD_URI_SAFE_ATTR,We),e.FORBID_CONTENTS&&(F===De&&(F=gr(F)),mr(F,e.FORBID_CONTENTS,We)),e.ADD_FORBID_CONTENTS&&(F===De&&(F=gr(F)),mr(F,e.ADD_FORBID_CONTENTS,We)),N&&(oe[`#text`]=!0),ye&&mr(oe,[`html`,`head`,`body`]),oe.table&&(mr(oe,[`tbody`]),delete de.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw dr(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw dr(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);b=e.TRUSTED_TYPES_POLICY,x=b.createHTML(``)}else b===void 0&&(b=Hr(p,i)),b!==null&&typeof x==`string`&&(x=b.createHTML(``));qn&&qn(e),Ge=e}},Ye=mr({},[...yr,...br,...xr]),Xe=mr({},[...Sr,...Cr]),Ze=function(e){let t=y(e);(!t||!t.tagName)&&(t={namespaceURI:Fe,tagName:`template`});let n=rr(e.tagName),r=rr(t.tagName);return Le[e.namespaceURI]?e.namespaceURI===Ne?t.namespaceURI===Pe?n===`svg`:t.namespaceURI===Me?n===`svg`&&(r===`annotation-xml`||ze[r]):!!Ye[n]:e.namespaceURI===Me?t.namespaceURI===Pe?n===`math`:t.namespaceURI===Ne?n===`math`&&Be[r]:!!Xe[n]:e.namespaceURI===Pe?t.namespaceURI===Ne&&!Be[r]||t.namespaceURI===Me&&!ze[r]?!1:!Xe[n]&&(Ve[n]||!Ye[n]):!!(He===`application/xhtml+xml`&&Le[e.namespaceURI]):!1},Qe=function(e){tr(t.removed,{element:e});try{y(e).removeChild(e)}catch{g(e)}},$e=function(e,n){try{tr(t.removed,{attribute:n.getAttributeNode(e),from:n})}catch{tr(t.removed,{attribute:null,from:n})}if(n.removeAttribute(e),e===`is`)if(xe||Se)try{Qe(n)}catch{}else try{n.setAttribute(e,``)}catch{}},et=function(e){let t=null,r=null;if(M)e=`<remove></remove>`+e;else{let t=ar(e,/^[\r\n\t ]+/);r=t&&t[0]}He===`application/xhtml+xml`&&Fe===Pe&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=b?b.createHTML(e):e;if(Fe===Pe)try{t=new f().parseFromString(i,He)}catch{}if(!t||!t.documentElement){t=S.createDocument(Fe,`template`,null);try{t.documentElement.innerHTML=Ie?x:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),Fe===Pe?T.call(t,ye?`html`:`body`)[0]:ye?t.documentElement:a},tt=function(e){return C.call(e.ownerDocument||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},nt=function(e){return e instanceof d&&(typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||!(e.attributes instanceof u)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`)},rt=function(e){return typeof s==`function`&&e instanceof s};function it(e,n,r){Qn(e,e=>{e.call(t,n,r,Ge)})}let at=function(e){let n=null;if(it(D.beforeSanitizeElements,e,null),nt(e))return Qe(e),!0;let r=We(e.nodeName);if(it(D.uponSanitizeElement,e,{tagName:r,allowedTags:oe}),ve&&e.hasChildNodes()&&!rt(e.firstElementChild)&&ur(/<[/\w!]/g,e.innerHTML)&&ur(/<[/\w!]/g,e.textContent)||e.nodeType===Br.progressingInstruction||ve&&e.nodeType===Br.comment&&ur(/<[/\w]/g,e.data))return Qe(e),!0;if(!(fe.tagCheck instanceof Function&&fe.tagCheck(r))&&(!oe[r]||de[r])){if(!de[r]&&st(r)&&(ue.tagNameCheck instanceof RegExp&&ur(ue.tagNameCheck,r)||ue.tagNameCheck instanceof Function&&ue.tagNameCheck(r)))return!1;if(N&&!F[r]){let t=y(e)||e.parentNode,n=v(e)||e.childNodes;if(n&&t){let r=n.length;for(let i=r-1;i>=0;--i){let r=h(n[i],!0);r.__removalCount=(e.__removalCount||0)+1,t.insertBefore(r,_(e))}}}return Qe(e),!0}return e instanceof c&&!Ze(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&ur(/<\/no(script|embed|frames)/i,e.innerHTML)?(Qe(e),!0):(_e&&e.nodeType===Br.text&&(n=e.textContent,Qn([O,ee,te],e=>{n=or(n,e,` `)}),e.textContent!==n&&(tr(t.removed,{element:e.cloneNode()}),e.textContent=n)),it(D.afterSanitizeElements,e,null),!1)},ot=function(e,t,r){if(j[t]||we&&(t===`id`||t===`name`)&&(r in n||r in Ke))return!1;if(!(me&&!j[t]&&ur(k,t))&&!(pe&&ur(A,t))&&!(fe.attributeCheck instanceof Function&&fe.attributeCheck(t,e))){if(!ce[t]||j[t]){if(!(st(e)&&(ue.tagNameCheck instanceof RegExp&&ur(ue.tagNameCheck,e)||ue.tagNameCheck instanceof Function&&ue.tagNameCheck(e))&&(ue.attributeNameCheck instanceof RegExp&&ur(ue.attributeNameCheck,t)||ue.attributeNameCheck instanceof Function&&ue.attributeNameCheck(t,e))||t===`is`&&ue.allowCustomizedBuiltInElements&&(ue.tagNameCheck instanceof RegExp&&ur(ue.tagNameCheck,r)||ue.tagNameCheck instanceof Function&&ue.tagNameCheck(r))))return!1}else if(!Ae[t]&&!ur(ae,or(r,re,``))&&!((t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&sr(r,`data:`)===0&&Oe[e])&&!(he&&!ur(ne,or(r,re,``)))&&r)return!1}return!0},st=function(e){return e!==`annotation-xml`&&ar(e,ie)},ct=function(e){it(D.beforeSanitizeAttributes,e,null);let{attributes:n}=e;if(!n||nt(e))return;let r={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:ce,forceKeepAttr:void 0},i=n.length;for(;i--;){let{name:a,namespaceURI:o,value:s}=n[i],c=We(a),l=s,u=a===`value`?l:cr(l);if(r.attrName=c,r.attrValue=u,r.keepAttr=!0,r.forceKeepAttr=void 0,it(D.uponSanitizeAttribute,e,r),u=r.attrValue,Te&&(c===`id`||c===`name`)&&($e(a,e),u=`user-content-`+u),ve&&ur(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,u)){$e(a,e);continue}if(c===`attributename`&&ar(u,`href`)){$e(a,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){$e(a,e);continue}if(!ge&&ur(/\/>/i,u)){$e(a,e);continue}_e&&Qn([O,ee,te],e=>{u=or(u,e,` `)});let d=We(e.nodeName);if(!ot(d,c,u)){$e(a,e);continue}if(b&&typeof p==`object`&&typeof p.getAttributeType==`function`&&!o)switch(p.getAttributeType(d,c)){case`TrustedHTML`:u=b.createHTML(u);break;case`TrustedScriptURL`:u=b.createScriptURL(u);break}if(u!==l)try{o?e.setAttributeNS(o,a,u):e.setAttribute(a,u),nt(e)?Qe(e):er(t.removed)}catch{$e(a,e)}}it(D.afterSanitizeAttributes,e,null)},lt=function e(t){let n=null,r=tt(t);for(it(D.beforeSanitizeShadowDOM,t,null);n=r.nextNode();)it(D.uponSanitizeShadowNode,n,null),at(n),ct(n),n.content instanceof a&&e(n.content);it(D.afterSanitizeShadowDOM,t,null)};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,o=null,c=null,l=null;if(Ie=!e,Ie&&(e=`<!-->`),typeof e!=`string`&&!rt(e))if(typeof e.toString==`function`){if(e=e.toString(),typeof e!=`string`)throw dr(`dirty is not a string, aborting`)}else throw dr(`toString is not a function`);if(!t.isSupported)return e;if(be||Je(n),t.removed=[],typeof e==`string`&&(Ee=!1),Ee){if(e.nodeName){let t=We(e.nodeName);if(!oe[t]||de[t])throw dr(`root node is forbidden and cannot be sanitized in-place`)}}else if(e instanceof s)i=et(`<!---->`),o=i.ownerDocument.importNode(e,!0),o.nodeType===Br.element&&o.nodeName===`BODY`||o.nodeName===`HTML`?i=o:i.appendChild(o);else{if(!xe&&!_e&&!ye&&e.indexOf(`<`)===-1)return b&&Ce?b.createHTML(e):e;if(i=et(e),!i)return xe?null:Ce?x:``}i&&M&&Qe(i.firstChild);let u=tt(Ee?e:i);for(;c=u.nextNode();)at(c),ct(c),c.content instanceof a&<(c.content);if(Ee)return e;if(xe){if(Se)for(l=w.call(i.ownerDocument);i.firstChild;)l.appendChild(i.firstChild);else l=i;return(ce.shadowroot||ce.shadowrootmode)&&(l=E.call(r,l,!0)),l}let d=ye?i.outerHTML:i.innerHTML;return ye&&oe[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&ur(Lr,i.ownerDocument.doctype.name)&&(d=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
|
|
66
|
-
`+d),_e&&Qn([O,ee,te],e=>{d=or(d,e,` `)}),b&&Ce?b.createHTML(d):d},t.setConfig=function(){Je(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),be=!0},t.clearConfig=function(){Ge=null,be=!1},t.isValidAttribute=function(e,t,n){return Ge||Je({}),ot(We(e),We(t),n)},t.addHook=function(e,t){typeof t==`function`&&tr(D[e],t)},t.removeHook=function(e,t){if(t!==void 0){let n=$n(D[e],t);return n===-1?void 0:nr(D[e],n,1)[0]}return er(D[e])},t.removeHooks=function(e){D[e]=[]},t.removeAllHooks=function(){D=Ur()},t}var Gr=Wr(),Kr=Gr.sanitize.bind(Gr);Gr.isSupported,Gr.addHook.bind(Gr),Gr.removeHook.bind(Gr),Gr.removeHooks.bind(Gr),Gr.removeAllHooks.bind(Gr),Gr.setConfig.bind(Gr),Gr.clearConfig.bind(Gr),Gr.isValidAttribute.bind(Gr),Gr.version,Gr.removed;function qr(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function Jr(e,t){let n=qr(e);return t===`shtml`||([`js`,`javascript`,`ts`,`typescript`,`jsx`,`tsx`].includes(t)?n=Xr(n):t===`json`?n=Zr(n):[`bash`,`sh`,`shell`,`zsh`].includes(t)&&(n=Qr(n))),n}function Yr(e){let t=[];return{html:e.replace(/<span class="tok-(?:comment|string)">[\s\S]*?<\/span>/g,e=>{let n=String.fromCharCode(57344+t.length);return t.push(e),n}),restore:e=>e.replace(/[\ue000-\uf8ff]/g,e=>t[e.charCodeAt(0)-57344]??e)}}function Xr(e){e=e.replace(/(\/\/[^\n]*)/g,`<span class="tok-comment">$1</span>`),e=e.replace(/(\/\*[\s\S]*?\*\/)/g,`<span class="tok-comment">$1</span>`),e=e.replace(/("[^&]*?"|'[^&]*?'|`[^`]*?`)/g,`<span class="tok-string">$1</span>`);let t=Yr(e);return e=t.html,e=e.replace(RegExp(`\\b(${`const.let.var.function.return.if.else.for.while.class.extends.import.export.from.default.new.this.async.await.try.catch.throw.typeof.instanceof.interface.type.enum.implements.abstract.public.private.protected.readonly.static.void.null.undefined.true.false`.split(`.`).join(`|`)})\\b`,`g`),`<span class="tok-keyword">$1</span>`),e=e.replace(/\b(\d+\.?\d*)\b/g,`<span class="tok-number">$1</span>`),e=e.replace(/\b([a-zA-Z_$][\w$]*)\s*(?=\()/g,`<span class="tok-fn">$1</span>`),t.restore(e)}function Zr(e){return e=e.replace(/("[^&]*?")\s*:/g,`<span class="tok-keyword">$1</span>:`),e=e.replace(/:\s*("[^&]*?")/g,`: <span class="tok-string">$1</span>`),e=e.replace(/\b(\d+\.?\d*)\b/g,`<span class="tok-number">$1</span>`),e=e.replace(/\b(true|false|null)\b/g,`<span class="tok-keyword">$1</span>`),e}function Qr(e){return e=e.replace(/(#[^\n]*)/g,`<span class="tok-comment">$1</span>`),e=e.replace(/("[^&]*?"|'[^&]*?')/g,`<span class="tok-string">$1</span>`),e=e.replace(RegExp(`\\b(${[`if`,`then`,`else`,`fi`,`for`,`do`,`done`,`while`,`case`,`esac`,`echo`,`export`,`cd`,`ls`,`mkdir`,`rm`,`cp`,`mv`,`cat`,`grep`,`npm`,`node`,`git`].join(`|`)})\\b`,`g`),`<span class="tok-keyword">$1</span>`),e}var $r=new zn({gfm:!0,breaks:!0,async:!1,renderer:{code({text:e,lang:t}){let n=t??``,r=Jr(e,n);return`<pre><code${n?` class="language-${qr(n)}"`:``}>${r}</code></pre>\n`},link({href:e,title:t,tokens:n}){let r=e??``;if(r.startsWith(`javascript:`))return this.parser.parseInline(n);let i=t?` title="${qr(t)}"`:``,a=this.parser.parseInline(n);return`<a href="${qr(r)}"${i} target="_blank" rel="noopener noreferrer">${a}</a>`}}}),ei={ALLOWED_TAGS:`a.b.i.em.strong.p.br.code.pre.ul.ol.li.h1.h2.h3.h4.h5.h6.table.thead.tbody.tr.th.td.del.blockquote.hr.img.span.div.details.summary.input`.split(`.`),ALLOWED_ATTR:[`href`,`src`,`alt`,`title`,`class`,`target`,`rel`,`type`,`checked`,`disabled`],ALLOW_DATA_ATTR:!1};function ti(e){return Kr(e,ei)}function ni(e){return e.replace(/<a\s([^>]*?)>/g,(e,t)=>{let n=t;return/(^|\s)target\s*=/i.test(n)?n=n.replace(/(^|\s)target\s*=\s*(['"])[^'"]*\2/gi,`$1target="_blank"`):n+=` target="_blank"`,/(^|\s)rel\s*=/i.test(n)?n=n.replace(/(^|\s)rel\s*=\s*(['"])[^'"]*\2/gi,`$1rel="noopener noreferrer"`):n+=` rel="noopener noreferrer"`,`<a ${n}>`})}var ri=/<p><strong>Error:<\/strong>\s*([\s\S]*?)<\/p>/g;function ii(e){return ni(ti($r.parse(e)))}function ai(e){return e.replace(ri,(e,t)=>`<div class="msg__error" role="alert"><div class="msg__error-label">Error</div><div class="msg__error-body">${t}</div></div>`)}function oi(e){return ii(e)}function si(e){return ai(ii(e))}var ci=`browser-coding-agent`,li=1,ui=`sessions`;function di(){return new Promise((e,t)=>{let n=indexedDB.open(ci,li);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(ui)||e.createObjectStore(ui,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var fi=class{db=null;async init(){this.db=await di()}ensureDb(){if(!this.db)throw Error(`SessionStore not initialized. Call init() first.`);return this.db}async save(e){let t=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(ui,`readwrite`);i.objectStore(ui).put(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(ui,`readonly`).objectStore(ui).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async list(){let e=this.ensureDb();return new Promise((t,n)=>{let r=e.transaction(ui,`readonly`).objectStore(ui).getAll();r.onsuccess=()=>{t(r.result.sort((e,t)=>t.updatedAt-e.updatedAt).map(e=>e.id))},r.onerror=()=>n(r.error)})}async delete(e){let t=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(ui,`readwrite`);i.objectStore(ui).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async saveMessages(e,t){let n=await this.load(e),r=n?{...n,messages:t,updatedAt:Date.now()}:{id:e,messages:t,createdAt:Date.now(),updatedAt:Date.now()};await this.save(r)}},pi={html:`text/html`,htm:`text/html`,css:`text/css`,js:`application/javascript`,mjs:`application/javascript`,json:`application/json`,svg:`image/svg+xml`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,apng:`image/apng`,bmp:`image/bmp`,ico:`image/x-icon`,woff:`font/woff`,woff2:`font/woff2`,ttf:`font/ttf`,mp3:`audio/mpeg`,mp4:`video/mp4`,webm:`video/webm`,mov:`video/quicktime`,m4v:`video/x-m4v`,ogv:`video/ogg`,pdf:`application/pdf`,txt:`text/plain`,xml:`application/xml`,wasm:`application/wasm`};function mi(e){return pi[e.split(`.`).pop()?.toLowerCase()??``]??`application/octet-stream`}function hi(e){return e.startsWith(`image/`)}function gi(e){return e.startsWith(`video/`)}function _i(e){return hi(e)||gi(e)}function vi(e){return _i(mi(e))}var yi={"not-allowed":`Microphone access denied. Check Chrome site permissions.`,"no-speech":`No speech detected. Try again.`,"audio-capture":`No microphone found. Check your audio input device.`,network:`Voice input requires an internet connection.`,aborted:`Voice input was interrupted.`,"service-not-available":`Speech recognition service unavailable. Try again later.`,"start-failed":`Failed to start speech recognition.`,"not-supported":`Speech recognition is not supported in this browser.`};function bi(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function xi(){return typeof window>`u`?null:window.SpeechRecognition||window.webkitSpeechRecognition||null}var Si=class e{recognition=null;_isListening=!1;shouldBeListening=!1;options;debounceTimer=null;autoSendTimer=null;pendingTranscript=``;consecutiveRestarts=0;inactivityTimer=null;messageListener=null;popupWindowId=null;constructor(e){this.options=e}start(){if(this._isListening)return;this.debounceTimer&&=(clearTimeout(this.debounceTimer),null);let e=xi();if(!e){this.options.onError(`Speech recognition is not supported in this browser.`),this.options.onStateChange(`error`);return}this.shouldBeListening=!0,this.pendingTranscript=``,this.consecutiveRestarts=0,this.cancelAutoSend(),this.resetInactivityTimer(),navigator.mediaDevices?.getUserMedia?navigator.mediaDevices.getUserMedia({audio:!0}).then(t=>{for(let e of t.getTracks())e.stop();this.shouldBeListening&&this.startRecognition(new e)}).catch(e=>{if(this.shouldBeListening)if(bi())this.startExtensionPopup();else{this.shouldBeListening=!1;let t=e?.name,n=yi[`not-allowed`];t===`NotFoundError`?n=yi[`audio-capture`]:t===`NotReadableError`&&(n=`Microphone is in use by another app. Try again.`),this.options.onError(n),this.options.onStateChange(`error`)}}):this.startRecognition(new e)}startExtensionPopup(){let e=this.options.lang??`en-US`,t=chrome.runtime.getURL(`voice-popup.html?lang=${encodeURIComponent(e)}`);chrome.windows.create({url:t,type:`popup`,width:300,height:68,focused:!0}).then(e=>{this.shouldBeListening&&(this.setupExtensionListener(),e?.id&&(this.popupWindowId=e.id))}).catch(()=>{this.shouldBeListening=!1,this.options.onError(`Failed to open voice input window.`),this.options.onStateChange(`error`)})}setupExtensionListener(){this.messageListener||(this.messageListener=e=>{if(e.source===`voice-popup`)switch(e.type){case`speech-result`:if(e.isFinal)this.pendingTranscript+=(this.pendingTranscript?` `:``)+e.text,this.options.onTranscript(this.pendingTranscript,!0),this.scheduleAutoSend();else{let t=this.pendingTranscript?this.pendingTranscript+` `+e.text:e.text;this.options.onTranscript(t,!1),this.cancelAutoSend()}break;case`speech-error`:{let t=yi[e.error]??`Speech recognition error: ${e.error}`;this.options.onError(t),e.fatal&&(this._isListening=!1,this.shouldBeListening=!1,this.popupWindowId=null,this.options.onStateChange(`error`));break}case`speech-state`:e.state===`listening`&&(this._isListening=!0,this.options.onStateChange(`listening`));break;case`speech-end`:this._isListening=!1,this.shouldBeListening=!1,this.popupWindowId=null,this.options.onStateChange(`idle`);break}},chrome.runtime.onMessage.addListener(this.messageListener))}removeExtensionListener(){this.messageListener&&=(chrome.runtime.onMessage.removeListener(this.messageListener),null)}startRecognition(e){this.recognition=e,this.recognition.continuous=!0,this.recognition.interimResults=!0,this.recognition.lang=this.options.lang??`en-US`,this.recognition.onresult=e=>{this.consecutiveRestarts=0,this.resetInactivityTimer();let t=``,n=``;for(let r=e.resultIndex;r<e.results.length;r++){let i=e.results[r];i.isFinal?n+=i[0].transcript:t+=i[0].transcript}if(n)this.pendingTranscript+=(this.pendingTranscript?` `:``)+n,this.options.onTranscript(this.pendingTranscript,!0),this.scheduleAutoSend();else if(t){let e=this.pendingTranscript?this.pendingTranscript+` `+t:t;this.options.onTranscript(e,!1),this.cancelAutoSend()}},this.recognition.onerror=e=>{let t=e.error,n=yi[t]??`Speech recognition error: ${t}`;if(t===`no-speech`){this.options.onError(n);return}t!==`aborted`&&(this._isListening=!1,this.shouldBeListening=!1,this.options.onError(n),this.options.onStateChange(`error`))},this.recognition.onend=()=>{if(this._isListening=!1,this.recognition&&=(this.recognition.onresult=null,this.recognition.onerror=null,this.recognition.onend=null,null),this.shouldBeListening){this.consecutiveRestarts++;let e=Math.min(300*2**(this.consecutiveRestarts-1),5e3),t=xi();this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.shouldBeListening&&t?this.startRecognition(new t):this.shouldBeListening&&(this.shouldBeListening=!1,this.options.onStateChange(`idle`))},e);return}this.options.onStateChange(`idle`)};try{this.recognition.start(),this._isListening=!0,this.options.onStateChange(`listening`)}catch{this.shouldBeListening=!1,this.options.onError(`Failed to start speech recognition.`),this.options.onStateChange(`error`)}}static SEND_DELAY_MS=2500;static INACTIVITY_TIMEOUT_MS=12e4;scheduleAutoSend(){this.cancelAutoSend(),this.options.autoSend&&(this.autoSendTimer=setTimeout(()=>{this.autoSendTimer=null;let e=this.pendingTranscript.trim();e&&(this.pendingTranscript=``,this.options.onAutoSend(e))},e.SEND_DELAY_MS))}cancelAutoSend(){this.autoSendTimer&&=(clearTimeout(this.autoSendTimer),null)}resetInactivityTimer(){this.clearInactivityTimer(),this.options.onAutoDisable&&(this.inactivityTimer=setTimeout(()=>{this.inactivityTimer=null,this.stop(),this.options.onAutoDisable?.()},e.INACTIVITY_TIMEOUT_MS))}clearInactivityTimer(){this.inactivityTimer&&=(clearTimeout(this.inactivityTimer),null)}stop(){if(this.shouldBeListening=!1,this.cancelAutoSend(),this.clearInactivityTimer(),this.pendingTranscript=``,this.debounceTimer&&=(clearTimeout(this.debounceTimer),null),this.popupWindowId!=null){try{chrome.runtime.sendMessage({target:`voice-popup`,type:`voice-stop`})}catch{}chrome.windows.remove(this.popupWindowId).catch(()=>{}),this.popupWindowId=null}else if(this.recognition){this.recognition.onresult=null,this.recognition.onerror=null,this.recognition.onend=null;try{this.recognition.stop()}catch{}this.recognition=null}this._isListening=!1,this.options.onStateChange(`idle`)}toggle(){this._isListening||this.shouldBeListening?this.stop():this.start()}isListening(){return this._isListening||this.shouldBeListening}setAutoSend(e){this.options.autoSend=e}destroy(){this.stop(),this.removeExtensionListener(),this.recognition=null}},Ci={autoSend:`voice-auto-send`,lang:`voice-lang`};function wi(){return localStorage.getItem(Ci.lang)||`en-US`}var Ti=`slicc-theme`,Ei=new Set([`dark`,`light`,`system`]);function Di(){let e=localStorage.getItem(Ti);return e&&Ei.has(e)?e:`system`}function Oi(){return document.documentElement.classList.contains(`theme-light`)}var ki=new Set;function Ai(e){e&&ki.add(e)}function ji(e){e&&ki.delete(e)}function Mi(){let e=Oi();for(let t of ki)try{t.postMessage({type:`slicc-theme`,isLight:e},`*`)}catch{ki.delete(t)}}function Ni(){let e=Di(),t=e===`light`;e===`system`&&(t=window.matchMedia?.(`(prefers-color-scheme: light)`).matches??!1),document.documentElement.classList.toggle(`theme-light`,t),Mi()}var Pi,Fi;function Ii(){Ni(),Pi=window.matchMedia?.(`(prefers-color-scheme: light)`),Pi?.addEventListener?.(`change`,()=>{Di()===`system`&&Ni()}),typeof MutationObserver<`u`&&!Fi&&(Fi=new MutationObserver(()=>Mi()),Fi.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}))}var Li=typeof chrome<`u`&&!!chrome?.runtime?.id,Ri=/<script\b([^>]*)\bsrc\s*=\s*["'](https?:\/\/[^"']+)["']([^>]*)><\/script>/gi;async function zi(e){let t=[],n;for(;(n=Ri.exec(e))!==null;)t.push({full:n[0],url:n[2],index:n.index});if(Ri.lastIndex=0,t.length===0)return e;let r=await Promise.all(t.map(async e=>{try{let t=await fetch(e.url);if(!t.ok)throw Error(`HTTP ${t.status}`);return{...e,text:await t.text()}}catch(t){let n=t instanceof Error?t.message:String(t);return{...e,text:`console.error('[sprinkle] Failed to load ${e.url}: ${n}')`}}})),i=e;for(let e=r.length-1;e>=0;e--){let{full:t,text:n}=r[e],a=n.replace(/<\/script/gi,`<\\/script`);i=i.replace(t,()=>`<script>${a}<\/script>`)}return i}function Bi(e){let t=e.trimStart().toLowerCase();return t.startsWith(`<!doctype`)||t.startsWith(`<html`)}var Vi=class e{container;bridge;scripts=[];iframe=null;static cachedLucideScript=null;static lucideScriptPromise=null;messageHandler=null;constructor(e,t){this.container=e,this.bridge=t}async render(e,t){this.dispose(),Li?await this.renderInSandbox(e,t,Bi(e)):Bi(e)?await this.renderFullDoc(e,t):this.renderInline(e,t)}async renderInSandbox(e,t,n=!1){let r=document.createElement(`iframe`);r.src=chrome.runtime.getURL(`sprinkle-sandbox.html`),r.style.cssText=`width: 100%; flex: 1; border: none; min-height: 0;`,this.iframe=r,console.log(`[sprinkle-renderer] creating sandbox iframe`,r.src),await new Promise((e,t)=>{let n=setTimeout(()=>{console.error(`[sprinkle-renderer] iframe load timed out after 5s`),t(Error(`sprinkle sandbox iframe load timed out`))},5e3);r.addEventListener(`load`,()=>{clearTimeout(n),console.log(`[sprinkle-renderer] iframe loaded, contentWindow:`,!!r.contentWindow),Ai(r.contentWindow),e()},{once:!0}),r.addEventListener(`error`,e=>{clearTimeout(n),console.error(`[sprinkle-renderer] iframe error:`,e),t(Error(`sprinkle sandbox iframe failed to load`))},{once:!0}),this.container.appendChild(r)}),this.messageHandler=e=>{if(e.source!==r.contentWindow)return;let n=e.data;if(n?.type){if(n.type===`sprinkle-lick`)this.bridge.lick({action:n.action,data:n.data});else if(n.type===`sprinkle-set-state`)this.bridge.setState(n.data);else if(n.type===`sprinkle-close`)this.bridge.close();else if(n.type===`sprinkle-stop-cone`)this.bridge.stopCone();else if(n.type===`sprinkle-storage-set`)try{localStorage.setItem(`slicc-sprinkle-ls:${t}:${n.key}`,n.value)}catch(e){console.warn(`[sprinkle-renderer] localStorage setItem failed:`,n.key,e)}else if(n.type===`sprinkle-storage-remove`)try{localStorage.removeItem(`slicc-sprinkle-ls:${t}:${n.key}`)}catch(e){console.warn(`[sprinkle-renderer] localStorage removeItem failed:`,n.key,e)}else if(n.type===`sprinkle-storage-clear`){let e=`slicc-sprinkle-ls:${t}:`;for(let t=localStorage.length-1;t>=0;t--){let n=localStorage.key(t);n?.startsWith(e)&&localStorage.removeItem(n)}}else if(n.type===`sprinkle-open`)this.bridge.open(n.path,n.projectRoot?{projectRoot:n.projectRoot}:void 0);else if(n.type===`sprinkle-readfile`)this.bridge.readFile(n.path).then(e=>r.contentWindow?.postMessage({type:`sprinkle-readfile-response`,id:n.id,content:e},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-readfile-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`));else if(n.type===`sprinkle-writefile`)this.bridge.writeFile(n.path,n.content).then(()=>r.contentWindow?.postMessage({type:`sprinkle-writefile-response`,id:n.id},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-writefile-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`));else if(n.type===`sprinkle-readdir`)this.bridge.readDir(n.path).then(e=>r.contentWindow?.postMessage({type:`sprinkle-readdir-response`,id:n.id,entries:e},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-readdir-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`));else if(n.type===`sprinkle-exists`)this.bridge.exists(n.path).then(e=>r.contentWindow?.postMessage({type:`sprinkle-exists-response`,id:n.id,exists:e},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-exists-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`));else if(n.type===`sprinkle-stat`)this.bridge.stat(n.path).then(e=>r.contentWindow?.postMessage({type:`sprinkle-stat-response`,id:n.id,stat:e},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-stat-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`));else if(n.type===`sprinkle-mkdir`)this.bridge.mkdir(n.path).then(()=>r.contentWindow?.postMessage({type:`sprinkle-mkdir-response`,id:n.id},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-mkdir-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`));else if(n.type===`sprinkle-rm`)this.bridge.rm(n.path).then(()=>r.contentWindow?.postMessage({type:`sprinkle-rm-response`,id:n.id},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-rm-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`));else if(n.type===`sprinkle-fetch-script`){let e=n.url,t=n.id;fetch(e).then(e=>e.ok?e.text():Promise.reject(Error(`HTTP ${e.status}`))).then(n=>{r.contentWindow?.postMessage({type:`sprinkle-fetch-script-response`,id:t,url:e,text:n},`*`)}).catch(n=>{r.contentWindow?.postMessage({type:`sprinkle-fetch-script-response`,id:t,url:e,error:n instanceof Error?n.message:String(n)},`*`)})}}},window.addEventListener(`message`,this.messageHandler);let i=this.collectThemeCSS(),a={},o=`slicc-sprinkle-ls:${t}:`;for(let e=0;e<localStorage.length;e++){let t=localStorage.key(e);t?.startsWith(o)&&(a[t.slice(o.length)]=localStorage.getItem(t)??``)}let s=this.bridge.getState(),c=``,l=``;if(n){let t=[];e.includes(`<slicc-editor`)&&t.push(fetch(chrome.runtime.getURL(`slicc-editor.js`)).then(e=>e.ok?e.text():``).then(e=>{c=e}).catch(()=>{})),e.includes(`<slicc-diff`)&&t.push(fetch(chrome.runtime.getURL(`slicc-diff.js`)).then(e=>e.ok?e.text():``).then(e=>{l=e}).catch(()=>{})),await Promise.all(t)}let u=await this.getLucideScript(),d=n?await zi(e):e;r.contentWindow.postMessage({type:`sprinkle-render`,content:d,name:t,themeCSS:i,savedState:s,savedStorage:a,fullDoc:n,editorScript:c,diffScript:l,lucideScript:u,isLight:Oi()},`*`)}pushUpdate(e){this.iframe?.contentWindow&&this.iframe.contentWindow.postMessage({type:`sprinkle-update`,data:e},`*`)}collectThemeCSS(){return Ui()}generateBridgeScript(){return`(function() {
|
|
66
|
+
`+d),_e&&Qn([O,ee,te],e=>{d=or(d,e,` `)}),b&&Ce?b.createHTML(d):d},t.setConfig=function(){Je(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),be=!0},t.clearConfig=function(){Ge=null,be=!1},t.isValidAttribute=function(e,t,n){return Ge||Je({}),ot(We(e),We(t),n)},t.addHook=function(e,t){typeof t==`function`&&tr(D[e],t)},t.removeHook=function(e,t){if(t!==void 0){let n=$n(D[e],t);return n===-1?void 0:nr(D[e],n,1)[0]}return er(D[e])},t.removeHooks=function(e){D[e]=[]},t.removeAllHooks=function(){D=Ur()},t}var Gr=Wr(),Kr=Gr.sanitize.bind(Gr);Gr.isSupported,Gr.addHook.bind(Gr),Gr.removeHook.bind(Gr),Gr.removeHooks.bind(Gr),Gr.removeAllHooks.bind(Gr),Gr.setConfig.bind(Gr),Gr.clearConfig.bind(Gr),Gr.isValidAttribute.bind(Gr),Gr.version,Gr.removed;function qr(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function Jr(e,t){let n=qr(e);return t===`shtml`||([`js`,`javascript`,`ts`,`typescript`,`jsx`,`tsx`].includes(t)?n=Xr(n):t===`json`?n=Zr(n):[`bash`,`sh`,`shell`,`zsh`].includes(t)&&(n=Qr(n))),n}function Yr(e){let t=[];return{html:e.replace(/<span class="tok-(?:comment|string)">[\s\S]*?<\/span>/g,e=>{let n=String.fromCharCode(57344+t.length);return t.push(e),n}),restore:e=>e.replace(/[\ue000-\uf8ff]/g,e=>t[e.charCodeAt(0)-57344]??e)}}function Xr(e){e=e.replace(/(\/\/[^\n]*)/g,`<span class="tok-comment">$1</span>`),e=e.replace(/(\/\*[\s\S]*?\*\/)/g,`<span class="tok-comment">$1</span>`),e=e.replace(/("[^&]*?"|'[^&]*?'|`[^`]*?`)/g,`<span class="tok-string">$1</span>`);let t=Yr(e);return e=t.html,e=e.replace(RegExp(`\\b(${`const.let.var.function.return.if.else.for.while.class.extends.import.export.from.default.new.this.async.await.try.catch.throw.typeof.instanceof.interface.type.enum.implements.abstract.public.private.protected.readonly.static.void.null.undefined.true.false`.split(`.`).join(`|`)})\\b`,`g`),`<span class="tok-keyword">$1</span>`),e=e.replace(/\b(\d+\.?\d*)\b/g,`<span class="tok-number">$1</span>`),e=e.replace(/\b([a-zA-Z_$][\w$]*)\s*(?=\()/g,`<span class="tok-fn">$1</span>`),t.restore(e)}function Zr(e){return e=e.replace(/("[^&]*?")\s*:/g,`<span class="tok-keyword">$1</span>:`),e=e.replace(/:\s*("[^&]*?")/g,`: <span class="tok-string">$1</span>`),e=e.replace(/\b(\d+\.?\d*)\b/g,`<span class="tok-number">$1</span>`),e=e.replace(/\b(true|false|null)\b/g,`<span class="tok-keyword">$1</span>`),e}function Qr(e){return e=e.replace(/(#[^\n]*)/g,`<span class="tok-comment">$1</span>`),e=e.replace(/("[^&]*?"|'[^&]*?')/g,`<span class="tok-string">$1</span>`),e=e.replace(RegExp(`\\b(${[`if`,`then`,`else`,`fi`,`for`,`do`,`done`,`while`,`case`,`esac`,`echo`,`export`,`cd`,`ls`,`mkdir`,`rm`,`cp`,`mv`,`cat`,`grep`,`npm`,`node`,`git`].join(`|`)})\\b`,`g`),`<span class="tok-keyword">$1</span>`),e}var $r=new zn({gfm:!0,breaks:!0,async:!1,renderer:{code({text:e,lang:t}){let n=t??``,r=Jr(e,n);return`<pre><code${n?` class="language-${qr(n)}"`:``}>${r}</code></pre>\n`},link({href:e,title:t,tokens:n}){let r=e??``;if(r.startsWith(`javascript:`))return this.parser.parseInline(n);let i=t?` title="${qr(t)}"`:``,a=this.parser.parseInline(n);return`<a href="${qr(r)}"${i} target="_blank" rel="noopener noreferrer">${a}</a>`},image({href:e,title:t,text:n}){let r=e??``,i=n?` alt="${qr(n)}"`:``,a=t?` title="${qr(t)}"`:``;return`<img src="${qr(r)}"${i}${a}>`}}}),ei={ALLOWED_TAGS:`a.b.i.em.strong.p.br.code.pre.ul.ol.li.h1.h2.h3.h4.h5.h6.table.thead.tbody.tr.th.td.del.blockquote.hr.img.span.div.details.summary.input`.split(`.`),ALLOWED_ATTR:[`href`,`src`,`alt`,`title`,`class`,`target`,`rel`,`type`,`checked`,`disabled`],ALLOW_DATA_ATTR:!1};function ti(e){return Kr(e,ei)}function ni(e){return e.replace(/<a\s([^>]*?)>/g,(e,t)=>{let n=t;return/(^|\s)target\s*=/i.test(n)?n=n.replace(/(^|\s)target\s*=\s*(['"])[^'"]*\2/gi,`$1target="_blank"`):n+=` target="_blank"`,/(^|\s)rel\s*=/i.test(n)?n=n.replace(/(^|\s)rel\s*=\s*(['"])[^'"]*\2/gi,`$1rel="noopener noreferrer"`):n+=` rel="noopener noreferrer"`,`<a ${n}>`})}var ri=/<p><strong>Error:<\/strong>\s*([\s\S]*?)<\/p>/g;function ii(e){return ni(ti($r.parse(e)))}function ai(e){return e.replace(ri,(e,t)=>`<div class="msg__error" role="alert"><div class="msg__error-label">Error</div><div class="msg__error-body">${t}</div></div>`)}function oi(e){return ii(e)}function si(e){return ai(ii(e))}var ci=`browser-coding-agent`,li=1,ui=`sessions`;function di(){return new Promise((e,t)=>{let n=indexedDB.open(ci,li);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(ui)||e.createObjectStore(ui,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var fi=class{db=null;async init(){this.db=await di()}ensureDb(){if(!this.db)throw Error(`SessionStore not initialized. Call init() first.`);return this.db}async save(e){let t=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(ui,`readwrite`);i.objectStore(ui).put(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(ui,`readonly`).objectStore(ui).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async list(){let e=this.ensureDb();return new Promise((t,n)=>{let r=e.transaction(ui,`readonly`).objectStore(ui).getAll();r.onsuccess=()=>{t(r.result.sort((e,t)=>t.updatedAt-e.updatedAt).map(e=>e.id))},r.onerror=()=>n(r.error)})}async delete(e){let t=this.ensureDb();return new Promise((n,r)=>{let i=t.transaction(ui,`readwrite`);i.objectStore(ui).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async saveMessages(e,t){let n=await this.load(e),r=n?{...n,messages:t,updatedAt:Date.now()}:{id:e,messages:t,createdAt:Date.now(),updatedAt:Date.now()};await this.save(r)}},pi={html:`text/html`,htm:`text/html`,css:`text/css`,js:`application/javascript`,mjs:`application/javascript`,json:`application/json`,svg:`image/svg+xml`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,apng:`image/apng`,bmp:`image/bmp`,ico:`image/x-icon`,woff:`font/woff`,woff2:`font/woff2`,ttf:`font/ttf`,mp3:`audio/mpeg`,mp4:`video/mp4`,webm:`video/webm`,mov:`video/quicktime`,m4v:`video/x-m4v`,ogv:`video/ogg`,pdf:`application/pdf`,txt:`text/plain`,xml:`application/xml`,wasm:`application/wasm`};function mi(e){return pi[e.split(`.`).pop()?.toLowerCase()??``]??`application/octet-stream`}function hi(e){return e.startsWith(`image/`)}function gi(e){return e.startsWith(`video/`)}function _i(e){return hi(e)||gi(e)}function vi(e){return _i(mi(e))}var yi={"not-allowed":`Microphone access denied. Check Chrome site permissions.`,"no-speech":`No speech detected. Try again.`,"audio-capture":`No microphone found. Check your audio input device.`,network:`Voice input requires an internet connection.`,aborted:`Voice input was interrupted.`,"service-not-available":`Speech recognition service unavailable. Try again later.`,"start-failed":`Failed to start speech recognition.`,"not-supported":`Speech recognition is not supported in this browser.`};function bi(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function xi(){return typeof window>`u`?null:window.SpeechRecognition||window.webkitSpeechRecognition||null}var Si=class e{recognition=null;_isListening=!1;shouldBeListening=!1;options;debounceTimer=null;autoSendTimer=null;pendingTranscript=``;consecutiveRestarts=0;inactivityTimer=null;messageListener=null;popupWindowId=null;constructor(e){this.options=e}start(){if(this._isListening)return;this.debounceTimer&&=(clearTimeout(this.debounceTimer),null);let e=xi();if(!e){this.options.onError(`Speech recognition is not supported in this browser.`),this.options.onStateChange(`error`);return}this.shouldBeListening=!0,this.pendingTranscript=``,this.consecutiveRestarts=0,this.cancelAutoSend(),this.resetInactivityTimer(),navigator.mediaDevices?.getUserMedia?navigator.mediaDevices.getUserMedia({audio:!0}).then(t=>{for(let e of t.getTracks())e.stop();this.shouldBeListening&&this.startRecognition(new e)}).catch(e=>{if(this.shouldBeListening)if(bi())this.startExtensionPopup();else{this.shouldBeListening=!1;let t=e?.name,n=yi[`not-allowed`];t===`NotFoundError`?n=yi[`audio-capture`]:t===`NotReadableError`&&(n=`Microphone is in use by another app. Try again.`),this.options.onError(n),this.options.onStateChange(`error`)}}):this.startRecognition(new e)}startExtensionPopup(){let e=this.options.lang??`en-US`,t=chrome.runtime.getURL(`voice-popup.html?lang=${encodeURIComponent(e)}`);chrome.windows.create({url:t,type:`popup`,width:300,height:68,focused:!0}).then(e=>{this.shouldBeListening&&(this.setupExtensionListener(),e?.id&&(this.popupWindowId=e.id))}).catch(()=>{this.shouldBeListening=!1,this.options.onError(`Failed to open voice input window.`),this.options.onStateChange(`error`)})}setupExtensionListener(){this.messageListener||(this.messageListener=e=>{if(e.source===`voice-popup`)switch(e.type){case`speech-result`:if(e.isFinal)this.pendingTranscript+=(this.pendingTranscript?` `:``)+e.text,this.options.onTranscript(this.pendingTranscript,!0),this.scheduleAutoSend();else{let t=this.pendingTranscript?this.pendingTranscript+` `+e.text:e.text;this.options.onTranscript(t,!1),this.cancelAutoSend()}break;case`speech-error`:{let t=yi[e.error]??`Speech recognition error: ${e.error}`;this.options.onError(t),e.fatal&&(this._isListening=!1,this.shouldBeListening=!1,this.popupWindowId=null,this.options.onStateChange(`error`));break}case`speech-state`:e.state===`listening`&&(this._isListening=!0,this.options.onStateChange(`listening`));break;case`speech-end`:this._isListening=!1,this.shouldBeListening=!1,this.popupWindowId=null,this.options.onStateChange(`idle`);break}},chrome.runtime.onMessage.addListener(this.messageListener))}removeExtensionListener(){this.messageListener&&=(chrome.runtime.onMessage.removeListener(this.messageListener),null)}startRecognition(e){this.recognition=e,this.recognition.continuous=!0,this.recognition.interimResults=!0,this.recognition.lang=this.options.lang??`en-US`,this.recognition.onresult=e=>{this.consecutiveRestarts=0,this.resetInactivityTimer();let t=``,n=``;for(let r=e.resultIndex;r<e.results.length;r++){let i=e.results[r];i.isFinal?n+=i[0].transcript:t+=i[0].transcript}if(n)this.pendingTranscript+=(this.pendingTranscript?` `:``)+n,this.options.onTranscript(this.pendingTranscript,!0),this.scheduleAutoSend();else if(t){let e=this.pendingTranscript?this.pendingTranscript+` `+t:t;this.options.onTranscript(e,!1),this.cancelAutoSend()}},this.recognition.onerror=e=>{let t=e.error,n=yi[t]??`Speech recognition error: ${t}`;if(t===`no-speech`){this.options.onError(n);return}t!==`aborted`&&(this._isListening=!1,this.shouldBeListening=!1,this.options.onError(n),this.options.onStateChange(`error`))},this.recognition.onend=()=>{if(this._isListening=!1,this.recognition&&=(this.recognition.onresult=null,this.recognition.onerror=null,this.recognition.onend=null,null),this.shouldBeListening){this.consecutiveRestarts++;let e=Math.min(300*2**(this.consecutiveRestarts-1),5e3),t=xi();this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.shouldBeListening&&t?this.startRecognition(new t):this.shouldBeListening&&(this.shouldBeListening=!1,this.options.onStateChange(`idle`))},e);return}this.options.onStateChange(`idle`)};try{this.recognition.start(),this._isListening=!0,this.options.onStateChange(`listening`)}catch{this.shouldBeListening=!1,this.options.onError(`Failed to start speech recognition.`),this.options.onStateChange(`error`)}}static SEND_DELAY_MS=2500;static INACTIVITY_TIMEOUT_MS=12e4;scheduleAutoSend(){this.cancelAutoSend(),this.options.autoSend&&(this.autoSendTimer=setTimeout(()=>{this.autoSendTimer=null;let e=this.pendingTranscript.trim();e&&(this.pendingTranscript=``,this.options.onAutoSend(e))},e.SEND_DELAY_MS))}cancelAutoSend(){this.autoSendTimer&&=(clearTimeout(this.autoSendTimer),null)}resetInactivityTimer(){this.clearInactivityTimer(),this.options.onAutoDisable&&(this.inactivityTimer=setTimeout(()=>{this.inactivityTimer=null,this.stop(),this.options.onAutoDisable?.()},e.INACTIVITY_TIMEOUT_MS))}clearInactivityTimer(){this.inactivityTimer&&=(clearTimeout(this.inactivityTimer),null)}stop(){if(this.shouldBeListening=!1,this.cancelAutoSend(),this.clearInactivityTimer(),this.pendingTranscript=``,this.debounceTimer&&=(clearTimeout(this.debounceTimer),null),this.popupWindowId!=null){try{chrome.runtime.sendMessage({target:`voice-popup`,type:`voice-stop`})}catch{}chrome.windows.remove(this.popupWindowId).catch(()=>{}),this.popupWindowId=null}else if(this.recognition){this.recognition.onresult=null,this.recognition.onerror=null,this.recognition.onend=null;try{this.recognition.stop()}catch{}this.recognition=null}this._isListening=!1,this.options.onStateChange(`idle`)}toggle(){this._isListening||this.shouldBeListening?this.stop():this.start()}isListening(){return this._isListening||this.shouldBeListening}setAutoSend(e){this.options.autoSend=e}destroy(){this.stop(),this.removeExtensionListener(),this.recognition=null}},Ci={autoSend:`voice-auto-send`,lang:`voice-lang`};function wi(){return localStorage.getItem(Ci.lang)||`en-US`}var Ti=`slicc-theme`,Ei=new Set([`dark`,`light`,`system`]);function Di(){let e=localStorage.getItem(Ti);return e&&Ei.has(e)?e:`system`}function Oi(){return document.documentElement.classList.contains(`theme-light`)}var ki=new Set;function Ai(e){e&&ki.add(e)}function ji(e){e&&ki.delete(e)}function Mi(){let e=Oi();for(let t of ki)try{t.postMessage({type:`slicc-theme`,isLight:e},`*`)}catch{ki.delete(t)}}function Ni(){let e=Di(),t=e===`light`;e===`system`&&(t=window.matchMedia?.(`(prefers-color-scheme: light)`).matches??!1),document.documentElement.classList.toggle(`theme-light`,t),Mi()}var Pi,Fi;function Ii(){Ni(),Pi=window.matchMedia?.(`(prefers-color-scheme: light)`),Pi?.addEventListener?.(`change`,()=>{Di()===`system`&&Ni()}),typeof MutationObserver<`u`&&!Fi&&(Fi=new MutationObserver(()=>Mi()),Fi.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}))}var Li=typeof chrome<`u`&&!!chrome?.runtime?.id,Ri=/<script\b([^>]*)\bsrc\s*=\s*["'](https?:\/\/[^"']+)["']([^>]*)><\/script>/gi;async function zi(e){let t=[],n;for(;(n=Ri.exec(e))!==null;)t.push({full:n[0],url:n[2],index:n.index});if(Ri.lastIndex=0,t.length===0)return e;let r=await Promise.all(t.map(async e=>{try{let t=await fetch(e.url);if(!t.ok)throw Error(`HTTP ${t.status}`);return{...e,text:await t.text()}}catch(t){let n=t instanceof Error?t.message:String(t);return{...e,text:`console.error('[sprinkle] Failed to load ${e.url}: ${n}')`}}})),i=e;for(let e=r.length-1;e>=0;e--){let{full:t,text:n}=r[e],a=n.replace(/<\/script/gi,`<\\/script`);i=i.replace(t,()=>`<script>${a}<\/script>`)}return i}function Bi(e){let t=e.trimStart().toLowerCase();return t.startsWith(`<!doctype`)||t.startsWith(`<html`)}var Vi=class e{container;bridge;scripts=[];iframe=null;static cachedLucideScript=null;static lucideScriptPromise=null;messageHandler=null;constructor(e,t){this.container=e,this.bridge=t}async render(e,t){this.dispose(),Li?await this.renderInSandbox(e,t,Bi(e)):Bi(e)?await this.renderFullDoc(e,t):this.renderInline(e,t)}async renderInSandbox(e,t,n=!1){let r=document.createElement(`iframe`);r.src=chrome.runtime.getURL(`sprinkle-sandbox.html`),r.style.cssText=`width: 100%; flex: 1; border: none; min-height: 0;`,this.iframe=r,console.log(`[sprinkle-renderer] creating sandbox iframe`,r.src),await new Promise((e,t)=>{let n=setTimeout(()=>{console.error(`[sprinkle-renderer] iframe load timed out after 5s`),t(Error(`sprinkle sandbox iframe load timed out`))},5e3);r.addEventListener(`load`,()=>{clearTimeout(n),console.log(`[sprinkle-renderer] iframe loaded, contentWindow:`,!!r.contentWindow),Ai(r.contentWindow),e()},{once:!0}),r.addEventListener(`error`,e=>{clearTimeout(n),console.error(`[sprinkle-renderer] iframe error:`,e),t(Error(`sprinkle sandbox iframe failed to load`))},{once:!0}),this.container.appendChild(r)}),this.messageHandler=e=>{if(e.source!==r.contentWindow)return;let n=e.data;if(n?.type){if(n.type===`sprinkle-lick`)this.bridge.lick({action:n.action,data:n.data});else if(n.type===`sprinkle-set-state`)this.bridge.setState(n.data);else if(n.type===`sprinkle-close`)this.bridge.close();else if(n.type===`sprinkle-stop-cone`)this.bridge.stopCone();else if(n.type===`sprinkle-storage-set`)try{localStorage.setItem(`slicc-sprinkle-ls:${t}:${n.key}`,n.value)}catch(e){console.warn(`[sprinkle-renderer] localStorage setItem failed:`,n.key,e)}else if(n.type===`sprinkle-storage-remove`)try{localStorage.removeItem(`slicc-sprinkle-ls:${t}:${n.key}`)}catch(e){console.warn(`[sprinkle-renderer] localStorage removeItem failed:`,n.key,e)}else if(n.type===`sprinkle-storage-clear`){let e=`slicc-sprinkle-ls:${t}:`;for(let t=localStorage.length-1;t>=0;t--){let n=localStorage.key(t);n?.startsWith(e)&&localStorage.removeItem(n)}}else if(n.type===`sprinkle-open`)this.bridge.open(n.path,n.projectRoot?{projectRoot:n.projectRoot}:void 0);else if(n.type===`sprinkle-readfile`)this.bridge.readFile(n.path).then(e=>r.contentWindow?.postMessage({type:`sprinkle-readfile-response`,id:n.id,content:e},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-readfile-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`));else if(n.type===`sprinkle-writefile`)this.bridge.writeFile(n.path,n.content).then(()=>r.contentWindow?.postMessage({type:`sprinkle-writefile-response`,id:n.id},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-writefile-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`));else if(n.type===`sprinkle-readdir`)this.bridge.readDir(n.path).then(e=>r.contentWindow?.postMessage({type:`sprinkle-readdir-response`,id:n.id,entries:e},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-readdir-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`));else if(n.type===`sprinkle-exists`)this.bridge.exists(n.path).then(e=>r.contentWindow?.postMessage({type:`sprinkle-exists-response`,id:n.id,exists:e},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-exists-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`));else if(n.type===`sprinkle-stat`)this.bridge.stat(n.path).then(e=>r.contentWindow?.postMessage({type:`sprinkle-stat-response`,id:n.id,stat:e},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-stat-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`));else if(n.type===`sprinkle-mkdir`)this.bridge.mkdir(n.path).then(()=>r.contentWindow?.postMessage({type:`sprinkle-mkdir-response`,id:n.id},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-mkdir-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`));else if(n.type===`sprinkle-rm`)this.bridge.rm(n.path).then(()=>r.contentWindow?.postMessage({type:`sprinkle-rm-response`,id:n.id},`*`),e=>r.contentWindow?.postMessage({type:`sprinkle-rm-response`,id:n.id,error:e instanceof Error?e.message:String(e)},`*`));else if(n.type===`sprinkle-fetch-script`){let e=n.url,t=n.id;fetch(e).then(e=>e.ok?e.text():Promise.reject(Error(`HTTP ${e.status}`))).then(n=>{r.contentWindow?.postMessage({type:`sprinkle-fetch-script-response`,id:t,url:e,text:n},`*`)}).catch(n=>{r.contentWindow?.postMessage({type:`sprinkle-fetch-script-response`,id:t,url:e,error:n instanceof Error?n.message:String(n)},`*`)})}}},window.addEventListener(`message`,this.messageHandler);let i=this.collectThemeCSS(),a={},o=`slicc-sprinkle-ls:${t}:`;for(let e=0;e<localStorage.length;e++){let t=localStorage.key(e);t?.startsWith(o)&&(a[t.slice(o.length)]=localStorage.getItem(t)??``)}let s=this.bridge.getState(),c=``,l=``;if(n){let t=[];e.includes(`<slicc-editor`)&&t.push(fetch(chrome.runtime.getURL(`slicc-editor.js`)).then(e=>e.ok?e.text():``).then(e=>{c=e}).catch(()=>{})),e.includes(`<slicc-diff`)&&t.push(fetch(chrome.runtime.getURL(`slicc-diff.js`)).then(e=>e.ok?e.text():``).then(e=>{l=e}).catch(()=>{})),await Promise.all(t)}let u=await this.getLucideScript(),d=n?await zi(e):e;r.contentWindow.postMessage({type:`sprinkle-render`,content:d,name:t,themeCSS:i,savedState:s,savedStorage:a,fullDoc:n,editorScript:c,diffScript:l,lucideScript:u,isLight:Oi()},`*`)}pushUpdate(e){this.iframe?.contentWindow&&this.iframe.contentWindow.postMessage({type:`sprinkle-update`,data:e},`*`)}collectThemeCSS(){return Ui()}generateBridgeScript(){return`(function() {
|
|
67
67
|
var _updateListeners = new Set();
|
|
68
68
|
var _sprinkleName = '';
|
|
69
69
|
var _state = null;
|
|
@@ -178,11 +178,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
178
178
|
lick: function(event) {
|
|
179
179
|
var action = typeof event === 'string' ? event : event.action;
|
|
180
180
|
var data = typeof event === 'string' ? undefined : ('data' in event ? event.data : event);
|
|
181
|
-
parent.postMessage({ type: '
|
|
181
|
+
parent.postMessage({ type: 'dip-lick', action: action, data: data }, '*');
|
|
182
182
|
}
|
|
183
183
|
};
|
|
184
184
|
function reportHeight() {
|
|
185
|
-
parent.postMessage({ type: '
|
|
185
|
+
parent.postMessage({ type: 'dip-height',
|
|
186
186
|
height: document.documentElement.scrollHeight }, '*');
|
|
187
187
|
}
|
|
188
188
|
window.addEventListener('message', function(e) {
|
|
@@ -216,7 +216,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
216
216
|
/* Resolve relative URLs against the iframe's base. */
|
|
217
217
|
var resolved;
|
|
218
218
|
try { resolved = new URL(href, document.baseURI).href; } catch(ex) { resolved = href; }
|
|
219
|
-
parent.postMessage({ type: '
|
|
219
|
+
parent.postMessage({ type: 'dip-open-link', url: resolved }, '*');
|
|
220
220
|
e.preventDefault();
|
|
221
221
|
e.stopPropagation();
|
|
222
222
|
return;
|
|
@@ -264,7 +264,7 @@ ${t.includes(`<slicc-editor`)?`<script src="/slicc-editor.js"><\/script>`:``}
|
|
|
264
264
|
${t.includes(`<slicc-diff`)?`<script src="/slicc-diff.js"><\/script>`:``}
|
|
265
265
|
<script src="/lucide-icons.js"><\/script>
|
|
266
266
|
</head>
|
|
267
|
-
<body class="sprinkle-inline">${t}</body></html>`;if(Wi)return Xi(e,i,n);let a=document.createElement(`iframe`);a.setAttribute(`sandbox`,`allow-scripts allow-same-origin`),a.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,a.srcdoc=i,e.appendChild(a),a.addEventListener(`load`,()=>Ai(a.contentWindow),{once:!0});let o=e=>{if(e.source!==a.contentWindow)return;let t=e.data;t?.type&&(t.type===`
|
|
267
|
+
<body class="sprinkle-inline">${t}</body></html>`;if(Wi)return Xi(e,i,n);let a=document.createElement(`iframe`);a.setAttribute(`sandbox`,`allow-scripts allow-same-origin`),a.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,a.srcdoc=i,e.appendChild(a),a.addEventListener(`load`,()=>Ai(a.contentWindow),{once:!0});let o=e=>{if(e.source!==a.contentWindow)return;let t=e.data;t?.type&&(t.type===`dip-lick`?n(t.action,t.data):t.type===`dip-height`?a.style.height=t.height+`px`:t.type===`dip-open-link`&&qi(t.url))};return window.addEventListener(`message`,o),{dispose(){window.removeEventListener(`message`,o),ji(a.contentWindow),a.remove()}}}function qi(e){if(!(typeof e!=`string`||!e)&&/^(https?:|mailto:)/i.test(e))try{window.open(e,`_blank`,`noopener,noreferrer`)}catch{}}function Ji(e,t){let n=[],r=e.querySelectorAll(`pre > code.language-shtml`);for(let e of r){let r=e.parentElement,i=e.textContent??``,a=document.createElement(`div`);a.className=`msg__dip`,r.replaceWith(a),n.push(Ki(a,i,t))}let i=e.querySelectorAll(`img[src$=".shtml"]`);for(let e of i){let r=e.getAttribute(`src`);if(!r)continue;let i=document.createElement(`div`);i.className=`msg__dip`,e.alt&&i.setAttribute(`title`,e.alt),e.replaceWith(i);let a=new AbortController,o=null,s=!1;n.push({dispose(){s=!0,a.abort(),o&&=(o.dispose(),null)}});let c=r.startsWith(`/`)?`/preview${r}`:r;fetch(c,{signal:a.signal}).then(e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.text()}).then(e=>{s||!i.isConnected||(o=Ki(i,e,t))}).catch(e=>{s||e?.name===`AbortError`||(i.textContent=`Failed to load dip: ${r}`,i.style.cssText=`padding:8px;font-size:12px;color:var(--s2-negative);font-family:var(--s2-font-mono)`)})}return n}function Yi(e){for(let t of e)try{t.dispose()}catch{}e.length=0}function Xi(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===`dip-lick`?n(t.action,t.data):t.type===`dip-height`?r.style.height=t.height+`px`:t.type===`dip-open-link`&&qi(t.url))};return window.addEventListener(`message`,i),r.addEventListener(`load`,()=>{Ai(r.contentWindow),r.contentWindow?.postMessage({type:`dip-render`,srcdoc:t,isLight:Oi()},`*`)},{once:!0}),{dispose(){window.removeEventListener(`message`,i),ji(r.contentWindow),r.remove()}}}var Zi=i(`tool-ui`),Qi=new class{pending=new Map;idCounter=0;generateId(){return`tool-ui-${++this.idCounter}-${Date.now().toString(36)}`}register(e,t,n,r){this.pending.set(e,{request:t,resolve:n,reject:r}),Zi.info(`Tool UI registered`,{id:e})}async handleAction(e,t){let n=this.pending.get(e);if(!n){Zi.warn(`Action for unknown tool UI`,{id:e,action:t.action});return}Zi.info(`Tool UI action`,{id:e,action:t.action});try{let e;e=n.request.onAction?await n.request.onAction(t.action,t.data):t,n.resolve(e)}catch(e){n.reject(e instanceof Error?e:Error(String(e)))}finally{this.pending.delete(e)}}cancel(e,t=`cancelled`){let n=this.pending.get(e);n&&(n.reject(Error(t)),this.pending.delete(e),Zi.info(`Tool UI cancelled`,{id:e,reason:t}))}cancelAll(e=`cancelled`){let t=this.pending.size;for(let[t,n]of this.pending)n.reject(Error(e));this.pending.clear(),t>0&&Zi.info(`All tool UIs cancelled`,{reason:e,count:t})}isPending(e){return this.pending.has(e)}getPendingIds(){return[...this.pending.keys()]}};async function $i(e,t){let n=e.id??Qi.generateId(),r,i,a=new Promise((e,t)=>{r=e,i=t});return Qi.register(n,e,r,i),t?t({content:[{type:`tool_ui`,requestId:n,html:e.html}]}):Zi.warn(`showToolUI called without onUpdate callback — UI may not render`),a.finally(()=>{t&&t({content:[{type:`tool_ui_done`,requestId:n}]})})}var ea=[];function ta(e){return ea.push(e),e}function na(e){let t=ea.lastIndexOf(e);t!==-1&&ea.splice(t,1)}function ra(){return ea.length>0?ea[ea.length-1]:null}async function ia(e){let t=ra();return t?$i(e,t.onUpdate):(Zi.warn(`showToolUIFromContext called without execution context`),null)}var aa=i(`tool-ui-renderer`),oa=typeof chrome<`u`&&!!chrome?.runtime?.id,sa=class{container;iframe=null;dip=null;messageHandler=null;requestId;nonce;constructor(e,t){this.container=e,this.requestId=t,this.nonce=crypto.randomUUID()}async render(e){oa?await this.renderInSandbox(e):this.renderWithDip(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(()=>{aa.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){aa.warn(`Tool UI message nonce mismatch`,{expected:this.nonce,received:n.nonce});return}n.type===`tool-ui-action`&&n.id===this.requestId?(aa.info(`Tool UI action received`,{id:n.id,action:n.action}),this.relayActionToOffscreen(n.action,n.data,n.picker).catch(e=>{aa.error(`relayActionToOffscreen failed`,{requestId:this.requestId,error:e instanceof Error?e.message:String(e)}),Qi.cancel(this.requestId,`Relay failed`)})):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 n=Ui();t.contentWindow.postMessage({type:`tool-ui-render`,id:this.requestId,nonce:this.nonce,html:e,themeCSS:n,isLight:Oi()},`*`)}renderWithDip(e){let t=document.createElement(`div`);t.className=`msg__dip`,this.container.appendChild(t),this.dip=Ki(t,e,(e,t)=>{aa.info(`Tool UI action (dip)`,{id:this.requestId,action:e}),Qi.handleAction(this.requestId,{action:e,data:t})})}async relayActionToOffscreen(e,t,n){let r=t;n===`directory`&&(r=await ca(this.requestId)),chrome.runtime.sendMessage({source:`panel`,payload:{type:`tool-ui-action`,requestId:this.requestId,action:e,data:r}}).catch(e=>{let t=e instanceof Error?e.message:String(e);aa.error(`Failed to relay tool UI action to offscreen`,{requestId:this.requestId,error:t}),Qi.cancel(this.requestId,`Relay failed: ${t}`)})}dispose(){this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.iframe&&=(this.iframe.remove(),null),this.dip&&=(this.dip.dispose(),null)}};function ca(e){return new Promise(t=>{let n=chrome.runtime.getURL(`mount-popup.html?requestId=${encodeURIComponent(e)}`),r=()=>{clearTimeout(i),chrome.runtime.onMessage.removeListener(a)},i=setTimeout(()=>{r(),t({cancelled:!0})},6e4),a=n=>{let i=n;!i||i.source!==`mount-popup`||i.requestId!==e||(r(),t(i))};chrome.runtime.onMessage.addListener(a),chrome.windows.create({url:n,type:`popup`,width:300,height:80,focused:!0}).catch(()=>{r(),t({error:`Failed to open directory picker window`})})})}var la=new Map;function ua(e,t,n){let r=la.get(t);r&&r.dispose();let i=new sa(e,t);return la.set(t,i),i.render(n).catch(e=>{aa.error(`Failed to render tool UI`,{requestId:t,error:e.message})}),i}function da(e){let t=la.get(e);t&&(t.dispose(),la.delete(e))}function fa(e){let t=e;return t=t.replace(/([A-Z_]*(?:TOKEN|KEY|SECRET|PASSWORD|AUTH|BEARER|API_KEY|ACCESS_TOKEN)[=:]\s*)"([^"]{8,})"/gi,`$1"***"`),t=t.replace(/([A-Z_]*(?:TOKEN|KEY|SECRET|PASSWORD|AUTH|BEARER|API_KEY|ACCESS_TOKEN)[=:]\s*)'([^']{8,})'/gi,`$1'***'`),t=t.replace(/([A-Z_]*(?:TOKEN|KEY|SECRET|PASSWORD|AUTH|BEARER|API_KEY|ACCESS_TOKEN)[=:]\s*)([^\s"'`]{8,})/gi,`$1***`),t=t.replace(/(Authorization:\s*Bearer\s+)([^\s"'`]{8,})/gi,`$1***`),t=t.replace(/(?<![A-Za-z0-9+/])(ghp_[A-Za-z0-9]{36}|gh[a-z]_[A-Za-z0-9]{36}|[A-Fa-f0-9]{40,}|[A-Za-z0-9+/]{40,}={0,2})(?![A-Za-z0-9+/=])/g,`***`),t}var pa={icon:st,title:`tool`,preview:e=>ba(e,80)},ma={read_file:{icon:Be,title:`read`,preview:e=>ya(e,`path`)??``,renderBody:Ta},write_file:{icon:ze,title:`write`,preview:e=>ya(e,`path`)??``},edit_file:{icon:Re,title:`edit`,preview:e=>ya(e,`path`)??``,renderBody:Pa},bash:{icon:et,title:`bash`,preview:e=>{let t=ya(e,`command`)??``;return t?fa(`$ ${xa(t,120)}`):``},renderBody:Na},browser:{icon:Ue,title:`browser`,preview:e=>ba(e,80)},javascript:{icon:Ie,title:`javascript`,preview:e=>xa((ya(e,`code`)??``).replace(/\s+/g,` `),100)},send_message:{icon:Ye,title:`message`,preview:e=>{let t=ya(e,`text`)??``;return t?`"${xa(t,100)}"`:``}},feed_scoop:{icon:rt,title:`feed`,preview:e=>ya(e,`scoop_name`)??``},scoop_scoop:{icon:Ge,title:`scoop`,preview:e=>ya(e,`name`)??``},drop_scoop:{icon:tt,title:`drop`,preview:e=>ya(e,`scoop_name`)??``},scoop_mute:{icon:at,title:`mute`,preview:e=>Sa(e)},scoop_unmute:{icon:it,title:`unmute`,preview:e=>Sa(e)},scoop_wait:{icon:We,title:`wait`,preview:e=>{let t=Sa(e),n=ya(e,`timeout_ms`);return n===void 0||n===``?t:t?`${t} (${n}ms)`:`${n}ms`}},list_scoops:{icon:Je,title:`list scoops`,preview:()=>``},list_tasks:{icon:qe,title:`list tasks`,preview:()=>``},register_scoop:{icon:nt,title:`register`,preview:e=>ya(e,`name`)??``},schedule_task:{icon:Fe,title:`schedule`,preview:e=>ya(e,`cron`)??ya(e,`name`)??``},update_global_memory:{icon:Ne,title:`memory`,preview:e=>xa((ya(e,`content`)??``).split(`
|
|
268
268
|
`).find(e=>e.trim().length>0)??``,100)},delegate_to_scoop:{icon:Qe,title:`delegate`,preview:e=>ya(e,`scoop_name`)??``}};function ha(e){return ma[e]??{...pa,title:e}}function ga(e){return e.result===void 0?`running`:e.isError?`error`:`success`}function _a(e){return Ca(ha(e).icon)}function va(e){let t=ha(e.name);if(t.renderBody)try{return t.renderBody(e)}catch{}return wa(e)}function ya(e,t){if(!e||typeof e!=`object`)return;let n=e[t];if(typeof n==`string`)return n;if(typeof n==`number`||typeof n==`boolean`)return String(n)}function ba(e,t){if(e==null)return``;if(typeof e==`string`)return xa(e,t);try{return xa(JSON.stringify(e),t)}catch{return xa(String(e),t)}}function xa(e,t){return e.length<=t?e:e.slice(0,t-1).trimEnd()+`…`}function Sa(e){if(!e||typeof e!=`object`)return``;let t=e.scoop_names;return Array.isArray(t)?xa(t.filter(e=>typeof e==`string`).join(`, `),100):``}function Ca(e){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);t.setAttribute(`xmlns`,`http://www.w3.org/2000/svg`),t.setAttribute(`width`,`14`),t.setAttribute(`height`,`14`),t.setAttribute(`viewBox`,`0 0 24 24`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke`,`currentColor`),t.setAttribute(`stroke-width`,`2`),t.setAttribute(`stroke-linecap`,`round`),t.setAttribute(`stroke-linejoin`,`round`);for(let[n,r]of e){let e=document.createElementNS(`http://www.w3.org/2000/svg`,n);for(let[t,n]of Object.entries(r))e.setAttribute(t,String(n));t.appendChild(e)}return t}function wa(e){let t=document.createElement(`div`);return t.className=`tool-call__body`,e.input!==void 0&&t.appendChild(Da(e.input)),e.result!==void 0&&t.appendChild(Ea(e)),t}function Ta(e){let t=document.createElement(`div`);return t.className=`tool-call__body`,e.result!==void 0&&t.appendChild(Ea(e)),t}function Ea(e){let t=document.createElement(`pre`);return t.className=`tool-call__result${e.isError?` tool-call__result--error`:``}`,t.textContent=e.result??``,t}function Da(e){let t=document.createElement(`pre`);return t.className=`tool-call__yaml`,t.innerHTML=Oa(e,0),t}function Oa(e,t){let n=` `.repeat(t);if(e==null)return`${n}<span class="tool-call__yaml-null">~</span>`;if(typeof e==`string`)return Ma(e,t);if(typeof e==`number`||typeof e==`boolean`)return`${n}<span class="tool-call__yaml-scalar">${qr(String(e))}</span>`;if(Array.isArray(e))return e.length===0?`${n}<span class="tool-call__yaml-scalar">[]</span>`:e.map(e=>Aa(e)?`${n}- ${ja(e)}`:`${n}- ${Oa(e,t+1).replace(/^\s+/,``)}`).join(`
|
|
269
269
|
`);if(typeof e==`object`){let r=Object.entries(e);return r.length===0?`${n}<span class="tool-call__yaml-scalar">{}</span>`:r.map(([e,n])=>ka(e,n,t)).join(`
|
|
270
270
|
`)}return`${n}${qr(String(e))}`}function ka(e,t,n){let r=` `.repeat(n),i=`<span class="tool-call__yaml-key">${qr(e)}</span>`;return Aa(t)?`${r}${i}: ${ja(t)}`:Array.isArray(t)&&t.length===0?`${r}${i}: <span class="tool-call__yaml-scalar">[]</span>`:typeof t==`object`&&t&&Object.keys(t).length===0?`${r}${i}: <span class="tool-call__yaml-scalar">{}</span>`:`${r}${i}:\n${Oa(t,n+1)}`}function Aa(e){return typeof e!=`object`||!e}function ja(e){if(e==null)return`<span class="tool-call__yaml-null">~</span>`;if(typeof e==`string`){if(e.includes(`
|
|
@@ -277,8 +277,8 @@ ${t.includes(`<slicc-diff`)?`<script src="/slicc-diff.js"><\/script>`:``}
|
|
|
277
277
|
`),s=[];for(let e of a)s.push(`<span class="tool-call__diff-del">- ${qr(e)}</span>`);for(let e of o)s.push(`<span class="tool-call__diff-add">+ ${qr(e)}</span>`);return i.innerHTML=s.join(``),r.appendChild(i),e.result!==void 0&&r.appendChild(Ea(e)),r}var Fa={icon:Me,label:`event`},Ia={webhook:{icon:ot,label:`webhook`},cron:{icon:Pe,label:`cron`},sprinkle:{icon:$e,label:`sprinkle`},fswatch:{icon:He,label:`files`},navigate:{icon:Le,label:`navigate`},"session-reload":{icon:Ze,label:`reload`},"scoop-notify":{icon:Ge,label:`scoop`},"scoop-idle":{icon:We,label:`idle`},"scoop-wait":{icon:qe,label:`wait`}};function La(e){return Ia[e.channel??``]??Fa}var Ra=/^\[([^\]:]+?)(?:\s+Event)?:\s*([^\]]+?)\]\s*\n?/,za=/^\[@([^\]]+?)\s+(completed|idle)\]\s*:?\s*\n?/,Ba=/^\[scoop_wait completed\]\s*\n([^\n]+)\n?/;function Va(e){let t=Ba.exec(e);if(t)return{preview:t[1].trim(),body:e.slice(t[0].length).replace(/^\s+/,``)};let n=za.exec(e);if(n)return{preview:`${n[1].trim()} ${n[2]}`,body:e.slice(n[0].length).replace(/^\s+/,``)};let r=Ra.exec(e);return r?{preview:r[2].trim(),body:e.slice(r[0].length).replace(/^\s+/,``)}:{preview:(e.split(`
|
|
278
278
|
`).find(e=>e.trim().length>0)??``).trim().slice(0,80),body:e}}function Ha(e){return Ua(La(e).icon)}function Ua(e){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);t.setAttribute(`xmlns`,`http://www.w3.org/2000/svg`),t.setAttribute(`width`,`14`),t.setAttribute(`height`,`14`),t.setAttribute(`viewBox`,`0 0 24 24`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke`,`currentColor`),t.setAttribute(`stroke-width`,`2`),t.setAttribute(`stroke-linecap`,`round`),t.setAttribute(`stroke-linejoin`,`round`);for(let[n,r]of e){let e=document.createElementNS(`http://www.w3.org/2000/svg`,n);for(let[t,n]of Object.entries(r))e.setAttribute(t,String(n));t.appendChild(e)}return t}var Wa=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`scoop-notify`,`scoop-idle`,`scoop-wait`]);function Ga(e){return e!=null&&Wa.has(e)}var Ka=null,qa=null,Ja=null,Ya=e=>k(()=>import(e),[]);typeof process<`u`&&(process.versions?.node||process.versions?.bun)&&(Ya(`node:fs`).then(e=>{Ka=e.existsSync}),Ya(`node:os`).then(e=>{qa=e.homedir}),Ya(`node:path`).then(e=>{Ja=e.join}));var Xa=null;function Za(){if(Xa===null){if(!Ka||!qa||!Ja)return typeof process<`u`&&(process.versions?.node||process.versions?.bun)||(Xa=!1),!1;let e={}.GOOGLE_APPLICATION_CREDENTIALS;Xa=Ka(e||Ja(qa(),`.config`,`gcloud`,`application_default_credentials.json`))}return Xa}function Qa(e){if(e===`github-copilot`)return[`COPILOT_GITHUB_TOKEN`,`GH_TOKEN`,`GITHUB_TOKEN`];if(e===`anthropic`)return[`ANTHROPIC_OAUTH_TOKEN`,`ANTHROPIC_API_KEY`];let t={openai:`OPENAI_API_KEY`,"azure-openai-responses":`AZURE_OPENAI_API_KEY`,google:`GEMINI_API_KEY`,"google-vertex":`GOOGLE_CLOUD_API_KEY`,groq:`GROQ_API_KEY`,cerebras:`CEREBRAS_API_KEY`,xai:`XAI_API_KEY`,openrouter:`OPENROUTER_API_KEY`,"vercel-ai-gateway":`AI_GATEWAY_API_KEY`,zai:`ZAI_API_KEY`,mistral:`MISTRAL_API_KEY`,minimax:`MINIMAX_API_KEY`,"minimax-cn":`MINIMAX_CN_API_KEY`,huggingface:`HF_TOKEN`,fireworks:`FIREWORKS_API_KEY`,opencode:`OPENCODE_API_KEY`,"opencode-go":`OPENCODE_API_KEY`,"kimi-coding":`KIMI_API_KEY`}[e];return t?[t]:void 0}function $a(e){let t=Qa(e);if(!t)return;let n=t.filter(e=>!!{}[e]);return n.length>0?n:void 0}function eo(e){let t=$a(e);if(t?.[0])return{}[t[0]];if(e===`google-vertex`){let e=Za(),t=!!({}.GOOGLE_CLOUD_PROJECT||{}.GCLOUD_PROJECT),n=!!{}.GOOGLE_CLOUD_LOCATION;if(e&&t&&n)return`<authenticated>`}if(e===`amazon-bedrock`&&({}.AWS_PROFILE||{}.AWS_ACCESS_KEY_ID&&{}.AWS_SECRET_ACCESS_KEY||{}.AWS_BEARER_TOKEN_BEDROCK||{}.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI||{}.AWS_CONTAINER_CREDENTIALS_FULL_URI||{}.AWS_WEB_IDENTITY_TOKEN_FILE))return`<authenticated>`}var to=r((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow})),no=r((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!==`default`&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,`__esModule`,{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;var r=to();Object.defineProperty(e,`Allow`,{enumerable:!0,get:function(){return r.Allow}}),n(to(),e);var i=class extends Error{};e.PartialJSON=i;var a=class extends Error{};e.MalformedJSON=a;function o(e,t=r.Allow.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return s(e.trim(),t)}e.parseJSON=o;var s=(e,t)=>{let n=e.length,o=0,s=e=>{throw new i(`${e} at position ${o}`)},c=e=>{throw new a(`${e} at position ${o}`)},l=()=>(m(),o>=n&&s(`Unexpected end of input`),e[o]===`"`?u():e[o]===`{`?d():e[o]===`[`?f():e.substring(o,o+4)===`null`||r.Allow.NULL&t&&n-o<4&&`null`.startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)===`true`||r.Allow.BOOL&t&&n-o<4&&`true`.startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)===`false`||r.Allow.BOOL&t&&n-o<5&&`false`.startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)===`Infinity`||r.Allow.INFINITY&t&&n-o<8&&`Infinity`.startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)===`-Infinity`||r.Allow._INFINITY&t&&1<n-o&&n-o<9&&`-Infinity`.startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)===`NaN`||r.Allow.NAN&t&&n-o<3&&`NaN`.startsWith(e.substring(o))?(o+=3,NaN):p()),u=()=>{let i=o,a=!1;for(o++;o<n&&(e[o]!==`"`||a&&e[o-1]===`\\`);)a=e[o]===`\\`?!a:!1,o++;if(e.charAt(o)==`"`)try{return JSON.parse(e.substring(i,++o-Number(a)))}catch(e){c(String(e))}else if(r.Allow.STR&t)try{return JSON.parse(e.substring(i,o-Number(a))+`"`)}catch{return JSON.parse(e.substring(i,e.lastIndexOf(`\\`))+`"`)}s(`Unterminated string literal`)},d=()=>{o++,m();let i={};try{for(;e[o]!==`}`;){if(m(),o>=n&&r.Allow.OBJ&t)return i;let a=u();m(),o++;try{i[a]=l()}catch(e){if(r.Allow.OBJ&t)return i;throw e}m(),e[o]===`,`&&o++}}catch{if(r.Allow.OBJ&t)return i;s(`Expected '}' at end of object`)}return o++,i},f=()=>{o++;let n=[];try{for(;e[o]!==`]`;)n.push(l()),m(),e[o]===`,`&&o++}catch{if(r.Allow.ARR&t)return n;s(`Expected ']' at end of array`)}return o++,n},p=()=>{if(o===0){e===`-`&&c(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(r.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}c(String(n))}}let i=o;for(e[o]===`-`&&o++;e[o]&&`,]}`.indexOf(e[o])===-1;)o++;o==n&&!(r.Allow.NUM&t)&&s(`Unterminated number literal`);try{return JSON.parse(e.substring(i,o))}catch{e.substring(i,o)===`-`&&s(`Not sure what '-' is`);try{return JSON.parse(e.substring(i,e.lastIndexOf(`e`)))}catch(e){c(String(e))}}},m=()=>{for(;o<n&&`
|
|
279
279
|
\r `.includes(e[o]);)o++};return l()};e.parse=o}))(),ro=new Set([`"`,`\\`,`/`,`b`,`f`,`n`,`r`,`t`,`u`]);function io(e){let t=e.codePointAt(0);return t!==void 0&&t>=0&&t<=31}function ao(e){switch(e){case`\b`:return`\\b`;case`\f`:return`\\f`;case`
|
|
280
|
-
`:return`\\n`;case`\r`:return`\\r`;case` `:return`\\t`;default:return`\\u${e.codePointAt(0)?.toString(16).padStart(4,`0`)??`0000`}`}}function oo(e){let t=``,n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(!n){t+=i,i===`"`&&(n=!0);continue}if(i===`"`){t+=i,n=!1;continue}if(i===`\\`){let n=e[r+1];if(n===void 0){t+=`\\\\`;continue}if(n===`u`){let n=e.slice(r+2,r+6);if(/^[0-9a-fA-F]{4}$/.test(n)){t+=`\\u${n}`,r+=5;continue}}if(ro.has(n)){t+=`\\${n}`,r+=1;continue}t+=`\\\\`;continue}t+=io(i)?ao(i):i}return t}function so(e){try{return JSON.parse(e)}catch(t){let n=oo(e);if(n!==e)return JSON.parse(n);throw t}}function co(e){if(!e||e.trim()===``)return{};try{return so(e)}catch{try{return(0,no.parse)(e)??{}}catch{try{return(0,no.parse)(oo(e))??{}}catch{return{}}}}}var lo=`tray`,uo=`trayWorkerUrl`,fo=`lead`;function po(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``,t.pathname!==`/`&&(t.pathname=t.pathname.replace(/\/+$/,``)||`/`);let n=t.toString();return n.endsWith(`/`)?n.slice(0,-1):n}catch{return null}}function mo(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``;let n=t.toString(),r=t.pathname.split(`/`).filter(Boolean);if(r.length<2||r.at(-2)!==`join`)return null;let[i,a,...o]=decodeURIComponent(r.at(-1)).split(`.`);if(!i||!a||o.length>0)return null;r.splice(-2,2),t.pathname=r.length>0?`/${r.join(`/`)}`:`/`;let s=po(t.toString());return s?{workerBaseUrl:s,trayId:i,joinUrl:n}:null}catch{return null}}function ho(e,t){let n=new URL(e);return n.searchParams.delete(uo),n.searchParams.delete(fo),n.searchParams.set(lo,t),n.toString()}var go=`slicc.trayWorkerBaseUrl`,_o=`slicc.trayJoinUrl`,vo=`https://www.sliccy.ai`;function yo(e,t){let n=po(e);if(!n)throw Error(`Invalid tray worker base URL: ${e}`);let r=t.replace(/^\/+/,``);return new URL(r,`${n}/`).toString()}function bo(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``;let n=t.pathname.split(`/`).filter(Boolean),r=null;if(n.length>=2&&n.at(-2)===`tray`)r=decodeURIComponent(n.at(-1)),n.splice(-2,2),t.pathname=n.length>0?`/${n.join(`/`)}`:`/`;else if(n.length>=2&&n.at(-2)===`join`)return mo(t.toString());let i=po(t.toString());return i?{workerBaseUrl:i,trayId:r,joinUrl:null}:null}catch{return null}}function xo(e){let t=bo(e);return t?.joinUrl?t:null}function So(e,t){let n=xo(t);return n?(e.setItem(_o,n.joinUrl),e.setItem(go,n.workerBaseUrl),n):null}function Co(e){return!!xo(e?.getItem(`slicc.trayJoinUrl`)??null)}function wo(e,t){let n=po(e);if(!n)throw Error(`Invalid tray worker base URL: ${e}`);let r=t?.trim();return r?new URL(`tray/${encodeURIComponent(r)}`,`${n}/`).toString():n}function To(e,t,n){return ho(e,wo(t,n))}async function Eo(e){let t=Oo(e.locationHref);if(t)return e.storage&&(t.joinUrl&&e.storage.setItem(_o,t.joinUrl),e.storage.setItem(go,t.workerBaseUrl)),t;let n=xo(e.storage?.getItem(`slicc.trayJoinUrl`)??null);if(n)return e.storage&&e.storage.setItem(go,n.workerBaseUrl),n;let r=e.runtimeConfigFetcher?await ko(e.runtimeConfigFetcher):null;if(r?.joinConfig)return e.storage&&(e.storage.setItem(_o,r.joinConfig.joinUrl),e.storage.setItem(go,r.joinConfig.workerBaseUrl)),r.joinConfig;let i=r?.workerBaseUrl??null,a=po(e.storage?.getItem(`slicc.trayWorkerBaseUrl`)??null),o=po(e.envBaseUrl??null),s=po(e.defaultWorkerBaseUrl??null),c=i??a??o??s;return c?(e.storage&&e.storage.setItem(go,c),{workerBaseUrl:c,trayId:null,joinUrl:null}):null}async function Do(e=fetch){try{let t=await e(`/api/runtime-config`,{cache:`no-store`});return t.ok?await t.json():null}catch{return null}}function Oo(e){try{let t=new URL(e),n=bo(t.searchParams.get(lo));if(n)return n;let r=bo(t.searchParams.get(fo));if(r)return r;let i=po(t.searchParams.get(uo));return i?{workerBaseUrl:i,trayId:null,joinUrl:null}:mo(e)||null}catch{return null}}async function ko(e){let t=await e();if(!t)return null;let n=xo(t.trayJoinUrl??null);return{workerBaseUrl:po(t.trayWorkerBaseUrl??null),joinConfig:n}}var Ao={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function jo(){return{...Ao}}function Mo(e){Ao={...e}}function No(e){Ao={...Ao,lastPingTime:e}}var Po=i(`chat-panel`),Fo=5*1024*1024,Io=512*1024;function Lo(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function Ro(e,t=18){let n=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);n.setAttribute(`xmlns`,`http://www.w3.org/2000/svg`),n.setAttribute(`width`,String(t)),n.setAttribute(`height`,String(t)),n.setAttribute(`viewBox`,`0 0 24 24`),n.setAttribute(`fill`,`none`),n.setAttribute(`stroke`,`currentColor`),n.setAttribute(`stroke-width`,`2`),n.setAttribute(`stroke-linecap`,`round`),n.setAttribute(`stroke-linejoin`,`round`);for(let[t,r]of e){let e=document.createElementNS(`http://www.w3.org/2000/svg`,t);for(let[t,n]of Object.entries(r))e.setAttribute(t,String(n));n.appendChild(e)}return n}function zo(e){let t=32768,n=Array(Math.ceil(e.length/t)),r=0;for(let i=0;i<e.length;i+=t){let a=e.subarray(i,i+t);n[r++]=String.fromCharCode(...a)}return btoa(n.join(``))}async function Bo(e){return zo(new Uint8Array(await e.arrayBuffer()))}async function Vo(e){return typeof e.text==`function`?e.text():new TextDecoder().decode(await e.arrayBuffer())}function Ho(e,t){return t.startsWith(`text/`)||t===`application/json`||t===`application/xml`||t===`image/svg+xml`?!0:/\.(?:md|markdown|txt|csv|tsv|json|jsonl|yaml|yml|xml|html|css|js|mjs|ts|tsx|jsx|py|rb|go|rs|java|c|cc|cpp|h|hpp|sh|bash|zsh|sql)$/i.test(e.name)}function Uo(e){return e.role===`assistant`?si(e.content):oi(e.content)}var Wo=class{container;messagesEl;messagesInner;inputArea;textarea;sendBtn;stopBtn;micBtn;attachBtn;fileInput;attachmentsEl;pendingAttachments=[];attachmentReadInProgress=!1;attachmentWriter=null;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;onModelChange;lickPersistQueues=new Map;constructor(e){this.container=e,this.sessionStore=new fi,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}setAttachmentWriter(e){this.attachmentWriter=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{}}async persistLickToSession(e,t){let n=(this.lickPersistQueues.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.writeLickToSession(e,t));return this.lickPersistQueues.set(e,n),n.finally(()=>{this.lickPersistQueues.get(e)===n&&this.lickPersistQueues.delete(e)}),n}async writeLickToSession(e,t){try{let n=(await this.sessionStore.load(e))?.messages??[];if(n.some(e=>e.id===t.id))return;let r={id:t.id,role:`user`,content:t.content,timestamp:t.timestamp,source:`lick`,channel:t.channel},i=n.length;for(let e=n.length-1;e>=0;e--){if(n[e].timestamp<=t.timestamp){i=e+1;break}i=e}n.splice(i,0,r),await this.sessionStore.saveMessages(e,n)}catch{}}setProcessing(e){e?this.setStreamingState(!0):this.setStreamingState(!1)}addSystemMessage(e){let t={id:Lo(),role:`assistant`,content:e,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t),this.persistSession()}addLickMessage(e,t,n,r){let i=r??Date.now();if(this.messages.some(t=>t.id===e))return;let a={id:e,role:`user`,content:t,timestamp:i,source:`lick`,channel:n},o=this.messages.length;for(let e=this.messages.length-1;e>=0;e--){if(this.messages[e].timestamp<=i){o=e+1;break}o=e}o===this.messages.length?(this.messages.push(a),this.appendMessageEl(a)):(this.messages.splice(o,0,a),this.renderMessages()),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()}addUserMessage(e,t){let n={id:Lo(),role:`user`,content:e,attachments:t,timestamp:Date.now()};this.messages.push(n),this.appendMessageEl(n)}async addAttachmentsFromFiles(e){let t=Array.from(e).filter(e=>e instanceof File);if(t.length!==0){this.attachmentReadInProgress=!0,this.attachBtn?.classList.add(`chat__attach-btn--busy`);try{for(let e of t){let t=await this.createAttachmentFromFile(e);t&&this.pendingAttachments.push(t)}this.renderPendingAttachments(),this.updateSendButtonState()}finally{this.attachmentReadInProgress=!1,this.attachBtn?.classList.remove(`chat__attach-btn--busy`),this.updateSendButtonState()}}}async createAttachmentFromFile(e){let t=e.type||mi(e.name),n=l(t),r=Ho(e,t);if(n&&e.size<=Fo){let n=await a({type:`image`,mimeType:t,data:await Bo(e)});if(n.type===`image`)return{id:Lo(),name:e.name,mimeType:n.mimeType,size:e.size,kind:`image`,data:n.data}}if(r&&e.size<=Io)return{id:Lo(),name:e.name,mimeType:t,size:e.size,kind:`text`,text:await Vo(e)};let i=n?`image`:r?`text`:`file`;if(this.attachmentWriter)try{let n=await this.attachmentWriter(e);return{id:Lo(),name:e.name,mimeType:t,size:e.size,kind:i,path:n}}catch(n){Po.error(`Failed to persist attachment to VFS`,n);let r=n instanceof Error?n.message:String(n);return this.addSystemMessage(`Could not save attachment ${e.name} to /tmp: ${r}`),{id:Lo(),name:e.name,mimeType:t,size:e.size,kind:i,error:`Could not be saved to the virtual filesystem: ${r}`}}return r&&e.size>Io?{id:Lo(),name:e.name,mimeType:t,size:e.size,kind:`text`,error:`Text attachment is above the ${O(Io)} inline limit.`}:n&&e.size>Fo?{id:Lo(),name:e.name,mimeType:t,size:e.size,kind:`image`,error:`Image attachment is above the ${O(Fo)} inline limit.`}:{id:Lo(),name:e.name,mimeType:t,size:e.size,kind:`file`}}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.container.appendChild(this.messagesEl),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.attachBtn=document.createElement(`button`),this.attachBtn.className=`chat__attach-btn`,this.attachBtn.type=`button`,this.attachBtn.appendChild(Ro(Xe,18)),this.attachBtn.dataset.tooltip=`Attach files`,this.fileInput=document.createElement(`input`),this.fileInput.className=`chat__file-input`,this.fileInput.type=`file`,this.fileInput.multiple=!0,this.fileInput.tabIndex=-1,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`,this.attachmentsEl=document.createElement(`div`),this.attachmentsEl.className=`chat__attachments`,c.appendChild(this.attachmentsEl),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.attachBtn),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),c.appendChild(this.fileInput),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.adjustTextareaHeight(),this.updateSendButtonState()}),this.sendBtn.addEventListener(`click`,()=>this.sendMessage()),this.attachBtn.addEventListener(`click`,()=>this.fileInput.click()),this.fileInput.addEventListener(`change`,()=>{let e=this.fileInput.files;e?.length&&this.addAttachmentsFromFiles(e),this.fileInput.value=``}),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 Si({onTranscript:(e,t)=>{this.textarea.value=e,this.adjustTextareaHeight()},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=>{Po.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:wi()}),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),this.renderPendingAttachments(),this.updateSendButtonState()}toggleVoiceMode(){this.voiceMode=!this.voiceMode,this.micBtn.classList.toggle(`chat__mic-btn--active`,this.voiceMode),this.voiceMode?this.voiceInput?.start():this.voiceInput?.stop()}adjustTextareaHeight(){let e=this.container.clientHeight||(typeof window<`u`?window.innerHeight:0)||0,t=Math.max(18,Math.floor(e*.3));this.textarea.style.height=`auto`;let n=this.textarea.scrollHeight,r=Math.min(n,t);this.textarea.style.height=r+`px`,this.textarea.style.overflowY=n>t?`auto`:`hidden`}resetTextareaHeight(){this.textarea.style.height=`auto`,this.textarea.style.overflowY=`hidden`}sendMessage(){if(this.attachmentReadInProgress)return;let e=this.textarea.value.trim(),t=this.pendingAttachments.map(e=>({...e}));if(!e&&t.length===0)return;this.autoScrollAttached=!0,this.hideJumpPill();let n=this.isStreaming,r={id:Lo(),role:`user`,content:e,attachments:t.length>0?t:void 0,timestamp:Date.now(),queued:n||void 0};this.messages.push(r),this.appendMessageEl(r),this.persistSession(),this.textarea.value=``,this.pendingAttachments=[],this.renderPendingAttachments(),this.resetTextareaHeight(),this.updateSendButtonState(),this.isStreaming||this.setStreamingState(!0),this.agent?.sendMessage(e,r.id,t)}handleAgentEvent(e){switch(Po.debug(`Agent event`,{type:e.type}),e.type){case`message_start`:this.handleMessageStart(e.messageId);break;case`content_delta`:this.handleContentDelta(e.messageId,e.text);break;case`content_done`:this.handleContentDone(e.messageId);break;case`tool_use_start`:this.handleToolUseStart(e.messageId,e.toolName,e.toolInput);break;case`tool_result`:this.handleToolResult(e.messageId,e.toolName,e.result,e.isError);break;case`tool_ui`:this.handleToolUI(e.messageId,e.toolName,e.requestId,e.html);break;case`tool_ui_done`:this.handleToolUIDone(e.messageId,e.requestId);break;case`turn_end`:this.handleTurnEnd(e.messageId);break;case`error`:this.handleError(e.error);break;case`screenshot`:break;case`terminal_output`:this.terminalOutputCallback?.(e.text);break}}handleMessageStart(e){this.setStreamingState(!0),this.currentStreamId=e;let t={id:e,role:`assistant`,content:``,timestamp:Date.now(),isStreaming:!0,toolCalls:[]};this.messages.push(t),this.appendMessageEl(t)}handleContentDelta(e,t){this.findMessage(e)&&(this.pendingDeltaText+=t,this.streamingRafId===null&&(this.streamingRafId=requestAnimationFrame(()=>this.flushPendingDelta())))}handleContentDone(e){if(this.pendingDeltaText&&this.currentStreamId===e){let t=this.findMessage(e);t&&(t.content+=this.pendingDeltaText)}this.cancelPendingDelta();let t=this.findMessage(e);t&&(t.isStreaming=!1,this.updateMessageEl(e))}handleToolUseStart(e,t,n){let r=this.findMessage(e);r&&(r.toolCalls||=[],r.toolCalls.push({id:Lo(),name:t,input:n}),this.updateMessageEl(e))}handleToolResult(e,t,n,r){let i=this.findMessage(e);if(!i||!i.toolCalls)return;let a=[...i.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);if(a){let e=n.match(/<img:(data:image\/[^>]+)>/);a.result=n.replace(/<img:data:image\/[^>]+>/g,``).trim(),e&&(a._screenshotDataUrl=e[1]),a.isError=r}this.updateMessageEl(e)}handleToolUI(e,t,n,r,i=0){let a=this.findMessage(e);if(!a||!a.toolCalls){if(i<10){setTimeout(()=>this.handleToolUI(e,t,n,r,i+1),100);return}Po.warn(`handleToolUI: message or toolCalls not found after retries`,{messageId:e});return}let o=[...a.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);if(!o){Po.warn(`handleToolUI: no matching tool call found`,{messageId:e,toolName:t});return}o._toolUIRequestId=n;let s=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);if(!s){if(i<10){setTimeout(()=>this.handleToolUI(e,t,n,r,i+1),100);return}Po.warn(`handleToolUI: wrapper element not found after retries`,{messageId:e});return}let c=[...s.querySelectorAll(`.tool-call`)].reverse().find(e=>e.querySelector(`.tool-call__name`)?.textContent===t);if(c){c instanceof HTMLDetailsElement&&(c.open=!0);let e=c.querySelector(`.tool-call__ui`);e||(e=document.createElement(`div`),e.className=`tool-call__ui`,c.appendChild(e)),ua(e,n,r)}else i<10?setTimeout(()=>this.handleToolUI(e,t,n,r,i+1),100):Po.warn(`handleToolUI: tool call element not found in DOM after retries`,{toolName:t})}handleToolUIDone(e,t){da(t)}handleTurnEnd(e){this.setStreamingState(!1),this.currentStreamId=null,this.persistSession()}handleError(e){this.setStreamingState(!1),this.currentStreamId=null;let t=this.messages[this.messages.length-1];if(t?.role===`assistant`&&t.isStreaming)t.isStreaming=!1,t.content+=`\n\n**Error:** ${e}`,this.updateMessageEl(t.id);else{let t={id:Lo(),role:`assistant`,content:`**Error:** ${e}`,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t)}this.persistSession()}setStreamingState(e){this.isStreaming=e;try{this.renderModelSelector()}catch{}if(this.stopBtn.style.display=e?`flex`:`none`,this.sendBtn.style.display=e?`none`:`flex`,this.updateSendButtonState(),this.textarea.disabled=!1,e){this.voiceInput?.isListening()&&this.voiceInput.stop(),this.micBtn.classList.remove(`chat__mic-btn--listening`);let e=this.messages.find(e=>e.queued);e&&(e.queued=!1,this.updateMessageEl(e.id))}e||(this.voiceMode?(this.micBtn.classList.add(`chat__mic-btn--listening`),this.voiceInput?.start()):this.textarea.focus())}renderModelSelector(){let e=this.modelSelectorEl;if(!e)return;for(;e.firstChild;)e.removeChild(e.firstChild);let t=v(),n=w(),r=m(),i=[];for(let e of t)for(let t of e.models)i.push({providerId:e.providerId,id:t.id,name:t.name,reasoning:t.reasoning});i.sort((e,t)=>e.reasoning===t.reasoning?e.name.localeCompare(t.name):e.reasoning?-1:1);let a=i.find(e=>e.id===n&&e.providerId===r)||i[0];if(!a)return;let o=this.isStreaming,s=document.createElement(`button`);if(s.className=`chat__model-btn chat__model-btn--compact`,o&&s.classList.add(`chat__model-btn--disabled`),s.textContent=a.name,!o){let e=document.createElement(`span`);e.className=`chat__model-chevron`,e.innerHTML=`<svg width="12" height="12" viewBox="0 0 16 16" fill="currentColor"><path d="M4.5 6l3.5 4 3.5-4z"/></svg>`,s.appendChild(e)}if(o)e.appendChild(s);else{let t=!1,a=document.createElement(`div`);a.className=`chat__model-menu`;let o=()=>{for(a.style.display=t?`block`:`none`;a.firstChild;)a.removeChild(a.firstChild);if(t)for(let e of i){let i=document.createElement(`div`);i.className=`chat__model-menu-item`;let o=e.id===n&&e.providerId===r;o&&i.classList.add(`chat__model-menu-item--active`);let s=document.createElement(`span`);if(s.textContent=e.name,i.appendChild(s),o){let e=document.createElement(`span`);e.className=`chat__model-check`,e.innerHTML=`<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M6.5 12.5l-4-4 1.4-1.4 2.6 2.6 5.6-5.6 1.4 1.4z"/></svg>`,i.appendChild(e)}i.addEventListener(`click`,()=>{let n=`${e.providerId}:${e.id}`;S(n),this.onModelChange?.(n),t=!1,this.renderModelSelector()}),a.appendChild(i)}};s.addEventListener(`click`,e=>{e.stopPropagation(),t=!t,o()}),document.addEventListener(`click`,()=>{t=!1,o()},{once:!0}),e.appendChild(s),e.appendChild(a),o()}}refreshModelSelector(){this.renderModelSelector()}findMessage(e){return this.messages.find(t=>t.id===e)}flushPendingDelta(){if(this.streamingRafId=null,!this.pendingDeltaText||!this.currentStreamId)return;let e=this.findMessage(this.currentStreamId);if(!e){this.pendingDeltaText=``;return}e.content+=this.pendingDeltaText,this.pendingDeltaText=``,this.updateStreamingContent(this.currentStreamId)}cancelPendingDelta(){this.streamingRafId!==null&&(cancelAnimationFrame(this.streamingRafId),this.streamingRafId=null),this.pendingDeltaText=``}updateStreamingContent(e){let t=this.findMessage(e);if(!t)return;let n=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);if(!n)return;let r=n.querySelector(`.msg__content`);if(r){if(r.innerHTML=Uo(t),t.isStreaming){let e=document.createElement(`span`);e.className=`streaming-cursor`,r.appendChild(e)}}else if(t.content.trim().length>0){this.updateMessageEl(e);return}this.scrollToBottom()}updateSendButtonState(){if(!this.sendBtn||!this.textarea)return;let e=this.textarea.value.trim().length>0;this.sendBtn.disabled=this.attachmentReadInProgress||!e&&this.pendingAttachments.length===0,this.attachBtn&&(this.attachBtn.disabled=this.attachmentReadInProgress)}renderPendingAttachments(){if(this.attachmentsEl){this.attachmentsEl.innerHTML=``,this.attachmentsEl.classList.toggle(`chat__attachments--visible`,this.pendingAttachments.length>0);for(let e of this.pendingAttachments)this.attachmentsEl.appendChild(this.createAttachmentChip(e,{removable:!0,onRemove:()=>{this.pendingAttachments=this.pendingAttachments.filter(t=>t.id!==e.id),this.renderPendingAttachments(),this.updateSendButtonState()}}))}}createAttachmentList(e){let t=document.createElement(`div`);t.className=`msg__attachments`;for(let n of e)t.appendChild(this.createAttachmentChip(n));return t}createAttachmentChip(e,t={}){let n=document.createElement(`div`);n.className=`attachment-chip attachment-chip--${e.kind}`,n.title=u(e);let r=document.createElement(`span`);if(r.className=`attachment-chip__visual`,e.kind===`image`&&e.data){let t=document.createElement(`img`);t.src=`data:${e.mimeType};base64,${e.data}`,t.alt=e.name||`Attached image`,r.appendChild(t)}else{let t=e.kind===`text`?Be:e.mimeType.startsWith(`image/`)?Ke:Ve;r.appendChild(Ro(t,16))}n.appendChild(r);let i=document.createElement(`span`);i.className=`attachment-chip__body`;let a=document.createElement(`span`);a.className=`attachment-chip__name`,a.textContent=e.name,i.appendChild(a);let o=document.createElement(`span`);if(o.className=`attachment-chip__meta`,o.textContent=e.error?`not included`:`${e.mimeType||`file`} · ${O(e.size)}`,i.appendChild(o),e.path){let t=document.createElement(`span`);t.className=`attachment-chip__path`,t.textContent=e.path,t.title=e.path,i.appendChild(t)}if(n.appendChild(i),t.removable){let r=document.createElement(`button`);r.className=`attachment-chip__remove`,r.type=`button`,r.title=`Remove ${e.name}`,r.appendChild(Ro(ct,14)),r.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),t.onRemove?.()}),n.appendChild(r)}return n}renderMessages(){this.disposeAllInlineSprinkles(),this.messagesInner.innerHTML=``;let e=null,t=0,n=-1;for(let e=this.messages.length-1;e>=0;e--)if(this.messages[e].role===`assistant`){n=e;break}let r=this.findLastRealUserIdx();for(let i=0;i<this.messages.length;i++){let a=this.messages[i],o=this.shouldShowLabel(a,e,t),s=r>i,c=this.createMessageEl(a,o,i===n,s);this.messagesInner.appendChild(c),e=a.role,t=a.timestamp}this.autoScrollAttached=!0,this.hideJumpPill(),this.scrollToBottom(!0)}appendMessageEl(e){let t=this.messagesInner.querySelector(`.msg__feedback`);t&&t.remove();let n=this.messages.length>=2?this.messages[this.messages.length-2]:null,r=this.shouldShowLabel(e,n?.role??null,n?.timestamp??0),i=e.role===`assistant`;this.isRealUserTurn(e)&&this.messagesInner.querySelectorAll(`.tool-call`).forEach(e=>e.classList.add(`tool-call--stale`));let a=this.createMessageEl(e,r,i);this.messagesInner.appendChild(a),this.scrollToBottom()}shouldShowLabel(e,t,n){return!!(e.source===`lick`||Ga(e.channel)||e.role!==t||e.timestamp-n>12e4)}updateMessageEl(e){let t=this.findMessage(e);if(!t)return;let n=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);if(n){this.disposeInlineSprinklesForMessage(e);let r=this.messages.indexOf(t),i=r>0?this.messages[r-1]:null,a=this.shouldShowLabel(t,i?.role??null,i?.timestamp??0),o=!1;if(t.role===`assistant`){let e=-1;for(let t=this.messages.length-1;t>=0;t--)if(this.messages[t].role===`assistant`){e=t;break}o=r===e}let s=this.findLastRealUserIdx()>r,c=this.createMessageEl(t,a,o,s);n.replaceWith(c)}this.scrollToBottom()}isRealUserTurn(e){return!(e.role!==`user`||e.source===`lick`||e.source===`delegation`||e.channel===`delegation`)}findLastRealUserIdx(){for(let e=this.messages.length-1;e>=0;e--)if(this.isRealUserTurn(this.messages[e]))return e;return-1}createMessageEl(e,t=!0,n=!1,r=!1){if(e.source===`lick`||Ga(e.channel)){let t=document.createElement(`div`);return t.className=`msg-group`,t.setAttribute(`data-msg-id`,e.id),t.appendChild(this.createLickEl(e)),t}let i=document.createElement(`div`);i.className=`msg-group${t?``:` msg-group--continuation`}`,i.setAttribute(`data-msg-id`,e.id);let a=document.createElement(`div`);if(a.className=`msg msg--${e.role}${e.queued?` msg--queued`:``}`,t){let t,n,r=this.currentScoopName!==null;e.role===`user`?e.source===`delegation`||e.channel===`delegation`?(t=`S`,n=`sliccy`):(t=`U`,n=`You`):r?(t=(this.currentScoopName||`S`).charAt(0).toUpperCase(),n=`@${this.currentScoopName}`):e.source&&e.source!==`cone`?(t=e.source.charAt(0).toUpperCase(),n=e.source):(t=`S`,n=`sliccy`);let i=document.createElement(`div`);i.className=`msg__role`;let o=document.createElement(`span`);if(o.className=`msg__icon`,o.textContent=t,i.appendChild(o),i.appendChild(document.createTextNode(` ${n}`)),e.queued){let t=document.createElement(`span`);t.className=`msg__queued-badge`,t.textContent=`queued`,i.appendChild(t);let n=document.createElement(`button`);n.className=`msg__queued-delete`,n.textContent=`×`,n.title=`Remove queued message`,n.addEventListener(`click`,t=>{t.stopPropagation(),this.deleteQueuedMessage(e.id)}),i.appendChild(n)}a.appendChild(i)}let o=(e.source===`lick`||Ga(e.channel))&&this.sessionId===`session-cone`,s=e.source&&e.source!==`cone`&&e.source!==`lick`&&e.role===`assistant`&&this.sessionId===`session-cone`;if(o||s){let t=document.createElement(`details`);t.className=`msg__collapsible`;let n=document.createElement(`summary`);n.className=`msg__summary`,n.textContent=e.content.slice(0,60).replace(/\n/g,` `)+(e.content.length>60?`...`:``),t.appendChild(n);let r=document.createElement(`div`);r.className=`msg__content`,r.innerHTML=Uo(e),e.attachments?.length&&t.appendChild(this.createAttachmentList(e.attachments)),e.isStreaming||this.hydrateInlineSprinklesInEl(r,e.id),t.appendChild(r),a.appendChild(t)}else{e.attachments?.length&&a.appendChild(this.createAttachmentList(e.attachments));let t=document.createElement(`div`);if(t.className=`msg__content`,t.innerHTML=Uo(e),e.isStreaming){let e=document.createElement(`span`);e.className=`streaming-cursor`,t.appendChild(e)}else this.hydrateInlineSprinklesInEl(t,e.id);a.appendChild(t)}let c=e.content.trim().length>0||!!e.attachments?.length;if(c&&i.appendChild(a),e.toolCalls)for(let t of e.toolCalls)i.appendChild(this.createToolCallEl(t,r));return e.role===`assistant`&&!e.isStreaming&&!e.queued&&c&&n&&i.appendChild(this.createFeedbackRow()),i}createFeedbackRow(){let e=document.createElement(`div`);e.className=`msg__feedback`;let t=document.createElement(`button`);return t.className=`msg__feedback-btn`,t.dataset.tooltip=`Copy chat`,t.setAttribute(`aria-label`,`Copy chat`),t.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="m11.75,18h-7.5c-1.24,0-2.25-1.01-2.25-2.25v-7.5c0-1.24,1.01-2.25,2.25-2.25.41,0,.75.34.75.75s-.34.75-.75.75c-.41,0-.75.34-.75.75v7.5c0,.41.34.75.75.75h7.5c.41,0,.75-.34.75-.75,0-.41.34-.75.75-.75s.75.34.75.75c0,1.24-1.01,2.25-2.25,2.25Z"/><path d="m6.75,5c-.41,0-.75-.34-.75-.75,0-1.24,1.01-2.25,2.25-2.25.41,0,.75.34.75.75s-.34.75-.75.75c-.41,0-.75.34-.75.75,0,.41-.34.75-.75.75Z"/><path d="m13,3.5h-2c-.41,0-.75-.34-.75-.75s.34-.75.75-.75h2c.41,0,.75.34.75.75s-.34.75-.75.75Z"/><path d="m13,14h-2c-.41,0-.75-.34-.75-.75s.34-.75.75-.75h2c.41,0,.75.34.75.75s-.34.75-.75.75Z"/><path d="m15.75,14c-.41,0-.75-.34-.75-.75s.34-.75.75-.75c.41,0,.75-.34.75-.75,0-.41.34-.75.75-.75s.75.34.75.75c0,1.24-1.01,2.25-2.25,2.25Z"/><path d="m17.25,5c-.41,0-.75-.34-.75-.75,0-.41-.34-.75-.75-.75-.41,0-.75-.34-.75-.75s.34-.75.75-.75c1.24,0,2.25,1.01,2.25,2.25,0,.41-.34.75-.75.75Z"/><path d="m17.25,9.75c-.41,0-.75-.34-.75-.75v-2c0-.41.34-.75.75-.75s.75.34.75.75v2c0,.41-.34.75-.75.75Z"/><path d="m6.75,9.75c-.41,0-.75-.34-.75-.75v-2c0-.41.34-.75.75-.75s.75.34.75.75v2c0,.41-.34.75-.75.75Z"/><path d="m8.25,14c-1.24,0-2.25-1.01-2.25-2.25,0-.41.34-.75.75-.75s.75.34.75.75c0,.41.34.75.75.75.41,0,.75.34.75.75s-.34.75-.75.75Z"/></svg>`,t.addEventListener(`click`,async()=>{let e=this.getMessages(),n=``;for(let t of e){let e=t.role===`user`?`User`:`Assistant`;if(n+=`## ${e}\n${t.content}\n\n`,t.attachments?.length&&(n+=`Attachments:\n${t.attachments.map(e=>`- ${u(e)}`).join(`
|
|
281
|
-
`)}\n\n`),t.toolCalls)for(let e of t.toolCalls)n+=`### Tool: ${e.name}\nInput: ${JSON.stringify(e.input,null,2)}\nResult: ${e.result??``}\n\n`}await navigator.clipboard.writeText(n),t.style.color=`var(--s2-positive)`,setTimeout(()=>{t.style.color=``},1500)}),e.appendChild(t),e}createLickEl(e){let t=La(e),{preview:n,body:r}=Va(e.content),i=document.createElement(`details`);i.className=`lick lick--${e.channel??`event`}`;let a=document.createElement(`summary`);a.className=`lick__header`;let o=document.createElement(`span`);if(o.className=`lick__type`,o.textContent=t.label,a.appendChild(o),n){let e=document.createElement(`span`);e.className=`lick__preview`,e.textContent=n,a.appendChild(e)}let s=document.createElement(`span`);s.className=`lick__icon`,s.appendChild(Ha(e)),a.appendChild(s),i.appendChild(a);let c=document.createElement(`div`);return c.className=`lick__details`,c.innerHTML=oi(r),i.appendChild(c),i}createToolCallEl(e,t=!1){let n=ha(e.name),r=ga(e),i=document.createElement(`details`);i.className=`tool-call tool-call--${r}${t?` tool-call--stale`:``}`;let a=document.createElement(`summary`);a.className=`tool-call__header`;let o=document.createElement(`span`);o.className=`tool-call__icon`,o.appendChild(_a(e.name)),a.appendChild(o);let s=document.createElement(`span`);s.className=`tool-call__name`,s.textContent=n.title,a.appendChild(s);let c=n.preview(e.input);if(c){let e=document.createElement(`span`);e.className=`tool-call__preview`,e.textContent=c,a.appendChild(e)}let l=document.createElement(`span`);l.className=`tool-call__status tool-call__status--${r}`,l.setAttribute(`aria-label`,r),a.appendChild(l),i.appendChild(a);let u=document.createElement(`div`);u.className=`tool-call__details`,u.appendChild(va(e));let d=e._screenshotDataUrl;if(d){let e=document.createElement(`img`);e.src=d,e.className=`tool-call__screenshot`,e.title=`Click to view full size`,e.addEventListener(`click`,e=>{e.stopPropagation();let t=window.open(`about:blank`);if(t){let e=t.document.createElement(`img`);e.src=d,t.document.title=`Screenshot`,t.document.body.style.margin=`0`,t.document.body.style.background=document.documentElement.classList.contains(`theme-light`)?`#f0f0f0`:`#141414`,t.document.body.appendChild(e)}}),u.appendChild(e)}return i.appendChild(u),i}scrollToBottom(e=!1){if(!e&&!this.autoScrollAttached){this.showJumpPill();return}requestAnimationFrame(()=>{this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this.lastScrollTop=this.messagesEl.scrollTop})}showJumpPill(){this.jumpPill.classList.add(`chat__jump-pill--visible`)}hideJumpPill(){this.jumpPill.classList.remove(`chat__jump-pill--visible`)}persistSession(){this.sessionStore.saveMessages(this.sessionId,this.messages).catch(()=>{})}
|
|
280
|
+
`:return`\\n`;case`\r`:return`\\r`;case` `:return`\\t`;default:return`\\u${e.codePointAt(0)?.toString(16).padStart(4,`0`)??`0000`}`}}function oo(e){let t=``,n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(!n){t+=i,i===`"`&&(n=!0);continue}if(i===`"`){t+=i,n=!1;continue}if(i===`\\`){let n=e[r+1];if(n===void 0){t+=`\\\\`;continue}if(n===`u`){let n=e.slice(r+2,r+6);if(/^[0-9a-fA-F]{4}$/.test(n)){t+=`\\u${n}`,r+=5;continue}}if(ro.has(n)){t+=`\\${n}`,r+=1;continue}t+=`\\\\`;continue}t+=io(i)?ao(i):i}return t}function so(e){try{return JSON.parse(e)}catch(t){let n=oo(e);if(n!==e)return JSON.parse(n);throw t}}function co(e){if(!e||e.trim()===``)return{};try{return so(e)}catch{try{return(0,no.parse)(e)??{}}catch{try{return(0,no.parse)(oo(e))??{}}catch{return{}}}}}var lo=`tray`,uo=`trayWorkerUrl`,fo=`lead`;function po(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``,t.pathname!==`/`&&(t.pathname=t.pathname.replace(/\/+$/,``)||`/`);let n=t.toString();return n.endsWith(`/`)?n.slice(0,-1):n}catch{return null}}function mo(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``;let n=t.toString(),r=t.pathname.split(`/`).filter(Boolean);if(r.length<2||r.at(-2)!==`join`)return null;let[i,a,...o]=decodeURIComponent(r.at(-1)).split(`.`);if(!i||!a||o.length>0)return null;r.splice(-2,2),t.pathname=r.length>0?`/${r.join(`/`)}`:`/`;let s=po(t.toString());return s?{workerBaseUrl:s,trayId:i,joinUrl:n}:null}catch{return null}}function ho(e,t){let n=new URL(e);return n.searchParams.delete(uo),n.searchParams.delete(fo),n.searchParams.set(lo,t),n.toString()}var go=`slicc.trayWorkerBaseUrl`,_o=`slicc.trayJoinUrl`,vo=`https://www.sliccy.ai`;function yo(e,t){let n=po(e);if(!n)throw Error(`Invalid tray worker base URL: ${e}`);let r=t.replace(/^\/+/,``);return new URL(r,`${n}/`).toString()}function bo(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``;let n=t.pathname.split(`/`).filter(Boolean),r=null;if(n.length>=2&&n.at(-2)===`tray`)r=decodeURIComponent(n.at(-1)),n.splice(-2,2),t.pathname=n.length>0?`/${n.join(`/`)}`:`/`;else if(n.length>=2&&n.at(-2)===`join`)return mo(t.toString());let i=po(t.toString());return i?{workerBaseUrl:i,trayId:r,joinUrl:null}:null}catch{return null}}function xo(e){let t=bo(e);return t?.joinUrl?t:null}function So(e,t){let n=xo(t);return n?(e.setItem(_o,n.joinUrl),e.setItem(go,n.workerBaseUrl),n):null}function Co(e){return!!xo(e?.getItem(`slicc.trayJoinUrl`)??null)}function wo(e,t){let n=po(e);if(!n)throw Error(`Invalid tray worker base URL: ${e}`);let r=t?.trim();return r?new URL(`tray/${encodeURIComponent(r)}`,`${n}/`).toString():n}function To(e,t,n){return ho(e,wo(t,n))}async function Eo(e){let t=Oo(e.locationHref);if(t)return e.storage&&(t.joinUrl&&e.storage.setItem(_o,t.joinUrl),e.storage.setItem(go,t.workerBaseUrl)),t;let n=xo(e.storage?.getItem(`slicc.trayJoinUrl`)??null);if(n)return e.storage&&e.storage.setItem(go,n.workerBaseUrl),n;let r=e.runtimeConfigFetcher?await ko(e.runtimeConfigFetcher):null;if(r?.joinConfig)return e.storage&&(e.storage.setItem(_o,r.joinConfig.joinUrl),e.storage.setItem(go,r.joinConfig.workerBaseUrl)),r.joinConfig;let i=r?.workerBaseUrl??null,a=po(e.storage?.getItem(`slicc.trayWorkerBaseUrl`)??null),o=po(e.envBaseUrl??null),s=po(e.defaultWorkerBaseUrl??null),c=i??a??o??s;return c?(e.storage&&e.storage.setItem(go,c),{workerBaseUrl:c,trayId:null,joinUrl:null}):null}async function Do(e=fetch){try{let t=await e(`/api/runtime-config`,{cache:`no-store`});return t.ok?await t.json():null}catch{return null}}function Oo(e){try{let t=new URL(e),n=bo(t.searchParams.get(lo));if(n)return n;let r=bo(t.searchParams.get(fo));if(r)return r;let i=po(t.searchParams.get(uo));return i?{workerBaseUrl:i,trayId:null,joinUrl:null}:mo(e)||null}catch{return null}}async function ko(e){let t=await e();if(!t)return null;let n=xo(t.trayJoinUrl??null);return{workerBaseUrl:po(t.trayWorkerBaseUrl??null),joinConfig:n}}var Ao={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function jo(){return{...Ao}}function Mo(e){Ao={...e}}function No(e){Ao={...Ao,lastPingTime:e}}var Po=i(`chat-panel`),Fo=5*1024*1024,Io=512*1024;function Lo(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function Ro(e,t=18){let n=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);n.setAttribute(`xmlns`,`http://www.w3.org/2000/svg`),n.setAttribute(`width`,String(t)),n.setAttribute(`height`,String(t)),n.setAttribute(`viewBox`,`0 0 24 24`),n.setAttribute(`fill`,`none`),n.setAttribute(`stroke`,`currentColor`),n.setAttribute(`stroke-width`,`2`),n.setAttribute(`stroke-linecap`,`round`),n.setAttribute(`stroke-linejoin`,`round`);for(let[t,r]of e){let e=document.createElementNS(`http://www.w3.org/2000/svg`,t);for(let[t,n]of Object.entries(r))e.setAttribute(t,String(n));n.appendChild(e)}return n}function zo(e){let t=32768,n=Array(Math.ceil(e.length/t)),r=0;for(let i=0;i<e.length;i+=t){let a=e.subarray(i,i+t);n[r++]=String.fromCharCode(...a)}return btoa(n.join(``))}async function Bo(e){return zo(new Uint8Array(await e.arrayBuffer()))}async function Vo(e){return typeof e.text==`function`?e.text():new TextDecoder().decode(await e.arrayBuffer())}function Ho(e,t){return t.startsWith(`text/`)||t===`application/json`||t===`application/xml`||t===`image/svg+xml`?!0:/\.(?:md|markdown|txt|csv|tsv|json|jsonl|yaml|yml|xml|html|css|js|mjs|ts|tsx|jsx|py|rb|go|rs|java|c|cc|cpp|h|hpp|sh|bash|zsh|sql)$/i.test(e.name)}function Uo(e){return e.role===`assistant`?si(e.content):oi(e.content)}var Wo=class{container;messagesEl;messagesInner;inputArea;textarea;sendBtn;stopBtn;micBtn;attachBtn;fileInput;attachmentsEl;pendingAttachments=[];attachmentReadInProgress=!1;attachmentWriter=null;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;dips=new Map;onDipLick;modelSelectorEl;onModelChange;lickPersistQueues=new Map;constructor(e){this.container=e,this.sessionStore=new fi,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}setAttachmentWriter(e){this.attachmentWriter=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{}}async persistLickToSession(e,t){let n=(this.lickPersistQueues.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.writeLickToSession(e,t));return this.lickPersistQueues.set(e,n),n.finally(()=>{this.lickPersistQueues.get(e)===n&&this.lickPersistQueues.delete(e)}),n}async writeLickToSession(e,t){try{let n=(await this.sessionStore.load(e))?.messages??[];if(n.some(e=>e.id===t.id))return;let r={id:t.id,role:`user`,content:t.content,timestamp:t.timestamp,source:`lick`,channel:t.channel},i=n.length;for(let e=n.length-1;e>=0;e--){if(n[e].timestamp<=t.timestamp){i=e+1;break}i=e}n.splice(i,0,r),await this.sessionStore.saveMessages(e,n)}catch{}}setProcessing(e){e?this.setStreamingState(!0):this.setStreamingState(!1)}addSystemMessage(e){let t={id:Lo(),role:`assistant`,content:e,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t),this.persistSession()}addLickMessage(e,t,n,r){let i=r??Date.now();if(this.messages.some(t=>t.id===e))return;let a={id:e,role:`user`,content:t,timestamp:i,source:`lick`,channel:n},o=this.messages.length;for(let e=this.messages.length-1;e>=0;e--){if(this.messages[e].timestamp<=i){o=e+1;break}o=e}o===this.messages.length?(this.messages.push(a),this.appendMessageEl(a)):(this.messages.splice(o,0,a),this.renderMessages()),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()}addUserMessage(e,t){let n={id:Lo(),role:`user`,content:e,attachments:t,timestamp:Date.now()};this.messages.push(n),this.appendMessageEl(n)}async addAttachmentsFromFiles(e){let t=Array.from(e).filter(e=>e instanceof File);if(t.length!==0){this.attachmentReadInProgress=!0,this.attachBtn?.classList.add(`chat__attach-btn--busy`);try{for(let e of t){let t=await this.createAttachmentFromFile(e);t&&this.pendingAttachments.push(t)}this.renderPendingAttachments(),this.updateSendButtonState()}finally{this.attachmentReadInProgress=!1,this.attachBtn?.classList.remove(`chat__attach-btn--busy`),this.updateSendButtonState()}}}async createAttachmentFromFile(e){let t=e.type||mi(e.name),n=l(t),r=Ho(e,t);if(n&&e.size<=Fo){let n=await a({type:`image`,mimeType:t,data:await Bo(e)});if(n.type===`image`)return{id:Lo(),name:e.name,mimeType:n.mimeType,size:e.size,kind:`image`,data:n.data}}if(r&&e.size<=Io)return{id:Lo(),name:e.name,mimeType:t,size:e.size,kind:`text`,text:await Vo(e)};let i=n?`image`:r?`text`:`file`;if(this.attachmentWriter)try{let n=await this.attachmentWriter(e);return{id:Lo(),name:e.name,mimeType:t,size:e.size,kind:i,path:n}}catch(n){Po.error(`Failed to persist attachment to VFS`,n);let r=n instanceof Error?n.message:String(n);return this.addSystemMessage(`Could not save attachment ${e.name} to /tmp: ${r}`),{id:Lo(),name:e.name,mimeType:t,size:e.size,kind:i,error:`Could not be saved to the virtual filesystem: ${r}`}}return r&&e.size>Io?{id:Lo(),name:e.name,mimeType:t,size:e.size,kind:`text`,error:`Text attachment is above the ${O(Io)} inline limit.`}:n&&e.size>Fo?{id:Lo(),name:e.name,mimeType:t,size:e.size,kind:`image`,error:`Image attachment is above the ${O(Fo)} inline limit.`}:{id:Lo(),name:e.name,mimeType:t,size:e.size,kind:`file`}}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.container.appendChild(this.messagesEl),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.attachBtn=document.createElement(`button`),this.attachBtn.className=`chat__attach-btn`,this.attachBtn.type=`button`,this.attachBtn.appendChild(Ro(Xe,18)),this.attachBtn.dataset.tooltip=`Attach files`,this.fileInput=document.createElement(`input`),this.fileInput.className=`chat__file-input`,this.fileInput.type=`file`,this.fileInput.multiple=!0,this.fileInput.tabIndex=-1,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`,this.attachmentsEl=document.createElement(`div`),this.attachmentsEl.className=`chat__attachments`,c.appendChild(this.attachmentsEl),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.attachBtn),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),c.appendChild(this.fileInput),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.adjustTextareaHeight(),this.updateSendButtonState()}),this.sendBtn.addEventListener(`click`,()=>this.sendMessage()),this.attachBtn.addEventListener(`click`,()=>this.fileInput.click()),this.fileInput.addEventListener(`change`,()=>{let e=this.fileInput.files;e?.length&&this.addAttachmentsFromFiles(e),this.fileInput.value=``}),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 Si({onTranscript:(e,t)=>{this.textarea.value=e,this.adjustTextareaHeight()},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=>{Po.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:wi()}),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),this.renderPendingAttachments(),this.updateSendButtonState()}toggleVoiceMode(){this.voiceMode=!this.voiceMode,this.micBtn.classList.toggle(`chat__mic-btn--active`,this.voiceMode),this.voiceMode?this.voiceInput?.start():this.voiceInput?.stop()}adjustTextareaHeight(){let e=this.container.clientHeight||(typeof window<`u`?window.innerHeight:0)||0,t=Math.max(18,Math.floor(e*.3));this.textarea.style.height=`auto`;let n=this.textarea.scrollHeight,r=Math.min(n,t);this.textarea.style.height=r+`px`,this.textarea.style.overflowY=n>t?`auto`:`hidden`}resetTextareaHeight(){this.textarea.style.height=`auto`,this.textarea.style.overflowY=`hidden`}sendMessage(){if(this.attachmentReadInProgress)return;let e=this.textarea.value.trim(),t=this.pendingAttachments.map(e=>({...e}));if(!e&&t.length===0)return;this.autoScrollAttached=!0,this.hideJumpPill();let n=this.isStreaming,r={id:Lo(),role:`user`,content:e,attachments:t.length>0?t:void 0,timestamp:Date.now(),queued:n||void 0};this.messages.push(r),this.appendMessageEl(r),this.persistSession(),this.textarea.value=``,this.pendingAttachments=[],this.renderPendingAttachments(),this.resetTextareaHeight(),this.updateSendButtonState(),this.isStreaming||this.setStreamingState(!0),this.agent?.sendMessage(e,r.id,t)}handleAgentEvent(e){switch(Po.debug(`Agent event`,{type:e.type}),e.type){case`message_start`:this.handleMessageStart(e.messageId);break;case`content_delta`:this.handleContentDelta(e.messageId,e.text);break;case`content_done`:this.handleContentDone(e.messageId);break;case`tool_use_start`:this.handleToolUseStart(e.messageId,e.toolName,e.toolInput);break;case`tool_result`:this.handleToolResult(e.messageId,e.toolName,e.result,e.isError);break;case`tool_ui`:this.handleToolUI(e.messageId,e.toolName,e.requestId,e.html);break;case`tool_ui_done`:this.handleToolUIDone(e.messageId,e.requestId);break;case`turn_end`:this.handleTurnEnd(e.messageId);break;case`error`:this.handleError(e.error);break;case`screenshot`:break;case`terminal_output`:this.terminalOutputCallback?.(e.text);break}}handleMessageStart(e){this.setStreamingState(!0),this.currentStreamId=e;let t={id:e,role:`assistant`,content:``,timestamp:Date.now(),isStreaming:!0,toolCalls:[]};this.messages.push(t),this.appendMessageEl(t)}handleContentDelta(e,t){this.findMessage(e)&&(this.pendingDeltaText+=t,this.streamingRafId===null&&(this.streamingRafId=requestAnimationFrame(()=>this.flushPendingDelta())))}handleContentDone(e){if(this.pendingDeltaText&&this.currentStreamId===e){let t=this.findMessage(e);t&&(t.content+=this.pendingDeltaText)}this.cancelPendingDelta();let t=this.findMessage(e);t&&(t.isStreaming=!1,this.updateMessageEl(e))}handleToolUseStart(e,t,n){let r=this.findMessage(e);r&&(r.toolCalls||=[],r.toolCalls.push({id:Lo(),name:t,input:n}),this.updateMessageEl(e))}handleToolResult(e,t,n,r){let i=this.findMessage(e);if(!i||!i.toolCalls)return;let a=[...i.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);if(a){let e=n.match(/<img:(data:image\/[^>]+)>/);a.result=n.replace(/<img:data:image\/[^>]+>/g,``).trim(),e&&(a._screenshotDataUrl=e[1]),a.isError=r}this.updateMessageEl(e)}handleToolUI(e,t,n,r,i=0){let a=this.findMessage(e);if(!a||!a.toolCalls){if(i<10){setTimeout(()=>this.handleToolUI(e,t,n,r,i+1),100);return}Po.warn(`handleToolUI: message or toolCalls not found after retries`,{messageId:e});return}let o=[...a.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);if(!o){Po.warn(`handleToolUI: no matching tool call found`,{messageId:e,toolName:t});return}o._toolUIRequestId=n;let s=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);if(!s){if(i<10){setTimeout(()=>this.handleToolUI(e,t,n,r,i+1),100);return}Po.warn(`handleToolUI: wrapper element not found after retries`,{messageId:e});return}let c=[...s.querySelectorAll(`.tool-call`)].reverse().find(e=>e.querySelector(`.tool-call__name`)?.textContent===t);if(c){c instanceof HTMLDetailsElement&&(c.open=!0);let e=c.querySelector(`.tool-call__ui`);e||(e=document.createElement(`div`),e.className=`tool-call__ui`,c.appendChild(e)),ua(e,n,r)}else i<10?setTimeout(()=>this.handleToolUI(e,t,n,r,i+1),100):Po.warn(`handleToolUI: tool call element not found in DOM after retries`,{toolName:t})}handleToolUIDone(e,t){da(t)}handleTurnEnd(e){this.setStreamingState(!1),this.currentStreamId=null,this.persistSession()}handleError(e){this.setStreamingState(!1),this.currentStreamId=null;let t=this.messages[this.messages.length-1];if(t?.role===`assistant`&&t.isStreaming)t.isStreaming=!1,t.content+=`\n\n**Error:** ${e}`,this.updateMessageEl(t.id);else{let t={id:Lo(),role:`assistant`,content:`**Error:** ${e}`,timestamp:Date.now()};this.messages.push(t),this.appendMessageEl(t)}this.persistSession()}setStreamingState(e){this.isStreaming=e;try{this.renderModelSelector()}catch{}if(this.stopBtn.style.display=e?`flex`:`none`,this.sendBtn.style.display=e?`none`:`flex`,this.updateSendButtonState(),this.textarea.disabled=!1,e){this.voiceInput?.isListening()&&this.voiceInput.stop(),this.micBtn.classList.remove(`chat__mic-btn--listening`);let e=this.messages.find(e=>e.queued);e&&(e.queued=!1,this.updateMessageEl(e.id))}e||(this.voiceMode?(this.micBtn.classList.add(`chat__mic-btn--listening`),this.voiceInput?.start()):this.textarea.focus())}renderModelSelector(){let e=this.modelSelectorEl;if(!e)return;for(;e.firstChild;)e.removeChild(e.firstChild);let t=v(),n=w(),r=m(),i=[];for(let e of t)for(let t of e.models)i.push({providerId:e.providerId,id:t.id,name:t.name,reasoning:t.reasoning});i.sort((e,t)=>e.reasoning===t.reasoning?e.name.localeCompare(t.name):e.reasoning?-1:1);let a=i.find(e=>e.id===n&&e.providerId===r)||i[0];if(!a)return;let o=this.isStreaming,s=document.createElement(`button`);if(s.className=`chat__model-btn chat__model-btn--compact`,o&&s.classList.add(`chat__model-btn--disabled`),s.textContent=a.name,!o){let e=document.createElement(`span`);e.className=`chat__model-chevron`,e.innerHTML=`<svg width="12" height="12" viewBox="0 0 16 16" fill="currentColor"><path d="M4.5 6l3.5 4 3.5-4z"/></svg>`,s.appendChild(e)}if(o)e.appendChild(s);else{let t=!1,a=document.createElement(`div`);a.className=`chat__model-menu`;let o=()=>{for(a.style.display=t?`block`:`none`;a.firstChild;)a.removeChild(a.firstChild);if(t)for(let e of i){let i=document.createElement(`div`);i.className=`chat__model-menu-item`;let o=e.id===n&&e.providerId===r;o&&i.classList.add(`chat__model-menu-item--active`);let s=document.createElement(`span`);if(s.textContent=e.name,i.appendChild(s),o){let e=document.createElement(`span`);e.className=`chat__model-check`,e.innerHTML=`<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M6.5 12.5l-4-4 1.4-1.4 2.6 2.6 5.6-5.6 1.4 1.4z"/></svg>`,i.appendChild(e)}i.addEventListener(`click`,()=>{let n=`${e.providerId}:${e.id}`;S(n),this.onModelChange?.(n),t=!1,this.renderModelSelector()}),a.appendChild(i)}};s.addEventListener(`click`,e=>{e.stopPropagation(),t=!t,o()}),document.addEventListener(`click`,()=>{t=!1,o()},{once:!0}),e.appendChild(s),e.appendChild(a),o()}}refreshModelSelector(){this.renderModelSelector()}findMessage(e){return this.messages.find(t=>t.id===e)}flushPendingDelta(){if(this.streamingRafId=null,!this.pendingDeltaText||!this.currentStreamId)return;let e=this.findMessage(this.currentStreamId);if(!e){this.pendingDeltaText=``;return}e.content+=this.pendingDeltaText,this.pendingDeltaText=``,this.updateStreamingContent(this.currentStreamId)}cancelPendingDelta(){this.streamingRafId!==null&&(cancelAnimationFrame(this.streamingRafId),this.streamingRafId=null),this.pendingDeltaText=``}updateStreamingContent(e){let t=this.findMessage(e);if(!t)return;let n=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);if(!n)return;let r=n.querySelector(`.msg__content`);if(r){if(r.innerHTML=Uo(t),t.isStreaming){let e=document.createElement(`span`);e.className=`streaming-cursor`,r.appendChild(e)}}else if(t.content.trim().length>0){this.updateMessageEl(e);return}this.scrollToBottom()}updateSendButtonState(){if(!this.sendBtn||!this.textarea)return;let e=this.textarea.value.trim().length>0;this.sendBtn.disabled=this.attachmentReadInProgress||!e&&this.pendingAttachments.length===0,this.attachBtn&&(this.attachBtn.disabled=this.attachmentReadInProgress)}renderPendingAttachments(){if(this.attachmentsEl){this.attachmentsEl.innerHTML=``,this.attachmentsEl.classList.toggle(`chat__attachments--visible`,this.pendingAttachments.length>0);for(let e of this.pendingAttachments)this.attachmentsEl.appendChild(this.createAttachmentChip(e,{removable:!0,onRemove:()=>{this.pendingAttachments=this.pendingAttachments.filter(t=>t.id!==e.id),this.renderPendingAttachments(),this.updateSendButtonState()}}))}}createAttachmentList(e){let t=document.createElement(`div`);t.className=`msg__attachments`;for(let n of e)t.appendChild(this.createAttachmentChip(n));return t}createAttachmentChip(e,t={}){let n=document.createElement(`div`);n.className=`attachment-chip attachment-chip--${e.kind}`,n.title=u(e);let r=document.createElement(`span`);if(r.className=`attachment-chip__visual`,e.kind===`image`&&e.data){let t=document.createElement(`img`);t.src=`data:${e.mimeType};base64,${e.data}`,t.alt=e.name||`Attached image`,r.appendChild(t)}else{let t=e.kind===`text`?Be:e.mimeType.startsWith(`image/`)?Ke:Ve;r.appendChild(Ro(t,16))}n.appendChild(r);let i=document.createElement(`span`);i.className=`attachment-chip__body`;let a=document.createElement(`span`);a.className=`attachment-chip__name`,a.textContent=e.name,i.appendChild(a);let o=document.createElement(`span`);if(o.className=`attachment-chip__meta`,o.textContent=e.error?`not included`:`${e.mimeType||`file`} · ${O(e.size)}`,i.appendChild(o),e.path){let t=document.createElement(`span`);t.className=`attachment-chip__path`,t.textContent=e.path,t.title=e.path,i.appendChild(t)}if(n.appendChild(i),t.removable){let r=document.createElement(`button`);r.className=`attachment-chip__remove`,r.type=`button`,r.title=`Remove ${e.name}`,r.appendChild(Ro(ct,14)),r.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),t.onRemove?.()}),n.appendChild(r)}return n}renderMessages(){this.disposeAllDips(),this.messagesInner.innerHTML=``;let e=null,t=0,n=-1;for(let e=this.messages.length-1;e>=0;e--)if(this.messages[e].role===`assistant`){n=e;break}let r=this.findLastRealUserIdx();for(let i=0;i<this.messages.length;i++){let a=this.messages[i],o=this.shouldShowLabel(a,e,t),s=r>i,c=this.createMessageEl(a,o,i===n,s);this.messagesInner.appendChild(c),e=a.role,t=a.timestamp}this.autoScrollAttached=!0,this.hideJumpPill(),this.scrollToBottom(!0)}appendMessageEl(e){let t=this.messagesInner.querySelector(`.msg__feedback`);t&&t.remove();let n=this.messages.length>=2?this.messages[this.messages.length-2]:null,r=this.shouldShowLabel(e,n?.role??null,n?.timestamp??0),i=e.role===`assistant`;this.isRealUserTurn(e)&&this.messagesInner.querySelectorAll(`.tool-call`).forEach(e=>e.classList.add(`tool-call--stale`));let a=this.createMessageEl(e,r,i);this.messagesInner.appendChild(a),this.scrollToBottom()}shouldShowLabel(e,t,n){return!!(e.source===`lick`||Ga(e.channel)||e.role!==t||e.timestamp-n>12e4)}updateMessageEl(e){let t=this.findMessage(e);if(!t)return;let n=this.messagesEl.querySelector(`[data-msg-id="${e}"]`);if(n){this.disposeDipsForMessage(e);let r=this.messages.indexOf(t),i=r>0?this.messages[r-1]:null,a=this.shouldShowLabel(t,i?.role??null,i?.timestamp??0),o=!1;if(t.role===`assistant`){let e=-1;for(let t=this.messages.length-1;t>=0;t--)if(this.messages[t].role===`assistant`){e=t;break}o=r===e}let s=this.findLastRealUserIdx()>r,c=this.createMessageEl(t,a,o,s);n.replaceWith(c)}this.scrollToBottom()}isRealUserTurn(e){return!(e.role!==`user`||e.source===`lick`||e.source===`delegation`||e.channel===`delegation`)}findLastRealUserIdx(){for(let e=this.messages.length-1;e>=0;e--)if(this.isRealUserTurn(this.messages[e]))return e;return-1}createMessageEl(e,t=!0,n=!1,r=!1){if(e.source===`lick`||Ga(e.channel)){let t=document.createElement(`div`);return t.className=`msg-group`,t.setAttribute(`data-msg-id`,e.id),t.appendChild(this.createLickEl(e)),t}let i=document.createElement(`div`);i.className=`msg-group${t?``:` msg-group--continuation`}`,i.setAttribute(`data-msg-id`,e.id);let a=document.createElement(`div`);if(a.className=`msg msg--${e.role}${e.queued?` msg--queued`:``}`,t){let t,n,r=this.currentScoopName!==null;e.role===`user`?e.source===`delegation`||e.channel===`delegation`?(t=`S`,n=`sliccy`):(t=`U`,n=`You`):r?(t=(this.currentScoopName||`S`).charAt(0).toUpperCase(),n=`@${this.currentScoopName}`):e.source&&e.source!==`cone`?(t=e.source.charAt(0).toUpperCase(),n=e.source):(t=`S`,n=`sliccy`);let i=document.createElement(`div`);i.className=`msg__role`;let o=document.createElement(`span`);if(o.className=`msg__icon`,o.textContent=t,i.appendChild(o),i.appendChild(document.createTextNode(` ${n}`)),e.queued){let t=document.createElement(`span`);t.className=`msg__queued-badge`,t.textContent=`queued`,i.appendChild(t);let n=document.createElement(`button`);n.className=`msg__queued-delete`,n.textContent=`×`,n.title=`Remove queued message`,n.addEventListener(`click`,t=>{t.stopPropagation(),this.deleteQueuedMessage(e.id)}),i.appendChild(n)}a.appendChild(i)}let o=(e.source===`lick`||Ga(e.channel))&&this.sessionId===`session-cone`,s=e.source&&e.source!==`cone`&&e.source!==`lick`&&e.role===`assistant`&&this.sessionId===`session-cone`;if(o||s){let t=document.createElement(`details`);t.className=`msg__collapsible`;let n=document.createElement(`summary`);n.className=`msg__summary`,n.textContent=e.content.slice(0,60).replace(/\n/g,` `)+(e.content.length>60?`...`:``),t.appendChild(n);let r=document.createElement(`div`);r.className=`msg__content`,r.innerHTML=Uo(e),e.attachments?.length&&t.appendChild(this.createAttachmentList(e.attachments)),e.isStreaming||this.hydrateDipsInEl(r,e.id),t.appendChild(r),a.appendChild(t)}else{e.attachments?.length&&a.appendChild(this.createAttachmentList(e.attachments));let t=document.createElement(`div`);if(t.className=`msg__content`,t.innerHTML=Uo(e),e.isStreaming){let e=document.createElement(`span`);e.className=`streaming-cursor`,t.appendChild(e)}else this.hydrateDipsInEl(t,e.id);a.appendChild(t)}let c=e.content.trim().length>0||!!e.attachments?.length;if(c&&i.appendChild(a),e.toolCalls)for(let t of e.toolCalls)i.appendChild(this.createToolCallEl(t,r));return e.role===`assistant`&&!e.isStreaming&&!e.queued&&c&&n&&i.appendChild(this.createFeedbackRow()),i}createFeedbackRow(){let e=document.createElement(`div`);e.className=`msg__feedback`;let t=document.createElement(`button`);return t.className=`msg__feedback-btn`,t.dataset.tooltip=`Copy chat`,t.setAttribute(`aria-label`,`Copy chat`),t.innerHTML=`<svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor"><path d="m11.75,18h-7.5c-1.24,0-2.25-1.01-2.25-2.25v-7.5c0-1.24,1.01-2.25,2.25-2.25.41,0,.75.34.75.75s-.34.75-.75.75c-.41,0-.75.34-.75.75v7.5c0,.41.34.75.75.75h7.5c.41,0,.75-.34.75-.75,0-.41.34-.75.75-.75s.75.34.75.75c0,1.24-1.01,2.25-2.25,2.25Z"/><path d="m6.75,5c-.41,0-.75-.34-.75-.75,0-1.24,1.01-2.25,2.25-2.25.41,0,.75.34.75.75s-.34.75-.75.75c-.41,0-.75.34-.75.75,0,.41-.34.75-.75.75Z"/><path d="m13,3.5h-2c-.41,0-.75-.34-.75-.75s.34-.75.75-.75h2c.41,0,.75.34.75.75s-.34.75-.75.75Z"/><path d="m13,14h-2c-.41,0-.75-.34-.75-.75s.34-.75.75-.75h2c.41,0,.75.34.75.75s-.34.75-.75.75Z"/><path d="m15.75,14c-.41,0-.75-.34-.75-.75s.34-.75.75-.75c.41,0,.75-.34.75-.75,0-.41.34-.75.75-.75s.75.34.75.75c0,1.24-1.01,2.25-2.25,2.25Z"/><path d="m17.25,5c-.41,0-.75-.34-.75-.75,0-.41-.34-.75-.75-.75-.41,0-.75-.34-.75-.75s.34-.75.75-.75c1.24,0,2.25,1.01,2.25,2.25,0,.41-.34.75-.75.75Z"/><path d="m17.25,9.75c-.41,0-.75-.34-.75-.75v-2c0-.41.34-.75.75-.75s.75.34.75.75v2c0,.41-.34.75-.75.75Z"/><path d="m6.75,9.75c-.41,0-.75-.34-.75-.75v-2c0-.41.34-.75.75-.75s.75.34.75.75v2c0,.41-.34.75-.75.75Z"/><path d="m8.25,14c-1.24,0-2.25-1.01-2.25-2.25,0-.41.34-.75.75-.75s.75.34.75.75c0,.41.34.75.75.75.41,0,.75.34.75.75s-.34.75-.75.75Z"/></svg>`,t.addEventListener(`click`,async()=>{let e=this.getMessages(),n=``;for(let t of e){let e=t.role===`user`?`User`:`Assistant`;if(n+=`## ${e}\n${t.content}\n\n`,t.attachments?.length&&(n+=`Attachments:\n${t.attachments.map(e=>`- ${u(e)}`).join(`
|
|
281
|
+
`)}\n\n`),t.toolCalls)for(let e of t.toolCalls)n+=`### Tool: ${e.name}\nInput: ${JSON.stringify(e.input,null,2)}\nResult: ${e.result??``}\n\n`}await navigator.clipboard.writeText(n),t.style.color=`var(--s2-positive)`,setTimeout(()=>{t.style.color=``},1500)}),e.appendChild(t),e}createLickEl(e){let t=La(e),{preview:n,body:r}=Va(e.content),i=document.createElement(`details`);i.className=`lick lick--${e.channel??`event`}`;let a=document.createElement(`summary`);a.className=`lick__header`;let o=document.createElement(`span`);if(o.className=`lick__type`,o.textContent=t.label,a.appendChild(o),n){let e=document.createElement(`span`);e.className=`lick__preview`,e.textContent=n,a.appendChild(e)}let s=document.createElement(`span`);s.className=`lick__icon`,s.appendChild(Ha(e)),a.appendChild(s),i.appendChild(a);let c=document.createElement(`div`);return c.className=`lick__details`,c.innerHTML=oi(r),i.appendChild(c),i}createToolCallEl(e,t=!1){let n=ha(e.name),r=ga(e),i=document.createElement(`details`);i.className=`tool-call tool-call--${r}${t?` tool-call--stale`:``}`;let a=document.createElement(`summary`);a.className=`tool-call__header`;let o=document.createElement(`span`);o.className=`tool-call__icon`,o.appendChild(_a(e.name)),a.appendChild(o);let s=document.createElement(`span`);s.className=`tool-call__name`,s.textContent=n.title,a.appendChild(s);let c=n.preview(e.input);if(c){let e=document.createElement(`span`);e.className=`tool-call__preview`,e.textContent=c,a.appendChild(e)}let l=document.createElement(`span`);l.className=`tool-call__status tool-call__status--${r}`,l.setAttribute(`aria-label`,r),a.appendChild(l),i.appendChild(a);let u=document.createElement(`div`);u.className=`tool-call__details`,u.appendChild(va(e));let d=e._screenshotDataUrl;if(d){let e=document.createElement(`img`);e.src=d,e.className=`tool-call__screenshot`,e.title=`Click to view full size`,e.addEventListener(`click`,e=>{e.stopPropagation();let t=window.open(`about:blank`);if(t){let e=t.document.createElement(`img`);e.src=d,t.document.title=`Screenshot`,t.document.body.style.margin=`0`,t.document.body.style.background=document.documentElement.classList.contains(`theme-light`)?`#f0f0f0`:`#141414`,t.document.body.appendChild(e)}}),u.appendChild(e)}return i.appendChild(u),i}scrollToBottom(e=!1){if(!e&&!this.autoScrollAttached){this.showJumpPill();return}requestAnimationFrame(()=>{this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this.lastScrollTop=this.messagesEl.scrollTop})}showJumpPill(){this.jumpPill.classList.add(`chat__jump-pill--visible`)}hideJumpPill(){this.jumpPill.classList.remove(`chat__jump-pill--visible`)}persistSession(){this.sessionStore.saveMessages(this.sessionId,this.messages).catch(()=>{})}disposeDipsForMessage(e){let t=this.dips.get(e);t&&(Yi(t),this.dips.delete(e))}disposeAllDips(){for(let[,e]of this.dips)Yi(e);this.dips.clear()}hydrateDipsInEl(e,t){let n=Ji(e,(e,t)=>this.onDipLick?.(e,t));this.dips.set(t,n)}dispose(){this.cancelPendingDelta(),this.disposeAllDips(),this.unsubscribe?.(),this.voiceInput?.destroy(),this.keydownListener&&=(document.removeEventListener(`keydown`,this.keydownListener),null),this.container.innerHTML=``}},Go=class{container;terminalViewEl;previewViewEl;previewEmptyEl;previewBtn;shell=null;activeView=`terminal`;onClearTerminal;constructor(e,t={}){this.container=e,this.onClearTerminal=t.onClearTerminal??null,this.render()}async mountShell(e){this.shell?.setPreviewStateListener(null),this.shell=e;let t=document.createElement(`div`);t.className=`terminal-panel__mount`,this.terminalViewEl.appendChild(t),await e.mount(t);let n=t.querySelector(`.terminal-panel__terminal-host`),r=t.querySelector(`.terminal-panel__preview`);if(!n||!r)throw Error(`terminal mount did not create expected hosts`);this.terminalViewEl.replaceChildren(n),this.previewViewEl.replaceChildren(this.previewEmptyEl),this.previewViewEl.appendChild(r),e.setPreviewStateListener(e=>this.handlePreviewStateChange(e))}clearTerminal(){this.shell?.clearTerminal()}async runCommand(e){return this.shell?(/^\s*imgcat(?:\s|$)/.test(e)||this.setActiveView(`terminal`),this.shell.executeCommandInTerminal(e)):{stdout:``,stderr:`terminal is unavailable
|
|
282
282
|
`,exitCode:1}}refit(){this.shell?.refit()}getBodyElement(){return this.container}render(){this.container.innerHTML=``,this.container.classList.add(`terminal-panel`);let e=document.createElement(`div`);e.className=`file-browser__header`;let t=document.createElement(`span`);if(t.className=`file-browser__header-title`,t.textContent=`Terminal`,e.appendChild(t),this.onClearTerminal){let t=document.createElement(`button`);t.className=`file-browser__header-btn`,t.dataset.tooltip=`Clear Terminal`,t.setAttribute(`aria-label`,`Clear Terminal`),t.innerHTML=`<svg width="14" height="14" viewBox="0 0 20 20" fill="none"><path d="m8.249,15.021c-.4,0-.733-.317-.748-.72l-.25-6.5c-.017-.414.307-.763.72-.778.01-.001.021-.001.03-.001.4,0,.733.317.748.72l.25,6.5c.017.414-.307.763-.72.778-.01.001-.021.001-.03.001Z" fill="currentColor"/><path d="m11.751,15.021c-.01,0-.02,0-.03-.001-.413-.016-.736-.364-.72-.778l.25-6.5c.015-.403.348-.72.748-.72.01,0,.02,0,.03.001.413.016.736.364.72.778l-.25,6.5c-.015.403-.348.72-.748.72Z" fill="currentColor"/><path d="m17,4h-3.5v-.75c0-1.24-1.01-2.25-2.25-2.25h-2.5c-1.24,0-2.25,1.01-2.25,2.25v.75h-3.5c-.414,0-.75.336-.75.75s.336.75.75.75h.52l.422,10.342c.048,1.21,1.036,2.158,2.248,2.158h7.619c1.212,0,2.2-.948,2.248-2.158l.422-10.342h.52c.414,0,.75-.336.75-.75s-.336-.75-.75-.75Zm-9-.75c0-.413.337-.75.75-.75h2.5c.413,0,.75.337.75.75v.75h-4v-.75Zm6.56,12.531c-.017.403-.346.719-.75.719h-7.619c-.404,0-.733-.316-.75-.719l-.42-10.281h9.959l-.42,10.281Z" fill="currentColor"/></svg>`,t.addEventListener(`click`,()=>this.onClearTerminal()),e.appendChild(t)}this.previewBtn=document.createElement(`button`),this.previewBtn.className=`file-browser__header-btn`,this.previewBtn.setAttribute(`aria-label`,`Toggle preview`),this.previewBtn.dataset.tooltip=`Preview`,this.previewBtn.disabled=!0;let n=`http://www.w3.org/2000/svg`,r=document.createElementNS(n,`svg`);r.setAttribute(`width`,`16`),r.setAttribute(`height`,`16`),r.setAttribute(`viewBox`,`0 0 20 20`),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`1.5`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`);let i=document.createElementNS(n,`path`);i.setAttribute(`d`,`M2 10s3-6 8-6 8 6 8 6-3 6-8 6-8-6-8-6z`),r.appendChild(i);let a=document.createElementNS(n,`circle`);a.setAttribute(`cx`,`10`),a.setAttribute(`cy`,`10`),a.setAttribute(`r`,`2.5`),r.appendChild(a),this.previewBtn.appendChild(r),this.previewBtn.addEventListener(`click`,()=>{this.previewBtn.disabled||this.setActiveView(this.activeView===`preview`?`terminal`:`preview`)}),e.appendChild(this.previewBtn),this.container.appendChild(e),this.terminalViewEl=document.createElement(`div`),this.terminalViewEl.className=`terminal-panel__view`,this.container.appendChild(this.terminalViewEl),this.previewViewEl=document.createElement(`div`),this.previewViewEl.className=`terminal-panel__view`,this.container.appendChild(this.previewViewEl),this.previewEmptyEl=document.createElement(`div`),this.previewEmptyEl.className=`terminal-panel__empty-state`,this.previewEmptyEl.textContent=`Run imgcat to preview media here.`,this.previewViewEl.appendChild(this.previewEmptyEl),this.setActiveView(`terminal`)}dispose(){this.shell?.setPreviewStateListener(null),this.shell?.dispose(),this.container.innerHTML=``}setActiveView(e){this.activeView=e,this.previewBtn.classList.toggle(`file-browser__header-btn--active`,e===`preview`),this.terminalViewEl.style.display=e===`terminal`?`flex`:`none`,this.previewViewEl.style.display=e===`preview`?`flex`:`none`,e===`terminal`&&this.refit()}handlePreviewStateChange(e){this.previewBtn.disabled=!e,this.previewEmptyEl.style.display=e?`none`:`flex`,e?this.setActiveView(`preview`):this.activeView===`preview`&&this.setActiveView(`terminal`)}};function Ko(e){return e<1024?e+` B`:e<1024*1024?(e/1024).toFixed(1)+`K`:e<1024*1024*1024?(e/(1024*1024)).toFixed(1)+`M`:(e/(1024*1024*1024)).toFixed(1)+`G`}function qo(e){let t=`http://www.w3.org/2000/svg`,n=document.createElementNS(t,`svg`);n.setAttribute(`width`,`14`),n.setAttribute(`height`,`14`),n.setAttribute(`viewBox`,`0 0 20 20`),n.setAttribute(`fill`,`none`),n.setAttribute(`stroke`,`currentColor`),n.setAttribute(`stroke-width`,`1.5`),n.setAttribute(`stroke-linecap`,`round`),n.setAttribute(`stroke-linejoin`,`round`),n.style.flexShrink=`0`;for(let r of e){let e=document.createElementNS(t,`path`);e.setAttribute(`d`,r),n.appendChild(e)}return n}function Jo(){return qo([`M2 6V5a1 1 0 0 1 1-1h4l2 2h8a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V6z`])}function Yo(){return qo([`M6 2h5l5 5v9a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1z`,`M11 2v5h5`])}function Xo(e){let t=`http://www.w3.org/2000/svg`,n=document.createElementNS(t,`svg`);n.setAttribute(`width`,`10`),n.setAttribute(`height`,`10`),n.setAttribute(`viewBox`,`0 0 20 20`),n.setAttribute(`fill`,`none`),n.setAttribute(`stroke`,`currentColor`),n.setAttribute(`stroke-width`,`2`),n.setAttribute(`stroke-linecap`,`round`),n.setAttribute(`stroke-linejoin`,`round`),n.style.flexShrink=`0`,n.style.transition=`transform 130ms ease`,e&&(n.style.transform=`rotate(90deg)`);let r=document.createElementNS(t,`path`);return r.setAttribute(`d`,`M7 5l5 5-5 5`),n.appendChild(r),n}function Zo(e){return`'${e.replace(/'/g,`'\\''`)}'`}function Qo(e){return`${vi(e)?`imgcat`:`cat`} ${Zo(e)}`}var $o=class{container;bodyEl;fs=null;expandedDirs=new Set([`/`]);refreshTimer=null;onRunCommand;selectedPath=null;keydownHandler=null;constructor(e,t={}){this.container=e,this.onRunCommand=t.onRunCommand??null,this.render()}setFs(e){this.fs=e,this.refresh(),this.refreshTimer=setInterval(()=>this.refresh(),3e3)}async refresh(){if(!this.fs)return;let e=document.createElement(`div`);try{await this.renderDir(`/`,e,0)}catch(e){console.warn(`[FileBrowser] Refresh failed:`,e instanceof Error?e.message:String(e));return}if(e.innerHTML===this.bodyEl.innerHTML){this.applySelection();return}let t=this.container.contains(document.activeElement);for(;this.bodyEl.firstChild;)this.bodyEl.removeChild(this.bodyEl.firstChild);for(;e.firstChild;)this.bodyEl.appendChild(e.firstChild);this.applySelection(),t&&this.selectedPath&&this.bodyEl.querySelector(`.file-browser__item--selected`)?.focus()}render(){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.container.classList.add(`file-browser`);let e=document.createElement(`div`);e.className=`file-browser__header`;let t=document.createElement(`span`);t.className=`file-browser__header-title`,t.textContent=`Files`,e.appendChild(t),this.container.appendChild(e),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`file-browser__body`,this.container.appendChild(this.bodyEl),this.setupKeydown()}async renderDir(e,t,n){if(!this.fs)return;let r;try{r=await this.fs.readDir(e)}catch(t){console.warn(`[FileBrowser] readDir failed:`,e,t instanceof Error?t.message:String(t));return}let i=r.filter(e=>e.type===`directory`).sort((e,t)=>e.name.localeCompare(t.name)),a=r.filter(e=>e.type===`file`).sort((e,t)=>e.name.localeCompare(t.name));for(let r of[...i,...a]){let i=e===`/`?`/`+r.name:e+`/`+r.name,a=document.createElement(`div`);if(a.className=`file-browser__item`,a.style.paddingLeft=12+n*16+`px`,a.dataset.path=r.type===`directory`&&!i.endsWith(`/`)?i+`/`:i,r.type===`directory`){let e=this.expandedDirs.has(i),o=document.createElement(`span`);o.className=`file-browser__arrow`,o.appendChild(Xo(e)),a.appendChild(o);let s=document.createElement(`span`);s.className=`file-browser__icon`,s.appendChild(Jo()),a.appendChild(s);let c=document.createElement(`span`);c.className=`file-browser__name`,c.textContent=r.name,a.appendChild(c);let l=document.createElement(`button`);l.className=`file-browser__action-btn`,l.style.marginLeft=`auto`,l.textContent=`ZIP`,l.title=`Download as ZIP`,l.addEventListener(`click`,e=>{e.stopPropagation(),this.downloadDirAsZip(i,r.name)}),a.appendChild(l),a.style.cursor=`pointer`,a.addEventListener(`click`,()=>{this.selectPath(i,`directory`),this.expandedDirs.has(i)?this.expandedDirs.delete(i):this.expandedDirs.add(i),this.refresh()}),t.appendChild(a),e&&await this.renderDir(i,t,n+1)}else{let e=document.createElement(`span`);e.className=`file-browser__arrow`,a.appendChild(e);let n=document.createElement(`span`);n.className=`file-browser__icon`,n.appendChild(Yo()),a.appendChild(n);let o=document.createElement(`span`);o.className=`file-browser__name`,o.textContent=r.name,a.appendChild(o);try{let e=await this.fs.stat(i),t=document.createElement(`span`);t.className=`file-browser__size`,t.textContent=Ko(e.size),a.appendChild(t)}catch(e){console.warn(`[FileBrowser] stat failed:`,i,e instanceof Error?e.message:String(e))}let s=document.createElement(`button`);s.className=`file-browser__action-btn`,s.style.marginLeft=`8px`,s.textContent=`CAT`,s.title=this.onRunCommand?vi(i)?`Preview media in terminal`:`Preview in terminal`:`Terminal unavailable`,s.disabled=!this.onRunCommand,s.addEventListener(`click`,e=>{e.stopPropagation(),this.previewFile(i)}),a.appendChild(s),a.addEventListener(`click`,()=>{this.selectPath(i,`file`)}),t.appendChild(a)}}}async collectFiles(e,t){if(!this.fs)return{};let n={},r=await this.fs.readDir(e);for(let i of r){let r=e===`/`?`/`+i.name:e+`/`+i.name,a=t?t+`/`+i.name:i.name;if(i.type===`directory`){let e=await this.collectFiles(r,a);Object.assign(n,e)}else{let e=await this.fs.readFile(r,{encoding:`binary`});n[a]=e instanceof Uint8Array?e:new TextEncoder().encode(e)}}return n}async downloadDirAsZip(e,t){if(this.fs)try{let n=re(await this.collectFiles(e,``)),r=new Blob([n.buffer],{type:`application/zip`}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=t+`.zip`,a.click(),URL.revokeObjectURL(i)}catch(t){console.error(`[FileBrowser] ZIP download failed:`,e,t instanceof Error?t.message:String(t))}}previewFile(e){if(!this.onRunCommand)return;let t=Qo(e);Promise.resolve(this.onRunCommand(t)).catch(t=>{console.error(`[FileBrowser] Preview command failed:`,e,t instanceof Error?t.message:String(t))})}selectPath(e,t){this.selectedPath=t===`directory`&&!e.endsWith(`/`)?e+`/`:e,this.applySelection(),this.bodyEl.querySelector(`.file-browser__item--selected`)?.focus()}applySelection(){let e=this.bodyEl.querySelector(`.file-browser__item--selected`);if(e&&(e.classList.remove(`file-browser__item--selected`),e.removeAttribute(`tabindex`)),!this.selectedPath)return;let t=this.bodyEl.querySelectorAll(`.file-browser__item`);for(let e of t)if(e.dataset.path===this.selectedPath){e.classList.add(`file-browser__item--selected`),e.tabIndex=0;break}}setupKeydown(){this.keydownHandler=e=>{!(e.metaKey||e.ctrlKey)||e.key!==`c`||this.selectedPath&&window.getSelection()?.isCollapsed!==!1&&(e.preventDefault(),navigator.clipboard.writeText(this.selectedPath).then(()=>{this.flashCopyFeedback()}).catch(e=>{console.warn(`[FileBrowser] Clipboard write failed:`,e instanceof Error?e.message:String(e))}))},this.container.addEventListener(`keydown`,this.keydownHandler)}flashCopyFeedback(){let e=this.bodyEl.querySelector(`.file-browser__item--selected`);e&&(e.classList.add(`file-browser__item--copy-flash`),setTimeout(()=>{e.classList.remove(`file-browser__item--copy-flash`)},300))}dispose(){for(this.keydownHandler&&=(this.container.removeEventListener(`keydown`,this.keydownHandler),null),this.refreshTimer&&=(clearInterval(this.refreshTimer),null);this.container.firstChild;)this.container.removeChild(this.container.firstChild)}},es=class{container;bodyEl;orchestrator=null;selectedScoopJid=null;refreshTimer=null;constructor(e){this.container=e,this.render()}setOrchestrator(e){this.orchestrator=e,this.refresh(),this.refreshTimer=setInterval(()=>this.refresh(),5e3)}setSelectedScoop(e){this.selectedScoopJid=e,this.refresh()}async refresh(){if(!this.orchestrator)return;let e=document.createElement(`div`);e.className=`memory-panel__content`;let t=document.createElement(`div`);t.className=`memory-panel__section`;let n=document.createElement(`div`);n.className=`memory-panel__section-header`,n.textContent=`Global Memory (/shared/CLAUDE.md)`,t.appendChild(n);let r=document.createElement(`div`);r.className=`memory-panel__memory-content`;try{r.textContent=await this.orchestrator.getGlobalMemory()||`(empty)`}catch{r.textContent=`(not available)`}if(t.appendChild(r),e.appendChild(t),this.selectedScoopJid){let t=this.orchestrator.getScoopContext(this.selectedScoopJid),n=this.orchestrator.getScoop(this.selectedScoopJid);if(t&&n){let r=document.createElement(`div`);r.className=`memory-panel__section`;let i=document.createElement(`div`);i.className=`memory-panel__section-header`,i.textContent=`${n.isCone?`Cone`:`Scoop`}: ${n.assistantLabel}`,r.appendChild(i);let a=document.createElement(`div`);a.className=`memory-panel__memory-content`;try{let e=t.getFS();if(e){let t=n.isCone?`/workspace/CLAUDE.md`:`/scoops/${n.folder}/CLAUDE.md`,r=await e.readFile(t,{encoding:`utf-8`});a.textContent=typeof r==`string`?r:new TextDecoder().decode(r)}else a.textContent=`(filesystem not ready)`}catch{a.textContent=`(no memory file yet)`}r.appendChild(a),e.appendChild(r)}}if(e.innerHTML!==this.bodyEl.innerHTML){for(;this.bodyEl.firstChild;)this.bodyEl.removeChild(this.bodyEl.firstChild);for(;e.firstChild;)this.bodyEl.appendChild(e.firstChild)}}render(){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.container.classList.add(`memory-panel`),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`memory-panel__body`,this.container.appendChild(this.bodyEl)}dispose(){this.refreshTimer&&=(clearInterval(this.refreshTimer),null)}},ts=i(`scoops-panel`),ns=class e{container;orchestrator=null;callbacks;selectedScoopJid=null;scoopStatuses=new Map;expanded=!1;eyesEl=null;hoveredJid=null;lastProcessingJid=null;coneJid=null;leftPupilGroup=null;rightPupilGroup=null;eyesSvg=null;mouseMoveBound=null;constructor(e,t){this.container=e,this.callbacks=t,this.render()}dispose(){this.mouseMoveBound&&=(document.removeEventListener(`mousemove`,this.mouseMoveBound),null),this.eyesEl?.remove(),this.eyesEl=null,this.eyesSvg=null,this.leftPupilGroup=null,this.rightPupilGroup=null,document.querySelectorAll(`.scoop-fixed-tooltip`).forEach(e=>e.remove())}toggleExpanded(){this.expanded=!this.expanded,this.container.classList.toggle(`layout__scoops--expanded`,this.expanded)}static LEFT_EYE={cx:55,cy:50,r:38};static RIGHT_EYE={cx:145,cy:50,r:38};static PUPIL_R=18;static MAX_OFFSET=16;createEyesEl(){let t=`http://www.w3.org/2000/svg`,n=document.createElement(`div`);n.className=`scoop-eyes`;let r=document.createElementNS(t,`svg`);r.setAttribute(`viewBox`,`0 0 200 100`),r.setAttribute(`width`,`100%`),r.setAttribute(`height`,`100%`);let{LEFT_EYE:i,RIGHT_EYE:a,PUPIL_R:o}=e,s=e=>{let n=document.createElementNS(t,`circle`);n.setAttribute(`cx`,String(e.cx)),n.setAttribute(`cy`,String(e.cy)),n.setAttribute(`r`,String(e.r)),n.setAttribute(`fill`,`#fff`),n.setAttribute(`stroke`,`#000`),n.setAttribute(`stroke-width`,`4`),r.appendChild(n);let i=document.createElementNS(t,`g`),a=document.createElementNS(t,`circle`);a.setAttribute(`cx`,String(e.cx)),a.setAttribute(`cy`,String(e.cy)),a.setAttribute(`r`,String(o)),a.setAttribute(`fill`,`#000`),i.appendChild(a);let s=document.createElementNS(t,`circle`);return s.setAttribute(`cx`,String(e.cx-o*.3)),s.setAttribute(`cy`,String(e.cy-o*.35)),s.setAttribute(`r`,String(o*.4)),s.setAttribute(`fill`,`#fff`),i.appendChild(s),r.appendChild(i),i};return this.leftPupilGroup=s(i),this.rightPupilGroup=s(a),n.appendChild(r),this.eyesSvg=r,this.mouseMoveBound||(this.mouseMoveBound=e=>this.onMouseMove(e),document.addEventListener(`mousemove`,this.mouseMoveBound)),n}onMouseMove(t){if(!this.eyesSvg||!this.leftPupilGroup||!this.rightPupilGroup)return;let n=this.eyesSvg.getBoundingClientRect();if(n.width===0||n.height===0)return;let r=200/n.width,i=100/n.height,a=(t.clientX-n.left)*r,o=(t.clientY-n.top)*i,{LEFT_EYE:s,RIGHT_EYE:c,MAX_OFFSET:l}=e;this.positionPupilGroup(this.leftPupilGroup,s.cx,s.cy,a,o,l),this.positionPupilGroup(this.rightPupilGroup,c.cx,c.cy,a,o,l)}positionPupilGroup(e,t,n,r,i,a){let o=r-t,s=i-n,c=Math.sqrt(o*o+s*s),l=Math.min(c,a),u=c>0?o/c*l:0,d=c>0?s/c*l:0;e.setAttribute(`transform`,`translate(${u},${d})`)}resolveEyesOwner(){if(this.hoveredJid&&this.hasScoopItem(this.hoveredJid))return this.hoveredJid;if(this.lastProcessingJid&&this.scoopStatuses.get(this.lastProcessingJid)===`processing`&&this.hasScoopItem(this.lastProcessingJid))return this.lastProcessingJid;for(let[e,t]of this.scoopStatuses)if(t===`processing`&&this.hasScoopItem(e))return this.lastProcessingJid=e,e;return this.coneJid}hasScoopItem(e){return!!this.container.querySelector(`.scoop-item[data-jid="${CSS.escape(e)}"]`)}moveEyes(){this.eyesEl||=this.createEyesEl();let e=this.resolveEyesOwner();if(!e)return;let t=this.container.querySelector(`.scoop-item[data-jid="${CSS.escape(e)}"]`);if(!t)return;let n=t.querySelector(`.scoop-icon-wrap`);n&&this.eyesEl.parentElement!==n&&n.appendChild(this.eyesEl)}setOrchestrator(e){this.orchestrator=e,this.refreshScoops()}updateScoopStatus(e,t){this.scoopStatuses.set(e,t),t===`processing`&&(this.lastProcessingJid=e),this.refreshScoops()}refreshScoops(){if(!this.orchestrator)return;document.querySelectorAll(`.scoop-fixed-tooltip`).forEach(e=>e.remove());let e=this.orchestrator.getScoops(),t=e.find(e=>e.isCone),n=e.filter(e=>!e.isCone),r=`http://www.w3.org/2000/svg`,i=[{base:`#FFB6C1`,outline:`#B97B88`},{base:`#98FB98`,outline:`#65AC65`},{base:`#87CEEB`,outline:`#5591AC`},{base:`#DDA0DD`,outline:`#9F649F`},{base:`#F0E68C`,outline:`#A9A059`},{base:`#FFD700`,outline:`#B89700`},{base:`#FFA07A`,outline:`#B86E50`},{base:`#DEB887`,outline:`#9F8260`},{base:`#F08080`,outline:`#AC5656`},{base:`#E0BBE4`,outline:`#A085A4`}],a=i.map(e=>e.base),o=i.map(e=>e.outline),s=this.container.querySelector(`.scoop-cone-header`);if(s){for(;s.firstChild;)s.removeChild(s.firstChild);if(t){this.coneJid=t.jid;let e=this.scoopStatuses.get(t.jid)??`inactive`,n=t.jid===this.selectedScoopJid,i=`#D2691E`,a=`#8B4513`,o=`#E8A75C`,c=document.createElement(`div`);c.className=`scoop-item scoop-item--cone ${n?`selected`:``} status-${e}`,c.dataset.jid=t.jid,c.setAttribute(`aria-label`,t.assistantLabel),c.style.setProperty(`--scoop-accent`,a),c.style.setProperty(`--scoop-bg`,i);let l=document.createElement(`div`);l.className=`scoop-icon-wrap scoop-icon-wrap--cone`,l.style.width=`40px`,l.style.height=`40px`;let u=document.createElementNS(r,`svg`);if(u.setAttribute(`width`,`24`),u.setAttribute(`height`,`24`),u.setAttribute(`viewBox`,`70 330 440 570`),u.innerHTML=`<path d="M108.22,414.88l189.84,460.03c1.36,3.3,6.09,3.16,7.25-.22l159.34-463.34c.87-2.53-1.03-5.16-3.7-5.13l-349.18,3.32c-2.74.03-4.59,2.82-3.55,5.35Z" fill="${i}" stroke="${a}" stroke-linejoin="round" stroke-width="20"/><path d="M261.93,482.48h0c15.03-15.03,4.46-40.72-16.79-40.83h0c-21.37-.11-32.14,25.72-17.03,40.83h0c9.34,9.34,24.48,9.34,33.82,0Z" fill="${o}"/><path d="M384.85,527.49l-51.82,51.82c-2.24,2.24-2.24,5.86,0,8.1l55.71,55.71c2.24,2.24,5.86,2.24,8.1,0h0c.62-.62,1.08-1.36,1.37-2.19l26.52-77.11c.71-2.07.18-4.36-1.37-5.91l-30.41-30.41c-2.24-2.24-5.86-2.24-8.1,0Z" fill="${o}"/><rect x="274.59" y="463.59" width="84.73" height="95.66" rx="42.36" ry="42.36" transform="translate(-268.79 373.91) rotate(-45)" fill="${o}"/><rect x="291.06" y="603.84" width="72.24" height="90.24" rx="36.12" ry="36.12" transform="translate(-363.06 421.43) rotate(-45)" fill="${o}"/><path d="M371.7,684.58l-25.94,25.94c-2.24,2.24-2.24,5.86,0,8.1l12.67,12.67c2.99,2.99,8.09,1.82,9.46-2.19l13.28-38.61c1.97-5.74-5.17-10.2-9.46-5.91Z" fill="${o}"/><path d="M159.42,564.14l2.73,6.83c1.52,3.82,6.46,4.83,9.37,1.93l2.05-2.05c2.24-2.24,2.24-5.86,0-8.1l-4.78-4.78c-4.4-4.4-11.67.39-9.37,6.17Z" fill="${o}"/><path d="M243.92,633.11l-48.65-48.65c-5.24-5.24-13.74-5.24-18.99,0h0c-3.8,3.8-4.97,9.49-2.98,14.47l27.77,69.54c3.58,8.95,15.14,11.33,21.96,4.51l20.89-20.89c5.24-5.24,5.24-13.74,0-18.99Z" fill="${o}"/><path d="M211.32,533.1h0c14.11-14.11,14.11-36.98,0-51.08l-34.94-34.94c-.72-.72-.72-1.89,0-2.62h0c1.16-1.16.34-3.15-1.3-3.16l-11.23-.06c-25.62-.13-43.23,25.72-33.73,49.51l5.37,13.45c1.82,4.55,4.54,8.68,8,12.15l16.74,16.74c14.11,14.11,36.98,14.11,51.08,0Z" fill="${o}"/><path d="M263.74,792.53h0c-5.69,5.69-7.45,14.23-4.46,21.71l22.5,56.36c6.92,17.34,31.68,16.74,37.75-.92l8.66-25.2c2.5-7.28.64-15.35-4.8-20.79l-31.17-31.17c-7.87-7.87-20.62-7.87-28.48,0Z" fill="${o}"/><path d="M392.94,503.07l40.81-40.81c2.24-2.24,5.86-2.24,8.1,0l.06.06c2.24,2.24,2.24,5.86,0,8.1l-40.81,40.81c-2.24,2.24-2.24,5.86,0,8.1l22.48,22.48c2.99,2.99,8.09,1.82,9.46-2.19l30.71-89.32c1.27-3.71-1.47-7.57-5.39-7.59l-120.63-.6c-5.11-.03-7.69,6.16-4.08,9.77l51.18,51.18c2.24,2.24,5.86,2.24,8.1,0Z" fill="${o}"/><rect x="217.18" y="527.25" width="72.24" height="95.66" rx="36.12" ry="36.12" transform="translate(-332.45 347.55) rotate(-45)" fill="${o}"/><path d="M350.28,739.46h0c-9.24-9.24-24.22-9.24-33.46,0l-13.94,13.94c-9.24,9.24-9.24,24.22,0,33.46l6.81,6.81c12.37,12.37,33.42,7.5,39.1-9.04l7.13-20.75c2.94-8.55.75-18.03-5.64-24.42Z" fill="${o}"/><path d="M234.18,749.12l13.2,33.06c1.52,3.82,6.46,4.83,9.37,1.93l9.93-9.93c2.24-2.24,2.24-5.86,0-8.1l-23.13-23.13c-4.4-4.4-11.67.39-9.37,6.17Z" fill="${o}"/><rect x="236.26" y="661.25" width="67.04" height="90.24" rx="33.52" ry="33.52" transform="translate(-420.46 397.65) rotate(-45)" fill="${o}"/><ellipse cx="288.37" cy="404.38" rx="182.34" ry="67.01" fill="${i}" stroke="${a}" stroke-miterlimit="10" stroke-width="20"/>`,l.appendChild(u),e===`processing`||e===`ready`||e===`error`){let t=document.createElement(`span`);t.className=`scoop-dot scoop-dot--${e}`,l.appendChild(t)}c.appendChild(l);let d=document.createElement(`div`);d.className=`scoop-info`;let f=document.createElement(`div`);if(f.className=`scoop-name`,f.textContent=t.assistantLabel,d.appendChild(f),e===`processing`||e===`error`){let t=document.createElement(`div`);t.className=`scoop-subtitle`,t.textContent=e===`processing`?`Working…`:`Error`,d.appendChild(t)}c.appendChild(d);let p=document.createElement(`div`);if(p.className=`scoop-actions`,e===`processing`){let e=document.createElement(`span`);e.className=`scoop-spin-dot`,p.appendChild(e)}else if(e===`error`){let e=document.createElement(`span`);e.className=`scoop-err-dot`,p.appendChild(e)}c.appendChild(p),c.addEventListener(`click`,()=>this.selectScoop(t)),c.addEventListener(`mouseenter`,()=>{this.hoveredJid=t.jid,this.moveEyes()}),c.addEventListener(`mouseleave`,()=>{this.hoveredJid===t.jid&&(this.hoveredJid=null),this.moveEyes()});let m=t.assistantLabel;c.addEventListener(`mouseenter`,()=>{if(this.expanded)return;let e=document.createElement(`div`);e.className=`scoop-fixed-tooltip`,e.textContent=m,document.body.appendChild(e);let t=c.getBoundingClientRect();e.style.top=`${t.top+t.height/2}px`,e.style.left=`${t.right+8}px`,c.__tip=e}),c.addEventListener(`mouseleave`,()=>{let e=c.__tip;e&&(e.remove(),c.__tip=null)}),s.appendChild(c)}}let c=this.container.querySelector(`.scoops-list`);if(c){for(;c.firstChild;)c.removeChild(c.firstChild);if(n.length===0){this.callbacks.onScoopsChanged?.(e),this.moveEyes();return}for(let e=0;e<n.length;e++){let t=n[e],i=this.scoopStatuses.get(t.jid)??`inactive`,s=t.jid===this.selectedScoopJid,l=a[e%a.length],u=o[e%o.length],d=document.createElement(`div`);d.className=`scoop-item ${s?`selected`:``} status-${i}`,d.dataset.jid=t.jid;let f=t.assistantLabel.replace(/-scoop$/,``);d.setAttribute(`aria-label`,f),d.style.setProperty(`--scoop-accent`,u),d.style.setProperty(`--scoop-bg`,l);let p=document.createElement(`div`);p.className=`scoop-icon-wrap`;let m=document.createElementNS(r,`svg`);m.setAttribute(`width`,`20`),m.setAttribute(`height`,`20`),m.setAttribute(`viewBox`,`0 0 580 470`);let h=document.createElementNS(r,`path`);if(h.setAttribute(`d`,`M566.75,340.67c0-29.85-12.97-56.87-33.96-76.47,4.8-9.98,7.44-20.71,7.44-31.9,0-38.29-30.62-71.33-74.92-86.77.33-3.07.51-6.17.51-9.3,0-69.72-84.29-126.24-188.26-126.24s-188.26,56.52-188.26,126.24c0,4,.29,7.95.83,11.86-34.94,15.4-58.48,44.25-58.48,77.34,0,18.21,7.15,35.15,19.39,49.26-25.1,19.88-41.05,49.47-41.05,82.54,0,59.85,52.15,108.37,116.49,108.37,10.83,0,21.3-1.4,31.26-3.98,31.42,41.91,83.55,69.34,142.55,69.34,64.73,0,121.2-33,151.11-81.94,63.8-.57,115.34-48.85,115.34-108.34Z`),h.setAttribute(`fill`,l),h.setAttribute(`stroke`,u),h.setAttribute(`stroke-width`,`20`),m.appendChild(h),p.appendChild(m),i===`processing`||i===`ready`||i===`error`){let e=document.createElement(`span`);e.className=`scoop-dot scoop-dot--${i}`,p.appendChild(e)}d.appendChild(p);let g=document.createElement(`div`);g.className=`scoop-info`;let _=document.createElement(`div`);if(_.className=`scoop-name`,_.textContent=f,g.appendChild(_),i===`processing`||i===`error`){let e=document.createElement(`div`);e.className=`scoop-subtitle`,e.textContent=i===`processing`?`Working…`:`Error`,g.appendChild(e)}d.appendChild(g);let v=document.createElement(`div`);if(v.className=`scoop-actions`,i===`processing`){let e=document.createElement(`span`);e.className=`scoop-spin-dot`,v.appendChild(e)}else if(i===`error`){let e=document.createElement(`span`);e.className=`scoop-err-dot`,v.appendChild(e)}d.appendChild(v),d.addEventListener(`click`,()=>{this.selectScoop(t)}),d.addEventListener(`mouseenter`,()=>{this.hoveredJid=t.jid,this.moveEyes()}),d.addEventListener(`mouseleave`,()=>{this.hoveredJid===t.jid&&(this.hoveredJid=null),this.moveEyes()}),d.addEventListener(`mouseenter`,()=>{if(this.expanded)return;let e=document.createElement(`div`);e.className=`scoop-fixed-tooltip`,e.textContent=f,document.body.appendChild(e);let t=d.getBoundingClientRect();e.style.top=`${t.top+t.height/2}px`,e.style.left=`${t.right+8}px`,d.__tip=e}),d.addEventListener(`mouseleave`,()=>{let e=d.__tip;e&&(e.remove(),d.__tip=null)}),c.appendChild(d)}this.callbacks.onScoopsChanged?.(e),this.moveEyes()}}selectScoop(e){this.selectedScoopJid=e.jid,this.refreshScoops(),this.callbacks.onScoopSelect(e);let t=new URL(window.location.href);e.isCone?t.searchParams.delete(`scoop`):t.searchParams.set(`scoop`,e.folder),history.replaceState(null,``,t.toString())}selectScoopByFolder(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.folder===e);t&&this.selectScoop(t)}setSelectedJid(e){this.selectedScoopJid=e,this.refreshScoops()}getSelectedScoopJid(){return this.selectedScoopJid}async deleteScoop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoop(e);if(t){if(t.isCone){alert(`Cannot delete the cone`);return}if(confirm(`Delete scoop "${t.name}"? This cannot be undone.`)){try{await this.orchestrator.unregisterScoop(e)}catch(e){let t=e instanceof Error?e.message:String(e);alert(t);return}this.selectedScoopJid===e&&(this.selectedScoopJid=null),this.refreshScoops(),ts.info(`Scoop deleted`,{jid:e,name:t.name})}}}async createCone(e=`Cone`){if(!this.orchestrator)throw Error(`Orchestrator not set`);let t={jid:`cone_${Date.now()}`,name:e,folder:`cone`,requiresTrigger:!1,isCone:!0,type:`cone`,assistantLabel:`sliccy`,addedAt:new Date().toISOString()};return await this.orchestrator.registerScoop(t),this.refreshScoops(),ts.info(`Cone created`,{jid:t.jid,name:e}),t}render(){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);let e=document.createElement(`div`);e.className=`scoops-panel`;let t=document.createElement(`div`);t.className=`scoop-cone-header`,e.appendChild(t);let n=document.createElement(`div`);n.className=`scoops-list`,e.appendChild(n),this.container.appendChild(e);let r=document.createElement(`style`);r.textContent=`
|
|
283
283
|
.scoops-panel {
|
|
284
284
|
display: flex;
|
|
@@ -3870,7 +3870,7 @@ except BaseException:
|
|
|
3870
3870
|
`,stderr:``,exitCode:0}}function O0(e){let t=``,n=8192;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function k0(){return dz(`open`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return D0();if(typeof window>`u`||typeof document>`u`)return{stdout:``,stderr:`open: browser APIs are unavailable in this environment
|
|
3871
3871
|
`,exitCode:1};let n=e.includes(`--download`)||e.includes(`-d`),r=e.includes(`--view`)||e.includes(`-v`),i=e.filter(e=>!E0.includes(e));if(i.length===0)return D0();let a=[];for(let e of i){if(c0(e)){window.open(e,`_blank`,`noopener,noreferrer`),a.push(`opened ${e}`);continue}let i=t.fs.resolvePath(t.cwd,e);if(i.endsWith(`.shtml`)){let e=typeof window<`u`?window.__slicc_sprinkleManager:void 0;if(e){let t=(i.split(`/`).pop()??``).replace(/\.shtml$/,``);try{await e.open(t),a.push(`opened sprinkle ${t} from ${i}`)}catch(e){return{stdout:``,stderr:`open: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}else{let e=p0(i);window.open(e,`_blank`,`noopener,noreferrer`),a.push(`opened ${i} → ${e}`)}continue}if(r){let n;try{n=await t.fs.stat(i)}catch{return{stdout:``,stderr:`open: no such file: ${e}\n`,exitCode:1}}if(!n.isFile)return{stdout:``,stderr:`open: not a file: ${e}\n`,exitCode:1};let r;try{r=await t.fs.readFileBuffer(i)}catch{return{stdout:``,stderr:`open: failed to read: ${e}\n`,exitCode:1}}let o=f0(i),s=O0(new Uint8Array(r));a.push(`${i} (${Math.round(r.byteLength/1024)} KB)\n<img:data:${o};base64,${s}>`)}else if(n){let n;try{n=await t.fs.stat(i)}catch{return{stdout:``,stderr:`open: no such file: ${e}\n`,exitCode:1}}if(!n.isFile)return{stdout:``,stderr:`open: not a file: ${e}\n`,exitCode:1};let r;try{r=await t.fs.readFileBuffer(i)}catch{return{stdout:``,stderr:`open: failed to read: ${e}\n`,exitCode:1}}let o=new Uint8Array(r.byteLength);o.set(r);let s=new Blob([o.buffer],{type:f0(i)}),c=URL.createObjectURL(s),l=document.createElement(`a`);l.href=c,l.download=a0(i)||`download`,l.style.display=`none`,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(c),0),a.push(`downloaded ${i}`)}else{let e=p0(i);window.open(e,`_blank`,`noopener,noreferrer`),a.push(`opened ${i} → ${e}`)}}return{stdout:a.join(`
|
|
3872
3872
|
`)+`
|
|
3873
|
-
`,stderr:``,exitCode:0}})}var A0=null,j0=null;async function M0(){return A0||=k(()=>import(`./es-
|
|
3873
|
+
`,stderr:``,exitCode:0}})}var A0=null,j0=null;async function M0(){return A0||=k(()=>import(`./es-COR0hHNS.js`),__vite__mapDeps([8,4,6])),A0}async function N0(){return j0||=k(()=>import(`./dist-Ehp5JdjU2.js`),__vite__mapDeps([9,1])),j0}function P0(e){return e.endsWith(`right`)?{range:e.slice(0,-5),rotation:90}:e.endsWith(`left`)?{range:e.slice(0,-4),rotation:270}:e.endsWith(`down`)?{range:e.slice(0,-4),rotation:180}:{range:e}}function F0(e){let{range:t,rotation:n}=P0(e);if(/^\d+$/.test(t)){let e=parseInt(t,10);return{start:e,end:e,rotation:n}}let r=t.match(/^(\d+)-(\d+|end)$/);if(r)return{start:parseInt(r[1],10),end:r[2]===`end`?`end`:parseInt(r[2],10),rotation:n};throw Error(`Invalid page range: ${e}`)}function I0(e,t){let n=e.start,r=e.end;if(n<1||n>t)throw Error(`Page ${n} out of range (1-${t})`);let i=r===`end`?t:r;if(i<1||i>t)throw Error(`Page ${i} out of range (1-${t})`);if(i<n)throw Error(`Invalid range: ${n}-${i}`);let a=[];for(let e=n;e<=i;e++)a.push(e);return a}function L0(){return{stdout:`usage: pdftk <input.pdf> <operation> [args...]
|
|
3874
3874
|
|
|
3875
3875
|
Operations:
|
|
3876
3876
|
dump_data Print metadata (page count, title, author, etc.)
|
|
@@ -4057,7 +4057,7 @@ Examples:
|
|
|
4057
4057
|
oauth-token adobe
|
|
4058
4058
|
oauth-token github --scope "repo,models:read"
|
|
4059
4059
|
curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
|
|
4060
|
-
`}function D2(){return dz(`oauth-token`,async e=>{let{getOAuthAccountInfo:t,getSelectedProvider:n,getAccounts:r}=await k(async()=>{let{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}=await import(`./provider-settings-
|
|
4060
|
+
`}function D2(){return dz(`oauth-token`,async e=>{let{getOAuthAccountInfo:t,getSelectedProvider:n,getAccounts:r}=await k(async()=>{let{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}=await import(`./provider-settings-DvtaGASm.js`).then(e=>e.l);return{getOAuthAccountInfo:e,getSelectedProvider:t,getAccounts:n}},__vite__mapDeps([10,4,1,11,12,13])),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await k(async()=>{let{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}=await import(`./provider-settings-DvtaGASm.js`).then(e=>e.h);return{getRegisteredProviderConfig:e,getRegisteredProviderIds:t}},__vite__mapDeps([10,4,1,11,12,13]));if(e.includes(`--help`)||e.includes(`-h`))return{stdout:E2(),stderr:``,exitCode:0};if(e.includes(`--list`))return O2(r,a,i,t);let o,s=e.indexOf(`--scope`);if(s>=0){if(o=e[s+1]?.trim(),!o||o.startsWith(`-`))return{stdout:``,stderr:`oauth-token: --scope requires a value
|
|
4061
4061
|
`,exitCode:1};e.splice(s,2)}let c,l=e.indexOf(`--provider`);if(l>=0){if(c=e[l+1],!c)return{stdout:``,stderr:`oauth-token: --provider requires a value
|
|
4062
4062
|
`,exitCode:1}}else if(e.length>0)c=e[0];else{let e=n(),t=i(e);if(t?.isOAuth&&t.onOAuthLogin)c=e;else if(c=a().find(e=>{let t=i(e);return t?.isOAuth&&t.onOAuthLogin}),!c)return{stdout:``,stderr:`oauth-token: no OAuth providers configured
|
|
4063
4063
|
`,exitCode:1}}let u=i(c);if(!u)return{stdout:``,stderr:`oauth-token: unknown provider "${c}"\n`,exitCode:1};if(!u.isOAuth||!u.onOAuthLogin)return{stdout:``,stderr:`oauth-token: provider "${c}" is not an OAuth provider\n`,exitCode:1};if(!o){let e=t(c);if(e&&!e.expired)return{stdout:`${e.token}\n`,stderr:``,exitCode:0}}try{let{createOAuthLauncher:e}=await k(async()=>{let{createOAuthLauncher:e}=await import(`./oauth-service-DUXASG7L.js`);return{createOAuthLauncher:e}},[]),n=e();await u.onOAuthLogin(n,()=>{},o?{scopes:o}:void 0);let r=t(c);return r&&r.token?{stdout:`${r.token}\n`,stderr:``,exitCode:0}:(console.error(`[oauth-token] Provider ${c}: login completed but no token was saved`),{stdout:``,stderr:`oauth-token: login completed but no token was saved
|
|
@@ -4218,7 +4218,7 @@ Options:
|
|
|
4218
4218
|
-h, --help Show this help message
|
|
4219
4219
|
`}function L4(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function R4(e){return`$${e.toFixed(2)}`}var z4=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function B4(e){let t=`${e.id} ${e.name??``}`;return!z4.test(t)}function V4(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 H4(e){let t=new Map;for(let n of e){let e=V4(n.id);t.has(e)||t.set(e,n)}return[...t.values()]}function U4(e,t,n,r,i){let a=i?F4(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 W4(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=`${R4(e.cost.input)} / ${R4(e.cost.output)}`,a=`${L4(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(`
|
|
4220
4220
|
`)+`
|
|
4221
|
-
`}function G4(e){return dz(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s}=await k(async()=>{let{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}=await import(`./provider-settings-
|
|
4221
|
+
`}function G4(e){return dz(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s}=await k(async()=>{let{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}=await import(`./provider-settings-DvtaGASm.js`).then(e=>e.l);return{getAccounts:e,getAvailableProviders:t,getProviderConfig:n,getProviderModels:r,getSelectedProvider:i,getSelectedModelId:a}},__vite__mapDeps([10,4,1,11,12,13]));if(t.includes(`--help`)||t.includes(`-h`))return{stdout:I4(),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.
|
|
4222
4222
|
`,exitCode:1};let v;f||(v=await N4(e,d),v.length===0&&(v=void 0));let y;if(m){let e=r();if(!e.includes(m))return{stdout:``,stderr:`Unknown provider: ${m}. Available: ${e.join(`, `)}\n`,exitCode:1};y=[m]}else y=l?[...new Set(_.map(e=>e.providerId))]:[h];let b=[],x=[];for(let e of y){let t=a(e).filter(B4);if(t.length===0){if(!l)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>U4(t,e,g,h,v)).sort((e,t)=>t.cost.input-e.cost.input);if(u||(n=H4(n)),b.push(...n),!c){let t=i(e);x.push(W4(t.name,e,n,!!v))}}return c?{stdout:JSON.stringify(b,null,2)+`
|
|
4223
4223
|
`,stderr:``,exitCode:0}:(!u&&!c&&x.push(`Showing latest versions only. Use --all-versions to see all.
|
|
4224
4224
|
`),{stdout:x.join(`
|
|
@@ -15843,7 +15843,7 @@ ${t}
|
|
|
15843
15843
|
... (truncated)`:t.responseText;r.set(e,{summary:n,timedOut:!1})}}let a=n.filter(e=>!r.has(e)),o=a.filter(e=>this.scoops.has(e)),s=a.filter(e=>!this.scoops.has(e));for(let e of s)r.set(e,{summary:null,timedOut:!0});let c=[],l=o.map(e=>new Promise(t=>{let n=n=>{r.has(e)||(r.set(e,{summary:n,timedOut:n===null}),t())};c.push({jid:e,waiter:n});let i=this.completionWaiters.get(e);i||(i=[],this.completionWaiters.set(e,i)),i.push(n)})),u=null;try{l.length>0&&(t!=null&&t>=0?await Promise.race([Promise.all(l),new Promise(e=>{u=setTimeout(()=>e(),t)})]):await Promise.all(l))}finally{u&&clearTimeout(u);for(let{jid:e,waiter:t}of c){let n=this.completionWaiters.get(e);if(!n)continue;let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&this.completionWaiters.delete(e)}for(let e of i)this.mutedScoops.delete(e)}for(let e of o)r.has(e)||r.set(e,{summary:null,timedOut:!0});return e.map(e=>{let t=r.get(e)??{summary:null,timedOut:!0};return{jid:e,summary:t.summary,timedOut:t.timedOut}})}scheduleScoopWait(e,t){let n=Array.from(new Set(e)),r=n.filter(e=>this.scoops.has(e)),i=n.filter(e=>!this.scoops.has(e));return this.waitForScoops(r,t).then(e=>this.deliverWaitResultsToCone(e)).catch(e=>{E5.error(`scheduleScoopWait failed`,{error:e instanceof Error?e.message:String(e)})}),{scheduled:r,unknown:i}}async deliverWaitResultsToCone(e){if(e.length===0)return;let t=Array.from(this.scoops.values()).find(e=>e.isCone);if(!t)return;let n=[`[scoop_wait completed]`],r=0,i=0;for(let t of e){let e=this.scoops.get(t.jid)?.folder??t.jid;t.timedOut?(r+=1,n.push(`--- ${e} (timed out) ---`)):(i+=1,n.push(`--- ${e} ---`),n.push(t.summary??`(no output)`))}let a=`${i} completed, ${r} timed out`;n.splice(1,0,a);let o={id:`scoop-wait-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,chatJid:t.jid,senderId:`scoop-wait`,senderName:`scoop-wait`,content:n.join(`
|
|
15844
15844
|
`),timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-wait`};try{this.callbacks.onIncomingMessage?.(t.jid,o)}catch(e){E5.warn(`onIncomingMessage for scoop-wait threw`,{error:e instanceof Error?e.message:String(e)})}try{await this.handleMessage(o)}catch(e){let n=e instanceof Error?e.message:String(e);E5.error(`Failed to route scoop-wait result to cone`,{error:n}),this.callbacks.onError(t.jid,`scoop_wait completed but notification failed: ${n}`)}}dispatchScoopEvent(e,t,...n){let r=this.scoopObservers.get(e);if(r)for(let i of r){let r=i[t];if(r)try{r(...n)}catch(n){E5.warn(`scoop observer threw`,{jid:e,event:t,error:n instanceof Error?n.message:String(n)})}}}async registerScoop(e){await Oe(e),this.scoops.set(e.jid,e),this.messageQueues.set(e.jid,[]),E5.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createScoopTab(e.jid)}catch(t){throw E5.error(`Scoop init failed`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)}),await this.destroyScoopTab(e.jid).catch(()=>{}),this.scoops.delete(e.jid),this.messageQueues.delete(e.jid),await xe(e.jid).catch(t=>{E5.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),t}}async unregisterScoop(e){let t=this.scoops.get(e);if(t&&this.lickManager){let{webhooks:e,cronTasks:n}=this.lickManager.getLicksForScoop(t.name,t.folder),r=C5(t.folder,e,n);if(r)throw r}this.snapshotScoopCost(e),this.clearIdleTimer(e),await this.destroyScoopTab(e),this.sessionStore?.delete(e).catch(t=>{E5.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await xe(e),this.scoops.delete(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.scoopResponseBuffer.delete(e),this.scoopObservers.delete(e);let n=this.completionWaiters.get(e);if(n){this.completionWaiters.delete(e);for(let t of n)try{t(null)}catch(t){E5.warn(`completion waiter threw on unregister`,{jid:e,error:t instanceof Error?t.message:String(t)})}}this.mutedScoops.delete(e),this.pendingCompletions.delete(e),E5.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 se.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.ensureGlobalMemory(),await Z8(this.sharedFs).catch(e=>{E5.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.droppedScoopCosts=[],E5.info(`Filesystem reset and defaults re-seeded`)}async clearAllMessages(){await F(),this.sessionStore&&await this.sessionStore.clearAll().catch(e=>{E5.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.contexts.values())e.clearMessages();this.lastAgentTimestamp.clear();for(let e of this.scoops.keys())this.messageQueues.set(e,[]);this.droppedScoopCosts=[],E5.info(`All messages cleared`)}async handleMessage(e){E5.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);G6(t?.isCone?`cone`:t?.name??`unknown`,localStorage.getItem(`selected-model`)??`unknown`),await me(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 me(i),this.callbacks.onIncomingMessage?.(e,i),E5.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);E5.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){E5.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}let n=e.channel===`webhook`||e.channel===`cron`||e.channel===`fswatch`||e.channel===`sprinkle`;if(!t.isCone&&t.requiresTrigger&&t.trigger&&!n&&!e.content.includes(t.trigger)){E5.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(E5.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:i?.status??`no-tab`,queueLength:r.length}),i?.status===`error`){E5.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.createScoopTab(e.chatJid),i=this.tabs.get(e.chatJid)}catch{E5.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`)E5.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{E5.debug(`Context already exists`,{jid:e});return}if(!this.sharedFs)throw Error(`Shared filesystem not initialized`);let n=`scoop-${t.folder}-${Date.now()}`,r=t.isCone?this.sharedFs:new ue(this.sharedFs,t.config?.writablePaths?[...t.config.writablePaths]:[],t.config?.visiblePaths?[...t.config.visiblePaths]:[]),i={onResponse:(n,r)=>{if(this.scoops.has(e)&&(this.callbacks.onResponse(e,n,r),this.dispatchScoopEvent(e,`onResponse`,n,r),!t.isCone))if(r){let t=this.scoopResponseBuffer.get(e)??``;this.scoopResponseBuffer.set(e,t+n)}else this.scoopResponseBuffer.set(e,n)},onResponseDone:()=>{if(!this.scoops.has(e))return;let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),this.callbacks.onResponseDone(e)},onError:t=>{if(!this.scoops.has(e))return;let n=this.tabs.get(e);n&&(n.status=`error`,n.error=t,this.tabs.set(e,n)),this.callbacks.onError(e,t),this.callbacks.onStatusChange(e,`error`),this.dispatchScoopEvent(e,`onError`,t),this.dispatchScoopEvent(e,`onStatusChange`,`error`)},onFatalError:t=>{if(!this.scoops.has(e))return;let n=this.scoops.get(e);E5.error(`Fatal scoop error`,{jid:e,folder:n.folder,error:t});let r=this.tabs.get(e);if(r&&(r.status=`error`,r.error=t,this.tabs.set(e,r)),this.callbacks.onError(e,t),this.callbacks.onStatusChange(e,`error`),this.dispatchScoopEvent(e,`onError`,t),this.dispatchScoopEvent(e,`onStatusChange`,`error`),n.isCone)return;this.mutedScoops.delete(e),this.pendingCompletions.delete(e),this.scoopResponseBuffer.delete(e);let i=this.completionWaiters.get(e);if(i&&i.length>0){this.completionWaiters.delete(e);for(let t of i)try{t(null)}catch(t){E5.warn(`completion waiter threw on fatal error`,{jid:e,error:t instanceof Error?t.message:String(t)})}}let a=Array.from(this.scoops.values()).find(e=>e.isCone);if(!a)return;let o={id:`scoop-error-${e}-${Date.now()}`,chatJid:a.jid,senderId:n.folder,senderName:n.assistantLabel,content:`[@${n.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.callbacks.onIncomingMessage?.(a.jid,o)}catch(e){E5.warn(`onIncomingMessage for scoop-error threw`,{scoop:n.folder,error:e instanceof Error?e.message:String(e)})}this.handleMessage(o).catch(e=>{E5.error(`Failed to route fatal error to cone`,{scoop:n.folder,error:e instanceof Error?e.message:String(e)})})},onStatusChange:n=>{if(!this.scoops.has(e))return;let r=this.tabs.get(e);r&&(r.status=n,r.lastActivity=new Date().toISOString(),this.tabs.set(e,r)),this.callbacks.onStatusChange(e,n),this.dispatchScoopEvent(e,`onStatusChange`,n),n===`ready`&&!t.isCone&&this.maybeNotifyConeOnScoopComplete(e)},onToolStart:(t,n)=>{this.callbacks.onToolStart?.(e,t,n)},onToolEnd:(t,n,r)=>{this.callbacks.onToolEnd?.(e,t,n,r)},onToolUI:(t,n,r)=>{this.callbacks.onToolUI?.(e,t,n,r)},onToolUIDone:t=>{this.callbacks.onToolUIDone?.(e,t)},onSendMessage:(t,n)=>{let r=`${n?`[${n}] `:``}${t}`;this.callbacks.onSendMessage(e,r),this.dispatchScoopEvent(e,`onSendMessage`,t)},getScoops:()=>this.getScoops(),getScoopTabState:t.isCone?e=>this.tabs.get(e):void 0,onFeedScoop:t.isCone?(e,n)=>this.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:t.isCone?async e=>{let t={...e,jid:`scoop_${e.folder}_${Date.now()}`};return await this.registerScoop(t),t}:void 0,onDropScoop:t.isCone?async e=>{await this.unregisterScoop(e)}:void 0,onMuteScoops:t.isCone?e=>this.muteScoops(e):void 0,onUnmuteScoops:t.isCone?e=>this.unmuteScoops(e):void 0,onScheduleScoopWait:t.isCone?(e,t)=>this.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:t.isCone?e=>this.setGlobalMemory(e):void 0,getBrowserAPI:()=>this.callbacks.getBrowserAPI()},a=Array.from(this.scoops.values()).find(e=>e.isCone)?.jid,o=new _5(t,i,r,this.sessionStore??void 0,this.sharedFs??void 0,a);this.contexts.set(e,o),this.tabs.set(e,{jid:e,contextId:n,status:`initializing`,lastActivity:new Date().toISOString()}),await o.init();let s=this.tabs.get(e);s&&s.status===`initializing`&&(s.status=`ready`,this.tabs.set(e,s),this.callbacks.onStatusChange(e,`ready`),this.dispatchScoopEvent(e,`onStatusChange`,`ready`));let c=this.scoops.get(e);c&&!c.isCone&&this.startIdleTimer(e),E5.info(`Scoop context created`,{jid:e,contextId:n})}async destroyScoopTab(e){this.clearIdleTimer(e);let t=this.contexts.get(e);t&&(t.dispose(),this.contexts.delete(e),this.tabs.delete(e),this.scoopObservers.delete(e),E5.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 Ee(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 Ee(t)}async getMessagesForScoop(e){return ve(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 E5.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[]){let a=this.contexts.get(e);a||=(await this.createScoopTab(e),this.contexts.get(e));let o=this.tabs.get(e);if(o?.status===`initializing`){if(E5.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){E5.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}a=this.contexts.get(e),o=this.tabs.get(e)}if(!a){E5.error(`Context not found after creation`,{jid:e});return}this.clearIdleTimer(e),this.scoopResponseBuffer.delete(e),o&&(o.status=`processing`,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o),this.callbacks.onStatusChange(e,`processing`),this.dispatchScoopEvent(e,`onStatusChange`,`processing`)),E5.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await a.prompt(t,i)}async processScoopQueue(e){let t=this.messageQueues.get(e);if(!t||t.length===0){E5.debug(`processScoopQueue: empty queue`,{jid:e});return}let n=this.tabs.get(e);if(n?.status!==`ready`){E5.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)??``,c=await ye(e,a,i);if(E5.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:c.length,queueLength:t.length}),c.length===0){E5.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]);return}let l=c.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${s(e.content,e.attachments)}`).join(`
|
|
15845
15845
|
`),u=c.flatMap(e=>o(e.attachments));this.messageQueues.set(e,[]);let d=c[c.length-1];this.lastAgentTimestamp.set(e,d.timestamp),await ke(`lastAgentTs_${e}`,d.timestamp),await this.sendPrompt(e,l,d.senderId,d.senderName,u)}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);E5.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();E5.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=>{E5.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),E5.info(`Skills reloaded across all contexts`,{count:e.length})}stopScoop(e){let t=this.contexts.get(e);t&&t.stop()}buildScoopCost(e,t){let n=t.getAgentMessages().filter(e=>e.role===`assistant`);if(n.length===0)return null;let r={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},i=new Map;for(let e of n)r.input+=e.usage.input,r.output+=e.usage.output,r.cacheRead+=e.usage.cacheRead,r.cacheWrite+=e.usage.cacheWrite,r.totalTokens+=e.usage.totalTokens,r.cost.input+=e.usage.cost.input,r.cost.output+=e.usage.cost.output,r.cost.cacheRead+=e.usage.cost.cacheRead,r.cost.cacheWrite+=e.usage.cost.cacheWrite,r.cost.total+=e.usage.cost.total,i.set(e.model,(i.get(e.model)??0)+1);let a=``,o=0;for(let[e,t]of i)t>o&&(a=e,o=t);let s=n.map(e=>e.timestamp).sort((e,t)=>e-t),c=s[0],l=s[s.length-1],u=900*1e3,d=l-c,f=Math.max(1,Math.ceil(d/u))*u;return{name:e.assistantLabel,type:e.isCone?`cone`:`scoop`,model:a,usage:r,turns:n.length,firstActivity:c,lastActivity:l,activeTimeMs:f}}snapshotScoopCost(e){let t=this.scoops.get(e),n=this.contexts.get(e);if(!t||!n)return;let r=this.buildScoopCost(t,n);r&&this.droppedScoopCosts.push(r)}getSessionCosts(){let e=[];for(let t of this.scoops.values()){let n=this.contexts.get(t.jid);if(!n)continue;let r=this.buildScoopCost(t,n);r&&e.push(r)}return e.push(...this.droppedScoopCosts),e}startIdleTimer(e){if(this.clearIdleTimer(e),this.tabs.get(e)?.status===`processing`)return;let t=setTimeout(()=>{this.idleTimers.delete(e);let t=this.scoops.get(e);if(!t||t.isCone||this.tabs.get(e)?.status!==`ready`)return;let n=Array.from(this.scoops.values()).find(e=>e.isCone);if(!n)return;let r={id:`scoop-idle-${e}-${Date.now()}`,chatJid:n.jid,senderId:t.folder,senderName:t.assistantLabel,content:`[@${t.assistantLabel} idle]: Scoop "${t.name}" has been ready for 2 minutes without receiving any work. This is expected if the scoop is waiting for webhooks or cron tasks. If you intended to delegate work, use feed_scoop to send a prompt.`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-idle`};E5.info(`Scoop idle timeout`,{jid:e,scoop:t.folder});try{this.callbacks.onIncomingMessage?.(n.jid,r)}catch(t){E5.warn(`onIncomingMessage for scoop-idle threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}this.handleMessage(r).catch(t=>{let n=t instanceof Error?t.message:String(t);E5.error(`Failed to send idle notification`,{jid:e,error:n})})},D5);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.completionWaiters.values())for(let t of e)try{t(null)}catch(e){E5.warn(`completion waiter threw during shutdown`,{error:e instanceof Error?e.message:String(e)})}this.completionWaiters.clear(),this.mutedScoops.clear(),this.pendingCompletions.clear();for(let e of this.contexts.keys())await this.destroyScoopTab(e);E5.info(`Orchestrator shutdown`)}};i(`heartbeat`);var N5=i(`tray-follower`);function P5(e){let t=new URL(e);return t.searchParams.set(`json`,`true`),t.toString()}async function F5(e){let t=P5(e.joinUrl),n=await H5(await(e.fetchImpl??fetch)(t,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:e.controllerId,runtime:e.runtime})}));return N5.info(`Follower tray attach response`,{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),I5(n)}function I5(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 L5(e){return V5(await U5(e,{action:`poll`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function R5(e){return V5(await U5(e,{action:`answer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function z5(e){return V5(await U5(e,{action:`ice-candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function B5(e){return V5(await U5(e,{action:`retry`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function V5(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function H5(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!W5(n)){let n=t?t.slice(0,200):`(empty)`;throw N5.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 U5(e,t){let n=P5(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(!G5(i))throw Error(`Tray follower bootstrap returned an invalid response (${r.status})`);return i}function W5(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`&&K5(r.bootstrap):r.action===`fail`?(r.code===`INVALID_JOIN_CAPABILITY`||r.code===`TRAY_EXPIRED`)&&typeof r.error==`string`:!1}function G5(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`&&K5(t.bootstrap)&&Array.isArray(t.events)}function K5(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 q5=n({AGENT_BRIDGE_GLOBAL_KEY:()=>Y5,AGENT_SPAWN_REQUEST_TYPE:()=>X5,createAgentBridge:()=>Z5,publishAgentBridge:()=>Q5,publishAgentBridgeProxy:()=>$5}),J5=i(`agent-bridge`),Y5=`__slicc_agent`,X5=`agent-spawn-request`;function Z5(e,t,n=null,r={}){let i=r.generateName??r7,a=r.generateUid??e7,o=r.resolveModel??a7;function s(){for(let t=0;t<8;t++){let t=i(),n=`agent_${i7(t)}`;if(!e.getScoops().some(e=>e.jid===n))return t}return a()}function c(t){if(t===void 0)return null;let n=e.getScoops().find(e=>e.jid===t);if(!n)return null;let r=n.config?.modelId;return r&&r.length>0?r:null}async function l(r){let i=r.modelId;if(i!==void 0&&(i===``||o(i)===null))return{finalText:`agent: unknown model: ${i}`,exitCode:1};let a=i??c(r.parentJid)??``,l=s(),u=`agent-${l}`,d=`agent_${i7(l)}`,f=`/scoops/${u}`,p=o7(r.cwd),m={visiblePaths:s7(r),writablePaths:c7([p,`/shared/`,`${f}/`,`/tmp/`]),allowedCommands:r.allowedCommands};a&&(m.modelId=a);let h={jid:d,name:u,folder:u,isCone:!1,type:`scoop`,requiresTrigger:!1,assistantLabel:u,addedAt:new Date().toISOString(),config:m,configSchemaVersion:2,notifyOnComplete:!1},g=[],_=``,v=null,y=e.observeScoop(d,{onSendMessage:e=>{g.push(e)},onResponse:(e,t)=>{t?_+=e:_=e},onError:e=>{v===null&&(v=e)}});try{try{await e.registerScoop(h)}catch(e){return{finalText:v??l7(e),exitCode:1}}return await e.sendPrompt(d,r.prompt,`agent`,`agent`),v===null?{finalText:g.length>0?g[g.length-1]:_,exitCode:0}:{finalText:v,exitCode:1}}catch(e){return{finalText:v??l7(e),exitCode:1}}finally{y();try{await e.unregisterScoop(d)}catch(e){J5.warn(`unregisterScoop failed`,{jid:d,error:l7(e)})}try{await t.rm(f,{recursive:!0})}catch(e){u7(e,`ENOENT`)||J5.warn(`scratch folder cleanup failed`,{folder:u,error:l7(e)})}if(n)try{await n.delete(d)}catch(e){J5.warn(`sessionStore.delete failed`,{jid:d,error:l7(e)})}}}return{spawn:l}}function Q5(e,t,n=null,r={}){let i=Z5(e,t,n,r);return globalThis[Y5]=i,J5.info(`agent bridge published on globalThis.__slicc_agent`),i}function $5(){let e={spawn(e){return new Promise((t,n)=>{let r=globalThis.chrome?.runtime;if(!r||typeof r.sendMessage!=`function`){n(Error(`agent: chrome.runtime.sendMessage not available`));return}let i=e=>{let i=r.lastError;if(i){n(Error(i.message??`chrome.runtime error`));return}if(e==null){n(Error(`agent: empty response from offscreen bridge`));return}let a=e;if(!a.ok){n(Error(a.error??`agent: offscreen bridge error`));return}if(!a.result){n(Error(`agent: offscreen bridge returned no result`));return}t(a.result)};try{r.sendMessage({source:`panel`,payload:{type:X5,options:e}},i)}catch(e){n(e instanceof Error?e:Error(String(e)))}})}};return globalThis[Y5]=e,J5.info(`agent bridge proxy published on globalThis.__slicc_agent`),e}function e7(){let e=globalThis;return typeof e.crypto?.randomUUID==`function`?e.crypto.randomUUID().replace(/-/g,``).slice(0,12):`${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}var t7=`amber.bouncy.breezy.bubbly.cheeky.chilly.cozy.dapper.dreamy.eager.exuberant.fluffy.frosty.gentle.giddy.glossy.jolly.lucky.mellow.merry.nimble.plucky.quirky.salty.sleepy.snappy.sparkly.spiffy.sunny.sweet.toasty.velvety.whimsy.zesty`.split(`.`),n7=`blueberry.butterscotch.caramel.cherry.chocolate.cinnamon.coconut.coffee.cookies.custard.espresso.fudge.gelato.hazelnut.honeycomb.lavender.lemon.mango.maple.marzipan.matcha.mint.mocha.neapolitan.nougat.peach.pecan.pistachio.praline.raspberry.sherbet.sorbet.stracciatella.strawberry.tiramisu.toffee.vanilla`.split(`.`);function r7(){return`${t7[Math.floor(Math.random()*t7.length)]}-${n7[Math.floor(Math.random()*n7.length)]}`}function i7(e){return e.replace(/-/g,`_`)}function a7(e){try{let t=v();for(let n of t)if(n.models.some(t=>t.id===e))return e;return null}catch{return null}}function o7(e){let t=de(e);return t.endsWith(`/`)?t:`${t}/`}function s7(e){if(e.visiblePaths!==void 0)return e.visiblePaths.map(o7);let t=[`/workspace/`];return e.invokingCwd&&e.invokingCwd.length>0&&t.push(o7(e.invokingCwd)),c7(t)}function c7(e){let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n}function l7(e){return e instanceof Error?e.message:String(e)}function u7(e,t){if(typeof e!=`object`||!e)return!1;let n=e.code;return typeof n==`string`&&n===t}var d7=i(`tray-webrtc`),f7=`tray-control`,p7=250,m7=class{peerConnectionFactory;dataChannelLabel;peers=new Map;iceServers;constructor(e){this.options=e,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>_7(this.iceServers)),this.dataChannelLabel=e.dataChannelLabel??f7}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=y7(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`)&&(d7.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`?(d7.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`?(d7.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:v7(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){d7.warn(`Failed to report tray bootstrap failure`,{error:e instanceof Error?e.message:String(e)})}}}},h7=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??(()=>_7(this.iceServers)),this.controllerIdFactory=e.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),this.pollIntervalMs=e.pollIntervalMs??p7}async start(){this.stopped=!1;let e=this.controllerIdFactory(),t=Date.now();Mo({state:`connecting`,joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:t,lastError:null}),d7.info(`Follower tray join starting`,{joinUrl:this.options.joinUrl});let n=0;for(;;){b7(this.stopped),n++;let t;try{t=await F5({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 Mo({...jo(),attachAttempts:n,lastError:t}),e}if(Mo({...jo(),attachAttempts:n,lastAttachCode:t.code}),t.action===`wait`){let e=t.retryAfterMs??1e3;d7.info(`Follower tray attach waiting`,{attempt:n,code:t.code,retryAfterMs:e}),n%10==0&&d7.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 Mo({state:`error`,joinUrl:this.options.joinUrl,trayId:null,error:e,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:e}),d7.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 Mo({state:`connected`,joinUrl:this.options.joinUrl,trayId:r.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:null}),d7.info(`Follower tray connected`,{trayId:r.trayId,controllerId:e}),r}catch(e){let r=e instanceof Error?e.message:String(e);throw Mo({state:`error`,joinUrl:this.options.joinUrl,trayId:t.trayId,error:r,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:r}),d7.warn(`Follower tray bootstrap failed`,{error:r}),e}}}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,Mo({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(b7(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 L5({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 R5({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,answer:v7(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 B5({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`)&&(d7.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?(d7.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?(d7.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=y7(n);r&&z5({joinUrl:this.options.joinUrl,controllerId:e,bootstrapId:t,candidate:r,fetchImpl:this.fetchImpl}).catch(e=>{d7.warn(`Failed to send follower ICE candidate`,{error:e instanceof Error?e.message:String(e)})})}),r}};function g7(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 h7({...e,sleep:o,onDisconnected:e=>{s||(d7.warn(`Follower disconnected, starting reconnect loop`,{reason:e}),f(e))}});return l=t,{manager:t,connectionPromise:t.start()}},f=async u=>{if(s||c)return;c=!0,l?.stop(),l=null;let f=0,p=n,m=u??`Unknown disconnect`;for(;!s&&f<a&&(f++,t.onReconnecting?.(f),Mo({...jo(),state:`reconnecting`,error:null,reconnectAttempts:f}),d7.info(`Reconnect attempt`,{attempt:f,delay:p}),await o(p),!s);){let n=null;try{let r=d();n=r.manager;let i=await r.connectionPromise;if(s){n.stop();break}c=!1,Mo({...jo(),state:`connected`,joinUrl:e.joinUrl,trayId:i.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),d7.info(`Reconnect successful`,{attempt:f,trayId:i.trayId}),t.onConnected(i);return}catch(e){m=e instanceof Error?e.message:String(e),d7.warn(`Reconnect attempt failed`,{attempt:f,error:m}),n?.stop(),l=null}p=Math.min(p*r,i)}s||(c=!1,Mo({...jo(),state:`error`,error:`Reconnect failed after ${f} attempts: ${m}`,reconnectAttempts:f}),d7.warn(`Reconnect gave up`,{attempts:f,lastError:m}),t.onGaveUp?.(m))},{connectionPromise:p}=d();return p.then(e=>{s||t.onConnected(e)}).catch(e=>{s||d7.warn(`Initial follower connection failed`,{error:e instanceof Error?e.message:String(e)})}),u}function _7(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 v7(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 y7(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 b7(e){if(e)throw Error(`Tray follower stopped before WebRTC bootstrap completed`)}var x7=64*1024;async function S7(e,t){try{switch(t.op){case`readFile`:return await C7(e,t.path,t.encoding);case`writeFile`:return[await w7(e,t.path,t.content,t.encoding)];case`stat`:return[await T7(e,t.path)];case`readDir`:return[await E7(e,t.path)];case`mkdir`:return[await D7(e,t.path,t.recursive)];case`rm`:return[await O7(e,t.path,t.recursive)];case`exists`:return[await k7(e,t.path)];case`walk`:return[await A7(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(e){return[M7(e)]}}async function C7(e,t,n){return(n??`utf-8`)===`utf-8`?j7(await e.readFile(t,{encoding:`utf-8`}),`utf-8`):j7(N7(await e.readFile(t,{encoding:`binary`})),`base64`)}async function w7(e,t,n,r){if(r===`base64`){let r=P7(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:`void`}}}async function T7(e,t){return{ok:!0,data:{type:`stat`,stat:await e.stat(t)}}}async function E7(e,t){return{ok:!0,data:{type:`dirEntries`,entries:await e.readDir(t)}}}async function D7(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function O7(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function k7(e,t){return{ok:!0,data:{type:`exists`,exists:await e.exists(t)}}}async function A7(e,t){let n=[];for await(let r of e.walk(t))n.push(r);return{ok:!0,data:{type:`paths`,paths:n}}}function j7(e,t){if(e.length<=x7)return[{ok:!0,data:{type:`file`,content:e,encoding:t}}];let n=Math.ceil(e.length/x7),r=[];for(let i=0;i<n;i++){let a=i*x7,o=e.slice(a,a+x7);r.push({ok:!0,data:{type:`file`,content:o,encoding:t},chunkIndex:i,totalChunks:n})}return r}function M7(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 N7(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function P7(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 F7=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()]}},I7=i(`data-channel-keepalive`),L7=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++,I7.debug(`Missed pong`,{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){I7.warn(`Channel declared dead`,{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}},R7=i(`tray-leader-sync`);function z7(e){return e?e.includes(`standalone`)?`standalone`:e.includes(`extension`)?`extension`:e.includes(`electron`)?`electron`:`unknown`:`unknown`}var B7=class{followers=new Map;registry=new F7;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=sc(t),i=r.onMessage(t=>{this.handleFollowerMessage(e,t)}),a=new L7({sendPing:()=>r.send({type:`ping`}),onDead:()=>{R7.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:z7(n?.runtime)}),R7.info(`Follower added to sync`,{bootstrapId:e,followerCount:this.followers.size}),this.options.onFollowerCountChanged?.(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(),R7.info(`Follower removed from sync`,{bootstrapId:e,followerCount:this.followers.size}),this.options.onFollowerCountChanged?.(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,n){if(this.followers.size===0)return;let r={type:`user_message_echo`,text:e,messageId:t,scoopJid:this.options.getScoopJid(),attachments:n};for(let e of this.followers.values())e.sync.send(r)}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();ic(t.sync,n,r),R7.debug(`Snapshot sent to follower`,{bootstrapId:e,messageCount:n.length})}handleFollowerMessage(e,t){switch(t.type){case`user_message`:{R7.info(`Follower user message received`,{bootstrapId:e,messageId:t.messageId});let n=t.attachments?.length?c(t.attachments):t.attachments;this.options.onFollowerMessage(t.text,t.messageId,n);break}case`abort`:R7.info(`Follower abort received`,{bootstrapId:e}),this.options.onFollowerAbort();break;case`request_snapshot`:R7.info(`Follower snapshot request received`,{bootstrapId:e}),this.sendSnapshotToFollower(e);break;case`targets.advertise`:R7.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),R7.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 lc({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),R7.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);tc(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=nc(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&&tc(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 S7(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?S7(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})})}},V7=i(`tray-follower-sync`),H7=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=cc(e),this.unsubscribe=this.sync.onMessage(e=>{this.handleLeaderMessage(e)}),this.keepalive=new L7({sendPing:()=>this.sync.send({type:`ping`}),onDead:()=>{V7.warn(`Leader keepalive dead, cleaning up`),this.handleDisconnect(`Keepalive timeout — leader not responding`),this.options.onDead?.()}}),this.keepalive.start(),e.addEventListener(`close`,()=>{V7.warn(`Data channel closed`),this.handleDisconnect(`Data channel closed`)}),e.addEventListener(`error`,()=>{V7.warn(`Data channel error`),this.handleDisconnect(`Data channel error`)})}sendMessage(e,t,n){let r=t??`follower-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.sentMessageIds.add(r);let i=n?.length?c(n):n;this.sync.send({type:`user_message`,text:e,messageId:r,attachments:i}),V7.info(`Sent user message to leader`,{messageId:r})}onEvent(e){return this.eventListeners.add(e),()=>this.eventListeners.delete(e)}stop(){this.sync.send({type:`abort`}),V7.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(),V7.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,Mo({...jo(),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`:V7.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=ac(this.snapshotChunkBuffer,e);this.snapshotChunkBuffer=t.buffer,t.result&&(V7.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),V7.debug(`Skipping own message echo`,{messageId:e.messageId});break}V7.info(`User message echo received`,{messageId:e.messageId,scoopJid:e.scoopJid}),this.options.onUserMessage?.(e.text,e.messageId,e.scoopJid,e.attachments);break;case`status`:this.options.onStatus?.(e.scoopStatus);break;case`error`:V7.warn(`Error from leader`,{error:e.error}),this.emitEvent({type:`error`,error:e.error});break;case`targets.registry`:V7.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(),No(Date.now());break}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch(t){V7.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}}createRemoteTransport(e,t){let n=new lc({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),V7.debug(`Tracking remote CDP session`,{remoteSessionId:e})}n===`Target.detachFromTarget`&&i&&this.remoteCDPSessions.has(i)&&(this.remoteCDPSessions.delete(i),V7.debug(`Removed remote CDP session on detach`,{sessionId:i})),tc(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=nc(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 S7(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})})}},U7=i(`tab-persistence-guard`),W7=`slicc-tray-leader-active`,G7=class{active=!1;audioCtx=null;oscillator=null;lockController=null;beforeUnloadHandler=null;constructor(e={}){this.options=e}activate(){this.active||(this.active=!0,this.startSilentAudio(),this.acquireWebLock(),this.installBeforeUnload(),U7.info(`Tab persistence guard activated`))}deactivate(){this.active&&(this.active=!1,this.stopSilentAudio(),this.releaseWebLock(),this.removeBeforeUnload(),U7.info(`Tab persistence guard deactivated`))}isActive(){return this.active}startSilentAudio(){try{let e=(this.options.audioContextFactory??(()=>{let e=typeof globalThis<`u`?globalThis.AudioContext??globalThis.webkitAudioContext:void 0;return e?new e:null}))();if(!e){U7.warn(`AudioContext unavailable — discard prevention via silent audio disabled`);return}e.resume?.().catch(()=>{});let t=e.createOscillator(),n=e.createGain();n.gain.value=0,t.connect(n),n.connect(e.destination),t.start(),this.audioCtx=e,this.oscillator=t}catch(e){U7.warn(`Failed to start silent audio guard`,{error:e instanceof Error?e.message:String(e)})}}stopSilentAudio(){try{this.oscillator?.stop()}catch{}this.oscillator=null,this.audioCtx&&=(this.audioCtx.close?.().catch(()=>{}),null)}acquireWebLock(){try{let e=this.options.lockManager??(typeof navigator<`u`&&`locks`in navigator?navigator.locks:null);if(!e){U7.warn(`navigator.locks unavailable — discard prevention via Web Lock disabled`);return}let t=new AbortController;this.lockController=t,e.request(W7,{mode:`exclusive`,signal:t.signal},()=>new Promise(e=>{if(t.signal.aborted){e();return}let n=()=>{t.signal.removeEventListener(`abort`,n),e()};t.signal.addEventListener(`abort`,n,{once:!0})})).catch(e=>{e?.name!==`AbortError`&&U7.warn(`Web Lock request rejected`,{error:e instanceof Error?e.message:String(e)})})}catch(e){U7.warn(`Failed to acquire Web Lock`,{error:e instanceof Error?e.message:String(e)})}}releaseWebLock(){try{this.lockController?.abort()}catch{}this.lockController=null}installBeforeUnload(){try{let e=this.options.windowRef??(typeof window<`u`?window:null);if(!e)return;let t=()=>{};e.addEventListener(`beforeunload`,t),this.beforeUnloadHandler=t}catch{}}removeBeforeUnload(){try{let e=this.options.windowRef??(typeof window<`u`?window:null);e&&this.beforeUnloadHandler&&e.removeEventListener(`beforeunload`,this.beforeUnloadHandler)}catch{}this.beforeUnloadHandler=null}};function K7(e,t){if(t)return`extension`;try{return Y7(new URL(e))?`electron-overlay`:`standalone`}catch{return`standalone`}}function q7(e,t){return e===`electron-overlay`||e===`standalone`&&t}function J7(e){try{let t=new URL(e).searchParams.get(`tab`);return t&&fs(t)?t:us}catch{return us}}function Y7(e){return e.pathname===`/electron`||e.pathname===`/electron/`||e.searchParams.get(`runtime`)===`electron-overlay`}function X7(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}/licks-ws`}function Z7(e,t){return`${new URL(e).origin}/webhooks/${t}`}function Q7(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function $7(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`slicc-electron-overlay:set-tab`}var e9=[`/shared/sprinkles`];async function t9(e){let t=new Map;for(let n of e9)await e.exists(n)&&await n9(e,n,t);return await n9(e,`/`,t),t}async function n9(e,t,n){for await(let r of e.walk(t)){if(!r.endsWith(`.shtml`))continue;let t=r9(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:i9(i,t),autoOpen:a9(i)})}}}function r9(e){let t=e.split(`/`).pop()??e;return t.endsWith(`.shtml`)?t.slice(0,-6):t}function i9(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 a9(e){return/data-sprinkle-autoopen\b/.test(e)}var o9=i(`sprinkle-manager`),s9=`slicc-open-sprinkles`,c9=class{fs;bridge;callbacks;availableSprinkles=new Map;watcherUnsub;openSprinkles=new Map;constructor(e,t,n,r){this.fs=e,this.bridge=new h2(e,t,e=>this.close(e),r),this.callbacks=n}async restoreOpenSprinkles(){try{let e=localStorage.getItem(s9);if(!e){for(let e of this.availableSprinkles.values())if(e.autoOpen)try{await this.open(e.name)}catch{o9.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{o9.warn(`Failed to restore sprinkle`,{name:e})}}catch{}}persistOpenSprinkles(){try{localStorage.setItem(s9,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),o9.info(`Auto-opened new sprinkle after install`,{name:e.name})}catch{o9.warn(`Failed to auto-open new sprinkle`,{name:e.name})}}async refresh(){this.availableSprinkles=await t9(this.fs),o9.info(`Discovered sprinkles`,{count:this.availableSprinkles.size})}async open(e,t){if(this.openSprinkles.has(e)){o9.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`});if(r==null)throw Error(`Failed to read sprinkle content: ${n.path} (file may be corrupted or missing)`);let i=typeof r==`string`?r:new TextDecoder(`utf-8`).decode(r),a=document.createElement(`div`);a.className=`sprinkle-panel`,a.style.cssText=`width: 100%; height: 100%; display: flex; flex-direction: column; overflow: hidden;`,a.dataset.sprinkle=e,this.openSprinkles.set(e,{renderer:null,container:a}),this.callbacks.addSprinkle(e,n.title,a,t);let o=new Vi(a,this.bridge.createAPI(e));await o.render(i,e),this.openSprinkles.get(e).renderer=o,this.persistOpenSprinkles(),q6(e),o9.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(),o9.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){o9.warn(`Cannot send to closed sprinkle`,{name:e});return}this.bridge.pushUpdate(e,t),n.renderer.pushUpdate(t)}};async function l9(e,t,n){let r=[],i=[];for(let{path:a,handle:o}of e){let e=typeof o?.name==`string`?o.name:``;if(!o||!(`queryPermission`in o)){i.push({path:a,dirName:e});continue}let s;try{s=await o.queryPermission({mode:`readwrite`})}catch(t){n?.warn?.(`queryPermission threw on persisted handle`,{path:a,error:t instanceof Error?t.message:String(t)}),i.push({path:a,dirName:e});continue}if(s!==`granted`){i.push({path:a,dirName:e});continue}try{await t.mount(a,o),n?.info?.(`Restored mount from previous session`,{path:a,name:e}),r.push({path:a,dirName:e})}catch(t){n?.warn?.(`Failed to re-mount persisted handle`,{path:a,error:t instanceof Error?t.message:String(t)}),i.push({path:a,dirName:e})}}return{restored:r,needsRecovery:i}}function u9(e){return`'${e.replace(/'/g,`'\\''`)}'`}function d9(e){let t=e.replace(/\r\n|[\r\n]/g,` `),n=t.match(/`+/g),r=n?Math.max(...n.map(e=>e.length))+1:1,i="`".repeat(r);return`${i}${t.startsWith("`")||t.endsWith("`")?` ${t} `:t}${i}`}function f9(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.map(({path:e,dirName:t})=>{let n=t?` (previously mounted from ${d9(t)})`:``;return`- ${d9(e)}${n}`}),n=e.map(({path:e})=>` mount ${u9(e)}`),r=e.length===1?`mount point`:`mount points`,i=e.length===1?`it`:`them`;return[`[Session Reload] Mount recovery required for ${e.length} ${r}.`,``,`The page was reloaded and the following ${r} lost filesystem permission. The browser cannot restore access without a fresh user gesture, so ${i} cannot be used until the user re-authorizes:`,``,...t,``,`Please tell the user what happened and ask whether they want to re-mount. If yes, run the corresponding command(s) so the folder picker opens and they can re-select the same directory:`,``,...n,``,"If the user no longer needs a mount, run `mount unmount <path>` (with the path shell-quoted the same way) to clear the stale entry instead."].join(`
|
|
15846
|
-
`)}var $=i(`main`),p9=`slicc-pending-mount`,m9=`pendingMount`;function h9(){try{let e=new URLSearchParams(window.location.search).get(`ui-fixture`);return e===null?!1:e===``||e===`1`||e.toLowerCase()===`true`}catch{return!1}}async function g9(e){let[{createChatFixture:t,FIXTURE_SESSION_ID:n,FIXTURE_SCOOP_NAME:r}]=await Promise.all([k(()=>import(`./chat-fixture-B8WPTUDJ.js`),[])]);await e.switchToContext(n,!0,r),e.loadMessages(t()),$.info(`Loaded UI fixture session for design iteration`)}async function _9(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(p9,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,m9),await new Promise(e=>n.oncomplete=()=>e()),t.close()}async function v9(e){let t;try{t=await new Promise((e,t)=>{let n=indexedDB.open(p9,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(m9);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)});if(r){n.objectStore(`handles`).delete(m9),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 y9(){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 b9(){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 x9(e,t,n,r){let i=y9(),a=0,o=!1,s=()=>{a=0,o||i.hide()};window.addEventListener(`dragenter`,e=>{Os(e.dataTransfer)&&(e.preventDefault(),a+=1,o||i.show(`Drop files`,`.skill archives install; other files attach to chat.`))}),window.addEventListener(`dragover`,e=>{Os(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect=`copy`),o||i.show(`Drop files`,`.skill archives install; other files attach to chat.`))}),window.addEventListener(`dragleave`,()=>{a!==0&&(a=Math.max(0,a-1),a===0&&!o&&i.hide())}),window.addEventListener(`dragend`,s),window.addEventListener(`blur`,s),window.addEventListener(`drop`,async c=>{let l=ks(c.dataTransfer),u=As(c.dataTransfer);if(!l&&u.length===0){s();return}if(c.preventDefault(),a=0,l&&o){i.hide(),t(`Another .skill installation is already in progress.`,`error`);return}if(u.length>0&&r)try{await r(u)}catch(e){t(`Failed to attach dropped files: ${e instanceof Error?e.message:String(e)}`,`error`)}if(l){o=!0,i.show(`Installing skill…`,l.name);try{let r=await pe(e,l);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{o=!1,i.hide()}}else i.hide()})}async function S9(e){let{OffscreenClient:t}=await k(async()=>{let{OffscreenClient:e}=await import(`./offscreen-client-CsH6V__l.js`);return{OffscreenClient:e}},__vite__mapDeps([19,13])),{VirtualFS:n}=await k(async()=>{let{VirtualFS:e}=await import(`./fs-Bs8Vlxfm.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([15,4,13,16])),{publishAgentBridgeProxy:r}=await k(async()=>{let{publishAgentBridgeProxy:e}=await Promise.resolve().then(()=>q5);return{publishAgentBridgeProxy:e}},void 0),i=new _s(e,!0);window.__slicc_debug_tabs=e=>i.setDebugTabs(e),await i.panels.chat.initSession(`session-cone`),r();let a=null,o=await n.create({dbName:`slicc-fs`});i.panels.fileBrowser.setFs(o),$.info(`File browser wired to shared VFS (local IndexedDB)`);let s=new BroadcastChannel(`preview-vfs`);s.onmessage=e=>{if(e.data?.type!==`preview-vfs-read`)return;let{id:t,path:n,asText:r}=e.data;(async()=>{try{let e=r?`utf-8`:`binary`,i=await o.readFile(n,{encoding:e});s.postMessage({type:`preview-vfs-response`,id:t,content:i})}catch(e){let r=e instanceof Error?e.message:String(e);r.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:n,error:r}),s.postMessage({type:`preview-vfs-response`,id:t,error:r})}})()},x9(o,b9(),async()=>{await i.panels.fileBrowser.refresh()},e=>i.panels.chat.addAttachmentsFromFiles(e));try{let{WasmShell:e}=await k(async()=>{let{WasmShell:e}=await Promise.resolve().then(()=>i8);return{WasmShell:e}},void 0),{PanelCdpProxy:t,BrowserAPI:n}=await k(async()=>{let{PanelCdpProxy:e,BrowserAPI:t}=await Promise.resolve().then(()=>uc);return{PanelCdpProxy:e,BrowserAPI:t}},void 0),{fetchSecretEnvVars:r}=await k(async()=>{let{fetchSecretEnvVars:e}=await Promise.resolve().then(()=>l5);return{fetchSecretEnvVars:e}},void 0),a=new t;await a.connect();let s=new n(a),c=await r(),l=new e({fs:o,browserAPI:s,env:Object.keys(c).length>0?c:void 0});await i.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 k(async()=>{let{registerSessionCostsProvider:e}=await Promise.resolve().then(()=>K4);return{registerSessionCostsProvider:e}},void 0);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=async e=>{a=e,c.selectedScoopJid=e.jid,i.panels.memory.setSelectedScoop(e.jid),i.setScoopSwitcherSelected?.(e.jid),i.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=e.isCone?void 0:e.name;await i.panels.chat.switchToContext(t,!e.isCone,n),c.isProcessing(e.jid)&&i.panels.chat.setProcessing(!0)};c=new t({onStatusChange:(e,t)=>{i.panels.scoops.updateScoopStatus(e,t),i.updateScoopSwitcherStatus?.(e,t),a?.jid===e&&(i.setAgentProcessing(t===`processing`),t===`processing`?i.panels.chat.setProcessing(!0):t===`ready`&&i.panels.chat.setProcessing(!1))},onScoopCreated:e=>{i.panels.scoops.refreshScoops(),i.refreshScoopSwitcher?.(),a||(a=e,c.selectedScoopJid=e.jid,i.panels.memory.setSelectedScoop(e.jid))},onScoopListUpdate:()=>{let e=new Set(c.getScoops().map(e=>e.folder));for(let t of l)e.has(t)||i.panels.chat.deleteSessionById(`session-${t}`);if(l=e,i.panels.scoops.refreshScoops(),i.refreshScoopSwitcher?.(),!a){let e=c.getScoops().find(e=>e.isCone);e&&(a=e,c.selectedScoopJid=e.jid,i.panels.memory.setSelectedScoop(e.jid))}},onIncomingMessage:(e,t)=>{if(Ga(t.channel)){let n=new Date(t.timestamp).getTime(),r=t.channel;if(a?.jid===e)i.panels.chat.addLickMessage(t.id,t.content,r,n);else{let a=c.getScoops().find(t=>t.jid===e),o=a?.isCone?`session-cone`:a?`session-${a.folder}`:`session-${e}`;i.panels.chat.persistLickToSession(o,{id:t.id,content:t.content,channel:r,timestamp:n})}return}if(a?.jid===e){let e=t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content;i.panels.chat.addUserMessage(e,t.attachments)}},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=a??c.getScoops().find(e=>e.isCone)??c.getScoops()[0];e&&(a=e,c.selectedScoopJid=e.jid,await u(e))}catch(e){$.error(`Failed to initialize on ready`,{error:e instanceof Error?e.message:String(e)})}}}),c.setLocalFS(o),i.panels.chat.setAttachmentWriter(Fs(o));let d=c.createAgentHandle();i.panels.chat.setAgent(d),i.panels.scoops.setOrchestrator(c),i.panels.memory.setOrchestrator(c),i.setScoopSwitcherOrchestrator?.(c),i.onScoopSelect=u,i.onModelChange=e=>{localStorage.setItem(`selected-model`,e),c.updateModel()},i.onClearChat=async()=>{let e=c.getScoops();for(let t of e){let e=t.isCone?`session-cone`:`session-${t.folder}`;await i.panels.chat.deleteSessionById(e)}c.clearAllMessages()},i.onClearFilesystem=async()=>{c.clearFilesystem()},i.panels.chat.onInlineSprinkleLick=(e,t)=>{c.sendSprinkleLick(`inline`,{action:e,data:t})};let f=new c9(o,async e=>{if(e.type===`sprinkle`){if(e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&o.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome completion marker`,e)),n===`shortcut-migrate`&&f.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&v9(o).catch(e=>$.warn(`Failed to mount workspace from onboarding`,e))}if(e.sprinkleName===`welcome`&&e.body?.action===`request-mount`){try{let e=window;if(!e.showDirectoryPicker)throw Error(`showDirectoryPicker not supported`);let t=await e.showDirectoryPicker({mode:`readwrite`});await _9(t),f.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),f.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}return}c.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop)}},{addSprinkle:(e,t,n,r)=>i.addSprinkle(e,t,n,r),removeSprinkle:e=>i.removeSprinkle(e)},()=>{let e=c.getScoops().find(e=>e.isCone);e&&c.stopScoop(e.jid)});if(window.__slicc_sprinkleManager=f,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 f.refresh(),e=f.available();break;case`opened`:e=f.opened();break;case`refresh`:await f.refresh(),e=f.available().length;break;case`open`:await f.open(r),e=!0;break;case`close`:f.close(r),e=!0;break;case`send`:f.sendToSprinkle(r,i),e=!0;break;case`openNewAutoOpen`:await f.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 f.refresh(),i.onSprinkleClose=e=>f.close(e),i.getAvailableSprinkles=()=>{let e=new Set(f.opened());return f.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},i.onOpenSprinkle=(e,t)=>f.open(e,t),i.updateAddButtons(),await f.restoreOpenSprinkles(),!await o.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await o.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await o.exists(`/shared/.welcomed`)&&!Co(window.localStorage)&&f.available().some(e=>e.name===`welcome`))try{await f.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`),h9()&&await g9(i.panels.chat),W6().catch(()=>{})}function C9(){if(typeof chrome<`u`&&chrome?.runtime?.id)return;let e=new Blob([`
|
|
15846
|
+
`)}var $=i(`main`),p9=`slicc-pending-mount`,m9=`pendingMount`;function h9(){try{let e=new URLSearchParams(window.location.search).get(`ui-fixture`);return e===null?!1:e===``||e===`1`||e.toLowerCase()===`true`}catch{return!1}}async function g9(e){let[{createChatFixture:t,FIXTURE_SESSION_ID:n,FIXTURE_SCOOP_NAME:r}]=await Promise.all([k(()=>import(`./chat-fixture-B8WPTUDJ.js`),[])]);await e.switchToContext(n,!0,r),e.loadMessages(t()),$.info(`Loaded UI fixture session for design iteration`)}async function _9(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(p9,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,m9),await new Promise(e=>n.oncomplete=()=>e()),t.close()}async function v9(e){let t;try{t=await new Promise((e,t)=>{let n=indexedDB.open(p9,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(m9);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)});if(r){n.objectStore(`handles`).delete(m9),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 y9(){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 b9(){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 x9(e,t,n,r){let i=y9(),a=0,o=!1,s=()=>{a=0,o||i.hide()};window.addEventListener(`dragenter`,e=>{Os(e.dataTransfer)&&(e.preventDefault(),a+=1,o||i.show(`Drop files`,`.skill archives install; other files attach to chat.`))}),window.addEventListener(`dragover`,e=>{Os(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect=`copy`),o||i.show(`Drop files`,`.skill archives install; other files attach to chat.`))}),window.addEventListener(`dragleave`,()=>{a!==0&&(a=Math.max(0,a-1),a===0&&!o&&i.hide())}),window.addEventListener(`dragend`,s),window.addEventListener(`blur`,s),window.addEventListener(`drop`,async c=>{let l=ks(c.dataTransfer),u=As(c.dataTransfer);if(!l&&u.length===0){s();return}if(c.preventDefault(),a=0,l&&o){i.hide(),t(`Another .skill installation is already in progress.`,`error`);return}if(u.length>0&&r)try{await r(u)}catch(e){t(`Failed to attach dropped files: ${e instanceof Error?e.message:String(e)}`,`error`)}if(l){o=!0,i.show(`Installing skill…`,l.name);try{let r=await pe(e,l);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{o=!1,i.hide()}}else i.hide()})}async function S9(e){let{OffscreenClient:t}=await k(async()=>{let{OffscreenClient:e}=await import(`./offscreen-client-CsH6V__l.js`);return{OffscreenClient:e}},__vite__mapDeps([19,13])),{VirtualFS:n}=await k(async()=>{let{VirtualFS:e}=await import(`./fs-Bs8Vlxfm.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([15,4,13,16])),{publishAgentBridgeProxy:r}=await k(async()=>{let{publishAgentBridgeProxy:e}=await Promise.resolve().then(()=>q5);return{publishAgentBridgeProxy:e}},void 0),i=new _s(e,!0);window.__slicc_debug_tabs=e=>i.setDebugTabs(e),await i.panels.chat.initSession(`session-cone`),r();let a=null,o=await n.create({dbName:`slicc-fs`});i.panels.fileBrowser.setFs(o),$.info(`File browser wired to shared VFS (local IndexedDB)`);let s=new BroadcastChannel(`preview-vfs`);s.onmessage=e=>{if(e.data?.type!==`preview-vfs-read`)return;let{id:t,path:n,asText:r}=e.data;(async()=>{try{let e=r?`utf-8`:`binary`,i=await o.readFile(n,{encoding:e});s.postMessage({type:`preview-vfs-response`,id:t,content:i})}catch(e){let r=e instanceof Error?e.message:String(e);r.includes(`ENOENT`)||$.error(`Preview VFS read failed`,{path:n,error:r}),s.postMessage({type:`preview-vfs-response`,id:t,error:r})}})()},x9(o,b9(),async()=>{await i.panels.fileBrowser.refresh()},e=>i.panels.chat.addAttachmentsFromFiles(e));try{let{WasmShell:e}=await k(async()=>{let{WasmShell:e}=await Promise.resolve().then(()=>i8);return{WasmShell:e}},void 0),{PanelCdpProxy:t,BrowserAPI:n}=await k(async()=>{let{PanelCdpProxy:e,BrowserAPI:t}=await Promise.resolve().then(()=>uc);return{PanelCdpProxy:e,BrowserAPI:t}},void 0),{fetchSecretEnvVars:r}=await k(async()=>{let{fetchSecretEnvVars:e}=await Promise.resolve().then(()=>l5);return{fetchSecretEnvVars:e}},void 0),a=new t;await a.connect();let s=new n(a),c=await r(),l=new e({fs:o,browserAPI:s,env:Object.keys(c).length>0?c:void 0});await i.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 k(async()=>{let{registerSessionCostsProvider:e}=await Promise.resolve().then(()=>K4);return{registerSessionCostsProvider:e}},void 0);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=async e=>{a=e,c.selectedScoopJid=e.jid,i.panels.memory.setSelectedScoop(e.jid),i.setScoopSwitcherSelected?.(e.jid),i.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=e.isCone?void 0:e.name;await i.panels.chat.switchToContext(t,!e.isCone,n),c.isProcessing(e.jid)&&i.panels.chat.setProcessing(!0)};c=new t({onStatusChange:(e,t)=>{i.panels.scoops.updateScoopStatus(e,t),i.updateScoopSwitcherStatus?.(e,t),a?.jid===e&&(i.setAgentProcessing(t===`processing`),t===`processing`?i.panels.chat.setProcessing(!0):t===`ready`&&i.panels.chat.setProcessing(!1))},onScoopCreated:e=>{i.panels.scoops.refreshScoops(),i.refreshScoopSwitcher?.(),a||(a=e,c.selectedScoopJid=e.jid,i.panels.memory.setSelectedScoop(e.jid))},onScoopListUpdate:()=>{let e=new Set(c.getScoops().map(e=>e.folder));for(let t of l)e.has(t)||i.panels.chat.deleteSessionById(`session-${t}`);if(l=e,i.panels.scoops.refreshScoops(),i.refreshScoopSwitcher?.(),!a){let e=c.getScoops().find(e=>e.isCone);e&&(a=e,c.selectedScoopJid=e.jid,i.panels.memory.setSelectedScoop(e.jid))}},onIncomingMessage:(e,t)=>{if(Ga(t.channel)){let n=new Date(t.timestamp).getTime(),r=t.channel;if(a?.jid===e)i.panels.chat.addLickMessage(t.id,t.content,r,n);else{let a=c.getScoops().find(t=>t.jid===e),o=a?.isCone?`session-cone`:a?`session-${a.folder}`:`session-${e}`;i.panels.chat.persistLickToSession(o,{id:t.id,content:t.content,channel:r,timestamp:n})}return}if(a?.jid===e){let e=t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content;i.panels.chat.addUserMessage(e,t.attachments)}},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=a??c.getScoops().find(e=>e.isCone)??c.getScoops()[0];e&&(a=e,c.selectedScoopJid=e.jid,await u(e))}catch(e){$.error(`Failed to initialize on ready`,{error:e instanceof Error?e.message:String(e)})}}}),c.setLocalFS(o),i.panels.chat.setAttachmentWriter(Fs(o));let d=c.createAgentHandle();i.panels.chat.setAgent(d),i.panels.scoops.setOrchestrator(c),i.panels.memory.setOrchestrator(c),i.setScoopSwitcherOrchestrator?.(c),i.onScoopSelect=u,i.onModelChange=e=>{localStorage.setItem(`selected-model`,e),c.updateModel()},i.onClearChat=async()=>{let e=c.getScoops();for(let t of e){let e=t.isCone?`session-cone`:`session-${t.folder}`;await i.panels.chat.deleteSessionById(e)}c.clearAllMessages()},i.onClearFilesystem=async()=>{c.clearFilesystem()},i.panels.chat.onDipLick=(e,t)=>{c.sendSprinkleLick(`inline`,{action:e,data:t})};let f=new c9(o,async e=>{if(e.type===`sprinkle`){if(e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&o.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome completion marker`,e)),n===`shortcut-migrate`&&f.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&v9(o).catch(e=>$.warn(`Failed to mount workspace from onboarding`,e))}if(e.sprinkleName===`welcome`&&e.body?.action===`request-mount`){try{let e=window;if(!e.showDirectoryPicker)throw Error(`showDirectoryPicker not supported`);let t=await e.showDirectoryPicker({mode:`readwrite`});await _9(t),f.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),f.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}return}c.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop)}},{addSprinkle:(e,t,n,r)=>i.addSprinkle(e,t,n,r),removeSprinkle:e=>i.removeSprinkle(e)},()=>{let e=c.getScoops().find(e=>e.isCone);e&&c.stopScoop(e.jid)});if(window.__slicc_sprinkleManager=f,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 f.refresh(),e=f.available();break;case`opened`:e=f.opened();break;case`refresh`:await f.refresh(),e=f.available().length;break;case`open`:await f.open(r),e=!0;break;case`close`:f.close(r),e=!0;break;case`send`:f.sendToSprinkle(r,i),e=!0;break;case`openNewAutoOpen`:await f.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 f.refresh(),i.onSprinkleClose=e=>f.close(e),i.getAvailableSprinkles=()=>{let e=new Set(f.opened());return f.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},i.onOpenSprinkle=(e,t)=>f.open(e,t),i.updateAddButtons(),await f.restoreOpenSprinkles(),!await o.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await o.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await o.exists(`/shared/.welcomed`)&&!Co(window.localStorage)&&f.available().some(e=>e.name===`welcome`))try{await f.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`),h9()&&await g9(i.panels.chat),W6().catch(()=>{})}function C9(){if(typeof chrome<`u`&&chrome?.runtime?.id)return;let e=new Blob([`
|
|
15847
15847
|
let lastPong = Date.now();
|
|
15848
15848
|
let frozen = false;
|
|
15849
15849
|
setInterval(() => {
|
|
@@ -15871,4 +15871,4 @@ ${t}
|
|
|
15871
15871
|
#app > .tab-content > .tab-content__panel {
|
|
15872
15872
|
height: 100%;
|
|
15873
15873
|
}
|
|
15874
|
-
`,document.head.appendChild(t),window.addEventListener(`message`,e=>{e.source===window.parent&&$7(e.data)&&o.setActiveTab(J7(`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 s=b9();await o.panels.chat.initSession(`session-cone`),$.info(`Session initialized`);let c=new Us,l=new Set,u=e=>{$.debug(`Emit to UI`,{type:e.type,listenerCount:l.size});for(let t of l)try{t(e)}catch(t){$.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}},d=null,p=new Map,m=new Map;function h(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function g(e){let t=m.get(e);return t||(t=[],m.set(e,t)),t}function _(e,t){let n=g(e),r=p.get(e);if(r){let e=n.find(e=>e.id===r);if(e)return e}r=`scoop-${e}-${h()}`,p.set(e,r);let i=v.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),d?.jid===e&&u({type:`message_start`,messageId:r}),o}let v=new M5(o.getIframeContainer(),{onResponse:(e,t,n)=>{let r=_(e);n?r.content+=t:(r.content=t,r.isStreaming=!1),d?.jid===e&&(u({type:`content_delta`,messageId:r.id,text:t}),n||u({type:`content_done`,messageId:r.id}))},onResponseDone:e=>{let t=g(e),n=p.get(e);if(n){let r=t.find(e=>e.id===n);r&&(r.isStreaming=!1),d?.jid===e&&u({type:`content_done`,messageId:n}),p.delete(e)}},onSendMessage:(e,t)=>{$.debug(`Send message requested`,{targetJid:e,textLength:t.length});let n=`msg-${h()}`,r={id:n,chatJid:e,senderId:`assistant`,senderName:`sliccy`,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`web`};v.handleMessage(r),g(e).push({id:n,role:`assistant`,content:t,timestamp:Date.now()}),d?.jid===e&&(u({type:`message_start`,messageId:n}),u({type:`content_delta`,messageId:n,text:t}),u({type:`content_done`,messageId:n}))},onStatusChange:(e,t)=>{if(o.panels.scoops.updateScoopStatus(e,t),o.updateScoopSwitcherStatus?.(e,t),d?.jid===e){if(o.setAgentProcessing(t===`processing`),t===`processing`)o.panels.chat.setProcessing(!0);else if(t===`ready`){o.panels.chat.setProcessing(!1);let t=p.get(e)??`done-${e}-${h()}`;p.delete(e),u({type:`turn_end`,messageId:t})}}},onError:(e,t)=>{$.error(`Scoop error`,{scoopJid:e,error:t}),d?.jid===e&&u({type:`error`,error:t})},getBrowserAPI:()=>c,onToolStart:(e,t,n)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let r=_(e);r.toolCalls||=[],r.toolCalls.push({id:h(),name:t,input:n}),d?.jid===e&&u({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=g(e),a=p.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)}}d?.jid===e&&a&&u({type:`tool_result`,messageId:a,toolName:t,result:n,isError:r})},onToolUI:(e,t,n,r)=>{let i=p.get(e);i?u({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=p.get(e);n&&u({type:`tool_ui_done`,messageId:n,requestId:t})},onIncomingMessage:(e,t)=>{if(Ga(t.channel)){let n=new Date(t.timestamp).getTime(),r=t.channel;if(g(e).push({id:t.id,role:`user`,content:t.content,timestamp:n,source:`lick`,channel:r}),d?.jid===e)o.panels.chat.addLickMessage(t.id,t.content,r,n);else{let i=v.getScoops().find(t=>t.jid===e),a=i?.isCone?`session-cone`:i?`session-${i.folder}`:`session-${e}`;o.panels.chat.persistLickToSession(a,{id:t.id,content:t.content,channel:r,timestamp:n})}return}let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel};g(e).push(n),d?.jid===e&&(u({type:`message_start`,messageId:t.id}),u({type:`content_delta`,messageId:t.id,text:n.content}),u({type:`content_done`,messageId:t.id}))}});await v.init(),o.panels.scoops.setOrchestrator(v),o.panels.memory.setOrchestrator(v),o.setScoopSwitcherOrchestrator?.(v);{let e=v.getSharedFS();e?Q5(v,e,v.getSessionStore()):$.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`)}let b=v.getSharedFS();if(b){o.panels.fileBrowser.setFs(b),$.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 b.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})}})()},x9(b,(e,t)=>{t===`error`?$.warn(`Dropped skill install failed`,{message:e}):$.info(`Dropped skill installed`,{message:e}),s(e,t)},async()=>{await o.panels.fileBrowser.refresh()},e=>o.panels.chat.addAttachmentsFromFiles(e));try{let{WasmShell:e}=await k(async()=>{let{WasmShell:e}=await Promise.resolve().then(()=>i8);return{WasmShell:e}},void 0),{fetchSecretEnvVars:t}=await k(async()=>{let{fetchSecretEnvVars:e}=await Promise.resolve().then(()=>l5);return{fetchSecretEnvVars:e}},void 0),n=await t(),r=new e({fs:b,browserAPI:c,env:Object.keys(n).length>0?n:void 0});await o.panels.terminal.mountShell(r),$.info(`Terminal mounted with shared VFS`);try{let{BshWatchdog:e}=await k(async()=>{let{BshWatchdog:e}=await import(`./bsh-watchdog-BofJVeV-.js`);return{BshWatchdog:e}},__vite__mapDeps([20,13])),t=new e({browserAPI:c,scriptCatalog:r.getScriptCatalog(),fs:b});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 x=v.getScoops(),S=x.some(e=>e.isCone);if(r)$.info(`Skipping local cone bootstrap while joining a tray without a configured provider`);else if(!S)d=await o.panels.scoops.createCone(),$.info(`Created cone`);else{let e=new URLSearchParams(window.location.search).get(`scoop`);if(e){let t=x.find(t=>t.folder===e);t?(d=t,$.info(`Restored scoop from URL`,{folder:e})):d=x.find(e=>e.isCone)??x[0]}else d=x.find(e=>e.isCone)??x[0]}d&&o.panels.memory.setSelectedScoop(d.jid);let C=null,w={sendMessage(e,t,n){if(!d){u({type:`error`,error:`No scoop selected`});return}let r={id:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:d.jid,senderId:`user`,senderName:`User`,content:e,attachments:n,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`};g(d.jid).push({id:r.id,role:`user`,content:e,attachments:n,timestamp:Date.now()}),C?.broadcastUserMessage(e,r.id,n),v.handleMessage(r),v.createScoopTab(d.jid)},onEvent(e){return l.add(e),()=>l.delete(e)},stop(){d&&(v.stopScoop(d.jid),v.clearQueuedMessages(d.jid).catch(e=>{$.error(`Failed to clear queued messages on stop`,{error:e instanceof Error?e.message:String(e)})}))}};o.panels.chat.setAgent(w),b&&o.panels.chat.setAttachmentWriter(Fs(b)),o.panels.chat.setDeleteQueuedMessageCallback(e=>{if(d){v.deleteQueuedMessage(d.jid,e).catch(t=>{$.error(`Failed to delete queued message`,{messageId:e,error:t instanceof Error?t.message:String(t)})});let t=m.get(d.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:E}=await k(async()=>{let{getLickManager:e}=await Promise.resolve().then(()=>b5);return{getLickManager:e}},void 0),D=E();await D.init(),v.setLickManager(D);let O=e=>{let t=e.type===`webhook`,n=e.type===`sprinkle`,r=e.type===`fswatch`,i=e.type===`session-reload`,a=e.type===`navigate`,s=t?e.webhookName:n?e.sprinkleName:r?e.fswatchName:i?`session-reload`:a?e.navigateUrl:e.cronName,c=t?e.webhookId:n?e.sprinkleName:r?e.fswatchId:i?`session-reload`:a?e.navigateUrl:e.cronId,l=e.type;if($.debug(`Lick event`,{type:e.type,name:s,targetScoop:e.targetScoop}),n&&e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&b?.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome marker`,e)),n===`shortcut-migrate`&&te?.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&b&&v9(b).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 _9(t),te?.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),te?.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}})();return}let u=v.getScoops(),f;if(f=e.targetScoop?u.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):u.find(e=>e.isCone),f){let u=`${l}-${c}-${Date.now()}`,p=t?`Webhook Event`:n?`Sprinkle Event`:r?`File Watch Event`:i?`Session Reload`:a?`Navigate Event`:`Cron Event`,m=null;if(i){let t=e.body;if(t?.reason===`mount-recovery`&&(m=f9(t.mounts??[]),m===null)){$.debug(`Dropping session-reload lick with empty mount-recovery list`);return}}m===null&&(m=`[${p}: ${s}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``);let h={id:u,chatJid:f.jid,senderId:l,senderName:`${l}:${s}`,content:m,timestamp:e.timestamp,fromAssistant:!1,channel:l},_=Date.now();if(g(f.jid).push({id:u,role:`user`,content:m,timestamp:_,source:`lick`,channel:l}),d?.jid===f.jid)o.panels.chat.addLickMessage(u,m,l,_);else{let e=f.isCone?`session-cone`:`session-${f.folder}`;o.panels.chat.persistLickToSession(e,{id:u,content:m,channel:l,timestamp:_})}$.info(`Routing lick to scoop`,{type:l,name:s,scoopJid:f.jid}),v.handleMessage(h)}else $.warn(`Lick target scoop not found`,{targetScoop:e.targetScoop})};D.setEventHandler(O);let ee=new Qs(c.getTransport(),e=>{D.emitEvent({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:new Date().toISOString(),body:{url:e.url,sliccHeader:e.sliccHeader,title:e.title}})});(async()=>{try{await c.connect(),await ee.start(),$.info(`Navigation watcher started`)}catch(e){$.warn(`Failed to start navigation watcher`,{error:e instanceof Error?e.message:String(e)})}})(),b&&oe().then(async e=>{if(e.length===0)return;let{needsRecovery:t}=await l9(e,b,$);t.length!==0&&O({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:t}})}).catch(e=>$.warn(`Failed to restore persisted mounts`,e)),o.panels.chat.onInlineSprinkleLick=(e,t)=>{O({type:`sprinkle`,sprinkleName:`inline`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:e,data:t}})};let te=null;if(b){if(te=new c9(b,O,{addSprinkle:(e,t,n,r)=>o.addSprinkle(e,t,n,r),removeSprinkle:e=>o.removeSprinkle(e)},()=>{let e=v.getScoops().find(e=>e.isCone);e&&(v.stopScoop(e.jid),v.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=te,window.__slicc_reloadSkills=()=>v.reloadAllSkills(),await te.refresh(),o.onSprinkleClose=e=>te.close(e),o.getAvailableSprinkles=()=>{let e=new Set(te.opened());return te.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},o.onOpenSprinkle=(e,t)=>te.open(e,t),o.updateAddButtons(),!await b.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await b.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await b.exists(`/shared/.welcomed`)&&!r&&te.available().some(e=>e.name===`welcome`))try{await te.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}await te.restoreOpenSprinkles(),$.info(`SprinkleManager initialized`)}let A=()=>{let e=X7(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:D.listWebhooks()};break;case`create_webhook`:{let t=await D.createWebhook(n.name||`default`,n.scoop,n.filter),r=b1().session,i=r?.webhookUrl?Q7(r.webhookUrl,t.id):Z7(window.location.href,t.id);e={type:`response`,requestId:n.requestId,data:{...t,url:i}};break}case`delete_webhook`:e=await D.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:D.listCronTasks()};break;case`create_crontask`:{if(!n.name)throw Error(`name is required`);if(!n.cron)throw Error(`cron is required`);let t=await D.createCronTask(n.name,n.cron,n.scoop,n.filter);e={type:`response`,requestId:n.requestId,data:t};break}case`delete_crontask`:e=await D.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=b1();e={type:`response`,requestId:n.requestId,data:{state:t.state,joinUrl:t.session?.joinUrl??null,workerBaseUrl:t.session?.workerBaseUrl??null,trayId:t.session?.trayId??null}};break}default:e={type:`response`,requestId:n.requestId,error:`Unknown request type: ${n.type}`}}}catch(t){e={type:`response`,requestId:n.requestId,error:t instanceof Error?t.message:String(t)}}t.send(JSON.stringify(e));return}if(n.type===`webhook_event`&&D.handleWebhookEvent(n.webhookId,n.headers,n.body),n.type===`navigate_event`){let e=typeof n.sliccHeader==`string`?n.sliccHeader:``,t=typeof n.url==`string`&&n.url.length>0?n.url:``;e&&t&&D.emitEvent({type:`navigate`,navigateUrl:t,targetScoop:void 0,timestamp:typeof n.timestamp==`string`?n.timestamp:new Date().toISOString(),body:{url:t,sliccHeader:e,title:typeof n.title==`string`?n.title:void 0}})}}catch(e){$.error(`Failed to process lick message`,{error:e instanceof Error?e.message:String(e)})}},t.onclose=()=>{$.warn(`Lick WebSocket disconnected, reconnecting in 3s...`),setTimeout(A,3e3)},t.onerror=e=>{$.error(`Lick WebSocket error`,{error:String(e)})}};A(),o.onModelChange=e=>{localStorage.setItem(`selected-model`,e),v.updateModel()};let ne=new Set;o.onClearChat=async()=>{await v.clearAllMessages(),m.clear(),ne.clear()},o.onClearFilesystem=async()=>{await v.resetFilesystem()};let re=async e=>{$.info(`Scoop selected`,{jid:e.jid,name:e.name}),d=e,v.createScoopTab(e.jid),o.panels.memory.setSelectedScoop(e.jid),o.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=m.get(e.jid),r=!ne.has(e.jid),i=e.isCone?void 0:e.name;if(!r&&n&&n.length>0)await o.panels.chat.switchToContext(t,!e.isCone,i),o.panels.chat.loadMessages(n);else{if(await o.panels.chat.switchToContext(t,!e.isCone,i),o.panels.chat.getMessages().length===0){let t=await v.getMessagesForScoop(e.jid);for(let e of t){let t=e.channel===`delegation`;Ga(e.channel)?o.panels.chat.addLickMessage(e.id,e.content,e.channel,new Date(e.timestamp).getTime()):t?o.panels.chat.addUserMessage(`**[Instructions from sliccy]**\n\n${e.content}`):e.fromAssistant?(u({type:`message_start`,messageId:e.id}),u({type:`content_delta`,messageId:e.id,text:e.content}),u({type:`content_done`,messageId:e.id})):o.panels.chat.addUserMessage(e.content)}}let n=o.panels.chat.getMessages(),r=new Set(n.map(e=>e.id)),a=g(e.jid),s=a.filter(e=>!r.has(e.id));a.length=0,a.push(...n,...s),s.length>0&&o.panels.chat.loadMessages(a)}e.isCone&&v.isProcessing(e.jid)&&o.panels.chat.setProcessing(!0),ne.add(e.jid)};if(o.onScoopSelect=re,d&&(v.createScoopTab(d.jid),await re(d)),h9()&&await g9(o.panels.chat),a===`standalone`||a===`electron-overlay`){let e=await Do(),t=q7(a,e!==null)?vo:null,n=await Eo({locationHref:window.location.href,storage:window.localStorage,envBaseUrl:null,defaultWorkerBaseUrl:t,runtimeConfigFetcher:async()=>e}),r=null,i=null,s=null;F2(()=>C?(e,t)=>C.sendFsRequest(e,t):r?(e,t)=>r.sendFsRequest(e,t):null),c$(()=>C?()=>C.getBestFollowerForTeleport():null),l$(()=>C?()=>C.getConnectedFollowers():null);let u=e=>{s&&=(clearInterval(s),null),r?.close();let t=`follower-${e.bootstrapId}`,n=new H7(e.channel,{browserTransport:c.getTransport(),browserAPI:c,onSnapshot:e=>{o.panels.chat.loadMessages(e)},onUserMessage:(e,t,n,r)=>{o.panels.chat.addUserMessage(e,r)},onStatus:e=>{o.panels.chat.setProcessing(e===`processing`)},onTargetsChanged:()=>void i()});r=n,c.setTrayTargetProvider(n),o.panels.chat.setAgent(n),n.requestSnapshot();let i=async()=>{try{let e=await c.listPages();n.advertiseTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})),t)}catch{}};s=setInterval(i,5e3),i(),$.info(`Follower sync wired to chat panel`,{trayId:e.trayId})},f=e=>{i?.cancel(),s&&=(clearInterval(s),null),r?.close(),r=null,i=g7({joinUrl:e,runtime:`slicc-standalone`,fetchImpl:O1()},{onConnected:e=>u(e),onReconnecting:e=>{$.info(`Follower reconnecting`,{attempt:e})},onGaveUp:e=>{$.warn(`Follower reconnect gave up`,{lastError:e})}})};if(window.addEventListener(`slicc:tray-join`,(e=>{f(e.detail.joinUrl)})),window.addEventListener(`beforeunload`,()=>{s&&clearInterval(s),r?.close(),i?.cancel()},{once:!0}),n?.joinUrl)f(n.joinUrl);else if(n?.workerBaseUrl){let e,t,r,i,a=new G7,s=()=>{t=new B7({browserTransport:c.getTransport(),browserAPI:c,getMessages:()=>o.panels.chat.getMessages(),getScoopJid:()=>d?.jid??`cone`,onFollowerMessage:(e,t,n)=>{o.panels.chat.addUserMessage(e,n),w.sendMessage(e,t,n)},onFollowerAbort:()=>{w.stop()},onFollowerCountChanged:e=>{e>0?a.activate():a.deactivate()}}),C=t,A1(()=>t.getConnectedFollowers()),c.setTrayTargetProvider(t),i&&clearInterval(i);let n=async()=>{try{let e=await c.listPages();t.setLocalTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})))}catch{}};i=setInterval(n,5e3),n(),r=new m7({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})}})};s(),l.add(e=>{t.broadcastEvent(e)}),e=new w1({workerBaseUrl:n.workerBaseUrl,runtime:`slicc-standalone`,fetchImpl:O1(),onControlMessage:e=>{if(e.type===`webhook.event`){D.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)})})},onReconnecting:(e,t)=>{$.info(`Leader tray reconnecting`,{attempt:e,lastError:t})},onReconnected:e=>{$.info(`Leader tray reconnected`,{trayId:e.trayId});let t=To(window.location.href,e.workerBaseUrl,e.trayId);t!==window.location.href&&window.history.replaceState(window.history.state,``,t)},onReconnectGaveUp:(e,t)=>{$.warn(`Leader tray reconnect gave up`,{lastError:e,attempts:t})}}),N1(async()=>{t.stop(),r.stop(),e.stop(),await e.clearSession();let n=await e.start(),i=To(window.location.href,n.workerBaseUrl,n.trayId);return i!==window.location.href&&window.history.replaceState(window.history.state,``,i),s(),b1()}),e.start().then(e=>{let t=To(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(),a.deactivate()},{once:!0})}}$.info(`Orchestrator initialized — cone+scoops ready`,{scoopCount:v.getScoops().length}),W6().catch(()=>{})}w9().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{Co as a,co as c,ta as d,go as i,eo as l,jo as n,So as o,vo as r,so as s,QK as t,na as u};
|
|
15874
|
+
`,document.head.appendChild(t),window.addEventListener(`message`,e=>{e.source===window.parent&&$7(e.data)&&o.setActiveTab(J7(`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 s=b9();await o.panels.chat.initSession(`session-cone`),$.info(`Session initialized`);let c=new Us,l=new Set,u=e=>{$.debug(`Emit to UI`,{type:e.type,listenerCount:l.size});for(let t of l)try{t(e)}catch(t){$.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}},d=null,p=new Map,m=new Map;function h(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function g(e){let t=m.get(e);return t||(t=[],m.set(e,t)),t}function _(e,t){let n=g(e),r=p.get(e);if(r){let e=n.find(e=>e.id===r);if(e)return e}r=`scoop-${e}-${h()}`,p.set(e,r);let i=v.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),d?.jid===e&&u({type:`message_start`,messageId:r}),o}let v=new M5(o.getIframeContainer(),{onResponse:(e,t,n)=>{let r=_(e);n?r.content+=t:(r.content=t,r.isStreaming=!1),d?.jid===e&&(u({type:`content_delta`,messageId:r.id,text:t}),n||u({type:`content_done`,messageId:r.id}))},onResponseDone:e=>{let t=g(e),n=p.get(e);if(n){let r=t.find(e=>e.id===n);r&&(r.isStreaming=!1),d?.jid===e&&u({type:`content_done`,messageId:n}),p.delete(e)}},onSendMessage:(e,t)=>{$.debug(`Send message requested`,{targetJid:e,textLength:t.length});let n=`msg-${h()}`,r={id:n,chatJid:e,senderId:`assistant`,senderName:`sliccy`,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`web`};v.handleMessage(r),g(e).push({id:n,role:`assistant`,content:t,timestamp:Date.now()}),d?.jid===e&&(u({type:`message_start`,messageId:n}),u({type:`content_delta`,messageId:n,text:t}),u({type:`content_done`,messageId:n}))},onStatusChange:(e,t)=>{if(o.panels.scoops.updateScoopStatus(e,t),o.updateScoopSwitcherStatus?.(e,t),d?.jid===e){if(o.setAgentProcessing(t===`processing`),t===`processing`)o.panels.chat.setProcessing(!0);else if(t===`ready`){o.panels.chat.setProcessing(!1);let t=p.get(e)??`done-${e}-${h()}`;p.delete(e),u({type:`turn_end`,messageId:t})}}},onError:(e,t)=>{$.error(`Scoop error`,{scoopJid:e,error:t}),d?.jid===e&&u({type:`error`,error:t})},getBrowserAPI:()=>c,onToolStart:(e,t,n)=>{if(new Set([`send_message`,`list_scoops`,`list_tasks`]).has(t))return;let r=_(e);r.toolCalls||=[],r.toolCalls.push({id:h(),name:t,input:n}),d?.jid===e&&u({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=g(e),a=p.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)}}d?.jid===e&&a&&u({type:`tool_result`,messageId:a,toolName:t,result:n,isError:r})},onToolUI:(e,t,n,r)=>{let i=p.get(e);i?u({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=p.get(e);n&&u({type:`tool_ui_done`,messageId:n,requestId:t})},onIncomingMessage:(e,t)=>{if(Ga(t.channel)){let n=new Date(t.timestamp).getTime(),r=t.channel;if(g(e).push({id:t.id,role:`user`,content:t.content,timestamp:n,source:`lick`,channel:r}),d?.jid===e)o.panels.chat.addLickMessage(t.id,t.content,r,n);else{let i=v.getScoops().find(t=>t.jid===e),a=i?.isCone?`session-cone`:i?`session-${i.folder}`:`session-${e}`;o.panels.chat.persistLickToSession(a,{id:t.id,content:t.content,channel:r,timestamp:n})}return}let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel};g(e).push(n),d?.jid===e&&(u({type:`message_start`,messageId:t.id}),u({type:`content_delta`,messageId:t.id,text:n.content}),u({type:`content_done`,messageId:t.id}))}});await v.init(),o.panels.scoops.setOrchestrator(v),o.panels.memory.setOrchestrator(v),o.setScoopSwitcherOrchestrator?.(v);{let e=v.getSharedFS();e?Q5(v,e,v.getSessionStore()):$.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`)}let b=v.getSharedFS();if(b){o.panels.fileBrowser.setFs(b),$.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 b.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})}})()},x9(b,(e,t)=>{t===`error`?$.warn(`Dropped skill install failed`,{message:e}):$.info(`Dropped skill installed`,{message:e}),s(e,t)},async()=>{await o.panels.fileBrowser.refresh()},e=>o.panels.chat.addAttachmentsFromFiles(e));try{let{WasmShell:e}=await k(async()=>{let{WasmShell:e}=await Promise.resolve().then(()=>i8);return{WasmShell:e}},void 0),{fetchSecretEnvVars:t}=await k(async()=>{let{fetchSecretEnvVars:e}=await Promise.resolve().then(()=>l5);return{fetchSecretEnvVars:e}},void 0),n=await t(),r=new e({fs:b,browserAPI:c,env:Object.keys(n).length>0?n:void 0});await o.panels.terminal.mountShell(r),$.info(`Terminal mounted with shared VFS`);try{let{BshWatchdog:e}=await k(async()=>{let{BshWatchdog:e}=await import(`./bsh-watchdog-BofJVeV-.js`);return{BshWatchdog:e}},__vite__mapDeps([20,13])),t=new e({browserAPI:c,scriptCatalog:r.getScriptCatalog(),fs:b});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 x=v.getScoops(),S=x.some(e=>e.isCone);if(r)$.info(`Skipping local cone bootstrap while joining a tray without a configured provider`);else if(!S)d=await o.panels.scoops.createCone(),$.info(`Created cone`);else{let e=new URLSearchParams(window.location.search).get(`scoop`);if(e){let t=x.find(t=>t.folder===e);t?(d=t,$.info(`Restored scoop from URL`,{folder:e})):d=x.find(e=>e.isCone)??x[0]}else d=x.find(e=>e.isCone)??x[0]}d&&o.panels.memory.setSelectedScoop(d.jid);let C=null,w={sendMessage(e,t,n){if(!d){u({type:`error`,error:`No scoop selected`});return}let r={id:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:d.jid,senderId:`user`,senderName:`User`,content:e,attachments:n,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`};g(d.jid).push({id:r.id,role:`user`,content:e,attachments:n,timestamp:Date.now()}),C?.broadcastUserMessage(e,r.id,n),v.handleMessage(r),v.createScoopTab(d.jid)},onEvent(e){return l.add(e),()=>l.delete(e)},stop(){d&&(v.stopScoop(d.jid),v.clearQueuedMessages(d.jid).catch(e=>{$.error(`Failed to clear queued messages on stop`,{error:e instanceof Error?e.message:String(e)})}))}};o.panels.chat.setAgent(w),b&&o.panels.chat.setAttachmentWriter(Fs(b)),o.panels.chat.setDeleteQueuedMessageCallback(e=>{if(d){v.deleteQueuedMessage(d.jid,e).catch(t=>{$.error(`Failed to delete queued message`,{messageId:e,error:t instanceof Error?t.message:String(t)})});let t=m.get(d.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:E}=await k(async()=>{let{getLickManager:e}=await Promise.resolve().then(()=>b5);return{getLickManager:e}},void 0),D=E();await D.init(),v.setLickManager(D);let O=e=>{let t=e.type===`webhook`,n=e.type===`sprinkle`,r=e.type===`fswatch`,i=e.type===`session-reload`,a=e.type===`navigate`,s=t?e.webhookName:n?e.sprinkleName:r?e.fswatchName:i?`session-reload`:a?e.navigateUrl:e.cronName,c=t?e.webhookId:n?e.sprinkleName:r?e.fswatchId:i?`session-reload`:a?e.navigateUrl:e.cronId,l=e.type;if($.debug(`Lick event`,{type:e.type,name:s,targetScoop:e.targetScoop}),n&&e.sprinkleName===`welcome`){let t=e.body,n=t?.action;(n===`onboarding-complete`||n===`shortcut-migrate`)&&b?.writeFile(`/shared/.welcomed`,`1`).catch(e=>$.warn(`Failed to persist welcome marker`,e)),n===`shortcut-migrate`&&te?.close(`welcome`),n===`onboarding-complete`&&t?.data?.mountWorkspace&&b&&v9(b).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 _9(t),te?.sendToSprinkle(`welcome`,{action:`mount-complete`,dirName:t.name})}catch(e){e.name!==`AbortError`&&$.warn(`Mount picker failed`,e),te?.sendToSprinkle(`welcome`,{action:`mount-cancelled`})}})();return}let u=v.getScoops(),f;if(f=e.targetScoop?u.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):u.find(e=>e.isCone),f){let u=`${l}-${c}-${Date.now()}`,p=t?`Webhook Event`:n?`Sprinkle Event`:r?`File Watch Event`:i?`Session Reload`:a?`Navigate Event`:`Cron Event`,m=null;if(i){let t=e.body;if(t?.reason===`mount-recovery`&&(m=f9(t.mounts??[]),m===null)){$.debug(`Dropping session-reload lick with empty mount-recovery list`);return}}m===null&&(m=`[${p}: ${s}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``);let h={id:u,chatJid:f.jid,senderId:l,senderName:`${l}:${s}`,content:m,timestamp:e.timestamp,fromAssistant:!1,channel:l},_=Date.now();if(g(f.jid).push({id:u,role:`user`,content:m,timestamp:_,source:`lick`,channel:l}),d?.jid===f.jid)o.panels.chat.addLickMessage(u,m,l,_);else{let e=f.isCone?`session-cone`:`session-${f.folder}`;o.panels.chat.persistLickToSession(e,{id:u,content:m,channel:l,timestamp:_})}$.info(`Routing lick to scoop`,{type:l,name:s,scoopJid:f.jid}),v.handleMessage(h)}else $.warn(`Lick target scoop not found`,{targetScoop:e.targetScoop})};D.setEventHandler(O);let ee=new Qs(c.getTransport(),e=>{D.emitEvent({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:new Date().toISOString(),body:{url:e.url,sliccHeader:e.sliccHeader,title:e.title}})});(async()=>{try{await c.connect(),await ee.start(),$.info(`Navigation watcher started`)}catch(e){$.warn(`Failed to start navigation watcher`,{error:e instanceof Error?e.message:String(e)})}})(),b&&oe().then(async e=>{if(e.length===0)return;let{needsRecovery:t}=await l9(e,b,$);t.length!==0&&O({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:t}})}).catch(e=>$.warn(`Failed to restore persisted mounts`,e)),o.panels.chat.onDipLick=(e,t)=>{O({type:`sprinkle`,sprinkleName:`inline`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{action:e,data:t}})};let te=null;if(b){if(te=new c9(b,O,{addSprinkle:(e,t,n,r)=>o.addSprinkle(e,t,n,r),removeSprinkle:e=>o.removeSprinkle(e)},()=>{let e=v.getScoops().find(e=>e.isCone);e&&(v.stopScoop(e.jid),v.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=te,window.__slicc_reloadSkills=()=>v.reloadAllSkills(),await te.refresh(),o.onSprinkleClose=e=>te.close(e),o.getAvailableSprinkles=()=>{let e=new Set(te.opened());return te.available().filter(t=>!e.has(t.name)).map(e=>({name:e.name,title:e.title}))},o.onOpenSprinkle=(e,t)=>te.open(e,t),o.updateAddButtons(),!await b.exists(`/shared/.welcomed`)&&localStorage.getItem(`slicc-welcomed`)&&(await b.writeFile(`/shared/.welcomed`,`1`).catch(()=>{}),localStorage.removeItem(`slicc-welcomed`)),!await b.exists(`/shared/.welcomed`)&&!r&&te.available().some(e=>e.name===`welcome`))try{await te.open(`welcome`)}catch(e){$.warn(`Failed to open welcome sprinkle`,e)}await te.restoreOpenSprinkles(),$.info(`SprinkleManager initialized`)}let A=()=>{let e=X7(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:D.listWebhooks()};break;case`create_webhook`:{let t=await D.createWebhook(n.name||`default`,n.scoop,n.filter),r=b1().session,i=r?.webhookUrl?Q7(r.webhookUrl,t.id):Z7(window.location.href,t.id);e={type:`response`,requestId:n.requestId,data:{...t,url:i}};break}case`delete_webhook`:e=await D.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:D.listCronTasks()};break;case`create_crontask`:{if(!n.name)throw Error(`name is required`);if(!n.cron)throw Error(`cron is required`);let t=await D.createCronTask(n.name,n.cron,n.scoop,n.filter);e={type:`response`,requestId:n.requestId,data:t};break}case`delete_crontask`:e=await D.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=b1();e={type:`response`,requestId:n.requestId,data:{state:t.state,joinUrl:t.session?.joinUrl??null,workerBaseUrl:t.session?.workerBaseUrl??null,trayId:t.session?.trayId??null}};break}default:e={type:`response`,requestId:n.requestId,error:`Unknown request type: ${n.type}`}}}catch(t){e={type:`response`,requestId:n.requestId,error:t instanceof Error?t.message:String(t)}}t.send(JSON.stringify(e));return}if(n.type===`webhook_event`&&D.handleWebhookEvent(n.webhookId,n.headers,n.body),n.type===`navigate_event`){let e=typeof n.sliccHeader==`string`?n.sliccHeader:``,t=typeof n.url==`string`&&n.url.length>0?n.url:``;e&&t&&D.emitEvent({type:`navigate`,navigateUrl:t,targetScoop:void 0,timestamp:typeof n.timestamp==`string`?n.timestamp:new Date().toISOString(),body:{url:t,sliccHeader:e,title:typeof n.title==`string`?n.title:void 0}})}}catch(e){$.error(`Failed to process lick message`,{error:e instanceof Error?e.message:String(e)})}},t.onclose=()=>{$.warn(`Lick WebSocket disconnected, reconnecting in 3s...`),setTimeout(A,3e3)},t.onerror=e=>{$.error(`Lick WebSocket error`,{error:String(e)})}};A(),o.onModelChange=e=>{localStorage.setItem(`selected-model`,e),v.updateModel()};let ne=new Set;o.onClearChat=async()=>{await v.clearAllMessages(),m.clear(),ne.clear()},o.onClearFilesystem=async()=>{await v.resetFilesystem()};let re=async e=>{$.info(`Scoop selected`,{jid:e.jid,name:e.name}),d=e,v.createScoopTab(e.jid),o.panels.memory.setSelectedScoop(e.jid),o.panels.scoops.setSelectedJid(e.jid);let t=e.isCone?`session-cone`:`session-${e.folder}`,n=m.get(e.jid),r=!ne.has(e.jid),i=e.isCone?void 0:e.name;if(!r&&n&&n.length>0)await o.panels.chat.switchToContext(t,!e.isCone,i),o.panels.chat.loadMessages(n);else{if(await o.panels.chat.switchToContext(t,!e.isCone,i),o.panels.chat.getMessages().length===0){let t=await v.getMessagesForScoop(e.jid);for(let e of t){let t=e.channel===`delegation`;Ga(e.channel)?o.panels.chat.addLickMessage(e.id,e.content,e.channel,new Date(e.timestamp).getTime()):t?o.panels.chat.addUserMessage(`**[Instructions from sliccy]**\n\n${e.content}`):e.fromAssistant?(u({type:`message_start`,messageId:e.id}),u({type:`content_delta`,messageId:e.id,text:e.content}),u({type:`content_done`,messageId:e.id})):o.panels.chat.addUserMessage(e.content)}}let n=o.panels.chat.getMessages(),r=new Set(n.map(e=>e.id)),a=g(e.jid),s=a.filter(e=>!r.has(e.id));a.length=0,a.push(...n,...s),s.length>0&&o.panels.chat.loadMessages(a)}e.isCone&&v.isProcessing(e.jid)&&o.panels.chat.setProcessing(!0),ne.add(e.jid)};if(o.onScoopSelect=re,d&&(v.createScoopTab(d.jid),await re(d)),h9()&&await g9(o.panels.chat),a===`standalone`||a===`electron-overlay`){let e=await Do(),t=q7(a,e!==null)?vo:null,n=await Eo({locationHref:window.location.href,storage:window.localStorage,envBaseUrl:null,defaultWorkerBaseUrl:t,runtimeConfigFetcher:async()=>e}),r=null,i=null,s=null;F2(()=>C?(e,t)=>C.sendFsRequest(e,t):r?(e,t)=>r.sendFsRequest(e,t):null),c$(()=>C?()=>C.getBestFollowerForTeleport():null),l$(()=>C?()=>C.getConnectedFollowers():null);let u=e=>{s&&=(clearInterval(s),null),r?.close();let t=`follower-${e.bootstrapId}`,n=new H7(e.channel,{browserTransport:c.getTransport(),browserAPI:c,onSnapshot:e=>{o.panels.chat.loadMessages(e)},onUserMessage:(e,t,n,r)=>{o.panels.chat.addUserMessage(e,r)},onStatus:e=>{o.panels.chat.setProcessing(e===`processing`)},onTargetsChanged:()=>void i()});r=n,c.setTrayTargetProvider(n),o.panels.chat.setAgent(n),n.requestSnapshot();let i=async()=>{try{let e=await c.listPages();n.advertiseTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})),t)}catch{}};s=setInterval(i,5e3),i(),$.info(`Follower sync wired to chat panel`,{trayId:e.trayId})},f=e=>{i?.cancel(),s&&=(clearInterval(s),null),r?.close(),r=null,i=g7({joinUrl:e,runtime:`slicc-standalone`,fetchImpl:O1()},{onConnected:e=>u(e),onReconnecting:e=>{$.info(`Follower reconnecting`,{attempt:e})},onGaveUp:e=>{$.warn(`Follower reconnect gave up`,{lastError:e})}})};if(window.addEventListener(`slicc:tray-join`,(e=>{f(e.detail.joinUrl)})),window.addEventListener(`beforeunload`,()=>{s&&clearInterval(s),r?.close(),i?.cancel()},{once:!0}),n?.joinUrl)f(n.joinUrl);else if(n?.workerBaseUrl){let e,t,r,i,a=new G7,s=()=>{t=new B7({browserTransport:c.getTransport(),browserAPI:c,getMessages:()=>o.panels.chat.getMessages(),getScoopJid:()=>d?.jid??`cone`,onFollowerMessage:(e,t,n)=>{o.panels.chat.addUserMessage(e,n),w.sendMessage(e,t,n)},onFollowerAbort:()=>{w.stop()},onFollowerCountChanged:e=>{e>0?a.activate():a.deactivate()}}),C=t,A1(()=>t.getConnectedFollowers()),c.setTrayTargetProvider(t),i&&clearInterval(i);let n=async()=>{try{let e=await c.listPages();t.setLocalTargets(e.map(e=>({targetId:e.targetId,title:e.title,url:e.url})))}catch{}};i=setInterval(n,5e3),n(),r=new m7({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})}})};s(),l.add(e=>{t.broadcastEvent(e)}),e=new w1({workerBaseUrl:n.workerBaseUrl,runtime:`slicc-standalone`,fetchImpl:O1(),onControlMessage:e=>{if(e.type===`webhook.event`){D.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)})})},onReconnecting:(e,t)=>{$.info(`Leader tray reconnecting`,{attempt:e,lastError:t})},onReconnected:e=>{$.info(`Leader tray reconnected`,{trayId:e.trayId});let t=To(window.location.href,e.workerBaseUrl,e.trayId);t!==window.location.href&&window.history.replaceState(window.history.state,``,t)},onReconnectGaveUp:(e,t)=>{$.warn(`Leader tray reconnect gave up`,{lastError:e,attempts:t})}}),N1(async()=>{t.stop(),r.stop(),e.stop(),await e.clearSession();let n=await e.start(),i=To(window.location.href,n.workerBaseUrl,n.trayId);return i!==window.location.href&&window.history.replaceState(window.history.state,``,i),s(),b1()}),e.start().then(e=>{let t=To(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(),a.deactivate()},{once:!0})}}$.info(`Orchestrator initialized — cone+scoops ready`,{scoopCount:v.getScoops().length}),W6().catch(()=>{})}w9().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{Co as a,co as c,ta as d,go as i,eo as l,jo as n,So as o,vo as r,so as s,QK as t,na as u};
|