tmux-weblink 2.2.50 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,46 +1,123 @@
1
- var ni=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function gt(e){return e.replace(/\x1b\[\?1049[hl]/g,"")}function Me(e){return e.replace(ni,"")}var qe;function ii(){return qe||(document.querySelector("link[data-tmux-web-xterm-css]")?qe=Promise.resolve():(qe=new Promise(e=>{let t=document.createElement("link");t.rel="stylesheet",t.href="/assets/xterm.css",t.setAttribute("data-tmux-web-xterm-css",""),t.addEventListener("load",()=>e(),{once:!0}),t.addEventListener("error",()=>e(),{once:!0}),document.head.appendChild(t)}),qe))}var ai=class Hn{terminal;fitAddon;container;webglActive=!1;repaintTimer=0;webglAddon=null;constructor(t,n,i){this.container=t,this.terminal=n,this.fitAddon=i,this.terminal.loadAddon(this.fitAddon),this.terminal.open(t),this.enableWebglRenderer(),document.addEventListener("visibilitychange",()=>{document.hidden||this.refreshPaintedRows()})}enableWebglRenderer(){if(si()==="webgl"){try{if(!document.createElement("canvas").getContext("webgl2",{failIfMajorPerformanceCaveat:!0}))return}catch{return}import("./addon-webgl-B45EJ6AW.js").then(({WebglAddon:t})=>{let n=new t;n.onContextLoss(()=>{this.webglActive=!1,this.webglAddon=null;try{n.dispose()}catch{}this.fit()});try{this.terminal.loadAddon(n)}catch{return}this.webglAddon=n,this.webglActive=!0,this.fit()}).catch(()=>{})}}refreshPaintedRows(){if(this.webglActive){try{this.webglAddon?.clearTextureAtlas?.()}catch{}try{this.terminal.refresh(0,Math.max(0,this.terminal.rows-1))}catch{}}}static async create(t,n,i){let[{Terminal:a},{FitAddon:r}]=await Promise.all([import("./xterm-BXEES47M.js"),import("./addon-fit-D5N335P2.js"),ii()]),o="'JetBrains Mono', 'SF Mono', 'Menlo', monospace",l=new a({fontSize:oi(14,o),fontFamily:o,cursorBlink:!0,cursorStyle:"bar",scrollback:n,convertEol:!1,smoothScrollDuration:120,theme:i});return new Hn(t,l,new r)}get cols(){return this.terminal.cols}get rows(){return this.terminal.rows}write(t){return new Promise(n=>this.terminal.write(t,n))}reset(){this.terminal.reset()}scrollToBottom(){this.terminal.scrollToBottom()}scrollToLine(t,n=!1){this.terminal.scrollToLine(Math.max(0,t),n),this.scheduleRepaintCheck()}scrollLines(t){this.terminal.scrollLines(t),this.scheduleRepaintCheck()}scheduleRepaintCheck(){this.webglActive&&(this.repaintTimer&&clearTimeout(this.repaintTimer),this.repaintTimer=setTimeout(()=>{this.repaintTimer=0,this.refreshPaintedRows()},150))}isNearScrollbackTop(){return this.terminal.buffer.active.viewportY<=1}viewportY(){return this.terminal.buffer.active.viewportY}baseY(){return this.terminal.buffer.active.baseY}cellHeight(){let t=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().height??0,n=this.terminal.rows;return t>0&&n>0?t/n:16}fit(){let t=li(this.container);if(t.width<=0||t.height<=0)return!1;let n=this.terminal.cols,i=this.terminal.rows,a=this.paintedCellWidth();a<=0&&(this.fitAddon.fit(),a=this.paintedCellWidth());let r=this.fitAddon.proposeDimensions?.();if(!r)return this.fitAddon.fit(),!0;let o=this.overlayScrollbarWidth(),l=o>0?o+2:0,u=a>0?Math.max(10,Math.min(r.cols,Math.floor((t.width-l)/a))):r.cols,p=r.rows;return(u!==this.terminal.cols||p!==this.terminal.rows)&&this.terminal.resize(u,p),this.webglActive&&(n!==this.terminal.cols||i!==this.terminal.rows)&&this.refreshPaintedRows(),!0}paintedCellWidth(){let t=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().width??0,n=this.terminal.cols;return t>0&&n>0?t/n:0}overlayScrollbarWidth(){let t=this.terminal.element?.querySelector(".vertical.scrollbar");if(!t)return 0;let n=t.getBoundingClientRect();return!(n.width>0)||!(n.height>0)?0:Math.round(n.width)}focus(){this.terminal.focus()}pasteText(t){this.terminal.paste(t)}input(t){this.terminal.input(t,!1)}onData(t){this.terminal.onData(t),this.terminal.onBinary(t)}onResize(t){this.terminal.onResize(t)}onScroll(t){this.terminal.onScroll(t)}attachCustomKeyEventHandler(t){this.terminal.attachCustomKeyEventHandler(t)}isFocused(){let t=document.activeElement;return t?t===this.container||t===this.terminal.textarea||this.container.contains(t)||!!t.closest?.(".xterm"):!1}getScreenText(){return this.getRowsText(0,this.terminal.rows-1)}getRowsText(t,n){let i=this.terminal.buffer.active,[a,r]=t<=n?[t,n]:[n,t],o=i.viewportY,l=[];for(let u=a;u<=r;u++){let p=i.getLine(o+u);l.push(p?p.translateToString(!0):"")}return l.join(`
2
- `)}selectRows(t,n){let i=this.terminal.buffer.active,[a,r]=t<=n?[t,n]:[n,t];this.terminal.selectLines(i.viewportY+a,i.viewportY+r)}selectCells(t,n,i,a){let r=this.terminal.buffer.active,o=Math.min(n,a),l=Math.max(n,a);if(o===l){let u=Math.min(t,i),p=Math.max(t,i);this.terminal.select(u,r.viewportY+o,p-u+1)}else this.terminal.selectLines(r.viewportY+o,r.viewportY+l)}getCellsText(t,n,i,a){let r=this.terminal.buffer.active,o=Math.min(n,a),l=Math.max(n,a),u=n<a?t:n>a?i:Math.min(t,i),p=n<a?i:n>a?t:Math.max(t,i),f=r.viewportY,y=[];for(let H=o;H<=l;H++){let L=r.getLine(f+H);if(!L){y.push("");continue}let w=H===o?u:0,g=H===l?p:this.terminal.cols-1,M="";for(let W=w;W<=g;W++){let P=L.getCell(W);P&&(M+=P.getChars())}y.push(M.replace(/\s+$/,""))}return y.join(`
3
- `)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}};function oi(e,t){try{let n=document.createElement("canvas").getContext("2d");if(!n)return e;let i=100;n.font=`${i}px ${t}`;let a=n.measureText("M").width/i;if(!Number.isFinite(a)||a<=0)return e;let r=window.devicePixelRatio||1,o=e,l=Number.POSITIVE_INFINITY;for(let u=4;u<=40;u++){let p=u/(a*r);if(p<e-1.5||p>e+1.5)continue;let f=Math.abs(p-e);f<l&&(l=f,o=p)}return Math.round(o*100)/100}catch{return e}}function si(){try{let e=new URLSearchParams(window.location.search).get("renderer");return e==="dom"||e==="webgl"?e:null}catch{return null}}function li(e){let t=e.getBoundingClientRect(),n=window.visualViewport;return n?{width:Math.min(t.width,n.width),height:Math.max(0,Math.min(t.height,n.height-Math.max(0,t.top)))}:t}function ri(e,t,n){return e.innerHTML="",e.classList.add("terminal-pending"),(async()=>{let i=await ai.create(e,n.scrollback,n.theme),a,r=0,o,l=null,u=0,p=0,f=.2,y=10,H=.95,L=.04,w=null,g=null;function M(s){w||(w=document.createElement("div"),w.style.cssText=["position:absolute","left:0","width:40%","padding:10px 0","text-align:center","font:600 14px/1.4 system-ui, -apple-system, sans-serif","color:rgba(255,255,255,0.95)","background:rgba(20,30,50,0.55)","border:1px solid rgba(255,255,255,0.25)","border-radius:10px","pointer-events:none","opacity:0","transition:opacity 0.15s ease","z-index:6"].join(";"),e.appendChild(w)),w.textContent=s?"\u2191 \u4E0A\u7FFB\u4E00\u9875 (PgUp)":"\u2193 \u4E0B\u7FFB\u4E00\u9875 (PgDn)",w.style.top=s?"10%":"auto",w.style.bottom=s?"auto":"10%",w.style.opacity="1",g&&clearTimeout(g),g=setTimeout(()=>{w&&(w.style.opacity="0")},900)}function W(){g&&clearTimeout(g),w&&(w.style.opacity="0")}function P(){u&&(cancelAnimationFrame(u),u=0),p=0}function j(s){if(P(),Math.abs(s)<f)return;p=Math.max(-y,Math.min(y,s));let d=()=>{if(B){u=0;return}let h=i.cellHeight(),E=h>0?Math.round(p*16/h):p>0?1:-1;E===0&&(E=p>0?1:-1);let I=i.viewportY()-E,ee=i.baseY(),se=Math.max(0,Math.min(I,ee));if(i.scrollToLine(se,!0),p*=H,se!==I){u=0;return}if(Math.abs(p)<L){u=0;return}u=requestAnimationFrame(d)};u=requestAnimationFrame(d)}let R=0,b="connecting",x=0,G=!1,v=[],_="",B=!1,le=1e3,A=location.protocol==="https:"?"wss:":"ws:",$t=n.wsBase||"/ws",Dn=A+"//"+location.host+$t+"/"+encodeURIComponent(t),An=($t.replace(/^\/ws/,"")||"")+"/api/session/"+encodeURIComponent(t)+"/upload",Fn=/^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(navigator.userAgent);function $n(){return v.join("")+_}async function Pn(s,d=0){let h=s?i.viewportY():0,E=Me($n());if(i.reset(),!E){s||i.scrollToBottom();return}await i.write(E),s?i.scrollToLine(d+h):i.scrollToBottom()}function re(s){a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify(s))}function Nn(s){let d;try{d=JSON.parse(s)}catch{b==="live"&&(_+=s,i.write(Me(s)));return}if(d.type==="auth.required"){let h=localStorage.getItem("tmux-web-token");h?re({type:"auth.token",token:h}):location.href="/login?returnTo="+encodeURIComponent(location.pathname+location.search);return}if(d.type==="attach_failed"&&typeof d.message=="string"){je=!0,b="dead",i.reset(),i.write(`\r
4
- \x1B[31m`+Me(d.message)+`\x1B[0m\r
5
- `).then(()=>{Re();try{a?.close()}catch{}});return}if(d.type==="auth.ok"){d.token&&localStorage.setItem("tmux-web-token",d.token),le=1e3,de(),re({type:"resize",cols:i.cols,rows:i.rows}),U();return}if(d.type==="auth.failed"){if(d.permanentLock||d.retryAfterMs&&d.retryAfterMs>6e4){localStorage.removeItem("tmux-web-token"),location.href="/login?error="+encodeURIComponent(d.message);return}return}if(d.type==="snapshot"&&typeof d.data=="string"){let h=gt(Me(d.data));v=[h],_="",x=typeof d.lines=="number"?d.lines:n.terminal.initialLines,b="live",i.reset(),de(),re({type:"resize",cols:i.cols,rows:i.rows}),i.write(h).then(()=>i.scrollToBottom());return}if(d.type==="window_changed"&&typeof d.activeIndex=="number"){let h=new URL(location.href);h.searchParams.get("window")!==String(d.activeIndex)&&(h.searchParams.set("window",String(d.activeIndex)),history.replaceState(history.state,"",h)),window.dispatchEvent(new CustomEvent("tmux:windows",{detail:d.windows}));return}if(d.type==="history"&&typeof d.data=="string"){d.lines>0&&d.data?(v.unshift(gt(d.data)),x+=d.lines,Pn(!0,d.lines).finally(()=>{G=!1})):G=!1;return}if(d.type==="data"&&typeof d.data=="string"){let h=gt(Me(d.data));if(b==="connecting"){b="live",_=h,i.write(h);return}b==="live"&&(_+=h,i.write(h))}}let je=!1;function Pt(){if(je)return;let s=Dn,d=localStorage.getItem("tmux-web-token");d&&(s+=(s.includes("?")?"&":"?")+"token="+encodeURIComponent(d)),s+=(s.includes("?")?"&":"?")+"cols="+i.cols+"&rows="+i.rows,a=new WebSocket(s),a.onopen=()=>{b="connecting",x=0,G=!1,v=[],_="",i.reset(),le=1e3},a.onmessage=h=>{typeof h.data=="string"&&Nn(h.data)},a.onclose=()=>{B||(b="connecting",!je&&setTimeout(()=>{le=Math.min(le*2,1e4),!B&&!je&&Pt()},le))},a.onerror=()=>a?.close()}function fe(s){re({type:"input",data:s})}function de(){return i.fit()}function Re(){e.classList.remove("terminal-pending")}function U(){r&&cancelAnimationFrame(r),o&&clearTimeout(o),de(),r=requestAnimationFrame(()=>{r=0,de()&&Re()}),o=setTimeout(()=>{de()&&Re()},120)}function Vn(){U(),setTimeout(U,50),setTimeout(U,150),setTimeout(U,300)}function Nt(s){return typeof s=="string"&&s.startsWith("image/")}function Vt(s){return s?.files?.length?s.files[0]??null:null}function On(s){if(!s?.items)return null;for(let d=0;d<s.items.length;d++){let h=s.items[d];if(h?.kind==="file"&&Nt(h.type))return h.getAsFile()}return null}async function jn(s){let d=new FormData,h=s instanceof File&&s.name?s.name:"upload";d.append("file",s,h);let E=localStorage.getItem("tmux-web-token"),I={};E&&(I.Authorization="Bearer "+E);let ee=await fetch(An,{method:"POST",body:d,headers:I});if(!ee.ok){let qt="upload failed";try{let Jt=await ee.json();Jt.error&&(qt=Jt.error)}catch{}throw new Error(qt)}let se=await ee.json();if(!se.path)throw new Error("no path in response");return se.path}async function ht(s){try{let d=await jn(s);fe(d)}catch{}}i.onData(s=>fe(s)),i.onResize(({cols:s,rows:d})=>re({type:"resize",cols:s,rows:d})),i.onScroll(()=>{b!=="live"||G||!i.isNearScrollbackTop()||(G=!0,re({type:"load_history",before:x}))});let ke=!1,Ce=!1,F=null,N=null,Le=document.createElement("div");Le.className="terminal-copy-banner",Le.innerHTML='<strong>Copy mode</strong><span class="hint">drag to copy \xB7 Esc exits</span>',Le.hidden=!0,e.appendChild(Le);let ne=document.createElement("div");ne.className="terminal-copy-banner terminal-copy-toast",ne.textContent="Copied",ne.hidden=!0,e.appendChild(ne);function Ot(s,d){let h=e.querySelector(".xterm-screen, canvas"),E=(h&&h.getBoundingClientRect().width>0?h:e).getBoundingClientRect(),I=E.height>0&&i.rows>0?E.height/i.rows:18,ee=E.width>0&&i.cols>0?E.width/i.cols:9;return{row:Math.max(0,Math.min(i.rows-1,Math.floor((d-E.top)/I))),col:Math.max(0,Math.min(i.cols-1,Math.floor((s-E.left)/ee)))}}async function _e(s){if(!s)return;try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(s);return}}catch{}let d=document.createElement("textarea");d.value=s,d.style.position="fixed",d.style.opacity="0",d.style.pointerEvents="none",document.body.appendChild(d),d.focus(),d.select();try{document.execCommand("copy")}catch{}d.remove()}let xe;function Ue(){ne.hidden=!1,xe&&clearTimeout(xe),xe=setTimeout(()=>{ne.hidden=!0},1e3)}function ge(s){ke=s,Le.hidden=!s,e.classList.toggle("terminal-copy-mode-active",s),s&&i.focus()}function jt(){ge(!ke)}function Rn(s){B||s.button!==0||Ce||(ke||s.shiftKey)&&(s.preventDefault(),s.stopPropagation(),Ce=!0,F=Ot(s.clientX,s.clientY),N=F,i.selectCells(F.col,F.row,N.col,N.row),document.addEventListener("mousemove",vt,!0),document.addEventListener("mouseup",ft,!0))}function vt(s){B||!Ce||!F||(s.preventDefault(),s.stopPropagation(),N=Ot(s.clientX,s.clientY),i.selectCells(F.col,F.row,N.col,N.row))}function ft(s){if(B||!Ce||!F||!N)return;s.preventDefault(),s.stopPropagation(),document.removeEventListener("mousemove",vt,!0),document.removeEventListener("mouseup",ft,!0),Ce=!1;let d=i.getCellsText(F.col,F.row,N.col,N.row);F=null,N=null,i.clearSelection(),ge(!1),d&&(ne.textContent="\u5DF2\u590D\u5236",_e(d).then(Ue)),i.focus()}e.addEventListener("mousedown",Rn,!0),document.addEventListener("keydown",_n,!0);function _n(s){if(!(B||!i.isFocused()||s.defaultPrevented||s.isComposing)){if(ke){if(s.key==="Escape"){s.preventDefault(),s.stopPropagation(),F=null,N=null,i.clearSelection(),ge(!1);return}if(s.key==="Enter"||(s.ctrlKey||s.metaKey)&&s.code==="KeyC"){s.preventDefault(),s.stopPropagation(),_e(i.getScreenText()).then(Ue),ge(!1);return}}if(s.altKey&&s.code==="KeyC"&&!s.ctrlKey&&!s.metaKey){if(s.preventDefault(),s.stopPropagation(),F&&N){let d=i.getCellsText(F.col,F.row,N.col,N.row);F=null,N=null,i.clearSelection(),ge(!1),d&&(ne.textContent="Copied",_e(d).then(Ue))}else{let d=i.getSelection();d?(i.clearSelection(),ne.textContent="Copied",_e(d).then(Ue)):jt()}return}if((s.ctrlKey||s.metaKey)&&s.code==="KeyV"){s.preventDefault(),s.stopPropagation(),(async()=>{try{if(navigator.clipboard?.read){let d=await navigator.clipboard.read();for(let h of d)for(let E of h.types)if(Nt(E)){let I=await h.getType(E);await ht(I);return}}}catch{}try{let d=await navigator.clipboard?.readText();d&&i.pasteText(Rt(d))}catch{}})();return}}}let We=0;function Rt(s){return s.split(`\r
1
+ var Ts=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function en(t){return t.replace(/\x1b\[\?1049[hl]/g,"")}function Qe(t){return t.replace(Ts,"")}var Et;function Is(){return Et||(document.querySelector("link[data-tmux-web-xterm-css]")?Et=Promise.resolve():(Et=new Promise(t=>{let e=document.createElement("link");e.rel="stylesheet",e.href="/assets/xterm.css",e.setAttribute("data-tmux-web-xterm-css",""),e.addEventListener("load",()=>t(),{once:!0}),e.addEventListener("error",()=>t(),{once:!0}),document.head.appendChild(e)}),Et))}var $s=class cs{terminal;fitAddon;container;webglActive=!1;repaintTimer=0;webglAddon=null;constructor(e,n,i){this.container=e,this.terminal=n,this.fitAddon=i,this.terminal.loadAddon(this.fitAddon),this.terminal.open(e),this.enableWebglRenderer(),document.addEventListener("visibilitychange",()=>{document.hidden||this.refreshPaintedRows()})}enableWebglRenderer(){if(Ms()==="webgl"){try{if(!document.createElement("canvas").getContext("webgl2",{failIfMajorPerformanceCaveat:!0}))return}catch{return}import("./addon-webgl-B45EJ6AW.js").then(({WebglAddon:e})=>{let n=new e;n.onContextLoss(()=>{this.webglActive=!1,this.webglAddon=null;try{n.dispose()}catch{}this.fit()});try{this.terminal.loadAddon(n)}catch{return}this.webglAddon=n,this.webglActive=!0,this.fit()}).catch(()=>{})}}refreshPaintedRows(){if(this.webglActive){try{this.webglAddon?.clearTextureAtlas?.()}catch{}try{this.terminal.refresh(0,Math.max(0,this.terminal.rows-1))}catch{}}}static async create(e,n,i){let[{Terminal:s},{FitAddon:l}]=await Promise.all([import("./xterm-BXEES47M.js"),import("./addon-fit-D5N335P2.js"),Is()]),r="'JetBrains Mono', 'SF Mono', 'Menlo', monospace",a=new s({fontSize:Bs(14,r),fontFamily:r,cursorBlink:!0,cursorStyle:"bar",scrollback:n,convertEol:!1,smoothScrollDuration:120,theme:i});return new cs(e,a,new l)}get cols(){return this.terminal.cols}get rows(){return this.terminal.rows}write(e){return new Promise(n=>this.terminal.write(e,n))}reset(){this.terminal.reset()}scrollToBottom(){this.terminal.scrollToBottom()}scrollToLine(e,n=!1){this.terminal.scrollToLine(Math.max(0,e),n),this.scheduleRepaintCheck()}scrollLines(e){this.terminal.scrollLines(e),this.scheduleRepaintCheck()}scheduleRepaintCheck(){this.webglActive&&(this.repaintTimer&&clearTimeout(this.repaintTimer),this.repaintTimer=setTimeout(()=>{this.repaintTimer=0,this.refreshPaintedRows()},150))}isNearScrollbackTop(){return this.terminal.buffer.active.viewportY<=1}viewportY(){return this.terminal.buffer.active.viewportY}baseY(){return this.terminal.buffer.active.baseY}cellHeight(){let e=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().height??0,n=this.terminal.rows;return e>0&&n>0?e/n:16}fit(){let e=zs(this.container);if(e.width<=0||e.height<=0)return!1;let n=this.terminal.cols,i=this.terminal.rows,s=this.paintedCellWidth();s<=0&&(this.fitAddon.fit(),s=this.paintedCellWidth());let l=this.fitAddon.proposeDimensions?.();if(!l)return this.fitAddon.fit(),!0;let r=this.overlayScrollbarWidth(),a=r>0?r+2:0,o=s>0?Math.max(10,Math.min(l.cols,Math.floor((e.width-a)/s))):l.cols,c=l.rows;return(o!==this.terminal.cols||c!==this.terminal.rows)&&this.terminal.resize(o,c),this.webglActive&&(n!==this.terminal.cols||i!==this.terminal.rows)&&this.refreshPaintedRows(),!0}paintedCellWidth(){let e=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().width??0,n=this.terminal.cols;return e>0&&n>0?e/n:0}overlayScrollbarWidth(){let e=this.terminal.element?.querySelector(".vertical.scrollbar");if(!e)return 0;let n=e.getBoundingClientRect();return!(n.width>0)||!(n.height>0)?0:Math.round(n.width)}focus(){this.terminal.focus()}pasteText(e){this.terminal.paste(e)}input(e){this.terminal.input(e,!1)}onData(e){this.terminal.onData(e),this.terminal.onBinary(e)}onResize(e){this.terminal.onResize(e)}onScroll(e){this.terminal.onScroll(e)}attachCustomKeyEventHandler(e){this.terminal.attachCustomKeyEventHandler(e)}isFocused(){let e=document.activeElement;return e?e===this.container||e===this.terminal.textarea||this.container.contains(e)||!!e.closest?.(".xterm"):!1}getScreenText(){return this.getRowsText(0,this.terminal.rows-1)}getRowsText(e,n){let i=this.terminal.buffer.active,[s,l]=e<=n?[e,n]:[n,e],r=i.viewportY,a=[];for(let o=s;o<=l;o++){let c=i.getLine(r+o);a.push(c?c.translateToString(!0):"")}return a.join(`
2
+ `)}selectRows(e,n){let i=this.terminal.buffer.active,[s,l]=e<=n?[e,n]:[n,e];this.terminal.selectLines(i.viewportY+s,i.viewportY+l)}selectCells(e,n,i,s){let l=this.terminal.buffer.active,r=Math.min(n,s),a=Math.max(n,s);if(r===a){let o=Math.min(e,i),c=Math.max(e,i);this.terminal.select(o,l.viewportY+r,c-o+1)}else this.terminal.selectLines(l.viewportY+r,l.viewportY+a)}getCellsText(e,n,i,s){let l=this.terminal.buffer.active,r=Math.min(n,s),a=Math.max(n,s),o=n<s?e:n>s?i:Math.min(e,i),c=n<s?i:n>s?e:Math.max(e,i),d=l.viewportY,m=[];for(let h=r;h<=a;h++){let u=l.getLine(d+h);if(!u){m.push("");continue}let f=h===r?o:0,b=h===a?c:this.terminal.cols-1,x="";for(let k=f;k<=b;k++){let y=u.getCell(k);y&&(x+=y.getChars())}m.push(x.replace(/\s+$/,""))}return m.join(`
3
+ `)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}};function Bs(t,e){try{let n=document.createElement("canvas").getContext("2d");if(!n)return t;let i=100;n.font=`${i}px ${e}`;let s=n.measureText("M").width/i;if(!Number.isFinite(s)||s<=0)return t;let l=window.devicePixelRatio||1,r=t,a=Number.POSITIVE_INFINITY;for(let o=4;o<=40;o++){let c=o/(s*l);if(c<t-1.5||c>t+1.5)continue;let d=Math.abs(c-t);d<a&&(a=d,r=c)}return Math.round(r*100)/100}catch{return t}}function Ms(){try{let t=new URLSearchParams(window.location.search).get("renderer");return t==="dom"||t==="webgl"?t:null}catch{return null}}function zs(t){let e=t.getBoundingClientRect(),n=window.visualViewport;return n?{width:Math.min(e.width,n.width),height:Math.max(0,Math.min(e.height,n.height-Math.max(0,e.top)))}:e}function As(t,e,n){return t.innerHTML="",t.classList.add("terminal-pending"),(async()=>{let i=await $s.create(t,n.scrollback,n.theme),s,l=0,r,a=null,o=0,c=0,d=.2,m=10,h=.95,u=.04,f=null,b=null;function x(p){f||(f=document.createElement("div"),f.style.cssText=["position:absolute","left:0","width:40%","padding:10px 0","text-align:center","font:600 14px/1.4 system-ui, -apple-system, sans-serif","color:rgba(255,255,255,0.95)","background:rgba(20,30,50,0.55)","border:1px solid rgba(255,255,255,0.25)","border-radius:10px","pointer-events:none","opacity:0","transition:opacity 0.15s ease","z-index:6"].join(";"),t.appendChild(f)),f.textContent=p?"\u2191 \u4E0A\u7FFB\u4E00\u9875 (PgUp)":"\u2193 \u4E0B\u7FFB\u4E00\u9875 (PgDn)",f.style.top=p?"10%":"auto",f.style.bottom=p?"auto":"10%",f.style.opacity="1",b&&clearTimeout(b),b=setTimeout(()=>{f&&(f.style.opacity="0")},900)}function k(){b&&clearTimeout(b),f&&(f.style.opacity="0")}function y(){o&&(cancelAnimationFrame(o),o=0),c=0}function B(p){if(y(),Math.abs(p)<d)return;c=Math.max(-m,Math.min(m,p));let v=()=>{if(L){o=0;return}let S=i.cellHeight(),z=S>0?Math.round(c*16/S):c>0?1:-1;z===0&&(z=c>0?1:-1);let N=i.viewportY()-z,ue=i.baseY(),ye=Math.max(0,Math.min(N,ue));if(i.scrollToLine(ye,!0),c*=h,ye!==N){o=0;return}if(Math.abs(c)<u){o=0;return}o=requestAnimationFrame(v)};o=requestAnimationFrame(v)}let T=0,I="connecting",M=0,$=!1,E=[],A="",L=!1,j=1e3,_=location.protocol==="https:"?"wss:":"ws:",de=n.wsBase||"/ws",G=_+"//"+location.host+de+"/"+encodeURIComponent(e),K=(de.replace(/^\/ws/,"")||"")+"/api/session/"+encodeURIComponent(e)+"/upload",bt=/^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(navigator.userAgent);function Ue(){return E.join("")+A}async function ee(p,v=0){let S=p?i.viewportY():0,z=Qe(Ue());if(i.reset(),!z){p||i.scrollToBottom();return}await i.write(z),p?i.scrollToLine(v+S):i.scrollToBottom()}function pe(p){s?.readyState===WebSocket.OPEN&&s.send(JSON.stringify(p))}function Le(p){let v;try{v=JSON.parse(p)}catch{I==="live"&&(A+=p,i.write(Qe(p)));return}if(v.type==="auth.required"){let S=localStorage.getItem("tmux-web-token");S?pe({type:"auth.token",token:S}):location.href="/login?returnTo="+encodeURIComponent(location.pathname+location.search);return}if(v.type==="attach_failed"&&typeof v.message=="string"){He=!0,I="dead",i.reset(),i.write(`\r
4
+ \x1B[31m`+Qe(v.message)+`\x1B[0m\r
5
+ `).then(()=>{kt();try{s?.close()}catch{}});return}if(v.type==="auth.ok"){v.token&&localStorage.setItem("tmux-web-token",v.token),j=1e3,Te(),pe({type:"resize",cols:i.cols,rows:i.rows}),Q();return}if(v.type==="auth.failed"){if(v.permanentLock||v.retryAfterMs&&v.retryAfterMs>6e4){localStorage.removeItem("tmux-web-token"),location.href="/login?error="+encodeURIComponent(v.message);return}return}if(v.type==="snapshot"&&typeof v.data=="string"){let S=en(Qe(v.data));E=[S],A="",M=typeof v.lines=="number"?v.lines:n.terminal.initialLines,I="live",i.reset(),Te(),pe({type:"resize",cols:i.cols,rows:i.rows}),i.write(S).then(()=>i.scrollToBottom());return}if(v.type==="window_changed"&&typeof v.activeIndex=="number"){let S=new URL(location.href);S.searchParams.get("window")!==String(v.activeIndex)&&(S.searchParams.set("window",String(v.activeIndex)),history.replaceState(history.state,"",S)),window.dispatchEvent(new CustomEvent("tmux:windows",{detail:v.windows}));return}if(v.type==="history"&&typeof v.data=="string"){v.lines>0&&v.data?(E.unshift(en(v.data)),M+=v.lines,ee(!0,v.lines).finally(()=>{$=!1})):$=!1;return}if(v.type==="data"&&typeof v.data=="string"){let S=en(Qe(v.data));if(I==="connecting"){I="live",A=S,i.write(S);return}I==="live"&&(A+=S,i.write(S))}}let He=!1;function Nn(){if(He)return;let p=G,v=localStorage.getItem("tmux-web-token");v&&(p+=(p.includes("?")?"&":"?")+"token="+encodeURIComponent(v)),p+=(p.includes("?")?"&":"?")+"cols="+i.cols+"&rows="+i.rows,s=new WebSocket(p),s.onopen=()=>{I="connecting",M=0,$=!1,E=[],A="",i.reset(),j=1e3},s.onmessage=S=>{typeof S.data=="string"&&Le(S.data)},s.onclose=()=>{L||(I="connecting",!He&&setTimeout(()=>{j=Math.min(j*2,1e4),!L&&!He&&Nn()},j))},s.onerror=()=>s?.close()}function _e(p){pe({type:"input",data:p})}function Te(){return i.fit()}function kt(){t.classList.remove("terminal-pending")}function Q(){l&&cancelAnimationFrame(l),r&&clearTimeout(r),Te(),l=requestAnimationFrame(()=>{l=0,Te()&&kt()}),r=setTimeout(()=>{Te()&&kt()},120)}function ds(){Q(),setTimeout(Q,50),setTimeout(Q,150),setTimeout(Q,300)}function On(p){return typeof p=="string"&&p.startsWith("image/")}function qn(p){return p?.files?.length?p.files[0]??null:null}function ps(p){if(!p?.items)return null;for(let v=0;v<p.items.length;v++){let S=p.items[v];if(S?.kind==="file"&&On(S.type))return S.getAsFile()}return null}async function us(p){let v=new FormData,S=p instanceof File&&p.name?p.name:"upload";v.append("file",p,S);let z=localStorage.getItem("tmux-web-token"),N={};z&&(N.Authorization="Bearer "+z);let ue=await fetch(K,{method:"POST",body:v,headers:N});if(!ue.ok){let Yn="upload failed";try{let Xn=await ue.json();Xn.error&&(Yn=Xn.error)}catch{}throw new Error(Yn)}let ye=await ue.json();if(!ye.path)throw new Error("no path in response");return ye.path}async function Kt(p){try{let v=await us(p);_e(v)}catch{}}i.onData(p=>_e(p)),i.onResize(({cols:p,rows:v})=>pe({type:"resize",cols:p,rows:v})),i.onScroll(()=>{I!=="live"||$||!i.isNearScrollbackTop()||($=!0,pe({type:"load_history",before:M}))});let Je=!1,Ze=!1,W=null,J=null,Ye=document.createElement("div");Ye.className="terminal-copy-banner",Ye.innerHTML='<strong>Copy mode</strong><span class="hint">drag to copy \xB7 Esc exits</span>',Ye.hidden=!0,t.appendChild(Ye);let ge=document.createElement("div");ge.className="terminal-copy-banner terminal-copy-toast",ge.textContent="Copied",ge.hidden=!0,t.appendChild(ge);function jn(p,v){let S=t.querySelector(".xterm-screen, canvas"),z=(S&&S.getBoundingClientRect().width>0?S:t).getBoundingClientRect(),N=z.height>0&&i.rows>0?z.height/i.rows:18,ue=z.width>0&&i.cols>0?z.width/i.cols:9;return{row:Math.max(0,Math.min(i.rows-1,Math.floor((v-z.top)/N))),col:Math.max(0,Math.min(i.cols-1,Math.floor((p-z.left)/ue)))}}async function wt(p){if(!p)return;try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(p);return}}catch{}let v=document.createElement("textarea");v.value=p,v.style.position="fixed",v.style.opacity="0",v.style.pointerEvents="none",document.body.appendChild(v),v.focus(),v.select();try{document.execCommand("copy")}catch{}v.remove()}let Xe;function yt(){ge.hidden=!1,Xe&&clearTimeout(Xe),Xe=setTimeout(()=>{ge.hidden=!0},1e3)}function Fe(p){Je=p,Ye.hidden=!p,t.classList.toggle("terminal-copy-mode-active",p),p&&i.focus()}function Vn(){Fe(!Je)}function hs(p){L||p.button!==0||Ze||(Je||p.shiftKey)&&(p.preventDefault(),p.stopPropagation(),Ze=!0,W=jn(p.clientX,p.clientY),J=W,i.selectCells(W.col,W.row,J.col,J.row),document.addEventListener("mousemove",Qt,!0),document.addEventListener("mouseup",Gt,!0))}function Qt(p){L||!Ze||!W||(p.preventDefault(),p.stopPropagation(),J=jn(p.clientX,p.clientY),i.selectCells(W.col,W.row,J.col,J.row))}function Gt(p){if(L||!Ze||!W||!J)return;p.preventDefault(),p.stopPropagation(),document.removeEventListener("mousemove",Qt,!0),document.removeEventListener("mouseup",Gt,!0),Ze=!1;let v=i.getCellsText(W.col,W.row,J.col,J.row);W=null,J=null,i.clearSelection(),Fe(!1),v&&(ge.textContent="\u5DF2\u590D\u5236",wt(v).then(yt)),i.focus()}t.addEventListener("mousedown",hs,!0),document.addEventListener("keydown",ms,!0);function ms(p){if(!(L||!i.isFocused()||p.defaultPrevented||p.isComposing)){if(Je){if(p.key==="Escape"){p.preventDefault(),p.stopPropagation(),W=null,J=null,i.clearSelection(),Fe(!1);return}if(p.key==="Enter"||(p.ctrlKey||p.metaKey)&&p.code==="KeyC"){p.preventDefault(),p.stopPropagation(),wt(i.getScreenText()).then(yt),Fe(!1);return}}if(p.altKey&&p.code==="KeyC"&&!p.ctrlKey&&!p.metaKey){if(p.preventDefault(),p.stopPropagation(),W&&J){let v=i.getCellsText(W.col,W.row,J.col,J.row);W=null,J=null,i.clearSelection(),Fe(!1),v&&(ge.textContent="Copied",wt(v).then(yt))}else{let v=i.getSelection();v?(i.clearSelection(),ge.textContent="Copied",wt(v).then(yt)):Vn()}return}if((p.ctrlKey||p.metaKey)&&p.code==="KeyV"){p.preventDefault(),p.stopPropagation(),(async()=>{try{if(navigator.clipboard?.read){let v=await navigator.clipboard.read();for(let S of v)for(let z of S.types)if(On(z)){let N=await S.getType(z);await Kt(N);return}}}catch{}try{let v=await navigator.clipboard?.readText();v&&i.pasteText(Wn(v))}catch{}})();return}}}let xt=0;function Wn(p){return p.split(`\r
6
6
  `).join(`
7
7
  `).split(`
8
- `).join("\r")}async function Un(s){let d=On(s.clipboardData);if(d){s.preventDefault(),s.stopPropagation();let I=Date.now();if(I-We<50)return;We=I,await ht(d);return}let h=s.clipboardData?.getData("text/plain");if(!h)return;s.preventDefault(),s.stopPropagation();let E=Date.now();E-We<50||(We=E,i.pasteText(Rt(h)))}let Se=0;function Wn(s){s.preventDefault(),Se++,Vt(s.dataTransfer)&&e.classList.add("terminal-drag-over")}function qn(s){s.preventDefault(),s.dataTransfer&&(s.dataTransfer.dropEffect="copy")}function Jn(s){s.preventDefault(),Se--,Se<=0&&(Se=0,e.classList.remove("terminal-drag-over"))}async function Yn(s){s.preventDefault(),Se=0,e.classList.remove("terminal-drag-over");let d=Vt(s.dataTransfer);d&&await ht(d)}function _t(s){!Fn||s.key!=="Escape"||ke||s.defaultPrevented||s.repeat||s.metaKey||s.ctrlKey||s.altKey||i.isFocused()&&(s.preventDefault(),s.stopPropagation(),fe("\x1B"))}e.addEventListener("paste",Un),e.addEventListener("dragenter",Wn),e.addEventListener("dragover",qn),e.addEventListener("dragleave",Jn),e.addEventListener("drop",Yn),document.addEventListener("keydown",_t,!0);function Kn(s){if(s.touches.length!==1){l=null;return}let d=s.touches[0];if(!d)return;P();let h=e.getBoundingClientRect(),E=d.clientX-h.left<h.width*.4?"tui":"history",I=d.clientY-h.top<h.height*.5;l={startX:d.clientX,startY:d.clientY,lastX:d.clientX,lastY:d.clientY,lastT:performance.now(),velocity:0,scrolling:!1,zone:E,tuiUp:I,sent:!1},s.stopPropagation()}function Xn(s){if(!l||s.touches.length!==1)return;let d=s.touches[0];if(!d)return;let h=d.clientY-l.startY,E=d.clientX-l.startX;if(!l.scrolling){if(Math.abs(h)<8||Math.abs(h)<Math.abs(E))return;l.scrolling=!0,R=Date.now()+500}s.preventDefault(),s.stopPropagation();let I=performance.now(),ee=d.clientY-l.lastY;if(l.zone==="tui"){l.sent||(l.sent=!0,fe(l.tuiUp?"\x1B[5~":"\x1B[6~"),M(l.tuiUp)),l.lastX=d.clientX,l.lastY=d.clientY,l.lastT=I;return}let se=I-l.lastT;se>0&&(l.velocity=ee/se),ei(-ee),l.lastX=d.clientX,l.lastY=d.clientY,l.lastT=I}function Qn(s){if(!l)return;let d=l.scrolling,h=l.zone,E=l.tuiUp,I=l.velocity;if(l=null,s.stopPropagation(),h==="tui"){d||(fe(E?"\x1B[5~":"\x1B[6~"),M(E),R=Date.now()+500,s.preventDefault());return}if(!d){i.focus();return}R=Date.now()+500,s.preventDefault(),I&&j(I)}function Zn(s){l=null,P(),s.stopPropagation()}function Gn(s){s.pointerType==="touch"&&Date.now()<R&&(s.preventDefault(),s.stopPropagation())}function ei(s){let d=i.cellHeight(),h=d>0?Math.round(s/d):s>0?1:-1;h===0&&(h=s>0?1:-1),i.scrollLines(h)}e.addEventListener("touchstart",Kn,{passive:!0,capture:!0}),e.addEventListener("touchmove",Xn,{passive:!1,capture:!0}),e.addEventListener("touchend",Qn,{passive:!1,capture:!0}),e.addEventListener("touchcancel",Zn,{passive:!0,capture:!0}),e.addEventListener("pointerup",Gn,!0);function Ut(){U()}window.addEventListener("resize",Ut),window.visualViewport?.addEventListener("resize",U),window.visualViewport?.addEventListener("scroll",U);let Wt=new ResizeObserver(()=>U());Wt.observe(e),document.fonts?.ready.then(()=>{U(),setTimeout(U,50),setTimeout(U,200)}),e.addEventListener("focusin",Vn,!0);async function ti(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(s=>setTimeout(s,1e3))])}catch{}}return requestAnimationFrame(()=>{de()&&Re(),(async()=>(await ti(),de()&&re({type:"resize",cols:i.cols,rows:i.rows}),Pt(),U()))()}),{destroy(){if(B=!0,P(),ge(!1),xe&&clearTimeout(xe),document.removeEventListener("mousemove",vt,!0),document.removeEventListener("mouseup",ft,!0),a){try{a.close(1e3,"session switch")}catch{}a=void 0}e.innerHTML="",e.classList.remove("terminal-pending"),window.removeEventListener("resize",Ut),Wt.disconnect(),document.removeEventListener("keydown",_t,!0)},focus(){i.focus()},sendInput(s){fe(s)},toggleCopyMode(){jt()}}})()}var Yt={menu:"M3 6h18v2H3V6zm0 5h18v2H3v-2zm0 5h18v2H3v-2z",close:"M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7a1 1 0 1 0-1.41 1.41L10.59 12l-4.89 4.89a1 1 0 1 0 1.41 1.41L12 13.41l4.89 4.89a1 1 0 1 0 1.41-1.41L13.41 12l4.89-4.89a1 1 0 0 0 0-1.4z",search:"M15.5 14h-.79l-.28-.27A6.47 6.47 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z",refresh:"M17.65 6.35A7.96 7.96 0 0 0 12 4a8 8 0 1 0 8 8h-2a6 6 0 1 1-6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z",add:"M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z",edit:"M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM5.92 19H5v-.92l9.06-9.06.92.92L5.92 19zm13.66-12.83a1 1 0 0 0 0-1.41l-1.34-1.34a1 1 0 0 0-1.41 0l-1.05 1.05 2.75 2.75 1.05-1.05z",delete:"M15 4V3H9v1H4v2h1.5l.81 13.05A2 2 0 0 0 8.3 21h7.4a2 2 0 0 0 1.99-1.95L18.5 6H20V4h-5zm-5.5 2h5l-.75 12h-3.5L9.5 6z",check:"M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z",sessions:"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z",notes:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6zm-1 2 5 5h-5V4zM6 20V4h5v7h7v9H6z",schedule:"M19 4h-1V2h-2v2H8V2H6v2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 16H5V10h14v10zM9 14H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2zm-8 4H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2z",agents:"M12 2a5 5 0 1 0 0 10 5 5 0 0 0 0-10zm0 8a3 3 0 1 1 0-6 3 3 0 0 1 0 6zm-7 13v-2a5 5 0 0 1 5-5h4a5 5 0 0 1 5 5v2h2v-2a7 7 0 0 0-7-7H10a7 7 0 0 0-7 7v2h2z",history:"M13 3a9 9 0 0 0-9 9H1l4 4 4-4H6a7 7 0 1 1 7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.96 8.96 0 0 0 13 21a9 9 0 0 0 0-18zm-1 5v5l4.25 2.55.75-1.23-3.5-2.08V8H12z","quick-commands":"M13 3 4 14h7l-1 7 9-11h-7l1-7z",windows:"M4 6h16v2H4V6zm0 5h10v2H4v-2zm0 5h16v2H4v-2z",terminal:"M4 17.6 6.4 20l8-8-8-8L4 6.4 11.6 12 4 17.6zM20 18h-8v2h8v-2z",microphone:"M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5-3c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z",keyboard:"M20 5H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-9 3h2v2h-2V8zm0 3h2v2h-2v-2zM8 8h2v2H8V8zm0 3h2v2H8v-2zm-1 2H5v-2h2v2zm0-3H5V8h2v2zm9 7H8v-2h8v2zm0-4h-2v-2h2v2zm0-3h-2V8h2v2zm3 3h-2v-2h2v2zm0-3h-2V8h2v2z",bot:"M11 2h2v3h2a3 3 0 0 1 3 3v1h1a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-1v1a3 3 0 0 1-3 3H9a3 3 0 0 1-3-3v-1H5a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2h1V8a3 3 0 0 1 3-3h2V2zm-2 6v1h6V8H9zm-2 5a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3zm10 0a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3z",layers:"M12 2 2 7l10 5 10-5-10-5zm0 7.5L4.5 5.8 12 2l7.5 3.8L12 9.5zM2 12l10 5 10-5-1.9-.95L12 14.9l-8.1-3.85L2 12zm0 4.5 10 5 10-5-1.9-.95L12 19.4l-8.1-3.85-1.9.95z",inbox:"M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2zm0 16H5v-3h3.6a3.5 3.5 0 0 0 6.8 0H19v3zm0-5h-4.7a3.5 3.5 0 0 1-6.6 0H5V5h14v9z","chevron-down":"M7.4 8.6 12 13.2l4.6-4.6L18 10l-6 6-6-6 1.4-1.4z",settings:"M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.488.488 0 0 0-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.484.484 0 0 0-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6a3.6 3.6 0 1 1 0-7.2 3.6 3.6 0 0 1 0 7.2z",pin:"M16 12V4h1V2H7v2h1v8l-4 4v2h5.2v6h1.6v-6H20v-2l-4-4z","pin-outline":"M16 12V4h1V2H7v2h1v8l-4 4v2h5.2v6h1.6v-6H20v-2l-4-4zm-4.8 7.2V11l2-2V4h1.6v5l2 2v5.2H11.2z",folder:"M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z",file:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6zm-1 2 5 5h-5V4zM6 20V4h5v7h7v9H6z",worktree:"M6 3a3 3 0 0 0-1 5.83v6.34a3 3 0 1 0 2 0V8.83A3 3 0 0 0 6 3zm0 2a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm0 12a1 1 0 1 1 0 2 1 1 0 0 1 0-2zM18 3a3 3 0 0 0-1 5.83V9a4 4 0 0 1-4 4h-2a3 3 0 1 0 0 2h2a6 6 0 0 0 6-6v-.17A3 3 0 0 0 18 3zm0 2a1 1 0 1 1 0 2 1 1 0 0 1 0-2zM9 13a1 1 0 1 1 0 2 1 1 0 0 1 0-2z",copy:"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z",export:"M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z",chevronRight:"M9.29 6.71a1 1 0 0 0 0 1.41L13.17 12l-3.88 3.88a1 1 0 1 0 1.41 1.41l4.59-4.59a1 1 0 0 0 0-1.41L10.7 6.7a1 1 0 0 0-1.41.01z",lightning:"M11 21h-1l1-7H7.5c-.58 0-.57-.32-.38-.66.19-.33.51-.89.73-1.27L13 3h1l-1 7h3.5c.49 0 .56.33.47.51l-.07.15c-.22.46-.58 1.18-.78 1.58L11 21z","git-branch":"M13.5 7a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0zm0 10a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0zM11 9.5v5.1a4.03 4.03 0 0 0-3-.1V9.4a4.03 4.03 0 0 0 3 .1z",external:"M14 3h7v7h-2V6l-9.29 9.29-1.41-1.41L17.59 4.5H14V3zm4 16H5V5h7V3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7h-2v7z",play:"M8 5v14l11-7L8 5z",stop:"M6 6h12v12H6V6z",warning:"M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z",info:"M11 7h2v2h-2V7zm0 4h2v6h-2v-6zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z",spinner:"M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46A7.93 7.93 0 0 0 20 12c0-4.42-3.58-8-8-8z",dots:"M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"};function di(e){return Yt[e]??Yt.menu}function ce(e,t=""){return`<svg viewBox="0 0 24 24" fill="currentColor"${t?" "+t:""}><path d="${di(e)}"/></svg>`}var m={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function yt(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function T(e,t){let n=await fetch(e,{...t,headers:{"content-type":"application/json",Authorization:`Bearer ${yt()}`,...t?.headers||{}}}),i=await n.text(),a=i?JSON.parse(i):null;if(!n.ok)throw new Error(a&&a.error||`HTTP ${n.status}`);return a}function c(e,t,n){let i=document.createElement(e);return t&&(i.className=t),n!==void 0&&(i.textContent=n),i}function ci(e){return e==="running"?"var(--panel-success)":e==="waiting_approval"||e==="waiting_input"?"#e0a23c":e==="failed"?"var(--panel-danger, #e5534b)":e==="completed"?"var(--panel-accent)":"var(--panel-muted)"}function ye(){let e=document.getElementById("bots-view");if(!e)return;let t=window.visualViewport,n=window.matchMedia("(max-width: 640px)").matches,i=!document.querySelector(".sidebar")?.classList.contains("collapsed");if(m.activeId&&t&&n&&!i){let a=document.querySelector(".fixed-header"),r=a?Math.round(a.getBoundingClientRect().height):0;e.style.position="fixed",e.style.top=`${Math.round(t.offsetTop)+r}px`,e.style.left=`${Math.round(t.offsetLeft)}px`,e.style.width=`${Math.round(t.width)}px`,e.style.height=`${Math.max(120,Math.round(t.height)-r)}px`,e.style.right="auto",e.style.bottom="auto"}else e.style.position="",e.style.top="",e.style.left="",e.style.width="",e.style.height="",e.style.right="",e.style.bottom=""}window.visualViewport?.addEventListener("resize",ye),window.visualViewport?.addEventListener("scroll",ye),window.addEventListener("resize",ye),document.addEventListener("click",()=>setTimeout(ye,0));function Je(){let e=m.approvals.length,t=document.getElementById("bots-inbox-badge");t&&(t.style.display=e?"inline-block":"none",t.textContent=String(e));let n=document.getElementById("bv-inbox-count");n&&(n.textContent=e?`(${e})`:""),window.__botsSnapshot=m.bots,window.__refreshSidebar?.()}function ui(){let e=document.getElementById("set-bot-templates"),t=document.getElementById("set-bot-new"),n=document.getElementById("set-bot-inbox"),i=()=>{document.getElementById("settings-popover")?.classList.remove("open"),document.getElementById("settings-backdrop")?.classList.remove("open")};e?.addEventListener("click",()=>{i(),Ie()}),t?.addEventListener("click",()=>{i(),ki()}),n?.addEventListener("click",()=>{i(),xt()})}function pi(){let e=c("div","bots-view");e.id="bots-view",e.hidden=!0;let t=c("div","bots-view-head"),n=c("div","bv-title"),i=c("span","bots-dot");i.id="bv-dot";let a=c("span","bv-title-text");a.id="bv-title";let r=c("span","bv-status");r.id="bv-status",n.append(i,a,r);let o=c("div","bv-actions"),l=c("div","bv-mode"),u=c("button","bv-mode-btn");u.id="bv-mode-btn",u.type="button",u.title="\u5BA1\u6279\u6A21\u5F0F\uFF08\u70B9\u5F00\u770B\u8BF4\u660E\uFF09",u.innerHTML=`<span id="bv-mode-label"></span>${ce("chevron-down",'width="12" height="12"')}`;let p=c("div","bv-mode-menu");p.id="bv-mode-menu",p.hidden=!0;for(let[b,x,G]of[["supervised","\u9ED8\u8BA4","\u53EA\u8BFB\u5DE5\u5177\uFF08read/grep/find/ls\uFF09\u76F4\u63A5\u653E\u884C\uFF1Bbash\u3001edit\u3001write\u3001\u6269\u5C55/MCP \u5DE5\u5177\u4F1A\u95EE\u4F60"],["parent-supervised","\u76D1\u7BA1","\u5176\u4F59\u5DE5\u5177\u4EA4\u7ED9\u4E0A\u7EA7 bot \u51B3\u5B9A\uFF08\u5E26\u7406\u7531\uFF09\uFF1B\u4F60\u4ECD\u7136\u80FD\u770B\u5230\u5E76\u56DE\u7B54\uFF0C\u5148\u7B54\u5148\u5F97\uFF1B\u6CA1\u6709\u4E0A\u7EA7\u65F6\u56DE\u843D\u5230\u9ED8\u8BA4"],["full-access","\u5168\u653E\u884C","\u6240\u6709\u5DE5\u5177\u76F4\u63A5\u6267\u884C\uFF0C\u4E0D\u518D\u8BE2\u95EE\u3002\u6CE8\u610F\u8FD9\u4E0D\u662F\u6C99\u7BB1"]]){let v=c("button");v.dataset.mode=b,v.innerHTML=`<b>${x}</b><span>${G}</span>`,v.onclick=()=>{p.hidden=!0,mi(b)},p.appendChild(v)}u.onclick=b=>{b.stopPropagation(),p.hidden=!p.hidden},l.append(u,p),document.addEventListener("click",b=>{l.contains(b.target)||(p.hidden=!0)});let f=c("button","btn","Allow all");f.id="bv-allow-all",f.title="Approve every pending request for this bot",f.onclick=()=>{if(!m.activeId)return;let b=m.approvals.filter(x=>x.botId===m.activeId);Promise.all(b.map(x=>T(`/api/bots/${x.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:x.id,allow:!0})}))).finally(()=>void Y(!0))};let y=c("button","btn","Needs you "),H=c("span");H.id="bv-inbox-count",y.appendChild(H),y.onclick=()=>void xt();let L=c("button","btn","Resume");L.onclick=()=>void Xt(b=>T(`/api/bots/${b}/resume`,{method:"POST"}).then(()=>Y(!0)));let w=c("button","btn danger","Stop");w.onclick=()=>void Xt(b=>T(`/api/bots/${b}/stop`,{method:"POST"}).then(()=>Y(!0)));let g=c("button","btn","Delete");g.onclick=()=>{m.activeId&&confirm("Delete this bot and its session?")&&T(`/api/bots/${m.activeId}`,{method:"DELETE"}).then(()=>{bt(),Y(!0)})};let M=c("button","btn");M.innerHTML=ce("close",'width="14" height="14"'),M.title="Close bot view",M.onclick=()=>bt(),o.append(l,f,y,L,w,g,M),t.append(n,o);let W=c("div","bots-messages");W.id="bots-messages";let P=c("div","bots-composer"),j=c("textarea");j.id="bots-input",j.rows=1,j.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",j.onkeydown=b=>{b.key==="Enter"&&!b.shiftKey&&(b.preventDefault(),Kt())};let R=c("button","btn primary");R.title="Send",R.setAttribute("aria-label","Send"),R.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V5M5 12l7-7 7 7"/></svg>',R.onclick=()=>void Kt(),P.append(j,R),e.append(t,W,P),document.querySelector(".main-area")?.appendChild(e),document.getElementById("bots-modal")||wi()}async function Kt(){let e=document.getElementById("bots-input");if(!e||!m.activeId||!e.value.trim())return;let t=e.value;e.value="";try{await T(`/api/bots/${m.activeId}/input`,{method:"POST",body:JSON.stringify({text:t})})}catch(n){ue({kind:"notice",level:"error",text:n instanceof Error?n.message:String(n)})}}function Xt(e){m.activeId&&e(m.activeId).catch(t=>ue({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)}))}function bt(){m.activeId=null,ye();let e=document.getElementById("bots-view");e&&(e.hidden=!0);try{m.ws?.close()}catch{}m.ws=null,Je();let t=document.getElementById("terminal-container"),n=document.getElementById("main-placeholder"),i=!!document.querySelector(".session-item.active:not(.bot-item)");t&&i?(t.style.display="",n&&(n.style.display="none")):n&&(n.style.display="")}async function Qt(e){m.activeId=e,window.__collapseSidebar?.(),ye(),m.items.set(e,[]);let t=document.getElementById("bots-view");t&&(t.hidden=!1);let n=document.getElementById("main-placeholder");n&&(n.style.display="none");let i=document.getElementById("terminal-container");i&&(i.style.display="none");let a=document.getElementById("file-editor");a&&(a.style.display="none"),Je(),kt();try{m.ws?.close()}catch{}let r=location.protocol==="https:"?"wss:":"ws:",o=new WebSocket(`${r}//${location.host}/ws/bots/${encodeURIComponent(e)}?token=${encodeURIComponent(yt())}`);m.ws=o,o.onmessage=l=>{try{Gt(JSON.parse(String(l.data)))}catch{}},o.onclose=()=>{m.activeId===e&&setTimeout(()=>{m.activeId===e&&Y(!0)},1500)},await Y(!0)}function wt(){return m.bots.find(e=>e.id===m.activeId)||null}function Et(){let e=wt();if(!e)return;let t=document.getElementById("bv-title"),n=document.getElementById("bv-status"),i=document.getElementById("bv-dot");t&&(t.textContent=e.title),n&&(n.textContent=`${e.status.replace(/_/g," ")} \xB7 ${e.templateId} \xB7 ${e.projectPath}`);let a=document.getElementById("bv-mode-label");a&&e.runtimeMode&&(a.textContent=Zt[e.runtimeMode]||e.runtimeMode);for(let l of document.querySelectorAll("#bv-mode-menu button"))l.classList.toggle("active",l.dataset.mode===e.runtimeMode);let r=document.getElementById("bv-allow-all"),o=m.approvals.filter(l=>l.botId===e.id).length;r&&(r.hidden=o===0,r.textContent=`Allow all (${o})`),i&&(i.style.background=ci(e.status))}var Zt={supervised:"\u9ED8\u8BA4","parent-supervised":"\u76D1\u7BA1","full-access":"\u5168\u653E\u884C"};async function mi(e){if(m.activeId)try{await T(`/api/bots/${m.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:e})});let t=wt();t&&(t.runtimeMode=e),Et(),ue({kind:"notice",level:"info",text:`\u5BA1\u6279\u6A21\u5F0F\uFF1A${Zt[e]||e}`})}catch(t){ue({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)})}}function ue(e,t=m.activeId){if(!t)return;let n=m.items.get(t)||[];n.push(e),m.items.set(t,n),t===m.activeId&&pe()}function pe(){m.renderQueued||(m.renderQueued=!0,requestAnimationFrame(()=>{m.renderQueued=!1,kt()}))}function kt(){let e=document.getElementById("bots-messages");if(!e||!m.activeId)return;let t=m.items.get(m.activeId)||[];e.textContent="";let n=null;for(let i of t)if(i.kind==="user"){let a=c("div","bv-msg bv-user");a.textContent=i.text,e.appendChild(a),n=null}else if(i.kind==="assistant"){let a=c("div","bv-msg bv-assistant");if(i.thinking){let o=c("details","bv-thinking");o.appendChild(c("summary",void 0,"thinking")),o.appendChild(c("div",void 0,i.thinking)),a.appendChild(o)}let r=c("div","bv-text");r.textContent=i.text,a.appendChild(r),e.appendChild(a),n=r}else if(i.kind==="tool")e.appendChild(hi(i)),n=null;else if(i.kind==="approval")e.appendChild(vi(i)),n=null;else if(i.kind==="notice"){let a=c("div",`bv-notice bv-notice-${i.level}`,i.text);e.appendChild(a)}n&&(n.scrollTop=n.scrollHeight),e.scrollTop=e.scrollHeight}function hi(e){let t=c("details","bv-tool");t.open=e.phase!=="end"||!!e.isError;let n=c("summary"),i=c("span","bv-tool-name",e.name);if(n.appendChild(i),e.phase!=="end"&&n.appendChild(c("span","bv-tool-phase",e.phase)),e.isError&&n.appendChild(c("span","bv-tool-error","error")),typeof e.durationMs=="number"&&n.appendChild(c("span","bv-tool-meta",`${Math.round(e.durationMs)}ms`)),t.appendChild(n),e.args!==void 0){let a=c("pre","bv-pre");a.textContent=typeof e.args=="string"?e.args:JSON.stringify(e.args,null,2),t.appendChild(a)}if(e.output){let a=c("pre","bv-pre bv-output");a.textContent=e.output,t.appendChild(a)}return t}function vi(e){let t=c("div","bv-approval"),n=e.approval;if(t.appendChild(c("div","bv-approval-title",n.title)),n.message&&t.appendChild(c("pre","bv-pre",n.message)),e.decided)return t.appendChild(c("div","bv-approval-decided",e.decided==="allowed"?"Allowed":"Denied")),t;let i=c("input","bv-reason");i.placeholder="reason (optional)";let a=c("div","bv-approval-actions"),r=c("button","btn primary","Allow"),o=c("button","btn",n.method==="confirm"&&/^Allow (.+?)\?$/.test(n.title)?`Always allow ${/^Allow (.+?)\?$/.exec(n.title)?.[1]}`:"Always allow");o.hidden=n.method!=="confirm";let l=c("button","btn danger","Deny"),u=async(p,f=!1)=>{try{await T(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:p,always:f,reason:i.value||void 0})}),e.decided=p?"allowed":"denied",pe(),Y(!0)}catch(y){ue({kind:"notice",level:"error",text:y instanceof Error?y.message:String(y)})}};return r.onclick=()=>void u(!0),o.onclick=()=>void u(!0,!0),l.onclick=()=>void u(!1),a.append(i,r,o,l),t.appendChild(a),t}function Gt(e){let t=String(e.type||""),n=m.activeId;if(!n)return;let i=m.items.get(n)||[];if(t==="snapshot")m.items.set(n,[]);else if(t==="user")ue({kind:"user",text:String(e.text||"")});else if(t==="status"){let a=wt();a&&(a.status=String(e.status||a.status)),Et(),yi()}else if(t==="message"){let a=e.message;if(!a||String(a.role||"")!=="assistant")return;let r=fi(a),o=gi(a),l=i[i.length-1];l&&l.kind==="assistant"?(l.text=r||l.text,l.thinking=o||l.thinking):i.push({kind:"assistant",text:r,thinking:o}),m.items.set(n,i),pe()}else if(t==="delta"){let a=String(e.kind||""),r=String(e.delta||""),o=i[i.length-1];(!o||o.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),o=i[i.length-1]),o.kind==="assistant"&&(a==="text"?o.text+=r:a==="thinking"&&(o.thinking+=r)),m.items.set(n,i),pe()}else if(t==="tool"){let a=String(e.callId||""),r=i.find(l=>l.kind==="tool"&&l.callId===a),o=String(e.phase||"start");r?(r.phase=o,o==="update"&&e.output&&(r.output=String(e.output)),o==="end"&&(e.output&&(r.output=String(e.output)),r.isError=e.isError===!0,typeof e.durationMs=="number"&&(r.durationMs=e.durationMs))):i.push({kind:"tool",callId:a,name:String(e.name||"tool"),args:e.args,output:e.output?String(e.output):void 0,isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,phase:o}),m.items.set(n,i),pe()}else if(t==="approval"){let a=e.approval;if(!a)return;let r=i;for(let o=r.length-1;o>=0;o--){let l=r[o];if(l.kind==="approval"&&l.approval.id===a.id){l.approval=a,a.state!=="pending"&&(l.decided=a.state==="allowed"?"allowed":"denied"),m.items.set(n,r),pe();return}}r.push({kind:"approval",approval:a}),m.items.set(n,r),pe()}else t==="notice"&&ue({kind:"notice",level:String(e.level||"info"),text:String(e.text||"")})}function fi(e){let t=e.content;return Array.isArray(t)?t.map(n=>n&&typeof n=="object"&&n.type==="text"?String(n.text||""):"").join(""):String(e.text||"")}function gi(e){let t=e.content;return Array.isArray(t)?t.map(n=>n&&typeof n=="object"&&n.type==="thinking"?String(n.thinking||""):"").join(""):""}async function Y(e=!1){try{let[t,n]=await Promise.all([T("/api/bots"),T("/api/bots/approvals")]);if(m.bots=t,m.approvals=n,Je(),Et(),e&&m.activeId){let i=await T(`/api/bots/${m.activeId}/events?limit=300`);bi(i)}}catch{}}async function yi(){try{m.bots=await T("/api/bots"),Je()}catch{}}function bi(e){if(m.activeId){m.items.set(m.activeId,[]);for(let t of e)Gt(t);kt()}}function wi(){let e=c("div","bots-modal");e.id="bots-modal",e.hidden=!0;let t=c("div","bots-modal-card"),n=c("div","bots-modal-head"),i=c("span");i.id="bots-modal-title";let a=c("button","btn");a.innerHTML=ce("close",'width="14" height="14"'),a.title="Close",a.onclick=()=>Ye(),n.append(i,a);let r=c("div","bots-modal-body");r.id="bots-modal-body",t.append(n,r),e.appendChild(t),e.onclick=o=>{o.target===e&&Ye()},document.body.appendChild(e)}function Ct(e){let t=document.getElementById("bots-modal"),n=document.getElementById("bots-modal-title"),i=document.getElementById("bots-modal-body");if(!t||!i)throw new Error("modal missing");return n&&(n.textContent=e),i.textContent="",t.hidden=!1,i}function Ye(){let e=document.getElementById("bots-modal");e&&(e.hidden=!0)}async function Ei(){return m.catalog||(m.catalog=await T("/api/bots/catalog")),m.catalog}async function en(){return m.templates=await T("/api/bots/templates"),m.templates}async function Ie(){let e=Ct("Bot templates"),[t,n]=await Promise.all([Ei(),en()]),i=c("div","bv-template-list");for(let u of n){let p=c("div","bv-template-row");p.appendChild(c("span","bv-template-name",u.manifest.name)),p.appendChild(c("span","bv-template-desc",u.manifest.description||""));let f=c("button","btn","Edit");f.onclick=()=>tn(e,t,u);let y=c("button","btn","Copy");y.title="Duplicate this template",y.onclick=()=>{let w=JSON.parse(JSON.stringify(u.manifest));w.name=`${u.manifest.name} copy`,T("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:w})}).then(()=>Ie()).catch(g=>alert(g instanceof Error?g.message:String(g)))};let H=c("button","btn danger","Delete");H.onclick=()=>{confirm(`Delete template ${u.manifest.name}?`)&&T(`/api/bots/templates/${u.id}`,{method:"DELETE"}).then(()=>Ie())};let L=c("span","bv-template-actions");L.append(f,y,H),p.appendChild(L),i.appendChild(p)}n.length===0&&i.appendChild(c("div","bots-empty","No templates yet")),e.appendChild(i);let a=c("div","bv-template-actions"),r=c("button","btn primary","New template");r.onclick=()=>tn(e,t,null);let o=c("button","btn","Export");o.title="Download templates + library as JSON",o.onclick=()=>{(async()=>{try{let u=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${yt()}`}});if(!u.ok)throw new Error(`HTTP ${u.status}`);let p=await u.blob(),f=document.createElement("a");f.href=URL.createObjectURL(p),f.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,f.click(),setTimeout(()=>URL.revokeObjectURL(f.href),2e3)}catch(u){alert(u instanceof Error?u.message:String(u))}})()};let l=c("button","btn","Import");l.title="Restore templates from a JSON bundle",l.onclick=()=>{let u=document.createElement("input");u.type="file",u.accept="application/json,.json",u.onchange=()=>{let p=u.files?.[0];p&&(async()=>{try{let f=JSON.parse(await p.text()),y=await T("/api/bots/import",{method:"POST",body:JSON.stringify(f)});alert(`Imported ${y.templates} templates, ${y.files} library files (${y.skipped} kept)`),await Ie()}catch(f){alert(f instanceof Error?f.message:String(f))}})()},u.click()},a.append(r,o,l),e.appendChild(a)}function Lt(e,t,n){let i=c("div","bv-field");i.appendChild(c("label","bv-label",e));let a=c("div","bv-check-grid"),r=[];for(let o of t){let l=c("label","bv-check"),u=document.createElement("input");u.type="checkbox",u.checked=n.includes(o.id),l.append(u,c("span",void 0,o.label)),o.hint&&(l.title=o.hint),a.appendChild(l),r.push({id:o.id,input:u})}return i.appendChild(a),{element:i,get:()=>r.filter(o=>o.input.checked).map(o=>o.id)}}function tn(e,t,n){e.textContent="";let i=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},a=c("input","bv-input");a.value=i.name,a.placeholder="Template name";let r=c("input","bv-input");r.value=i.description||"",r.placeholder="One line description";let o=c("textarea","bv-textarea");o.rows=6,o.value=i.system||"",o.placeholder="System prompt for this bot (written to SYSTEM.md)";let l=Lt("Skills",t.skills.map(v=>({id:v.id,label:v.name,hint:v.description})),i.skills||[]),u=Lt("Extensions (Pi builtins + library)",t.extensions.map(v=>({id:v.id,label:`${v.name}${v.kind==="builtin"?" (builtin)":""}`,hint:v.description})),(i.extensions||[]).map(v=>v.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),p=Lt("Prompt templates",t.prompts.map(v=>({id:v.id,label:v.name})),i.prompts||[]),f=c("select","bv-input");f.appendChild(new Option("none",""));for(let v of t.mcp)f.appendChild(new Option(v.name,v.id));i.mcp&&(f.value=t.mcp.find(v=>JSON.stringify(v.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");let y=c("div","bv-field");y.appendChild(c("label","bv-label","Tools (allow list; deny always blocks)"));let H=c("div","bv-check-grid"),L=[];for(let v of t.tools){let _=c("label","bv-check"),B=document.createElement("input");B.type="checkbox",B.checked=(i.tools?.allow||[]).includes(v.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(v.name),_.append(B,c("span",void 0,v.name)),H.appendChild(_),L.push({name:v.name,input:B})}y.appendChild(H);let w=c("input","bv-input");w.value=(i.tools?.deny||[]).join(", "),w.placeholder="Always deny (comma separated), e.g. bash, write";let g=c("textarea","bv-textarea");g.rows=2,g.value=(i.packages||[]).join(`
9
- `),g.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";let M=c("select","bv-input");M.appendChild(new Option("default (Pi settings)",""));for(let v of t.models)M.appendChild(new Option(`${v.provider}/${v.model}`,`${v.provider}
10
- ${v.model}`));i.model?.provider&&i.model?.id&&(M.value=`${i.model.provider}
11
- ${i.model.id}`);let W=c("select","bv-input");for(let v of["","off","minimal","low","medium","high","xhigh","max"])W.appendChild(new Option(v||"default",v));i.model?.thinking&&(W.value=i.model.thinking);let P=c("select","bv-input");for(let v of["supervised","auto-accept-edits","full-access"])P.appendChild(new Option(v,v));P.value=i.permissions?.runtimeMode||"supervised";let j=c("select","bv-input");j.appendChild(new Option("ignore project .pi (recommended)","ignore")),j.appendChild(new Option("inherit project .pi (needs trust)","inherit")),j.value=i.projectResources||"ignore";let R=c("label","bv-check"),b=document.createElement("input");b.type="checkbox",b.checked=!!i.orchestrator,R.append(b,c("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));let x=(v,_)=>{let B=c("div","bv-field");return B.appendChild(c("label","bv-label",v)),B.appendChild(_),B};e.append(x("Name",a),x("Description",r),x("System prompt",o),l.element,u.element,p.element,x("MCP preset",f),y,x("Always deny tools",w),x("Packages",g),x("Model",M),x("Thinking level",W),x("Approval mode",P),x("Project resources",j),R);let G=c("button","btn primary",n?"Save template":"Create template");G.onclick=async()=>{let[v,_]=M.value.split(`
12
- `),B=t.mcp.find(A=>A.id===f.value),le={name:a.value.trim()||"bot",description:r.value.trim()||void 0,system:o.value.trim()||void 0,skills:l.get(),extensions:u.get().map(A=>(A.startsWith("builtin:"),A)),prompts:p.get(),packages:g.value.split(`
13
- `).map(A=>A.trim()).filter(Boolean),mcp:B?{mcpServers:B.servers}:void 0,tools:{allow:L.filter(A=>A.input.checked).map(A=>A.name),deny:w.value.split(",").map(A=>A.trim()).filter(Boolean)},model:v?{provider:v,id:_,thinking:W.value||void 0}:void 0,permissions:{runtimeMode:P.value},projectResources:j.value==="inherit"?"inherit":"ignore",orchestrator:b.checked||void 0};try{await T("/api/bots/templates",{method:"POST",body:JSON.stringify({id:n?.id,manifest:le})}),Ye(),await Ie()}catch(A){alert(A instanceof Error?A.message:String(A))}},e.appendChild(G)}async function ki(){return nn("")}async function nn(e){let t=Ct("New bot"),n=await en();if(n.length===0){t.appendChild(c("div","bots-empty","No templates yet \u2014 create one with \u201CNew template\u201D."));return}let i=c("select","bv-input");for(let p of n)i.appendChild(new Option(p.manifest.name,p.id));let a=c("input","bv-input");a.placeholder="Title (defaults to template name)";let r=c("input","bv-input");r.placeholder="/path/to/project";let o=e||m.bots[0]?.projectPath||"";r.value=o;let l=c("select","bv-input");l.appendChild(new Option("shared \u2014 run in the project folder","shared")),l.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),t.append(Ke("Template",i),Ke("Title",a),Ke("Project path",r),Ke("Workspace",l));let u=c("button","btn primary","Create bot");u.onclick=async()=>{try{let p=await T("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:a.value.trim()||void 0,projectPath:r.value.trim()||void 0,isolation:l.value})});Ye(),await Y(!0),await Qt(p.id)}catch(p){alert(p instanceof Error?p.message:String(p))}},t.appendChild(u)}function Ke(e,t){let n=c("div","bv-field");return n.appendChild(c("label","bv-label",e)),n.appendChild(t),n}async function xt(){let e=Ct("Needs you");if(m.approvals=await T("/api/bots/approvals"),m.approvals.length===0){e.appendChild(c("div","bots-empty","Nothing waiting."));return}for(let t of m.approvals){let n=c("div","bv-approval");n.appendChild(c("div","bv-approval-title",`${t.botTitle}: ${t.title}`)),t.message&&n.appendChild(c("pre","bv-pre",t.message));let i=c("input","bv-reason");i.placeholder="reason (optional)";let a=c("div","bv-approval-actions"),r=c("button","btn primary","Allow"),o=c("button","btn danger","Deny"),l=async u=>{await T(`/api/bots/${t.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:t.id,allow:u,reason:i.value||void 0})}),await Y(!0),await xt()};r.onclick=()=>void l(!0),o.onclick=()=>void l(!1),a.append(i,r,o),n.appendChild(a),e.appendChild(n)}}function Ci(){window.__botsInited||(window.__botsInited=!0,pi(),ui(),window.__openBot=Qt,document.addEventListener("click",e=>{let t=e.target;t&&(t.closest(".session-item.bot-item")||t.closest(".session-item")&&m.activeId&&setTimeout(()=>bt(),0))},!0),Y(!0),m.pollTimer=window.setInterval(()=>{document.hidden||Y()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(m.pollTimer)))}var Be=window.__TMUX_WEB_SHELL__,S=null,z=null,Te=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null,V=Te;window.__tmuxWebScopeAgent=Te;var St="sessions",ie="",Xe="",Qe="",an="";function $(e){return V?"/a/"+encodeURIComponent(V)+e:e}var k=document.getElementById("sidebar-content"),me=document.getElementById("main-placeholder"),q=document.getElementById("terminal-container"),ze=document.getElementById("file-editor"),Li=document.getElementById("fe-path"),K=document.getElementById("fe-status"),He=document.getElementById("fe-content"),he=document.getElementById("fe-save"),xi=document.getElementById("fe-delete"),Si=document.getElementById("fe-back"),on=document.getElementById("fe-new-name"),Mi=document.getElementById("fe-new-btn"),Mt=document.getElementById("settings-backdrop"),sn=document.getElementById("settings-popover"),ln=document.querySelector(".sidebar"),rn="tmux-web-force-narrow";function Ze(){try{return localStorage.getItem(rn)==="1"}catch{return!1}}function dn(){document.documentElement.classList.toggle("force-narrow",Ze()),Ze()&&cn()&&De()}function cn(){return Ze()?!0:window.matchMedia("(max-width: 640px)").matches}function De(){cn()&&ln.classList.add("collapsed")}function un(){ln.classList.remove("collapsed")}window.__collapseSidebar=De,document.getElementById("mode-sessions").addEventListener("click",()=>{un(),pn("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{un(),pn("files")});function pn(e){St=e,document.querySelectorAll(".mode-btn").forEach(n=>n.classList.remove("active"));let t=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");t&&t.classList.add("active"),e==="sessions"?(It="",ae()):Ri()}var It="";async function ae(){if(St!=="sessions")return;try{let t=await(await fetch("/api/sidebar/sessions")).json(),n=(window.__botsSnapshot||[]).map(a=>[a.id,a.title,a.status,a.projectPath]),i=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones,bots:n});if(i===It)return;It=i,Di(t)}catch{k.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}let e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{let t=window.__openNewSessionModal;typeof t=="function"?t():document.getElementById("new-session-modal")?.classList.add("open")}),Ft()}var mn="tmux-web-sidebar-group-collapsed";function hn(){try{return new Set(JSON.parse(localStorage.getItem(mn)||"[]"))}catch{return new Set}}function Ii(e){try{localStorage.setItem(mn,JSON.stringify([...e]))}catch{}}function Bi(e,t,n){if(!e)return"\u2026";let i=n&&(e===n||e.startsWith(n+"/"))?"~"+e.slice(n.length):e,a=i.split("/").filter(Boolean);if(a.length===0)return e;for(let r=1;r<=a.length;r++){let o=a.slice(-r).join("/");if(!t.some(l=>!l||l===e?!1:(n&&(l===n||l.startsWith(n+"/"))?"~"+l.slice(n.length):l).split("/").filter(Boolean).slice(-r).join("/")===o))return o}return i}function Ti(e){let t=document.createElement("div");t.className="session-item bot-item",t.setAttribute("data-bot-id",e.id),t.title=`Bot \xB7 ${e.projectPath}`;let n=e.status==="running"?"var(--panel-success)":e.status==="waiting_approval"||e.status==="waiting_input"?"#e0a23c":e.status==="failed"?"var(--panel-danger, #e5534b)":"var(--panel-muted)";return t.innerHTML=`${ce("bot",'class="bot-icon"')}<span>${C(e.title)}</span><span class="bot-status-dot" style="background:${n}"></span>`,t.addEventListener("click",i=>{i.stopPropagation(),window.__openBot?.(e.id)}),t}function vn(e,t,n,i=!0){let a=new Map;for(let p of e){let f=p.path||"";a.has(f)||a.set(f,[]),a.get(f).push(p)}let r=n?[]:window.__botsSnapshot||[],o=new Map;for(let p of r)a.has(p.projectPath)||a.set(p.projectPath,[]),o.has(p.projectPath)||o.set(p.projectPath,[]),o.get(p.projectPath).push(p);let l=[...a.keys()],u=hn();for(let[p,f]of a){let y=Bi(p,l,t),H=u.has(p),L=document.createElement("div");if(L.className="session-group-header"+(H?" collapsed":""),L.title=p||"No working directory",L.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${C(y)}</span>`,!n&&p){let g=document.createElement("button");g.className="sg-add-bot",g.innerHTML=ce("add",'width="12" height="12"'),g.title=`New bot in ${p}`,g.addEventListener("click",M=>{M.stopPropagation(),Tt(p)}),L.appendChild(g)}L.addEventListener("click",()=>{let g=hn(),M=L.nextElementSibling;g.has(p)?(g.delete(p),L.classList.remove("collapsed"),M?.classList.remove("collapsed")):(g.add(p),L.classList.add("collapsed"),M?.classList.add("collapsed")),Ii(g)});let w=document.createElement("div");w.className="session-group-body"+(H?" collapsed":"");for(let g of f)w.appendChild(n?zi(g,n,i):Hi(g));for(let g of o.get(p)||[])w.appendChild(Ti(g));k.appendChild(L),k.appendChild(w)}}function zi(e,t,n){let i=document.createElement("div");i.className="session-item"+(e.name===z&&V===t?" active":"")+(n?"":" session-offline"),i.setAttribute("data-session",e.name),i.setAttribute("data-agent",t),i.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
14
- <span>${C(e.name)}</span>${n?"":'<span class="meta">offline</span>'}
15
- <button class="session-edit-btn" data-session="${C(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,n&&i.addEventListener("click",r=>{r.target.closest(".session-edit-btn")||Ae(e.name,t)});let a=i.querySelector(".session-edit-btn");return a&&a.addEventListener("click",r=>{r.stopPropagation(),rt(e.name,a,{agentId:t})}),i}function Hi(e){let t=document.createElement("div");t.className="session-item"+(e.name===z&&!V?" active":""),t.setAttribute("data-session",e.name),t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
16
- <span>${C(e.name)}</span>
17
- <button class="session-edit-btn" data-session="${C(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>
18
- `,t.addEventListener("click",i=>{i.target.closest(".session-edit-btn")||Ae(e.name)});let n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",i=>{i.stopPropagation(),rt(e.name,n)}),t}function Di(e){k.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';let t=e.recent||[],n=document.createElement("div");n.className="sidebar-section-label"+(Te?" clickable":""),n.textContent=Te?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",Te&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),k.appendChild(n),vn(t,e.home);let i=e.agents||[];for(let r of i){if(!r.sessions||r.sessions.length===0)continue;let o=r.agentId===V,l=document.createElement("div");l.className="sidebar-section-label machine-label"+(r.online?"":" agent-offline-label")+(!o&&r.online?" clickable":""),l.textContent=r.agentName+(r.online?"":" (offline)"),!o&&r.online&&(l.title="\u6253\u5F00 "+r.agentName,l.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(r.agentId)+"/"})),k.appendChild(l),vn(r.sessions,e.home,r.agentId,r.online)}let a=e.tombstones||[];if(a.length>0){let r=document.createElement("div");r.className="sidebar-section-label tombstone-label",r.textContent="\u5931\u6548\u4F1A\u8BDD",k.appendChild(r);for(let o of a){let l=document.createElement("div");l.className="session-item session-tombstone",l.setAttribute("data-session",o.name),o.agentId&&l.setAttribute("data-agent",o.agentId);let u=o.agentId?o.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";l.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
19
- <span>${C(o.name)}</span><span class="meta">\u5931\u6548${u}</span>
20
- <button class="session-edit-btn" data-session="${C(o.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,l.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",l.addEventListener("click",()=>{rt(o.name,l,{tombstone:!0,agentId:o.agentId})});let p=l.querySelector(".session-edit-btn");p&&p.addEventListener("click",f=>{f.stopPropagation(),rt(o.name,p,{tombstone:!0,agentId:o.agentId})}),k.appendChild(l)}}}function C(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function Ae(e,t){if(z===e&&S&&V===(t||null))return;ze.style.display="none",me.style.display="none",q.style.display="",q.classList.add("terminal-pending"),De(),S&&(st(),S.destroy(),S=null),z=e,V=t||null,window.__tmuxWebScopeAgent=V,window.__tmuxWebCurrentSession=z,aa(e,t);let n=At(e,t);Tn.set(n,Date.now()+na);let i=Ee.get(n);if(i&&i.state==="working"){i.state="idle",i.doneUntil=void 0,i.unread=!1;let a=k.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');a&&mt(a,n,i)}for(let a of k.querySelectorAll(".session-item"))a.classList.toggle("active",a.getAttribute("data-session")===e&&(a.getAttribute("data-agent")||null)===V);try{S=await ri(q,e,{terminal:Be.terminal,scrollback:Be.scrollback,theme:Be.theme,wsBase:V?"/ws/a/"+encodeURIComponent(V):Be.wsBase||"/ws"}),xn()}catch(a){console.error("[shell] terminal init failed:",a);let r=a&&typeof a=="object"&&"message"in a?a.message:String(a);q.textContent="Failed to open terminal for "+e+": "+r,q.classList.remove("terminal-pending")}}var Ge=[],D=null,fn=!1;function Ai(e){if(!D||!D.files.length)return null;let t=D.repoRoot;if(!t||!e.startsWith(t))return null;let n=e.slice(t.length+1);for(let i of D.files)if(i.path===n)return i.status;return null}async function Fi(e){fn=!0;try{let t=await fetch($("/api/git/status?path="+encodeURIComponent(e)));t.ok?D=await t.json():D=null}catch{D=null}finally{fn=!1}}function $i(){if(!D||!D.branch)return"";let{branch:e,linesAdded:t,linesRemoved:n}=D,i=`<div class="sidebar-git"><div class="git-branch-badge">
8
+ `).join("\r")}async function fs(p){let v=ps(p.clipboardData);if(v){p.preventDefault(),p.stopPropagation();let N=Date.now();if(N-xt<50)return;xt=N,await Kt(v);return}let S=p.clipboardData?.getData("text/plain");if(!S)return;p.preventDefault(),p.stopPropagation();let z=Date.now();z-xt<50||(xt=z,i.pasteText(Wn(S)))}let Ke=0;function gs(p){p.preventDefault(),Ke++,qn(p.dataTransfer)&&t.classList.add("terminal-drag-over")}function vs(p){p.preventDefault(),p.dataTransfer&&(p.dataTransfer.dropEffect="copy")}function bs(p){p.preventDefault(),Ke--,Ke<=0&&(Ke=0,t.classList.remove("terminal-drag-over"))}async function ks(p){p.preventDefault(),Ke=0,t.classList.remove("terminal-drag-over");let v=qn(p.dataTransfer);v&&await Kt(v)}function Un(p){!bt||p.key!=="Escape"||Je||p.defaultPrevented||p.repeat||p.metaKey||p.ctrlKey||p.altKey||i.isFocused()&&(p.preventDefault(),p.stopPropagation(),_e("\x1B"))}t.addEventListener("paste",fs),t.addEventListener("dragenter",gs),t.addEventListener("dragover",vs),t.addEventListener("dragleave",bs),t.addEventListener("drop",ks),document.addEventListener("keydown",Un,!0);function ws(p){if(p.touches.length!==1){a=null;return}let v=p.touches[0];if(!v)return;y();let S=t.getBoundingClientRect(),z=v.clientX-S.left<S.width*.4?"tui":"history",N=v.clientY-S.top<S.height*.5;a={startX:v.clientX,startY:v.clientY,lastX:v.clientX,lastY:v.clientY,lastT:performance.now(),velocity:0,scrolling:!1,zone:z,tuiUp:N,sent:!1},p.stopPropagation()}function ys(p){if(!a||p.touches.length!==1)return;let v=p.touches[0];if(!v)return;let S=v.clientY-a.startY,z=v.clientX-a.startX;if(!a.scrolling){if(Math.abs(S)<8||Math.abs(S)<Math.abs(z))return;a.scrolling=!0,T=Date.now()+500}p.preventDefault(),p.stopPropagation();let N=performance.now(),ue=v.clientY-a.lastY;if(a.zone==="tui"){a.sent||(a.sent=!0,_e(a.tuiUp?"\x1B[5~":"\x1B[6~"),x(a.tuiUp)),a.lastX=v.clientX,a.lastY=v.clientY,a.lastT=N;return}let ye=N-a.lastT;ye>0&&(a.velocity=ue/ye),Cs(-ue),a.lastX=v.clientX,a.lastY=v.clientY,a.lastT=N}function xs(p){if(!a)return;let v=a.scrolling,S=a.zone,z=a.tuiUp,N=a.velocity;if(a=null,p.stopPropagation(),S==="tui"){v||(_e(z?"\x1B[5~":"\x1B[6~"),x(z),T=Date.now()+500,p.preventDefault());return}if(!v){i.focus();return}T=Date.now()+500,p.preventDefault(),N&&B(N)}function Es(p){a=null,y(),p.stopPropagation()}function Ss(p){p.pointerType==="touch"&&Date.now()<T&&(p.preventDefault(),p.stopPropagation())}function Cs(p){let v=i.cellHeight(),S=v>0?Math.round(p/v):p>0?1:-1;S===0&&(S=p>0?1:-1),i.scrollLines(S)}t.addEventListener("touchstart",ws,{passive:!0,capture:!0}),t.addEventListener("touchmove",ys,{passive:!1,capture:!0}),t.addEventListener("touchend",xs,{passive:!1,capture:!0}),t.addEventListener("touchcancel",Es,{passive:!0,capture:!0}),t.addEventListener("pointerup",Ss,!0);function Jn(){Q()}window.addEventListener("resize",Jn),window.visualViewport?.addEventListener("resize",Q),window.visualViewport?.addEventListener("scroll",Q);let Zn=new ResizeObserver(()=>Q());Zn.observe(t),document.fonts?.ready.then(()=>{Q(),setTimeout(Q,50),setTimeout(Q,200)}),t.addEventListener("focusin",ds,!0);async function Ls(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(p=>setTimeout(p,1e3))])}catch{}}return requestAnimationFrame(()=>{Te()&&kt(),(async()=>(await Ls(),Te()&&pe({type:"resize",cols:i.cols,rows:i.rows}),Nn(),Q()))()}),{destroy(){if(L=!0,y(),Fe(!1),Xe&&clearTimeout(Xe),document.removeEventListener("mousemove",Qt,!0),document.removeEventListener("mouseup",Gt,!0),s){try{s.close(1e3,"session switch")}catch{}s=void 0}t.innerHTML="",t.classList.remove("terminal-pending"),window.removeEventListener("resize",Jn),Zn.disconnect(),document.removeEventListener("keydown",Un,!0)},focus(){i.focus()},sendInput(p){_e(p)},toggleCopyMode(){Vn()}}})()}var Kn={menu:"M3 6h18v2H3V6zm0 5h18v2H3v-2zm0 5h18v2H3v-2z",close:"M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7a1 1 0 1 0-1.41 1.41L10.59 12l-4.89 4.89a1 1 0 1 0 1.41 1.41L12 13.41l4.89 4.89a1 1 0 1 0 1.41-1.41L13.41 12l4.89-4.89a1 1 0 0 0 0-1.4z",search:"M15.5 14h-.79l-.28-.27A6.47 6.47 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z",refresh:"M17.65 6.35A7.96 7.96 0 0 0 12 4a8 8 0 1 0 8 8h-2a6 6 0 1 1-6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z",add:"M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z",edit:"M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM5.92 19H5v-.92l9.06-9.06.92.92L5.92 19zm13.66-12.83a1 1 0 0 0 0-1.41l-1.34-1.34a1 1 0 0 0-1.41 0l-1.05 1.05 2.75 2.75 1.05-1.05z",delete:"M15 4V3H9v1H4v2h1.5l.81 13.05A2 2 0 0 0 8.3 21h7.4a2 2 0 0 0 1.99-1.95L18.5 6H20V4h-5zm-5.5 2h5l-.75 12h-3.5L9.5 6z",check:"M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z",sessions:"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z",notes:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6zm-1 2 5 5h-5V4zM6 20V4h5v7h7v9H6z",schedule:"M19 4h-1V2h-2v2H8V2H6v2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 16H5V10h14v10zM9 14H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2zm-8 4H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2z",agents:"M12 2a5 5 0 1 0 0 10 5 5 0 0 0 0-10zm0 8a3 3 0 1 1 0-6 3 3 0 0 1 0 6zm-7 13v-2a5 5 0 0 1 5-5h4a5 5 0 0 1 5 5v2h2v-2a7 7 0 0 0-7-7H10a7 7 0 0 0-7 7v2h2z",history:"M13 3a9 9 0 0 0-9 9H1l4 4 4-4H6a7 7 0 1 1 7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.96 8.96 0 0 0 13 21a9 9 0 0 0 0-18zm-1 5v5l4.25 2.55.75-1.23-3.5-2.08V8H12z","quick-commands":"M13 3 4 14h7l-1 7 9-11h-7l1-7z",windows:"M4 6h16v2H4V6zm0 5h10v2H4v-2zm0 5h16v2H4v-2z",terminal:"M4 17.6 6.4 20l8-8-8-8L4 6.4 11.6 12 4 17.6zM20 18h-8v2h8v-2z",microphone:"M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5-3c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z",keyboard:"M20 5H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-9 3h2v2h-2V8zm0 3h2v2h-2v-2zM8 8h2v2H8V8zm0 3h2v2H8v-2zm-1 2H5v-2h2v2zm0-3H5V8h2v2zm9 7H8v-2h8v2zm0-4h-2v-2h2v2zm0-3h-2V8h2v2zm3 3h-2v-2h2v2zm0-3h-2V8h2v2z",bot:"M11 2h2v3h2a3 3 0 0 1 3 3v1h1a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-1v1a3 3 0 0 1-3 3H9a3 3 0 0 1-3-3v-1H5a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2h1V8a3 3 0 0 1 3-3h2V2zm-2 6v1h6V8H9zm-2 5a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3zm10 0a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3z",layers:"M12 2 2 7l10 5 10-5-10-5zm0 7.5L4.5 5.8 12 2l7.5 3.8L12 9.5zM2 12l10 5 10-5-1.9-.95L12 14.9l-8.1-3.85L2 12zm0 4.5 10 5 10-5-1.9-.95L12 19.4l-8.1-3.85-1.9.95z",inbox:"M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2zm0 16H5v-3h3.6a3.5 3.5 0 0 0 6.8 0H19v3zm0-5h-4.7a3.5 3.5 0 0 1-6.6 0H5V5h14v9z","chevron-down":"M7.4 8.6 12 13.2l4.6-4.6L18 10l-6 6-6-6 1.4-1.4z",settings:"M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.488.488 0 0 0-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.484.484 0 0 0-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6a3.6 3.6 0 1 1 0-7.2 3.6 3.6 0 0 1 0 7.2z",pin:"M16 12V4h1V2H7v2h1v8l-4 4v2h5.2v6h1.6v-6H20v-2l-4-4z","pin-outline":"M16 12V4h1V2H7v2h1v8l-4 4v2h5.2v6h1.6v-6H20v-2l-4-4zm-4.8 7.2V11l2-2V4h1.6v5l2 2v5.2H11.2z",folder:"M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z",file:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6zm-1 2 5 5h-5V4zM6 20V4h5v7h7v9H6z",worktree:"M6 3a3 3 0 0 0-1 5.83v6.34a3 3 0 1 0 2 0V8.83A3 3 0 0 0 6 3zm0 2a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm0 12a1 1 0 1 1 0 2 1 1 0 0 1 0-2zM18 3a3 3 0 0 0-1 5.83V9a4 4 0 0 1-4 4h-2a3 3 0 1 0 0 2h2a6 6 0 0 0 6-6v-.17A3 3 0 0 0 18 3zm0 2a1 1 0 1 1 0 2 1 1 0 0 1 0-2zM9 13a1 1 0 1 1 0 2 1 1 0 0 1 0-2z",copy:"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z",export:"M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z",chevronRight:"M9.29 6.71a1 1 0 0 0 0 1.41L13.17 12l-3.88 3.88a1 1 0 1 0 1.41 1.41l4.59-4.59a1 1 0 0 0 0-1.41L10.7 6.7a1 1 0 0 0-1.41.01z",lightning:"M11 21h-1l1-7H7.5c-.58 0-.57-.32-.38-.66.19-.33.51-.89.73-1.27L13 3h1l-1 7h3.5c.49 0 .56.33.47.51l-.07.15c-.22.46-.58 1.18-.78 1.58L11 21z","git-branch":"M13.5 7a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0zm0 10a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0zM11 9.5v5.1a4.03 4.03 0 0 0-3-.1V9.4a4.03 4.03 0 0 0 3 .1z",external:"M14 3h7v7h-2V6l-9.29 9.29-1.41-1.41L17.59 4.5H14V3zm4 16H5V5h7V3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7h-2v7z",play:"M8 5v14l11-7L8 5z",stop:"M6 6h12v12H6V6z",warning:"M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z",info:"M11 7h2v2h-2V7zm0 4h2v6h-2v-6zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z",spinner:"M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46A7.93 7.93 0 0 0 20 12c0-4.42-3.58-8-8-8z",dots:"M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"};function Rs(t){return Kn[t]??Kn.menu}function xe(t,e=""){return`<svg viewBox="0 0 24 24" fill="currentColor"${e?" "+e:""}><path d="${Rs(t)}"/></svg>`}function tn(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ie=tn();function Qn(t){Ie=t}var $e={exec:()=>null};function Be(t){let e=[];return n=>{let i=Math.max(0,Math.min(3,n-1)),s=e[i];return s||(s=t(i),e[i]=s),s}}function C(t,e=""){let n=typeof t=="string"?t:t.source,i={replace:(s,l)=>{let r=typeof l=="string"?l:l.source;return r=r.replace(H.caret,"$1"),n=n.replace(s,r),i},getRegex:()=>new RegExp(n,e)};return i}var Gn=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),ei="^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)",H={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,listInterruptsParagraph:/^ {0,3}(?:[*+-]|0{0,8}1[.)])[ \t]+[^ \t\n]/,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^( {1,3})(?:`{3}|~{3})/,beginningSpace:/^[ \t]{1,3}/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,leadingSpaceTab:/^[ \t]+/,multipleSpaceGlobal:/\s+/g,multipleSpaceTabGlobal:/[ \t\r\n]+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,textIndentedContinuation:/^(?:\n(?: {4}| {0,3}\t)[ \t]*[^ \t\n][^\n]*)+/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+)[ \t]*)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,blockquoteMarkerWhitespace:/^( {0,3}>)(\t[ \t]*)/gm,blockquoteFenceOpen:/^ {0,3}(`{3,}(?=[^`]*$)|~{3,})/,blockquoteFenceClose:/^ {0,3}(`{3,}|~{3,})[ \t]*$/,blockquoteListItemStart:/^ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|$)/,nestedBlockMarker:/^ {0,3}(?:(?:[*+-]|\d{1,9}[.)])(?: |$)|> ?)/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\][ \t]+\S/,listReplaceTask:/^\[[ xX]\][ \t]+/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableHeader:new RegExp(ei+"(?:\\n|$)"),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,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,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:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Be(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Be(t=>new RegExp(`^ {0,${t}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:Be(t=>new RegExp(`^ {0,${t}}(?:\`{3,}(?=[^\`\\n]*(?:\\n|$))|~~~)`)),headingBeginRegex:Be(t=>new RegExp(`^ {0,${t}}#{1,6}(?:\\s|$)`)),pedanticHeadingBeginRegex:Be(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:Be(t=>new RegExp(`^ {0,${t}}(?:</?(?:${sn})(?:[ \\t]+|$|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`,"i")),blockquoteBeginRegex:Be(t=>new RegExp(`^ {0,${t}}>`)),nestedContainerMarkers:/^(?: {0,3}(?:(?:[*+-]|\d{1,9}[.)])[ \t]+|>[ \t]?))+/},Ps=/^(?:[ \t]*(?:\n|$))+/,Ds=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Hs=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}(?:(?=`)\1`*|(?=~)\1~*)[ \t]*(?=\n|$)|$)/,Ge=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,_s=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,nn=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,sn="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",et=C(" {0,3}(?:</?(?:tag)(?:[ \\t]+|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",sn).getRegex(),ti=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?![ \t]*\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+)[ \t]*(?:\n+|$)/,ni=C(ti).replace(/bull/g,nn).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}(?=[^`\n]*(?:\n|$))|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/\|table/g,"").replace(/html/g,et).getRegex(),Fs=C(ti).replace(/bull/g,nn).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}(?=[^`\n]*(?:\n|$))|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).replace(/html/g,et).getRegex(),rn=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Ns=/^[^\n]+/,ln=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\\n]|\n(?![ \t]*\n))+/,Os=C(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<(?:\\.|[^\n<>\\])*>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ln).replace("title",/(?:"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\\n]|\n(?!\n))*'|\((?:\\[\s\S]|[^()\\])*\))/).getRegex(),qs=C(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,nn).getRegex(),an=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,js=C("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?:[ \\t]+|\\n|/?>|$)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!(?:script|pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*?[ \\t]*/?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",an).replace("tag",sn).replace("attribute",/[ \t]+[a-zA-Z:_][\w.:-]*(?:[ \t]*=[ \t]*"[^"\n]*"|[ \t]*=[ \t]*'[^'\n]*'|[ \t]*=[ \t]*[^\s"'=<>`]+)?/).getRegex(),ii=t=>C(rn).replace("hr",Ge).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",t).replace("html",et).getRegex(),Vs=ii(H.listInterruptsParagraph),Ws=ii(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),si=/ {0,3}> ?(?:(?!blank)(paragraph)|[^\n]*)(?:\n|$)/,Us=C(/^(first)(?:next)*/).replace("first",C(si).replace("blank",/[ \t]*(?:\n|$)| {4}/).getRegex()).replace("next",C(si).replace("blank",/[ \t]*(?:\n|$)/).getRegex()).replace(/paragraph/g,Ws).getRegex(),on={blockquote:Us,code:Ds,def:Os,fences:Hs,heading:_s,hr:Ge,html:js,lheading:ni,list:qs,newline:Ps,paragraph:Vs,table:$e,text:Ns},Js=C(ei+"(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ge).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|0{0,8}1[.)])[ \\t]").replace("html",et).getRegex(),Zs={...on,lheading:Fs,table:Js,paragraph:C(rn).replace("hr",Ge).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",H.tableHeader).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",H.listInterruptsParagraph).replace("html",et).getRegex()},Ys={...on,html:C(`^ *(?:comment(?: *\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1>(?: *\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?>(?: *\\n{2,}|\\s*$))`).replace("comment",an).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:$e,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:C(rn).replace("hr",Ge).replace("heading",` *#{1,6} *[^
9
+ ]`).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").replace("lheading",ni).getRegex()},Xs=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ks=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ri=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,Qs=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,he=/[\p{P}\p{S}]/u,Ne=/[\s\p{P}\p{S}]/u,tt=/[^\s\p{P}\p{S}]/u,Gs=C(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ne).getRegex(),er=/[\p{Pi}\p{Ps}"']/u,li=/(?!~)[\p{P}\p{S}]/u,tr=/(?!~)[\s\p{P}\p{S}]/u,nr=/(?:[^\s\p{P}\p{S}]|~)/u,ir=C(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Gn?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ai=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,sr=C(ai,"u").replace(/punct/g,he).getRegex(),rr=C(ai,"u").replace(/punct/g,li).getRegex(),lr=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,ar=C(lr,"u").replace(/openQuote/g,er).replace(/punct/g,he).getRegex(),oi="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",or=C(oi,"gu").replace(/notPunctSpace/g,tt).replace(/punctSpace/g,Ne).replace(/punct/g,he).getRegex(),cr=C(oi,"gu").replace(/notPunctSpace/g,nr).replace(/punctSpace/g,tr).replace(/punct/g,li).getRegex(),dr="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",pr=C(dr,"gu").replace(/notPunctSpace/g,tt).replace(/punctSpace/g,Ne).replace(/punct/g,he).getRegex(),ur=C("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,tt).replace(/punctSpace/g,Ne).replace(/punct/g,he).getRegex(),hr="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",mr=C(hr,"gu").replace(/notPunctSpace/g,tt).replace(/punctSpace/g,Ne).replace(/punct/g,he).getRegex(),fr=C(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,he).getRegex(),gr="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",vr=C(gr,"gu").replace(/notPunctSpace/g,tt).replace(/punctSpace/g,Ne).replace(/punct/g,he).getRegex(),br=C(/\\(punct)/,"gu").replace(/punct/g,he).getRegex(),kr=C(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,"gu").replace(/punct/g,he).getRegex(),wr=C(/^<(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(),yr=C(an).replace("(?:-->|$)","-->").getRegex(),xr=C("^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",yr).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ci=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,St=C(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",ci).getRegex(),Ct=/\\[^ \t\n\x00-\x1f]|\\(?=[ \t\n])|[^ \t\n\x00-\x1f\\()]/,Er=C(/\((?:char)*\)/).replace("char",Ct).getRegex(),Sr=C(/\((?:char|p1)*\)/).replace("char",Ct).replace("p1",Er).getRegex(),Cr=C(/\((?:char|p2)*\)/).replace("char",Ct).replace("p2",Sr).getRegex(),Lr=C(/(?!<)(?:char|p3)+/).replace("char",Ct).replace("p3",Cr).getRegex(),Tr=C(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace("label",St).replace("href",C(/<(?:\\.|[^\n<>\\])*>|bareHref|(?=\))/).replace("bareHref",Lr).getRegex()).replace("title",/"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|\((?:\\[\s\S]|[^)\\])*\)/).getRegex(),Ir=C(/^!?\[(label)\]\[(ref)\]/).replace("label",St).replace("ref",ln).getRegex(),$r=C(/^!?\[(ref)\](?:\[\])?/).replace("ref",ln).getRegex(),di=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,Br=C(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace("brackets",ci).getRegex(),Mr=C("reflink|nolink(?!\\()","g").replace("reflink",C(/^!?\[(label)\]\[(ref)\]/).replace("label",Br).replace("ref",di).getRegex()).replace("nolink",C(/^!?\[(ref)\](?:\[\])?/).replace("ref",di).getRegex()).getRegex(),pi=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,zr=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/,Ar=C(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,zr).getRegex(),cn={_backpedal:$e,anyPunctuation:br,anyPunctuationOutsideCode:kr,autolink:wr,blockSkip:ir,br:ri,code:Ks,del:$e,delLDelim:$e,delRDelim:$e,emStrongLDelim:sr,emStrongRDelimAst:or,emStrongRDelimUnd:ur,escape:Xs,link:Tr,nolink:$r,punctuation:Gs,reflink:Ir,reflinkSearch:Mr,tag:xr,text:Qs,url:$e},Rr={...cn,emStrongLDelim:ar,emStrongRDelimAst:pr,emStrongRDelimUnd:mr,link:C(/^!?\[(label)\]\((.*?)\)/).replace("label",St).getRegex(),reflink:C(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",St).getRegex()},dn={...cn,emStrongRDelimAst:cr,emStrongLDelim:rr,delLDelim:fr,delRDelim:vr,url:C(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("emailProtocol",Ar).replace("protocol",pi).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:C(/^(?:[A-Za-z0-9.+-]+(?=@)|[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|wwwStart|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))))/).replace("protocol",pi).replace(/emailProtocol/g,/(?:mailto|xmpp):/).replace("wwwStart",Gn?"(?<![^\\s*_~(])www\\.":"www\\.").getRegex()},Pr={...dn,br:C(ri).replace("{2,}","*").getRegex(),text:C(dn.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Lt={normal:on,gfm:Zs,pedantic:Ys},nt={normal:cn,gfm:dn,breaks:Pr,pedantic:Rr},Dr={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},ui=t=>Dr[t];function Z(t,e){if(e){if(H.escapeTest.test(t))return t.replace(H.escapeReplace,ui)}else if(H.escapeTestNoEncode.test(t))return t.replace(H.escapeReplaceNoEncode,ui);return t}function Hr(t){return H.numericCharacterReference.test(t)?t.replace(H.numericCharacterReferenceOrAmpersand,(e,n,i)=>{if(n===void 0&&i===void 0)return"&amp;";let s=n===void 0?Number.parseInt(i,16):Number.parseInt(n,10);return s===0||s>1114111||s>=55296&&s<=57343?"\uFFFD":s===38?"&amp;":String.fromCodePoint(s)}):t}function hi(t){try{t=encodeURI(t).replace(H.percentDecode,"%")}catch{return null}return t}function pn(t,e){let n=t.replace(H.findPipe,(l,r,a)=>{let o=!1,c=r;for(;--c>=0&&a[c]==="\\";)o=!o;return o?"|":" |"}),i=n.split(H.splitPipe),s=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),e)if(i.length>e)i.splice(e);else for(;i.length<e;)i.push("");for(;s<i.length;s++)i[s]=i[s].trim().replace(H.slashPipe,"|");return i}function ve(t,e,n){let i=t.length;if(i===0)return"";let s=0;for(;s<i;){let l=t.charAt(i-s-1);if(l===e&&!n)s++;else if(l!==e&&n)s++;else break}return t.slice(0,i-s)}function mi(t){let e=t.split(`
10
+ `),n=e.length-1;for(;n>=0&&H.blankLine.test(e[n]);)n--;return e.length-n<=2?t:e.slice(0,n+1).join(`
11
+ `)}function Tt(t,e=!1){let n=e?H.multipleSpaceGlobal:H.multipleSpaceTabGlobal;return t.trim().replace(n," ").toLowerCase().toUpperCase().toLowerCase()}function fi(t,e){if(t.indexOf(e[0])===-1&&t.indexOf(e[1])===-1)return-1;let n=0;for(let i=0;i<t.length;i++)if(t[i]==="\\")i++;else if(t[i]===e[0])n++;else if(t[i]===e[1]&&(n--,n<0))return i;return n>0?-2:-1}var Oe=new WeakMap;function un(t){let e={"*":-1,_:-1},n=-1,i=t.length;for(let s=0;s<i;s++){let l=t[s];if(l!=="*"&&l!=="_"&&l!=="~")continue;let r=s===0?`
12
+ `:t[s-1],a=s+1;for(;a<i&&t[a]===l;)a++;r!==" "&&r!==" "&&r!==`
13
+ `&&r!=="\r"&&r!=="\f"&&(l==="~"?n=s:e[l]=s),s=a-1}return{maskedSrc:t,lastPossibleEmStrongCloserIndex:e,lastPossibleDelCloserIndex:n}}function _r(t,e){let n=un(e),i=Oe.get(t);i?i.push(n):Oe.set(t,[n])}function Fr(t){let e=Oe.get(t);e&&(e.pop(),e.length===0&&Oe.delete(t))}function gi(t,e,n){let i=Oe.get(t)?.at(-1);return i&&i.maskedSrc===e?i.lastPossibleEmStrongCloserIndex[n]:un(e).lastPossibleEmStrongCloserIndex[n]}function vi(t,e){let n=Oe.get(t)?.at(-1);return n&&n.maskedSrc===e?n.lastPossibleDelCloserIndex:un(e).lastPossibleDelCloserIndex}function it(t,e=0){let n=e,i="";for(let s of t)if(s===" "){let l=4-n%4;i+=" ".repeat(l),n+=l}else i+=s,n++;return i}function Nr(t){let e,n=!1;return t.map(i=>{if(n)return i;let{depth:s,expanded:l,keptIndent:r,content:a}=Or(i,e?.depth??1/0);if(e?.depth!==s&&(e=void 0),e){let c=H.blockquoteFenceClose.exec(a)?.[1];return!c||c[0]!==e.marker[0]||c.length<e.marker.length?r:(e=void 0,l)}if(n=H.blockquoteListItemStart.test(a),n)return i;let o=H.blockquoteFenceOpen.exec(a)?.[1];return o&&(e={marker:o,depth:s}),l}).join(`
14
+ `)}function Or(t,e){let n=0,i=0,s=0,l=0,r="";for(;s<e;){let d=n,m=i;for(;t[d]===" "||t[d]===" ";)m+=bi(t[d],m),d++;if(t[d]!==">"||m-l>3)break;r+=" ".repeat(m-i)+">",s++,n=d+1,i=m+1,l=t[n]===" "||t[n]===" "?i+1:i}if(s===0)return{depth:s,expanded:t,keptIndent:t,content:t};let a="",o="";for(;(t[n]===" "||t[n]===" ")&&i<l+4;){let d=bi(t[n],i);a+=" ".repeat(d),o+=i<l&&d>1?" ".repeat(d):t[n],i+=d,n++}let c=t.slice(n);return{depth:s,expanded:r+a+c,keptIndent:r+o+c,content:" ".repeat(Math.max(0,i-l))+c}}function bi(t,e){return t===" "?4-e%4:1}function qr(t,e){let n="";for(let i=0;i<t.length;i++){if(t[i]==="`"){let s=e.inline.code.exec(t.slice(i));if(s){n+=s[0],i+=s[0].length-1;continue}}if(t[i]==="\\"&&(t[i+1]==="["||t[i+1]==="]")){n+=t[i+1],i++;continue}n+=t[i]}return n}function ki(t,e,n,i,s){let l=e.href,r=e.title||null,a=qr(t[1],s),o=t[0].charAt(0)==="!",c=i.state.inLink,d=i.state.linkEmitted,m=i.state.inRawBlock;i.state.inLink=!0,i.state.linkEmitted=!1;let h=i.inlineTokens(a),u=i.state.linkEmitted;if(i.state.linkEmitted=d,i.state.inLink=c,!o){if(u){i.state.inRawBlock=m;return}i.state.linkEmitted=!0}return{type:o?"image":"link",raw:n,href:l,title:r,text:a,tokens:h}}function jr(t,e,n,i){let s=t.match(n.other.indentCodeCompensation);if(s===null)return e;let l=s[1].length;return e.split(`
15
+ `).map(r=>{let a=r.match(n.other.beginningSpace);if(a===null)return r;let[o]=a,c=o.indexOf(" ");if(c!==-1&&c<l){if(i)return" ".repeat(4-l)+r.slice(c+1);if(t[l]==="~")return r}return r.slice(Math.min(o.length,l))}).join(`
16
+ `)}function wi(t,e,n,i){if(!e.includes("<"))return!1;for(let s=0;s<e.length;s++){if(e[s]==="\\"){s++;continue}if(e[s]==="`"){let a=i.inline.code.exec(e.slice(s));if(a){s+=a[0].length-1;continue}}if(e[s]!=="<")continue;let l=t.slice(n+s),r=i.inline.tag.exec(l)||i.inline.autolink.exec(l);if(r){if(r[0].length>e.length-s)return!0;s+=r[0].length-1}}return!1}var Me=class{options;rules;lexer;constructor(t){this.options=t||Ie}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let n=this.options.pedantic?e[0]:mi(e[0]),i=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:i}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],i=jr(n,e[3]||"",this.rules,this.lexer.state.top&&!this.lexer.state.inBlockquote);e[3]!==void 0&&(i===""||i.endsWith(`
17
+ `))&&(i+=`
18
+ `);let s=e[2];if(s){let l=0,r=s.length;for(;l<r&&(s[l]===" "||s[l]===" ");)l++;for(;r>l&&(s[r-1]===" "||s[r-1]===" ");)r--;s=s.slice(l,r).replace(this.rules.inline.anyPunctuation,"$1")}return{type:"code",raw:n,lang:s,text:i}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let n=e[2].trim();if(this.rules.other.endingHash.test(n)){let i=ve(n,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceTabChar.test(i))&&(n=i.trim())}return{type:"heading",raw:ve(e[0],`
19
+ `),depth:e[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:ve(e[0],`
20
+ `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=ve(e[0],`
21
+ `).split(`
22
+ `),i="",s="",l=[];for(;n.length>0;){let r=!1,a=[],o;for(o=0;o<n.length;o++)if(this.rules.other.blockquoteStart.test(n[o]))a.push(n[o]),r=!0;else if(!r)a.push(n[o]);else break;n=n.slice(o);let c=a.join(`
23
+ `),d=(this.lexer.state.top&&!this.lexer.state.inBlockquote&&c.includes(" ")?Nr(a):c).replace(this.rules.other.blockquoteMarkerWhitespace,(b,x,k)=>k.startsWith(" ")?x+" "+k.slice(1):x+it(k,x.length)).replace(this.rules.other.blockquoteSetextReplace,`
24
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
25
+ ${c}`:c,s=s?`${s}
26
+ ${d}`:d;let m=this.lexer.state.top,h=this.lexer.state.inBlockquote,u=this.lexer.state.lastToken;if(this.lexer.state.top=!0,this.lexer.state.inBlockquote=!0,this.lexer.blockTokens(d,l,!0),this.lexer.state.top=m,this.lexer.state.inBlockquote=h,n.length===0)break;let f=l.at(-1);if(f?.type==="code"||f?.type==="heading"||f?.type==="hr"||f?.type==="html"||f?.type==="table")break;if(f?.type==="blockquote"){let b=f,x=n.join(`
27
+ `),k=b.raw+`
28
+ `+x.replace(this.rules.other.blockquoteSetextReplace2,"");this.lexer.state.inBlockquote=!0,this.lexer.state.lastToken=l.at(-2);let y=this.blockquote(k);this.lexer.state.inBlockquote=h,this.lexer.state.lastToken=u,l[l.length-1]=y;let B=k.substring(y.raw.length).replace(/^\n/,""),T=B?B.split(`
29
+ `).length:0,I=T?n.slice(0,-T):n;if(I.length>0&&(i=`${i}
30
+ ${I.join(`
31
+ `)}`),s=s.substring(0,s.length-b.text.length)+y.text,n=n.slice(I.length),n.length>0&&this.rules.other.blockquoteStart.test(n[0]))continue;break}else if(f?.type==="list"){let b=f,x=b.raw+`
32
+ `+n.join(`
33
+ `);this.lexer.state.inBlockquote=!0,this.lexer.state.lastToken=l.at(-2);let k=this.list(x);this.lexer.state.top=m,this.lexer.state.inBlockquote=h,this.lexer.state.lastToken=u,l[l.length-1]=k;let y=k.raw.length>b.raw.length?x.slice(b.raw.length+1,k.raw.length).split(`
34
+ `).length:0;if(y>0){let B=n.slice(0,y).join(`
35
+ `);i=`${i}
36
+ ${B}`,s=`${s}
37
+ ${B}`}if(n=n.slice(y),n.length>0&&!this.rules.other.blockquoteStart.test(n[0]))break;continue}}return{type:"blockquote",raw:i,tokens:l,text:s}}}list(t){let e=this.rules.block.list.exec(t);if(e){if(!this.options.pedantic&&this.lexer.state.lastToken?.type==="text"&&!this.rules.other.listInterruptsParagraph.test(t))return;let n=t,i=()=>n.length-t.length,s=e[1].trim(),l=s.length>1,r={type:"list",raw:"",ordered:l,start:l?+s.slice(0,-1):"",loose:!1,items:[]};s=l?`\\d{1,9}\\${s.slice(-1)}`:`\\${s}`,this.options.pedantic&&(s=l?s:"[*+-]");let a=this.rules.other.listItemRegex(s),o=!1;for(;t;){let h=!1,u="";if(!(e=a.exec(t))||this.rules.block.hr.test(t))break;let f=i();t=t.substring(e[0].length);let b=e[2].split(`
38
+ `,1)[0],x=e[1].length,k=this.options.pedantic?it(b,x):b.replace(this.rules.other.leadingSpaceTab,M=>it(M,x)),y=t.split(`
39
+ `,1)[0],B=!k.trim(),T=0;if(this.options.pedantic?(T=2,u=k.trimStart()):B?T=x+1:(T=k.search(this.rules.other.nonSpaceChar),T=T>4?1:T,u=k.slice(T),k=u,T+=x),B&&this.rules.other.blankLine.test(y)&&(t=t.substring(y.length+1),h=!0),!h){let M=this.rules.other.nextBulletRegex(T),$=this.rules.other.hrRegex(T),E=this.rules.other.fencesBeginRegex(T),A=this.options.pedantic?this.rules.other.pedanticHeadingBeginRegex(T):this.rules.other.headingBeginRegex(T),L=this.rules.other.htmlBeginRegex(T),j=this.rules.other.blockquoteBeginRegex(T),_=!1;for(;t;){let de=t.split(`
40
+ `,1)[0],G;if(y=de,this.options.pedantic?(y=y.replace(this.rules.other.listReplaceNesting," "),G=y):G=y.replace(this.rules.other.leadingSpaceTab,K=>it(K)),E.test(y)||A.test(y)||L.test(y)||j.test(y)||M.test(y)||$.test(y))break;if(G.search(this.rules.other.nonSpaceChar)>=T||!y.trim())u+=`
41
+ `+G.slice(T),_=!1;else{if(B)break;let K=k;if(!this.options.pedantic&&!u.includes(`
42
+ `)&&!k.includes(" ")){let ee;for(;!$.test(K)&&(ee=this.rules.other.nestedBlockMarker.exec(K));)K=K.slice(ee[0].length);if(!K.trim())break}if(K.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||E.test(K)||A.test(K)||L.test(K)||$.test(K))break;if(!this.options.pedantic&&!_){let ee=k.replace(this.rules.other.nestedContainerMarkers,"");if(this.rules.block.fences.test(ee)||this.rules.block.heading.test(ee)||this.rules.block.hr.test(ee))break}let bt=!this.options.pedantic&&/^ {0,3}(?:=+|-+) *$/.test(y)&&this.rules.block.lheading.test(`${k}
43
+ ${y}`)?` ${G.replace(/^ {0,3}/,"")}`:y,Ue=!this.options.pedantic&&!_&&G.startsWith(" ")?this.rules.block.list.exec(k):null;if(Ue?.[2]){let ee=Ue[1].length,pe=Ue[2].replace(this.rules.other.leadingSpaceTab,He=>it(He,ee)),Le=pe.search(this.rules.other.nonSpaceChar);Le>0&&Le<=4&&!this.rules.other.nestedBlockMarker.test(pe.slice(Le))&&G.search(this.rules.other.nonSpaceChar)>=ee+Le&&this.rules.other.listInterruptsParagraph.test(G.slice(ee+Le))&&(bt=` ${G}`)}u+=`
44
+ `+bt,_=!0}B=!y.trim(),t=t.substring(de.length+1),k=G.slice(T)}}let I=n.slice(f,i());r.loose||(o?r.loose=!0:this.rules.other.doubleBlankLine.test(I)&&(o=!0)),r.items.push({type:"list_item",raw:I,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]})}let c=r.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;r.raw=n.slice(0,i()).trimEnd();let d=[],m=this.lexer.state.top;for(let h of r.items)if(this.lexer.state.top=!1,d.push(this.lexer.inlineQueue.length),h.tokens=this.lexer.blockTokens(h.text,[]),!r.loose){let u=h.tokens.filter(b=>b.type==="space"),f=u.length>0&&u.some(b=>this.rules.other.anyLine.test(b.raw));r.loose=f}this.lexer.state.top=m;for(let h=0;h<r.items.length;h++){let u=r.items[h],f=u.tokens[0];if(u.task&&(f?.type==="text"||f?.type==="paragraph")){u.text=u.text.replace(this.rules.other.listReplaceTask,""),f.raw=f.raw.replace(this.rules.other.listReplaceTask,""),f.text=f.text.replace(this.rules.other.listReplaceTask,"");let b=this.lexer.inlineQueue;for(let k=d[h];k<b.length;k++)if(b[k].tokens===f.tokens){b[k].src=b[k].src.replace(this.rules.other.listReplaceTask,"");break}let x=this.rules.other.listTaskCheckbox.exec(u.raw);if(x){let k={type:"checkbox",raw:x[0]+" ",checked:x[0]!=="[ ]"};u.checked=k.checked,r.loose?u.tokens[0]&&["paragraph","text"].includes(u.tokens[0].type)&&"tokens"in u.tokens[0]&&u.tokens[0].tokens?(u.tokens[0].raw=k.raw+u.tokens[0].raw,u.tokens[0].text=k.raw+u.tokens[0].text,u.tokens[0].tokens.unshift(k)):u.tokens.unshift({type:"paragraph",raw:k.raw,text:k.raw,tokens:[k]}):u.tokens.unshift(k)}}else u.task&&(u.task=!1)}if(r.loose)for(let h of r.items){h.loose=!0;for(let u of h.tokens)u.type==="text"&&(u.type="paragraph")}return r}}html(t){let e=this.rules.block.html.exec(t);if(e){if(this.lexer.state.lastToken?.type==="paragraph"&&!this.rules.other.htmlBeginRegex(4).test(t))return;let n=mi(e[0]);return{type:"html",block:!0,raw:n,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:n}}}def(t){let e=this.rules.block.def.exec(t);if(e){if(!this.rules.other.startAngleBracket.test(e[2])&&fi(e[2],"()")!==-1)return;let n=Tt(e[1],this.options.pedantic),i=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:ve(e[0],`
45
+ `),href:i,title:s}}}table(t){let e,n;if(this.options.gfm&&!this.options.pedantic){let r=this.rules.other.tableHeader.exec(t);if(!r||!this.rules.other.tableDelimiter.test(r[2])||(e=pn(r[1]),n=r[2].replace(this.rules.other.tableAlignChars,"").split("|"),e.length!==n.length))return}let i=this.rules.block.table.exec(t);if(!i||!this.rules.other.tableDelimiter.test(i[2]))return;e??=pn(i[1]),n??=i[2].replace(this.rules.other.tableAlignChars,"").split("|");let s=i[3]?.trim()?i[3].replace(this.rules.other.tableRowBlankLine,"").split(`
46
+ `):[],l={type:"table",raw:ve(i[0],`
47
+ `),header:[],align:[],rows:[]};if(e.length===n.length){for(let r of n)this.rules.other.tableAlignRight.test(r)?l.align.push("right"):this.rules.other.tableAlignCenter.test(r)?l.align.push("center"):this.rules.other.tableAlignLeft.test(r)?l.align.push("left"):l.align.push(null);for(let r=0;r<e.length;r++)l.header.push({text:e[r],tokens:this.lexer.inline(e[r]),header:!0,align:l.align[r]});for(let r of s)l.rows.push(pn(r,l.header.length).map((a,o)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:l.align[o]})));return l}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let n=e[1].trim();return{type:"heading",raw:ve(e[0],`
48
+ `),depth:e[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let n=e[1].charAt(e[1].length-1)===`
49
+ `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e){let n=e[0],i=e[0],s=this.rules.other.textIndentedContinuation.exec(t.slice(n.length));return s&&(n+=s[0],i+=s[0].replace(this.rules.other.codeRemoveIndent,"")),{type:"text",raw:n,text:i,tokens:this.lexer.inline(i)}}}escape(t){if(t.charCodeAt(0)!==92)return;let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){if(t.charCodeAt(0)!==60)return;let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){if(this.lexer.state.linkParenPossible===!1)return;let e=t.charCodeAt(0);if(e!==91&&e!==33)return;let n=this.rules.inline.link.exec(t);if(n){let i=n[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&wi(t,n[1],i,this.rules))return;let s=n[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(s)){if(!this.rules.other.endAngleBracket.test(s))return;let o=ve(s.slice(0,-1),"\\");if((s.length-o.length)%2===0)return}else{let o=fi(n[2],"()");if(o===-2)return;if(o>-1){let c=(n[0].indexOf("!")===0?5:4)+n[1].length+o;n[2]=n[2].substring(0,o),n[0]=n[0].substring(0,c).trim(),n[3]=""}}let l=ve(n[0].slice(0,-1),"\\");if((n[0].length-l.length)%2===0)return;let r=n[2],a="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(r);o&&(r=o[1],a=o[3])}else a=n[3]?n[3].slice(1,-1):"";return this.options.pedantic&&(r=r.trim()),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(s)?r=r.slice(1):r=r.slice(1,-1)),ki(n,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:a&&a.replace(this.rules.inline.anyPunctuation,"$1")},n[0],this.lexer,this.rules)}}reflink(t,e){let n=t.charCodeAt(0);if(n!==91&&n!==33)return;let i;if((i=this.rules.inline.reflink.exec(t))||(i=this.rules.inline.nolink.exec(t))){let s=i[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&wi(t,i[1],s,this.rules))return;let l=e[Tt(i[2]||i[1],this.options.pedantic)];if(!l){let r=i[0].charAt(0);return{type:"text",raw:r,text:r}}return ki(i,l,i[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let i=this.rules.inline.emStrongLDelim.exec(t);if(!i||!i[1]&&!i[2]&&!i[3]&&!i[4])return;let s=i[0][0],l=n===s,r=e.length-t.length,a=r;for(;!this.options.pedantic&&a>0&&e[a-1]===s;)a--;let o=[...e.slice(Math.max(0,a-2),a)].at(-1)??"",c=o==="*"||o==="_"||!!this.rules.inline.punctuation.exec(o);a<r&&(n=o);let d=a<r?c:n==="*"||n==="_"||!!this.rules.inline.punctuation.exec(n);if(i[4]&&n.match(this.rules.other.unicodeAlphaNumeric))return;let m=i[1]||i[3]||"";if(!m||!n||d){let h=[...i[0]].length-1,u,f,b=h,x=0,k=r-a+h,y=!this.options.pedantic&&!!o.trim()&&(!!m||s==="*"&&!c);if(s!=="*"&&s!=="_")return;let B=s==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd,T=gi(this,e,s),I=e.length-t.length+h;if(T<I)return;e=e.slice(-1*t.length+h);let M=T-I;for(B.lastIndex=0;(i=B.exec(e))!==null&&!(i.index>M);){if(u=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!u)continue;f=[...u].length;let $=f>b-h;if(i[3]||i[4]){b+=f;continue}else if((i[5]||i[6]||y&&$)&&k%3&&!((k+f)%3)){if(l&&(i[5]||i[6]))break;x+=f;continue}if(b-=f,b>0)continue;f=Math.min(f,f+b+x);let E=[...i[0]][0].length,A=t.slice(0,h+i.index+E+f);if(Math.min(h,f)%2){let j=A.slice(1,-1);return{type:"em",raw:A,text:j,tokens:this.lexer.inlineTokens(j)}}let L=A.slice(2,-2);return{type:"strong",raw:A,text:L,tokens:this.lexer.inlineTokens(L)}}}}codespan(t){if(t.charCodeAt(0)!==96)return;let e=this.rules.inline.code.exec(t);if(e){let n=e[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(n),s=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return i&&s&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:e[0],text:n}}}br(t){let e=t.charCodeAt(0);if(e!==32&&e!==92&&e!==10)return;let n=this.rules.inline.br.exec(t);if(n)return{type:"br",raw:n[0]}}del(t,e,n=""){if(t.charCodeAt(0)!==126)return;let i=this.rules.inline.delLDelim.exec(t);if(i&&(!i[1]||!n||this.rules.inline.punctuation.exec(n))){let s=[...i[0]].length-1,l,r,a=s,o=this.rules.inline.delRDelim,c=vi(this,e),d=e.length-t.length+s;if(c<d)return;e=e.slice(-1*t.length+s);let m=c-d;for(o.lastIndex=0;(i=o.exec(e))!==null&&!(i.index>m);){if(l=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!l||(r=[...l].length,r!==s))continue;if(i[3]||i[4]){a+=r;continue}if(a-=r,a>0)continue;r=Math.min(r,r+a);let h=[...i[0]][0].length,u=t.slice(0,s+i.index+h+r),f=u.slice(s,-s);return{type:"del",raw:u,text:f,tokens:this.lexer.inlineTokens(f)}}}}autolink(t){if(t.charCodeAt(0)!==60)return;let e=this.rules.inline.autolink.exec(t);if(e){let n,i;return e[2]==="@"?(n=e[1],i="mailto:"+n):(n=e[1],i=n),{type:"link",raw:e[0],text:n,href:i,autolink:!0,tokens:[{type:"text",raw:n,text:n}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let n,i;if(e[2]==="@")n=e[0],i="mailto:"+n;else{let s;do s=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(s!==e[0]);n=e[0],e[1]==="www."?i="http://"+e[0]:i=e[0]}return{type:"link",raw:e[0],text:n,href:i,autolink:!0,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let n=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:n?e[0]:Hr(e[0]),escaped:n}}}},ie=class _n{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Ie,this.options.tokenizer=this.options.tokenizer||new Me,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,linkParenPossible:!0,top:!0,inBlockquote:!1};let n={other:H,block:Lt.normal,inline:nt.normal};this.options.pedantic?(n.block=Lt.pedantic,n.inline=nt.pedantic):this.options.gfm&&(n.block=Lt.gfm,this.options.breaks?n.inline=nt.breaks:n.inline=nt.gfm),this.tokenizer.rules=n}static get rules(){return{block:Lt,inline:nt}}static lex(e,n){return new _n(n).lex(e)}static lexInline(e,n){let i=new _n(n);return e.includes("\r")&&(e=e.replace(H.carriageReturn,`
50
+ `)),i.inlineTokens(e)}lex(e){e=e.replace(H.carriageReturn,`
51
+ `),this.blockTokens(e,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let i=this.inlineQueue[n];this.state.inRawBlock=!1,this.inlineTokens(i.src,i.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,n=[],i=!1){this.tokenizer.lexer=this;let s=this.state.lastToken;this.options.pedantic&&(e=e.replace(H.tabCharGlobal," ").replace(H.spaceLine,""));let l=1/0,r,a=this.options.gfm&&!this.options.pedantic&&this.tokenizer.paragraph===Me.prototype.paragraph;for(;e;){if(e.length<l)l=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}this.state.lastToken=n.at(-1);let o;if(this.options.extensions?.block?.some(d=>(o=d.call({lexer:this},e,n))?(e=e.substring(o.raw.length),n.push(o),!0):!1))continue;if(o=this.tokenizer.space(e)){e=e.substring(o.raw.length);let d=n.at(-1);o.raw.length===1&&d!==void 0?d.raw+=`
52
+ `:n.push(o);continue}if(o=this.tokenizer.code(e)){e=e.substring(o.raw.length);let d=n.at(-1);d?.type==="paragraph"||d?.type==="text"?(d.raw+=(d.raw.endsWith(`
53
+ `)?"":`
54
+ `)+o.raw,d.text+=`
55
+ `+o.text,this.inlineQueue.at(-1).src=d.text):n.push(o);continue}if(o=this.tokenizer.fences(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.heading(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.hr(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.blockquote(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.list(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.html(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.def(e)){e=e.substring(o.raw.length);let d=n.at(-1);d?.type==="paragraph"||d?.type==="text"?(d.raw+=(d.raw.endsWith(`
56
+ `)?"":`
57
+ `)+o.raw,d.text+=`
58
+ `+o.raw,this.inlineQueue.at(-1).src=d.text):(this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title}),n.push(o));continue}if(o=this.tokenizer.table(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.lheading(e)){e=e.substring(o.raw.length),n.push(o);continue}let c=e;if(this.options.extensions?.startBlock){let d=1/0,m=e.slice(1),h;this.options.extensions.startBlock.forEach(u=>{h=u.call({lexer:this},m),typeof h=="number"&&h>=0&&(d=Math.min(d,h))}),d<1/0&&d>=0&&(c=e.substring(0,d+1))}if(this.state.top&&(o=this.tokenizer.paragraph(c))){let d=n.at(-1);(i||d===r&&a)&&d?.type==="paragraph"?(d.raw+=(d.raw.endsWith(`
59
+ `)?"":`
60
+ `)+o.raw,d.text+=`
61
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=d.text,r=d):(n.push(o),r=o),i=c.length!==e.length,e=e.substring(o.raw.length);continue}if(o=this.tokenizer.text(e)){e=e.substring(o.raw.length);let d=n.at(-1);d?.type==="text"?(d.raw+=(d.raw.endsWith(`
62
+ `)?"":`
63
+ `)+o.raw,d.text+=`
64
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=d.text):n.push(o);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,this.state.lastToken=s,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}linkInText(e){if(!e.includes("["))return!1;let n=this.tokenizer.rules.inline.link;for(let i of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(n.test(i[0])&&e.charAt(i.index-1)!=="!")return!0;for(let i of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let s=i[0],l=s.lastIndexOf("[");if(!(s.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,Tt(s.slice(l+1,-1),this.options.pedantic)))&&!(l>1&&this.linkInText(s.slice(1,l-1))))return!0}return!1}inlineTokens(e,n=[]){this.tokenizer.lexer=this;let i=this.state.linkParenPossible;this.state.linkParenPossible=e.includes(")");try{return this.#t(e,n)}finally{this.state.linkParenPossible=i}}#t(e,n){let i=e.includes("*")||e.includes("_")||e.includes("~"),s=i||this.options.hooks?.emStrongMask||this.tokenizer.emStrong!==Me.prototype.emStrong||this.tokenizer.del!==Me.prototype.del?this.#i(e):e;if(!i)return this.#e(e,s,n);_r(this.tokenizer,s);try{return this.#e(e,s,n)}finally{Fr(this.tokenizer)}}#e(e,n,i){let s=!1,l="",r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}s||(l=""),s=!1;let a;if(this.options.extensions?.inline?.some(d=>(a=d.call({lexer:this},e,i))?(e=e.substring(a.raw.length),i.push(a),!0):!1))continue;if(a=this.tokenizer.escape(e)){e=e.substring(a.raw.length),i.push(a);continue}if(a=this.tokenizer.tag(e)){e=e.substring(a.raw.length),i.push(a);continue}if(a=this.tokenizer.link(e)){e=e.substring(a.raw.length),i.push(a);continue}if(a=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(a.raw.length);let d=i.at(-1);a.type==="text"&&d?.type==="text"?(d.raw+=a.raw,d.text+=a.text):i.push(a);continue}let o=e[0];if(o==="*"||o==="_"){let d=n.length-e.length;if(gi(this.tokenizer,n,o)<=d){let m=1;for(;m<e.length&&e.charCodeAt(m)===o.charCodeAt(0);)m++;let h=e.substring(0,m),u=i.at(-1);u?.type==="text"&&!u.escaped?(u.raw+=h,u.text+=h):i.push({type:"text",raw:h,text:h,escaped:!1}),e=e.substring(m),l=o,s=!0;continue}}else if(o==="~"){let d=n.length-e.length;if(vi(this.tokenizer,n)<=d){let m=1;for(;m<e.length&&e.charCodeAt(m)===126;)m++;let h=e.substring(0,m),u=i.at(-1);u?.type==="text"&&!u.escaped?(u.raw+=h,u.text+=h):i.push({type:"text",raw:h,text:h,escaped:!1}),e=e.substring(m),l=o,s=!0;continue}}if(a=this.tokenizer.emStrong(e,n,l)){e=e.substring(a.raw.length),i.push(a);continue}if(a=this.tokenizer.codespan(e)){e=e.substring(a.raw.length),i.push(a);continue}if(a=this.tokenizer.br(e)){e=e.substring(a.raw.length),i.push(a);continue}if(a=this.tokenizer.del(e,n,l)){e=e.substring(a.raw.length),i.push(a);continue}if(a=this.tokenizer.autolink(e)){e=e.substring(a.raw.length),i.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(e))){e=e.substring(a.raw.length),i.push(a);continue}let c=e;if(this.options.extensions?.startInline){let d=1/0,m=e.slice(1),h;this.options.extensions.startInline.forEach(u=>{h=u.call({lexer:this},m),typeof h=="number"&&h>=0&&(d=Math.min(d,h))}),d<1/0&&d>=0&&(c=e.substring(0,d+1))}if(a=this.tokenizer.inlineText(c)){e=e.substring(a.raw.length),a.raw.slice(-1)!=="_"&&(l=a.raw.slice(-1)),s=!0;let d=i.at(-1);d?.type==="text"?(d.raw+=a.raw,d.text+=a.text):i.push(a);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return i}#n(e){let{blockSkip:n,tag:i,autolink:s}=this.tokenizer.rules.inline,l="",r=0,a;for(n.lastIndex=0;a=n.exec(e);){let o=a.index+(a[2]?a[2].length:0),c=a.index+a[0].length;if(e.charAt(o)==="<"){let d=e.slice(o),m=i.exec(d)||s.exec(d);if(!m){n.lastIndex=o+1;continue}c=o+m[0].length,n.lastIndex=c}l+=e.slice(r,o)+"["+"a".repeat(c-o-2)+"]",r=c}return l+e.slice(r)}#i(e){let n=e;if(this.tokens.links&&e.includes("[")){let i=this.tokenizer.rules.inline.reflinkSearch,s=l=>{let r=l.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,Tt(l.slice(r+1,-1),this.options.pedantic)))return l;if(r>1&&l.charAt(0)!=="!"){let a=l.slice(1,r-1);if(this.linkInText(a))return"["+a.replace(i,s)+"]["+"a".repeat(l.length-r-2)+"]"}return"["+"a".repeat(l.length-2)+"]"};n=n.replace(i,s)}return n=n.replace(this.tokenizer.rules.inline.anyPunctuationOutsideCode,(i,s,l)=>l?"+".repeat(i.length):s?s+i.slice(s.length,-s.length).replace(/`/g,"+")+s:i),n=this.#n(n),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n,n}infiniteLoopError(e){let n="Infinite loop on byte: "+e;if(this.options.silent)console.error(n);else throw new Error(n)}};function hn(t,e=!1){let n;for(let i=0;i<t.length;i++){let s=t[i],l=s;if(s.type==="codespan"||s.type==="escape"||e&&s.type==="text"){let r=Z(s.text,!0);r!==s.text&&(l={...s,text:r})}else if(s.type==="link"&&s.autolink){let r=Z(s.text,!0),a=s.tokens,o=a&&(a.length===1&&a[0].type==="text"&&a[0].text===s.text?r!==s.text?[{...a[0],text:r}]:a:hn(a,!0));(r!==s.text||o!==a)&&(l=o!==a?{...s,text:r,tokens:o}:{...s,text:r})}else if("tokens"in s&&s.tokens){let r=hn(s.tokens,e);r!==s.tokens&&(l={...s,tokens:r})}l!==s?(n||(n=t.slice(0,i)),n.push(l)):n&&n.push(s)}return n||t}var It=class{options;parser;constructor(t){this.options=t||Ie}space(t){return""}code({text:t,lang:e,escaped:n}){let i=(e||"").trim().match(H.notSpaceStart)?.[0],s=t?t.replace(H.endingNewline,"")+`
65
+ `:"";return i?'<pre><code class="language-'+Z(i)+'">'+(n?s:Z(s,!0))+`</code></pre>
66
+ `:"<pre><code>"+(n?s:Z(s,!0))+`</code></pre>
67
+ `}blockquote({tokens:t}){return`<blockquote>
68
+ ${this.parser.parse(t)}</blockquote>
69
+ `}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`<h${e}>${this.parser.parseInline(t)}</h${e}>
70
+ `}hr(t){return`<hr>
71
+ `}list(t){let e=t.ordered,n=t.start,i="";for(let r=0;r<t.items.length;r++){let a=t.items[r];i+=this.listitem(a)}let s=e?"ol":"ul",l=e&&n!==1?' start="'+n+'"':"";return"<"+s+l+`>
72
+ `+i+"</"+s+`>
73
+ `}listitem(t){return`<li>${this.parser.parse(t.tokens)}</li>
74
+ `}checkbox({checked:t}){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:t}){return`<p>${this.parser.parseInline(t)}</p>
75
+ `}table(t){let e="",n="";for(let s=0;s<t.header.length;s++)n+=this.tablecell(t.header[s]);e+=this.tablerow({text:n});let i="";for(let s=0;s<t.rows.length;s++){let l=t.rows[s];n="";for(let r=0;r<l.length;r++)n+=this.tablecell(l[r]);i+=this.tablerow({text:n})}return i&&(i=`<tbody>${i}</tbody>`),`<table>
76
+ <thead>
77
+ `+e+`</thead>
78
+ `+i+`</table>
79
+ `}tablerow({text:t}){return`<tr>
80
+ ${t}</tr>
81
+ `}tablecell(t){let e=this.parser.parseInline(t.tokens),n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
82
+ `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${Z(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,text:n,tokens:i,autolink:s}){let l=s?Z(n,!0):this.parser.parseInline(i),r=hi(t);if(r===null)return l;t=Z(r,s);let a='<a href="'+t+'"';return e&&(a+=' title="'+Z(e)+'"'),a+=">"+l+"</a>",a}image({href:t,title:e,text:n,tokens:i}){i&&(n=this.parser.parseInline(hn(i),this.parser.textRenderer));let s=hi(t);if(s===null)return Z(n);t=s;let l=`<img src="${Z(t)}" alt="${Z(n)}"`;return e&&(l+=` title="${Z(e)}"`),l+=">",l}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:Z(t.text)}},mn=class{parser;strong({text:t,tokens:e}){return e?this.parser.parseInline(e,this):t}em({text:t,tokens:e}){return e?this.parser.parseInline(e,this):t}codespan({text:t}){return t}del({text:t,tokens:e}){return e?this.parser.parseInline(e,this):t}html({text:t}){return t}text({text:t}){return t}link({text:t,tokens:e}){return e?this.parser.parseInline(e,this):t}image({text:t,tokens:e}){return e?this.parser.parseInline(e,this):t}br(){return`
83
+ `}checkbox({raw:t}){return t}},se=class Fn{options;renderer;textRenderer;constructor(e){this.options=e||Ie,this.options.renderer=this.options.renderer||new It,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new mn,this.textRenderer.parser=this}static parse(e,n){return new Fn(n).parse(e)}static parseInline(e,n){return new Fn(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let i=0;i<e.length;i++){let s=e[i],l=this.options.extensions?.renderers;if(l&&Object.hasOwn(l,s.type)&&l[s.type]){let a=s,o=l[a.type].call({parser:this},a);if(o!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(a.type)){n+=o===!1?"":o??"";continue}}let r=s;switch(r.type){case"space":{n+=this.renderer.space(r);break}case"hr":{n+=this.renderer.hr(r);break}case"heading":{n+=this.renderer.heading(r);break}case"code":{n+=this.renderer.code(r);break}case"table":{n+=this.renderer.table(r);break}case"blockquote":{n+=this.renderer.blockquote(r);break}case"list":{n+=this.renderer.list(r);break}case"checkbox":{n+=this.renderer.checkbox(r);break}case"html":{n+=this.renderer.html(r);break}case"def":{n+=this.renderer.def(r);break}case"paragraph":{n+=this.renderer.paragraph(r);break}case"text":{n+=this.renderer.text(r);break}default:{let a='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let i="";for(let s=0;s<e.length;s++){let l=e[s],r=this.options.extensions?.renderers;if(r&&Object.hasOwn(r,l.type)&&r[l.type]){let o=r[l.type].call({parser:this},l);if(o!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(l.type)){i+=o===!1?"":o??"";continue}}let a=l;switch(a.type){case"escape":{i+=n.text(a);break}case"html":{i+=n.html(a);break}case"link":{i+=n.link(a);break}case"image":{i+=n.image(a);break}case"checkbox":{i+=n.checkbox(a);break}case"strong":{i+=n.strong(a);break}case"em":{i+=n.em(a);break}case"codespan":{i+=n.codespan(a);break}case"br":{i+=n.br(a);break}case"del":{i+=n.del(a);break}case"text":{i+=n.text(a);break}default:{let o='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return i}},st=class{options;block;constructor(t){this.options=t||Ie}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(t=this.block){return t?ie.lex:ie.lexInline}provideParser(t=this.block){return t?se.parse:se.parseInline}};function Ee(t,e){if(Array.isArray(e))for(let n=0;n<e.length;n++)t.push(e[n]);else t.push(e)}var Vr=class{defaults=tn();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=se;Renderer=It;TextRenderer=mn;Lexer=ie;Tokenizer=Me;Hooks=st;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let i of t)switch(Ee(n,e.call(this,i)),i.type){case"table":{let s=i;for(let l of s.header)Ee(n,this.walkTokens(l.tokens,e));for(let l of s.rows)for(let r of l)Ee(n,this.walkTokens(r.tokens,e));break}case"list":{let s=i;Ee(n,this.walkTokens(s.items,e));break}default:{let s=i;this.defaults.extensions?.childTokens?.[s.type]?this.defaults.extensions.childTokens[s.type].forEach(l=>{if(s[l]){let r=s[l].flat(1/0);Ee(n,this.walkTokens(r,e))}}):s.tokens&&Ee(n,this.walkTokens(s.tokens,e))}}return n}use(...t){let e=this.defaults.extensions||{renderers:Object.create(null),childTokens:Object.create(null)};return t.forEach(n=>{let i={...n};if(i.async=this.defaults.async||i.async||!1,n.extensions&&(n.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s&&s.renderer){let l=s.renderer,r=e.renderers[s.name];r?e.renderers[s.name]=function(...a){let o=l.apply(this,a);return o===!1&&(o=r.apply(this,a)),o}:e.renderers[s.name]=l}if("tokenizer"in s&&s.tokenizer){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let l=e[s.level];l?l.unshift(s.tokenizer):e[s.level]=[s.tokenizer],s.start&&(s.level==="block"?e.startBlock?e.startBlock.push(s.start):e.startBlock=[s.start]:s.level==="inline"&&(e.startInline?e.startInline.push(s.start):e.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(e.childTokens[s.name]=s.childTokens)}),i.extensions=e),n.renderer){let s=this.defaults.renderer||new It(this.defaults);for(let l in n.renderer){if(!(l in s))throw new Error(`renderer '${l}' does not exist`);if(["options","parser"].includes(l))continue;let r=l,a=n.renderer[r];if(a===void 0)continue;let o=s[r];s[r]=(...c)=>{let d=a.apply(s,c);return d===!1&&(d=o.apply(s,c)),d===!1?"":d??""}}i.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new Me(this.defaults);for(let l in n.tokenizer){if(!(l in s))throw new Error(`tokenizer '${l}' does not exist`);if(["options","rules","lexer"].includes(l))continue;let r=l,a=n.tokenizer[r];if(a===void 0)continue;let o=s[r];s[r]=(...c)=>{let d=a.apply(s,c);return d===!1&&(d=o.apply(s,c)),d}}i.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new st;for(let l in n.hooks){if(!(l in s))throw new Error(`hook '${l}' does not exist`);if(["options","block"].includes(l))continue;let r=l,a=n.hooks[r];if(a===void 0)continue;let o=s[r];st.passThroughHooks.has(l)?s[r]=c=>{if(s.options.async&&st.passThroughHooksRespectAsync.has(l))return(async()=>{let m=await a.call(s,c);return o.call(s,m)})();let d=a.call(s,c);return o.call(s,d)}:s[r]=(...c)=>{if(s.options.async)return(async()=>{let m=await a.apply(s,c);return m===!1&&(m=await o.apply(s,c)),m})();let d=a.apply(s,c);return d===!1&&(d=o.apply(s,c)),d}}i.hooks=s}if(n.walkTokens){let s=this.defaults.walkTokens,l=n.walkTokens;i.walkTokens=function(r){let a=[];return Ee(a,l.call(this,r)),s&&Ee(a,s.call(this,r)),a}}this.defaults={...this.defaults,...i}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return ie.lex(t,e??this.defaults)}parser(t,e){return se.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let i={...n},s={...this.defaults,...i},l=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&i.async===!1)return l(new 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 e>"u"||e===null)return l(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return l(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=t),s.async)return(async()=>{let r=s.hooks?await s.hooks.preprocess(e):e,a=await(s.hooks?await s.hooks.provideLexer(t):t?ie.lex:ie.lexInline)(r,s),o=s.hooks?await s.hooks.processAllTokens(a):a;s.walkTokens&&await Promise.all(this.walkTokens(o,s.walkTokens));let c=await(s.hooks?await s.hooks.provideParser(t):t?se.parse:se.parseInline)(o,s);return s.hooks?await s.hooks.postprocess(c):c})().catch(l);try{s.hooks&&(e=s.hooks.preprocess(e));let r=(s.hooks?s.hooks.provideLexer(t):t?ie.lex:ie.lexInline)(e,s);s.hooks&&(r=s.hooks.processAllTokens(r)),s.walkTokens&&this.walkTokens(r,s.walkTokens);let a=(s.hooks?s.hooks.provideParser(t):t?se.parse:se.parseInline)(r,s);return s.hooks&&(a=s.hooks.postprocess(a)),a}catch(r){return l(r)}}}onError(t,e){return n=>{let i=n instanceof Error?n:new Error(String(n));if(i.message+=`
84
+ Please report this to https://github.com/markedjs/marked.`,t){let s="<p>An error occurred:</p><pre>"+Z(i.message+"",!0)+"</pre>";return e?Promise.resolve(s):s}if(e)return Promise.reject(i);throw i}}},ze=new Vr;function R(t,e){return ze.parse(t,e)}function Wr(t,e){return ze.parseInline(t,e)}R.options=R.setOptions=function(t){return ze.setOptions(t),R.defaults=ze.defaults,Qn(R.defaults),R},R.getDefaults=tn,R.defaults=Ie;function Ur(...t){return ze.use(...t),R.defaults=ze.defaults,Qn(R.defaults),R}R.use=Ur,R.walkTokens=function(t,e){return ze.walkTokens(t,e)},R.parseInline=Wr,R.Parser=se,R.parser=se.parse,R.Renderer=It,R.TextRenderer=mn,R.Lexer=ie,R.lexer=ie.lex,R.Tokenizer=Me,R.Hooks=st,R.parse=R;var Yl=R.options,Xl=R.setOptions,Kl=R.walkTokens,Ql=R.parseInline,Gl=se.parse,ea=ie.lex,Jr=new Set(["http:","https:","mailto:"]);function yi(t){let e=(t??"").trim();if(!e||e.startsWith("//"))return null;if(!/^[a-z][a-z0-9+.-]*:/i.test(e))return e;try{return Jr.has(new URL(e).protocol)?e:null}catch{return null}}var xi=t=>/^[a-z][a-z0-9+.-]*:/i.test(t)&&!t.startsWith("mailto:"),Ei=4e5,Zr=200;function Yr(t){let e=new Map,n=0;function i(m,h){let u=m.length+Zr;if(!(u>Ei/4)){e.set(m,{fragment:h,chars:u}),n+=u;for(let f of e.keys()){if(n<=Ei)break;let b=e.get(f);b&&(e.delete(f),n-=b.chars)}}}function s(m,h){h.split(`
85
+ `).forEach((u,f)=>{f>0&&m.appendChild(t.createElement("br")),u&&m.appendChild(t.createTextNode(u))})}function l(m,h){switch(h.type){case"text":{if(h.tokens?.length){for(let u of h.tokens)l(m,u);return}s(m,h.text??h.raw??"");return}case"escape":m.appendChild(t.createTextNode(h.text??""));return;case"strong":case"em":case"del":{let u=t.createElement(h.type==="strong"?"strong":h.type==="em"?"em":"del");for(let f of h.tokens??[])l(u,f);m.appendChild(u);return}case"codespan":{let u=t.createElement("code");u.textContent=h.text??"",m.appendChild(u);return}case"br":m.appendChild(t.createElement("br"));return;case"link":{let u=h.tokens??[],f=yi(h.href);if(!f){for(let x of u)l(m,x);return}let b=t.createElement("a");b.href=f,b.rel="noreferrer noopener",h.title&&(b.title=h.title),xi(f)&&(b.target="_blank");for(let x of u)l(b,x);m.appendChild(b);return}case"image":{let u=yi(h.href),f=h.text?.trim()||h.href||"image";if(!u){m.appendChild(t.createTextNode(f));return}let b=t.createElement("a");b.href=u,b.textContent=f,b.rel="noreferrer noopener",xi(u)&&(b.target="_blank"),m.appendChild(b);return}case"html":m.appendChild(t.createTextNode(h.raw??h.text??""));return;default:if(h.tokens?.length){for(let u of h.tokens)l(m,u);return}s(m,h.text??h.raw??"")}}function r(m){let h=t.createElement("div");h.className="bv-code";let u=t.createElement("div");u.className="bv-code-head";let f=(m.lang??"").trim().split(/\s+/)[0]??"",b=t.createElement("span");b.className="bv-code-lang",b.textContent=f||"text";let x=t.createElement("button");x.type="button",x.className="bv-code-copy",x.textContent="Copy";let k=m.text??"";x.addEventListener("click",()=>{let T=navigator.clipboard?.writeText(k);T&&T.then(()=>{x.textContent="Copied",window.setTimeout(()=>{x.textContent="Copy"},1200)},()=>{})}),u.append(b,x);let y=t.createElement("pre"),B=t.createElement("code");return f&&(B.className=`language-${f}`),B.textContent=k,y.appendChild(B),h.append(u,y),h}function a(m,h){let u=t.createElement("div");u.className="bv-table";let f=t.createElement("table"),b=t.createElement("thead"),x=t.createElement("tr"),k=h.align??[],y=(T,I,M)=>{let $=t.createElement(T);k[M]&&($.style.textAlign=k[M]);for(let E of I.tokens??[])l($,E);return $};(h.header??[]).forEach((T,I)=>x.appendChild(y("th",T,I))),b.appendChild(x);let B=t.createElement("tbody");for(let T of h.rows??[]){let I=t.createElement("tr");T.forEach((M,$)=>I.appendChild(y("td",M,$))),B.appendChild(I)}f.append(b,B),u.appendChild(f),m.appendChild(u)}function o(m,h){let u=t.createElement("li");if(h.task){let f=t.createElement("input");f.type="checkbox",f.disabled=!0,f.checked=h.checked===!0,u.appendChild(f)}for(let f of h.tokens??[])if(f.type==="text")l(u,f);else if(f.type==="paragraph")for(let b of f.tokens??[])l(u,b);else c(u,f);m.appendChild(u)}function c(m,h){switch(h.type){case"space":return;case"heading":{let u=Math.min(Math.max(h.depth??1,1),6),f=t.createElement(`h${u}`);for(let b of h.tokens??[])l(f,b);m.appendChild(f);return}case"paragraph":{let u=t.createElement("p");for(let f of h.tokens??[])l(u,f);m.appendChild(u);return}case"text":l(m,h);return;case"code":m.appendChild(r(h));return;case"blockquote":{let u=t.createElement("blockquote");for(let f of h.tokens??[])c(u,f);m.appendChild(u);return}case"list":{let u=h.items??h.tokens??[];if(h.ordered){let f=t.createElement("ol");typeof h.start=="number"&&h.start!==1&&(f.start=h.start);for(let b of u)o(f,b);m.appendChild(f)}else{let f=t.createElement("ul");for(let b of u)o(f,b);m.appendChild(f)}return}case"table":a(m,h);return;case"hr":m.appendChild(t.createElement("hr"));return;case"html":case"escape":m.appendChild(t.createTextNode(h.raw??h.text??""));return;default:if(h.tokens?.length){for(let u of h.tokens)c(m,u);return}h.text&&m.appendChild(t.createTextNode(h.text))}}function d(m){let h=t.createDocumentFragment();try{let u=R.lexer(m);for(let f of u)c(h,f)}catch{h.replaceChildren(t.createTextNode(m))}return h}return m=>{let h=e.get(m);if(h)return e.delete(m),e.set(m,h),h.fragment.cloneNode(!0);let u=d(m);return i(m,u),u.cloneNode(!0)}}var fn=Yr(document),w={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1},Se=[],me=!0,Xr=!1,Si=0;function gn(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function O(t,e){let n=await fetch(t,{...e,headers:{"content-type":"application/json",Authorization:`Bearer ${gn()}`,...e?.headers||{}}}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok)throw new Error(s&&s.error||`HTTP ${n.status}`);return s}function g(t,e,n){let i=document.createElement(t);return e&&(i.className=e),n!==void 0&&(i.textContent=n),i}function Kr(t){return t==="running"?"var(--panel-success)":t==="waiting_approval"||t==="waiting_input"?"#e0a23c":t==="failed"?"var(--panel-danger, #e5534b)":t==="completed"?"var(--panel-accent)":"var(--panel-muted)"}function Ce(){vn||(vn=requestAnimationFrame(()=>{vn=0,Qr()}))}var vn=0,$t="";function Qr(){let t=document.getElementById("bots-view");if(!t)return;let e=window.visualViewport,n=window.matchMedia("(max-width: 640px)").matches,i=!document.querySelector(".sidebar")?.classList.contains("collapsed");if(w.activeId&&e&&n&&!i){let s=document.querySelector(".fixed-header"),l=s?Math.round(s.getBoundingClientRect().height):0,r=Math.round(e.offsetTop)+l,a=Math.round(e.offsetLeft),o=Math.round(e.width),c=Math.max(120,Math.round(e.height)-l),d=`fixed|${r}|${a}|${o}|${c}`;if(d===$t)return;$t=d,t.style.position="fixed",t.style.top=`${r}px`,t.style.left=`${a}px`,t.style.width=`${o}px`,t.style.height=`${c}px`,t.style.right="auto",t.style.bottom="auto"}else{if($t==="")return;$t="",t.style.position="",t.style.top="",t.style.left="",t.style.width="",t.style.height="",t.style.right="",t.style.bottom=""}}window.visualViewport?.addEventListener("resize",Ce),window.visualViewport?.addEventListener("scroll",Ce),window.addEventListener("resize",Ce),document.addEventListener("click",Ce);var Ci=document.querySelector(".sidebar");Ci&&new MutationObserver(Ce).observe(Ci,{attributes:!0,attributeFilter:["class"]}),window.__syncBotsViewport=Ce;function Bt(){let t=w.approvals.length,e=document.getElementById("bots-inbox-badge");e&&(e.style.display=t?"inline-block":"none",e.textContent=String(t));let n=document.getElementById("bv-inbox-count");n&&(n.textContent=t?`(${t})`:""),window.__botsSnapshot=w.bots,window.__refreshSidebar?.()}function Gr(){let t=document.getElementById("set-bot-templates"),e=document.getElementById("set-bot-new"),n=document.getElementById("set-bot-inbox"),i=()=>{document.getElementById("settings-popover")?.classList.remove("open"),document.getElementById("settings-backdrop")?.classList.remove("open")};t?.addEventListener("click",()=>{i(),rt()}),e?.addEventListener("click",()=>{i(),ul()}),n?.addEventListener("click",()=>{i(),Tn()})}function el(){let t=g("div","bots-view");t.id="bots-view",t.hidden=!0;let e=g("div","bots-view-head"),n=g("div","bv-title"),i=g("span","bots-dot");i.id="bv-dot";let s=g("span","bv-title-text");s.id="bv-title";let l=g("span","bv-status");l.id="bv-status",n.append(i,s,l);let r=g("div","bv-actions"),a=g("div","bv-mode"),o=g("button","bv-mode-btn");o.id="bv-mode-btn",o.type="button",o.title="\u5BA1\u6279\u6A21\u5F0F\uFF08\u70B9\u5F00\u770B\u8BF4\u660E\uFF09",o.innerHTML=`<span id="bv-mode-label"></span>${xe("chevron-down",'width="12" height="12"')}`;let c=g("div","bv-mode-menu");c.id="bv-mode-menu",c.hidden=!0;for(let[L,j,_]of[["supervised","\u9ED8\u8BA4","\u53EA\u8BFB\u5DE5\u5177\uFF08read/grep/find/ls\uFF09\u76F4\u63A5\u653E\u884C\uFF1Bbash\u3001edit\u3001write\u3001\u6269\u5C55/MCP \u5DE5\u5177\u4F1A\u95EE\u4F60"],["parent-supervised","\u76D1\u7BA1","\u5176\u4F59\u5DE5\u5177\u4EA4\u7ED9\u4E0A\u7EA7 bot \u51B3\u5B9A\uFF08\u5E26\u7406\u7531\uFF09\uFF1B\u4F60\u4ECD\u7136\u80FD\u770B\u5230\u5E76\u56DE\u7B54\uFF0C\u5148\u7B54\u5148\u5F97\uFF1B\u6CA1\u6709\u4E0A\u7EA7\u65F6\u56DE\u843D\u5230\u9ED8\u8BA4"],["full-access","\u5168\u653E\u884C","\u6240\u6709\u5DE5\u5177\u76F4\u63A5\u6267\u884C\uFF0C\u4E0D\u518D\u8BE2\u95EE\u3002\u6CE8\u610F\u8FD9\u4E0D\u662F\u6C99\u7BB1"]]){let de=g("button");de.dataset.mode=L,de.innerHTML=`<b>${j}</b><span>${_}</span>`,de.onclick=()=>{c.hidden=!0,tl(L)},c.appendChild(de)}o.onclick=L=>{L.stopPropagation(),c.hidden=!c.hidden},a.append(o,c),document.addEventListener("click",L=>{a.contains(L.target)||(c.hidden=!0)});let d=g("button","btn","Allow all");d.id="bv-allow-all",d.title="Approve every pending request for this bot",d.onclick=()=>{if(!w.activeId)return;let L=w.approvals.filter(j=>j.botId===w.activeId);Promise.all(L.map(j=>O(`/api/bots/${j.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:j.id,allow:!0})}))).finally(()=>void re(!0))};let m=g("button","btn","Needs you "),h=g("span");h.id="bv-inbox-count",m.appendChild(h),m.onclick=()=>void Tn();let u=g("button","btn","Resume");u.onclick=()=>void Ii(L=>O(`/api/bots/${L}/resume`,{method:"POST"}).then(()=>re(!0)));let f=g("button","btn danger","Stop");f.onclick=()=>void Ii(L=>O(`/api/bots/${L}/stop`,{method:"POST"}).then(()=>re(!0)));let b=g("button","btn","Delete");b.onclick=()=>{w.activeId&&confirm("Delete this bot and its session?")&&O(`/api/bots/${w.activeId}`,{method:"DELETE"}).then(()=>{kn(),re(!0)})};let x=g("button","btn");x.innerHTML=xe("close",'width="14" height="14"'),x.title="Close bot view",x.onclick=()=>kn(),r.append(a,d,m,u,f,b,x),e.append(n,r);let k=g("div","bots-messages");k.id="bots-messages";let y=g("button","bv-jump");y.type="button",y.id="bv-jump",y.innerHTML=`${xe("chevron-down",'width="14" height="14"')}<span>Latest</span>`,y.title="Jump to the latest message",y.hidden=!0,y.onclick=()=>{me=!0,k.scrollTop=k.scrollHeight,y.hidden=!0};let B=()=>{me=k.scrollHeight-k.scrollTop-k.clientHeight<48,y.hidden=me};k.addEventListener("scroll",B,{passive:!0}),k.addEventListener("touchmove",()=>{me=!1,y.hidden=k.scrollHeight-k.clientHeight<1},{passive:!0}),k.addEventListener("wheel",()=>{me=!1},{passive:!0});let T=g("div","bots-composer-wrap"),I=g("div","bv-composer-error");I.id="bv-composer-error",I.hidden=!0;let M=g("div","bots-composer"),$=g("textarea");$.id="bots-input",$.rows=1,$.placeholder="Message the bot\u2026",$.spellcheck=!1;let E=window.matchMedia("(pointer: coarse)").matches;E||($.enterKeyHint="send"),$.onkeydown=L=>{L.key!=="Enter"||L.shiftKey||L.isComposing||E||L.keyCode===229||(L.preventDefault(),Ti())},$.oninput=()=>bn(null);let A=g("button","btn primary");A.id="bv-send",A.title="Send",A.setAttribute("aria-label","Send"),A.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V5M5 12l7-7 7 7"/></svg>',A.onclick=()=>void Ti(),M.append($,A),M.addEventListener("click",L=>{L.target?.closest("button")||document.activeElement!==$&&$.focus()}),T.append(I,M),t.append(e,k,y,T),document.querySelector(".main-area")?.appendChild(t),document.getElementById("bots-modal")||dl()}function bn(t){let e=document.getElementById("bv-composer-error");e&&(e.textContent=t??"",e.hidden=!t)}function Li(t){let e=document.getElementById("bv-send");e&&(e.disabled=t,e.setAttribute("aria-busy",t?"true":"false"),e.title=t?"Sending\u2026":"Send")}async function Ti(){let t=document.getElementById("bots-input");if(!t||!w.activeId||Xr||!t.value.trim())return;let e=w.activeId,n=t.value;bn(null),Li(!0);try{await O(`/api/bots/${e}/input`,{method:"POST",body:JSON.stringify({text:n})}),t.value===n&&(t.value=""),me=!0}catch(i){bn(i instanceof Error?i.message:String(i))}finally{Li(!1)}}function Ii(t){w.activeId&&t(w.activeId).catch(e=>qe({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)}))}function kn(){w.activeId=null,Se=[],me=!0,Ce();let t=document.getElementById("bots-view");t&&(t.hidden=!0);try{w.ws?.close()}catch{}w.ws=null,Bt();let e=document.getElementById("terminal-container"),n=document.getElementById("main-placeholder"),i=!!document.querySelector(".session-item.active:not(.bot-item)");e&&i?(e.style.display="",n&&(n.style.display="none")):n&&(n.style.display="")}async function $i(t){w.activeId=t,Se=[],me=!0;let e=document.getElementById("bv-jump");e&&(e.hidden=!0),window.__collapseSidebar?.(),Ce(),w.items.set(t,[]);let n=document.getElementById("bots-view");n&&(n.hidden=!1);let i=document.getElementById("main-placeholder");i&&(i.style.display="none");let s=document.getElementById("terminal-container");s&&(s.style.display="none");let l=document.getElementById("file-editor");l&&(l.style.display="none"),Bt(),Sn();try{w.ws?.close()}catch{}let r=location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(`${r}//${location.host}/ws/bots/${encodeURIComponent(t)}?token=${encodeURIComponent(gn())}`);w.ws=a,a.onmessage=o=>{try{Mi(JSON.parse(String(o.data)))}catch{}},a.onclose=()=>{w.activeId===t&&setTimeout(()=>{w.activeId===t&&re(!0)},1500)},await re(!0)}function wn(){return w.bots.find(t=>t.id===w.activeId)||null}function yn(){let t=wn();if(!t)return;let e=document.getElementById("bv-title"),n=document.getElementById("bv-status"),i=document.getElementById("bv-dot");e&&(e.textContent=t.title),n&&(n.textContent=`${t.status.replace(/_/g," ")} \xB7 ${t.templateId} \xB7 ${t.projectPath}`);let s=document.getElementById("bv-mode-label");s&&t.runtimeMode&&(s.textContent=Bi[t.runtimeMode]||t.runtimeMode);for(let a of document.querySelectorAll("#bv-mode-menu button"))a.classList.toggle("active",a.dataset.mode===t.runtimeMode);let l=document.getElementById("bv-allow-all"),r=w.approvals.filter(a=>a.botId===t.id).length;l&&(l.hidden=r===0,l.textContent=`Allow all (${r})`),i&&(i.style.background=Kr(t.status))}var Bi={supervised:"\u9ED8\u8BA4","parent-supervised":"\u76D1\u7BA1","full-access":"\u5168\u653E\u884C"};async function tl(t){if(w.activeId)try{await O(`/api/bots/${w.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:t})});let e=wn();e&&(e.runtimeMode=t),yn(),qe({kind:"notice",level:"info",text:`\u5BA1\u6279\u6A21\u5F0F\uFF1A${Bi[t]||t}`})}catch(e){qe({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)})}}function qe(t,e=w.activeId){if(!e)return;let n=w.items.get(e)||[];n.push(t),w.items.set(e,n),e===w.activeId&&Ae()}function Ae(){if(w.renderQueued)return;w.renderQueued=!0;let t=Math.max(0,60-(performance.now()-Si));window.setTimeout(()=>{w.renderQueued=!1,Si=performance.now(),Sn()},t)}function xn(t){switch(t.kind){case"assistant":return{text:t.text,thinking:t.thinking};case"tool":return{phase:t.phase,output:t.output,error:t.isError,durationMs:t.durationMs};case"approval":return{decided:t.decided,approvalState:t.approval.state};default:return{}}}function nl(t,e){return t.text!==e.text||t.thinking!==e.thinking||t.phase!==e.phase||t.output!==e.output||t.error!==e.error||t.durationMs!==e.durationMs||t.decided!==e.decided||t.approvalState!==e.approvalState}function En(t){if(t.kind==="user"){let e=g("div","bv-msg bv-user");return e.appendChild(fn(t.text)),e}if(t.kind==="assistant"){let e=g("div","bv-msg bv-assistant");if(t.thinking){let i=g("details","bv-thinking");i.appendChild(g("summary",void 0,"thinking")),i.appendChild(g("div",void 0,t.thinking)),e.appendChild(i)}let n=g("div","bv-text");return n.appendChild(fn(t.text)),e.appendChild(n),e}return t.kind==="tool"?sl(t):t.kind==="approval"?rl(t):g("div",`bv-notice bv-notice-${t.level}`,t.text)}function il(t,e){let n=t.querySelector("details.bv-thinking");if(e.thinking)if(n){let s=n.querySelector("div");s&&s.textContent!==e.thinking&&(s.textContent=e.thinking)}else{let s=g("details","bv-thinking");s.appendChild(g("summary",void 0,"thinking")),s.appendChild(g("div",void 0,e.thinking)),t.prepend(s)}else n&&n.remove();let i=t.querySelector(".bv-text");i&&i.replaceChildren(fn(e.text))}function Sn(){let t=document.getElementById("bots-messages");if(!t||!w.activeId||document.getElementById("bots-view")?.hidden)return;let e=w.items.get(w.activeId)||[],n=me;if(e.length<Se.length||e.some((i,s)=>Se[s]?.item!==i))t.textContent="",Se=e.map(i=>{let s=En(i);return t.appendChild(s),{item:i,snapshot:xn(i),node:s}});else{for(let i=Se.length;i<e.length;i++){let s=e[i],l=En(s);t.appendChild(l),Se.push({item:s,snapshot:xn(s),node:l})}for(let i=0;i<e.length;i++){let s=e[i],l=Se[i],r=xn(s);if(nl(l.snapshot,r)){if(s.kind==="assistant")il(l.node,s);else{let a=En(s);l.node.replaceWith(a),l.node=a}l.snapshot=r}}}n&&(t.scrollTop=t.scrollHeight)}function sl(t){let e=g("details","bv-tool");e.open=t.phase!=="end"||!!t.isError;let n=g("summary"),i=g("span","bv-tool-name",t.name);if(n.appendChild(i),t.phase!=="end"&&n.appendChild(g("span","bv-tool-phase",t.phase)),t.isError&&n.appendChild(g("span","bv-tool-error","error")),typeof t.durationMs=="number"&&n.appendChild(g("span","bv-tool-meta",`${Math.round(t.durationMs)}ms`)),e.appendChild(n),t.args!==void 0){let s=g("pre","bv-pre");s.textContent=typeof t.args=="string"?t.args:JSON.stringify(t.args,null,2),e.appendChild(s)}if(t.output){let s=g("pre","bv-pre bv-output");s.textContent=t.output,e.appendChild(s)}return e}function rl(t){let e=g("div","bv-approval"),n=t.approval;if(e.appendChild(g("div","bv-approval-title",n.title)),n.message&&e.appendChild(g("pre","bv-pre",n.message)),t.decided)return e.appendChild(g("div","bv-approval-decided",t.decided==="allowed"?"Allowed":"Denied")),e;let i=g("input","bv-reason");i.placeholder="reason (optional)";let s=g("div","bv-approval-actions"),l=g("button","btn primary","Allow"),r=g("button","btn",n.method==="confirm"&&/^Allow (.+?)\?$/.test(n.title)?`Always allow ${/^Allow (.+?)\?$/.exec(n.title)?.[1]}`:"Always allow");r.hidden=n.method!=="confirm";let a=g("button","btn danger","Deny"),o=async(c,d=!1)=>{try{await O(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:c,always:d,reason:i.value||void 0})}),t.decided=c?"allowed":"denied",Ae(),re(!0)}catch(m){qe({kind:"notice",level:"error",text:m instanceof Error?m.message:String(m)})}};return l.onclick=()=>void o(!0),r.onclick=()=>void o(!0,!0),a.onclick=()=>void o(!1),s.append(i,l,r,a),e.appendChild(s),e}function Mi(t){let e=String(t.type||""),n=w.activeId;if(!n)return;let i=w.items.get(n)||[];if(e==="snapshot")w.items.set(n,[]);else if(e==="user")me=!0,qe({kind:"user",text:String(t.text||"")});else if(e==="status"){let s=wn();s&&(s.status=String(t.status||s.status)),yn(),ol()}else if(e==="message"){let s=t.message;if(!s||String(s.role||"")!=="assistant")return;let l=ll(s),r=al(s),a=i[i.length-1];a&&a.kind==="assistant"?(a.text=l||a.text,a.thinking=r||a.thinking):i.push({kind:"assistant",text:l,thinking:r}),w.items.set(n,i),Ae()}else if(e==="delta"){let s=String(t.kind||""),l=String(t.delta||""),r=i[i.length-1];(!r||r.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),r=i[i.length-1]),r.kind==="assistant"&&(s==="text"?r.text+=l:s==="thinking"&&(r.thinking+=l)),w.items.set(n,i),Ae()}else if(e==="tool"){let s=String(t.callId||""),l=i.find(a=>a.kind==="tool"&&a.callId===s),r=String(t.phase||"start");l?(l.phase=r,r==="update"&&t.output&&(l.output=String(t.output)),r==="end"&&(t.output&&(l.output=String(t.output)),l.isError=t.isError===!0,typeof t.durationMs=="number"&&(l.durationMs=t.durationMs))):i.push({kind:"tool",callId:s,name:String(t.name||"tool"),args:t.args,output:t.output?String(t.output):void 0,isError:t.isError===!0,durationMs:typeof t.durationMs=="number"?t.durationMs:void 0,phase:r}),w.items.set(n,i),Ae()}else if(e==="approval"){let s=t.approval;if(!s)return;let l=i;for(let r=l.length-1;r>=0;r--){let a=l[r];if(a.kind==="approval"&&a.approval.id===s.id){a.approval=s,s.state!=="pending"&&(a.decided=s.state==="allowed"?"allowed":"denied"),w.items.set(n,l),Ae();return}}l.push({kind:"approval",approval:s}),w.items.set(n,l),Ae()}else e==="notice"&&qe({kind:"notice",level:String(t.level||"info"),text:String(t.text||"")})}function ll(t){let e=t.content;return Array.isArray(e)?e.map(n=>n&&typeof n=="object"&&n.type==="text"?String(n.text||""):"").join(""):String(t.text||"")}function al(t){let e=t.content;return Array.isArray(e)?e.map(n=>n&&typeof n=="object"&&n.type==="thinking"?String(n.thinking||""):"").join(""):""}async function re(t=!1){try{let[e,n]=await Promise.all([O("/api/bots"),O("/api/bots/approvals")]);if(w.bots=e,w.approvals=n,Bt(),yn(),t&&w.activeId){let i=await O(`/api/bots/${w.activeId}/events?limit=300`);cl(i)}}catch{}}async function ol(){try{w.bots=await O("/api/bots"),Bt()}catch{}}function cl(t){if(w.activeId){w.items.set(w.activeId,[]);for(let e of t)Mi(e);Sn()}}function dl(){let t=g("div","bots-modal");t.id="bots-modal",t.hidden=!0;let e=g("div","bots-modal-card"),n=g("div","bots-modal-head"),i=g("span");i.id="bots-modal-title";let s=g("button","btn");s.innerHTML=xe("close",'width="14" height="14"'),s.title="Close",s.onclick=()=>Mt(),n.append(i,s);let l=g("div","bots-modal-body");l.id="bots-modal-body",e.append(n,l),t.appendChild(e),t.onclick=r=>{r.target===t&&Mt()},document.body.appendChild(t)}function Cn(t){let e=document.getElementById("bots-modal"),n=document.getElementById("bots-modal-title"),i=document.getElementById("bots-modal-body");if(!e||!i)throw new Error("modal missing");return n&&(n.textContent=t),i.textContent="",e.hidden=!1,i}function Mt(){let t=document.getElementById("bots-modal");t&&(t.hidden=!0)}async function pl(){return w.catalog||(w.catalog=await O("/api/bots/catalog")),w.catalog}async function zi(){return w.templates=await O("/api/bots/templates"),w.templates}async function rt(){let t=Cn("Bot templates"),[e,n]=await Promise.all([pl(),zi()]),i=g("div","bv-template-list");for(let o of n){let c=g("div","bv-template-row");c.appendChild(g("span","bv-template-name",o.manifest.name)),c.appendChild(g("span","bv-template-desc",o.manifest.description||""));let d=g("button","btn","Edit");d.onclick=()=>Ai(t,e,o);let m=g("button","btn","Copy");m.title="Duplicate this template",m.onclick=()=>{let f=JSON.parse(JSON.stringify(o.manifest));f.name=`${o.manifest.name} copy`,O("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:f})}).then(()=>rt()).catch(b=>alert(b instanceof Error?b.message:String(b)))};let h=g("button","btn danger","Delete");h.onclick=()=>{confirm(`Delete template ${o.manifest.name}?`)&&O(`/api/bots/templates/${o.id}`,{method:"DELETE"}).then(()=>rt())};let u=g("span","bv-template-actions");u.append(d,m,h),c.appendChild(u),i.appendChild(c)}n.length===0&&i.appendChild(g("div","bots-empty","No templates yet")),t.appendChild(i);let s=g("div","bv-template-actions"),l=g("button","btn primary","New template");l.onclick=()=>Ai(t,e,null);let r=g("button","btn","Export");r.title="Download templates + library as JSON",r.onclick=()=>{(async()=>{try{let o=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${gn()}`}});if(!o.ok)throw new Error(`HTTP ${o.status}`);let c=await o.blob(),d=document.createElement("a");d.href=URL.createObjectURL(c),d.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,d.click(),setTimeout(()=>URL.revokeObjectURL(d.href),2e3)}catch(o){alert(o instanceof Error?o.message:String(o))}})()};let a=g("button","btn","Import");a.title="Restore templates from a JSON bundle",a.onclick=()=>{let o=document.createElement("input");o.type="file",o.accept="application/json,.json",o.onchange=()=>{let c=o.files?.[0];c&&(async()=>{try{let d=JSON.parse(await c.text()),m=await O("/api/bots/import",{method:"POST",body:JSON.stringify(d)});alert(`Imported ${m.templates} templates, ${m.files} library files (${m.skipped} kept)`),await rt()}catch(d){alert(d instanceof Error?d.message:String(d))}})()},o.click()},s.append(l,r,a),t.appendChild(s)}function Ln(t,e,n){let i=g("div","bv-field");i.appendChild(g("label","bv-label",t));let s=g("div","bv-check-grid"),l=[];for(let r of e){let a=g("label","bv-check"),o=document.createElement("input");o.type="checkbox",o.checked=n.includes(r.id),a.append(o,g("span",void 0,r.label)),r.hint&&(a.title=r.hint),s.appendChild(a),l.push({id:r.id,input:o})}return i.appendChild(s),{element:i,get:()=>l.filter(r=>r.input.checked).map(r=>r.id)}}function Ai(t,e,n){t.textContent="";let i=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},s=g("input","bv-input");s.value=i.name,s.placeholder="Template name";let l=g("input","bv-input");l.value=i.description||"",l.placeholder="One line description";let r=g("textarea","bv-textarea");r.rows=6,r.value=i.system||"",r.placeholder="System prompt for this bot (written to SYSTEM.md)";let a=Ln("Skills",e.skills.map(E=>({id:E.id,label:E.name,hint:E.description})),i.skills||[]),o=Ln("Extensions (Pi builtins + library)",e.extensions.map(E=>({id:E.id,label:`${E.name}${E.kind==="builtin"?" (builtin)":""}`,hint:E.description})),(i.extensions||[]).map(E=>E.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),c=Ln("Prompt templates",e.prompts.map(E=>({id:E.id,label:E.name})),i.prompts||[]),d=g("select","bv-input");d.appendChild(new Option("none",""));for(let E of e.mcp)d.appendChild(new Option(E.name,E.id));i.mcp&&(d.value=e.mcp.find(E=>JSON.stringify(E.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");let m=g("div","bv-field");m.appendChild(g("label","bv-label","Tools (allow list; deny always blocks)"));let h=g("div","bv-check-grid"),u=[];for(let E of e.tools){let A=g("label","bv-check"),L=document.createElement("input");L.type="checkbox",L.checked=(i.tools?.allow||[]).includes(E.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(E.name),A.append(L,g("span",void 0,E.name)),h.appendChild(A),u.push({name:E.name,input:L})}m.appendChild(h);let f=g("input","bv-input");f.value=(i.tools?.deny||[]).join(", "),f.placeholder="Always deny (comma separated), e.g. bash, write";let b=g("textarea","bv-textarea");b.rows=2,b.value=(i.packages||[]).join(`
86
+ `),b.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";let x=g("select","bv-input");x.appendChild(new Option("default (Pi settings)",""));for(let E of e.models)x.appendChild(new Option(`${E.provider}/${E.model}`,`${E.provider}
87
+ ${E.model}`));i.model?.provider&&i.model?.id&&(x.value=`${i.model.provider}
88
+ ${i.model.id}`);let k=g("select","bv-input");for(let E of["","off","minimal","low","medium","high","xhigh","max"])k.appendChild(new Option(E||"default",E));i.model?.thinking&&(k.value=i.model.thinking);let y=g("select","bv-input");for(let E of["supervised","auto-accept-edits","full-access"])y.appendChild(new Option(E,E));y.value=i.permissions?.runtimeMode||"supervised";let B=g("select","bv-input");B.appendChild(new Option("ignore project .pi (recommended)","ignore")),B.appendChild(new Option("inherit project .pi (needs trust)","inherit")),B.value=i.projectResources||"ignore";let T=g("label","bv-check"),I=document.createElement("input");I.type="checkbox",I.checked=!!i.orchestrator,T.append(I,g("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));let M=(E,A)=>{let L=g("div","bv-field");return L.appendChild(g("label","bv-label",E)),L.appendChild(A),L};t.append(M("Name",s),M("Description",l),M("System prompt",r),a.element,o.element,c.element,M("MCP preset",d),m,M("Always deny tools",f),M("Packages",b),M("Model",x),M("Thinking level",k),M("Approval mode",y),M("Project resources",B),T);let $=g("button","btn primary",n?"Save template":"Create template");$.onclick=async()=>{let[E,A]=x.value.split(`
89
+ `),L=e.mcp.find(_=>_.id===d.value),j={name:s.value.trim()||"bot",description:l.value.trim()||void 0,system:r.value.trim()||void 0,skills:a.get(),extensions:o.get().map(_=>(_.startsWith("builtin:"),_)),prompts:c.get(),packages:b.value.split(`
90
+ `).map(_=>_.trim()).filter(Boolean),mcp:L?{mcpServers:L.servers}:void 0,tools:{allow:u.filter(_=>_.input.checked).map(_=>_.name),deny:f.value.split(",").map(_=>_.trim()).filter(Boolean)},model:E?{provider:E,id:A,thinking:k.value||void 0}:void 0,permissions:{runtimeMode:y.value},projectResources:B.value==="inherit"?"inherit":"ignore",orchestrator:I.checked||void 0};try{await O("/api/bots/templates",{method:"POST",body:JSON.stringify({id:n?.id,manifest:j})}),Mt(),await rt()}catch(_){alert(_ instanceof Error?_.message:String(_))}},t.appendChild($)}async function ul(){return Ri("")}async function Ri(t){let e=Cn("New bot"),n=await zi();if(n.length===0){e.appendChild(g("div","bots-empty","No templates yet \u2014 create one with \u201CNew template\u201D."));return}let i=g("select","bv-input");for(let c of n)i.appendChild(new Option(c.manifest.name,c.id));let s=g("input","bv-input");s.placeholder="Title (defaults to template name)";let l=g("input","bv-input");l.placeholder="/path/to/project";let r=t||w.bots[0]?.projectPath||"";l.value=r;let a=g("select","bv-input");a.appendChild(new Option("shared \u2014 run in the project folder","shared")),a.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),e.append(zt("Template",i),zt("Title",s),zt("Project path",l),zt("Workspace",a));let o=g("button","btn primary","Create bot");o.onclick=async()=>{try{let c=await O("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:s.value.trim()||void 0,projectPath:l.value.trim()||void 0,isolation:a.value})});Mt(),await re(!0),await $i(c.id)}catch(c){alert(c instanceof Error?c.message:String(c))}},e.appendChild(o)}function zt(t,e){let n=g("div","bv-field");return n.appendChild(g("label","bv-label",t)),n.appendChild(e),n}async function Tn(){let t=Cn("Needs you");if(w.approvals=await O("/api/bots/approvals"),w.approvals.length===0){t.appendChild(g("div","bots-empty","Nothing waiting."));return}for(let e of w.approvals){let n=g("div","bv-approval");n.appendChild(g("div","bv-approval-title",`${e.botTitle}: ${e.title}`)),e.message&&n.appendChild(g("pre","bv-pre",e.message));let i=g("input","bv-reason");i.placeholder="reason (optional)";let s=g("div","bv-approval-actions"),l=g("button","btn primary","Allow"),r=g("button","btn danger","Deny"),a=async o=>{await O(`/api/bots/${e.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:e.id,allow:o,reason:i.value||void 0})}),await re(!0),await Tn()};l.onclick=()=>void a(!0),r.onclick=()=>void a(!1),s.append(i,l,r),n.appendChild(s),t.appendChild(n)}}function hl(){window.__botsInited||(window.__botsInited=!0,el(),Gr(),window.__openBot=$i,document.addEventListener("click",t=>{let e=t.target;e&&(e.closest(".session-item.bot-item")||e.closest(".session-item")&&w.activeId&&setTimeout(()=>kn(),0))},!0),re(!0),w.pollTimer=window.setInterval(()=>{document.hidden||re()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(w.pollTimer)))}var lt=window.__TMUX_WEB_SHELL__,F=null,q=null,at=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null,Y=at;window.__tmuxWebScopeAgent=at;var In="sessions",be="",At="",Rt="",Pi="";function U(t){return Y?"/a/"+encodeURIComponent(Y)+t:t}var P=document.getElementById("sidebar-content"),Re=document.getElementById("main-placeholder"),te=document.getElementById("terminal-container"),ot=document.getElementById("file-editor"),ml=document.getElementById("fe-path"),le=document.getElementById("fe-status"),ct=document.getElementById("fe-content"),Pe=document.getElementById("fe-save"),fl=document.getElementById("fe-delete"),gl=document.getElementById("fe-back"),Di=document.getElementById("fe-new-name"),vl=document.getElementById("fe-new-btn"),$n=document.getElementById("settings-backdrop"),Hi=document.getElementById("settings-popover"),_i=document.querySelector(".sidebar"),Fi="tmux-web-force-narrow";function Pt(){try{return localStorage.getItem(Fi)==="1"}catch{return!1}}function Ni(){document.documentElement.classList.toggle("force-narrow",Pt()),Pt()&&Oi()&&dt()}function Oi(){return Pt()?!0:window.matchMedia("(max-width: 640px)").matches}function dt(){Oi()&&_i.classList.add("collapsed")}function qi(){_i.classList.remove("collapsed")}window.__collapseSidebar=dt,document.getElementById("mode-sessions").addEventListener("click",()=>{qi(),ji("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{qi(),ji("files")});function ji(t){In=t,document.querySelectorAll(".mode-btn").forEach(n=>n.classList.remove("active"));let e=document.getElementById(t==="sessions"?"mode-sessions":"mode-files");e&&e.classList.add("active"),t==="sessions"?(Bn="",ke()):zl()}var Bn="";async function ke(){if(In!=="sessions")return;try{let e=await(await fetch("/api/sidebar/sessions")).json(),n=(window.__botsSnapshot||[]).map(s=>[s.id,s.title,s.status,s.projectPath]),i=JSON.stringify({recent:e.recent,agents:e.agents,tombstones:e.tombstones,bots:n});if(i===Bn)return;Bn=i,El(e)}catch{P.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}let t=document.getElementById("ns-btn");t&&t.addEventListener("click",()=>{let e=window.__openNewSessionModal;typeof e=="function"?e():document.getElementById("new-session-modal")?.classList.add("open")}),Hn()}var Vi="tmux-web-sidebar-group-collapsed";function Wi(){try{return new Set(JSON.parse(localStorage.getItem(Vi)||"[]"))}catch{return new Set}}function bl(t){try{localStorage.setItem(Vi,JSON.stringify([...t]))}catch{}}function kl(t,e,n){if(!t)return"\u2026";let i=n&&(t===n||t.startsWith(n+"/"))?"~"+t.slice(n.length):t,s=i.split("/").filter(Boolean);if(s.length===0)return t;for(let l=1;l<=s.length;l++){let r=s.slice(-l).join("/");if(!e.some(a=>!a||a===t?!1:(n&&(a===n||a.startsWith(n+"/"))?"~"+a.slice(n.length):a).split("/").filter(Boolean).slice(-l).join("/")===r))return r}return i}function wl(t){let e=document.createElement("div");e.className="session-item bot-item",e.setAttribute("data-bot-id",t.id),e.title=`Bot \xB7 ${t.projectPath}`;let n=t.status==="running"?"var(--panel-success)":t.status==="waiting_approval"||t.status==="waiting_input"?"#e0a23c":t.status==="failed"?"var(--panel-danger, #e5534b)":"var(--panel-muted)";return e.innerHTML=`${xe("bot",'class="bot-icon"')}<span>${D(t.title)}</span><span class="bot-status-dot" style="background:${n}"></span>`,e.addEventListener("click",i=>{i.stopPropagation(),window.__openBot?.(t.id)}),e}function Ui(t,e,n,i=!0){let s=new Map;for(let c of t){let d=c.path||"";s.has(d)||s.set(d,[]),s.get(d).push(c)}let l=n?[]:window.__botsSnapshot||[],r=new Map;for(let c of l)s.has(c.projectPath)||s.set(c.projectPath,[]),r.has(c.projectPath)||r.set(c.projectPath,[]),r.get(c.projectPath).push(c);let a=[...s.keys()],o=Wi();for(let[c,d]of s){let m=kl(c,a,e),h=o.has(c),u=document.createElement("div");if(u.className="session-group-header"+(h?" collapsed":""),u.title=c||"No working directory",u.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${D(m)}</span>`,!n&&c){let b=document.createElement("button");b.className="sg-add-bot",b.innerHTML=xe("add",'width="12" height="12"'),b.title=`New bot in ${c}`,b.addEventListener("click",x=>{x.stopPropagation(),zn(c)}),u.appendChild(b)}u.addEventListener("click",()=>{let b=Wi(),x=u.nextElementSibling;b.has(c)?(b.delete(c),u.classList.remove("collapsed"),x?.classList.remove("collapsed")):(b.add(c),u.classList.add("collapsed"),x?.classList.add("collapsed")),bl(b)});let f=document.createElement("div");f.className="session-group-body"+(h?" collapsed":"");for(let b of d)f.appendChild(n?yl(b,n,i):xl(b));for(let b of r.get(c)||[])f.appendChild(wl(b));P.appendChild(u),P.appendChild(f)}}function yl(t,e,n){let i=document.createElement("div");i.className="session-item"+(t.name===q&&Y===e?" active":"")+(n?"":" session-offline"),i.setAttribute("data-session",t.name),i.setAttribute("data-agent",e),i.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${t.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
91
+ <span>${D(t.name)}</span>${n?"":'<span class="meta">offline</span>'}
92
+ <button class="session-edit-btn" data-session="${D(t.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,n&&i.addEventListener("click",l=>{l.target.closest(".session-edit-btn")||pt(t.name,e)});let s=i.querySelector(".session-edit-btn");return s&&s.addEventListener("click",l=>{l.stopPropagation(),Wt(t.name,s,{agentId:e})}),i}function xl(t){let e=document.createElement("div");e.className="session-item"+(t.name===q&&!Y?" active":""),e.setAttribute("data-session",t.name),e.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${t.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
93
+ <span>${D(t.name)}</span>
94
+ <button class="session-edit-btn" data-session="${D(t.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>
95
+ `,e.addEventListener("click",i=>{i.target.closest(".session-edit-btn")||pt(t.name)});let n=e.querySelector(".session-edit-btn");return n&&n.addEventListener("click",i=>{i.stopPropagation(),Wt(t.name,n)}),e}function El(t){P.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';let e=t.recent||[],n=document.createElement("div");n.className="sidebar-section-label"+(at?" clickable":""),n.textContent=at?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",at&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),P.appendChild(n),Ui(e,t.home);let i=t.agents||[];for(let l of i){if(!l.sessions||l.sessions.length===0)continue;let r=l.agentId===Y,a=document.createElement("div");a.className="sidebar-section-label machine-label"+(l.online?"":" agent-offline-label")+(!r&&l.online?" clickable":""),a.textContent=l.agentName+(l.online?"":" (offline)"),!r&&l.online&&(a.title="\u6253\u5F00 "+l.agentName,a.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(l.agentId)+"/"})),P.appendChild(a),Ui(l.sessions,t.home,l.agentId,l.online)}let s=t.tombstones||[];if(s.length>0){let l=document.createElement("div");l.className="sidebar-section-label tombstone-label",l.textContent="\u5931\u6548\u4F1A\u8BDD",P.appendChild(l);for(let r of s){let a=document.createElement("div");a.className="session-item session-tombstone",a.setAttribute("data-session",r.name),r.agentId&&a.setAttribute("data-agent",r.agentId);let o=r.agentId?r.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";a.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
96
+ <span>${D(r.name)}</span><span class="meta">\u5931\u6548${o}</span>
97
+ <button class="session-edit-btn" data-session="${D(r.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,a.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",a.addEventListener("click",()=>{Wt(r.name,a,{tombstone:!0,agentId:r.agentId})});let c=a.querySelector(".session-edit-btn");c&&c.addEventListener("click",d=>{d.stopPropagation(),Wt(r.name,c,{tombstone:!0,agentId:r.agentId})}),P.appendChild(a)}}}function D(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function pt(t,e){if(q===t&&F&&Y===(e||null))return;ot.style.display="none",Re.style.display="none",te.style.display="",te.classList.add("terminal-pending"),dt(),F&&(jt(),F.destroy(),F=null),q=t,Y=e||null,window.__tmuxWebScopeAgent=Y,window.__tmuxWebCurrentSession=q,Zl(t,e);let n=Dn(t,e);as.set(n,Date.now()+Ul);let i=We.get(n);if(i&&i.state==="working"){i.state="idle",i.doneUntil=void 0,i.unread=!1;let s=P.querySelector(e?'.session-item[data-agent="'+CSS.escape(e)+'"][data-session="'+CSS.escape(t)+'"]':'.session-item[data-session="'+CSS.escape(t)+'"]:not([data-agent])');s&&Xt(s,n,i)}for(let s of P.querySelectorAll(".session-item"))s.classList.toggle("active",s.getAttribute("data-session")===t&&(s.getAttribute("data-agent")||null)===Y);try{F=await As(te,t,{terminal:lt.terminal,scrollback:lt.scrollback,theme:lt.theme,wsBase:Y?"/ws/a/"+encodeURIComponent(Y):lt.wsBase||"/ws"}),ns()}catch(s){console.error("[shell] terminal init failed:",s);let l=s&&typeof s=="object"&&"message"in s?s.message:String(s);te.textContent="Failed to open terminal for "+t+": "+l,te.classList.remove("terminal-pending")}}var Dt=[],V=null,Ji=!1;function Sl(t){if(!V||!V.files.length)return null;let e=V.repoRoot;if(!e||!t.startsWith(e))return null;let n=t.slice(e.length+1);for(let i of V.files)if(i.path===n)return i.status;return null}async function Cl(t){Ji=!0;try{let e=await fetch(U("/api/git/status?path="+encodeURIComponent(t)));e.ok?V=await e.json():V=null}catch{V=null}finally{Ji=!1}}function Ll(){if(!V||!V.branch)return"";let{branch:t,linesAdded:e,linesRemoved:n}=V,i=`<div class="sidebar-git"><div class="git-branch-badge">
21
98
  <svg viewBox="0 0 16 16" fill="currentColor"><path d="M11.63 1.22a.75.75 0 00-1.06 0L5.99 5.8 4.12 3.93a.75.75 0 10-1.06 1.06L4.93 6.87A3.5 3.5 0 003 10.09v3.16a.75.75 0 001 0v-3.16a2.5 2.5 0 012.5-2.5h.27l-1.06 1.06a.75.75 0 001.06 1.06l2.37-2.38a.75.75 0 000-1.06L7.59 5.27l4.04-4.05a.75.75 0 000-1.06L11.63 1.22zM3.25 13.94a.75.75 0 01-.75-.75v-.69a.75.75 0 011.5 0v.69c0 .414-.336.75-.75.75z"/></svg>
22
- ${C(e)}</div>`;return(t>0||n>0)&&(i+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${n}</span></div>`),i+"</div>"}k.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&be&&D&&(e.stopPropagation(),En())});var Fe=document.getElementById("header-git"),gn=document.getElementById("git-diff-view"),yn=document.getElementById("gd-path"),et=document.getElementById("gd-status"),tt=document.getElementById("gd-content"),Pi=document.getElementById("gd-back"),be=null;function $e(e){if(!e||!e.branch){Fe.style.display="none",be=null;return}be=e.repoRoot;let{branch:t,linesAdded:n,linesRemoved:i}=e,a=`<span class="branch">${C(t)}</span>`;(n>0||i>0)&&(a+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${i}</span>`),Fe.innerHTML=a,Fe.style.display="block"}Fe.addEventListener("click",e=>{be&&D&&(e.stopPropagation(),En())});var O=document.getElementById("git-popover"),nt=document.getElementById("git-popover-backdrop");function Bt(){let e=Fe.getBoundingClientRect();O.style.top=e.bottom+4+"px",O.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function bn(){let e=be,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(at(),e){St="files",document.querySelectorAll(".mode-btn").forEach(i=>i.classList.remove("active"));let n=document.getElementById("mode-files");n&&n.classList.add("active"),oe(e)}})}var wn="";function En(){if(!D)return;let e=D.files||[];if(!e.length)O.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
23
- <div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let t=`<div class="git-popover-header">${e.length} file${e.length>1?"s":""} changed</div>`;for(let n=0;n<e.length;n++){let i=e[n],a=i.additions||0,r=i.deletions||0,o="";switch(i.status){case"M":o='<span class="git-file-status M">M</span>';break;case"A":o='<span class="git-file-status A">A</span>';break;case"D":o='<span class="git-file-status D">D</span>';break;case"?":o='<span class="git-file-status ?">?</span>';break;case"R":o='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
24
- ${o}<span class="file-path">${C(i.path)}</span>
25
- <span class="file-add">${a>0?"+"+a:""}</span>
26
- <span class="file-del">${r>0?"-"+r:""}</span>
27
- </div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',wn=t,O.innerHTML=t,O.querySelectorAll(".git-popover-item").forEach(n=>{let i=parseInt(n.dataset.idx||"0",10),a=e[i];!a||a.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>Cn(a.path)))})}Bt(),O.classList.add("open"),nt.classList.add("open"),bn()}function Ni(){return window.innerWidth>=1024}function kn(e,t){let n=(e+(t&&e?`
28
- `:"")+t).split(`
29
- `),i="",a=0,r=0;for(let o of n){let l=o;if(l.startsWith("@@")){let u=l.match(/@@\s+-(\d+)[^+]*\+(\d+)/);u&&(a=parseInt(u[1],10)-1,r=parseInt(u[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${C(l)}</span></div>`;continue}if(l.startsWith("diff --git")||l.startsWith("index ")||l.startsWith("--- ")||l.startsWith("+++ ")||l.startsWith("new file")||l.startsWith("deleted file")){l.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${C(l)}</span></div>`);continue}if(l.startsWith("+"))r++,i+=`<div class="diff-line add"><span class="ln-no">${r}</span><span class="ln-body">${C(l)}</span></div>`;else if(l.startsWith("-"))a++,i+=`<div class="diff-line del"><span class="ln-no">${a}</span><span class="ln-body">${C(l)}</span></div>`;else if(l.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${C(l)}</span></div>`;else{if(!l&&!a&&!r)continue;a++,r++,i+=`<div class="diff-line"><span class="ln-no">${a}</span><span class="ln-no" style="margin-right:12px">${r}</span><span class="ln-body">${C(l)}</span></div>`}}return{html:i,lineCount:n.length}}var it=null;async function Cn(e){let t=be;if(t)if(at(),Ni()){q.style.display="none",S&&(st(),S.destroy(),S=null,it=z,z=null),$e(null),ze.style.display="none",me.style.display="none",gn.style.display="flex",yn.textContent=e,et.textContent="Loading\u2026",tt.innerHTML="";try{let n=await fetch($("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Oi(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);et.textContent="Error",tt.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${C(i)}</div>`}}else{O.innerHTML=`<div class="git-diff-view"><div class="diff-header">
99
+ ${D(t)}</div>`;return(e>0||n>0)&&(i+=`<div class="git-diff-stats">+<span class="add">${e}</span> <span class="del">-${n}</span></div>`),i+"</div>"}P.addEventListener("click",t=>{t.target.closest(".sidebar-git")&&je&&V&&(t.stopPropagation(),Qi())});var ut=document.getElementById("header-git"),Zi=document.getElementById("git-diff-view"),Yi=document.getElementById("gd-path"),Ht=document.getElementById("gd-status"),_t=document.getElementById("gd-content"),Tl=document.getElementById("gd-back"),je=null;function ht(t){if(!t||!t.branch){ut.style.display="none",je=null;return}je=t.repoRoot;let{branch:e,linesAdded:n,linesRemoved:i}=t,s=`<span class="branch">${D(e)}</span>`;(n>0||i>0)&&(s+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${i}</span>`),ut.innerHTML=s,ut.style.display="block"}ut.addEventListener("click",t=>{je&&V&&(t.stopPropagation(),Qi())});var X=document.getElementById("git-popover"),Ft=document.getElementById("git-popover-backdrop");function Mn(){let t=ut.getBoundingClientRect();X.style.top=t.bottom+4+"px",X.style.left=Math.max(8,Math.min(t.left,window.innerWidth-400))+"px"}function Xi(){let t=je,e=document.getElementById("git-popover-browse");e&&e.addEventListener("click",()=>{if(Ot(),t){In="files",document.querySelectorAll(".mode-btn").forEach(i=>i.classList.remove("active"));let n=document.getElementById("mode-files");n&&n.classList.add("active"),we(t)}})}var Ki="";function Qi(){if(!V)return;let t=V.files||[];if(!t.length)X.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
100
+ <div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let e=`<div class="git-popover-header">${t.length} file${t.length>1?"s":""} changed</div>`;for(let n=0;n<t.length;n++){let i=t[n],s=i.additions||0,l=i.deletions||0,r="";switch(i.status){case"M":r='<span class="git-file-status M">M</span>';break;case"A":r='<span class="git-file-status A">A</span>';break;case"D":r='<span class="git-file-status D">D</span>';break;case"?":r='<span class="git-file-status ?">?</span>';break;case"R":r='<span class="git-file-status R">R</span>';break}e+=`<div class="git-popover-item" data-idx="${n}">
101
+ ${r}<span class="file-path">${D(i.path)}</span>
102
+ <span class="file-add">${s>0?"+"+s:""}</span>
103
+ <span class="file-del">${l>0?"-"+l:""}</span>
104
+ </div>`}e+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',Ki=e,X.innerHTML=e,X.querySelectorAll(".git-popover-item").forEach(n=>{let i=parseInt(n.dataset.idx||"0",10),s=t[i];!s||s.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>es(s.path)))})}Mn(),X.classList.add("open"),Ft.classList.add("open"),Xi()}function Il(){return window.innerWidth>=1024}function Gi(t,e){let n=(t+(e&&t?`
105
+ `:"")+e).split(`
106
+ `),i="",s=0,l=0;for(let r of n){let a=r;if(a.startsWith("@@")){let o=a.match(/@@\s+-(\d+)[^+]*\+(\d+)/);o&&(s=parseInt(o[1],10)-1,l=parseInt(o[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${D(a)}</span></div>`;continue}if(a.startsWith("diff --git")||a.startsWith("index ")||a.startsWith("--- ")||a.startsWith("+++ ")||a.startsWith("new file")||a.startsWith("deleted file")){a.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${D(a)}</span></div>`);continue}if(a.startsWith("+"))l++,i+=`<div class="diff-line add"><span class="ln-no">${l}</span><span class="ln-body">${D(a)}</span></div>`;else if(a.startsWith("-"))s++,i+=`<div class="diff-line del"><span class="ln-no">${s}</span><span class="ln-body">${D(a)}</span></div>`;else if(a.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${D(a)}</span></div>`;else{if(!a&&!s&&!l)continue;s++,l++,i+=`<div class="diff-line"><span class="ln-no">${s}</span><span class="ln-no" style="margin-right:12px">${l}</span><span class="ln-body">${D(a)}</span></div>`}}return{html:i,lineCount:n.length}}var Nt=null;async function es(t){let e=je;if(e)if(Ot(),Il()){te.style.display="none",F&&(jt(),F.destroy(),F=null,Nt=q,q=null),ht(null),ot.style.display="none",Re.style.display="none",Zi.style.display="flex",Yi.textContent=t,Ht.textContent="Loading\u2026",_t.innerHTML="";try{let n=await fetch(U("/api/git/diff?path="+encodeURIComponent(e)+"&file="+encodeURIComponent(t)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Bl(t,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);Ht.textContent="Error",_t.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${D(i)}</div>`}}else{X.innerHTML=`<div class="git-diff-view"><div class="diff-header">
30
107
  <button class="diff-back">\u2190 Back</button>
31
- <span class="diff-filename">${C(e)}</span>
108
+ <span class="diff-filename">${D(t)}</span>
32
109
  <span class="diff-loading">Loading\u2026</span>
33
- </div></div>`,Bt(),O.classList.add("open"),nt.classList.add("open");try{let n=await fetch($("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Vi(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);O.innerHTML=`<div class="git-diff-view"><div class="diff-header">
110
+ </div></div>`,Mn(),X.classList.add("open"),Ft.classList.add("open");try{let n=await fetch(U("/api/git/diff?path="+encodeURIComponent(e)+"&file="+encodeURIComponent(t)));if(!n.ok)throw new Error(await n.text());let i=await n.json();$l(t,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);X.innerHTML=`<div class="git-diff-view"><div class="diff-header">
34
111
  <button class="diff-back">\u2190 Back</button>
35
- <span class="diff-filename">${C(e)}</span>
36
- </div><div class="diff-empty">Error loading diff: ${C(i)}</div></div>`}}}function Vi(e,t,n){if(!t&&!n){O.innerHTML=`<div class="git-diff-view"><div class="diff-header">
112
+ <span class="diff-filename">${D(t)}</span>
113
+ </div><div class="diff-empty">Error loading diff: ${D(i)}</div></div>`}}}function $l(t,e,n){if(!e&&!n){X.innerHTML=`<div class="git-diff-view"><div class="diff-header">
37
114
  <button class="diff-back">\u2190 Back</button>
38
- <span class="diff-filename">${C(e)}</span>
39
- </div><div class="diff-empty">No diff content available</div></div>`;return}let{html:i,lineCount:a}=kn(t,n);O.innerHTML=`<div class="git-diff-view"><div class="diff-header">
115
+ <span class="diff-filename">${D(t)}</span>
116
+ </div><div class="diff-empty">No diff content available</div></div>`;return}let{html:i,lineCount:s}=Gi(e,n);X.innerHTML=`<div class="git-diff-view"><div class="diff-header">
40
117
  <button class="diff-back">\u2190 Back</button>
41
- <span class="diff-filename">${C(e)}</span>
42
- <span class="diff-filesize">${a} lines</span>
43
- </div><div class="diff-content">${i}</div></div>`,O.querySelector(".diff-back")?.addEventListener("click",()=>{O.innerHTML=wn,Bt(),D&&O.querySelectorAll(".git-popover-item").forEach(r=>{let o=parseInt(r.dataset.idx||"0",10),l=D.files[o];!l||l.status==="D"||(r.style.cursor="pointer",r.addEventListener("click",()=>Cn(l.path)))}),bn()})}function Oi(e,t,n){if(!t&&!n){et.textContent="No diff",tt.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}let{html:i,lineCount:a}=kn(t,n);yn.textContent=e,et.textContent=a+" lines",tt.innerHTML=i}function ji(){gn.style.display="none",it?(q.style.display="",q.classList.add("terminal-pending"),Ae(it),it=null):z?(q.style.display="",q.classList.add("terminal-pending"),xn()):me.style.display="flex"}Pi.addEventListener("click",ji);function at(){O.classList.remove("open"),nt.classList.remove("open")}nt.addEventListener("click",at),document.addEventListener("keydown",e=>{e.key==="Escape"&&(at(),pt())});async function Ln(e){try{let t=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(t.path){let n=await fetch("/api/git/status?path="+encodeURIComponent(t.path));if(n.ok){let i=await n.json();D=i,$e(i);return}}}catch{}D=null,$e(null)}var ot=null;function xn(){st(),z&&(Ln(z),ot=setInterval(()=>{z&&Ln(z)},3e4))}function st(){ot&&(clearInterval(ot),ot=null)}async function Tt(e){let t=e;if(t.startsWith("~"))try{let n=await(await fetch($("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof n.path=="string"&&n.path&&(t=n.path)}catch{}t=t.replace(/\/+$/,"")||"/",nn(t)}function Sn(e,t){let n=document.createElement("button");n.className="file-tree-bot-btn",n.innerHTML=ce("add",'width="12" height="12"'),n.title=`Create bot in ${t}`,n.setAttribute("aria-label",`Create bot in ${t}`),n.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),Tt(t)}),e.appendChild(n)}function Ri(){if(Ge=Be.fsRoots||[],Ge.length===0){if(z){_i(z);return}oe("");return}k.innerHTML="";for(let e of Ge){let t=document.createElement("div");t.className="file-tree-item",t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${C(e)}`,t.addEventListener("click",()=>oe(e)),Sn(t,e),k.appendChild(t)}}async function _i(e){k.innerHTML='<div class="file-tree-empty">Loading...</div>';try{let t=await(await fetch($("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?oe(t.path):k.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{k.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function oe(e){ie=e,k.innerHTML='<div class="file-tree-empty">Loading...</div>';let t=Fi(e);try{let n=await(await fetch($("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof n.path=="string"&&n.path?n.path:e;if(i&&(ie=i),await t,k.innerHTML="",i){let o=document.createElement("div");o.className="file-tree-item file-tree-create-bot",o.innerHTML=`<span class="file-tree-bot-plus">${ce("add",'width="11" height="11"')}</span> Create bot in this folder`,o.title=`Create bot in ${i}`,o.addEventListener("click",()=>void Tt(i)),k.appendChild(o)}$e(D),k.innerHTML+=$i();let a=Ui(i||e);if(a&&!Ge.some(o=>i===o)){let o=document.createElement("div");o.className="file-tree-item",o.innerHTML="..",o.addEventListener("click",()=>oe(a)),k.appendChild(o)}if(n.dirs)for(let o of n.dirs){let l=o.split("/").pop()||o.split("\\").pop(),u=document.createElement("div");u.className="file-tree-item",u.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${C(l)}`,u.addEventListener("click",()=>oe(o)),Sn(u,o),k.appendChild(u)}else k.innerHTML="";let r=n.files||[];for(let o of r){let l=o.split("/").pop()||o.split("\\").pop(),u=Ai(o),p="",f="";if(u)switch(u){case"M":p="git-mod",f='<span class="git-file-status M">M</span>';break;case"A":p="git-add",f='<span class="git-file-status A">A</span>';break;case"D":p="git-del",f='<span class="git-file-status D">D</span>';break;case"?":p="git-untracked",f='<span class="git-file-status ?">?</span>';break;case"R":p="git-mod",f='<span class="git-file-status R">R</span>';break}let y=document.createElement("div");y.className="file-tree-item file"+(p?" "+p:""),y.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${f}${C(l)}`,y.addEventListener("click",()=>Wi(o)),k.appendChild(y)}}catch{k.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function Ui(e){let t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function Wi(e){Xe=e,q.style.display="none",S&&(st(),S.destroy(),S=null,z=null),$e(null),De(),me.style.display="none",ze.style.display="flex",Li.textContent=e,K.textContent="Loading...",he.style.display="none";try{let t=await fetch($("/api/file?path="+encodeURIComponent(e)));if(!t.ok){let i=await t.json();K.textContent=i.error||"Failed to load",He.value="";return}let n=await t.json();He.value=n.content,Qe=n.content,an=n.content,K.textContent=n.size+" bytes",he.style.display=""}catch{K.textContent="Failed to load",He.value=""}}He.addEventListener("input",()=>{Qe=He.value}),he.addEventListener("click",async()=>{he.textContent="Saving...",he.disabled=!0;try{let e=await fetch($("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Xe,content:Qe})});if(!e.ok){let t=await e.json();K.textContent=t.error||"Save failed";return}an=Qe,K.textContent="Saved"}catch{K.textContent="Save failed"}finally{he.disabled=!1,he.textContent="Save"}}),xi.addEventListener("click",async()=>{if(confirm("Delete "+Xe+"?"))try{let e=await fetch($("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Xe})});if(!e.ok){let t=await e.json();K.textContent=t.error||"Delete failed";return}ze.style.display="none",me.style.display="flex",ie&&oe(ie)}catch{K.textContent="Delete failed"}}),Si.addEventListener("click",()=>{ze.style.display="none",me.style.display="flex",ie&&oe(ie)}),Mi.addEventListener("click",async()=>{let e=on.value.trim();if(!e)return;let t=ie+"/"+e;try{let n=await fetch($("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){let i=await n.json();K.textContent=i.error||"Create failed";return}on.value="",ie&&oe(ie)}catch{K.textContent="Create failed"}});var lt=document.getElementById("force-narrow-toggle");lt&&(lt.checked=Ze(),lt.addEventListener("change",()=>{try{localStorage.setItem(rn,lt.checked?"1":"0")}catch{}dn(),ae()})),dn(),document.getElementById("mode-settings").addEventListener("click",()=>{let e=sn.classList.toggle("open");Mt.classList.toggle("open",e)}),Mt.addEventListener("click",()=>{sn.classList.remove("open"),Mt.classList.remove("open")});var J="",X=!1,Q,Pe=document.createElement("div");Pe.className="session-popover-backdrop",document.body.appendChild(Pe);var Z=document.createElement("div");Z.id="session-popover",Z.className="session-popover",Z.style.display="none",Z.innerHTML=`<div class="sp-field">
118
+ <span class="diff-filename">${D(t)}</span>
119
+ <span class="diff-filesize">${s} lines</span>
120
+ </div><div class="diff-content">${i}</div></div>`,X.querySelector(".diff-back")?.addEventListener("click",()=>{X.innerHTML=Ki,Mn(),V&&X.querySelectorAll(".git-popover-item").forEach(l=>{let r=parseInt(l.dataset.idx||"0",10),a=V.files[r];!a||a.status==="D"||(l.style.cursor="pointer",l.addEventListener("click",()=>es(a.path)))}),Xi()})}function Bl(t,e,n){if(!e&&!n){Ht.textContent="No diff",_t.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}let{html:i,lineCount:s}=Gi(e,n);Yi.textContent=t,Ht.textContent=s+" lines",_t.innerHTML=i}function Ml(){Zi.style.display="none",Nt?(te.style.display="",te.classList.add("terminal-pending"),pt(Nt),Nt=null):q?(te.style.display="",te.classList.add("terminal-pending"),ns()):Re.style.display="flex"}Tl.addEventListener("click",Ml);function Ot(){X.classList.remove("open"),Ft.classList.remove("open")}Ft.addEventListener("click",Ot),document.addEventListener("keydown",t=>{t.key==="Escape"&&(Ot(),Yt())});async function ts(t){try{let e=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(t))).json();if(e.path){let n=await fetch("/api/git/status?path="+encodeURIComponent(e.path));if(n.ok){let i=await n.json();V=i,ht(i);return}}}catch{}V=null,ht(null)}var qt=null;function ns(){jt(),q&&(ts(q),qt=setInterval(()=>{q&&ts(q)},3e4))}function jt(){qt&&(clearInterval(qt),qt=null)}async function zn(t){let e=t;if(e.startsWith("~"))try{let n=await(await fetch(U("/api/fs/list?path="+encodeURIComponent(e)))).json();typeof n.path=="string"&&n.path&&(e=n.path)}catch{}e=e.replace(/\/+$/,"")||"/",Ri(e)}function is(t,e){let n=document.createElement("button");n.className="file-tree-bot-btn",n.innerHTML=xe("add",'width="12" height="12"'),n.title=`Create bot in ${e}`,n.setAttribute("aria-label",`Create bot in ${e}`),n.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),zn(e)}),t.appendChild(n)}function zl(){if(Dt=lt.fsRoots||[],Dt.length===0){if(q){Al(q);return}we("");return}P.innerHTML="";for(let t of Dt){let e=document.createElement("div");e.className="file-tree-item",e.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${D(t)}`,e.addEventListener("click",()=>we(t)),is(e,t),P.appendChild(e)}}async function Al(t){P.innerHTML='<div class="file-tree-empty">Loading...</div>';try{let e=await(await fetch(U("/api/fs/session-path?session="+encodeURIComponent(t)))).json();e.path?we(e.path):P.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{P.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function we(t){be=t,P.innerHTML='<div class="file-tree-empty">Loading...</div>';let e=Cl(t);try{let n=await(await fetch(U("/api/fs/list?path="+encodeURIComponent(t)))).json(),i=typeof n.path=="string"&&n.path?n.path:t;if(i&&(be=i),await e,P.innerHTML="",i){let r=document.createElement("div");r.className="file-tree-item file-tree-create-bot",r.innerHTML=`<span class="file-tree-bot-plus">${xe("add",'width="11" height="11"')}</span> Create bot in this folder`,r.title=`Create bot in ${i}`,r.addEventListener("click",()=>void zn(i)),P.appendChild(r)}ht(V),P.innerHTML+=Ll();let s=Rl(i||t);if(s&&!Dt.some(r=>i===r)){let r=document.createElement("div");r.className="file-tree-item",r.innerHTML="..",r.addEventListener("click",()=>we(s)),P.appendChild(r)}if(n.dirs)for(let r of n.dirs){let a=r.split("/").pop()||r.split("\\").pop(),o=document.createElement("div");o.className="file-tree-item",o.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${D(a)}`,o.addEventListener("click",()=>we(r)),is(o,r),P.appendChild(o)}else P.innerHTML="";let l=n.files||[];for(let r of l){let a=r.split("/").pop()||r.split("\\").pop(),o=Sl(r),c="",d="";if(o)switch(o){case"M":c="git-mod",d='<span class="git-file-status M">M</span>';break;case"A":c="git-add",d='<span class="git-file-status A">A</span>';break;case"D":c="git-del",d='<span class="git-file-status D">D</span>';break;case"?":c="git-untracked",d='<span class="git-file-status ?">?</span>';break;case"R":c="git-mod",d='<span class="git-file-status R">R</span>';break}let m=document.createElement("div");m.className="file-tree-item file"+(c?" "+c:""),m.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${d}${D(a)}`,m.addEventListener("click",()=>Pl(r)),P.appendChild(m)}}catch{P.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function Rl(t){let e=t.lastIndexOf("/");return e<=0?null:t.substring(0,e)}async function Pl(t){At=t,te.style.display="none",F&&(jt(),F.destroy(),F=null,q=null),ht(null),dt(),Re.style.display="none",ot.style.display="flex",ml.textContent=t,le.textContent="Loading...",Pe.style.display="none";try{let e=await fetch(U("/api/file?path="+encodeURIComponent(t)));if(!e.ok){let i=await e.json();le.textContent=i.error||"Failed to load",ct.value="";return}let n=await e.json();ct.value=n.content,Rt=n.content,Pi=n.content,le.textContent=n.size+" bytes",Pe.style.display=""}catch{le.textContent="Failed to load",ct.value=""}}ct.addEventListener("input",()=>{Rt=ct.value}),Pe.addEventListener("click",async()=>{Pe.textContent="Saving...",Pe.disabled=!0;try{let t=await fetch(U("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:At,content:Rt})});if(!t.ok){let e=await t.json();le.textContent=e.error||"Save failed";return}Pi=Rt,le.textContent="Saved"}catch{le.textContent="Save failed"}finally{Pe.disabled=!1,Pe.textContent="Save"}}),fl.addEventListener("click",async()=>{if(confirm("Delete "+At+"?"))try{let t=await fetch(U("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:At})});if(!t.ok){let e=await t.json();le.textContent=e.error||"Delete failed";return}ot.style.display="none",Re.style.display="flex",be&&we(be)}catch{le.textContent="Delete failed"}}),gl.addEventListener("click",()=>{ot.style.display="none",Re.style.display="flex",be&&we(be)}),vl.addEventListener("click",async()=>{let t=Di.value.trim();if(!t)return;let e=be+"/"+t;try{let n=await fetch(U("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok){let i=await n.json();le.textContent=i.error||"Create failed";return}Di.value="",be&&we(be)}catch{le.textContent="Create failed"}});var Vt=document.getElementById("force-narrow-toggle");Vt&&(Vt.checked=Pt(),Vt.addEventListener("change",()=>{try{localStorage.setItem(Fi,Vt.checked?"1":"0")}catch{}Ni(),ke()})),Ni(),document.getElementById("mode-settings").addEventListener("click",()=>{let t=Hi.classList.toggle("open");$n.classList.toggle("open",t)}),$n.addEventListener("click",()=>{Hi.classList.remove("open"),$n.classList.remove("open")});var ne="",ae=!1,oe,mt=document.createElement("div");mt.className="session-popover-backdrop",document.body.appendChild(mt);var ce=document.createElement("div");ce.id="session-popover",ce.className="session-popover",ce.style.display="none",ce.innerHTML=`<div class="sp-field">
44
121
  <label>Rename session</label>
45
122
  <input type="text" id="sp-name" />
46
123
  </div>
@@ -50,5 +127,5 @@ ${i.model.id}`);let W=c("select","bv-input");for(let v of["","off","minimal","lo
50
127
  <button class="btn danger sp-delete" id="sp-delete">Delete</button>
51
128
  </div>
52
129
  <hr class="sp-divider" id="sp-divider" />
53
- <button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>`,document.body.appendChild(Z);function qi(e){let t=e.getBoundingClientRect(),n=window.innerHeight,i=Z.offsetHeight||240,a=t.bottom+4;a+i>n-8&&(a=Math.max(8,t.top-i-4)),Z.style.top=a+"px",Z.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}function rt(e,t,n){J=e,X=!!n?.tombstone,Q=n?.agentId;let i=document.getElementById("sp-name");i.value=e;let a=Z.querySelector(".sp-field label");a.textContent=X?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";let r=document.getElementById("sp-rebuild");r.style.display=X?"":"none";let o=document.getElementById("sp-delete");o.textContent=X?"\u5220\u9664\u8BB0\u5F55":"Delete",o.title=X?"\u5220\u9664\u5931\u6548\u8BB0\u5F55\uFF08\u5893\u7891\u6D88\u5931\uFF09":"Delete session";let l=document.getElementById("sp-divider");l&&(l.style.display=X?"":"none");let u=document.getElementById("sp-save");u.textContent=X?"\u91CD\u547D\u540D":"Save",Pe.classList.add("open"),Z.style.display="block",qi(t),setTimeout(()=>i.focus(),50)}function ve(){Pe.classList.remove("open"),Z.style.display="none"}Pe.addEventListener("click",ve),document.getElementById("sp-save").addEventListener("click",async()=>{let e=document.getElementById("sp-name").value.trim();if(!e||e===J){ve();return}try{let t=X?{oldName:J,newName:e,agentId:Q}:{oldName:J,newName:e,...Q?{agentId:Q}:{}};if(!(await fetch($(X?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;ve(),ae(),!X&&z===J&&(Q??null)===V&&Ae(e,Q)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+J+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{let e=await fetch($("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:J,agentId:Q})});if(!e.ok){let t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}ve(),ae()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(X){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+J+'"\uFF1F'))return;try{if(!(await fetch($("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:J,agentId:Q})})).ok)return;ve(),ae()}catch{}return}if(confirm('Delete session "'+J+'"?'))try{if(!(await fetch($("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:J,...Q?{agentId:Q}:{}})})).ok)return;ve(),z===J&&(Q??null)===V&&(S&&(S.destroy(),S=null),z=null,q.style.display="none",me.style.display="flex"),ae()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",ve);var Mn={esc:"\x1B",tab:" ","s-tab":"\x1B[Z",up:"\x1B[A",down:"\x1B[B",left:"\x1B[D",right:"\x1B[C",space:" ",enter:"\r","ctrl-r":"","ctrl-c":"",btw:"/btw ",yes:"yes\r"},dt=document.getElementById("mobile-keys"),Ji=new Set(["up","down","left","right","tab","s-tab","space"]),Yi=400,Ki=80,Ne=0,ct=0,ut=!1;function Xi(){Ne&&(clearTimeout(Ne),Ne=0),ct&&(clearInterval(ct),ct=0)}dt.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),dt.addEventListener("pointerdown",e=>{let t=e.target.closest("button[data-key]");if(!t)return;let n=t.dataset.key;Ji.has(n)&&(ut=!1,Ne=setTimeout(()=>{Ne=0,ut=!0,ct=setInterval(()=>{let i=Mn[n];i&&S&&S.sendInput(i)},Ki)},Yi))});for(let e of["pointerup","pointercancel","pointerleave"])dt.addEventListener(e,Xi);dt.addEventListener("click",e=>{let t=e.target.closest("button[data-key]");if(!t||!S)return;if(ut){ut=!1;return}let n=Mn[t.dataset.key];n&&(S.sendInput(n),S.focus())});var te=document.getElementById("mk-input"),In=document.getElementById("mk-send");function Bn(){if(!te||!S)return;let e=te.value;e&&(S.sendInput(e+"\r"),te.value="",te.rows=1,S.focus())}if(te&&(te.addEventListener("input",()=>{te.rows=1;let e=te.value.split(`
54
- `).length;te.rows=Math.min(e,4)}),te.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Bn())})),In&&In.addEventListener("click",Bn),window.visualViewport){let e=document.querySelector(".app-layout"),t=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",t),window.addEventListener("orientationchange",()=>setTimeout(t,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}var zt=document.getElementById("process-panel"),Ve=document.getElementById("proc-list"),Qi=document.getElementById("proc-close"),Ht=document.getElementById("proc-backdrop"),Zi=document.getElementById("header-ram");function Gi(){Ve.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch($("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){Ve.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(let n of e){let i=n.rss,a=i<1048576?(i/1024).toFixed(0)+"K":(i/1048576).toFixed(1)+"M";t+='<div class="proc-row" data-pid="'+n.pid+'"><span class="proc-mem">'+n.mem+'%</span><span class="proc-rss">'+a+'</span><span class="proc-cmd" title="'+C(n.command)+'">'+C(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">&times;</button></div>'}Ve.innerHTML=t;for(let n of Ve.querySelectorAll(".proc-row")){let i=n.querySelector(".proc-kill");i&&i.addEventListener("click",a=>{let r=a.target.closest(".proc-row");!r||!confirm("Kill PID "+r.dataset.pid+"?")||fetch($("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(r.dataset.pid,10)})}).then(o=>o.json()).then(o=>{o.ok?r.style.opacity="0.3":alert("Failed: "+(o.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{Ve.innerHTML='<div class="proc-empty">Failed to load</div>'})}function ea(){zt.classList.add("open"),Ht.classList.add("open"),Gi()}function pt(){zt.classList.remove("open"),Ht.classList.remove("open")}Zi.addEventListener("click",e=>{e.stopPropagation(),zt.classList.contains("open")?pt():ea()}),Qi.addEventListener("click",pt),Ht.addEventListener("click",pt);var ta=2e3,Oe=null,Dt=null,we=new Map,Ee=new Map,na=5e3,Tn=new Map;function At(e,t){return(t?"a:"+t+":":"l:")+e}function ia(e,t,n){let i=At(e,t);if(n==="working"){let p=Tn.get(i);if(p&&Date.now()<p)return}let a=Ee.get(i),r=e===z&&(t??null)===V,o=n==="idle"&&a?.state==="working";Ee.set(i,{session:e,agentId:t,state:n,doneUntil:o?Date.now()+ta:void 0,unread:o?!r:!1});let l=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',u=k.querySelector(l);u&&mt(u,i,Ee.get(i))}function mt(e,t,n){let i=we.get(t);i&&(clearTimeout(i),we.delete(t)),e.classList.remove("working","just-done");let a=n.session===z&&(n.agentId??null)===V;n.state==="working"?e.classList.add("working"):a&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),we.set(t,setTimeout(()=>{e.classList.remove("just-done"),we.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!a&&n.unread&&e.classList.add("just-done")}function Ft(){for(let[e,t]of Ee){let n=t.agentId?'.session-item[data-agent="'+CSS.escape(t.agentId)+'"][data-session="'+CSS.escape(t.session)+'"]':'.session-item[data-session="'+CSS.escape(t.session)+'"]:not([data-agent])',i=k.querySelector(n);i&&mt(i,e,t)}}function aa(e,t){let n=At(e,t),i=Ee.get(n);if(!i)return;let a=we.get(n);a&&(clearTimeout(a),we.delete(n)),i.doneUntil=void 0,i.unread=!1;let r=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',o=k.querySelector(r);o&&mt(o,n,i)}function zn(){if(Oe||Dt)return;let e=localStorage.getItem("tmux-web-token"),t=(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws/activity";e&&(t+="?token="+encodeURIComponent(e));try{let n=new WebSocket(t);Oe=n,n.onmessage=i=>{try{let a=JSON.parse(String(i.data));a&&a.type==="session.activity"&&typeof a.session=="string"&&ia(a.session,a.agentId||void 0,a.state==="working"?"working":"idle")}catch{}},n.onclose=()=>{Oe===n&&(Oe=null,Dt=setTimeout(()=>{Dt=null,zn()},5e3))},n.onerror=()=>{try{n.close()}catch{}}}catch{Oe=null}}window.__openSession=Ae,window.__refreshSidebar=ae,ae(),De(),Ft(),zn(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Ft()}),setInterval(()=>{document.visibilityState==="visible"&&ae()},1e4),Ci();
130
+ <button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>`,document.body.appendChild(ce);function Dl(t){let e=t.getBoundingClientRect(),n=window.innerHeight,i=ce.offsetHeight||240,s=e.bottom+4;s+i>n-8&&(s=Math.max(8,e.top-i-4)),ce.style.top=s+"px",ce.style.left=Math.max(8,Math.min(e.left,window.innerWidth-240))+"px"}function Wt(t,e,n){ne=t,ae=!!n?.tombstone,oe=n?.agentId;let i=document.getElementById("sp-name");i.value=t;let s=ce.querySelector(".sp-field label");s.textContent=ae?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";let l=document.getElementById("sp-rebuild");l.style.display=ae?"":"none";let r=document.getElementById("sp-delete");r.textContent=ae?"\u5220\u9664\u8BB0\u5F55":"Delete",r.title=ae?"\u5220\u9664\u5931\u6548\u8BB0\u5F55\uFF08\u5893\u7891\u6D88\u5931\uFF09":"Delete session";let a=document.getElementById("sp-divider");a&&(a.style.display=ae?"":"none");let o=document.getElementById("sp-save");o.textContent=ae?"\u91CD\u547D\u540D":"Save",mt.classList.add("open"),ce.style.display="block",Dl(e),setTimeout(()=>i.focus(),50)}function De(){mt.classList.remove("open"),ce.style.display="none"}mt.addEventListener("click",De),document.getElementById("sp-save").addEventListener("click",async()=>{let t=document.getElementById("sp-name").value.trim();if(!t||t===ne){De();return}try{let e=ae?{oldName:ne,newName:t,agentId:oe}:{oldName:ne,newName:t,...oe?{agentId:oe}:{}};if(!(await fetch(U(ae?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).ok)return;De(),ke(),!ae&&q===ne&&(oe??null)===Y&&pt(t,oe)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+ne+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{let t=await fetch(U("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:ne,agentId:oe})});if(!t.ok){let e=await t.json();alert(e.error||"\u91CD\u5EFA\u5931\u8D25");return}De(),ke()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(ae){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+ne+'"\uFF1F'))return;try{if(!(await fetch(U("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:ne,agentId:oe})})).ok)return;De(),ke()}catch{}return}if(confirm('Delete session "'+ne+'"?'))try{if(!(await fetch(U("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:ne,...oe?{agentId:oe}:{}})})).ok)return;De(),q===ne&&(oe??null)===Y&&(F&&(F.destroy(),F=null),q=null,te.style.display="none",Re.style.display="flex"),ke()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",De);var ss={esc:"\x1B",tab:" ","s-tab":"\x1B[Z",up:"\x1B[A",down:"\x1B[B",left:"\x1B[D",right:"\x1B[C",space:" ",enter:"\r","ctrl-r":"","ctrl-c":"",btw:"/btw ",yes:"yes\r"},Ut=document.getElementById("mobile-keys"),Hl=new Set(["up","down","left","right","tab","s-tab","space"]),_l=400,Fl=80,ft=0,Jt=0,Zt=!1;function Nl(){ft&&(clearTimeout(ft),ft=0),Jt&&(clearInterval(Jt),Jt=0)}Ut.addEventListener("mousedown",t=>{t.target.closest("button[data-key]")&&t.preventDefault()}),Ut.addEventListener("pointerdown",t=>{let e=t.target.closest("button[data-key]");if(!e)return;let n=e.dataset.key;Hl.has(n)&&(Zt=!1,ft=setTimeout(()=>{ft=0,Zt=!0,Jt=setInterval(()=>{let i=ss[n];i&&F&&F.sendInput(i)},Fl)},_l))});for(let t of["pointerup","pointercancel","pointerleave"])Ut.addEventListener(t,Nl);Ut.addEventListener("click",t=>{let e=t.target.closest("button[data-key]");if(!e||!F)return;if(Zt){Zt=!1;return}let n=ss[e.dataset.key];n&&(F.sendInput(n),F.focus())});var fe=document.getElementById("mk-input"),rs=document.getElementById("mk-send");function ls(){if(!fe||!F)return;let t=fe.value;t&&(F.sendInput(t+"\r"),fe.value="",fe.rows=1,F.focus())}if(fe&&(fe.addEventListener("input",()=>{fe.rows=1;let t=fe.value.split(`
131
+ `).length;fe.rows=Math.min(t,4)}),fe.addEventListener("keydown",t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),ls())})),rs&&rs.addEventListener("click",ls),window.visualViewport){let t=document.querySelector(".app-layout"),e=()=>{t&&(t.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",e),window.addEventListener("orientationchange",()=>setTimeout(e,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}var An=document.getElementById("process-panel"),gt=document.getElementById("proc-list"),Ol=document.getElementById("proc-close"),Rn=document.getElementById("proc-backdrop"),ql=document.getElementById("header-ram");function jl(){gt.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(U("/api/system/processes")).then(t=>t.json()).then(t=>{if(!Array.isArray(t)||!t.length){gt.innerHTML='<div class="proc-empty">No processes</div>';return}let e="";for(let n of t){let i=n.rss,s=i<1048576?(i/1024).toFixed(0)+"K":(i/1048576).toFixed(1)+"M";e+='<div class="proc-row" data-pid="'+n.pid+'"><span class="proc-mem">'+n.mem+'%</span><span class="proc-rss">'+s+'</span><span class="proc-cmd" title="'+D(n.command)+'">'+D(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">&times;</button></div>'}gt.innerHTML=e;for(let n of gt.querySelectorAll(".proc-row")){let i=n.querySelector(".proc-kill");i&&i.addEventListener("click",s=>{let l=s.target.closest(".proc-row");!l||!confirm("Kill PID "+l.dataset.pid+"?")||fetch(U("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(l.dataset.pid,10)})}).then(r=>r.json()).then(r=>{r.ok?l.style.opacity="0.3":alert("Failed: "+(r.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{gt.innerHTML='<div class="proc-empty">Failed to load</div>'})}function Vl(){An.classList.add("open"),Rn.classList.add("open"),jl()}function Yt(){An.classList.remove("open"),Rn.classList.remove("open")}ql.addEventListener("click",t=>{t.stopPropagation(),An.classList.contains("open")?Yt():Vl()}),Ol.addEventListener("click",Yt),Rn.addEventListener("click",Yt);var Wl=2e3,vt=null,Pn=null,Ve=new Map,We=new Map,Ul=5e3,as=new Map;function Dn(t,e){return(e?"a:"+e+":":"l:")+t}function Jl(t,e,n){let i=Dn(t,e);if(n==="working"){let c=as.get(i);if(c&&Date.now()<c)return}let s=We.get(i),l=t===q&&(e??null)===Y,r=n==="idle"&&s?.state==="working";We.set(i,{session:t,agentId:e,state:n,doneUntil:r?Date.now()+Wl:void 0,unread:r?!l:!1});let a=e?'.session-item[data-agent="'+CSS.escape(e)+'"][data-session="'+CSS.escape(t)+'"]':'.session-item[data-session="'+CSS.escape(t)+'"]:not([data-agent])',o=P.querySelector(a);o&&Xt(o,i,We.get(i))}function Xt(t,e,n){let i=Ve.get(e);i&&(clearTimeout(i),Ve.delete(e)),t.classList.remove("working","just-done");let s=n.session===q&&(n.agentId??null)===Y;n.state==="working"?t.classList.add("working"):s&&n.doneUntil&&Date.now()<n.doneUntil?(t.classList.add("just-done"),Ve.set(e,setTimeout(()=>{t.classList.remove("just-done"),Ve.delete(e)},Math.max(0,n.doneUntil-Date.now())))):!s&&n.unread&&t.classList.add("just-done")}function Hn(){for(let[t,e]of We){let n=e.agentId?'.session-item[data-agent="'+CSS.escape(e.agentId)+'"][data-session="'+CSS.escape(e.session)+'"]':'.session-item[data-session="'+CSS.escape(e.session)+'"]:not([data-agent])',i=P.querySelector(n);i&&Xt(i,t,e)}}function Zl(t,e){let n=Dn(t,e),i=We.get(n);if(!i)return;let s=Ve.get(n);s&&(clearTimeout(s),Ve.delete(n)),i.doneUntil=void 0,i.unread=!1;let l=e?'.session-item[data-agent="'+CSS.escape(e)+'"][data-session="'+CSS.escape(t)+'"]':'.session-item[data-session="'+CSS.escape(t)+'"]:not([data-agent])',r=P.querySelector(l);r&&Xt(r,n,i)}function os(){if(vt||Pn)return;let t=localStorage.getItem("tmux-web-token"),e=(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws/activity";t&&(e+="?token="+encodeURIComponent(t));try{let n=new WebSocket(e);vt=n,n.onmessage=i=>{try{let s=JSON.parse(String(i.data));s&&s.type==="session.activity"&&typeof s.session=="string"&&Jl(s.session,s.agentId||void 0,s.state==="working"?"working":"idle")}catch{}},n.onclose=()=>{vt===n&&(vt=null,Pn=setTimeout(()=>{Pn=null,os()},5e3))},n.onerror=()=>{try{n.close()}catch{}}}catch{vt=null}}window.__openSession=pt,window.__refreshSidebar=ke,ke(),dt(),Hn(),os(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Hn()}),setInterval(()=>{document.visibilityState==="visible"&&ke()},1e4),hl();