tmux-weblink 2.2.45 → 2.2.46

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,46 @@
1
- var ti=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function bt(e){return e.replace(/\x1b\[\?1049[hl]/g,"")}function Le(e){return e.replace(ti,"")}var Ue;function ni(){return Ue||(document.querySelector("link[data-tmux-web-xterm-css]")?Ue=Promise.resolve():(Ue=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)}),Ue))}var ii=class Dn{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(ai()==="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:s},{FitAddon:r}]=await Promise.all([import("./xterm-BXEES47M.js"),import("./addon-fit-D5N335P2.js"),ni()]),a="'JetBrains Mono', 'SF Mono', 'Menlo', monospace",o=new s({fontSize:si(14,a),fontFamily:a,cursorBlink:!0,cursorStyle:"bar",scrollback:n,convertEol:!1,smoothScrollDuration:120,theme:i});return new Dn(t,o,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=oi(this.container);if(t.width<=0||t.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 r=this.fitAddon.proposeDimensions?.();if(!r)return this.fitAddon.fit(),!0;let a=this.overlayScrollbarWidth(),o=a>0?a+2:0,p=s>0?Math.max(10,Math.min(r.cols,Math.floor((t.width-o)/s))):r.cols,u=r.rows;return(p!==this.terminal.cols||u!==this.terminal.rows)&&this.terminal.resize(p,u),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,[s,r]=t<=n?[t,n]:[n,t],a=i.viewportY,o=[];for(let p=s;p<=r;p++){let u=i.getLine(a+p);o.push(u?u.translateToString(!0):"")}return o.join(`
2
- `)}selectRows(t,n){let i=this.terminal.buffer.active,[s,r]=t<=n?[t,n]:[n,t];this.terminal.selectLines(i.viewportY+s,i.viewportY+r)}selectCells(t,n,i,s){let r=this.terminal.buffer.active,a=Math.min(n,s),o=Math.max(n,s);if(a===o){let p=Math.min(t,i),u=Math.max(t,i);this.terminal.select(p,r.viewportY+a,u-p+1)}else this.terminal.selectLines(r.viewportY+a,r.viewportY+o)}getCellsText(t,n,i,s){let r=this.terminal.buffer.active,a=Math.min(n,s),o=Math.max(n,s),p=n<s?t:n>s?i:Math.min(t,i),u=n<s?i:n>s?t:Math.max(t,i),h=r.viewportY,b=[];for(let B=a;B<=o;B++){let L=r.getLine(h+B);if(!L){b.push("");continue}let k=B===a?p:0,g=B===o?u:this.terminal.cols-1,M="";for(let F=k;F<=g;F++){let O=L.getCell(F);O&&(M+=O.getChars())}b.push(M.replace(/\s+$/,""))}return b.join(`
3
- `)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}};function si(e,t){try{let n=document.createElement("canvas").getContext("2d");if(!n)return e;let i=100;n.font=`${i}px ${t}`;let s=n.measureText("M").width/i;if(!Number.isFinite(s)||s<=0)return e;let r=window.devicePixelRatio||1,a=e,o=Number.POSITIVE_INFINITY;for(let p=4;p<=40;p++){let u=p/(s*r);if(u<e-1.5||u>e+1.5)continue;let h=Math.abs(u-e);h<o&&(o=h,a=u)}return Math.round(a*100)/100}catch{return e}}function ai(){try{let e=new URLSearchParams(window.location.search).get("renderer");return e==="dom"||e==="webgl"?e:null}catch{return null}}function oi(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 li(e,t,n){return e.innerHTML="",e.classList.add("terminal-pending"),(async()=>{let i=await ii.create(e,n.scrollback,n.theme),s,r=0,a,o=null,p=0,u=0,h=.2,b=10,B=.95,L=.04,k=null,g=null;function M(l){k||(k=document.createElement("div"),k.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(k)),k.textContent=l?"\u2191 \u4E0A\u7FFB\u4E00\u9875 (PgUp)":"\u2193 \u4E0B\u7FFB\u4E00\u9875 (PgDn)",k.style.top=l?"10%":"auto",k.style.bottom=l?"auto":"10%",k.style.opacity="1",g&&clearTimeout(g),g=setTimeout(()=>{k&&(k.style.opacity="0")},900)}function F(){g&&clearTimeout(g),k&&(k.style.opacity="0")}function O(){p&&(cancelAnimationFrame(p),p=0),u=0}function C(l){if(O(),Math.abs(l)<h)return;u=Math.max(-b,Math.min(b,l));let c=()=>{if(I){p=0;return}let f=i.cellHeight(),y=f>0?Math.round(u*16/f):u>0?1:-1;y===0&&(y=u>0?1:-1);let S=i.viewportY()-y,Z=i.baseY(),oe=Math.max(0,Math.min(S,Z));if(i.scrollToLine(oe,!0),u*=B,oe!==S){p=0;return}if(Math.abs(u)<L){p=0;return}p=requestAnimationFrame(c)};p=requestAnimationFrame(c)}let _=0,U="connecting",j=0,ae=!1,v=[],W="",I=!1,re=1e3,A=location.protocol==="https:"?"wss:":"ws:",Pt=n.wsBase||"/ws",$n=A+"//"+location.host+Pt+"/"+encodeURIComponent(t),An=(Pt.replace(/^\/ws/,"")||"")+"/api/session/"+encodeURIComponent(t)+"/upload",Pn=/^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(navigator.userAgent);function Nn(){return v.join("")+W}async function Fn(l,c=0){let f=l?i.viewportY():0,y=Le(Nn());if(i.reset(),!y){l||i.scrollToBottom();return}await i.write(y),l?i.scrollToLine(c+f):i.scrollToBottom()}function de(l){s?.readyState===WebSocket.OPEN&&s.send(JSON.stringify(l))}function On(l){let c;try{c=JSON.parse(l)}catch{U==="live"&&(W+=l,i.write(Le(l)));return}if(c.type==="auth.required"){let f=localStorage.getItem("tmux-web-token");f?de({type:"auth.token",token:f}):location.href="/login?returnTo="+encodeURIComponent(location.pathname+location.search);return}if(c.type==="attach_failed"&&typeof c.message=="string"){je=!0,U="dead",i.reset(),i.write(`\r
4
- \x1B[31m`+Le(c.message)+`\x1B[0m\r
5
- `).then(()=>{He();try{s?.close()}catch{}});return}if(c.type==="auth.ok"){c.token&&localStorage.setItem("tmux-web-token",c.token),re=1e3,ce(),de({type:"resize",cols:i.cols,rows:i.rows}),q();return}if(c.type==="auth.failed"){if(c.permanentLock||c.retryAfterMs&&c.retryAfterMs>6e4){localStorage.removeItem("tmux-web-token"),location.href="/login?error="+encodeURIComponent(c.message);return}return}if(c.type==="snapshot"&&typeof c.data=="string"){let f=bt(Le(c.data));v=[f],W="",j=typeof c.lines=="number"?c.lines:n.terminal.initialLines,U="live",i.reset(),ce(),de({type:"resize",cols:i.cols,rows:i.rows}),i.write(f).then(()=>i.scrollToBottom());return}if(c.type==="window_changed"&&typeof c.activeIndex=="number"){let f=new URL(location.href);f.searchParams.get("window")!==String(c.activeIndex)&&(f.searchParams.set("window",String(c.activeIndex)),history.replaceState(history.state,"",f)),window.dispatchEvent(new CustomEvent("tmux:windows",{detail:c.windows}));return}if(c.type==="history"&&typeof c.data=="string"){c.lines>0&&c.data?(v.unshift(bt(c.data)),j+=c.lines,Fn(!0,c.lines).finally(()=>{ae=!1})):ae=!1;return}if(c.type==="data"&&typeof c.data=="string"){let f=bt(Le(c.data));if(U==="connecting"){U="live",W=f,i.write(f);return}U==="live"&&(W+=f,i.write(f))}}let je=!1;function Nt(){if(je)return;let l=$n,c=localStorage.getItem("tmux-web-token");c&&(l+=(l.includes("?")?"&":"?")+"token="+encodeURIComponent(c)),l+=(l.includes("?")?"&":"?")+"cols="+i.cols+"&rows="+i.rows,s=new WebSocket(l),s.onopen=()=>{U="connecting",j=0,ae=!1,v=[],W="",i.reset(),re=1e3},s.onmessage=f=>{typeof f.data=="string"&&On(f.data)},s.onclose=()=>{I||(U="connecting",!je&&setTimeout(()=>{re=Math.min(re*2,1e4),!I&&!je&&Nt()},re))},s.onerror=()=>s?.close()}function he(l){de({type:"input",data:l})}function ce(){return i.fit()}function He(){e.classList.remove("terminal-pending")}function q(){r&&cancelAnimationFrame(r),a&&clearTimeout(a),ce(),r=requestAnimationFrame(()=>{r=0,ce()&&He()}),a=setTimeout(()=>{ce()&&He()},120)}function jn(){q(),setTimeout(q,50),setTimeout(q,150),setTimeout(q,300)}function Ft(l){return typeof l=="string"&&l.startsWith("image/")}function Ot(l){return l?.files?.length?l.files[0]??null:null}function Hn(l){if(!l?.items)return null;for(let c=0;c<l.items.length;c++){let f=l.items[c];if(f?.kind==="file"&&Ft(f.type))return f.getAsFile()}return null}async function Rn(l){let c=new FormData,f=l instanceof File&&l.name?l.name:"upload";c.append("file",l,f);let y=localStorage.getItem("tmux-web-token"),S={};y&&(S.Authorization="Bearer "+y);let Z=await fetch(An,{method:"POST",body:c,headers:S});if(!Z.ok){let Wt="upload failed";try{let qt=await Z.json();qt.error&&(Wt=qt.error)}catch{}throw new Error(Wt)}let oe=await Z.json();if(!oe.path)throw new Error("no path in response");return oe.path}async function ht(l){try{let c=await Rn(l);he(c)}catch{}}i.onData(l=>he(l)),i.onResize(({cols:l,rows:c})=>de({type:"resize",cols:l,rows:c})),i.onScroll(()=>{U!=="live"||ae||!i.isNearScrollbackTop()||(ae=!0,de({type:"load_history",before:j}))});let Ee=!1,ke=!1,P=null,H=null,Ce=document.createElement("div");Ce.className="terminal-copy-banner",Ce.innerHTML='<strong>Copy mode</strong><span class="hint">drag to copy \xB7 Esc exits</span>',Ce.hidden=!0,e.appendChild(Ce);let te=document.createElement("div");te.className="terminal-copy-banner terminal-copy-toast",te.textContent="Copied",te.hidden=!0,e.appendChild(te);function jt(l,c){let f=e.querySelector(".xterm-screen, canvas"),y=(f&&f.getBoundingClientRect().width>0?f:e).getBoundingClientRect(),S=y.height>0&&i.rows>0?y.height/i.rows:18,Z=y.width>0&&i.cols>0?y.width/i.cols:9;return{row:Math.max(0,Math.min(i.rows-1,Math.floor((c-y.top)/S))),col:Math.max(0,Math.min(i.cols-1,Math.floor((l-y.left)/Z)))}}async function Re(l){if(!l)return;try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(l);return}}catch{}let c=document.createElement("textarea");c.value=l,c.style.position="fixed",c.style.opacity="0",c.style.pointerEvents="none",document.body.appendChild(c),c.focus(),c.select();try{document.execCommand("copy")}catch{}c.remove()}let xe;function ze(){te.hidden=!1,xe&&clearTimeout(xe),xe=setTimeout(()=>{te.hidden=!0},1e3)}function ve(l){Ee=l,Ce.hidden=!l,e.classList.toggle("terminal-copy-mode-active",l),l&&i.focus()}function Ht(){ve(!Ee)}function zn(l){I||l.button!==0||ke||(Ee||l.shiftKey)&&(l.preventDefault(),l.stopPropagation(),ke=!0,P=jt(l.clientX,l.clientY),H=P,i.selectCells(P.col,P.row,H.col,H.row),document.addEventListener("mousemove",vt,!0),document.addEventListener("mouseup",gt,!0))}function vt(l){I||!ke||!P||(l.preventDefault(),l.stopPropagation(),H=jt(l.clientX,l.clientY),i.selectCells(P.col,P.row,H.col,H.row))}function gt(l){if(I||!ke||!P||!H)return;l.preventDefault(),l.stopPropagation(),document.removeEventListener("mousemove",vt,!0),document.removeEventListener("mouseup",gt,!0),ke=!1;let c=i.getCellsText(P.col,P.row,H.col,H.row);P=null,H=null,i.clearSelection(),ve(!1),c&&(te.textContent="\u5DF2\u590D\u5236",Re(c).then(ze)),i.focus()}e.addEventListener("mousedown",zn,!0),document.addEventListener("keydown",_n,!0);function _n(l){if(!(I||!i.isFocused()||l.defaultPrevented||l.isComposing)){if(Ee){if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),P=null,H=null,i.clearSelection(),ve(!1);return}if(l.key==="Enter"||(l.ctrlKey||l.metaKey)&&l.code==="KeyC"){l.preventDefault(),l.stopPropagation(),Re(i.getScreenText()).then(ze),ve(!1);return}}if(l.altKey&&l.code==="KeyC"&&!l.ctrlKey&&!l.metaKey){if(l.preventDefault(),l.stopPropagation(),P&&H){let c=i.getCellsText(P.col,P.row,H.col,H.row);P=null,H=null,i.clearSelection(),ve(!1),c&&(te.textContent="Copied",Re(c).then(ze))}else{let c=i.getSelection();c?(i.clearSelection(),te.textContent="Copied",Re(c).then(ze)):Ht()}return}if((l.ctrlKey||l.metaKey)&&l.code==="KeyV"){l.preventDefault(),l.stopPropagation(),(async()=>{try{if(navigator.clipboard?.read){let c=await navigator.clipboard.read();for(let f of c)for(let y of f.types)if(Ft(y)){let S=await f.getType(y);await ht(S);return}}}catch{}try{let c=await navigator.clipboard?.readText();c&&i.pasteText(Rt(c))}catch{}})();return}}}let _e=0;function Rt(l){return l.split(`\r
1
+ var ei=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function vt(e){return e.replace(/\x1b\[\?1049[hl]/g,"")}function Se(e){return e.replace(ei,"")}var Ue;function ti(){return Ue||(document.querySelector("link[data-tmux-web-xterm-css]")?Ue=Promise.resolve():(Ue=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)}),Ue))}var ni=class Mn{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:s},{FitAddon:r}]=await Promise.all([import("./xterm-BXEES47M.js"),import("./addon-fit-D5N335P2.js"),ti()]),a="'JetBrains Mono', 'SF Mono', 'Menlo', monospace",o=new s({fontSize:ii(14,a),fontFamily:a,cursorBlink:!0,cursorStyle:"bar",scrollback:n,convertEol:!1,smoothScrollDuration:120,theme:i});return new Mn(t,o,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=ai(this.container);if(t.width<=0||t.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 r=this.fitAddon.proposeDimensions?.();if(!r)return this.fitAddon.fit(),!0;let a=this.overlayScrollbarWidth(),o=a>0?a+2:0,p=s>0?Math.max(10,Math.min(r.cols,Math.floor((t.width-o)/s))):r.cols,u=r.rows;return(p!==this.terminal.cols||u!==this.terminal.rows)&&this.terminal.resize(p,u),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,[s,r]=t<=n?[t,n]:[n,t],a=i.viewportY,o=[];for(let p=s;p<=r;p++){let u=i.getLine(a+p);o.push(u?u.translateToString(!0):"")}return o.join(`
2
+ `)}selectRows(t,n){let i=this.terminal.buffer.active,[s,r]=t<=n?[t,n]:[n,t];this.terminal.selectLines(i.viewportY+s,i.viewportY+r)}selectCells(t,n,i,s){let r=this.terminal.buffer.active,a=Math.min(n,s),o=Math.max(n,s);if(a===o){let p=Math.min(t,i),u=Math.max(t,i);this.terminal.select(p,r.viewportY+a,u-p+1)}else this.terminal.selectLines(r.viewportY+a,r.viewportY+o)}getCellsText(t,n,i,s){let r=this.terminal.buffer.active,a=Math.min(n,s),o=Math.max(n,s),p=n<s?t:n>s?i:Math.min(t,i),u=n<s?i:n>s?t:Math.max(t,i),h=r.viewportY,b=[];for(let M=a;M<=o;M++){let C=r.getLine(h+M);if(!C){b.push("");continue}let y=M===a?p:0,g=M===o?u:this.terminal.cols-1,A="";for(let F=y;F<=g;F++){let O=C.getCell(F);O&&(A+=O.getChars())}b.push(A.replace(/\s+$/,""))}return b.join(`
3
+ `)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}};function ii(e,t){try{let n=document.createElement("canvas").getContext("2d");if(!n)return e;let i=100;n.font=`${i}px ${t}`;let s=n.measureText("M").width/i;if(!Number.isFinite(s)||s<=0)return e;let r=window.devicePixelRatio||1,a=e,o=Number.POSITIVE_INFINITY;for(let p=4;p<=40;p++){let u=p/(s*r);if(u<e-1.5||u>e+1.5)continue;let h=Math.abs(u-e);h<o&&(o=h,a=u)}return Math.round(a*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 ai(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 oi(e,t,n){return e.innerHTML="",e.classList.add("terminal-pending"),(async()=>{let i=await ni.create(e,n.scrollback,n.theme),s,r=0,a,o=null,p=0,u=0,h=.2,b=10,M=.95,C=.04,y=null,g=null;function A(l){y||(y=document.createElement("div"),y.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(y)),y.textContent=l?"\u2191 \u4E0A\u7FFB\u4E00\u9875 (PgUp)":"\u2193 \u4E0B\u7FFB\u4E00\u9875 (PgDn)",y.style.top=l?"10%":"auto",y.style.bottom=l?"auto":"10%",y.style.opacity="1",g&&clearTimeout(g),g=setTimeout(()=>{y&&(y.style.opacity="0")},900)}function F(){g&&clearTimeout(g),y&&(y.style.opacity="0")}function O(){p&&(cancelAnimationFrame(p),p=0),u=0}function x(l){if(O(),Math.abs(l)<h)return;u=Math.max(-b,Math.min(b,l));let c=()=>{if(I){p=0;return}let f=i.cellHeight(),w=f>0?Math.round(u*16/f):u>0?1:-1;w===0&&(w=u>0?1:-1);let L=i.viewportY()-w,Z=i.baseY(),oe=Math.max(0,Math.min(L,Z));if(i.scrollToLine(oe,!0),u*=M,oe!==L){p=0;return}if(Math.abs(u)<C){p=0;return}p=requestAnimationFrame(c)};p=requestAnimationFrame(c)}let _=0,U="connecting",H=0,ae=!1,v=[],W="",I=!1,le=1e3,$=location.protocol==="https:"?"wss:":"ws:",$t=n.wsBase||"/ws",An=$+"//"+location.host+$t+"/"+encodeURIComponent(t),Dn=($t.replace(/^\/ws/,"")||"")+"/api/session/"+encodeURIComponent(t)+"/upload",$n=/^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(navigator.userAgent);function Pn(){return v.join("")+W}async function Nn(l,c=0){let f=l?i.viewportY():0,w=Se(Pn());if(i.reset(),!w){l||i.scrollToBottom();return}await i.write(w),l?i.scrollToLine(c+f):i.scrollToBottom()}function re(l){s?.readyState===WebSocket.OPEN&&s.send(JSON.stringify(l))}function Fn(l){let c;try{c=JSON.parse(l)}catch{U==="live"&&(W+=l,i.write(Se(l)));return}if(c.type==="auth.required"){let f=localStorage.getItem("tmux-web-token");f?re({type:"auth.token",token:f}):location.href="/login?returnTo="+encodeURIComponent(location.pathname+location.search);return}if(c.type==="attach_failed"&&typeof c.message=="string"){He=!0,U="dead",i.reset(),i.write(`\r
4
+ \x1B[31m`+Se(c.message)+`\x1B[0m\r
5
+ `).then(()=>{je();try{s?.close()}catch{}});return}if(c.type==="auth.ok"){c.token&&localStorage.setItem("tmux-web-token",c.token),le=1e3,de(),re({type:"resize",cols:i.cols,rows:i.rows}),q();return}if(c.type==="auth.failed"){if(c.permanentLock||c.retryAfterMs&&c.retryAfterMs>6e4){localStorage.removeItem("tmux-web-token"),location.href="/login?error="+encodeURIComponent(c.message);return}return}if(c.type==="snapshot"&&typeof c.data=="string"){let f=vt(Se(c.data));v=[f],W="",H=typeof c.lines=="number"?c.lines:n.terminal.initialLines,U="live",i.reset(),de(),re({type:"resize",cols:i.cols,rows:i.rows}),i.write(f).then(()=>i.scrollToBottom());return}if(c.type==="window_changed"&&typeof c.activeIndex=="number"){let f=new URL(location.href);f.searchParams.get("window")!==String(c.activeIndex)&&(f.searchParams.set("window",String(c.activeIndex)),history.replaceState(history.state,"",f)),window.dispatchEvent(new CustomEvent("tmux:windows",{detail:c.windows}));return}if(c.type==="history"&&typeof c.data=="string"){c.lines>0&&c.data?(v.unshift(vt(c.data)),H+=c.lines,Nn(!0,c.lines).finally(()=>{ae=!1})):ae=!1;return}if(c.type==="data"&&typeof c.data=="string"){let f=vt(Se(c.data));if(U==="connecting"){U="live",W=f,i.write(f);return}U==="live"&&(W+=f,i.write(f))}}let He=!1;function Pt(){if(He)return;let l=An,c=localStorage.getItem("tmux-web-token");c&&(l+=(l.includes("?")?"&":"?")+"token="+encodeURIComponent(c)),l+=(l.includes("?")?"&":"?")+"cols="+i.cols+"&rows="+i.rows,s=new WebSocket(l),s.onopen=()=>{U="connecting",H=0,ae=!1,v=[],W="",i.reset(),le=1e3},s.onmessage=f=>{typeof f.data=="string"&&Fn(f.data)},s.onclose=()=>{I||(U="connecting",!He&&setTimeout(()=>{le=Math.min(le*2,1e4),!I&&!He&&Pt()},le))},s.onerror=()=>s?.close()}function he(l){re({type:"input",data:l})}function de(){return i.fit()}function je(){e.classList.remove("terminal-pending")}function q(){r&&cancelAnimationFrame(r),a&&clearTimeout(a),de(),r=requestAnimationFrame(()=>{r=0,de()&&je()}),a=setTimeout(()=>{de()&&je()},120)}function On(){q(),setTimeout(q,50),setTimeout(q,150),setTimeout(q,300)}function Nt(l){return typeof l=="string"&&l.startsWith("image/")}function Ft(l){return l?.files?.length?l.files[0]??null:null}function Hn(l){if(!l?.items)return null;for(let c=0;c<l.items.length;c++){let f=l.items[c];if(f?.kind==="file"&&Nt(f.type))return f.getAsFile()}return null}async function jn(l){let c=new FormData,f=l instanceof File&&l.name?l.name:"upload";c.append("file",l,f);let w=localStorage.getItem("tmux-web-token"),L={};w&&(L.Authorization="Bearer "+w);let Z=await fetch(Dn,{method:"POST",body:c,headers:L});if(!Z.ok){let Ut="upload failed";try{let Wt=await Z.json();Wt.error&&(Ut=Wt.error)}catch{}throw new Error(Ut)}let oe=await Z.json();if(!oe.path)throw new Error("no path in response");return oe.path}async function mt(l){try{let c=await jn(l);he(c)}catch{}}i.onData(l=>he(l)),i.onResize(({cols:l,rows:c})=>re({type:"resize",cols:l,rows:c})),i.onScroll(()=>{U!=="live"||ae||!i.isNearScrollbackTop()||(ae=!0,re({type:"load_history",before:H}))});let we=!1,Ee=!1,P=null,j=null,ke=document.createElement("div");ke.className="terminal-copy-banner",ke.innerHTML='<strong>Copy mode</strong><span class="hint">drag to copy \xB7 Esc exits</span>',ke.hidden=!0,e.appendChild(ke);let ee=document.createElement("div");ee.className="terminal-copy-banner terminal-copy-toast",ee.textContent="Copied",ee.hidden=!0,e.appendChild(ee);function Ot(l,c){let f=e.querySelector(".xterm-screen, canvas"),w=(f&&f.getBoundingClientRect().width>0?f:e).getBoundingClientRect(),L=w.height>0&&i.rows>0?w.height/i.rows:18,Z=w.width>0&&i.cols>0?w.width/i.cols:9;return{row:Math.max(0,Math.min(i.rows-1,Math.floor((c-w.top)/L))),col:Math.max(0,Math.min(i.cols-1,Math.floor((l-w.left)/Z)))}}async function Re(l){if(!l)return;try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(l);return}}catch{}let c=document.createElement("textarea");c.value=l,c.style.position="fixed",c.style.opacity="0",c.style.pointerEvents="none",document.body.appendChild(c),c.focus(),c.select();try{document.execCommand("copy")}catch{}c.remove()}let Ce;function ze(){ee.hidden=!1,Ce&&clearTimeout(Ce),Ce=setTimeout(()=>{ee.hidden=!0},1e3)}function ve(l){we=l,ke.hidden=!l,e.classList.toggle("terminal-copy-mode-active",l),l&&i.focus()}function Ht(){ve(!we)}function Rn(l){I||l.button!==0||Ee||(we||l.shiftKey)&&(l.preventDefault(),l.stopPropagation(),Ee=!0,P=Ot(l.clientX,l.clientY),j=P,i.selectCells(P.col,P.row,j.col,j.row),document.addEventListener("mousemove",ft,!0),document.addEventListener("mouseup",ht,!0))}function ft(l){I||!Ee||!P||(l.preventDefault(),l.stopPropagation(),j=Ot(l.clientX,l.clientY),i.selectCells(P.col,P.row,j.col,j.row))}function ht(l){if(I||!Ee||!P||!j)return;l.preventDefault(),l.stopPropagation(),document.removeEventListener("mousemove",ft,!0),document.removeEventListener("mouseup",ht,!0),Ee=!1;let c=i.getCellsText(P.col,P.row,j.col,j.row);P=null,j=null,i.clearSelection(),ve(!1),c&&(ee.textContent="\u5DF2\u590D\u5236",Re(c).then(ze)),i.focus()}e.addEventListener("mousedown",Rn,!0),document.addEventListener("keydown",zn,!0);function zn(l){if(!(I||!i.isFocused()||l.defaultPrevented||l.isComposing)){if(we){if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),P=null,j=null,i.clearSelection(),ve(!1);return}if(l.key==="Enter"||(l.ctrlKey||l.metaKey)&&l.code==="KeyC"){l.preventDefault(),l.stopPropagation(),Re(i.getScreenText()).then(ze),ve(!1);return}}if(l.altKey&&l.code==="KeyC"&&!l.ctrlKey&&!l.metaKey){if(l.preventDefault(),l.stopPropagation(),P&&j){let c=i.getCellsText(P.col,P.row,j.col,j.row);P=null,j=null,i.clearSelection(),ve(!1),c&&(ee.textContent="Copied",Re(c).then(ze))}else{let c=i.getSelection();c?(i.clearSelection(),ee.textContent="Copied",Re(c).then(ze)):Ht()}return}if((l.ctrlKey||l.metaKey)&&l.code==="KeyV"){l.preventDefault(),l.stopPropagation(),(async()=>{try{if(navigator.clipboard?.read){let c=await navigator.clipboard.read();for(let f of c)for(let w of f.types)if(Nt(w)){let L=await f.getType(w);await mt(L);return}}}catch{}try{let c=await navigator.clipboard?.readText();c&&i.pasteText(jt(c))}catch{}})();return}}}let _e=0;function jt(l){return l.split(`\r
6
6
  `).join(`
7
7
  `).split(`
8
- `).join("\r")}async function Un(l){let c=Hn(l.clipboardData);if(c){l.preventDefault(),l.stopPropagation();let S=Date.now();if(S-_e<50)return;_e=S,await ht(c);return}let f=l.clipboardData?.getData("text/plain");if(!f)return;l.preventDefault(),l.stopPropagation();let y=Date.now();y-_e<50||(_e=y,i.pasteText(Rt(f)))}let Se=0;function Wn(l){l.preventDefault(),Se++,Ot(l.dataTransfer)&&e.classList.add("terminal-drag-over")}function qn(l){l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect="copy")}function Jn(l){l.preventDefault(),Se--,Se<=0&&(Se=0,e.classList.remove("terminal-drag-over"))}async function Yn(l){l.preventDefault(),Se=0,e.classList.remove("terminal-drag-over");let c=Ot(l.dataTransfer);c&&await ht(c)}function zt(l){!Pn||l.key!=="Escape"||Ee||l.defaultPrevented||l.repeat||l.metaKey||l.ctrlKey||l.altKey||i.isFocused()&&(l.preventDefault(),l.stopPropagation(),he("\x1B"))}e.addEventListener("paste",Un),e.addEventListener("dragenter",Wn),e.addEventListener("dragover",qn),e.addEventListener("dragleave",Jn),e.addEventListener("drop",Yn),document.addEventListener("keydown",zt,!0);function Vn(l){if(l.touches.length!==1){o=null;return}let c=l.touches[0];if(!c)return;O();let f=e.getBoundingClientRect(),y=c.clientX-f.left<f.width*.4?"tui":"history",S=c.clientY-f.top<f.height*.5;o={startX:c.clientX,startY:c.clientY,lastX:c.clientX,lastY:c.clientY,lastT:performance.now(),velocity:0,scrolling:!1,zone:y,tuiUp:S,sent:!1},l.stopPropagation()}function Kn(l){if(!o||l.touches.length!==1)return;let c=l.touches[0];if(!c)return;let f=c.clientY-o.startY,y=c.clientX-o.startX;if(!o.scrolling){if(Math.abs(f)<8||Math.abs(f)<Math.abs(y))return;o.scrolling=!0,_=Date.now()+500}l.preventDefault(),l.stopPropagation();let S=performance.now(),Z=c.clientY-o.lastY;if(o.zone==="tui"){o.sent||(o.sent=!0,he(o.tuiUp?"\x1B[5~":"\x1B[6~"),M(o.tuiUp)),o.lastX=c.clientX,o.lastY=c.clientY,o.lastT=S;return}let oe=S-o.lastT;oe>0&&(o.velocity=Z/oe),Gn(-Z),o.lastX=c.clientX,o.lastY=c.clientY,o.lastT=S}function Xn(l){if(!o)return;let c=o.scrolling,f=o.zone,y=o.tuiUp,S=o.velocity;if(o=null,l.stopPropagation(),f==="tui"){c||(he(y?"\x1B[5~":"\x1B[6~"),M(y),_=Date.now()+500,l.preventDefault());return}if(!c){i.focus();return}_=Date.now()+500,l.preventDefault(),S&&C(S)}function Qn(l){o=null,O(),l.stopPropagation()}function Zn(l){l.pointerType==="touch"&&Date.now()<_&&(l.preventDefault(),l.stopPropagation())}function Gn(l){let c=i.cellHeight(),f=c>0?Math.round(l/c):l>0?1:-1;f===0&&(f=l>0?1:-1),i.scrollLines(f)}e.addEventListener("touchstart",Vn,{passive:!0,capture:!0}),e.addEventListener("touchmove",Kn,{passive:!1,capture:!0}),e.addEventListener("touchend",Xn,{passive:!1,capture:!0}),e.addEventListener("touchcancel",Qn,{passive:!0,capture:!0}),e.addEventListener("pointerup",Zn,!0);function _t(){q()}window.addEventListener("resize",_t),window.visualViewport?.addEventListener("resize",q),window.visualViewport?.addEventListener("scroll",q);let Ut=new ResizeObserver(()=>q());Ut.observe(e),document.fonts?.ready.then(()=>{q(),setTimeout(q,50),setTimeout(q,200)}),e.addEventListener("focusin",jn,!0);async function ei(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(l=>setTimeout(l,1e3))])}catch{}}return requestAnimationFrame(()=>{ce()&&He(),(async()=>(await ei(),ce()&&de({type:"resize",cols:i.cols,rows:i.rows}),Nt(),q()))()}),{destroy(){if(I=!0,O(),ve(!1),xe&&clearTimeout(xe),document.removeEventListener("mousemove",vt,!0),document.removeEventListener("mouseup",gt,!0),s){try{s.close(1e3,"session switch")}catch{}s=void 0}e.innerHTML="",e.classList.remove("terminal-pending"),window.removeEventListener("resize",_t),Ut.disconnect(),document.removeEventListener("keydown",zt,!0)},focus(){i.focus()},sendInput(l){he(l)},toggleCopyMode(){Ht()}}})()}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 D(e,t){let n=await fetch(e,{...t,headers:{"content-type":"application/json",Authorization:`Bearer ${yt()}`,...t?.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 d(e,t,n){let i=document.createElement(e);return t&&(i.className=t),n!==void 0&&(i.textContent=n),i}function ri(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 di(){let e=d("div","bots-section");e.id="bots-section";let t=d("div","bots-head"),n=d("span","bots-title","Bots"),i=d("span","bots-badge");i.hidden=!0,n.appendChild(i);let s=d("span","bots-head-actions"),r=d("button","bots-icon-btn","\u2699");r.title="Bot templates",r.onclick=()=>void Ye();let a=d("button","bots-icon-btn","+");a.title="New bot from template",a.onclick=()=>void yi(),s.append(r,a),t.append(n,s);let o=d("div","bots-list");o.id="bots-list",e.append(t,o);let p=document.querySelector(".sidebar"),u=document.querySelector(".sidebar-footer");return p&&p.insertBefore(e,u||null),{list:o,badge:i}}var wt=null,We=null;function qe(){wt&&(wt.textContent="");let e=m.approvals.length;We&&(We.hidden=e===0,We.textContent=String(e));let t=document.getElementById("bv-inbox-count");t&&(t.textContent=e?`(${e})`:""),window.__botsSnapshot=m.bots,window.__refreshSidebar?.()}function ci(){let e=d("div","bots-view");e.id="bots-view",e.hidden=!0;let t=d("div","bots-view-head"),n=d("div","bv-title"),i=d("span","bots-dot");i.id="bv-dot";let s=d("span","bv-title-text");s.id="bv-title";let r=d("span","bv-status");r.id="bv-status",n.append(i,s,r);let a=d("div","bv-actions"),o=d("select","bv-mode-select");o.id="bv-mode",o.title="Approval mode for this bot";for(let[C,_]of[["supervised","Approve every tool"],["auto-accept-edits","Auto-accept edits"],["full-access","No approvals"]])o.appendChild(new Option(_,C));o.onchange=()=>{m.activeId&&D(`/api/bots/${m.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:o.value})}).then(()=>pe({kind:"notice",level:"info",text:`Approval mode: ${o.value}`})).catch(C=>pe({kind:"notice",level:"error",text:C instanceof Error?C.message:String(C)}))};let p=d("button","btn","Allow all");p.id="bv-allow-all",p.title="Approve every pending request for this bot",p.onclick=()=>{if(!m.activeId)return;let C=m.approvals.filter(_=>_.botId===m.activeId);Promise.all(C.map(_=>D(`/api/bots/${_.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:_.id,allow:!0})}))).finally(()=>void K(!0))};let u=d("button","btn","Needs you "),h=d("span");h.id="bv-inbox-count",u.appendChild(h),u.onclick=()=>void tn();let b=d("button","btn","Resume");b.onclick=()=>void Yt(C=>D(`/api/bots/${C}/resume`,{method:"POST"}).then(()=>K(!0)));let B=d("button","btn danger","Stop");B.onclick=()=>void Yt(C=>D(`/api/bots/${C}/stop`,{method:"POST"}).then(()=>K(!0)));let L=d("button","btn","Delete");L.onclick=()=>{m.activeId&&confirm("Delete this bot and its session?")&&D(`/api/bots/${m.activeId}`,{method:"DELETE"}).then(()=>{Et(),K(!0)})};let k=d("button","btn","\u2715");k.onclick=()=>Et(),a.append(o,p,u,b,B,L,k),t.append(n,a);let g=d("div","bots-messages");g.id="bots-messages";let M=d("div","bots-composer"),F=d("textarea");F.id="bots-input",F.rows=1,F.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",F.onkeydown=C=>{C.key==="Enter"&&!C.shiftKey&&(C.preventDefault(),Jt())};let O=d("button","btn primary","Send");O.onclick=()=>void Jt(),M.append(F,O),e.append(t,g,M),document.querySelector(".main-area")?.appendChild(e),document.getElementById("bots-modal")||gi()}async function Jt(){let e=document.getElementById("bots-input");if(!e||!m.activeId||!e.value.trim())return;let t=e.value;e.value="";try{await D(`/api/bots/${m.activeId}/input`,{method:"POST",body:JSON.stringify({text:t})})}catch(n){pe({kind:"notice",level:"error",text:n instanceof Error?n.message:String(n)})}}function Yt(e){m.activeId&&e(m.activeId).catch(t=>pe({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)}))}function Et(){m.activeId=null;let e=document.getElementById("bots-view");e&&(e.hidden=!0);try{m.ws?.close()}catch{}m.ws=null,qe();let t=document.getElementById("main-placeholder");t&&(t.style.display="")}async function Vt(e){m.activeId=e,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 s=document.getElementById("file-editor");s&&(s.style.display="none"),qe(),kt();try{m.ws?.close()}catch{}let r=location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(`${r}//${location.host}/ws/bots/${encodeURIComponent(e)}?token=${encodeURIComponent(yt())}`);m.ws=a,a.onmessage=o=>{try{Qt(JSON.parse(String(o.data)))}catch{}},a.onclose=()=>{m.activeId===e&&setTimeout(()=>{m.activeId===e&&K(!0)},1500)},await K(!0)}function Kt(){return m.bots.find(e=>e.id===m.activeId)||null}function Xt(){let e=Kt();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 s=document.getElementById("bv-mode");s&&e.runtimeMode&&(s.value=e.runtimeMode);let r=document.getElementById("bv-allow-all"),a=m.approvals.filter(o=>o.botId===e.id).length;r&&(r.hidden=a===0,r.textContent=`Allow all (${a})`),i&&(i.style.background=ri(e.status))}function pe(e,t=m.activeId){if(!t)return;let n=m.items.get(t)||[];n.push(e),m.items.set(t,n),t===m.activeId&&ue()}function ue(){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 s=d("div","bv-msg bv-user");s.textContent=i.text,e.appendChild(s),n=null}else if(i.kind==="assistant"){let s=d("div","bv-msg bv-assistant");if(i.thinking){let a=d("details","bv-thinking");a.appendChild(d("summary",void 0,"thinking")),a.appendChild(d("div",void 0,i.thinking)),s.appendChild(a)}let r=d("div","bv-text");r.textContent=i.text,s.appendChild(r),e.appendChild(s),n=r}else if(i.kind==="tool")e.appendChild(pi(i)),n=null;else if(i.kind==="approval")e.appendChild(ui(i)),n=null;else if(i.kind==="notice"){let s=d("div",`bv-notice bv-notice-${i.level}`,i.text);e.appendChild(s)}n&&(n.scrollTop=n.scrollHeight),e.scrollTop=e.scrollHeight}function pi(e){let t=d("details","bv-tool");t.open=e.phase!=="end"||!!e.isError;let n=d("summary"),i=d("span","bv-tool-name",e.name);if(n.appendChild(i),e.phase!=="end"&&n.appendChild(d("span","bv-tool-phase",e.phase)),e.isError&&n.appendChild(d("span","bv-tool-error","error")),typeof e.durationMs=="number"&&n.appendChild(d("span","bv-tool-meta",`${Math.round(e.durationMs)}ms`)),t.appendChild(n),e.args!==void 0){let s=d("pre","bv-pre");s.textContent=typeof e.args=="string"?e.args:JSON.stringify(e.args,null,2),t.appendChild(s)}if(e.output){let s=d("pre","bv-pre bv-output");s.textContent=e.output,t.appendChild(s)}return t}function ui(e){let t=d("div","bv-approval"),n=e.approval;if(t.appendChild(d("div","bv-approval-title",n.title)),n.message&&t.appendChild(d("pre","bv-pre",n.message)),e.decided)return t.appendChild(d("div","bv-approval-decided",e.decided==="allowed"?"Allowed":"Denied")),t;let i=d("input","bv-reason");i.placeholder="reason (optional)";let s=d("div","bv-approval-actions"),r=d("button","btn primary","Allow"),a=d("button","btn",n.method==="confirm"&&/^Allow (.+?)\?$/.test(n.title)?`Always allow ${/^Allow (.+?)\?$/.exec(n.title)?.[1]}`:"Always allow");a.hidden=n.method!=="confirm";let o=d("button","btn danger","Deny"),p=async(u,h=!1)=>{try{await D(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:u,always:h,reason:i.value||void 0})}),e.decided=u?"allowed":"denied",ue(),K(!0)}catch(b){pe({kind:"notice",level:"error",text:b instanceof Error?b.message:String(b)})}};return r.onclick=()=>void p(!0),a.onclick=()=>void p(!0,!0),o.onclick=()=>void p(!1),s.append(i,r,a,o),t.appendChild(s),t}function Qt(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")pe({kind:"user",text:String(e.text||"")});else if(t==="status"){let s=Kt();s&&(s.status=String(e.status||s.status)),Xt(),hi()}else if(t==="message"){let s=e.message;if(!s||String(s.role||"")!=="assistant")return;let r=mi(s),a=fi(s),o=i[i.length-1];o&&o.kind==="assistant"?(o.text=r||o.text,o.thinking=a||o.thinking):i.push({kind:"assistant",text:r,thinking:a}),m.items.set(n,i),ue()}else if(t==="delta"){let s=String(e.kind||""),r=String(e.delta||""),a=i[i.length-1];(!a||a.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),a=i[i.length-1]),a.kind==="assistant"&&(s==="text"?a.text+=r:s==="thinking"&&(a.thinking+=r)),m.items.set(n,i),ue()}else if(t==="tool"){let s=String(e.callId||""),r=i.find(o=>o.kind==="tool"&&o.callId===s),a=String(e.phase||"start");r?(r.phase=a,a==="update"&&e.output&&(r.output=String(e.output)),a==="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:s,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:a}),m.items.set(n,i),ue()}else if(t==="approval"){let s=e.approval;if(!s)return;let r=i;for(let a=r.length-1;a>=0;a--){let o=r[a];if(o.kind==="approval"&&o.approval.id===s.id){o.approval=s,s.state!=="pending"&&(o.decided=s.state==="allowed"?"allowed":"denied"),m.items.set(n,r),ue();return}}r.push({kind:"approval",approval:s}),m.items.set(n,r),ue()}else t==="notice"&&pe({kind:"notice",level:String(e.level||"info"),text:String(e.text||"")})}function mi(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 fi(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 K(e=!1){try{let[t,n]=await Promise.all([D("/api/bots"),D("/api/bots/approvals")]);if(m.bots=t,m.approvals=n,qe(),Xt(),e&&m.activeId){let i=await D(`/api/bots/${m.activeId}/events?limit=300`);vi(i)}}catch{}}async function hi(){try{m.bots=await D("/api/bots"),qe()}catch{}}function vi(e){if(m.activeId){m.items.set(m.activeId,[]);for(let t of e)Qt(t);kt()}}function gi(){let e=d("div","bots-modal");e.id="bots-modal",e.hidden=!0;let t=d("div","bots-modal-card"),n=d("div","bots-modal-head"),i=d("span");i.id="bots-modal-title";let s=d("button","btn","\u2715");s.onclick=()=>Je(),n.append(i,s);let r=d("div","bots-modal-body");r.id="bots-modal-body",t.append(n,r),e.appendChild(t),e.onclick=a=>{a.target===e&&Je()},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 Je(){let e=document.getElementById("bots-modal");e&&(e.hidden=!0)}async function bi(){return m.catalog||(m.catalog=await D("/api/bots/catalog")),m.catalog}async function Zt(){return m.templates=await D("/api/bots/templates"),m.templates}async function Ye(){let e=Ct("Bot templates"),[t,n]=await Promise.all([bi(),Zt()]),i=d("div","bv-template-list");for(let p of n){let u=d("div","bv-template-row");u.appendChild(d("span","bv-template-name",p.manifest.name)),u.appendChild(d("span","bv-template-desc",p.manifest.description||""));let h=d("button","btn","Edit");h.onclick=()=>Gt(e,t,p);let b=d("button","btn danger","Delete");b.onclick=()=>{confirm(`Delete template ${p.manifest.name}?`)&&D(`/api/bots/templates/${p.id}`,{method:"DELETE"}).then(()=>Ye())};let B=d("span","bv-template-actions");B.append(h,b),u.appendChild(B),i.appendChild(u)}n.length===0&&i.appendChild(d("div","bots-empty","No templates yet")),e.appendChild(i);let s=d("div","bv-template-actions"),r=d("button","btn primary","New template");r.onclick=()=>Gt(e,t,null);let a=d("button","btn","Export");a.title="Download templates + library as JSON",a.onclick=()=>{(async()=>{try{let p=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${yt()}`}});if(!p.ok)throw new Error(`HTTP ${p.status}`);let u=await p.blob(),h=document.createElement("a");h.href=URL.createObjectURL(u),h.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,h.click(),setTimeout(()=>URL.revokeObjectURL(h.href),2e3)}catch(p){alert(p instanceof Error?p.message:String(p))}})()};let o=d("button","btn","Import");o.title="Restore templates from a JSON bundle",o.onclick=()=>{let p=document.createElement("input");p.type="file",p.accept="application/json,.json",p.onchange=()=>{let u=p.files?.[0];u&&(async()=>{try{let h=JSON.parse(await u.text()),b=await D("/api/bots/import",{method:"POST",body:JSON.stringify(h)});alert(`Imported ${b.templates} templates, ${b.files} library files (${b.skipped} kept)`),await Ye()}catch(h){alert(h instanceof Error?h.message:String(h))}})()},p.click()},s.append(r,a,o),e.appendChild(s)}function xt(e,t,n){let i=d("div","bv-field");i.appendChild(d("label","bv-label",e));let s=d("div","bv-check-grid"),r=[];for(let a of t){let o=d("label","bv-check"),p=document.createElement("input");p.type="checkbox",p.checked=n.includes(a.id),o.append(p,d("span",void 0,a.label)),a.hint&&(o.title=a.hint),s.appendChild(o),r.push({id:a.id,input:p})}return i.appendChild(s),{element:i,get:()=>r.filter(a=>a.input.checked).map(a=>a.id)}}function Gt(e,t,n){e.textContent="";let i=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},s=d("input","bv-input");s.value=i.name,s.placeholder="Template name";let r=d("input","bv-input");r.value=i.description||"",r.placeholder="One line description";let a=d("textarea","bv-textarea");a.rows=6,a.value=i.system||"",a.placeholder="System prompt for this bot (written to SYSTEM.md)";let o=xt("Skills",t.skills.map(v=>({id:v.id,label:v.name,hint:v.description})),i.skills||[]),p=xt("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)$/,""))),u=xt("Prompt templates",t.prompts.map(v=>({id:v.id,label:v.name})),i.prompts||[]),h=d("select","bv-input");h.appendChild(new Option("none",""));for(let v of t.mcp)h.appendChild(new Option(v.name,v.id));i.mcp&&(h.value=t.mcp.find(v=>JSON.stringify(v.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");let b=d("div","bv-field");b.appendChild(d("label","bv-label","Tools (allow list; deny always blocks)"));let B=d("div","bv-check-grid"),L=[];for(let v of t.tools){let W=d("label","bv-check"),I=document.createElement("input");I.type="checkbox",I.checked=(i.tools?.allow||[]).includes(v.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(v.name),W.append(I,d("span",void 0,v.name)),B.appendChild(W),L.push({name:v.name,input:I})}b.appendChild(B);let k=d("input","bv-input");k.value=(i.tools?.deny||[]).join(", "),k.placeholder="Always deny (comma separated), e.g. bash, write";let g=d("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=d("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 F=d("select","bv-input");for(let v of["","off","minimal","low","medium","high","xhigh","max"])F.appendChild(new Option(v||"default",v));i.model?.thinking&&(F.value=i.model.thinking);let O=d("select","bv-input");for(let v of["supervised","auto-accept-edits","full-access"])O.appendChild(new Option(v,v));O.value=i.permissions?.runtimeMode||"supervised";let C=d("select","bv-input");C.appendChild(new Option("ignore project .pi (recommended)","ignore")),C.appendChild(new Option("inherit project .pi (needs trust)","inherit")),C.value=i.projectResources||"ignore";let _=d("label","bv-check"),U=document.createElement("input");U.type="checkbox",U.checked=!!i.orchestrator,_.append(U,d("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));let j=(v,W)=>{let I=d("div","bv-field");return I.appendChild(d("label","bv-label",v)),I.appendChild(W),I};e.append(j("Name",s),j("Description",r),j("System prompt",a),o.element,p.element,u.element,j("MCP preset",h),b,j("Always deny tools",k),j("Packages",g),j("Model",M),j("Thinking level",F),j("Approval mode",O),j("Project resources",C),_);let ae=d("button","btn primary",n?"Save template":"Create template");ae.onclick=async()=>{let[v,W]=M.value.split(`
12
- `),I=t.mcp.find(A=>A.id===h.value),re={name:s.value.trim()||"bot",description:r.value.trim()||void 0,system:a.value.trim()||void 0,skills:o.get(),extensions:p.get().map(A=>(A.startsWith("builtin:"),A)),prompts:u.get(),packages:g.value.split(`
13
- `).map(A=>A.trim()).filter(Boolean),mcp:I?{mcpServers:I.servers}:void 0,tools:{allow:L.filter(A=>A.input.checked).map(A=>A.name),deny:k.value.split(",").map(A=>A.trim()).filter(Boolean)},model:v?{provider:v,id:W,thinking:F.value||void 0}:void 0,permissions:{runtimeMode:O.value},projectResources:C.value==="inherit"?"inherit":"ignore",orchestrator:U.checked||void 0};try{await D("/api/bots/templates",{method:"POST",body:JSON.stringify({id:n?.id,manifest:re})}),Je(),await Ye()}catch(A){alert(A instanceof Error?A.message:String(A))}},e.appendChild(ae)}async function yi(){return en("")}async function en(e){let t=Ct("New bot"),n=await Zt();if(n.length===0){t.appendChild(d("div","bots-empty","Create a template first (\u2699)."));return}let i=d("select","bv-input");for(let u of n)i.appendChild(new Option(u.manifest.name,u.id));let s=d("input","bv-input");s.placeholder="Title (defaults to template name)";let r=d("input","bv-input");r.placeholder="/path/to/project";let a=e||m.bots[0]?.projectPath||"";r.value=a;let o=d("select","bv-input");o.appendChild(new Option("shared \u2014 run in the project folder","shared")),o.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),t.append(Ve("Template",i),Ve("Title",s),Ve("Project path",r),Ve("Workspace",o));let p=d("button","btn primary","Create bot");p.onclick=async()=>{try{let u=await D("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:s.value.trim()||void 0,projectPath:r.value.trim()||void 0,isolation:o.value})});Je(),await K(!0),await Vt(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},t.appendChild(p)}function Ve(e,t){let n=d("div","bv-field");return n.appendChild(d("label","bv-label",e)),n.appendChild(t),n}async function tn(){let e=Ct("Needs you");if(m.approvals=await D("/api/bots/approvals"),m.approvals.length===0){e.appendChild(d("div","bots-empty","Nothing waiting."));return}for(let t of m.approvals){let n=d("div","bv-approval");n.appendChild(d("div","bv-approval-title",`${t.botTitle}: ${t.title}`)),t.message&&n.appendChild(d("pre","bv-pre",t.message));let i=d("input","bv-reason");i.placeholder="reason (optional)";let s=d("div","bv-approval-actions"),r=d("button","btn primary","Allow"),a=d("button","btn danger","Deny"),o=async p=>{await D(`/api/bots/${t.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:t.id,allow:p,reason:i.value||void 0})}),await K(!0),await tn()};r.onclick=()=>void o(!0),a.onclick=()=>void o(!1),s.append(i,r,a),n.appendChild(s),e.appendChild(n)}}function wi(){if(document.getElementById("bots-section"))return;let e=di();wt=e.list,We=e.badge,ci(),window.__openBot=Vt,document.addEventListener("click",t=>{let n=t.target;n&&n.closest(".session-item")&&m.activeId&&Et()},!0),K(!0),m.pollTimer=window.setInterval(()=>{document.hidden||K()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(m.pollTimer))}var Ie=window.__TMUX_WEB_SHELL__,x=null,T=null,Te=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null,R=Te;window.__tmuxWebScopeAgent=Te;var St="sessions",ne="",Ke="",Xe="",nn="";function N(e){return R?"/a/"+encodeURIComponent(R)+e:e}var w=document.getElementById("sidebar-content"),me=document.getElementById("main-placeholder"),J=document.getElementById("terminal-container"),Be=document.getElementById("file-editor"),Ei=document.getElementById("fe-path"),X=document.getElementById("fe-status"),Me=document.getElementById("fe-content"),fe=document.getElementById("fe-save"),ki=document.getElementById("fe-delete"),Ci=document.getElementById("fe-back"),sn=document.getElementById("fe-new-name"),xi=document.getElementById("fe-new-btn"),Lt=document.getElementById("settings-backdrop"),an=document.getElementById("settings-popover"),on=document.querySelector(".sidebar"),ln="tmux-web-force-narrow";function Qe(){try{return localStorage.getItem(ln)==="1"}catch{return!1}}function rn(){document.documentElement.classList.toggle("force-narrow",Qe()),Qe()&&dn()&&Ze()}function dn(){return Qe()?!0:window.matchMedia("(max-width: 640px)").matches}function Ze(){dn()&&on.classList.add("collapsed")}function cn(){on.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{cn(),pn("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{cn(),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="",ie()):Hi()}var It="";async function ie(){if(St!=="sessions")return;try{let t=await(await fetch("/api/sidebar/sessions")).json(),n=(window.__botsSnapshot||[]).map(s=>[s.id,s.title,s.status,s.projectPath]),i=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones,bots:n});if(i===It)return;It=i,Mi(t)}catch{w.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")}),At()}var un="tmux-web-sidebar-group-collapsed";function mn(){try{return new Set(JSON.parse(localStorage.getItem(un)||"[]"))}catch{return new Set}}function Si(e){try{localStorage.setItem(un,JSON.stringify([...e]))}catch{}}function Li(e,t,n){if(!e)return"\u2026";let i=n&&(e===n||e.startsWith(n+"/"))?"~"+e.slice(n.length):e,s=i.split("/").filter(Boolean);if(s.length===0)return e;for(let r=1;r<=s.length;r++){let a=s.slice(-r).join("/");if(!t.some(o=>!o||o===e?!1:(n&&(o===n||o.startsWith(n+"/"))?"~"+o.slice(n.length):o).split("/").filter(Boolean).slice(-r).join("/")===a))return a}return i}function Ii(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=`<svg class="bot-icon" viewBox="0 0 24 24" fill="currentColor"><path d="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"/></svg><span>${E(e.title)}</span><span class="bot-status-dot" style="background:${n}"></span>`,t.addEventListener("click",i=>{i.stopPropagation(),window.__openBot?.(e.id)}),t}function fn(e,t,n,i=!0){let s=new Map;for(let u of e){let h=u.path||"";s.has(h)||s.set(h,[]),s.get(h).push(u)}let r=n?[]:window.__botsSnapshot||[],a=new Map;for(let u of r)s.has(u.projectPath)||s.set(u.projectPath,[]),a.has(u.projectPath)||a.set(u.projectPath,[]),a.get(u.projectPath).push(u);let o=[...s.keys()],p=mn();for(let[u,h]of s){let b=Li(u,o,t),B=p.has(u),L=document.createElement("div");if(L.className="session-group-header"+(B?" collapsed":""),L.title=u||"No working directory",L.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${E(b)}</span>`,!n&&u){let g=document.createElement("button");g.className="sg-add-bot",g.textContent="+",g.title=`New bot in ${u}`,g.addEventListener("click",M=>{M.stopPropagation(),lt(u)}),L.appendChild(g)}L.addEventListener("click",()=>{let g=mn(),M=L.nextElementSibling;g.has(u)?(g.delete(u),L.classList.remove("collapsed"),M?.classList.remove("collapsed")):(g.add(u),L.classList.add("collapsed"),M?.classList.add("collapsed")),Si(g)});let k=document.createElement("div");k.className="session-group-body"+(B?" collapsed":"");for(let g of h)k.appendChild(n?Ti(g,n,i):Bi(g,u));for(let g of a.get(u)||[])k.appendChild(Ii(g));w.appendChild(L),w.appendChild(k)}}function Ti(e,t,n){let i=document.createElement("div");i.className="session-item"+(e.name===T&&R===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>${E(e.name)}</span>${n?"":'<span class="meta">offline</span>'}
15
- <button class="session-edit-btn" data-session="${E(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")||De(e.name,t)});let s=i.querySelector(".session-edit-btn");return s&&s.addEventListener("click",r=>{r.stopPropagation(),dt(e.name,s,{agentId:t})}),i}function Bi(e,t){let n=document.createElement("div");n.className="session-item"+(e.name===T&&!R?" active":""),n.setAttribute("data-session",e.name),n.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>${E(e.name)}</span>
17
- <button class="session-edit-btn" data-session="${E(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
- `,n.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||De(e.name)});let i=n.querySelector(".session-edit-btn");return i&&i.addEventListener("click",s=>{s.stopPropagation(),dt(e.name,i,{sessionPath:t})}),n}function Mi(e){w.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="/"})),w.appendChild(n),fn(t,e.home);let i=e.agents||[];for(let r of i){if(!r.sessions||r.sessions.length===0)continue;let a=r.agentId===R,o=document.createElement("div");o.className="sidebar-section-label machine-label"+(r.online?"":" agent-offline-label")+(!a&&r.online?" clickable":""),o.textContent=r.agentName+(r.online?"":" (offline)"),!a&&r.online&&(o.title="\u6253\u5F00 "+r.agentName,o.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(r.agentId)+"/"})),w.appendChild(o),fn(r.sessions,e.home,r.agentId,r.online)}let s=e.tombstones||[];if(s.length>0){let r=document.createElement("div");r.className="sidebar-section-label tombstone-label",r.textContent="\u5931\u6548\u4F1A\u8BDD",w.appendChild(r);for(let a of s){let o=document.createElement("div");o.className="session-item session-tombstone",o.setAttribute("data-session",a.name),a.agentId&&o.setAttribute("data-agent",a.agentId);let p=a.agentId?a.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";o.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
19
- <span>${E(a.name)}</span><span class="meta">\u5931\u6548${p}</span>
20
- <button class="session-edit-btn" data-session="${E(a.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>`,o.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",o.addEventListener("click",()=>{dt(a.name,o,{tombstone:!0,agentId:a.agentId})});let u=o.querySelector(".session-edit-btn");u&&u.addEventListener("click",h=>{h.stopPropagation(),dt(a.name,u,{tombstone:!0,agentId:a.agentId})}),w.appendChild(o)}}}function E(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function De(e,t){if(T===e&&x&&R===(t||null))return;Be.style.display="none",me.style.display="none",J.style.display="",J.classList.add("terminal-pending"),Ze(),x&&(ot(),x.destroy(),x=null),T=e,R=t||null,window.__tmuxWebScopeAgent=R,window.__tmuxWebCurrentSession=T,ts(e,t);let n=$t(e,t);Bn.set(n,Date.now()+Gi);let i=we.get(n);if(i&&i.state==="working"){i.state="idle",i.doneUntil=void 0,i.unread=!1;let s=w.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');s&&ft(s,n,i)}for(let s of w.querySelectorAll(".session-item"))s.classList.toggle("active",s.getAttribute("data-session")===e&&(s.getAttribute("data-agent")||null)===R);try{x=await li(J,e,{terminal:Ie.terminal,scrollback:Ie.scrollback,theme:Ie.theme,wsBase:R?"/ws/a/"+encodeURIComponent(R):Ie.wsBase||"/ws"}),xn()}catch(s){console.error("[shell] terminal init failed:",s);let r=s&&typeof s=="object"&&"message"in s?s.message:String(s);J.textContent="Failed to open terminal for "+e+": "+r,J.classList.remove("terminal-pending")}}var Ge=[],$=null,hn=!1;function Di(e){if(!$||!$.files.length)return null;let t=$.repoRoot;if(!t||!e.startsWith(t))return null;let n=e.slice(t.length+1);for(let i of $.files)if(i.path===n)return i.status;return null}async function $i(e){hn=!0;try{let t=await fetch(N("/api/git/status?path="+encodeURIComponent(e)));t.ok?$=await t.json():$=null}catch{$=null}finally{hn=!1}}function Ai(){if(!$||!$.branch)return"";let{branch:e,linesAdded:t,linesRemoved:n}=$,i=`<div class="sidebar-git"><div class="git-branch-badge">
8
+ `).join("\r")}async function _n(l){let c=Hn(l.clipboardData);if(c){l.preventDefault(),l.stopPropagation();let L=Date.now();if(L-_e<50)return;_e=L,await mt(c);return}let f=l.clipboardData?.getData("text/plain");if(!f)return;l.preventDefault(),l.stopPropagation();let w=Date.now();w-_e<50||(_e=w,i.pasteText(jt(f)))}let xe=0;function Un(l){l.preventDefault(),xe++,Ft(l.dataTransfer)&&e.classList.add("terminal-drag-over")}function Wn(l){l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect="copy")}function qn(l){l.preventDefault(),xe--,xe<=0&&(xe=0,e.classList.remove("terminal-drag-over"))}async function Jn(l){l.preventDefault(),xe=0,e.classList.remove("terminal-drag-over");let c=Ft(l.dataTransfer);c&&await mt(c)}function Rt(l){!$n||l.key!=="Escape"||we||l.defaultPrevented||l.repeat||l.metaKey||l.ctrlKey||l.altKey||i.isFocused()&&(l.preventDefault(),l.stopPropagation(),he("\x1B"))}e.addEventListener("paste",_n),e.addEventListener("dragenter",Un),e.addEventListener("dragover",Wn),e.addEventListener("dragleave",qn),e.addEventListener("drop",Jn),document.addEventListener("keydown",Rt,!0);function Yn(l){if(l.touches.length!==1){o=null;return}let c=l.touches[0];if(!c)return;O();let f=e.getBoundingClientRect(),w=c.clientX-f.left<f.width*.4?"tui":"history",L=c.clientY-f.top<f.height*.5;o={startX:c.clientX,startY:c.clientY,lastX:c.clientX,lastY:c.clientY,lastT:performance.now(),velocity:0,scrolling:!1,zone:w,tuiUp:L,sent:!1},l.stopPropagation()}function Kn(l){if(!o||l.touches.length!==1)return;let c=l.touches[0];if(!c)return;let f=c.clientY-o.startY,w=c.clientX-o.startX;if(!o.scrolling){if(Math.abs(f)<8||Math.abs(f)<Math.abs(w))return;o.scrolling=!0,_=Date.now()+500}l.preventDefault(),l.stopPropagation();let L=performance.now(),Z=c.clientY-o.lastY;if(o.zone==="tui"){o.sent||(o.sent=!0,he(o.tuiUp?"\x1B[5~":"\x1B[6~"),A(o.tuiUp)),o.lastX=c.clientX,o.lastY=c.clientY,o.lastT=L;return}let oe=L-o.lastT;oe>0&&(o.velocity=Z/oe),Zn(-Z),o.lastX=c.clientX,o.lastY=c.clientY,o.lastT=L}function Vn(l){if(!o)return;let c=o.scrolling,f=o.zone,w=o.tuiUp,L=o.velocity;if(o=null,l.stopPropagation(),f==="tui"){c||(he(w?"\x1B[5~":"\x1B[6~"),A(w),_=Date.now()+500,l.preventDefault());return}if(!c){i.focus();return}_=Date.now()+500,l.preventDefault(),L&&x(L)}function Xn(l){o=null,O(),l.stopPropagation()}function Qn(l){l.pointerType==="touch"&&Date.now()<_&&(l.preventDefault(),l.stopPropagation())}function Zn(l){let c=i.cellHeight(),f=c>0?Math.round(l/c):l>0?1:-1;f===0&&(f=l>0?1:-1),i.scrollLines(f)}e.addEventListener("touchstart",Yn,{passive:!0,capture:!0}),e.addEventListener("touchmove",Kn,{passive:!1,capture:!0}),e.addEventListener("touchend",Vn,{passive:!1,capture:!0}),e.addEventListener("touchcancel",Xn,{passive:!0,capture:!0}),e.addEventListener("pointerup",Qn,!0);function zt(){q()}window.addEventListener("resize",zt),window.visualViewport?.addEventListener("resize",q),window.visualViewport?.addEventListener("scroll",q);let _t=new ResizeObserver(()=>q());_t.observe(e),document.fonts?.ready.then(()=>{q(),setTimeout(q,50),setTimeout(q,200)}),e.addEventListener("focusin",On,!0);async function Gn(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(l=>setTimeout(l,1e3))])}catch{}}return requestAnimationFrame(()=>{de()&&je(),(async()=>(await Gn(),de()&&re({type:"resize",cols:i.cols,rows:i.rows}),Pt(),q()))()}),{destroy(){if(I=!0,O(),ve(!1),Ce&&clearTimeout(Ce),document.removeEventListener("mousemove",ft,!0),document.removeEventListener("mouseup",ht,!0),s){try{s.close(1e3,"session switch")}catch{}s=void 0}e.innerHTML="",e.classList.remove("terminal-pending"),window.removeEventListener("resize",zt),_t.disconnect(),document.removeEventListener("keydown",Rt,!0)},focus(){i.focus()},sendInput(l){he(l)},toggleCopyMode(){Ht()}}})()}var m={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function gt(){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 ${gt()}`,...t?.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 d(e,t,n){let i=document.createElement(e);return t&&(i.className=t),n!==void 0&&(i.textContent=n),i}function li(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 ri(){let e=d("div","bots-section");e.id="bots-section";let t=d("div","bots-head"),n=d("span","bots-title","Bots"),i=d("span","bots-badge");i.hidden=!0,n.appendChild(i);let s=d("span","bots-head-actions"),r=d("button","bots-icon-btn","\u2699");r.title="Bot templates",r.onclick=()=>void Le();let a=d("button","bots-icon-btn","+");a.title="New bot from template",a.onclick=()=>void bi(),s.append(r,a),t.append(n,s);let o=d("div","bots-list");o.id="bots-list",e.append(t,o);let p=document.querySelector(".sidebar"),u=document.querySelector(".sidebar-footer");return p&&p.insertBefore(e,u||null),{list:o,badge:i}}var bt=null,We=null;function qe(){bt&&(bt.textContent="");let e=m.approvals.length;We&&(We.hidden=e===0,We.textContent=String(e));let t=document.getElementById("bv-inbox-count");t&&(t.textContent=e?`(${e})`:""),window.__botsSnapshot=m.bots,window.__refreshSidebar?.()}function di(){let e=d("div","bots-view");e.id="bots-view",e.hidden=!0;let t=d("div","bots-view-head"),n=d("div","bv-title"),i=d("span","bots-dot");i.id="bv-dot";let s=d("span","bv-title-text");s.id="bv-title";let r=d("span","bv-status");r.id="bv-status",n.append(i,s,r);let a=d("div","bv-actions"),o=d("select","bv-mode-select");o.id="bv-mode",o.title="Approval mode for this bot";for(let[x,_]of[["supervised","\u9ED8\u8BA4\uFF1A\u53EA\u8BFB\u81EA\u52A8\uFF0C\u5176\u4F59\u95EE\u6211"],["parent-supervised","Super agent \u76D1\u7BA1\uFF1A\u4EA4\u7ED9\u4E0A\u7EA7 bot"],["full-access","Full access\uFF1A\u5168\u90E8\u653E\u884C"]])o.appendChild(new Option(_,x));o.onchange=()=>{m.activeId&&T(`/api/bots/${m.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:o.value})}).then(()=>ce({kind:"notice",level:"info",text:`Approval mode: ${o.value}`})).catch(x=>ce({kind:"notice",level:"error",text:x instanceof Error?x.message:String(x)}))};let p=d("button","btn","Allow all");p.id="bv-allow-all",p.title="Approve every pending request for this bot",p.onclick=()=>{if(!m.activeId)return;let x=m.approvals.filter(_=>_.botId===m.activeId);Promise.all(x.map(_=>T(`/api/bots/${_.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:_.id,allow:!0})}))).finally(()=>void K(!0))};let u=d("button","btn","Needs you "),h=d("span");h.id="bv-inbox-count",u.appendChild(h),u.onclick=()=>void en();let b=d("button","btn","Resume");b.onclick=()=>void Jt(x=>T(`/api/bots/${x}/resume`,{method:"POST"}).then(()=>K(!0)));let M=d("button","btn danger","Stop");M.onclick=()=>void Jt(x=>T(`/api/bots/${x}/stop`,{method:"POST"}).then(()=>K(!0)));let C=d("button","btn","Delete");C.onclick=()=>{m.activeId&&confirm("Delete this bot and its session?")&&T(`/api/bots/${m.activeId}`,{method:"DELETE"}).then(()=>{yt(),K(!0)})};let y=d("button","btn","\u2715");y.onclick=()=>yt(),a.append(o,p,u,b,M,C,y),t.append(n,a);let g=d("div","bots-messages");g.id="bots-messages";let A=d("div","bots-composer"),F=d("textarea");F.id="bots-input",F.rows=1,F.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",F.onkeydown=x=>{x.key==="Enter"&&!x.shiftKey&&(x.preventDefault(),qt())};let O=d("button","btn primary","Send");O.onclick=()=>void qt(),A.append(F,O),e.append(t,g,A),document.querySelector(".main-area")?.appendChild(e),document.getElementById("bots-modal")||vi()}async function qt(){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){ce({kind:"notice",level:"error",text:n instanceof Error?n.message:String(n)})}}function Jt(e){m.activeId&&e(m.activeId).catch(t=>ce({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)}))}function yt(){m.activeId=null;let e=document.getElementById("bots-view");e&&(e.hidden=!0);try{m.ws?.close()}catch{}m.ws=null,qe();let t=document.getElementById("main-placeholder");t&&(t.style.display="")}async function Yt(e){m.activeId=e,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 s=document.getElementById("file-editor");s&&(s.style.display="none"),qe(),wt();try{m.ws?.close()}catch{}let r=location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(`${r}//${location.host}/ws/bots/${encodeURIComponent(e)}?token=${encodeURIComponent(gt())}`);m.ws=a,a.onmessage=o=>{try{Xt(JSON.parse(String(o.data)))}catch{}},a.onclose=()=>{m.activeId===e&&setTimeout(()=>{m.activeId===e&&K(!0)},1500)},await K(!0)}function Kt(){return m.bots.find(e=>e.id===m.activeId)||null}function Vt(){let e=Kt();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 s=document.getElementById("bv-mode");s&&e.runtimeMode&&(s.value=e.runtimeMode);let r=document.getElementById("bv-allow-all"),a=m.approvals.filter(o=>o.botId===e.id).length;r&&(r.hidden=a===0,r.textContent=`Allow all (${a})`),i&&(i.style.background=li(e.status))}function ce(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,wt()}))}function wt(){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 s=d("div","bv-msg bv-user");s.textContent=i.text,e.appendChild(s),n=null}else if(i.kind==="assistant"){let s=d("div","bv-msg bv-assistant");if(i.thinking){let a=d("details","bv-thinking");a.appendChild(d("summary",void 0,"thinking")),a.appendChild(d("div",void 0,i.thinking)),s.appendChild(a)}let r=d("div","bv-text");r.textContent=i.text,s.appendChild(r),e.appendChild(s),n=r}else if(i.kind==="tool")e.appendChild(ci(i)),n=null;else if(i.kind==="approval")e.appendChild(pi(i)),n=null;else if(i.kind==="notice"){let s=d("div",`bv-notice bv-notice-${i.level}`,i.text);e.appendChild(s)}n&&(n.scrollTop=n.scrollHeight),e.scrollTop=e.scrollHeight}function ci(e){let t=d("details","bv-tool");t.open=e.phase!=="end"||!!e.isError;let n=d("summary"),i=d("span","bv-tool-name",e.name);if(n.appendChild(i),e.phase!=="end"&&n.appendChild(d("span","bv-tool-phase",e.phase)),e.isError&&n.appendChild(d("span","bv-tool-error","error")),typeof e.durationMs=="number"&&n.appendChild(d("span","bv-tool-meta",`${Math.round(e.durationMs)}ms`)),t.appendChild(n),e.args!==void 0){let s=d("pre","bv-pre");s.textContent=typeof e.args=="string"?e.args:JSON.stringify(e.args,null,2),t.appendChild(s)}if(e.output){let s=d("pre","bv-pre bv-output");s.textContent=e.output,t.appendChild(s)}return t}function pi(e){let t=d("div","bv-approval"),n=e.approval;if(t.appendChild(d("div","bv-approval-title",n.title)),n.message&&t.appendChild(d("pre","bv-pre",n.message)),e.decided)return t.appendChild(d("div","bv-approval-decided",e.decided==="allowed"?"Allowed":"Denied")),t;let i=d("input","bv-reason");i.placeholder="reason (optional)";let s=d("div","bv-approval-actions"),r=d("button","btn primary","Allow"),a=d("button","btn",n.method==="confirm"&&/^Allow (.+?)\?$/.test(n.title)?`Always allow ${/^Allow (.+?)\?$/.exec(n.title)?.[1]}`:"Always allow");a.hidden=n.method!=="confirm";let o=d("button","btn danger","Deny"),p=async(u,h=!1)=>{try{await T(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:u,always:h,reason:i.value||void 0})}),e.decided=u?"allowed":"denied",pe(),K(!0)}catch(b){ce({kind:"notice",level:"error",text:b instanceof Error?b.message:String(b)})}};return r.onclick=()=>void p(!0),a.onclick=()=>void p(!0,!0),o.onclick=()=>void p(!1),s.append(i,r,a,o),t.appendChild(s),t}function Xt(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")ce({kind:"user",text:String(e.text||"")});else if(t==="status"){let s=Kt();s&&(s.status=String(e.status||s.status)),Vt(),fi()}else if(t==="message"){let s=e.message;if(!s||String(s.role||"")!=="assistant")return;let r=ui(s),a=mi(s),o=i[i.length-1];o&&o.kind==="assistant"?(o.text=r||o.text,o.thinking=a||o.thinking):i.push({kind:"assistant",text:r,thinking:a}),m.items.set(n,i),pe()}else if(t==="delta"){let s=String(e.kind||""),r=String(e.delta||""),a=i[i.length-1];(!a||a.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),a=i[i.length-1]),a.kind==="assistant"&&(s==="text"?a.text+=r:s==="thinking"&&(a.thinking+=r)),m.items.set(n,i),pe()}else if(t==="tool"){let s=String(e.callId||""),r=i.find(o=>o.kind==="tool"&&o.callId===s),a=String(e.phase||"start");r?(r.phase=a,a==="update"&&e.output&&(r.output=String(e.output)),a==="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:s,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:a}),m.items.set(n,i),pe()}else if(t==="approval"){let s=e.approval;if(!s)return;let r=i;for(let a=r.length-1;a>=0;a--){let o=r[a];if(o.kind==="approval"&&o.approval.id===s.id){o.approval=s,s.state!=="pending"&&(o.decided=s.state==="allowed"?"allowed":"denied"),m.items.set(n,r),pe();return}}r.push({kind:"approval",approval:s}),m.items.set(n,r),pe()}else t==="notice"&&ce({kind:"notice",level:String(e.level||"info"),text:String(e.text||"")})}function ui(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 mi(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 K(e=!1){try{let[t,n]=await Promise.all([T("/api/bots"),T("/api/bots/approvals")]);if(m.bots=t,m.approvals=n,qe(),Vt(),e&&m.activeId){let i=await T(`/api/bots/${m.activeId}/events?limit=300`);hi(i)}}catch{}}async function fi(){try{m.bots=await T("/api/bots"),qe()}catch{}}function hi(e){if(m.activeId){m.items.set(m.activeId,[]);for(let t of e)Xt(t);wt()}}function vi(){let e=d("div","bots-modal");e.id="bots-modal",e.hidden=!0;let t=d("div","bots-modal-card"),n=d("div","bots-modal-head"),i=d("span");i.id="bots-modal-title";let s=d("button","btn","\u2715");s.onclick=()=>Je(),n.append(i,s);let r=d("div","bots-modal-body");r.id="bots-modal-body",t.append(n,r),e.appendChild(t),e.onclick=a=>{a.target===e&&Je()},document.body.appendChild(e)}function Et(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 Je(){let e=document.getElementById("bots-modal");e&&(e.hidden=!0)}async function gi(){return m.catalog||(m.catalog=await T("/api/bots/catalog")),m.catalog}async function Qt(){return m.templates=await T("/api/bots/templates"),m.templates}async function Le(){let e=Et("Bot templates"),[t,n]=await Promise.all([gi(),Qt()]),i=d("div","bv-template-list");for(let p of n){let u=d("div","bv-template-row");u.appendChild(d("span","bv-template-name",p.manifest.name)),u.appendChild(d("span","bv-template-desc",p.manifest.description||""));let h=d("button","btn","Edit");h.onclick=()=>Zt(e,t,p);let b=d("button","btn","Copy");b.title="Duplicate this template",b.onclick=()=>{let y=JSON.parse(JSON.stringify(p.manifest));y.name=`${p.manifest.name} copy`,T("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:y})}).then(()=>Le()).catch(g=>alert(g instanceof Error?g.message:String(g)))};let M=d("button","btn danger","Delete");M.onclick=()=>{confirm(`Delete template ${p.manifest.name}?`)&&T(`/api/bots/templates/${p.id}`,{method:"DELETE"}).then(()=>Le())};let C=d("span","bv-template-actions");C.append(h,b,M),u.appendChild(C),i.appendChild(u)}n.length===0&&i.appendChild(d("div","bots-empty","No templates yet")),e.appendChild(i);let s=d("div","bv-template-actions"),r=d("button","btn primary","New template");r.onclick=()=>Zt(e,t,null);let a=d("button","btn","Export");a.title="Download templates + library as JSON",a.onclick=()=>{(async()=>{try{let p=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${gt()}`}});if(!p.ok)throw new Error(`HTTP ${p.status}`);let u=await p.blob(),h=document.createElement("a");h.href=URL.createObjectURL(u),h.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,h.click(),setTimeout(()=>URL.revokeObjectURL(h.href),2e3)}catch(p){alert(p instanceof Error?p.message:String(p))}})()};let o=d("button","btn","Import");o.title="Restore templates from a JSON bundle",o.onclick=()=>{let p=document.createElement("input");p.type="file",p.accept="application/json,.json",p.onchange=()=>{let u=p.files?.[0];u&&(async()=>{try{let h=JSON.parse(await u.text()),b=await T("/api/bots/import",{method:"POST",body:JSON.stringify(h)});alert(`Imported ${b.templates} templates, ${b.files} library files (${b.skipped} kept)`),await Le()}catch(h){alert(h instanceof Error?h.message:String(h))}})()},p.click()},s.append(r,a,o),e.appendChild(s)}function kt(e,t,n){let i=d("div","bv-field");i.appendChild(d("label","bv-label",e));let s=d("div","bv-check-grid"),r=[];for(let a of t){let o=d("label","bv-check"),p=document.createElement("input");p.type="checkbox",p.checked=n.includes(a.id),o.append(p,d("span",void 0,a.label)),a.hint&&(o.title=a.hint),s.appendChild(o),r.push({id:a.id,input:p})}return i.appendChild(s),{element:i,get:()=>r.filter(a=>a.input.checked).map(a=>a.id)}}function Zt(e,t,n){e.textContent="";let i=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},s=d("input","bv-input");s.value=i.name,s.placeholder="Template name";let r=d("input","bv-input");r.value=i.description||"",r.placeholder="One line description";let a=d("textarea","bv-textarea");a.rows=6,a.value=i.system||"",a.placeholder="System prompt for this bot (written to SYSTEM.md)";let o=kt("Skills",t.skills.map(v=>({id:v.id,label:v.name,hint:v.description})),i.skills||[]),p=kt("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)$/,""))),u=kt("Prompt templates",t.prompts.map(v=>({id:v.id,label:v.name})),i.prompts||[]),h=d("select","bv-input");h.appendChild(new Option("none",""));for(let v of t.mcp)h.appendChild(new Option(v.name,v.id));i.mcp&&(h.value=t.mcp.find(v=>JSON.stringify(v.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");let b=d("div","bv-field");b.appendChild(d("label","bv-label","Tools (allow list; deny always blocks)"));let M=d("div","bv-check-grid"),C=[];for(let v of t.tools){let W=d("label","bv-check"),I=document.createElement("input");I.type="checkbox",I.checked=(i.tools?.allow||[]).includes(v.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(v.name),W.append(I,d("span",void 0,v.name)),M.appendChild(W),C.push({name:v.name,input:I})}b.appendChild(M);let y=d("input","bv-input");y.value=(i.tools?.deny||[]).join(", "),y.placeholder="Always deny (comma separated), e.g. bash, write";let g=d("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 A=d("select","bv-input");A.appendChild(new Option("default (Pi settings)",""));for(let v of t.models)A.appendChild(new Option(`${v.provider}/${v.model}`,`${v.provider}
10
+ ${v.model}`));i.model?.provider&&i.model?.id&&(A.value=`${i.model.provider}
11
+ ${i.model.id}`);let F=d("select","bv-input");for(let v of["","off","minimal","low","medium","high","xhigh","max"])F.appendChild(new Option(v||"default",v));i.model?.thinking&&(F.value=i.model.thinking);let O=d("select","bv-input");for(let v of["supervised","auto-accept-edits","full-access"])O.appendChild(new Option(v,v));O.value=i.permissions?.runtimeMode||"supervised";let x=d("select","bv-input");x.appendChild(new Option("ignore project .pi (recommended)","ignore")),x.appendChild(new Option("inherit project .pi (needs trust)","inherit")),x.value=i.projectResources||"ignore";let _=d("label","bv-check"),U=document.createElement("input");U.type="checkbox",U.checked=!!i.orchestrator,_.append(U,d("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));let H=(v,W)=>{let I=d("div","bv-field");return I.appendChild(d("label","bv-label",v)),I.appendChild(W),I};e.append(H("Name",s),H("Description",r),H("System prompt",a),o.element,p.element,u.element,H("MCP preset",h),b,H("Always deny tools",y),H("Packages",g),H("Model",A),H("Thinking level",F),H("Approval mode",O),H("Project resources",x),_);let ae=d("button","btn primary",n?"Save template":"Create template");ae.onclick=async()=>{let[v,W]=A.value.split(`
12
+ `),I=t.mcp.find($=>$.id===h.value),le={name:s.value.trim()||"bot",description:r.value.trim()||void 0,system:a.value.trim()||void 0,skills:o.get(),extensions:p.get().map($=>($.startsWith("builtin:"),$)),prompts:u.get(),packages:g.value.split(`
13
+ `).map($=>$.trim()).filter(Boolean),mcp:I?{mcpServers:I.servers}:void 0,tools:{allow:C.filter($=>$.input.checked).map($=>$.name),deny:y.value.split(",").map($=>$.trim()).filter(Boolean)},model:v?{provider:v,id:W,thinking:F.value||void 0}:void 0,permissions:{runtimeMode:O.value},projectResources:x.value==="inherit"?"inherit":"ignore",orchestrator:U.checked||void 0};try{await T("/api/bots/templates",{method:"POST",body:JSON.stringify({id:n?.id,manifest:le})}),Je(),await Le()}catch($){alert($ instanceof Error?$.message:String($))}},e.appendChild(ae)}async function bi(){return Gt("")}async function Gt(e){let t=Et("New bot"),n=await Qt();if(n.length===0){t.appendChild(d("div","bots-empty","Create a template first (\u2699)."));return}let i=d("select","bv-input");for(let u of n)i.appendChild(new Option(u.manifest.name,u.id));let s=d("input","bv-input");s.placeholder="Title (defaults to template name)";let r=d("input","bv-input");r.placeholder="/path/to/project";let a=e||m.bots[0]?.projectPath||"";r.value=a;let o=d("select","bv-input");o.appendChild(new Option("shared \u2014 run in the project folder","shared")),o.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),t.append(Ye("Template",i),Ye("Title",s),Ye("Project path",r),Ye("Workspace",o));let p=d("button","btn primary","Create bot");p.onclick=async()=>{try{let u=await T("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:s.value.trim()||void 0,projectPath:r.value.trim()||void 0,isolation:o.value})});Je(),await K(!0),await Yt(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},t.appendChild(p)}function Ye(e,t){let n=d("div","bv-field");return n.appendChild(d("label","bv-label",e)),n.appendChild(t),n}async function en(){let e=Et("Needs you");if(m.approvals=await T("/api/bots/approvals"),m.approvals.length===0){e.appendChild(d("div","bots-empty","Nothing waiting."));return}for(let t of m.approvals){let n=d("div","bv-approval");n.appendChild(d("div","bv-approval-title",`${t.botTitle}: ${t.title}`)),t.message&&n.appendChild(d("pre","bv-pre",t.message));let i=d("input","bv-reason");i.placeholder="reason (optional)";let s=d("div","bv-approval-actions"),r=d("button","btn primary","Allow"),a=d("button","btn danger","Deny"),o=async p=>{await T(`/api/bots/${t.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:t.id,allow:p,reason:i.value||void 0})}),await K(!0),await en()};r.onclick=()=>void o(!0),a.onclick=()=>void o(!1),s.append(i,r,a),n.appendChild(s),e.appendChild(n)}}function yi(){if(document.getElementById("bots-section"))return;let e=ri();bt=e.list,We=e.badge,di(),window.__openBot=Yt,document.addEventListener("click",t=>{let n=t.target;n&&n.closest(".session-item")&&m.activeId&&yt()},!0),K(!0),m.pollTimer=window.setInterval(()=>{document.hidden||K()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(m.pollTimer))}var Ie=window.__TMUX_WEB_SHELL__,S=null,B=null,Te=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null,R=Te;window.__tmuxWebScopeAgent=Te;var Ct="sessions",te="",Ke="",Ve="",tn="";function N(e){return R?"/a/"+encodeURIComponent(R)+e:e}var E=document.getElementById("sidebar-content"),ue=document.getElementById("main-placeholder"),J=document.getElementById("terminal-container"),Be=document.getElementById("file-editor"),wi=document.getElementById("fe-path"),V=document.getElementById("fe-status"),Me=document.getElementById("fe-content"),me=document.getElementById("fe-save"),Ei=document.getElementById("fe-delete"),ki=document.getElementById("fe-back"),nn=document.getElementById("fe-new-name"),Ci=document.getElementById("fe-new-btn"),xt=document.getElementById("settings-backdrop"),sn=document.getElementById("settings-popover"),an=document.querySelector(".sidebar"),on="tmux-web-force-narrow";function Xe(){try{return localStorage.getItem(on)==="1"}catch{return!1}}function ln(){document.documentElement.classList.toggle("force-narrow",Xe()),Xe()&&rn()&&Qe()}function rn(){return Xe()?!0:window.matchMedia("(max-width: 640px)").matches}function Qe(){rn()&&an.classList.add("collapsed")}function dn(){an.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{dn(),cn("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{dn(),cn("files")});function cn(e){Ct=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"?(St="",ne()):Hi()}var St="";async function ne(){if(Ct!=="sessions")return;try{let t=await(await fetch("/api/sidebar/sessions")).json(),n=(window.__botsSnapshot||[]).map(s=>[s.id,s.title,s.status,s.projectPath]),i=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones,bots:n});if(i===St)return;St=i,Bi(t)}catch{E.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")}),Dt()}var pn="tmux-web-sidebar-group-collapsed";function un(){try{return new Set(JSON.parse(localStorage.getItem(pn)||"[]"))}catch{return new Set}}function xi(e){try{localStorage.setItem(pn,JSON.stringify([...e]))}catch{}}function Si(e,t,n){if(!e)return"\u2026";let i=n&&(e===n||e.startsWith(n+"/"))?"~"+e.slice(n.length):e,s=i.split("/").filter(Boolean);if(s.length===0)return e;for(let r=1;r<=s.length;r++){let a=s.slice(-r).join("/");if(!t.some(o=>!o||o===e?!1:(n&&(o===n||o.startsWith(n+"/"))?"~"+o.slice(n.length):o).split("/").filter(Boolean).slice(-r).join("/")===a))return a}return i}function Li(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=`<svg class="bot-icon" viewBox="0 0 24 24" fill="currentColor"><path d="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"/></svg><span>${k(e.title)}</span><span class="bot-status-dot" style="background:${n}"></span>`,t.addEventListener("click",i=>{i.stopPropagation(),window.__openBot?.(e.id)}),t}function mn(e,t,n,i=!0){let s=new Map;for(let u of e){let h=u.path||"";s.has(h)||s.set(h,[]),s.get(h).push(u)}let r=n?[]:window.__botsSnapshot||[],a=new Map;for(let u of r)s.has(u.projectPath)||s.set(u.projectPath,[]),a.has(u.projectPath)||a.set(u.projectPath,[]),a.get(u.projectPath).push(u);let o=[...s.keys()],p=un();for(let[u,h]of s){let b=Si(u,o,t),M=p.has(u),C=document.createElement("div");if(C.className="session-group-header"+(M?" collapsed":""),C.title=u||"No working directory",C.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${k(b)}</span>`,!n&&u){let g=document.createElement("button");g.className="sg-add-bot",g.textContent="+",g.title=`New bot in ${u}`,g.addEventListener("click",A=>{A.stopPropagation(),It(u)}),C.appendChild(g)}C.addEventListener("click",()=>{let g=un(),A=C.nextElementSibling;g.has(u)?(g.delete(u),C.classList.remove("collapsed"),A?.classList.remove("collapsed")):(g.add(u),C.classList.add("collapsed"),A?.classList.add("collapsed")),xi(g)});let y=document.createElement("div");y.className="session-group-body"+(M?" collapsed":"");for(let g of h)y.appendChild(n?Ii(g,n,i):Ti(g));for(let g of a.get(u)||[])y.appendChild(Li(g));E.appendChild(C),E.appendChild(y)}}function Ii(e,t,n){let i=document.createElement("div");i.className="session-item"+(e.name===B&&R===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>${k(e.name)}</span>${n?"":'<span class="meta">offline</span>'}
15
+ <button class="session-edit-btn" data-session="${k(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 s=i.querySelector(".session-edit-btn");return s&&s.addEventListener("click",r=>{r.stopPropagation(),lt(e.name,s,{agentId:t})}),i}function Ti(e){let t=document.createElement("div");t.className="session-item"+(e.name===B&&!R?" 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>${k(e.name)}</span>
17
+ <button class="session-edit-btn" data-session="${k(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(),lt(e.name,n)}),t}function Bi(e){E.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="/"})),E.appendChild(n),mn(t,e.home);let i=e.agents||[];for(let r of i){if(!r.sessions||r.sessions.length===0)continue;let a=r.agentId===R,o=document.createElement("div");o.className="sidebar-section-label machine-label"+(r.online?"":" agent-offline-label")+(!a&&r.online?" clickable":""),o.textContent=r.agentName+(r.online?"":" (offline)"),!a&&r.online&&(o.title="\u6253\u5F00 "+r.agentName,o.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(r.agentId)+"/"})),E.appendChild(o),mn(r.sessions,e.home,r.agentId,r.online)}let s=e.tombstones||[];if(s.length>0){let r=document.createElement("div");r.className="sidebar-section-label tombstone-label",r.textContent="\u5931\u6548\u4F1A\u8BDD",E.appendChild(r);for(let a of s){let o=document.createElement("div");o.className="session-item session-tombstone",o.setAttribute("data-session",a.name),a.agentId&&o.setAttribute("data-agent",a.agentId);let p=a.agentId?a.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";o.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
19
+ <span>${k(a.name)}</span><span class="meta">\u5931\u6548${p}</span>
20
+ <button class="session-edit-btn" data-session="${k(a.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>`,o.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",o.addEventListener("click",()=>{lt(a.name,o,{tombstone:!0,agentId:a.agentId})});let u=o.querySelector(".session-edit-btn");u&&u.addEventListener("click",h=>{h.stopPropagation(),lt(a.name,u,{tombstone:!0,agentId:a.agentId})}),E.appendChild(o)}}}function k(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function Ae(e,t){if(B===e&&S&&R===(t||null))return;Be.style.display="none",ue.style.display="none",J.style.display="",J.classList.add("terminal-pending"),Qe(),S&&(at(),S.destroy(),S=null),B=e,R=t||null,window.__tmuxWebScopeAgent=R,window.__tmuxWebCurrentSession=B,es(e,t);let n=At(e,t);Tn.set(n,Date.now()+Zi);let i=ye.get(n);if(i&&i.state==="working"){i.state="idle",i.doneUntil=void 0,i.unread=!1;let s=E.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');s&&ut(s,n,i)}for(let s of E.querySelectorAll(".session-item"))s.classList.toggle("active",s.getAttribute("data-session")===e&&(s.getAttribute("data-agent")||null)===R);try{S=await oi(J,e,{terminal:Ie.terminal,scrollback:Ie.scrollback,theme:Ie.theme,wsBase:R?"/ws/a/"+encodeURIComponent(R):Ie.wsBase||"/ws"}),Cn()}catch(s){console.error("[shell] terminal init failed:",s);let r=s&&typeof s=="object"&&"message"in s?s.message:String(s);J.textContent="Failed to open terminal for "+e+": "+r,J.classList.remove("terminal-pending")}}var Ze=[],D=null,fn=!1;function Mi(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 Ai(e){fn=!0;try{let t=await fetch(N("/api/git/status?path="+encodeURIComponent(e)));t.ok?D=await t.json():D=null}catch{D=null}finally{fn=!1}}function Di(){if(!D||!D.branch)return"";let{branch:e,linesAdded:t,linesRemoved:n}=D,i=`<div class="sidebar-git"><div class="git-branch-badge">
21
21
  <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
- ${E(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>"}w.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&ge&&$&&(e.stopPropagation(),wn())});var $e=document.getElementById("header-git"),vn=document.getElementById("git-diff-view"),gn=document.getElementById("gd-path"),et=document.getElementById("gd-status"),tt=document.getElementById("gd-content"),Pi=document.getElementById("gd-back"),ge=null;function Ae(e){if(!e||!e.branch){$e.style.display="none",ge=null;return}ge=e.repoRoot;let{branch:t,linesAdded:n,linesRemoved:i}=e,s=`<span class="branch">${E(t)}</span>`;(n>0||i>0)&&(s+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${i}</span>`),$e.innerHTML=s,$e.style.display="block"}$e.addEventListener("click",e=>{ge&&$&&(e.stopPropagation(),wn())});var z=document.getElementById("git-popover"),nt=document.getElementById("git-popover-backdrop");function Tt(){let e=$e.getBoundingClientRect();z.style.top=e.bottom+4+"px",z.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function bn(){let e=ge,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(st(),e){St="files",document.querySelectorAll(".mode-btn").forEach(i=>i.classList.remove("active"));let n=document.getElementById("mode-files");n&&n.classList.add("active"),se(e)}})}var yn="";function wn(){if(!$)return;let e=$.files||[];if(!e.length)z.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
22
+ ${k(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>"}E.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&ge&&D&&(e.stopPropagation(),yn())});var De=document.getElementById("header-git"),hn=document.getElementById("git-diff-view"),vn=document.getElementById("gd-path"),Ge=document.getElementById("gd-status"),et=document.getElementById("gd-content"),$i=document.getElementById("gd-back"),ge=null;function $e(e){if(!e||!e.branch){De.style.display="none",ge=null;return}ge=e.repoRoot;let{branch:t,linesAdded:n,linesRemoved:i}=e,s=`<span class="branch">${k(t)}</span>`;(n>0||i>0)&&(s+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${i}</span>`),De.innerHTML=s,De.style.display="block"}De.addEventListener("click",e=>{ge&&D&&(e.stopPropagation(),yn())});var z=document.getElementById("git-popover"),tt=document.getElementById("git-popover-backdrop");function Lt(){let e=De.getBoundingClientRect();z.style.top=e.bottom+4+"px",z.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function gn(){let e=ge,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(it(),e){Ct="files",document.querySelectorAll(".mode-btn").forEach(i=>i.classList.remove("active"));let n=document.getElementById("mode-files");n&&n.classList.add("active"),ie(e)}})}var bn="";function yn(){if(!D)return;let e=D.files||[];if(!e.length)z.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
23
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],s=i.additions||0,r=i.deletions||0,a="";switch(i.status){case"M":a='<span class="git-file-status M">M</span>';break;case"A":a='<span class="git-file-status A">A</span>';break;case"D":a='<span class="git-file-status D">D</span>';break;case"?":a='<span class="git-file-status ?">?</span>';break;case"R":a='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
24
- ${a}<span class="file-path">${E(i.path)}</span>
24
+ ${a}<span class="file-path">${k(i.path)}</span>
25
25
  <span class="file-add">${s>0?"+"+s:""}</span>
26
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>',yn=t,z.innerHTML=t,z.querySelectorAll(".git-popover-item").forEach(n=>{let i=parseInt(n.dataset.idx||"0",10),s=e[i];!s||s.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>kn(s.path)))})}Tt(),z.classList.add("open"),nt.classList.add("open"),bn()}function Ni(){return window.innerWidth>=1024}function En(e,t){let n=(e+(t&&e?`
27
+ </div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',bn=t,z.innerHTML=t,z.querySelectorAll(".git-popover-item").forEach(n=>{let i=parseInt(n.dataset.idx||"0",10),s=e[i];!s||s.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>En(s.path)))})}Lt(),z.classList.add("open"),tt.classList.add("open"),gn()}function Pi(){return window.innerWidth>=1024}function wn(e,t){let n=(e+(t&&e?`
28
28
  `:"")+t).split(`
29
- `),i="",s=0,r=0;for(let a of n){let o=a;if(o.startsWith("@@")){let p=o.match(/@@\s+-(\d+)[^+]*\+(\d+)/);p&&(s=parseInt(p[1],10)-1,r=parseInt(p[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${E(o)}</span></div>`;continue}if(o.startsWith("diff --git")||o.startsWith("index ")||o.startsWith("--- ")||o.startsWith("+++ ")||o.startsWith("new file")||o.startsWith("deleted file")){o.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${E(o)}</span></div>`);continue}if(o.startsWith("+"))r++,i+=`<div class="diff-line add"><span class="ln-no">${r}</span><span class="ln-body">${E(o)}</span></div>`;else if(o.startsWith("-"))s++,i+=`<div class="diff-line del"><span class="ln-no">${s}</span><span class="ln-body">${E(o)}</span></div>`;else if(o.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${E(o)}</span></div>`;else{if(!o&&!s&&!r)continue;s++,r++,i+=`<div class="diff-line"><span class="ln-no">${s}</span><span class="ln-no" style="margin-right:12px">${r}</span><span class="ln-body">${E(o)}</span></div>`}}return{html:i,lineCount:n.length}}var it=null;async function kn(e){let t=ge;if(t)if(st(),Ni()){J.style.display="none",x&&(ot(),x.destroy(),x=null,it=T,T=null),Ae(null),Be.style.display="none",me.style.display="none",vn.style.display="flex",gn.textContent=e,et.textContent="Loading\u2026",tt.innerHTML="";try{let n=await fetch(N("/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: ${E(i)}</div>`}}else{z.innerHTML=`<div class="git-diff-view"><div class="diff-header">
29
+ `),i="",s=0,r=0;for(let a of n){let o=a;if(o.startsWith("@@")){let p=o.match(/@@\s+-(\d+)[^+]*\+(\d+)/);p&&(s=parseInt(p[1],10)-1,r=parseInt(p[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${k(o)}</span></div>`;continue}if(o.startsWith("diff --git")||o.startsWith("index ")||o.startsWith("--- ")||o.startsWith("+++ ")||o.startsWith("new file")||o.startsWith("deleted file")){o.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${k(o)}</span></div>`);continue}if(o.startsWith("+"))r++,i+=`<div class="diff-line add"><span class="ln-no">${r}</span><span class="ln-body">${k(o)}</span></div>`;else if(o.startsWith("-"))s++,i+=`<div class="diff-line del"><span class="ln-no">${s}</span><span class="ln-body">${k(o)}</span></div>`;else if(o.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${k(o)}</span></div>`;else{if(!o&&!s&&!r)continue;s++,r++,i+=`<div class="diff-line"><span class="ln-no">${s}</span><span class="ln-no" style="margin-right:12px">${r}</span><span class="ln-body">${k(o)}</span></div>`}}return{html:i,lineCount:n.length}}var nt=null;async function En(e){let t=ge;if(t)if(it(),Pi()){J.style.display="none",S&&(at(),S.destroy(),S=null,nt=B,B=null),$e(null),Be.style.display="none",ue.style.display="none",hn.style.display="flex",vn.textContent=e,Ge.textContent="Loading\u2026",et.innerHTML="";try{let n=await fetch(N("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Fi(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);Ge.textContent="Error",et.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${k(i)}</div>`}}else{z.innerHTML=`<div class="git-diff-view"><div class="diff-header">
30
30
  <button class="diff-back">\u2190 Back</button>
31
- <span class="diff-filename">${E(e)}</span>
31
+ <span class="diff-filename">${k(e)}</span>
32
32
  <span class="diff-loading">Loading\u2026</span>
33
- </div></div>`,Tt(),z.classList.add("open"),nt.classList.add("open");try{let n=await fetch(N("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Fi(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);z.innerHTML=`<div class="git-diff-view"><div class="diff-header">
33
+ </div></div>`,Lt(),z.classList.add("open"),tt.classList.add("open");try{let n=await fetch(N("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Ni(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);z.innerHTML=`<div class="git-diff-view"><div class="diff-header">
34
34
  <button class="diff-back">\u2190 Back</button>
35
- <span class="diff-filename">${E(e)}</span>
36
- </div><div class="diff-empty">Error loading diff: ${E(i)}</div></div>`}}}function Fi(e,t,n){if(!t&&!n){z.innerHTML=`<div class="git-diff-view"><div class="diff-header">
35
+ <span class="diff-filename">${k(e)}</span>
36
+ </div><div class="diff-empty">Error loading diff: ${k(i)}</div></div>`}}}function Ni(e,t,n){if(!t&&!n){z.innerHTML=`<div class="git-diff-view"><div class="diff-header">
37
37
  <button class="diff-back">\u2190 Back</button>
38
- <span class="diff-filename">${E(e)}</span>
39
- </div><div class="diff-empty">No diff content available</div></div>`;return}let{html:i,lineCount:s}=En(t,n);z.innerHTML=`<div class="git-diff-view"><div class="diff-header">
38
+ <span class="diff-filename">${k(e)}</span>
39
+ </div><div class="diff-empty">No diff content available</div></div>`;return}let{html:i,lineCount:s}=wn(t,n);z.innerHTML=`<div class="git-diff-view"><div class="diff-header">
40
40
  <button class="diff-back">\u2190 Back</button>
41
- <span class="diff-filename">${E(e)}</span>
41
+ <span class="diff-filename">${k(e)}</span>
42
42
  <span class="diff-filesize">${s} lines</span>
43
- </div><div class="diff-content">${i}</div></div>`,z.querySelector(".diff-back")?.addEventListener("click",()=>{z.innerHTML=yn,Tt(),$&&z.querySelectorAll(".git-popover-item").forEach(r=>{let a=parseInt(r.dataset.idx||"0",10),o=$.files[a];!o||o.status==="D"||(r.style.cursor="pointer",r.addEventListener("click",()=>kn(o.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:s}=En(t,n);gn.textContent=e,et.textContent=s+" lines",tt.innerHTML=i}function ji(){vn.style.display="none",it?(J.style.display="",J.classList.add("terminal-pending"),De(it),it=null):T?(J.style.display="",J.classList.add("terminal-pending"),xn()):me.style.display="flex"}Pi.addEventListener("click",ji);function st(){z.classList.remove("open"),nt.classList.remove("open")}nt.addEventListener("click",st),document.addEventListener("keydown",e=>{e.key==="Escape"&&(st(),mt())});async function Cn(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();$=i,Ae(i);return}}}catch{}$=null,Ae(null)}var at=null;function xn(){ot(),T&&(Cn(T),at=setInterval(()=>{T&&Cn(T)},3e4))}function ot(){at&&(clearInterval(at),at=null)}async function lt(e){let t=e;if(t.startsWith("~"))try{let n=await(await fetch(N("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof n.path=="string"&&n.path&&(t=n.path)}catch{}t=t.replace(/\/+$/,"")||"/",en(t)}function Sn(e,t){let n=document.createElement("button");n.className="file-tree-bot-btn",n.textContent="+",n.title=`Create bot in ${t}`,n.setAttribute("aria-label",`Create bot in ${t}`),n.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),lt(t)}),e.appendChild(n)}function Hi(){if(Ge=Ie.fsRoots||[],Ge.length===0){if(T){Ri(T);return}se("");return}w.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> ${E(e)}`,t.addEventListener("click",()=>se(e)),Sn(t,e),w.appendChild(t)}}async function Ri(e){w.innerHTML='<div class="file-tree-empty">Loading...</div>';try{let t=await(await fetch(N("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?se(t.path):w.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{w.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function se(e){ne=e,w.innerHTML='<div class="file-tree-empty">Loading...</div>';let t=$i(e);try{let n=await(await fetch(N("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof n.path=="string"&&n.path?n.path:e;if(i&&(ne=i),await t,w.innerHTML="",i){let a=document.createElement("div");a.className="file-tree-item file-tree-create-bot",a.innerHTML='<span class="file-tree-bot-plus">+</span> Create bot in this folder',a.title=`Create bot in ${i}`,a.addEventListener("click",()=>void lt(i)),w.appendChild(a)}Ae($),w.innerHTML+=Ai();let s=zi(i||e);if(s&&!Ge.some(a=>i===a)){let a=document.createElement("div");a.className="file-tree-item",a.innerHTML="..",a.addEventListener("click",()=>se(s)),w.appendChild(a)}if(n.dirs)for(let a of n.dirs){let o=a.split("/").pop()||a.split("\\").pop(),p=document.createElement("div");p.className="file-tree-item",p.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> ${E(o)}`,p.addEventListener("click",()=>se(a)),Sn(p,a),w.appendChild(p)}else w.innerHTML="";let r=n.files||[];for(let a of r){let o=a.split("/").pop()||a.split("\\").pop(),p=Di(a),u="",h="";if(p)switch(p){case"M":u="git-mod",h='<span class="git-file-status M">M</span>';break;case"A":u="git-add",h='<span class="git-file-status A">A</span>';break;case"D":u="git-del",h='<span class="git-file-status D">D</span>';break;case"?":u="git-untracked",h='<span class="git-file-status ?">?</span>';break;case"R":u="git-mod",h='<span class="git-file-status R">R</span>';break}let b=document.createElement("div");b.className="file-tree-item file"+(u?" "+u:""),b.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${h}${E(o)}`,b.addEventListener("click",()=>_i(a)),w.appendChild(b)}}catch{w.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function zi(e){let t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function _i(e){Ke=e,J.style.display="none",x&&(ot(),x.destroy(),x=null,T=null),Ae(null),Ze(),me.style.display="none",Be.style.display="flex",Ei.textContent=e,X.textContent="Loading...",fe.style.display="none";try{let t=await fetch(N("/api/file?path="+encodeURIComponent(e)));if(!t.ok){let i=await t.json();X.textContent=i.error||"Failed to load",Me.value="";return}let n=await t.json();Me.value=n.content,Xe=n.content,nn=n.content,X.textContent=n.size+" bytes",fe.style.display=""}catch{X.textContent="Failed to load",Me.value=""}}Me.addEventListener("input",()=>{Xe=Me.value}),fe.addEventListener("click",async()=>{fe.textContent="Saving...",fe.disabled=!0;try{let e=await fetch(N("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Ke,content:Xe})});if(!e.ok){let t=await e.json();X.textContent=t.error||"Save failed";return}nn=Xe,X.textContent="Saved"}catch{X.textContent="Save failed"}finally{fe.disabled=!1,fe.textContent="Save"}}),ki.addEventListener("click",async()=>{if(confirm("Delete "+Ke+"?"))try{let e=await fetch(N("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Ke})});if(!e.ok){let t=await e.json();X.textContent=t.error||"Delete failed";return}Be.style.display="none",me.style.display="flex",ne&&se(ne)}catch{X.textContent="Delete failed"}}),Ci.addEventListener("click",()=>{Be.style.display="none",me.style.display="flex",ne&&se(ne)}),xi.addEventListener("click",async()=>{let e=sn.value.trim();if(!e)return;let t=ne+"/"+e;try{let n=await fetch(N("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){let i=await n.json();X.textContent=i.error||"Create failed";return}sn.value="",ne&&se(ne)}catch{X.textContent="Create failed"}});var rt=document.getElementById("force-narrow-toggle");rt&&(rt.checked=Qe(),rt.addEventListener("change",()=>{try{localStorage.setItem(ln,rt.checked?"1":"0")}catch{}rn(),ie()})),rn(),document.getElementById("mode-settings").addEventListener("click",()=>{let e=an.classList.toggle("open");Lt.classList.toggle("open",e)}),Lt.addEventListener("click",()=>{an.classList.remove("open"),Lt.classList.remove("open")});var Y="",G=!1,V,Pe=document.createElement("div");Pe.className="session-popover-backdrop",document.body.appendChild(Pe);var Q=document.createElement("div");Q.id="session-popover",Q.className="session-popover",Q.style.display="none",Q.innerHTML=`<div class="sp-field">
43
+ </div><div class="diff-content">${i}</div></div>`,z.querySelector(".diff-back")?.addEventListener("click",()=>{z.innerHTML=bn,Lt(),D&&z.querySelectorAll(".git-popover-item").forEach(r=>{let a=parseInt(r.dataset.idx||"0",10),o=D.files[a];!o||o.status==="D"||(r.style.cursor="pointer",r.addEventListener("click",()=>En(o.path)))}),gn()})}function Fi(e,t,n){if(!t&&!n){Ge.textContent="No diff",et.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}=wn(t,n);vn.textContent=e,Ge.textContent=s+" lines",et.innerHTML=i}function Oi(){hn.style.display="none",nt?(J.style.display="",J.classList.add("terminal-pending"),Ae(nt),nt=null):B?(J.style.display="",J.classList.add("terminal-pending"),Cn()):ue.style.display="flex"}$i.addEventListener("click",Oi);function it(){z.classList.remove("open"),tt.classList.remove("open")}tt.addEventListener("click",it),document.addEventListener("keydown",e=>{e.key==="Escape"&&(it(),pt())});async function kn(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 st=null;function Cn(){at(),B&&(kn(B),st=setInterval(()=>{B&&kn(B)},3e4))}function at(){st&&(clearInterval(st),st=null)}async function It(e){let t=e;if(t.startsWith("~"))try{let n=await(await fetch(N("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof n.path=="string"&&n.path&&(t=n.path)}catch{}t=t.replace(/\/+$/,"")||"/",Gt(t)}function xn(e,t){let n=document.createElement("button");n.className="file-tree-bot-btn",n.textContent="+",n.title=`Create bot in ${t}`,n.setAttribute("aria-label",`Create bot in ${t}`),n.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),It(t)}),e.appendChild(n)}function Hi(){if(Ze=Ie.fsRoots||[],Ze.length===0){if(B){ji(B);return}ie("");return}E.innerHTML="";for(let e of Ze){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> ${k(e)}`,t.addEventListener("click",()=>ie(e)),xn(t,e),E.appendChild(t)}}async function ji(e){E.innerHTML='<div class="file-tree-empty">Loading...</div>';try{let t=await(await fetch(N("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?ie(t.path):E.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{E.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function ie(e){te=e,E.innerHTML='<div class="file-tree-empty">Loading...</div>';let t=Ai(e);try{let n=await(await fetch(N("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof n.path=="string"&&n.path?n.path:e;if(i&&(te=i),await t,E.innerHTML="",i){let a=document.createElement("div");a.className="file-tree-item file-tree-create-bot",a.innerHTML='<span class="file-tree-bot-plus">+</span> Create bot in this folder',a.title=`Create bot in ${i}`,a.addEventListener("click",()=>void It(i)),E.appendChild(a)}$e(D),E.innerHTML+=Di();let s=Ri(i||e);if(s&&!Ze.some(a=>i===a)){let a=document.createElement("div");a.className="file-tree-item",a.innerHTML="..",a.addEventListener("click",()=>ie(s)),E.appendChild(a)}if(n.dirs)for(let a of n.dirs){let o=a.split("/").pop()||a.split("\\").pop(),p=document.createElement("div");p.className="file-tree-item",p.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> ${k(o)}`,p.addEventListener("click",()=>ie(a)),xn(p,a),E.appendChild(p)}else E.innerHTML="";let r=n.files||[];for(let a of r){let o=a.split("/").pop()||a.split("\\").pop(),p=Mi(a),u="",h="";if(p)switch(p){case"M":u="git-mod",h='<span class="git-file-status M">M</span>';break;case"A":u="git-add",h='<span class="git-file-status A">A</span>';break;case"D":u="git-del",h='<span class="git-file-status D">D</span>';break;case"?":u="git-untracked",h='<span class="git-file-status ?">?</span>';break;case"R":u="git-mod",h='<span class="git-file-status R">R</span>';break}let b=document.createElement("div");b.className="file-tree-item file"+(u?" "+u:""),b.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${h}${k(o)}`,b.addEventListener("click",()=>zi(a)),E.appendChild(b)}}catch{E.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function Ri(e){let t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function zi(e){Ke=e,J.style.display="none",S&&(at(),S.destroy(),S=null,B=null),$e(null),Qe(),ue.style.display="none",Be.style.display="flex",wi.textContent=e,V.textContent="Loading...",me.style.display="none";try{let t=await fetch(N("/api/file?path="+encodeURIComponent(e)));if(!t.ok){let i=await t.json();V.textContent=i.error||"Failed to load",Me.value="";return}let n=await t.json();Me.value=n.content,Ve=n.content,tn=n.content,V.textContent=n.size+" bytes",me.style.display=""}catch{V.textContent="Failed to load",Me.value=""}}Me.addEventListener("input",()=>{Ve=Me.value}),me.addEventListener("click",async()=>{me.textContent="Saving...",me.disabled=!0;try{let e=await fetch(N("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Ke,content:Ve})});if(!e.ok){let t=await e.json();V.textContent=t.error||"Save failed";return}tn=Ve,V.textContent="Saved"}catch{V.textContent="Save failed"}finally{me.disabled=!1,me.textContent="Save"}}),Ei.addEventListener("click",async()=>{if(confirm("Delete "+Ke+"?"))try{let e=await fetch(N("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Ke})});if(!e.ok){let t=await e.json();V.textContent=t.error||"Delete failed";return}Be.style.display="none",ue.style.display="flex",te&&ie(te)}catch{V.textContent="Delete failed"}}),ki.addEventListener("click",()=>{Be.style.display="none",ue.style.display="flex",te&&ie(te)}),Ci.addEventListener("click",async()=>{let e=nn.value.trim();if(!e)return;let t=te+"/"+e;try{let n=await fetch(N("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){let i=await n.json();V.textContent=i.error||"Create failed";return}nn.value="",te&&ie(te)}catch{V.textContent="Create failed"}});var ot=document.getElementById("force-narrow-toggle");ot&&(ot.checked=Xe(),ot.addEventListener("change",()=>{try{localStorage.setItem(on,ot.checked?"1":"0")}catch{}ln(),ne()})),ln(),document.getElementById("mode-settings").addEventListener("click",()=>{let e=sn.classList.toggle("open");xt.classList.toggle("open",e)}),xt.addEventListener("click",()=>{sn.classList.remove("open"),xt.classList.remove("open")});var Y="",se=!1,X,Pe=document.createElement("div");Pe.className="session-popover-backdrop",document.body.appendChild(Pe);var Q=document.createElement("div");Q.id="session-popover",Q.className="session-popover",Q.style.display="none",Q.innerHTML=`<div class="sp-field">
44
44
  <label>Rename session</label>
45
45
  <input type="text" id="sp-name" />
46
46
  </div>
@@ -50,6 +50,5 @@ ${i.model.id}`);let F=d("select","bv-input");for(let v of["","off","minimal","lo
50
50
  </div>
51
51
  <hr class="sp-divider" />
52
52
  <button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>
53
- <button class="btn" id="sp-create-bot" style="display:none">\uFF0B \u5728\u6B64\u76EE\u5F55\u521B\u5EFA Bot</button>
54
- <button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(Q);function Ui(e){let t=e.getBoundingClientRect(),n=window.innerHeight,i=Q.offsetHeight||240,s=t.bottom+4;s+i>n-8&&(s=Math.max(8,t.top-i-4)),Q.style.top=s+"px",Q.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}var be="";function dt(e,t,n){Y=e,G=!!n?.tombstone,V=n?.agentId,be=n?.sessionPath||"";let i=document.getElementById("sp-name");i.value=e;let s=Q.querySelector(".sp-field label");s.textContent=G?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";let r=document.getElementById("sp-rebuild");r.style.display=G?"":"none";let a=document.getElementById("sp-delete");a.textContent=G?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";let o=document.getElementById("sp-save");o.textContent=G?"\u91CD\u547D\u540D":"Save";let p=document.getElementById("sp-create-bot");p.style.display=!G&&!V&&be?"":"none",p.title=be?`Create bot in ${be}`:"",Pe.classList.add("open"),Q.style.display="block",Ui(t),setTimeout(()=>i.focus(),50)}function le(){Pe.classList.remove("open"),Q.style.display="none"}Pe.addEventListener("click",le),document.getElementById("sp-create-bot").addEventListener("click",()=>{if(!be)return;let e=be;le(),lt(e)}),document.getElementById("sp-save").addEventListener("click",async()=>{let e=document.getElementById("sp-name").value.trim();if(!e||e===Y){le();return}try{let t=G?{oldName:Y,newName:e,agentId:V}:{oldName:Y,newName:e,...V?{agentId:V}:{}};if(!(await fetch(N(G?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;le(),ie(),!G&&T===Y&&(V??null)===R&&De(e,V)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+Y+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{let e=await fetch(N("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Y,agentId:V})});if(!e.ok){let t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}le(),ie()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(G){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+Y+'"\uFF1F'))return;try{if(!(await fetch(N("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Y,agentId:V})})).ok)return;le(),ie()}catch{}return}if(confirm('Delete session "'+Y+'"?'))try{if(!(await fetch(N("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Y,...V?{agentId:V}:{}})})).ok)return;le(),T===Y&&(V??null)===R&&(x&&(x.destroy(),x=null),T=null,J.style.display="none",me.style.display="flex"),ie()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",le);var Ln={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"},ct=document.getElementById("mobile-keys"),Wi=new Set(["up","down","left","right","tab","s-tab","space"]),qi=400,Ji=80,Ne=0,pt=0,ut=!1;function Yi(){Ne&&(clearTimeout(Ne),Ne=0),pt&&(clearInterval(pt),pt=0)}ct.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),ct.addEventListener("pointerdown",e=>{let t=e.target.closest("button[data-key]");if(!t)return;let n=t.dataset.key;Wi.has(n)&&(ut=!1,Ne=setTimeout(()=>{Ne=0,ut=!0,pt=setInterval(()=>{let i=Ln[n];i&&x&&x.sendInput(i)},Ji)},qi))});for(let e of["pointerup","pointercancel","pointerleave"])ct.addEventListener(e,Yi);ct.addEventListener("click",e=>{let t=e.target.closest("button[data-key]");if(!t||!x)return;if(ut){ut=!1;return}let n=Ln[t.dataset.key];n&&(x.sendInput(n),x.focus())});var ee=document.getElementById("mk-input"),In=document.getElementById("mk-send");function Tn(){if(!ee||!x)return;let e=ee.value;e&&(x.sendInput(e+"\r"),ee.value="",ee.rows=1,x.focus())}if(ee&&(ee.addEventListener("input",()=>{ee.rows=1;let e=ee.value.split(`
55
- `).length;ee.rows=Math.min(e,4)}),ee.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Tn())})),In&&In.addEventListener("click",Tn),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 Bt=document.getElementById("process-panel"),Fe=document.getElementById("proc-list"),Vi=document.getElementById("proc-close"),Mt=document.getElementById("proc-backdrop"),Ki=document.getElementById("header-ram");function Xi(){Fe.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(N("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){Fe.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(let n of e){let i=n.rss,s=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">'+s+'</span><span class="proc-cmd" title="'+E(n.command)+'">'+E(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">&times;</button></div>'}Fe.innerHTML=t;for(let n of Fe.querySelectorAll(".proc-row")){let i=n.querySelector(".proc-kill");i&&i.addEventListener("click",s=>{let r=s.target.closest(".proc-row");!r||!confirm("Kill PID "+r.dataset.pid+"?")||fetch(N("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(r.dataset.pid,10)})}).then(a=>a.json()).then(a=>{a.ok?r.style.opacity="0.3":alert("Failed: "+(a.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{Fe.innerHTML='<div class="proc-empty">Failed to load</div>'})}function Qi(){Bt.classList.add("open"),Mt.classList.add("open"),Xi()}function mt(){Bt.classList.remove("open"),Mt.classList.remove("open")}Ki.addEventListener("click",e=>{e.stopPropagation(),Bt.classList.contains("open")?mt():Qi()}),Vi.addEventListener("click",mt),Mt.addEventListener("click",mt);var Zi=2e3,Oe=null,Dt=null,ye=new Map,we=new Map,Gi=5e3,Bn=new Map;function $t(e,t){return(t?"a:"+t+":":"l:")+e}function es(e,t,n){let i=$t(e,t);if(n==="working"){let u=Bn.get(i);if(u&&Date.now()<u)return}let s=we.get(i),r=e===T&&(t??null)===R,a=n==="idle"&&s?.state==="working";we.set(i,{session:e,agentId:t,state:n,doneUntil:a?Date.now()+Zi:void 0,unread:a?!r:!1});let o=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',p=w.querySelector(o);p&&ft(p,i,we.get(i))}function ft(e,t,n){let i=ye.get(t);i&&(clearTimeout(i),ye.delete(t)),e.classList.remove("working","just-done");let s=n.session===T&&(n.agentId??null)===R;n.state==="working"?e.classList.add("working"):s&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),ye.set(t,setTimeout(()=>{e.classList.remove("just-done"),ye.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!s&&n.unread&&e.classList.add("just-done")}function At(){for(let[e,t]of we){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=w.querySelector(n);i&&ft(i,e,t)}}function ts(e,t){let n=$t(e,t),i=we.get(n);if(!i)return;let s=ye.get(n);s&&(clearTimeout(s),ye.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])',a=w.querySelector(r);a&&ft(a,n,i)}function Mn(){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 s=JSON.parse(String(i.data));s&&s.type==="session.activity"&&typeof s.session=="string"&&es(s.session,s.agentId||void 0,s.state==="working"?"working":"idle")}catch{}},n.onclose=()=>{Oe===n&&(Oe=null,Dt=setTimeout(()=>{Dt=null,Mn()},5e3))},n.onerror=()=>{try{n.close()}catch{}}}catch{Oe=null}}window.__openSession=De,window.__refreshSidebar=ie,ie(),Ze(),At(),Mn(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&At()}),setInterval(()=>{document.visibilityState==="visible"&&ie()},1e4),wi();
53
+ <button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(Q);function _i(e){let t=e.getBoundingClientRect(),n=window.innerHeight,i=Q.offsetHeight||240,s=t.bottom+4;s+i>n-8&&(s=Math.max(8,t.top-i-4)),Q.style.top=s+"px",Q.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}function lt(e,t,n){Y=e,se=!!n?.tombstone,X=n?.agentId;let i=document.getElementById("sp-name");i.value=e;let s=Q.querySelector(".sp-field label");s.textContent=se?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";let r=document.getElementById("sp-rebuild");r.style.display=se?"":"none";let a=document.getElementById("sp-delete");a.textContent=se?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";let o=document.getElementById("sp-save");o.textContent=se?"\u91CD\u547D\u540D":"Save",Pe.classList.add("open"),Q.style.display="block",_i(t),setTimeout(()=>i.focus(),50)}function fe(){Pe.classList.remove("open"),Q.style.display="none"}Pe.addEventListener("click",fe),document.getElementById("sp-save").addEventListener("click",async()=>{let e=document.getElementById("sp-name").value.trim();if(!e||e===Y){fe();return}try{let t=se?{oldName:Y,newName:e,agentId:X}:{oldName:Y,newName:e,...X?{agentId:X}:{}};if(!(await fetch(N(se?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;fe(),ne(),!se&&B===Y&&(X??null)===R&&Ae(e,X)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+Y+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{let e=await fetch(N("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Y,agentId:X})});if(!e.ok){let t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}fe(),ne()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(se){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+Y+'"\uFF1F'))return;try{if(!(await fetch(N("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Y,agentId:X})})).ok)return;fe(),ne()}catch{}return}if(confirm('Delete session "'+Y+'"?'))try{if(!(await fetch(N("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Y,...X?{agentId:X}:{}})})).ok)return;fe(),B===Y&&(X??null)===R&&(S&&(S.destroy(),S=null),B=null,J.style.display="none",ue.style.display="flex"),ne()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",fe);var Sn={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"},rt=document.getElementById("mobile-keys"),Ui=new Set(["up","down","left","right","tab","s-tab","space"]),Wi=400,qi=80,Ne=0,dt=0,ct=!1;function Ji(){Ne&&(clearTimeout(Ne),Ne=0),dt&&(clearInterval(dt),dt=0)}rt.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),rt.addEventListener("pointerdown",e=>{let t=e.target.closest("button[data-key]");if(!t)return;let n=t.dataset.key;Ui.has(n)&&(ct=!1,Ne=setTimeout(()=>{Ne=0,ct=!0,dt=setInterval(()=>{let i=Sn[n];i&&S&&S.sendInput(i)},qi)},Wi))});for(let e of["pointerup","pointercancel","pointerleave"])rt.addEventListener(e,Ji);rt.addEventListener("click",e=>{let t=e.target.closest("button[data-key]");if(!t||!S)return;if(ct){ct=!1;return}let n=Sn[t.dataset.key];n&&(S.sendInput(n),S.focus())});var G=document.getElementById("mk-input"),Ln=document.getElementById("mk-send");function In(){if(!G||!S)return;let e=G.value;e&&(S.sendInput(e+"\r"),G.value="",G.rows=1,S.focus())}if(G&&(G.addEventListener("input",()=>{G.rows=1;let e=G.value.split(`
54
+ `).length;G.rows=Math.min(e,4)}),G.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),In())})),Ln&&Ln.addEventListener("click",In),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 Tt=document.getElementById("process-panel"),Fe=document.getElementById("proc-list"),Yi=document.getElementById("proc-close"),Bt=document.getElementById("proc-backdrop"),Ki=document.getElementById("header-ram");function Vi(){Fe.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(N("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){Fe.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(let n of e){let i=n.rss,s=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">'+s+'</span><span class="proc-cmd" title="'+k(n.command)+'">'+k(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">&times;</button></div>'}Fe.innerHTML=t;for(let n of Fe.querySelectorAll(".proc-row")){let i=n.querySelector(".proc-kill");i&&i.addEventListener("click",s=>{let r=s.target.closest(".proc-row");!r||!confirm("Kill PID "+r.dataset.pid+"?")||fetch(N("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(r.dataset.pid,10)})}).then(a=>a.json()).then(a=>{a.ok?r.style.opacity="0.3":alert("Failed: "+(a.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{Fe.innerHTML='<div class="proc-empty">Failed to load</div>'})}function Xi(){Tt.classList.add("open"),Bt.classList.add("open"),Vi()}function pt(){Tt.classList.remove("open"),Bt.classList.remove("open")}Ki.addEventListener("click",e=>{e.stopPropagation(),Tt.classList.contains("open")?pt():Xi()}),Yi.addEventListener("click",pt),Bt.addEventListener("click",pt);var Qi=2e3,Oe=null,Mt=null,be=new Map,ye=new Map,Zi=5e3,Tn=new Map;function At(e,t){return(t?"a:"+t+":":"l:")+e}function Gi(e,t,n){let i=At(e,t);if(n==="working"){let u=Tn.get(i);if(u&&Date.now()<u)return}let s=ye.get(i),r=e===B&&(t??null)===R,a=n==="idle"&&s?.state==="working";ye.set(i,{session:e,agentId:t,state:n,doneUntil:a?Date.now()+Qi:void 0,unread:a?!r:!1});let o=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',p=E.querySelector(o);p&&ut(p,i,ye.get(i))}function ut(e,t,n){let i=be.get(t);i&&(clearTimeout(i),be.delete(t)),e.classList.remove("working","just-done");let s=n.session===B&&(n.agentId??null)===R;n.state==="working"?e.classList.add("working"):s&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),be.set(t,setTimeout(()=>{e.classList.remove("just-done"),be.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!s&&n.unread&&e.classList.add("just-done")}function Dt(){for(let[e,t]of ye){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=E.querySelector(n);i&&ut(i,e,t)}}function es(e,t){let n=At(e,t),i=ye.get(n);if(!i)return;let s=be.get(n);s&&(clearTimeout(s),be.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])',a=E.querySelector(r);a&&ut(a,n,i)}function Bn(){if(Oe||Mt)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 s=JSON.parse(String(i.data));s&&s.type==="session.activity"&&typeof s.session=="string"&&Gi(s.session,s.agentId||void 0,s.state==="working"?"working":"idle")}catch{}},n.onclose=()=>{Oe===n&&(Oe=null,Mt=setTimeout(()=>{Mt=null,Bn()},5e3))},n.onerror=()=>{try{n.close()}catch{}}}catch{Oe=null}}window.__openSession=Ae,window.__refreshSidebar=ne,ne(),Qe(),Dt(),Bn(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Dt()}),setInterval(()=>{document.visibilityState==="visible"&&ne()},1e4),yi();
@@ -1,6 +1,6 @@
1
- const d={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function L(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function f(t,n){const o=await fetch(t,{...n,headers:{"content-type":"application/json",Authorization:`Bearer ${L()}`,...n?.headers||{}}}),i=await o.text(),a=i?JSON.parse(i):null;if(!o.ok)throw new Error(a&&a.error||`HTTP ${o.status}`);return a}function e(t,n,o){const i=document.createElement(t);return n&&(i.className=n),o!==void 0&&(i.textContent=o),i}function F(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 nt(){const t=e("div","bots-section");t.id="bots-section";const n=e("div","bots-head"),o=e("span","bots-title","Bots"),i=e("span","bots-badge");i.hidden=!0,o.appendChild(i);const a=e("span","bots-head-actions"),l=e("button","bots-icon-btn","\u2699");l.title="Bot templates",l.onclick=()=>void J();const s=e("button","bots-icon-btn","+");s.title="New bot from template",s.onclick=()=>void ut(),a.append(l,s),n.append(o,a);const c=e("div","bots-list");c.id="bots-list",t.append(n,c);const r=document.querySelector(".sidebar"),u=document.querySelector(".sidebar-footer");return r&&r.insertBefore(t,u||null),{list:c,badge:i}}let R=null,P=null;function j(){R&&(R.textContent="");const t=d.approvals.length;P&&(P.hidden=t===0,P.textContent=String(t));const n=document.getElementById("bv-inbox-count");n&&(n.textContent=t?`(${t})`:""),window.__botsSnapshot=d.bots,window.__refreshSidebar?.()}function bt(t){const n=e("div","bots-row");n.dataset.botId=t.id,t.id===d.activeId&&n.classList.add("active");const o=e("span","bots-dot");o.style.background=F(t.status);const i=e("span","bots-name",t.title),a=e("span","bots-meta",t.status.replace(/_/g," "));return n.append(o,i,a),n.onclick=()=>void q(t.id),n}function ot(){const t=e("div","bots-view");t.id="bots-view",t.hidden=!0;const n=e("div","bots-view-head"),o=e("div","bv-title"),i=e("span","bots-dot");i.id="bv-dot";const a=e("span","bv-title-text");a.id="bv-title";const l=e("span","bv-status");l.id="bv-status",o.append(i,a,l);const s=e("div","bv-actions"),c=e("select","bv-mode-select");c.id="bv-mode",c.title="Approval mode for this bot";for(const[b,C]of[["supervised","Approve every tool"],["auto-accept-edits","Auto-accept edits"],["full-access","No approvals"]])c.appendChild(new Option(C,b));c.onchange=()=>{d.activeId&&f(`/api/bots/${d.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:c.value})}).then(()=>$({kind:"notice",level:"info",text:`Approval mode: ${c.value}`})).catch(b=>$({kind:"notice",level:"error",text:b instanceof Error?b.message:String(b)}))};const r=e("button","btn","Allow all");r.id="bv-allow-all",r.title="Approve every pending request for this bot",r.onclick=()=>{if(!d.activeId)return;const b=d.approvals.filter(C=>C.botId===d.activeId);Promise.all(b.map(C=>f(`/api/bots/${C.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:C.id,allow:!0})}))).finally(()=>void y(!0))};const u=e("button","btn","Needs you "),m=e("span");m.id="bv-inbox-count",u.appendChild(m),u.onclick=()=>void tt();const v=e("button","btn","Resume");v.onclick=()=>void G(b=>f(`/api/bots/${b}/resume`,{method:"POST"}).then(()=>y(!0)));const S=e("button","btn danger","Stop");S.onclick=()=>void G(b=>f(`/api/bots/${b}/stop`,{method:"POST"}).then(()=>y(!0)));const A=e("button","btn","Delete");A.onclick=()=>{d.activeId&&confirm("Delete this bot and its session?")&&f(`/api/bots/${d.activeId}`,{method:"DELETE"}).then(()=>{_(),y(!0)})};const E=e("button","btn","\u2715");E.onclick=()=>_(),s.append(c,r,u,v,S,A,E),n.append(o,s);const I=e("div","bots-messages");I.id="bots-messages";const x=e("div","bots-composer"),w=e("textarea");w.id="bots-input",w.rows=1,w.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",w.onkeydown=b=>{b.key==="Enter"&&!b.shiftKey&&(b.preventDefault(),z())};const O=e("button","btn primary","Send");O.onclick=()=>void z(),x.append(w,O),t.append(n,I,x),document.querySelector(".main-area")?.appendChild(t),document.getElementById("bots-modal")||ct()}async function z(){const t=document.getElementById("bots-input");if(!t||!d.activeId||!t.value.trim())return;const n=t.value;t.value="";try{await f(`/api/bots/${d.activeId}/input`,{method:"POST",body:JSON.stringify({text:n})})}catch(o){$({kind:"notice",level:"error",text:o instanceof Error?o.message:String(o)})}}function G(t){d.activeId&&t(d.activeId).catch(n=>$({kind:"notice",level:"error",text:n instanceof Error?n.message:String(n)}))}function _(){d.activeId=null;const t=document.getElementById("bots-view");t&&(t.hidden=!0);try{d.ws?.close()}catch{}d.ws=null,j();const n=document.getElementById("main-placeholder");n&&(n.style.display="")}async function q(t){d.activeId=t,d.items.set(t,[]);const n=document.getElementById("bots-view");n&&(n.hidden=!1);const o=document.getElementById("main-placeholder");o&&(o.style.display="none");const i=document.getElementById("terminal-container");i&&(i.style.display="none");const a=document.getElementById("file-editor");a&&(a.style.display="none"),j(),U();try{d.ws?.close()}catch{}const l=location.protocol==="https:"?"wss:":"ws:",s=new WebSocket(`${l}//${location.host}/ws/bots/${encodeURIComponent(t)}?token=${encodeURIComponent(L())}`);d.ws=s,s.onmessage=c=>{try{Y(JSON.parse(String(c.data)))}catch{}},s.onclose=()=>{d.activeId===t&&setTimeout(()=>{d.activeId===t&&y(!0)},1500)},await y(!0)}function K(){return d.bots.find(t=>t.id===d.activeId)||null}function V(){const t=K();if(!t)return;const n=document.getElementById("bv-title"),o=document.getElementById("bv-status"),i=document.getElementById("bv-dot");n&&(n.textContent=t.title),o&&(o.textContent=`${t.status.replace(/_/g," ")} \xB7 ${t.templateId} \xB7 ${t.projectPath}`);const a=document.getElementById("bv-mode");a&&t.runtimeMode&&(a.value=t.runtimeMode);const l=document.getElementById("bv-allow-all"),s=d.approvals.filter(c=>c.botId===t.id).length;l&&(l.hidden=s===0,l.textContent=`Allow all (${s})`),i&&(i.style.background=F(t.status))}function $(t,n=d.activeId){if(!n)return;const o=d.items.get(n)||[];o.push(t),d.items.set(n,o),n===d.activeId&&B()}function B(){d.renderQueued||(d.renderQueued=!0,requestAnimationFrame(()=>{d.renderQueued=!1,U()}))}function U(){const t=document.getElementById("bots-messages");if(!t||!d.activeId)return;const n=d.items.get(d.activeId)||[];t.textContent="";let o=null;for(const i of n)if(i.kind==="user"){const a=e("div","bv-msg bv-user");a.textContent=i.text,t.appendChild(a),o=null}else if(i.kind==="assistant"){const a=e("div","bv-msg bv-assistant");if(i.thinking){const s=e("details","bv-thinking");s.appendChild(e("summary",void 0,"thinking")),s.appendChild(e("div",void 0,i.thinking)),a.appendChild(s)}const l=e("div","bv-text");l.textContent=i.text,a.appendChild(l),t.appendChild(a),o=l}else if(i.kind==="tool")t.appendChild(it(i)),o=null;else if(i.kind==="approval")t.appendChild(at(i)),o=null;else if(i.kind==="notice"){const a=e("div",`bv-notice bv-notice-${i.level}`,i.text);t.appendChild(a)}o&&(o.scrollTop=o.scrollHeight),t.scrollTop=t.scrollHeight}function it(t){const n=e("details","bv-tool");n.open=t.phase!=="end"||!!t.isError;const o=e("summary"),i=e("span","bv-tool-name",t.name);if(o.appendChild(i),t.phase!=="end"&&o.appendChild(e("span","bv-tool-phase",t.phase)),t.isError&&o.appendChild(e("span","bv-tool-error","error")),typeof t.durationMs=="number"&&o.appendChild(e("span","bv-tool-meta",`${Math.round(t.durationMs)}ms`)),n.appendChild(o),t.args!==void 0){const a=e("pre","bv-pre");a.textContent=typeof t.args=="string"?t.args:JSON.stringify(t.args,null,2),n.appendChild(a)}if(t.output){const a=e("pre","bv-pre bv-output");a.textContent=t.output,n.appendChild(a)}return n}function at(t){const n=e("div","bv-approval"),o=t.approval;if(n.appendChild(e("div","bv-approval-title",o.title)),o.message&&n.appendChild(e("pre","bv-pre",o.message)),t.decided)return n.appendChild(e("div","bv-approval-decided",t.decided==="allowed"?"Allowed":"Denied")),n;const i=e("input","bv-reason");i.placeholder="reason (optional)";const a=e("div","bv-approval-actions"),l=e("button","btn primary","Allow"),s=e("button","btn",o.method==="confirm"&&/^Allow (.+?)\?$/.test(o.title)?`Always allow ${/^Allow (.+?)\?$/.exec(o.title)?.[1]}`:"Always allow");s.hidden=o.method!=="confirm";const c=e("button","btn danger","Deny"),r=async(u,m=!1)=>{try{await f(`/api/bots/${o.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:o.id,allow:u,always:m,reason:i.value||void 0})}),t.decided=u?"allowed":"denied",B(),y(!0)}catch(v){$({kind:"notice",level:"error",text:v instanceof Error?v.message:String(v)})}};return l.onclick=()=>void r(!0),s.onclick=()=>void r(!0,!0),c.onclick=()=>void r(!1),a.append(i,l,s,c),n.appendChild(a),n}function Y(t){const n=String(t.type||""),o=d.activeId;if(!o)return;const i=d.items.get(o)||[];if(n==="snapshot")d.items.set(o,[]);else if(n==="user")$({kind:"user",text:String(t.text||"")});else if(n==="status"){const a=K();a&&(a.status=String(t.status||a.status)),V(),lt()}else if(n==="message"){const a=t.message;if(!a||String(a.role||"")!=="assistant")return;const s=st(a),c=dt(a),r=i[i.length-1];r&&r.kind==="assistant"?(r.text=s||r.text,r.thinking=c||r.thinking):i.push({kind:"assistant",text:s,thinking:c}),d.items.set(o,i),B()}else if(n==="delta"){const a=String(t.kind||""),l=String(t.delta||"");let s=i[i.length-1];(!s||s.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),s=i[i.length-1]),s.kind==="assistant"&&(a==="text"?s.text+=l:a==="thinking"&&(s.thinking+=l)),d.items.set(o,i),B()}else if(n==="tool"){const a=String(t.callId||""),l=i.find(c=>c.kind==="tool"&&c.callId===a),s=String(t.phase||"start");l?(l.phase=s,s==="update"&&t.output&&(l.output=String(t.output)),s==="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:a,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:s}),d.items.set(o,i),B()}else if(n==="approval"){const a=t.approval;if(!a)return;const l=i;for(let s=l.length-1;s>=0;s--){const c=l[s];if(c.kind==="approval"&&c.approval.id===a.id){c.approval=a,a.state!=="pending"&&(c.decided=a.state==="allowed"?"allowed":"denied"),d.items.set(o,l),B();return}}l.push({kind:"approval",approval:a}),d.items.set(o,l),B()}else n==="notice"&&$({kind:"notice",level:String(t.level||"info"),text:String(t.text||"")})}function st(t){const n=t.content;return Array.isArray(n)?n.map(o=>o&&typeof o=="object"&&o.type==="text"?String(o.text||""):"").join(""):String(t.text||"")}function dt(t){const n=t.content;return Array.isArray(n)?n.map(o=>o&&typeof o=="object"&&o.type==="thinking"?String(o.thinking||""):"").join(""):""}async function y(t=!1){try{const[n,o]=await Promise.all([f("/api/bots"),f("/api/bots/approvals")]);if(d.bots=n,d.approvals=o,j(),V(),t&&d.activeId){const i=await f(`/api/bots/${d.activeId}/events?limit=300`);rt(i)}}catch{}}async function lt(){try{d.bots=await f("/api/bots"),j()}catch{}}function rt(t){if(d.activeId){d.items.set(d.activeId,[]);for(const n of t)Y(n);U()}}function ct(){const t=e("div","bots-modal");t.id="bots-modal",t.hidden=!0;const n=e("div","bots-modal-card"),o=e("div","bots-modal-head"),i=e("span");i.id="bots-modal-title";const a=e("button","btn","\u2715");a.onclick=()=>M(),o.append(i,a);const l=e("div","bots-modal-body");l.id="bots-modal-body",n.append(o,l),t.appendChild(n),t.onclick=s=>{s.target===t&&M()},document.body.appendChild(t)}function W(t){const n=document.getElementById("bots-modal"),o=document.getElementById("bots-modal-title"),i=document.getElementById("bots-modal-body");if(!n||!i)throw new Error("modal missing");return o&&(o.textContent=t),i.textContent="",n.hidden=!1,i}function M(){const t=document.getElementById("bots-modal");t&&(t.hidden=!0)}async function pt(){return d.catalog||(d.catalog=await f("/api/bots/catalog")),d.catalog}async function X(){return d.templates=await f("/api/bots/templates"),d.templates}async function J(){const t=W("Bot templates"),[n,o]=await Promise.all([pt(),X()]),i=e("div","bv-template-list");for(const r of o){const u=e("div","bv-template-row");u.appendChild(e("span","bv-template-name",r.manifest.name)),u.appendChild(e("span","bv-template-desc",r.manifest.description||""));const m=e("button","btn","Edit");m.onclick=()=>Z(t,n,r);const v=e("button","btn danger","Delete");v.onclick=()=>{confirm(`Delete template ${r.manifest.name}?`)&&f(`/api/bots/templates/${r.id}`,{method:"DELETE"}).then(()=>J())};const S=e("span","bv-template-actions");S.append(m,v),u.appendChild(S),i.appendChild(u)}o.length===0&&i.appendChild(e("div","bots-empty","No templates yet")),t.appendChild(i);const a=e("div","bv-template-actions"),l=e("button","btn primary","New template");l.onclick=()=>Z(t,n,null);const s=e("button","btn","Export");s.title="Download templates + library as JSON",s.onclick=()=>{(async()=>{try{const r=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${L()}`}});if(!r.ok)throw new Error(`HTTP ${r.status}`);const u=await r.blob(),m=document.createElement("a");m.href=URL.createObjectURL(u),m.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,m.click(),setTimeout(()=>URL.revokeObjectURL(m.href),2e3)}catch(r){alert(r instanceof Error?r.message:String(r))}})()};const c=e("button","btn","Import");c.title="Restore templates from a JSON bundle",c.onclick=()=>{const r=document.createElement("input");r.type="file",r.accept="application/json,.json",r.onchange=()=>{const u=r.files?.[0];u&&(async()=>{try{const m=JSON.parse(await u.text()),v=await f("/api/bots/import",{method:"POST",body:JSON.stringify(m)});alert(`Imported ${v.templates} templates, ${v.files} library files (${v.skipped} kept)`),await J()}catch(m){alert(m instanceof Error?m.message:String(m))}})()},r.click()},a.append(l,s,c),t.appendChild(a)}function H(t,n,o){const i=e("div","bv-field");i.appendChild(e("label","bv-label",t));const a=e("div","bv-check-grid"),l=[];for(const s of n){const c=e("label","bv-check"),r=document.createElement("input");r.type="checkbox",r.checked=o.includes(s.id),c.append(r,e("span",void 0,s.label)),s.hint&&(c.title=s.hint),a.appendChild(c),l.push({id:s.id,input:r})}return i.appendChild(a),{element:i,get:()=>l.filter(s=>s.input.checked).map(s=>s.id)}}function Z(t,n,o){t.textContent="";const i=o?JSON.parse(JSON.stringify(o.manifest)):{name:"new-bot",description:""},a=e("input","bv-input");a.value=i.name,a.placeholder="Template name";const l=e("input","bv-input");l.value=i.description||"",l.placeholder="One line description";const s=e("textarea","bv-textarea");s.rows=6,s.value=i.system||"",s.placeholder="System prompt for this bot (written to SYSTEM.md)";const c=H("Skills",n.skills.map(p=>({id:p.id,label:p.name,hint:p.description})),i.skills||[]),r=H("Extensions (Pi builtins + library)",n.extensions.map(p=>({id:p.id,label:`${p.name}${p.kind==="builtin"?" (builtin)":""}`,hint:p.description})),(i.extensions||[]).map(p=>p.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),u=H("Prompt templates",n.prompts.map(p=>({id:p.id,label:p.name})),i.prompts||[]),m=e("select","bv-input");m.appendChild(new Option("none",""));for(const p of n.mcp)m.appendChild(new Option(p.name,p.id));i.mcp&&(m.value=n.mcp.find(p=>JSON.stringify(p.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");const v=e("div","bv-field");v.appendChild(e("label","bv-label","Tools (allow list; deny always blocks)"));const S=e("div","bv-check-grid"),A=[];for(const p of n.tools){const T=e("label","bv-check"),g=document.createElement("input");g.type="checkbox",g.checked=(i.tools?.allow||[]).includes(p.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(p.name),T.append(g,e("span",void 0,p.name)),S.appendChild(T),A.push({name:p.name,input:g})}v.appendChild(S);const E=e("input","bv-input");E.value=(i.tools?.deny||[]).join(", "),E.placeholder="Always deny (comma separated), e.g. bash, write";const I=e("textarea","bv-textarea");I.rows=2,I.value=(i.packages||[]).join(`
2
- `),I.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";const x=e("select","bv-input");x.appendChild(new Option("default (Pi settings)",""));for(const p of n.models)x.appendChild(new Option(`${p.provider}/${p.model}`,`${p.provider}
3
- ${p.model}`));i.model?.provider&&i.model?.id&&(x.value=`${i.model.provider}
4
- ${i.model.id}`);const w=e("select","bv-input");for(const p of["","off","minimal","low","medium","high","xhigh","max"])w.appendChild(new Option(p||"default",p));i.model?.thinking&&(w.value=i.model.thinking);const O=e("select","bv-input");for(const p of["supervised","auto-accept-edits","full-access"])O.appendChild(new Option(p,p));O.value=i.permissions?.runtimeMode||"supervised";const b=e("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";const C=e("label","bv-check"),N=document.createElement("input");N.type="checkbox",N.checked=!!i.orchestrator,C.append(N,e("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));const k=(p,T)=>{const g=e("div","bv-field");return g.appendChild(e("label","bv-label",p)),g.appendChild(T),g};t.append(k("Name",a),k("Description",l),k("System prompt",s),c.element,r.element,u.element,k("MCP preset",m),v,k("Always deny tools",E),k("Packages",I),k("Model",x),k("Thinking level",w),k("Approval mode",O),k("Project resources",b),C);const Q=e("button","btn primary",o?"Save template":"Create template");Q.onclick=async()=>{const[p,T]=x.value.split(`
5
- `),g=n.mcp.find(h=>h.id===m.value),et={name:a.value.trim()||"bot",description:l.value.trim()||void 0,system:s.value.trim()||void 0,skills:c.get(),extensions:r.get().map(h=>(h.startsWith("builtin:"),h)),prompts:u.get(),packages:I.value.split(`
6
- `).map(h=>h.trim()).filter(Boolean),mcp:g?{mcpServers:g.servers}:void 0,tools:{allow:A.filter(h=>h.input.checked).map(h=>h.name),deny:E.value.split(",").map(h=>h.trim()).filter(Boolean)},model:p?{provider:p,id:T,thinking:w.value||void 0}:void 0,permissions:{runtimeMode:O.value},projectResources:b.value==="inherit"?"inherit":"ignore",orchestrator:N.checked||void 0};try{await f("/api/bots/templates",{method:"POST",body:JSON.stringify({id:o?.id,manifest:et})}),M(),await J()}catch(h){alert(h instanceof Error?h.message:String(h))}},t.appendChild(Q)}async function ut(){return mt("")}async function mt(t){const n=W("New bot"),o=await X();if(o.length===0){n.appendChild(e("div","bots-empty","Create a template first (\u2699)."));return}const i=e("select","bv-input");for(const u of o)i.appendChild(new Option(u.manifest.name,u.id));const a=e("input","bv-input");a.placeholder="Title (defaults to template name)";const l=e("input","bv-input");l.placeholder="/path/to/project";const s=t||d.bots[0]?.projectPath||"";l.value=s;const c=e("select","bv-input");c.appendChild(new Option("shared \u2014 run in the project folder","shared")),c.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),n.append(D("Template",i),D("Title",a),D("Project path",l),D("Workspace",c));const r=e("button","btn primary","Create bot");r.onclick=async()=>{try{const u=await f("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:a.value.trim()||void 0,projectPath:l.value.trim()||void 0,isolation:c.value})});M(),await y(!0),await q(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},n.appendChild(r)}function D(t,n){const o=e("div","bv-field");return o.appendChild(e("label","bv-label",t)),o.appendChild(n),o}async function tt(){const t=W("Needs you");if(d.approvals=await f("/api/bots/approvals"),d.approvals.length===0){t.appendChild(e("div","bots-empty","Nothing waiting."));return}for(const n of d.approvals){const o=e("div","bv-approval");o.appendChild(e("div","bv-approval-title",`${n.botTitle}: ${n.title}`)),n.message&&o.appendChild(e("pre","bv-pre",n.message));const i=e("input","bv-reason");i.placeholder="reason (optional)";const a=e("div","bv-approval-actions"),l=e("button","btn primary","Allow"),s=e("button","btn danger","Deny"),c=async r=>{await f(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:r,reason:i.value||void 0})}),await y(!0),await tt()};l.onclick=()=>void c(!0),s.onclick=()=>void c(!1),a.append(i,l,s),o.appendChild(a),t.appendChild(o)}}function ft(){if(document.getElementById("bots-section"))return;const t=nt();R=t.list,P=t.badge,ot(),window.__openBot=q,document.addEventListener("click",n=>{const o=n.target;o&&o.closest(".session-item")&&d.activeId&&_()},!0),y(!0),d.pollTimer=window.setInterval(()=>{document.hidden||y()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(d.pollTimer))}export{ft as initBots,mt as openNewBotForPath};
1
+ const d={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function L(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function f(t,n){const o=await fetch(t,{...n,headers:{"content-type":"application/json",Authorization:`Bearer ${L()}`,...n?.headers||{}}}),i=await o.text(),a=i?JSON.parse(i):null;if(!o.ok)throw new Error(a&&a.error||`HTTP ${o.status}`);return a}function e(t,n,o){const i=document.createElement(t);return n&&(i.className=n),o!==void 0&&(i.textContent=o),i}function Q(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 nt(){const t=e("div","bots-section");t.id="bots-section";const n=e("div","bots-head"),o=e("span","bots-title","Bots"),i=e("span","bots-badge");i.hidden=!0,o.appendChild(i);const a=e("span","bots-head-actions"),l=e("button","bots-icon-btn","\u2699");l.title="Bot templates",l.onclick=()=>void A();const s=e("button","bots-icon-btn","+");s.title="New bot from template",s.onclick=()=>void ut(),a.append(l,s),n.append(o,a);const c=e("div","bots-list");c.id="bots-list",t.append(n,c);const r=document.querySelector(".sidebar"),u=document.querySelector(".sidebar-footer");return r&&r.insertBefore(t,u||null),{list:c,badge:i}}let R=null,j=null;function J(){R&&(R.textContent="");const t=d.approvals.length;j&&(j.hidden=t===0,j.textContent=String(t));const n=document.getElementById("bv-inbox-count");n&&(n.textContent=t?`(${t})`:""),window.__botsSnapshot=d.bots,window.__refreshSidebar?.()}function bt(t){const n=e("div","bots-row");n.dataset.botId=t.id,t.id===d.activeId&&n.classList.add("active");const o=e("span","bots-dot");o.style.background=Q(t.status);const i=e("span","bots-name",t.title),a=e("span","bots-meta",t.status.replace(/_/g," "));return n.append(o,i,a),n.onclick=()=>void q(t.id),n}function ot(){const t=e("div","bots-view");t.id="bots-view",t.hidden=!0;const n=e("div","bots-view-head"),o=e("div","bv-title"),i=e("span","bots-dot");i.id="bv-dot";const a=e("span","bv-title-text");a.id="bv-title";const l=e("span","bv-status");l.id="bv-status",o.append(i,a,l);const s=e("div","bv-actions"),c=e("select","bv-mode-select");c.id="bv-mode",c.title="Approval mode for this bot";for(const[b,I]of[["supervised","\u9ED8\u8BA4\uFF1A\u53EA\u8BFB\u81EA\u52A8\uFF0C\u5176\u4F59\u95EE\u6211"],["parent-supervised","Super agent \u76D1\u7BA1\uFF1A\u4EA4\u7ED9\u4E0A\u7EA7 bot"],["full-access","Full access\uFF1A\u5168\u90E8\u653E\u884C"]])c.appendChild(new Option(I,b));c.onchange=()=>{d.activeId&&f(`/api/bots/${d.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:c.value})}).then(()=>B({kind:"notice",level:"info",text:`Approval mode: ${c.value}`})).catch(b=>B({kind:"notice",level:"error",text:b instanceof Error?b.message:String(b)}))};const r=e("button","btn","Allow all");r.id="bv-allow-all",r.title="Approve every pending request for this bot",r.onclick=()=>{if(!d.activeId)return;const b=d.approvals.filter(I=>I.botId===d.activeId);Promise.all(b.map(I=>f(`/api/bots/${I.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:I.id,allow:!0})}))).finally(()=>void w(!0))};const u=e("button","btn","Needs you "),m=e("span");m.id="bv-inbox-count",u.appendChild(m),u.onclick=()=>void tt();const v=e("button","btn","Resume");v.onclick=()=>void G(b=>f(`/api/bots/${b}/resume`,{method:"POST"}).then(()=>w(!0)));const x=e("button","btn danger","Stop");x.onclick=()=>void G(b=>f(`/api/bots/${b}/stop`,{method:"POST"}).then(()=>w(!0)));const E=e("button","btn","Delete");E.onclick=()=>{d.activeId&&confirm("Delete this bot and its session?")&&f(`/api/bots/${d.activeId}`,{method:"DELETE"}).then(()=>{_(),w(!0)})};const k=e("button","btn","\u2715");k.onclick=()=>_(),s.append(c,r,u,v,x,E,k),n.append(o,s);const g=e("div","bots-messages");g.id="bots-messages";const O=e("div","bots-composer"),S=e("textarea");S.id="bots-input",S.rows=1,S.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",S.onkeydown=b=>{b.key==="Enter"&&!b.shiftKey&&(b.preventDefault(),z())};const $=e("button","btn primary","Send");$.onclick=()=>void z(),O.append(S,$),t.append(n,g,O),document.querySelector(".main-area")?.appendChild(t),document.getElementById("bots-modal")||ct()}async function z(){const t=document.getElementById("bots-input");if(!t||!d.activeId||!t.value.trim())return;const n=t.value;t.value="";try{await f(`/api/bots/${d.activeId}/input`,{method:"POST",body:JSON.stringify({text:n})})}catch(o){B({kind:"notice",level:"error",text:o instanceof Error?o.message:String(o)})}}function G(t){d.activeId&&t(d.activeId).catch(n=>B({kind:"notice",level:"error",text:n instanceof Error?n.message:String(n)}))}function _(){d.activeId=null;const t=document.getElementById("bots-view");t&&(t.hidden=!0);try{d.ws?.close()}catch{}d.ws=null,J();const n=document.getElementById("main-placeholder");n&&(n.style.display="")}async function q(t){d.activeId=t,d.items.set(t,[]);const n=document.getElementById("bots-view");n&&(n.hidden=!1);const o=document.getElementById("main-placeholder");o&&(o.style.display="none");const i=document.getElementById("terminal-container");i&&(i.style.display="none");const a=document.getElementById("file-editor");a&&(a.style.display="none"),J(),U();try{d.ws?.close()}catch{}const l=location.protocol==="https:"?"wss:":"ws:",s=new WebSocket(`${l}//${location.host}/ws/bots/${encodeURIComponent(t)}?token=${encodeURIComponent(L())}`);d.ws=s,s.onmessage=c=>{try{Y(JSON.parse(String(c.data)))}catch{}},s.onclose=()=>{d.activeId===t&&setTimeout(()=>{d.activeId===t&&w(!0)},1500)},await w(!0)}function K(){return d.bots.find(t=>t.id===d.activeId)||null}function V(){const t=K();if(!t)return;const n=document.getElementById("bv-title"),o=document.getElementById("bv-status"),i=document.getElementById("bv-dot");n&&(n.textContent=t.title),o&&(o.textContent=`${t.status.replace(/_/g," ")} \xB7 ${t.templateId} \xB7 ${t.projectPath}`);const a=document.getElementById("bv-mode");a&&t.runtimeMode&&(a.value=t.runtimeMode);const l=document.getElementById("bv-allow-all"),s=d.approvals.filter(c=>c.botId===t.id).length;l&&(l.hidden=s===0,l.textContent=`Allow all (${s})`),i&&(i.style.background=Q(t.status))}function B(t,n=d.activeId){if(!n)return;const o=d.items.get(n)||[];o.push(t),d.items.set(n,o),n===d.activeId&&T()}function T(){d.renderQueued||(d.renderQueued=!0,requestAnimationFrame(()=>{d.renderQueued=!1,U()}))}function U(){const t=document.getElementById("bots-messages");if(!t||!d.activeId)return;const n=d.items.get(d.activeId)||[];t.textContent="";let o=null;for(const i of n)if(i.kind==="user"){const a=e("div","bv-msg bv-user");a.textContent=i.text,t.appendChild(a),o=null}else if(i.kind==="assistant"){const a=e("div","bv-msg bv-assistant");if(i.thinking){const s=e("details","bv-thinking");s.appendChild(e("summary",void 0,"thinking")),s.appendChild(e("div",void 0,i.thinking)),a.appendChild(s)}const l=e("div","bv-text");l.textContent=i.text,a.appendChild(l),t.appendChild(a),o=l}else if(i.kind==="tool")t.appendChild(it(i)),o=null;else if(i.kind==="approval")t.appendChild(at(i)),o=null;else if(i.kind==="notice"){const a=e("div",`bv-notice bv-notice-${i.level}`,i.text);t.appendChild(a)}o&&(o.scrollTop=o.scrollHeight),t.scrollTop=t.scrollHeight}function it(t){const n=e("details","bv-tool");n.open=t.phase!=="end"||!!t.isError;const o=e("summary"),i=e("span","bv-tool-name",t.name);if(o.appendChild(i),t.phase!=="end"&&o.appendChild(e("span","bv-tool-phase",t.phase)),t.isError&&o.appendChild(e("span","bv-tool-error","error")),typeof t.durationMs=="number"&&o.appendChild(e("span","bv-tool-meta",`${Math.round(t.durationMs)}ms`)),n.appendChild(o),t.args!==void 0){const a=e("pre","bv-pre");a.textContent=typeof t.args=="string"?t.args:JSON.stringify(t.args,null,2),n.appendChild(a)}if(t.output){const a=e("pre","bv-pre bv-output");a.textContent=t.output,n.appendChild(a)}return n}function at(t){const n=e("div","bv-approval"),o=t.approval;if(n.appendChild(e("div","bv-approval-title",o.title)),o.message&&n.appendChild(e("pre","bv-pre",o.message)),t.decided)return n.appendChild(e("div","bv-approval-decided",t.decided==="allowed"?"Allowed":"Denied")),n;const i=e("input","bv-reason");i.placeholder="reason (optional)";const a=e("div","bv-approval-actions"),l=e("button","btn primary","Allow"),s=e("button","btn",o.method==="confirm"&&/^Allow (.+?)\?$/.test(o.title)?`Always allow ${/^Allow (.+?)\?$/.exec(o.title)?.[1]}`:"Always allow");s.hidden=o.method!=="confirm";const c=e("button","btn danger","Deny"),r=async(u,m=!1)=>{try{await f(`/api/bots/${o.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:o.id,allow:u,always:m,reason:i.value||void 0})}),t.decided=u?"allowed":"denied",T(),w(!0)}catch(v){B({kind:"notice",level:"error",text:v instanceof Error?v.message:String(v)})}};return l.onclick=()=>void r(!0),s.onclick=()=>void r(!0,!0),c.onclick=()=>void r(!1),a.append(i,l,s,c),n.appendChild(a),n}function Y(t){const n=String(t.type||""),o=d.activeId;if(!o)return;const i=d.items.get(o)||[];if(n==="snapshot")d.items.set(o,[]);else if(n==="user")B({kind:"user",text:String(t.text||"")});else if(n==="status"){const a=K();a&&(a.status=String(t.status||a.status)),V(),lt()}else if(n==="message"){const a=t.message;if(!a||String(a.role||"")!=="assistant")return;const s=st(a),c=dt(a),r=i[i.length-1];r&&r.kind==="assistant"?(r.text=s||r.text,r.thinking=c||r.thinking):i.push({kind:"assistant",text:s,thinking:c}),d.items.set(o,i),T()}else if(n==="delta"){const a=String(t.kind||""),l=String(t.delta||"");let s=i[i.length-1];(!s||s.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),s=i[i.length-1]),s.kind==="assistant"&&(a==="text"?s.text+=l:a==="thinking"&&(s.thinking+=l)),d.items.set(o,i),T()}else if(n==="tool"){const a=String(t.callId||""),l=i.find(c=>c.kind==="tool"&&c.callId===a),s=String(t.phase||"start");l?(l.phase=s,s==="update"&&t.output&&(l.output=String(t.output)),s==="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:a,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:s}),d.items.set(o,i),T()}else if(n==="approval"){const a=t.approval;if(!a)return;const l=i;for(let s=l.length-1;s>=0;s--){const c=l[s];if(c.kind==="approval"&&c.approval.id===a.id){c.approval=a,a.state!=="pending"&&(c.decided=a.state==="allowed"?"allowed":"denied"),d.items.set(o,l),T();return}}l.push({kind:"approval",approval:a}),d.items.set(o,l),T()}else n==="notice"&&B({kind:"notice",level:String(t.level||"info"),text:String(t.text||"")})}function st(t){const n=t.content;return Array.isArray(n)?n.map(o=>o&&typeof o=="object"&&o.type==="text"?String(o.text||""):"").join(""):String(t.text||"")}function dt(t){const n=t.content;return Array.isArray(n)?n.map(o=>o&&typeof o=="object"&&o.type==="thinking"?String(o.thinking||""):"").join(""):""}async function w(t=!1){try{const[n,o]=await Promise.all([f("/api/bots"),f("/api/bots/approvals")]);if(d.bots=n,d.approvals=o,J(),V(),t&&d.activeId){const i=await f(`/api/bots/${d.activeId}/events?limit=300`);rt(i)}}catch{}}async function lt(){try{d.bots=await f("/api/bots"),J()}catch{}}function rt(t){if(d.activeId){d.items.set(d.activeId,[]);for(const n of t)Y(n);U()}}function ct(){const t=e("div","bots-modal");t.id="bots-modal",t.hidden=!0;const n=e("div","bots-modal-card"),o=e("div","bots-modal-head"),i=e("span");i.id="bots-modal-title";const a=e("button","btn","\u2715");a.onclick=()=>M(),o.append(i,a);const l=e("div","bots-modal-body");l.id="bots-modal-body",n.append(o,l),t.appendChild(n),t.onclick=s=>{s.target===t&&M()},document.body.appendChild(t)}function W(t){const n=document.getElementById("bots-modal"),o=document.getElementById("bots-modal-title"),i=document.getElementById("bots-modal-body");if(!n||!i)throw new Error("modal missing");return o&&(o.textContent=t),i.textContent="",n.hidden=!1,i}function M(){const t=document.getElementById("bots-modal");t&&(t.hidden=!0)}async function pt(){return d.catalog||(d.catalog=await f("/api/bots/catalog")),d.catalog}async function X(){return d.templates=await f("/api/bots/templates"),d.templates}async function A(){const t=W("Bot templates"),[n,o]=await Promise.all([pt(),X()]),i=e("div","bv-template-list");for(const r of o){const u=e("div","bv-template-row");u.appendChild(e("span","bv-template-name",r.manifest.name)),u.appendChild(e("span","bv-template-desc",r.manifest.description||""));const m=e("button","btn","Edit");m.onclick=()=>Z(t,n,r);const v=e("button","btn","Copy");v.title="Duplicate this template",v.onclick=()=>{const k=JSON.parse(JSON.stringify(r.manifest));k.name=`${r.manifest.name} copy`,f("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:k})}).then(()=>A()).catch(g=>alert(g instanceof Error?g.message:String(g)))};const x=e("button","btn danger","Delete");x.onclick=()=>{confirm(`Delete template ${r.manifest.name}?`)&&f(`/api/bots/templates/${r.id}`,{method:"DELETE"}).then(()=>A())};const E=e("span","bv-template-actions");E.append(m,v,x),u.appendChild(E),i.appendChild(u)}o.length===0&&i.appendChild(e("div","bots-empty","No templates yet")),t.appendChild(i);const a=e("div","bv-template-actions"),l=e("button","btn primary","New template");l.onclick=()=>Z(t,n,null);const s=e("button","btn","Export");s.title="Download templates + library as JSON",s.onclick=()=>{(async()=>{try{const r=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${L()}`}});if(!r.ok)throw new Error(`HTTP ${r.status}`);const u=await r.blob(),m=document.createElement("a");m.href=URL.createObjectURL(u),m.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,m.click(),setTimeout(()=>URL.revokeObjectURL(m.href),2e3)}catch(r){alert(r instanceof Error?r.message:String(r))}})()};const c=e("button","btn","Import");c.title="Restore templates from a JSON bundle",c.onclick=()=>{const r=document.createElement("input");r.type="file",r.accept="application/json,.json",r.onchange=()=>{const u=r.files?.[0];u&&(async()=>{try{const m=JSON.parse(await u.text()),v=await f("/api/bots/import",{method:"POST",body:JSON.stringify(m)});alert(`Imported ${v.templates} templates, ${v.files} library files (${v.skipped} kept)`),await A()}catch(m){alert(m instanceof Error?m.message:String(m))}})()},r.click()},a.append(l,s,c),t.appendChild(a)}function H(t,n,o){const i=e("div","bv-field");i.appendChild(e("label","bv-label",t));const a=e("div","bv-check-grid"),l=[];for(const s of n){const c=e("label","bv-check"),r=document.createElement("input");r.type="checkbox",r.checked=o.includes(s.id),c.append(r,e("span",void 0,s.label)),s.hint&&(c.title=s.hint),a.appendChild(c),l.push({id:s.id,input:r})}return i.appendChild(a),{element:i,get:()=>l.filter(s=>s.input.checked).map(s=>s.id)}}function Z(t,n,o){t.textContent="";const i=o?JSON.parse(JSON.stringify(o.manifest)):{name:"new-bot",description:""},a=e("input","bv-input");a.value=i.name,a.placeholder="Template name";const l=e("input","bv-input");l.value=i.description||"",l.placeholder="One line description";const s=e("textarea","bv-textarea");s.rows=6,s.value=i.system||"",s.placeholder="System prompt for this bot (written to SYSTEM.md)";const c=H("Skills",n.skills.map(p=>({id:p.id,label:p.name,hint:p.description})),i.skills||[]),r=H("Extensions (Pi builtins + library)",n.extensions.map(p=>({id:p.id,label:`${p.name}${p.kind==="builtin"?" (builtin)":""}`,hint:p.description})),(i.extensions||[]).map(p=>p.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),u=H("Prompt templates",n.prompts.map(p=>({id:p.id,label:p.name})),i.prompts||[]),m=e("select","bv-input");m.appendChild(new Option("none",""));for(const p of n.mcp)m.appendChild(new Option(p.name,p.id));i.mcp&&(m.value=n.mcp.find(p=>JSON.stringify(p.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");const v=e("div","bv-field");v.appendChild(e("label","bv-label","Tools (allow list; deny always blocks)"));const x=e("div","bv-check-grid"),E=[];for(const p of n.tools){const N=e("label","bv-check"),y=document.createElement("input");y.type="checkbox",y.checked=(i.tools?.allow||[]).includes(p.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(p.name),N.append(y,e("span",void 0,p.name)),x.appendChild(N),E.push({name:p.name,input:y})}v.appendChild(x);const k=e("input","bv-input");k.value=(i.tools?.deny||[]).join(", "),k.placeholder="Always deny (comma separated), e.g. bash, write";const g=e("textarea","bv-textarea");g.rows=2,g.value=(i.packages||[]).join(`
2
+ `),g.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";const O=e("select","bv-input");O.appendChild(new Option("default (Pi settings)",""));for(const p of n.models)O.appendChild(new Option(`${p.provider}/${p.model}`,`${p.provider}
3
+ ${p.model}`));i.model?.provider&&i.model?.id&&(O.value=`${i.model.provider}
4
+ ${i.model.id}`);const S=e("select","bv-input");for(const p of["","off","minimal","low","medium","high","xhigh","max"])S.appendChild(new Option(p||"default",p));i.model?.thinking&&(S.value=i.model.thinking);const $=e("select","bv-input");for(const p of["supervised","auto-accept-edits","full-access"])$.appendChild(new Option(p,p));$.value=i.permissions?.runtimeMode||"supervised";const b=e("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";const I=e("label","bv-check"),P=document.createElement("input");P.type="checkbox",P.checked=!!i.orchestrator,I.append(P,e("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));const C=(p,N)=>{const y=e("div","bv-field");return y.appendChild(e("label","bv-label",p)),y.appendChild(N),y};t.append(C("Name",a),C("Description",l),C("System prompt",s),c.element,r.element,u.element,C("MCP preset",m),v,C("Always deny tools",k),C("Packages",g),C("Model",O),C("Thinking level",S),C("Approval mode",$),C("Project resources",b),I);const F=e("button","btn primary",o?"Save template":"Create template");F.onclick=async()=>{const[p,N]=O.value.split(`
5
+ `),y=n.mcp.find(h=>h.id===m.value),et={name:a.value.trim()||"bot",description:l.value.trim()||void 0,system:s.value.trim()||void 0,skills:c.get(),extensions:r.get().map(h=>(h.startsWith("builtin:"),h)),prompts:u.get(),packages:g.value.split(`
6
+ `).map(h=>h.trim()).filter(Boolean),mcp:y?{mcpServers:y.servers}:void 0,tools:{allow:E.filter(h=>h.input.checked).map(h=>h.name),deny:k.value.split(",").map(h=>h.trim()).filter(Boolean)},model:p?{provider:p,id:N,thinking:S.value||void 0}:void 0,permissions:{runtimeMode:$.value},projectResources:b.value==="inherit"?"inherit":"ignore",orchestrator:P.checked||void 0};try{await f("/api/bots/templates",{method:"POST",body:JSON.stringify({id:o?.id,manifest:et})}),M(),await A()}catch(h){alert(h instanceof Error?h.message:String(h))}},t.appendChild(F)}async function ut(){return mt("")}async function mt(t){const n=W("New bot"),o=await X();if(o.length===0){n.appendChild(e("div","bots-empty","Create a template first (\u2699)."));return}const i=e("select","bv-input");for(const u of o)i.appendChild(new Option(u.manifest.name,u.id));const a=e("input","bv-input");a.placeholder="Title (defaults to template name)";const l=e("input","bv-input");l.placeholder="/path/to/project";const s=t||d.bots[0]?.projectPath||"";l.value=s;const c=e("select","bv-input");c.appendChild(new Option("shared \u2014 run in the project folder","shared")),c.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),n.append(D("Template",i),D("Title",a),D("Project path",l),D("Workspace",c));const r=e("button","btn primary","Create bot");r.onclick=async()=>{try{const u=await f("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:a.value.trim()||void 0,projectPath:l.value.trim()||void 0,isolation:c.value})});M(),await w(!0),await q(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},n.appendChild(r)}function D(t,n){const o=e("div","bv-field");return o.appendChild(e("label","bv-label",t)),o.appendChild(n),o}async function tt(){const t=W("Needs you");if(d.approvals=await f("/api/bots/approvals"),d.approvals.length===0){t.appendChild(e("div","bots-empty","Nothing waiting."));return}for(const n of d.approvals){const o=e("div","bv-approval");o.appendChild(e("div","bv-approval-title",`${n.botTitle}: ${n.title}`)),n.message&&o.appendChild(e("pre","bv-pre",n.message));const i=e("input","bv-reason");i.placeholder="reason (optional)";const a=e("div","bv-approval-actions"),l=e("button","btn primary","Allow"),s=e("button","btn danger","Deny"),c=async r=>{await f(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:r,reason:i.value||void 0})}),await w(!0),await tt()};l.onclick=()=>void c(!0),s.onclick=()=>void c(!1),a.append(i,l,s),o.appendChild(a),t.appendChild(o)}}function ft(){if(document.getElementById("bots-section"))return;const t=nt();R=t.list,j=t.badge,ot(),window.__openBot=q,document.addEventListener("click",n=>{const o=n.target;o&&o.closest(".session-item")&&d.activeId&&_()},!0),w(!0),d.pollTimer=window.setInterval(()=>{document.hidden||w()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(d.pollTimer))}export{ft as initBots,mt as openNewBotForPath};
@@ -1,34 +1,34 @@
1
- import{initTerminal as nt}from"./terminal-core.js";import{initBots as st,openNewBotForPath as it}from"./bots-client.js";const z=window.__TMUX_WEB_SHELL__;let f=null,u=null;const O=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let h=O;window.__tmuxWebScopeAgent=O;let be="sessions",x="",Q="",ee="",xe="";function g(e){return h?"/a/"+encodeURIComponent(h)+e:e}const d=document.getElementById("sidebar-content"),$=document.getElementById("main-placeholder"),w=document.getElementById("terminal-container"),U=document.getElementById("file-editor"),ot=document.getElementById("fe-path"),k=document.getElementById("fe-status"),W=document.getElementById("fe-content"),_=document.getElementById("fe-save"),at=document.getElementById("fe-delete"),lt=document.getElementById("fe-back"),Te=document.getElementById("fe-new-name"),ct=document.getElementById("fe-new-btn"),we=document.getElementById("settings-backdrop"),Me=document.getElementById("settings-popover"),He=document.querySelector(".sidebar"),Ne="tmux-web-force-narrow";function te(){try{return localStorage.getItem(Ne)==="1"}catch{return!1}}function Re(){document.documentElement.classList.toggle("force-narrow",te()),te()&&$e()&&ne()}function $e(){return te()?!0:window.matchMedia("(max-width: 640px)").matches}function ne(){$e()&&He.classList.add("collapsed")}function _e(){He.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{_e(),Ae("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{_e(),Ae("files")});function Ae(e){be=e,document.querySelectorAll(".mode-btn").forEach(t=>t.classList.remove("active"));const n=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");n&&n.classList.add("active"),e==="sessions"?(Le="",T()):kt()}let Le="";async function T(){if(be!=="sessions")return;try{const t=await(await fetch("/api/sidebar/sessions")).json(),s=(window.__botsSnapshot||[]).map(o=>[o.id,o.title,o.status,o.projectPath]),i=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones,bots:s});if(i===Le)return;Le=i,mt(t)}catch{d.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}const e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{const n=window.__openNewSessionModal;typeof n=="function"?n():document.getElementById("new-session-modal")?.classList.add("open")}),Ie()}const Pe="tmux-web-sidebar-group-collapsed";function De(){try{return new Set(JSON.parse(localStorage.getItem(Pe)||"[]"))}catch{return new Set}}function rt(e){try{localStorage.setItem(Pe,JSON.stringify([...e]))}catch{}}function dt(e,n,t){if(!e)return"\u2026";const s=t&&(e===t||e.startsWith(t+"/"))?"~"+e.slice(t.length):e,i=s.split("/").filter(Boolean);if(i.length===0)return e;for(let o=1;o<=i.length;o++){const a=i.slice(-o).join("/");if(!n.some(l=>!l||l===e?!1:(t&&(l===t||l.startsWith(t+"/"))?"~"+l.slice(t.length):l).split("/").filter(Boolean).slice(-o).join("/")===a))return a}return s}function pt(e){const n=document.createElement("div");n.className="session-item bot-item",n.setAttribute("data-bot-id",e.id),n.title=`Bot \xB7 ${e.projectPath}`;const t=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 n.innerHTML=`<svg class="bot-icon" viewBox="0 0 24 24" fill="currentColor"><path d="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"/></svg><span>${p(e.title)}</span><span class="bot-status-dot" style="background:${t}"></span>`,n.addEventListener("click",s=>{s.stopPropagation(),window.__openBot?.(e.id)}),n}function je(e,n,t,s=!0){const i=new Map;for(const r of e){const v=r.path||"";i.has(v)||i.set(v,[]),i.get(v).push(r)}const o=t?[]:window.__botsSnapshot||[],a=new Map;for(const r of o)i.has(r.projectPath)||i.set(r.projectPath,[]),a.has(r.projectPath)||a.set(r.projectPath,[]),a.get(r.projectPath).push(r);const c=[...i.keys()],l=De();for(const[r,v]of i){const H=dt(r,c,n),R=l.has(r),I=document.createElement("div");if(I.className="session-group-header"+(R?" collapsed":""),I.title=r||"No working directory",I.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${p(H)}</span>`,!t&&r){const y=document.createElement("button");y.className="sg-add-bot",y.textContent="+",y.title=`New bot in ${r}`,y.addEventListener("click",Z=>{Z.stopPropagation(),pe(r)}),I.appendChild(y)}I.addEventListener("click",()=>{const y=De(),Z=I.nextElementSibling;y.has(r)?(y.delete(r),I.classList.remove("collapsed"),Z?.classList.remove("collapsed")):(y.add(r),I.classList.add("collapsed"),Z?.classList.add("collapsed")),rt(y)});const X=document.createElement("div");X.className="session-group-body"+(R?" collapsed":"");for(const y of v)X.appendChild(t?ft(y,t,s):ut(y,r));for(const y of a.get(r)||[])X.appendChild(pt(y));d.appendChild(I),d.appendChild(X)}}function ft(e,n,t){const s=document.createElement("div");s.className="session-item"+(e.name===u&&h===n?" active":"")+(t?"":" session-offline"),s.setAttribute("data-session",e.name),s.setAttribute("data-agent",n),s.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>
2
- <span>${p(e.name)}</span>${t?"":'<span class="meta">offline</span>'}
3
- <button class="session-edit-btn" data-session="${p(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>`,t&&s.addEventListener("click",o=>{o.target.closest(".session-edit-btn")||F(e.name,n)});const i=s.querySelector(".session-edit-btn");return i&&i.addEventListener("click",o=>{o.stopPropagation(),ue(e.name,i,{agentId:n})}),s}function ut(e,n){const t=document.createElement("div");t.className="session-item"+(e.name===u&&!h?" 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>
1
+ import{initTerminal as tt}from"./terminal-core.js";import{initBots as nt,openNewBotForPath as st}from"./bots-client.js";const j=window.__TMUX_WEB_SHELL__;let f=null,u=null;const z=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let h=z;window.__tmuxWebScopeAgent=z;let ye="sessions",I="",Z="",Q="",Ie="";function g(e){return h?"/a/"+encodeURIComponent(h)+e:e}const d=document.getElementById("sidebar-content"),R=document.getElementById("main-placeholder"),w=document.getElementById("terminal-container"),O=document.getElementById("file-editor"),it=document.getElementById("fe-path"),E=document.getElementById("fe-status"),U=document.getElementById("fe-content"),_=document.getElementById("fe-save"),ot=document.getElementById("fe-delete"),at=document.getElementById("fe-back"),xe=document.getElementById("fe-new-name"),lt=document.getElementById("fe-new-btn"),he=document.getElementById("settings-backdrop"),Te=document.getElementById("settings-popover"),Me=document.querySelector(".sidebar"),He="tmux-web-force-narrow";function ee(){try{return localStorage.getItem(He)==="1"}catch{return!1}}function Ne(){document.documentElement.classList.toggle("force-narrow",ee()),ee()&&Re()&&te()}function Re(){return ee()?!0:window.matchMedia("(max-width: 640px)").matches}function te(){Re()&&Me.classList.add("collapsed")}function _e(){Me.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{_e(),$e("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{_e(),$e("files")});function $e(e){ye=e,document.querySelectorAll(".mode-btn").forEach(n=>n.classList.remove("active"));const t=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");t&&t.classList.add("active"),e==="sessions"?(be="",x()):Et()}let be="";async function x(){if(ye!=="sessions")return;try{const n=await(await fetch("/api/sidebar/sessions")).json(),s=(window.__botsSnapshot||[]).map(o=>[o.id,o.title,o.status,o.projectPath]),i=JSON.stringify({recent:n.recent,agents:n.agents,tombstones:n.tombstones,bots:s});if(i===be)return;be=i,ut(n)}catch{d.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}const e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{const t=window.__openNewSessionModal;typeof t=="function"?t():document.getElementById("new-session-modal")?.classList.add("open")}),Be()}const Ae="tmux-web-sidebar-group-collapsed";function Pe(){try{return new Set(JSON.parse(localStorage.getItem(Ae)||"[]"))}catch{return new Set}}function ct(e){try{localStorage.setItem(Ae,JSON.stringify([...e]))}catch{}}function rt(e,t,n){if(!e)return"\u2026";const s=n&&(e===n||e.startsWith(n+"/"))?"~"+e.slice(n.length):e,i=s.split("/").filter(Boolean);if(i.length===0)return e;for(let o=1;o<=i.length;o++){const a=i.slice(-o).join("/");if(!t.some(c=>!c||c===e?!1:(n&&(c===n||c.startsWith(n+"/"))?"~"+c.slice(n.length):c).split("/").filter(Boolean).slice(-o).join("/")===a))return a}return s}function dt(e){const t=document.createElement("div");t.className="session-item bot-item",t.setAttribute("data-bot-id",e.id),t.title=`Bot \xB7 ${e.projectPath}`;const 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=`<svg class="bot-icon" viewBox="0 0 24 24" fill="currentColor"><path d="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"/></svg><span>${p(e.title)}</span><span class="bot-status-dot" style="background:${n}"></span>`,t.addEventListener("click",s=>{s.stopPropagation(),window.__openBot?.(e.id)}),t}function De(e,t,n,s=!0){const i=new Map;for(const r of e){const v=r.path||"";i.has(v)||i.set(v,[]),i.get(v).push(r)}const o=n?[]:window.__botsSnapshot||[],a=new Map;for(const r of o)i.has(r.projectPath)||i.set(r.projectPath,[]),a.has(r.projectPath)||a.set(r.projectPath,[]),a.get(r.projectPath).push(r);const l=[...i.keys()],c=Pe();for(const[r,v]of i){const H=rt(r,l,t),N=c.has(r),B=document.createElement("div");if(B.className="session-group-header"+(N?" collapsed":""),B.title=r||"No working directory",B.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${p(H)}</span>`,!n&&r){const y=document.createElement("button");y.className="sg-add-bot",y.textContent="+",y.title=`New bot in ${r}`,y.addEventListener("click",X=>{X.stopPropagation(),Le(r)}),B.appendChild(y)}B.addEventListener("click",()=>{const y=Pe(),X=B.nextElementSibling;y.has(r)?(y.delete(r),B.classList.remove("collapsed"),X?.classList.remove("collapsed")):(y.add(r),B.classList.add("collapsed"),X?.classList.add("collapsed")),ct(y)});const Y=document.createElement("div");Y.className="session-group-body"+(N?" collapsed":"");for(const y of v)Y.appendChild(n?pt(y,n,s):ft(y));for(const y of a.get(r)||[])Y.appendChild(dt(y));d.appendChild(B),d.appendChild(Y)}}function pt(e,t,n){const s=document.createElement("div");s.className="session-item"+(e.name===u&&h===t?" active":"")+(n?"":" session-offline"),s.setAttribute("data-session",e.name),s.setAttribute("data-agent",t),s.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>
2
+ <span>${p(e.name)}</span>${n?"":'<span class="meta">offline</span>'}
3
+ <button class="session-edit-btn" data-session="${p(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&&s.addEventListener("click",o=>{o.target.closest(".session-edit-btn")||W(e.name,t)});const i=s.querySelector(".session-edit-btn");return i&&i.addEventListener("click",o=>{o.stopPropagation(),pe(e.name,i,{agentId:t})}),s}function ft(e){const t=document.createElement("div");t.className="session-item"+(e.name===u&&!h?" 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>
4
4
  <span>${p(e.name)}</span>
5
5
  <button class="session-edit-btn" data-session="${p(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>
6
- `,t.addEventListener("click",i=>{i.target.closest(".session-edit-btn")||F(e.name)});const s=t.querySelector(".session-edit-btn");return s&&s.addEventListener("click",i=>{i.stopPropagation(),ue(e.name,s,{sessionPath:n})}),t}function mt(e){d.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';const n=e.recent||[],t=document.createElement("div");t.className="sidebar-section-label"+(O?" clickable":""),t.textContent=O?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",O&&(t.title="Back to hub",t.addEventListener("click",()=>{window.location.href="/"})),d.appendChild(t),je(n,e.home);const s=e.agents||[];for(const o of s){if(!o.sessions||o.sessions.length===0)continue;const a=o.agentId===h,c=document.createElement("div");c.className="sidebar-section-label machine-label"+(o.online?"":" agent-offline-label")+(!a&&o.online?" clickable":""),c.textContent=o.agentName+(o.online?"":" (offline)"),!a&&o.online&&(c.title="\u6253\u5F00 "+o.agentName,c.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(o.agentId)+"/"})),d.appendChild(c),je(o.sessions,e.home,o.agentId,o.online)}const i=e.tombstones||[];if(i.length>0){const o=document.createElement("div");o.className="sidebar-section-label tombstone-label",o.textContent="\u5931\u6548\u4F1A\u8BDD",d.appendChild(o);for(const a of i){const c=document.createElement("div");c.className="session-item session-tombstone",c.setAttribute("data-session",a.name),a.agentId&&c.setAttribute("data-agent",a.agentId);const l=a.agentId?a.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";c.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
7
- <span>${p(a.name)}</span><span class="meta">\u5931\u6548${l}</span>
8
- <button class="session-edit-btn" data-session="${p(a.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>`,c.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",c.addEventListener("click",()=>{ue(a.name,c,{tombstone:!0,agentId:a.agentId})});const r=c.querySelector(".session-edit-btn");r&&r.addEventListener("click",v=>{v.stopPropagation(),ue(a.name,r,{tombstone:!0,agentId:a.agentId})}),d.appendChild(c)}}}function p(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function F(e,n){if(u===e&&f&&h===(n||null))return;U.style.display="none",$.style.display="none",w.style.display="",w.classList.add("terminal-pending"),ne(),f&&(de(),f.destroy(),f=null),u=e,h=n||null,window.__tmuxWebScopeAgent=h,window.__tmuxWebCurrentSession=u,jt(e,n);const t=Be(e,n);et.set(t,Date.now()+Pt);const s=j.get(t);if(s&&s.state==="working"){s.state="idle",s.doneUntil=void 0,s.unread=!1;const i=d.querySelector(n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');i&&he(i,t,s)}for(const i of d.querySelectorAll(".session-item"))i.classList.toggle("active",i.getAttribute("data-session")===e&&(i.getAttribute("data-agent")||null)===h);try{f=await nt(w,e,{terminal:z.terminal,scrollback:z.scrollback,theme:z.theme,wsBase:h?"/ws/a/"+encodeURIComponent(h):z.wsBase||"/ws"}),Ke()}catch(i){console.error("[shell] terminal init failed:",i);const o=i&&typeof i=="object"&&"message"in i?i.message:String(i);w.textContent="Failed to open terminal for "+e+": "+o,w.classList.remove("terminal-pending")}}let se=[],m=null,ze=!1;function gt(e){if(!m||!m.files.length)return null;const n=m.repoRoot;if(!n||!e.startsWith(n))return null;const t=e.slice(n.length+1);for(const s of m.files)if(s.path===t)return s.status;return null}async function vt(e){ze=!0;try{const n=await fetch(g("/api/git/status?path="+encodeURIComponent(e)));n.ok?m=await n.json():m=null}catch{m=null}finally{ze=!1}}function yt(){if(!m||!m.branch)return"";const{branch:e,linesAdded:n,linesRemoved:t}=m;let s=`<div class="sidebar-git"><div class="git-branch-badge">
6
+ `,t.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||W(e.name)});const n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",s=>{s.stopPropagation(),pe(e.name,n)}),t}function ut(e){d.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';const t=e.recent||[],n=document.createElement("div");n.className="sidebar-section-label"+(z?" clickable":""),n.textContent=z?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",z&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),d.appendChild(n),De(t,e.home);const s=e.agents||[];for(const o of s){if(!o.sessions||o.sessions.length===0)continue;const a=o.agentId===h,l=document.createElement("div");l.className="sidebar-section-label machine-label"+(o.online?"":" agent-offline-label")+(!a&&o.online?" clickable":""),l.textContent=o.agentName+(o.online?"":" (offline)"),!a&&o.online&&(l.title="\u6253\u5F00 "+o.agentName,l.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(o.agentId)+"/"})),d.appendChild(l),De(o.sessions,e.home,o.agentId,o.online)}const i=e.tombstones||[];if(i.length>0){const o=document.createElement("div");o.className="sidebar-section-label tombstone-label",o.textContent="\u5931\u6548\u4F1A\u8BDD",d.appendChild(o);for(const a of i){const l=document.createElement("div");l.className="session-item session-tombstone",l.setAttribute("data-session",a.name),a.agentId&&l.setAttribute("data-agent",a.agentId);const c=a.agentId?a.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";l.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
7
+ <span>${p(a.name)}</span><span class="meta">\u5931\u6548${c}</span>
8
+ <button class="session-edit-btn" data-session="${p(a.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",()=>{pe(a.name,l,{tombstone:!0,agentId:a.agentId})});const r=l.querySelector(".session-edit-btn");r&&r.addEventListener("click",v=>{v.stopPropagation(),pe(a.name,r,{tombstone:!0,agentId:a.agentId})}),d.appendChild(l)}}}function p(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function W(e,t){if(u===e&&f&&h===(t||null))return;O.style.display="none",R.style.display="none",w.style.display="",w.classList.add("terminal-pending"),te(),f&&(re(),f.destroy(),f=null),u=e,h=t||null,window.__tmuxWebScopeAgent=h,window.__tmuxWebCurrentSession=u,Dt(e,t);const n=Se(e,t);Qe.set(n,Date.now()+At);const s=D.get(n);if(s&&s.state==="working"){s.state="idle",s.doneUntil=void 0,s.unread=!1;const i=d.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');i&&ve(i,n,s)}for(const i of d.querySelectorAll(".session-item"))i.classList.toggle("active",i.getAttribute("data-session")===e&&(i.getAttribute("data-agent")||null)===h);try{f=await tt(w,e,{terminal:j.terminal,scrollback:j.scrollback,theme:j.theme,wsBase:h?"/ws/a/"+encodeURIComponent(h):j.wsBase||"/ws"}),Je()}catch(i){console.error("[shell] terminal init failed:",i);const o=i&&typeof i=="object"&&"message"in i?i.message:String(i);w.textContent="Failed to open terminal for "+e+": "+o,w.classList.remove("terminal-pending")}}let ne=[],m=null,je=!1;function mt(e){if(!m||!m.files.length)return null;const t=m.repoRoot;if(!t||!e.startsWith(t))return null;const n=e.slice(t.length+1);for(const s of m.files)if(s.path===n)return s.status;return null}async function gt(e){je=!0;try{const t=await fetch(g("/api/git/status?path="+encodeURIComponent(e)));t.ok?m=await t.json():m=null}catch{m=null}finally{je=!1}}function vt(){if(!m||!m.branch)return"";const{branch:e,linesAdded:t,linesRemoved:n}=m;let s=`<div class="sidebar-git"><div class="git-branch-badge">
9
9
  <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>
10
- ${p(e)}</div>`;return(n>0||t>0)&&(s+=`<div class="git-diff-stats">+<span class="add">${n}</span> <span class="del">-${t}</span></div>`),s+"</div>"}d.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&A&&m&&(e.stopPropagation(),Ge())});const G=document.getElementById("header-git"),Oe=document.getElementById("git-diff-view"),Ue=document.getElementById("gd-path"),ie=document.getElementById("gd-status"),oe=document.getElementById("gd-content"),ht=document.getElementById("gd-back");let A=null;function V(e){if(!e||!e.branch){G.style.display="none",A=null;return}A=e.repoRoot;const{branch:n,linesAdded:t,linesRemoved:s}=e;let i=`<span class="branch">${p(n)}</span>`;(t>0||s>0)&&(i+=`<span class="sep">\xB7</span>+<span class="diff-add">${t}</span> <span class="diff-del">-${s}</span>`),G.innerHTML=i,G.style.display="block"}G.addEventListener("click",e=>{A&&m&&(e.stopPropagation(),Ge())});const b=document.getElementById("git-popover"),ae=document.getElementById("git-popover-backdrop");function Ee(){const e=G.getBoundingClientRect();b.style.top=e.bottom+4+"px",b.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function We(){const e=A,n=document.getElementById("git-popover-browse");n&&n.addEventListener("click",()=>{if(ce(),e){be="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));const t=document.getElementById("mode-files");t&&t.classList.add("active"),M(e)}})}let Fe="";function Ge(){if(!m)return;const e=m.files||[];if(!e.length)b.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
11
- <div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let n=`<div class="git-popover-header">${e.length} file${e.length>1?"s":""} changed</div>`;for(let t=0;t<e.length;t++){const s=e[t],i=s.additions||0,o=s.deletions||0;let a="";switch(s.status){case"M":a='<span class="git-file-status M">M</span>';break;case"A":a='<span class="git-file-status A">A</span>';break;case"D":a='<span class="git-file-status D">D</span>';break;case"?":a='<span class="git-file-status ?">?</span>';break;case"R":a='<span class="git-file-status R">R</span>';break}n+=`<div class="git-popover-item" data-idx="${t}">
10
+ ${p(e)}</div>`;return(t>0||n>0)&&(s+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${n}</span></div>`),s+"</div>"}d.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&A&&m&&(e.stopPropagation(),Fe())});const F=document.getElementById("header-git"),ze=document.getElementById("git-diff-view"),Oe=document.getElementById("gd-path"),se=document.getElementById("gd-status"),ie=document.getElementById("gd-content"),yt=document.getElementById("gd-back");let A=null;function G(e){if(!e||!e.branch){F.style.display="none",A=null;return}A=e.repoRoot;const{branch:t,linesAdded:n,linesRemoved:s}=e;let i=`<span class="branch">${p(t)}</span>`;(n>0||s>0)&&(i+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${s}</span>`),F.innerHTML=i,F.style.display="block"}F.addEventListener("click",e=>{A&&m&&(e.stopPropagation(),Fe())});const b=document.getElementById("git-popover"),oe=document.getElementById("git-popover-backdrop");function we(){const e=F.getBoundingClientRect();b.style.top=e.bottom+4+"px",b.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function Ue(){const e=A,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(le(),e){ye="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));const n=document.getElementById("mode-files");n&&n.classList.add("active"),T(e)}})}let We="";function Fe(){if(!m)return;const e=m.files||[];if(!e.length)b.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
11
+ <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++){const s=e[n],i=s.additions||0,o=s.deletions||0;let a="";switch(s.status){case"M":a='<span class="git-file-status M">M</span>';break;case"A":a='<span class="git-file-status A">A</span>';break;case"D":a='<span class="git-file-status D">D</span>';break;case"?":a='<span class="git-file-status ?">?</span>';break;case"R":a='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
12
12
  ${a}<span class="file-path">${p(s.path)}</span>
13
13
  <span class="file-add">${i>0?"+"+i:""}</span>
14
14
  <span class="file-del">${o>0?"-"+o:""}</span>
15
- </div>`}n+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',Fe=n,b.innerHTML=n,b.querySelectorAll(".git-popover-item").forEach(t=>{const s=parseInt(t.dataset.idx||"0",10),i=e[s];!i||i.status==="D"||(t.classList.add("clickable"),t.style.cursor="pointer",t.addEventListener("click",()=>qe(i.path)))})}Ee(),b.classList.add("open"),ae.classList.add("open"),We()}function bt(){return window.innerWidth>=1024}function Ve(e,n){const s=(e+(n&&e?`
16
- `:"")+n).split(`
17
- `);let i="",o=0,a=0;for(const c of s){const l=c;if(l.startsWith("@@")){const r=l.match(/@@\s+-(\d+)[^+]*\+(\d+)/);r&&(o=parseInt(r[1],10)-1,a=parseInt(r[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${p(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">${p(l)}</span></div>`);continue}if(l.startsWith("+"))a++,i+=`<div class="diff-line add"><span class="ln-no">${a}</span><span class="ln-body">${p(l)}</span></div>`;else if(l.startsWith("-"))o++,i+=`<div class="diff-line del"><span class="ln-no">${o}</span><span class="ln-body">${p(l)}</span></div>`;else if(l.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${p(l)}</span></div>`;else{if(!l&&!o&&!a)continue;o++,a++,i+=`<div class="diff-line"><span class="ln-no">${o}</span><span class="ln-no" style="margin-right:12px">${a}</span><span class="ln-body">${p(l)}</span></div>`}}return{html:i,lineCount:s.length}}let le=null;async function qe(e){const n=A;if(n)if(ce(),bt()){w.style.display="none",f&&(de(),f.destroy(),f=null,le=u,u=null),V(null),U.style.display="none",$.style.display="none",Oe.style.display="flex",Ue.textContent=e,ie.textContent="Loading\u2026",oe.innerHTML="";try{const t=await fetch(g("/api/git/diff?path="+encodeURIComponent(n)+"&file="+encodeURIComponent(e)));if(!t.ok)throw new Error(await t.text());const s=await t.json();Lt(e,s.diff,s.stagedDiff)}catch(t){const s=t instanceof Error?t.message:String(t);ie.textContent="Error",oe.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${p(s)}</div>`}}else{b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
15
+ </div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',We=t,b.innerHTML=t,b.querySelectorAll(".git-popover-item").forEach(n=>{const s=parseInt(n.dataset.idx||"0",10),i=e[s];!i||i.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>Ve(i.path)))})}we(),b.classList.add("open"),oe.classList.add("open"),Ue()}function ht(){return window.innerWidth>=1024}function Ge(e,t){const s=(e+(t&&e?`
16
+ `:"")+t).split(`
17
+ `);let i="",o=0,a=0;for(const l of s){const c=l;if(c.startsWith("@@")){const r=c.match(/@@\s+-(\d+)[^+]*\+(\d+)/);r&&(o=parseInt(r[1],10)-1,a=parseInt(r[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${p(c)}</span></div>`;continue}if(c.startsWith("diff --git")||c.startsWith("index ")||c.startsWith("--- ")||c.startsWith("+++ ")||c.startsWith("new file")||c.startsWith("deleted file")){c.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${p(c)}</span></div>`);continue}if(c.startsWith("+"))a++,i+=`<div class="diff-line add"><span class="ln-no">${a}</span><span class="ln-body">${p(c)}</span></div>`;else if(c.startsWith("-"))o++,i+=`<div class="diff-line del"><span class="ln-no">${o}</span><span class="ln-body">${p(c)}</span></div>`;else if(c.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${p(c)}</span></div>`;else{if(!c&&!o&&!a)continue;o++,a++,i+=`<div class="diff-line"><span class="ln-no">${o}</span><span class="ln-no" style="margin-right:12px">${a}</span><span class="ln-body">${p(c)}</span></div>`}}return{html:i,lineCount:s.length}}let ae=null;async function Ve(e){const t=A;if(t)if(le(),ht()){w.style.display="none",f&&(re(),f.destroy(),f=null,ae=u,u=null),G(null),O.style.display="none",R.style.display="none",ze.style.display="flex",Oe.textContent=e,se.textContent="Loading\u2026",ie.innerHTML="";try{const n=await fetch(g("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());const s=await n.json();wt(e,s.diff,s.stagedDiff)}catch(n){const s=n instanceof Error?n.message:String(n);se.textContent="Error",ie.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${p(s)}</div>`}}else{b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
18
18
  <button class="diff-back">\u2190 Back</button>
19
19
  <span class="diff-filename">${p(e)}</span>
20
20
  <span class="diff-loading">Loading\u2026</span>
21
- </div></div>`,Ee(),b.classList.add("open"),ae.classList.add("open");try{const t=await fetch(g("/api/git/diff?path="+encodeURIComponent(n)+"&file="+encodeURIComponent(e)));if(!t.ok)throw new Error(await t.text());const s=await t.json();wt(e,s.diff,s.stagedDiff)}catch(t){const s=t instanceof Error?t.message:String(t);b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
21
+ </div></div>`,we(),b.classList.add("open"),oe.classList.add("open");try{const n=await fetch(g("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());const s=await n.json();bt(e,s.diff,s.stagedDiff)}catch(n){const s=n instanceof Error?n.message:String(n);b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
22
22
  <button class="diff-back">\u2190 Back</button>
23
23
  <span class="diff-filename">${p(e)}</span>
24
- </div><div class="diff-empty">Error loading diff: ${p(s)}</div></div>`}}}function wt(e,n,t){if(!n&&!t){b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
24
+ </div><div class="diff-empty">Error loading diff: ${p(s)}</div></div>`}}}function bt(e,t,n){if(!t&&!n){b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
25
25
  <button class="diff-back">\u2190 Back</button>
26
26
  <span class="diff-filename">${p(e)}</span>
27
- </div><div class="diff-empty">No diff content available</div></div>`;return}const{html:s,lineCount:i}=Ve(n,t);b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
27
+ </div><div class="diff-empty">No diff content available</div></div>`;return}const{html:s,lineCount:i}=Ge(t,n);b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
28
28
  <button class="diff-back">\u2190 Back</button>
29
29
  <span class="diff-filename">${p(e)}</span>
30
30
  <span class="diff-filesize">${i} lines</span>
31
- </div><div class="diff-content">${s}</div></div>`,b.querySelector(".diff-back")?.addEventListener("click",()=>{b.innerHTML=Fe,Ee(),m&&b.querySelectorAll(".git-popover-item").forEach(o=>{const a=parseInt(o.dataset.idx||"0",10),c=m.files[a];!c||c.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>qe(c.path)))}),We()})}function Lt(e,n,t){if(!n&&!t){ie.textContent="No diff",oe.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}const{html:s,lineCount:i}=Ve(n,t);Ue.textContent=e,ie.textContent=i+" lines",oe.innerHTML=s}function Et(){Oe.style.display="none",le?(w.style.display="",w.classList.add("terminal-pending"),F(le),le=null):u?(w.style.display="",w.classList.add("terminal-pending"),Ke()):$.style.display="flex"}ht.addEventListener("click",Et);function ce(){b.classList.remove("open"),ae.classList.remove("open")}ae.addEventListener("click",ce),document.addEventListener("keydown",e=>{e.key==="Escape"&&(ce(),ye())});async function Je(e){try{const t=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(t.path){const s=await fetch("/api/git/status?path="+encodeURIComponent(t.path));if(s.ok){const i=await s.json();m=i,V(i);return}}}catch{}m=null,V(null)}let re=null;function Ke(){de(),u&&(Je(u),re=setInterval(()=>{u&&Je(u)},3e4))}function de(){re&&(clearInterval(re),re=null)}async function pe(e){let n=e;if(n.startsWith("~"))try{const s=await(await fetch(g("/api/fs/list?path="+encodeURIComponent(n)))).json();typeof s.path=="string"&&s.path&&(n=s.path)}catch{}n=n.replace(/\/+$/,"")||"/",it(n)}function Ye(e,n){const t=document.createElement("button");t.className="file-tree-bot-btn",t.textContent="+",t.title=`Create bot in ${n}`,t.setAttribute("aria-label",`Create bot in ${n}`),t.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),pe(n)}),e.appendChild(t)}function kt(){if(se=z.fsRoots||[],se.length===0){if(u){Ct(u);return}M("");return}d.innerHTML="";for(const e of se){const n=document.createElement("div");n.className="file-tree-item",n.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> ${p(e)}`,n.addEventListener("click",()=>M(e)),Ye(n,e),d.appendChild(n)}}async function Ct(e){d.innerHTML='<div class="file-tree-empty">Loading...</div>';try{const t=await(await fetch(g("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?M(t.path):d.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{d.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function M(e){x=e,d.innerHTML='<div class="file-tree-empty">Loading...</div>';const n=vt(e);try{const s=await(await fetch(g("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof s.path=="string"&&s.path?s.path:e;if(i&&(x=i),await n,d.innerHTML="",i){const c=document.createElement("div");c.className="file-tree-item file-tree-create-bot",c.innerHTML='<span class="file-tree-bot-plus">+</span> Create bot in this folder',c.title=`Create bot in ${i}`,c.addEventListener("click",()=>void pe(i)),d.appendChild(c)}V(m),d.innerHTML+=yt();const o=St(i||e);if(o&&!se.some(l=>i===l)){const l=document.createElement("div");l.className="file-tree-item",l.innerHTML="..",l.addEventListener("click",()=>M(o)),d.appendChild(l)}if(s.dirs)for(const c of s.dirs){const l=c.split("/").pop()||c.split("\\").pop(),r=document.createElement("div");r.className="file-tree-item",r.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> ${p(l)}`,r.addEventListener("click",()=>M(c)),Ye(r,c),d.appendChild(r)}else d.innerHTML="";const a=s.files||[];for(const c of a){const l=c.split("/").pop()||c.split("\\").pop(),r=gt(c);let v="",H="";if(r)switch(r){case"M":v="git-mod",H='<span class="git-file-status M">M</span>';break;case"A":v="git-add",H='<span class="git-file-status A">A</span>';break;case"D":v="git-del",H='<span class="git-file-status D">D</span>';break;case"?":v="git-untracked",H='<span class="git-file-status ?">?</span>';break;case"R":v="git-mod",H='<span class="git-file-status R">R</span>';break}const R=document.createElement("div");R.className="file-tree-item file"+(v?" "+v:""),R.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${H}${p(l)}`,R.addEventListener("click",()=>Bt(c)),d.appendChild(R)}}catch{d.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function St(e){const n=e.lastIndexOf("/");return n<=0?null:e.substring(0,n)}async function Bt(e){Q=e,w.style.display="none",f&&(de(),f.destroy(),f=null,u=null),V(null),ne(),$.style.display="none",U.style.display="flex",ot.textContent=e,k.textContent="Loading...",_.style.display="none";try{const n=await fetch(g("/api/file?path="+encodeURIComponent(e)));if(!n.ok){const s=await n.json();k.textContent=s.error||"Failed to load",W.value="";return}const t=await n.json();W.value=t.content,ee=t.content,xe=t.content,k.textContent=t.size+" bytes",_.style.display=""}catch{k.textContent="Failed to load",W.value=""}}W.addEventListener("input",()=>{ee=W.value}),_.addEventListener("click",async()=>{_.textContent="Saving...",_.disabled=!0;try{const e=await fetch(g("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Q,content:ee})});if(!e.ok){const n=await e.json();k.textContent=n.error||"Save failed";return}xe=ee,k.textContent="Saved"}catch{k.textContent="Save failed"}finally{_.disabled=!1,_.textContent="Save"}}),at.addEventListener("click",async()=>{if(confirm("Delete "+Q+"?"))try{const e=await fetch(g("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Q})});if(!e.ok){const n=await e.json();k.textContent=n.error||"Delete failed";return}U.style.display="none",$.style.display="flex",x&&M(x)}catch{k.textContent="Delete failed"}}),lt.addEventListener("click",()=>{U.style.display="none",$.style.display="flex",x&&M(x)}),ct.addEventListener("click",async()=>{const e=Te.value.trim();if(!e)return;const n=x+"/"+e;try{const t=await fetch(g("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n})});if(!t.ok){const s=await t.json();k.textContent=s.error||"Create failed";return}Te.value="",x&&M(x)}catch{k.textContent="Create failed"}});const fe=document.getElementById("force-narrow-toggle");fe&&(fe.checked=te(),fe.addEventListener("change",()=>{try{localStorage.setItem(Ne,fe.checked?"1":"0")}catch{}Re(),T()})),Re(),document.getElementById("mode-settings").addEventListener("click",()=>{const e=Me.classList.toggle("open");we.classList.toggle("open",e)}),we.addEventListener("click",()=>{Me.classList.remove("open"),we.classList.remove("open")});let L="",S=!1,E;const q=document.createElement("div");q.className="session-popover-backdrop",document.body.appendChild(q);const C=document.createElement("div");C.id="session-popover",C.className="session-popover",C.style.display="none",C.innerHTML=`<div class="sp-field">
31
+ </div><div class="diff-content">${s}</div></div>`,b.querySelector(".diff-back")?.addEventListener("click",()=>{b.innerHTML=We,we(),m&&b.querySelectorAll(".git-popover-item").forEach(o=>{const a=parseInt(o.dataset.idx||"0",10),l=m.files[a];!l||l.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>Ve(l.path)))}),Ue()})}function wt(e,t,n){if(!t&&!n){se.textContent="No diff",ie.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}const{html:s,lineCount:i}=Ge(t,n);Oe.textContent=e,se.textContent=i+" lines",ie.innerHTML=s}function Lt(){ze.style.display="none",ae?(w.style.display="",w.classList.add("terminal-pending"),W(ae),ae=null):u?(w.style.display="",w.classList.add("terminal-pending"),Je()):R.style.display="flex"}yt.addEventListener("click",Lt);function le(){b.classList.remove("open"),oe.classList.remove("open")}oe.addEventListener("click",le),document.addEventListener("keydown",e=>{e.key==="Escape"&&(le(),ge())});async function qe(e){try{const n=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(n.path){const s=await fetch("/api/git/status?path="+encodeURIComponent(n.path));if(s.ok){const i=await s.json();m=i,G(i);return}}}catch{}m=null,G(null)}let ce=null;function Je(){re(),u&&(qe(u),ce=setInterval(()=>{u&&qe(u)},3e4))}function re(){ce&&(clearInterval(ce),ce=null)}async function Le(e){let t=e;if(t.startsWith("~"))try{const s=await(await fetch(g("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof s.path=="string"&&s.path&&(t=s.path)}catch{}t=t.replace(/\/+$/,"")||"/",st(t)}function Ke(e,t){const n=document.createElement("button");n.className="file-tree-bot-btn",n.textContent="+",n.title=`Create bot in ${t}`,n.setAttribute("aria-label",`Create bot in ${t}`),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),Le(t)}),e.appendChild(n)}function Et(){if(ne=j.fsRoots||[],ne.length===0){if(u){kt(u);return}T("");return}d.innerHTML="";for(const e of ne){const 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> ${p(e)}`,t.addEventListener("click",()=>T(e)),Ke(t,e),d.appendChild(t)}}async function kt(e){d.innerHTML='<div class="file-tree-empty">Loading...</div>';try{const n=await(await fetch(g("/api/fs/session-path?session="+encodeURIComponent(e)))).json();n.path?T(n.path):d.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{d.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function T(e){I=e,d.innerHTML='<div class="file-tree-empty">Loading...</div>';const t=gt(e);try{const s=await(await fetch(g("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof s.path=="string"&&s.path?s.path:e;if(i&&(I=i),await t,d.innerHTML="",i){const l=document.createElement("div");l.className="file-tree-item file-tree-create-bot",l.innerHTML='<span class="file-tree-bot-plus">+</span> Create bot in this folder',l.title=`Create bot in ${i}`,l.addEventListener("click",()=>void Le(i)),d.appendChild(l)}G(m),d.innerHTML+=vt();const o=Ct(i||e);if(o&&!ne.some(c=>i===c)){const c=document.createElement("div");c.className="file-tree-item",c.innerHTML="..",c.addEventListener("click",()=>T(o)),d.appendChild(c)}if(s.dirs)for(const l of s.dirs){const c=l.split("/").pop()||l.split("\\").pop(),r=document.createElement("div");r.className="file-tree-item",r.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> ${p(c)}`,r.addEventListener("click",()=>T(l)),Ke(r,l),d.appendChild(r)}else d.innerHTML="";const a=s.files||[];for(const l of a){const c=l.split("/").pop()||l.split("\\").pop(),r=mt(l);let v="",H="";if(r)switch(r){case"M":v="git-mod",H='<span class="git-file-status M">M</span>';break;case"A":v="git-add",H='<span class="git-file-status A">A</span>';break;case"D":v="git-del",H='<span class="git-file-status D">D</span>';break;case"?":v="git-untracked",H='<span class="git-file-status ?">?</span>';break;case"R":v="git-mod",H='<span class="git-file-status R">R</span>';break}const N=document.createElement("div");N.className="file-tree-item file"+(v?" "+v:""),N.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${H}${p(c)}`,N.addEventListener("click",()=>St(l)),d.appendChild(N)}}catch{d.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function Ct(e){const t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function St(e){Z=e,w.style.display="none",f&&(re(),f.destroy(),f=null,u=null),G(null),te(),R.style.display="none",O.style.display="flex",it.textContent=e,E.textContent="Loading...",_.style.display="none";try{const t=await fetch(g("/api/file?path="+encodeURIComponent(e)));if(!t.ok){const s=await t.json();E.textContent=s.error||"Failed to load",U.value="";return}const n=await t.json();U.value=n.content,Q=n.content,Ie=n.content,E.textContent=n.size+" bytes",_.style.display=""}catch{E.textContent="Failed to load",U.value=""}}U.addEventListener("input",()=>{Q=U.value}),_.addEventListener("click",async()=>{_.textContent="Saving...",_.disabled=!0;try{const e=await fetch(g("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Z,content:Q})});if(!e.ok){const t=await e.json();E.textContent=t.error||"Save failed";return}Ie=Q,E.textContent="Saved"}catch{E.textContent="Save failed"}finally{_.disabled=!1,_.textContent="Save"}}),ot.addEventListener("click",async()=>{if(confirm("Delete "+Z+"?"))try{const e=await fetch(g("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Z})});if(!e.ok){const t=await e.json();E.textContent=t.error||"Delete failed";return}O.style.display="none",R.style.display="flex",I&&T(I)}catch{E.textContent="Delete failed"}}),at.addEventListener("click",()=>{O.style.display="none",R.style.display="flex",I&&T(I)}),lt.addEventListener("click",async()=>{const e=xe.value.trim();if(!e)return;const t=I+"/"+e;try{const n=await fetch(g("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){const s=await n.json();E.textContent=s.error||"Create failed";return}xe.value="",I&&T(I)}catch{E.textContent="Create failed"}});const de=document.getElementById("force-narrow-toggle");de&&(de.checked=ee(),de.addEventListener("change",()=>{try{localStorage.setItem(He,de.checked?"1":"0")}catch{}Ne(),x()})),Ne(),document.getElementById("mode-settings").addEventListener("click",()=>{const e=Te.classList.toggle("open");he.classList.toggle("open",e)}),he.addEventListener("click",()=>{Te.classList.remove("open"),he.classList.remove("open")});let L="",M=!1,k;const V=document.createElement("div");V.className="session-popover-backdrop",document.body.appendChild(V);const C=document.createElement("div");C.id="session-popover",C.className="session-popover",C.style.display="none",C.innerHTML=`<div class="sp-field">
32
32
  <label>Rename session</label>
33
33
  <input type="text" id="sp-name" />
34
34
  </div>
@@ -38,6 +38,5 @@ import{initTerminal as nt}from"./terminal-core.js";import{initBots as st,openNew
38
38
  </div>
39
39
  <hr class="sp-divider" />
40
40
  <button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>
41
- <button class="btn" id="sp-create-bot" style="display:none">\uFF0B \u5728\u6B64\u76EE\u5F55\u521B\u5EFA Bot</button>
42
- <button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(C);function It(e){const n=e.getBoundingClientRect(),t=window.innerHeight,s=C.offsetHeight||240;let i=n.bottom+4;i+s>t-8&&(i=Math.max(8,n.top-s-4)),C.style.top=i+"px",C.style.left=Math.max(8,Math.min(n.left,window.innerWidth-240))+"px"}let P="";function ue(e,n,t){L=e,S=!!t?.tombstone,E=t?.agentId,P=t?.sessionPath||"";const s=document.getElementById("sp-name");s.value=e;const i=C.querySelector(".sp-field label");i.textContent=S?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const o=document.getElementById("sp-rebuild");o.style.display=S?"":"none";const a=document.getElementById("sp-delete");a.textContent=S?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";const c=document.getElementById("sp-save");c.textContent=S?"\u91CD\u547D\u540D":"Save";const l=document.getElementById("sp-create-bot");l.style.display=!S&&!E&&P?"":"none",l.title=P?`Create bot in ${P}`:"",q.classList.add("open"),C.style.display="block",It(n),setTimeout(()=>s.focus(),50)}function N(){q.classList.remove("open"),C.style.display="none"}q.addEventListener("click",N),document.getElementById("sp-create-bot").addEventListener("click",()=>{if(!P)return;const e=P;N(),pe(e)}),document.getElementById("sp-save").addEventListener("click",async()=>{const e=document.getElementById("sp-name").value.trim();if(!e||e===L){N();return}try{const n=S?{oldName:L,newName:e,agentId:E}:{oldName:L,newName:e,...E?{agentId:E}:{}};if(!(await fetch(g(S?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).ok)return;N(),T(),!S&&u===L&&(E??null)===h&&F(e,E)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+L+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{const e=await fetch(g("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:E})});if(!e.ok){const n=await e.json();alert(n.error||"\u91CD\u5EFA\u5931\u8D25");return}N(),T()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(S){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+L+'"\uFF1F'))return;try{if(!(await fetch(g("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:E})})).ok)return;N(),T()}catch{}return}if(confirm('Delete session "'+L+'"?'))try{if(!(await fetch(g("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,...E?{agentId:E}:{}})})).ok)return;N(),u===L&&(E??null)===h&&(f&&(f.destroy(),f=null),u=null,w.style.display="none",$.style.display="flex"),T()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",N);const Xe={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"},me=document.getElementById("mobile-keys"),xt=new Set(["up","down","left","right","tab","s-tab","space"]),Tt=400,Mt=80;let J=0,ge=0,ve=!1;function Ht(){J&&(clearTimeout(J),J=0),ge&&(clearInterval(ge),ge=0)}me.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),me.addEventListener("pointerdown",e=>{const n=e.target.closest("button[data-key]");if(!n)return;const t=n.dataset.key;xt.has(t)&&(ve=!1,J=setTimeout(()=>{J=0,ve=!0,ge=setInterval(()=>{const s=Xe[t];s&&f&&f.sendInput(s)},Mt)},Tt))});for(const e of["pointerup","pointercancel","pointerleave"])me.addEventListener(e,Ht);me.addEventListener("click",e=>{const n=e.target.closest("button[data-key]");if(!n||!f)return;if(ve){ve=!1;return}const t=Xe[n.dataset.key];t&&(f.sendInput(t),f.focus())});const B=document.getElementById("mk-input"),Ze=document.getElementById("mk-send");function Qe(){if(!B||!f)return;const e=B.value;e&&(f.sendInput(e+"\r"),B.value="",B.rows=1,f.focus())}if(B&&(B.addEventListener("input",()=>{B.rows=1;const e=B.value.split(`
43
- `).length;B.rows=Math.min(e,4)}),B.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Qe())})),Ze&&Ze.addEventListener("click",Qe),window.visualViewport){const e=document.querySelector(".app-layout"),n=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",n),window.addEventListener("orientationchange",()=>setTimeout(n,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}const ke=document.getElementById("process-panel"),K=document.getElementById("proc-list"),Nt=document.getElementById("proc-close"),Ce=document.getElementById("proc-backdrop"),Rt=document.getElementById("header-ram");function $t(){K.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(g("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){K.innerHTML='<div class="proc-empty">No processes</div>';return}let n="";for(const t of e){const s=t.rss,i=s<1048576?(s/1024).toFixed(0)+"K":(s/1048576).toFixed(1)+"M";n+='<div class="proc-row" data-pid="'+t.pid+'"><span class="proc-mem">'+t.mem+'%</span><span class="proc-rss">'+i+'</span><span class="proc-cmd" title="'+p(t.command)+'">'+p(t.command)+'</span><button class="proc-kill" title="Kill PID '+t.pid+'">&times;</button></div>'}K.innerHTML=n;for(const t of K.querySelectorAll(".proc-row")){const s=t.querySelector(".proc-kill");s&&s.addEventListener("click",i=>{const o=i.target.closest(".proc-row");!o||!confirm("Kill PID "+o.dataset.pid+"?")||fetch(g("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(o.dataset.pid,10)})}).then(a=>a.json()).then(a=>{a.ok?o.style.opacity="0.3":alert("Failed: "+(a.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{K.innerHTML='<div class="proc-empty">Failed to load</div>'})}function _t(){ke.classList.add("open"),Ce.classList.add("open"),$t()}function ye(){ke.classList.remove("open"),Ce.classList.remove("open")}Rt.addEventListener("click",e=>{e.stopPropagation(),ke.classList.contains("open")?ye():_t()}),Nt.addEventListener("click",ye),Ce.addEventListener("click",ye);const At=2e3;let Y=null,Se=null;const D=new Map,j=new Map,Pt=5e3,et=new Map;function Be(e,n){return(n?"a:"+n+":":"l:")+e}function Dt(e,n,t){const s=Be(e,n);if(t==="working"){const r=et.get(s);if(r&&Date.now()<r)return}const i=j.get(s),o=e===u&&(n??null)===h,a=t==="idle"&&i?.state==="working";j.set(s,{session:e,agentId:n,state:t,doneUntil:a?Date.now()+At:void 0,unread:a?!o:!1});const c=n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',l=d.querySelector(c);l&&he(l,s,j.get(s))}function he(e,n,t){const s=D.get(n);s&&(clearTimeout(s),D.delete(n)),e.classList.remove("working","just-done");const i=t.session===u&&(t.agentId??null)===h;t.state==="working"?e.classList.add("working"):i&&t.doneUntil&&Date.now()<t.doneUntil?(e.classList.add("just-done"),D.set(n,setTimeout(()=>{e.classList.remove("just-done"),D.delete(n)},Math.max(0,t.doneUntil-Date.now())))):!i&&t.unread&&e.classList.add("just-done")}function Ie(){for(const[e,n]of j){const t=n.agentId?'.session-item[data-agent="'+CSS.escape(n.agentId)+'"][data-session="'+CSS.escape(n.session)+'"]':'.session-item[data-session="'+CSS.escape(n.session)+'"]:not([data-agent])',s=d.querySelector(t);s&&he(s,e,n)}}function jt(e,n){const t=Be(e,n),s=j.get(t);if(!s)return;const i=D.get(t);i&&(clearTimeout(i),D.delete(t)),s.doneUntil=void 0,s.unread=!1;const o=n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',a=d.querySelector(o);a&&he(a,t,s)}function tt(){if(Y||Se)return;const e=localStorage.getItem("tmux-web-token");let t=(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws/activity";e&&(t+="?token="+encodeURIComponent(e));try{const s=new WebSocket(t);Y=s,s.onmessage=i=>{try{const o=JSON.parse(String(i.data));o&&o.type==="session.activity"&&typeof o.session=="string"&&Dt(o.session,o.agentId||void 0,o.state==="working"?"working":"idle")}catch{}},s.onclose=()=>{Y===s&&(Y=null,Se=setTimeout(()=>{Se=null,tt()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{Y=null}}window.__openSession=F,window.__refreshSidebar=T,T(),ne(),Ie(),tt(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Ie()}),setInterval(()=>{document.visibilityState==="visible"&&T()},1e4),st();
41
+ <button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(C);function Bt(e){const t=e.getBoundingClientRect(),n=window.innerHeight,s=C.offsetHeight||240;let i=t.bottom+4;i+s>n-8&&(i=Math.max(8,t.top-s-4)),C.style.top=i+"px",C.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}let Ot="";function pe(e,t,n){L=e,M=!!n?.tombstone,k=n?.agentId;const s=document.getElementById("sp-name");s.value=e;const i=C.querySelector(".sp-field label");i.textContent=M?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const o=document.getElementById("sp-rebuild");o.style.display=M?"":"none";const a=document.getElementById("sp-delete");a.textContent=M?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";const l=document.getElementById("sp-save");l.textContent=M?"\u91CD\u547D\u540D":"Save",V.classList.add("open"),C.style.display="block",Bt(t),setTimeout(()=>s.focus(),50)}function $(){V.classList.remove("open"),C.style.display="none"}V.addEventListener("click",$),document.getElementById("sp-save").addEventListener("click",async()=>{const e=document.getElementById("sp-name").value.trim();if(!e||e===L){$();return}try{const t=M?{oldName:L,newName:e,agentId:k}:{oldName:L,newName:e,...k?{agentId:k}:{}};if(!(await fetch(g(M?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;$(),x(),!M&&u===L&&(k??null)===h&&W(e,k)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+L+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{const e=await fetch(g("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:k})});if(!e.ok){const t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}$(),x()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(M){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+L+'"\uFF1F'))return;try{if(!(await fetch(g("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:k})})).ok)return;$(),x()}catch{}return}if(confirm('Delete session "'+L+'"?'))try{if(!(await fetch(g("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,...k?{agentId:k}:{}})})).ok)return;$(),u===L&&(k??null)===h&&(f&&(f.destroy(),f=null),u=null,w.style.display="none",R.style.display="flex"),x()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",$);const Ye={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"},fe=document.getElementById("mobile-keys"),It=new Set(["up","down","left","right","tab","s-tab","space"]),xt=400,Tt=80;let q=0,ue=0,me=!1;function Mt(){q&&(clearTimeout(q),q=0),ue&&(clearInterval(ue),ue=0)}fe.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),fe.addEventListener("pointerdown",e=>{const t=e.target.closest("button[data-key]");if(!t)return;const n=t.dataset.key;It.has(n)&&(me=!1,q=setTimeout(()=>{q=0,me=!0,ue=setInterval(()=>{const s=Ye[n];s&&f&&f.sendInput(s)},Tt)},xt))});for(const e of["pointerup","pointercancel","pointerleave"])fe.addEventListener(e,Mt);fe.addEventListener("click",e=>{const t=e.target.closest("button[data-key]");if(!t||!f)return;if(me){me=!1;return}const n=Ye[t.dataset.key];n&&(f.sendInput(n),f.focus())});const S=document.getElementById("mk-input"),Xe=document.getElementById("mk-send");function Ze(){if(!S||!f)return;const e=S.value;e&&(f.sendInput(e+"\r"),S.value="",S.rows=1,f.focus())}if(S&&(S.addEventListener("input",()=>{S.rows=1;const e=S.value.split(`
42
+ `).length;S.rows=Math.min(e,4)}),S.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Ze())})),Xe&&Xe.addEventListener("click",Ze),window.visualViewport){const 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})}const Ee=document.getElementById("process-panel"),J=document.getElementById("proc-list"),Ht=document.getElementById("proc-close"),ke=document.getElementById("proc-backdrop"),Nt=document.getElementById("header-ram");function Rt(){J.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(g("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){J.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(const n of e){const s=n.rss,i=s<1048576?(s/1024).toFixed(0)+"K":(s/1048576).toFixed(1)+"M";t+='<div class="proc-row" data-pid="'+n.pid+'"><span class="proc-mem">'+n.mem+'%</span><span class="proc-rss">'+i+'</span><span class="proc-cmd" title="'+p(n.command)+'">'+p(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">&times;</button></div>'}J.innerHTML=t;for(const n of J.querySelectorAll(".proc-row")){const s=n.querySelector(".proc-kill");s&&s.addEventListener("click",i=>{const o=i.target.closest(".proc-row");!o||!confirm("Kill PID "+o.dataset.pid+"?")||fetch(g("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(o.dataset.pid,10)})}).then(a=>a.json()).then(a=>{a.ok?o.style.opacity="0.3":alert("Failed: "+(a.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{J.innerHTML='<div class="proc-empty">Failed to load</div>'})}function _t(){Ee.classList.add("open"),ke.classList.add("open"),Rt()}function ge(){Ee.classList.remove("open"),ke.classList.remove("open")}Nt.addEventListener("click",e=>{e.stopPropagation(),Ee.classList.contains("open")?ge():_t()}),Ht.addEventListener("click",ge),ke.addEventListener("click",ge);const $t=2e3;let K=null,Ce=null;const P=new Map,D=new Map,At=5e3,Qe=new Map;function Se(e,t){return(t?"a:"+t+":":"l:")+e}function Pt(e,t,n){const s=Se(e,t);if(n==="working"){const r=Qe.get(s);if(r&&Date.now()<r)return}const i=D.get(s),o=e===u&&(t??null)===h,a=n==="idle"&&i?.state==="working";D.set(s,{session:e,agentId:t,state:n,doneUntil:a?Date.now()+$t:void 0,unread:a?!o:!1});const l=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',c=d.querySelector(l);c&&ve(c,s,D.get(s))}function ve(e,t,n){const s=P.get(t);s&&(clearTimeout(s),P.delete(t)),e.classList.remove("working","just-done");const i=n.session===u&&(n.agentId??null)===h;n.state==="working"?e.classList.add("working"):i&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),P.set(t,setTimeout(()=>{e.classList.remove("just-done"),P.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!i&&n.unread&&e.classList.add("just-done")}function Be(){for(const[e,t]of D){const 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])',s=d.querySelector(n);s&&ve(s,e,t)}}function Dt(e,t){const n=Se(e,t),s=D.get(n);if(!s)return;const i=P.get(n);i&&(clearTimeout(i),P.delete(n)),s.doneUntil=void 0,s.unread=!1;const o=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',a=d.querySelector(o);a&&ve(a,n,s)}function et(){if(K||Ce)return;const e=localStorage.getItem("tmux-web-token");let n=(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws/activity";e&&(n+="?token="+encodeURIComponent(e));try{const s=new WebSocket(n);K=s,s.onmessage=i=>{try{const o=JSON.parse(String(i.data));o&&o.type==="session.activity"&&typeof o.session=="string"&&Pt(o.session,o.agentId||void 0,o.state==="working"?"working":"idle")}catch{}},s.onclose=()=>{K===s&&(K=null,Ce=setTimeout(()=>{Ce=null,et()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{K=null}}window.__openSession=W,window.__refreshSidebar=x,x(),te(),Be(),et(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Be()}),setInterval(()=>{document.visibilityState==="visible"&&x()},1e4),nt();
@@ -1,3 +1,4 @@
1
- import{execFileSync as y}from"node:child_process";import{mkdirSync as d,readFileSync as S,rmSync as E,writeFileSync as v}from"node:fs";import p from"node:path";import w from"node:os";import{getBotStore as _}from"./store.js";import{materialize as T}from"./materialize.js";import{PiRpc as x}from"./rpc.js";import{buildCatalog as A,ORCHESTRATION_TOOLS as O,READONLY_TOOLS as B}from"./catalog.js";import{TERMINAL_STATUSES as h}from"./types.js";const f=4,I=8;class j{store=_();token;apiBase;runtimes=new Map;sockets=new Map;listeners=new Set;approvals=new Map;recent=new Map;constructor(t){this.token=this.store.token,this.apiBase=`http://127.0.0.1:${t}/api/bots`;for(const e of this.store.listInstances())!h.includes(e.status)&&e.status!=="queued"&&(e.status="stale",this.store.saveInstance(e))}listTemplates(){return this.store.listTemplates()}getTemplate(t){return this.store.getTemplate(t)}saveTemplate(t){return this.store.saveTemplate(t)}deleteTemplate(t){return this.store.deleteTemplate(t)}catalog(){return A()}listBots(t={}){return this.store.listInstances().filter(s=>!(t.project&&s.projectPath!==t.project||t.parentBotId&&s.parentBotId!==t.parentBotId||t.status&&s.status!==t.status))}getBot(t){return this.store.getInstance(t)}children(t){return this.store.listInstances().filter(e=>e.parentBotId===t)}createInstance(t){const e=this.getTemplate(t.templateId);if(!e)throw new Error(`unknown template: ${t.templateId}`);let s=null;if(t.parentBotId){if(s=this.getBot(t.parentBotId),!s)throw new Error("parent bot not found");if(s.depth+1>f)throw new Error(`nesting depth limit is ${f}`)}let n=t.projectPath||s?.projectPath||process.env.HOME||"/";n==="~"?n=w.homedir():n.startsWith("~/")&&(n=p.join(w.homedir(),n.slice(2)));const r=p.resolve(n),o=this.store.newId(),i=t.isolation||"shared";let a=r;if(i==="worktree"){const m=p.join(this.store.root,"worktrees",o);try{d(p.dirname(m),{recursive:!0,mode:448}),y("git",["-C",r,"worktree","add","-b",`tw-bot/${o.slice(0,8)}`,m],{timeout:2e4,stdio:"ignore"}),a=m}catch{a=r}}const c=new Date().toISOString(),u={id:o,templateId:e.id,title:t.title||e.manifest.name,projectPath:r,workspacePath:a,isolation:i,parentBotId:s?.id,depth:s?s.depth+1:0,runtimeMode:t.runtimeMode||e.manifest.permissions?.runtimeMode||"supervised",projectResources:e.manifest.projectResources||"ignore",status:"queued",sessionFile:p.join(this.store.sessionsDir(o),`${o}.jsonl`),createdAt:c,updatedAt:c,model:e.manifest.model};return d(this.store.sessionsDir(o),{recursive:!0,mode:448}),this.store.saveInstance(u),this.emit(u.id,{type:"status",status:"queued",at:c}),this.pump(),u}activeInProject(t){return this.store.listInstances().filter(e=>e.projectPath===t&&!h.includes(e.status)&&e.status!=="queued").length}pump(){for(const t of this.store.listInstances())t.status==="queued"&&(this.activeInProject(t.projectPath)>=I||this.start(t))}start(t){const e=this.getTemplate(t.templateId);if(!e){this.setStatus(t.id,"failed","template disappeared");return}const s=T(e,t,{apiBase:this.apiBase,token:this.token}),n=e.manifest.binaryPath||"pi",r=new x({command:n,args:s.args,cwd:t.workspacePath,env:s.env,onEvent:o=>this.handleEvent(t.id,o),onStderr:o=>{/error|failed/i.test(o)&&this.emit(t.id,{type:"notice",level:"warn",text:o.slice(0,500),at:new Date().toISOString()})},onExit:()=>{this.runtimes.delete(t.id);const o=this.store.getInstance(t.id);o&&!h.includes(o.status)&&this.setStatus(t.id,"failed","pi exited unexpectedly"),this.pump()}});this.runtimes.set(t.id,r),t.status="starting",t.pid=void 0,this.store.saveInstance(t),this.emit(t.id,{type:"status",status:"starting",at:new Date().toISOString()}),r.start()}handleEvent(t,e){const s=String(e.type||""),n=new Date().toISOString();switch(s){case"agent_start":this.setStatus(t,"running");break;case"agent_end":break;case"agent_settled":this.setStatus(t,e.aborted===!0?"cancelled":"completed");break;case"message_start":case"message_end":{const r=e.message;if(r){if(s==="message_end"&&r.role==="assistant"){const o=this.store.getInstance(t),i=M(r);o&&i&&(o.lastText=i,this.store.saveInstance(o))}this.emit(t,{type:"message",message:r,at:n})}break}case"message_update":{const r=e.assistantMessageEvent;if(!r)break;const o=r.type==="text_delta"?"text":r.type==="thinking_delta"?"thinking":r.type==="toolcall_delta"?"tool-args":null;if(!o)break;const i=e.message;this.emit(t,{type:"delta",kind:o,delta:String(r.delta||""),contentIndex:typeof r.contentIndex=="number"?r.contentIndex:void 0,messageId:typeof i?.id=="string"?i.id:void 0,at:n});break}case"tool_execution_start":this.emit(t,{type:"tool",phase:"start",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),args:e.args,at:n});break;case"tool_execution_update":this.emit(t,{type:"tool",phase:"update",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:k(e.partialResult),at:n});break;case"tool_execution_end":this.emit(t,{type:"tool",phase:"end",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:k(e.result),isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,at:n});break;case"extension_ui_request":this.handleUiRequest(t,e);break;default:break}}handleUiRequest(t,e){const s=String(e.method||""),n=new Date().toISOString(),r=this.store.getInstance(t);if(s==="notify"){this.emit(t,{type:"notice",level:e.notifyType==="error"?"error":e.notifyType==="warning"?"warn":"info",text:String(e.message||""),at:n});return}if(!["confirm","select","input","editor"].includes(s))return;const o=String(e.id||""),i=o?this.approvals.get(t)?.get(o):void 0;if(i&&i.state==="pending")return;const a=String(e.title||"Approval required"),c=/^Allow (.+?)\?$/.exec(a),u={id:String(e.id||""),botId:t,botTitle:r?.title||t,kind:s==="confirm"?"tool":"question",method:s,title:a,toolName:c?c[1]:void 0,message:typeof e.message=="string"?e.message:void 0,options:Array.isArray(e.options)?e.options.map(String):void 0,state:"pending",createdAt:n};this.approvals.has(t)||this.approvals.set(t,new Map),this.approvals.get(t).set(u.id,u),this.setStatus(t,"waiting_approval"),this.emit(t,{type:"approval",approval:u,at:n})}allowTool(t,e){if(!this.store.getInstance(t))throw new Error("bot not found");const n=p.join(this.store.agentDir(t),".allowed-tools");let r=[];try{r=JSON.parse(S(n,"utf8")),Array.isArray(r)||(r=[])}catch{r=[]}return r.includes(e)||r.push(e),d(p.dirname(n),{recursive:!0,mode:448}),v(n,`${JSON.stringify(r)}
2
- `,{mode:384}),r}allowedTools(t){try{const e=JSON.parse(S(p.join(this.store.agentDir(t),".allowed-tools"),"utf8"));return Array.isArray(e)?e.map(String):[]}catch{return[]}}setRuntimeMode(t,e){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");s.runtimeMode=e,this.store.saveInstance(s);const n=p.join(this.store.agentDir(t),".runtime-mode");d(p.dirname(n),{recursive:!0,mode:448}),v(n,`${e}
3
- `,{mode:384}),this.emit(t,{type:"notice",level:"info",text:`Approval mode: ${e}`,at:new Date().toISOString()})}respondApproval(t,e,s,n,r="human",o=!1){const i=this.approvals.get(t)?.get(e);if(!i)throw new Error("approval not found");const a=this.runtimes.get(t);if(!a)throw new Error("bot is not running");const c={type:"extension_ui_response",id:e};i.method==="confirm"?c.confirmed=s:i.method==="select"?c.value=s?i.options?.[0]:i.options?.[1]||i.options?.[0]:s?c.value=n||"":c.cancelled=!0,a.send(c),s&&o&&i.toolName&&this.allowTool(t,i.toolName),i.state=s?"allowed":"denied",i.decidedBy=r,i.reason=n,i.decidedAt=new Date().toISOString();try{this.store.appendEvent(t,{type:"approval",approval:i,at:i.decidedAt})}catch{}return this.broadcast(t,{type:"approval",approval:i,at:i.decidedAt}),this.setStatus(t,"running"),i}listApprovals(){const t=[];for(const[,e]of this.approvals)for(const s of e.values())s.state==="pending"&&t.push(s);return t.sort((e,s)=>e.createdAt.localeCompare(s.createdAt))}async input(t,e,s){const n=this.store.getInstance(t);if(!n)throw new Error("bot not found");if(!this.runtimes.has(t)){this.resume(t);const a=Date.now()+2e4;for(;!this.runtimes.has(t)&&Date.now()<a;)await new Promise(c=>setTimeout(c,150))}const r=this.runtimes.get(t);if(!r)throw new Error("bot is not running");const o=new Date().toISOString();this.emit(t,{type:"user",text:e,at:o});const i={type:"prompt",message:e};s==="steer"&&(i.streamingBehavior="steer"),s==="follow_up"&&(i.streamingBehavior="followUp"),!i.streamingBehavior&&(n.status==="running"||n.status==="waiting_approval")&&(i.streamingBehavior="steer");try{await r.request(i,2e4)}catch(a){const c=a instanceof Error?a.message:String(a);if(!i.streamingBehavior&&/streaming/i.test(c)){await r.request({...i,streamingBehavior:"steer"},2e4);return}throw a}}stop(t,e=!0){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");if(e)for(const n of this.children(t))this.stop(n.id,!0);try{this.runtimes.get(t)?.kill()}catch{}this.runtimes.delete(t),h.includes(s.status)||this.setStatus(t,"cancelled"),this.pump()}resume(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");this.runtimes.has(t)||(e.status="queued",this.store.saveInstance(e),this.emit(t,{type:"status",status:"queued",at:new Date().toISOString()}),this.pump())}deleteBot(t,e=!0){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");if(e)for(const n of this.children(t))this.deleteBot(n.id,!0);try{this.runtimes.get(t)?.kill()}catch{}if(this.runtimes.delete(t),this.store.deleteInstance(t),this.approvals.delete(t),this.recent.delete(t),s.isolation==="worktree"){try{y("git",["-C",s.projectPath,"worktree","remove","--force",s.workspacePath],{timeout:2e4,stdio:"ignore"})}catch{}E(s.workspacePath,{recursive:!0,force:!0})}this.pump()}status(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");const s=[...this.approvals.get(t)?.values()||[]].filter(n=>n.state==="pending");return{...e,pendingApprovals:s.length,lastText:e.lastText?.slice(0,4e3)}}result(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");return{botId:t,status:e.status,text:e.lastText||"",title:e.title}}async waitFor(t,e=45e3){const s=Date.now()+Math.min(e,45e3),n=new Set(t);for(;Date.now()<s;){const r=[...n].filter(o=>{const i=this.store.getInstance(o);return!i||h.includes(i.status)});if(r.length)return{bots:r.map(o=>this.result(o))};await new Promise(o=>setTimeout(o,250))}return{timeout:!0,bots:t.map(r=>{const o=this.store.getInstance(r);return{botId:r,status:o?.status||"missing",title:o?.title}})}}attachSocket(t,e){this.sockets.has(t)||this.sockets.set(t,new Set),this.sockets.get(t).add(e);const s=this.store.getInstance(t);e.send(JSON.stringify({type:"snapshot",bot:s,approvals:this.listApprovals().filter(n=>n.botId===t)}));for(const n of this.store.readEvents(t,400))e.send(JSON.stringify(n));e.on("close",()=>this.sockets.get(t)?.delete(e))}broadcast(t,e){const s=JSON.stringify(e);for(const n of this.sockets.get(t)||[])if(n.readyState===1)try{n.send(s)}catch{}}emit(t,e){this.store.appendEvent(t,e);const s=this.recent.get(t)||[];s.push(e),s.length>800&&s.splice(0,s.length-800),this.recent.set(t,s),this.broadcast(t,e);for(const n of this.listeners)try{n(e)}catch{}}onEvent(t){return this.listeners.add(t),()=>this.listeners.delete(t)}setStatus(t,e,s){const n=this.store.getInstance(t);n&&(n.status=e,s&&(n.lastError=s),this.store.saveInstance(n),this.emit(t,{type:"status",status:e,at:new Date().toISOString(),error:s}),h.includes(e)&&this.pump())}}function M(l){const t=l.content;return Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&e.type==="text"?String(e.text||""):"").join("").trim():""}function k(l){if(l==null)return"";if(typeof l=="string")return l;try{return JSON.stringify(l).slice(0,4e3)}catch{return String(l)}}let g=null;function F(){if(!g){const l=Number(process.env.PORT)||21e3;g=new j(l)}return g}export{j as BotManager,I as MAX_CONCURRENT_PER_PROJECT,f as MAX_DEPTH,O as ORCHESTRATION_TOOLS,B as READONLY_TOOLS,F as getBotManager};
1
+ import{execFileSync as v}from"node:child_process";import{mkdirSync as m,readFileSync as w,rmSync as x,writeFileSync as I}from"node:fs";import p from"node:path";import k from"node:os";import{getBotStore as A}from"./store.js";import{materialize as B}from"./materialize.js";import{PiRpc as M}from"./rpc.js";import{buildCatalog as O,ORCHESTRATION_TOOLS as j,READONLY_TOOLS as D}from"./catalog.js";import{TERMINAL_STATUSES as d}from"./types.js";const f=4,E=8;class P{store=A();token;apiBase;runtimes=new Map;sockets=new Map;listeners=new Set;approvals=new Map;recent=new Map;constructor(t){this.token=this.store.token,this.apiBase=`http://127.0.0.1:${t}/api/bots`;for(const e of this.store.listInstances()){let s=!1;!d.includes(e.status)&&e.status!=="queued"&&(e.status="stale",s=!0);const n=g(e.runtimeMode);n!==e.runtimeMode&&(e.runtimeMode=n,s=!0),s&&this.store.saveInstance(e)}}listTemplates(){return this.store.listTemplates()}getTemplate(t){return this.store.getTemplate(t)}saveTemplate(t){return this.store.saveTemplate(t)}deleteTemplate(t){return this.store.deleteTemplate(t)}catalog(){return O()}listBots(t={}){return this.store.listInstances().filter(s=>!(t.project&&s.projectPath!==t.project||t.parentBotId&&s.parentBotId!==t.parentBotId||t.status&&s.status!==t.status))}getBot(t){return this.store.getInstance(t)}children(t){return this.store.listInstances().filter(e=>e.parentBotId===t)}createInstance(t){const e=this.getTemplate(t.templateId);if(!e)throw new Error(`unknown template: ${t.templateId}`);let s=null;if(t.parentBotId){if(s=this.getBot(t.parentBotId),!s)throw new Error("parent bot not found");if(s.depth+1>f)throw new Error(`nesting depth limit is ${f}`)}let n=t.projectPath||s?.projectPath||process.env.HOME||"/";n==="~"?n=k.homedir():n.startsWith("~/")&&(n=p.join(k.homedir(),n.slice(2)));const r=p.resolve(n),o=this.store.newId(),i=t.isolation||"shared";let a=r;if(i==="worktree"){const h=p.join(this.store.root,"worktrees",o);try{m(p.dirname(h),{recursive:!0,mode:448}),v("git",["-C",r,"worktree","add","-b",`tw-bot/${o.slice(0,8)}`,h],{timeout:2e4,stdio:"ignore"}),a=h}catch{a=r}}const c=new Date().toISOString(),u={id:o,templateId:e.id,title:t.title||e.manifest.name,projectPath:r,workspacePath:a,isolation:i,parentBotId:s?.id,depth:s?s.depth+1:0,runtimeMode:g(t.runtimeMode||e.manifest.permissions?.runtimeMode),projectResources:e.manifest.projectResources||"ignore",status:"queued",sessionFile:p.join(this.store.sessionsDir(o),`${o}.jsonl`),createdAt:c,updatedAt:c,model:e.manifest.model};return m(this.store.sessionsDir(o),{recursive:!0,mode:448}),this.store.saveInstance(u),this.emit(u.id,{type:"status",status:"queued",at:c}),this.pump(),u}activeInProject(t){return this.store.listInstances().filter(e=>e.projectPath===t&&!d.includes(e.status)&&e.status!=="queued").length}pump(){for(const t of this.store.listInstances())t.status==="queued"&&(this.activeInProject(t.projectPath)>=E||this.start(t))}start(t){const e=this.getTemplate(t.templateId);if(!e){this.setStatus(t.id,"failed","template disappeared");return}const s=B(e,t,{apiBase:this.apiBase,token:this.token}),n=e.manifest.binaryPath||"pi",r=new M({command:n,args:s.args,cwd:t.workspacePath,env:s.env,onEvent:o=>this.handleEvent(t.id,o),onStderr:o=>{/error|failed/i.test(o)&&this.emit(t.id,{type:"notice",level:"warn",text:o.slice(0,500),at:new Date().toISOString()})},onExit:()=>{this.runtimes.delete(t.id);const o=this.store.getInstance(t.id);o&&!d.includes(o.status)&&this.setStatus(t.id,"failed","pi exited unexpectedly"),this.pump()}});this.runtimes.set(t.id,r),t.status="starting",t.pid=void 0,this.store.saveInstance(t),this.emit(t.id,{type:"status",status:"starting",at:new Date().toISOString()}),r.start()}handleEvent(t,e){const s=String(e.type||""),n=new Date().toISOString();switch(s){case"agent_start":this.setStatus(t,"running");break;case"agent_end":break;case"agent_settled":this.setStatus(t,e.aborted===!0?"cancelled":"completed");break;case"message_start":case"message_end":{const r=e.message;if(r){if(s==="message_end"&&r.role==="assistant"){const o=this.store.getInstance(t),i=b(r);o&&i&&(o.lastText=i,this.store.saveInstance(o))}this.emit(t,{type:"message",message:r,at:n})}break}case"message_update":{const r=e.assistantMessageEvent;if(!r)break;const o=r.type==="text_delta"?"text":r.type==="thinking_delta"?"thinking":r.type==="toolcall_delta"?"tool-args":null;if(!o)break;const i=e.message;this.emit(t,{type:"delta",kind:o,delta:String(r.delta||""),contentIndex:typeof r.contentIndex=="number"?r.contentIndex:void 0,messageId:typeof i?.id=="string"?i.id:void 0,at:n});break}case"tool_execution_start":this.emit(t,{type:"tool",phase:"start",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),args:e.args,at:n});break;case"tool_execution_update":this.emit(t,{type:"tool",phase:"update",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:_(e.partialResult),at:n});break;case"tool_execution_end":this.emit(t,{type:"tool",phase:"end",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:_(e.result),isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,at:n});break;case"extension_ui_request":this.handleUiRequest(t,e);break;default:break}}handleUiRequest(t,e){const s=String(e.method||""),n=new Date().toISOString(),r=this.store.getInstance(t);if(s==="notify"){this.emit(t,{type:"notice",level:e.notifyType==="error"?"error":e.notifyType==="warning"?"warn":"info",text:String(e.message||""),at:n});return}if(!["confirm","select","input","editor"].includes(s))return;const o=String(e.id||""),i=o?this.approvals.get(t)?.get(o):void 0;if(i&&i.state==="pending")return;const a=String(e.title||"Approval required"),c=/^Allow (.+?)\?$/.exec(a),u={id:String(e.id||""),botId:t,botTitle:r?.title||t,kind:s==="confirm"?"tool":"question",method:s,title:a,toolName:c?c[1]:void 0,message:typeof e.message=="string"?e.message:void 0,options:Array.isArray(e.options)?e.options.map(String):void 0,state:"pending",createdAt:n};if(this.approvals.has(t)||this.approvals.set(t,new Map),this.approvals.get(t).set(u.id,u),r&&r.runtimeMode==="parent-supervised"&&r.parentBotId){const h=this.store.getInstance(r.parentBotId);if(h){u.escalatedTo=h.id;const S=u.message?u.message.slice(0,500):"",T=[`Child bot "${r.title}" (${r.id}) needs approval: ${u.title}`,S?`Arguments: ${S}`:"",`Decide with bot_approve({ botId: "${r.id}", requestId: "${u.id}", allow: true|false, reason: "..." }).`,"If you do nothing the user will answer it."].filter(Boolean).join(`
2
+ `);this.input(h.id,T,"steer").catch(()=>{this.emit(t,{type:"notice",level:"warn",text:"Could not reach the supervising bot; waiting for the user.",at:n})})}}this.setStatus(t,"waiting_approval"),this.emit(t,{type:"approval",approval:u,at:n})}allowTool(t,e){if(!this.store.getInstance(t))throw new Error("bot not found");const n=p.join(this.store.agentDir(t),".allowed-tools");let r=[];try{r=JSON.parse(w(n,"utf8")),Array.isArray(r)||(r=[])}catch{r=[]}return r.includes(e)||r.push(e),m(p.dirname(n),{recursive:!0,mode:448}),I(n,`${JSON.stringify(r)}
3
+ `,{mode:384}),r}allowedTools(t){try{const e=JSON.parse(w(p.join(this.store.agentDir(t),".allowed-tools"),"utf8"));return Array.isArray(e)?e.map(String):[]}catch{return[]}}setRuntimeMode(t,e){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");s.runtimeMode=g(e),this.store.saveInstance(s);const n=p.join(this.store.agentDir(t),".runtime-mode");m(p.dirname(n),{recursive:!0,mode:448}),I(n,`${s.runtimeMode}
4
+ `,{mode:384}),this.emit(t,{type:"notice",level:"info",text:`Approval mode: ${e}`,at:new Date().toISOString()})}respondApproval(t,e,s,n,r="human",o=!1){const i=this.approvals.get(t)?.get(e);if(!i)throw new Error("approval not found");const a=this.runtimes.get(t);if(!a)throw new Error("bot is not running");const c={type:"extension_ui_response",id:e};i.method==="confirm"?c.confirmed=s:i.method==="select"?c.value=s?i.options?.[0]:i.options?.[1]||i.options?.[0]:s?c.value=n||"":c.cancelled=!0,a.send(c),s&&o&&i.toolName&&this.allowTool(t,i.toolName),i.state=s?"allowed":"denied",i.decidedBy=r,i.reason=n,i.decidedAt=new Date().toISOString();try{this.store.appendEvent(t,{type:"approval",approval:i,at:i.decidedAt})}catch{}return this.broadcast(t,{type:"approval",approval:i,at:i.decidedAt}),this.setStatus(t,"running"),i}listApprovals(){const t=[];for(const[,e]of this.approvals)for(const s of e.values())s.state==="pending"&&t.push(s);return t.sort((e,s)=>e.createdAt.localeCompare(s.createdAt))}async input(t,e,s){const n=this.store.getInstance(t);if(!n)throw new Error("bot not found");if(!this.runtimes.has(t)){this.resume(t);const a=Date.now()+2e4;for(;!this.runtimes.has(t)&&Date.now()<a;)await new Promise(c=>setTimeout(c,150))}const r=this.runtimes.get(t);if(!r)throw new Error("bot is not running");const o=new Date().toISOString();this.emit(t,{type:"user",text:e,at:o});const i={type:"prompt",message:e};s==="steer"&&(i.streamingBehavior="steer"),s==="follow_up"&&(i.streamingBehavior="followUp"),!i.streamingBehavior&&(n.status==="running"||n.status==="waiting_approval")&&(i.streamingBehavior="steer");try{await r.request(i,2e4)}catch(a){const c=a instanceof Error?a.message:String(a);if(!i.streamingBehavior&&/streaming/i.test(c)){await r.request({...i,streamingBehavior:"steer"},2e4);return}throw a}}stop(t,e=!0){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");if(e)for(const n of this.children(t))this.stop(n.id,!0);try{this.runtimes.get(t)?.kill()}catch{}this.runtimes.delete(t),d.includes(s.status)||this.setStatus(t,"cancelled"),this.pump()}resume(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");this.runtimes.has(t)||(e.status="queued",this.store.saveInstance(e),this.emit(t,{type:"status",status:"queued",at:new Date().toISOString()}),this.pump())}deleteBot(t,e=!0){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");if(e)for(const n of this.children(t))this.deleteBot(n.id,!0);try{this.runtimes.get(t)?.kill()}catch{}if(this.runtimes.delete(t),this.store.deleteInstance(t),this.approvals.delete(t),this.recent.delete(t),s.isolation==="worktree"){try{v("git",["-C",s.projectPath,"worktree","remove","--force",s.workspacePath],{timeout:2e4,stdio:"ignore"})}catch{}x(s.workspacePath,{recursive:!0,force:!0})}this.pump()}status(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");const s=[...this.approvals.get(t)?.values()||[]].filter(n=>n.state==="pending");return{...e,pendingApprovals:s.length,lastText:e.lastText?.slice(0,4e3)}}result(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");return{botId:t,status:e.status,text:e.lastText||"",title:e.title}}async waitFor(t,e=45e3){const s=Date.now()+Math.min(e,45e3),n=new Set(t);for(;Date.now()<s;){const r=[...n].filter(o=>{const i=this.store.getInstance(o);return!i||d.includes(i.status)});if(r.length)return{bots:r.map(o=>this.result(o))};await new Promise(o=>setTimeout(o,250))}return{timeout:!0,bots:t.map(r=>{const o=this.store.getInstance(r);return{botId:r,status:o?.status||"missing",title:o?.title}})}}attachSocket(t,e){this.sockets.has(t)||this.sockets.set(t,new Set),this.sockets.get(t).add(e);const s=this.store.getInstance(t);e.send(JSON.stringify({type:"snapshot",bot:s,approvals:this.listApprovals().filter(n=>n.botId===t)}));for(const n of this.store.readEvents(t,400))e.send(JSON.stringify(n));e.on("close",()=>this.sockets.get(t)?.delete(e))}broadcast(t,e){const s=JSON.stringify(e);for(const n of this.sockets.get(t)||[])if(n.readyState===1)try{n.send(s)}catch{}}emit(t,e){this.store.appendEvent(t,e);const s=this.recent.get(t)||[];s.push(e),s.length>800&&s.splice(0,s.length-800),this.recent.set(t,s),this.broadcast(t,e);for(const n of this.listeners)try{n(e)}catch{}}onEvent(t){return this.listeners.add(t),()=>this.listeners.delete(t)}setStatus(t,e,s){const n=this.store.getInstance(t);n&&(n.status=e,s&&(n.lastError=s),this.store.saveInstance(n),this.emit(t,{type:"status",status:e,at:new Date().toISOString(),error:s}),d.includes(e)&&this.pump())}}function g(l){return l==="full-access"?"full-access":l==="parent-supervised"?"parent-supervised":"supervised"}function b(l){const t=l.content;return Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&e.type==="text"?String(e.text||""):"").join("").trim():""}function _(l){if(l==null)return"";if(typeof l=="string")return l;try{return JSON.stringify(l).slice(0,4e3)}catch{return String(l)}}let y=null;function H(){if(!y){const l=Number(process.env.PORT)||21e3;y=new P(l)}return y}export{P as BotManager,E as MAX_CONCURRENT_PER_PROJECT,f as MAX_DEPTH,j as ORCHESTRATION_TOOLS,D as READONLY_TOOLS,H as getBotManager};
@@ -1 +1 @@
1
- import{exportBots as m,importBots as j}from"./transfer.js";function f(s,l){const{manager:o,userAuth:u}=l,a=async(r,t)=>{const e=r.req.header("x-bots-token");return e&&e===o.token?t():u()(r,t)},c=()=>a,n=()=>u();s.get("/api/bots/catalog",n(),async r=>r.json(await o.catalog())),s.get("/api/bots/templates",n(),r=>r.json(o.listTemplates())),s.post("/api/bots/templates",n(),async r=>{const t=await r.req.json().catch(()=>null);if(!t||!t.manifest||typeof t.manifest.name!="string")return r.json({error:"manifest.name is required"},400);try{const e=o.saveTemplate({id:typeof t.id=="string"?t.id:void 0,manifest:t.manifest});return r.json(e,200)}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.get("/api/bots/export",n(),r=>{const t=m(o.store);return r.json(t,200,{"content-disposition":`attachment; filename="tmux-weblink-bots-${t.exportedAt.slice(0,10)}.json"`})}),s.post("/api/bots/import",n(),async r=>{const t=await r.req.json().catch(()=>null);if(!t)return r.json({error:"invalid bundle"},400);try{return r.json(j(o.store,t,{overwriteLibrary:t.overwriteLibrary===!0}))}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.delete("/api/bots/templates/:id",n(),r=>o.deleteTemplate(r.req.param("id"))?r.json({ok:!0}):r.json({error:"not found"},404)),s.get("/api/bots",a,r=>{const t=r.req.query("project")||void 0,e=r.req.query("parent")||void 0,i=r.req.query("status")||void 0;return r.json(o.listBots({project:t,parentBotId:e,parentOnly:!!e,status:i}))});const p=async r=>{const t=await r.req.json().catch(()=>null);if(!t||typeof t.templateId!="string")return r.json({error:"templateId is required"},400);try{const e=o.createInstance({templateId:t.templateId,title:typeof t.title=="string"?t.title:void 0,projectPath:typeof t.projectPath=="string"?t.projectPath:void 0,isolation:t.isolation==="worktree"?"worktree":"shared",parentBotId:typeof t.parentBotId=="string"?t.parentBotId:void 0,runtimeMode:t.runtimeMode});return r.json(e,201)}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}};s.post("/api/bots",n(),p),s.post("/api/bots/create",c(),p),s.post("/api/bots/list_templates",a,r=>r.json(o.listTemplates().map(t=>({id:t.id,name:t.manifest.name,description:t.manifest.description,orchestrator:!!t.manifest.orchestrator})))),s.post("/api/bots/list",a,async r=>{const t=await r.req.json().catch(()=>({})),e=t.parentBotId,i=o.listBots({parentBotId:t.parentOnly&&e?e:void 0,status:t.status});return r.json(i.map(d=>({id:d.id,title:d.title,status:d.status,projectPath:d.projectPath,parentBotId:d.parentBotId,depth:d.depth,lastText:d.lastText?.slice(0,400),updatedAt:d.updatedAt})))}),s.post("/api/bots/status",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId)return r.json({error:"botId is required"},400);try{return r.json(o.status(t.botId))}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},404)}}),s.post("/api/bots/message",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId||typeof t.text!="string")return r.json({error:"botId and text are required"},400);try{return await o.input(t.botId,t.text,t.mode==="follow_up"?"follow_up":t.mode==="steer"?"steer":void 0),r.json({ok:!0})}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/wait",a,async r=>{const t=await r.req.json().catch(()=>({}));return!Array.isArray(t.botIds)||t.botIds.length===0?r.json({error:"botIds is required"},400):r.json(await o.waitFor(t.botIds,typeof t.timeoutMs=="number"?t.timeoutMs:void 0))}),s.post("/api/bots/result",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId)return r.json({error:"botId is required"},400);try{return r.json(o.result(t.botId))}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},404)}}),s.post("/api/bots/stop",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId)return r.json({error:"botId is required"},400);try{return o.stop(t.botId,t.cascade!==!1),r.json({ok:!0})}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/approvals",a,r=>r.json(o.listApprovals())),s.post("/api/bots/approve",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId||!t.requestId)return r.json({error:"botId and requestId are required"},400);const e=r.req.header("x-bots-token")===o.token?"parent-bot":"human";if(e==="parent-bot"&&!t.reason)return r.json({error:"a reason is required when a bot approves"},400);try{return r.json(o.respondApproval(t.botId,t.requestId,t.allow===!0,t.reason,e,t.always===!0))}catch(i){return r.json({error:i instanceof Error?i.message:String(i)},400)}}),s.get("/api/bots/approvals",n(),r=>r.json(o.listApprovals())),s.get("/api/bots/:id",n(),r=>{const t=o.getBot(r.req.param("id"));return t?r.json(t):r.json({error:"not found"},404)}),s.get("/api/bots/:id/events",n(),r=>{const t=Number(r.req.query("limit"))||400;return r.json(o.store.readEvents(r.req.param("id"),t))}),s.post("/api/bots/:id/input",n(),async r=>{const t=await r.req.json().catch(()=>({}));if(typeof t.text!="string"||!t.text.trim())return r.json({error:"text is required"},400);try{return await o.input(r.req.param("id"),t.text,t.mode==="follow_up"?"follow_up":t.mode==="steer"?"steer":void 0),r.json({ok:!0})}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/:id/stop",n(),r=>{try{return o.stop(r.req.param("id"),!0),r.json({ok:!0})}catch(t){return r.json({error:t instanceof Error?t.message:String(t)},400)}}),s.post("/api/bots/:id/resume",n(),r=>{try{return o.resume(r.req.param("id")),r.json({ok:!0})}catch(t){return r.json({error:t instanceof Error?t.message:String(t)},400)}}),s.post("/api/bots/:id/approve",n(),async r=>{const t=await r.req.json().catch(()=>({}));if(!t.requestId)return r.json({error:"requestId is required"},400);try{return r.json(o.respondApproval(r.req.param("id"),t.requestId,t.allow===!0,t.reason,"human",t.always===!0))}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/:id/mode",n(),async r=>{const e=(await r.req.json().catch(()=>({}))).mode;if(e!=="supervised"&&e!=="auto-accept-edits"&&e!=="full-access")return r.json({error:"mode must be supervised, auto-accept-edits or full-access"},400);try{return o.setRuntimeMode(r.req.param("id"),e),r.json({ok:!0,mode:e})}catch(i){return r.json({error:i instanceof Error?i.message:String(i)},400)}}),s.post("/api/bots/:id/allowed-tools",n(),async r=>{const t=await r.req.json().catch(()=>({}));if(!t.tool)return r.json({error:"tool is required"},400);try{return r.json({tools:o.allowTool(r.req.param("id"),t.tool)})}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.delete("/api/bots/:id",n(),r=>{try{return o.deleteBot(r.req.param("id"),!0),r.json({ok:!0})}catch(t){return r.json({error:t instanceof Error?t.message:String(t)},400)}})}export{f as registerBotRoutes};
1
+ import{exportBots as m,importBots as j}from"./transfer.js";function f(s,l){const{manager:o,userAuth:u}=l,a=async(r,t)=>{const e=r.req.header("x-bots-token");return e&&e===o.token?t():u()(r,t)},c=()=>a,n=()=>u();s.get("/api/bots/catalog",n(),async r=>r.json(await o.catalog())),s.get("/api/bots/templates",n(),r=>r.json(o.listTemplates())),s.post("/api/bots/templates",n(),async r=>{const t=await r.req.json().catch(()=>null);if(!t||!t.manifest||typeof t.manifest.name!="string")return r.json({error:"manifest.name is required"},400);try{const e=o.saveTemplate({id:typeof t.id=="string"?t.id:void 0,manifest:t.manifest});return r.json(e,200)}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.get("/api/bots/export",n(),r=>{const t=m(o.store);return r.json(t,200,{"content-disposition":`attachment; filename="tmux-weblink-bots-${t.exportedAt.slice(0,10)}.json"`})}),s.post("/api/bots/import",n(),async r=>{const t=await r.req.json().catch(()=>null);if(!t)return r.json({error:"invalid bundle"},400);try{return r.json(j(o.store,t,{overwriteLibrary:t.overwriteLibrary===!0}))}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.delete("/api/bots/templates/:id",n(),r=>o.deleteTemplate(r.req.param("id"))?r.json({ok:!0}):r.json({error:"not found"},404)),s.get("/api/bots",a,r=>{const t=r.req.query("project")||void 0,e=r.req.query("parent")||void 0,i=r.req.query("status")||void 0;return r.json(o.listBots({project:t,parentBotId:e,parentOnly:!!e,status:i}))});const p=async r=>{const t=await r.req.json().catch(()=>null);if(!t||typeof t.templateId!="string")return r.json({error:"templateId is required"},400);try{const e=o.createInstance({templateId:t.templateId,title:typeof t.title=="string"?t.title:void 0,projectPath:typeof t.projectPath=="string"?t.projectPath:void 0,isolation:t.isolation==="worktree"?"worktree":"shared",parentBotId:typeof t.parentBotId=="string"?t.parentBotId:void 0,runtimeMode:t.runtimeMode});return r.json(e,201)}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}};s.post("/api/bots",n(),p),s.post("/api/bots/create",c(),p),s.post("/api/bots/list_templates",a,r=>r.json(o.listTemplates().map(t=>({id:t.id,name:t.manifest.name,description:t.manifest.description,orchestrator:!!t.manifest.orchestrator})))),s.post("/api/bots/list",a,async r=>{const t=await r.req.json().catch(()=>({})),e=t.parentBotId,i=o.listBots({parentBotId:t.parentOnly&&e?e:void 0,status:t.status});return r.json(i.map(d=>({id:d.id,title:d.title,status:d.status,projectPath:d.projectPath,parentBotId:d.parentBotId,depth:d.depth,lastText:d.lastText?.slice(0,400),updatedAt:d.updatedAt})))}),s.post("/api/bots/status",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId)return r.json({error:"botId is required"},400);try{return r.json(o.status(t.botId))}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},404)}}),s.post("/api/bots/message",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId||typeof t.text!="string")return r.json({error:"botId and text are required"},400);try{return await o.input(t.botId,t.text,t.mode==="follow_up"?"follow_up":t.mode==="steer"?"steer":void 0),r.json({ok:!0})}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/wait",a,async r=>{const t=await r.req.json().catch(()=>({}));return!Array.isArray(t.botIds)||t.botIds.length===0?r.json({error:"botIds is required"},400):r.json(await o.waitFor(t.botIds,typeof t.timeoutMs=="number"?t.timeoutMs:void 0))}),s.post("/api/bots/result",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId)return r.json({error:"botId is required"},400);try{return r.json(o.result(t.botId))}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},404)}}),s.post("/api/bots/stop",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId)return r.json({error:"botId is required"},400);try{return o.stop(t.botId,t.cascade!==!1),r.json({ok:!0})}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/approvals",a,r=>r.json(o.listApprovals())),s.post("/api/bots/approve",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId||!t.requestId)return r.json({error:"botId and requestId are required"},400);const e=r.req.header("x-bots-token")===o.token?"parent-bot":"human";if(e==="parent-bot"&&!t.reason)return r.json({error:"a reason is required when a bot approves"},400);try{return r.json(o.respondApproval(t.botId,t.requestId,t.allow===!0,t.reason,e,t.always===!0))}catch(i){return r.json({error:i instanceof Error?i.message:String(i)},400)}}),s.get("/api/bots/approvals",n(),r=>r.json(o.listApprovals())),s.get("/api/bots/:id",n(),r=>{const t=o.getBot(r.req.param("id"));return t?r.json(t):r.json({error:"not found"},404)}),s.get("/api/bots/:id/events",n(),r=>{const t=Number(r.req.query("limit"))||400;return r.json(o.store.readEvents(r.req.param("id"),t))}),s.post("/api/bots/:id/input",n(),async r=>{const t=await r.req.json().catch(()=>({}));if(typeof t.text!="string"||!t.text.trim())return r.json({error:"text is required"},400);try{return await o.input(r.req.param("id"),t.text,t.mode==="follow_up"?"follow_up":t.mode==="steer"?"steer":void 0),r.json({ok:!0})}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/:id/stop",n(),r=>{try{return o.stop(r.req.param("id"),!0),r.json({ok:!0})}catch(t){return r.json({error:t instanceof Error?t.message:String(t)},400)}}),s.post("/api/bots/:id/resume",n(),r=>{try{return o.resume(r.req.param("id")),r.json({ok:!0})}catch(t){return r.json({error:t instanceof Error?t.message:String(t)},400)}}),s.post("/api/bots/:id/approve",n(),async r=>{const t=await r.req.json().catch(()=>({}));if(!t.requestId)return r.json({error:"requestId is required"},400);try{return r.json(o.respondApproval(r.req.param("id"),t.requestId,t.allow===!0,t.reason,"human",t.always===!0))}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/:id/mode",n(),async r=>{const e=(await r.req.json().catch(()=>({}))).mode;if(e!=="supervised"&&e!=="parent-supervised"&&e!=="full-access")return r.json({error:"mode must be supervised, parent-supervised or full-access"},400);try{return o.setRuntimeMode(r.req.param("id"),e),r.json({ok:!0,mode:e})}catch(i){return r.json({error:i instanceof Error?i.message:String(i)},400)}}),s.post("/api/bots/:id/allowed-tools",n(),async r=>{const t=await r.req.json().catch(()=>({}));if(!t.tool)return r.json({error:"tool is required"},400);try{return r.json({tools:o.allowTool(r.req.param("id"),t.tool)})}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.delete("/api/bots/:id",n(),r=>{try{return o.deleteBot(r.req.param("id"),!0),r.json({ok:!0})}catch(t){return r.json({error:t instanceof Error?t.message:String(t)},400)}})}export{f as registerBotRoutes};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tmux-weblink",
3
- "version": "2.2.45",
3
+ "version": "2.2.46",
4
4
  "description": "Access your tmux sessions from the browser. A continuation of tmux-web and persalink.",
5
5
  "type": "module",
6
6
  "bin": {