tmux-weblink 2.2.40 → 2.2.41

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,34 +1,34 @@
1
- import{initTerminal as Xe}from"./terminal-core.js";const D=window.__TMUX_WEB_SHELL__;let p=null,u=null;const P=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let g=P;window.__tmuxWebScopeAgent=P;let me="sessions",x="",J="",K="",Se="";function v(e){return g?"/a/"+encodeURIComponent(g)+e:e}const r=document.getElementById("sidebar-content"),H=document.getElementById("main-placeholder"),b=document.getElementById("terminal-container"),j=document.getElementById("file-editor"),Ze=document.getElementById("fe-path"),E=document.getElementById("fe-status"),O=document.getElementById("fe-content"),R=document.getElementById("fe-save"),Qe=document.getElementById("fe-delete"),et=document.getElementById("fe-back"),Ce=document.getElementById("fe-new-name"),tt=document.getElementById("fe-new-btn"),ge=document.getElementById("settings-backdrop"),Ie=document.getElementById("settings-popover"),Be=document.querySelector(".sidebar"),xe="tmux-web-force-narrow";function Y(){try{return localStorage.getItem(xe)==="1"}catch{return!1}}function Te(){document.documentElement.classList.toggle("force-narrow",Y()),Y()&&Me()&&X()}function Me(){return Y()?!0:window.matchMedia("(max-width: 640px)").matches}function X(){Me()&&Be.classList.add("collapsed")}function He(){Be.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{He(),Re("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{He(),Re("files")});function Re(e){me=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"?(ve="",I()):gt()}let ve="";async function I(){if(me!=="sessions")return;try{const t=await(await fetch("/api/sidebar/sessions")).json(),s=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones});if(s===ve)return;ve=s,at(t)}catch{r.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")}),Ee()}const Ne="tmux-web-sidebar-group-collapsed";function Ae(){try{return new Set(JSON.parse(localStorage.getItem(Ne)||"[]"))}catch{return new Set}}function nt(e){try{localStorage.setItem(Ne,JSON.stringify([...e]))}catch{}}function st(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(c=>!c||c===e?!1:(t&&(c===t||c.startsWith(t+"/"))?"~"+c.slice(t.length):c).split("/").filter(Boolean).slice(-o).join("/")===a))return a}return s}function _e(e,n,t,s=!0){const i=new Map;for(const l of e){const c=l.path||"";i.has(c)||i.set(c,[]),i.get(c).push(l)}const o=[...i.keys()],a=Ae();for(const[l,c]of i){const f=st(l,o,n),L=a.has(l),h=document.createElement("div");h.className="session-group-header"+(L?" collapsed":""),h.title=l||"No working directory",h.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${d(f)}</span>`,h.addEventListener("click",()=>{const M=Ae(),ke=h.nextElementSibling;M.has(l)?(M.delete(l),h.classList.remove("collapsed"),ke?.classList.remove("collapsed")):(M.add(l),h.classList.add("collapsed"),ke?.classList.add("collapsed")),nt(M)});const ue=document.createElement("div");ue.className="session-group-body"+(L?" collapsed":"");for(const M of c)ue.appendChild(t?it(M,t,s):ot(M));r.appendChild(h),r.appendChild(ue)}}function it(e,n,t){const s=document.createElement("div");s.className="session-item"+(e.name===u&&g===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>
1
+ import{initTerminal as Xe}from"./terminal-core.js";import{initBots as Ze}from"./bots-client.js";const D=window.__TMUX_WEB_SHELL__;let p=null,u=null;const P=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let g=P;window.__tmuxWebScopeAgent=P;let me="sessions",x="",J="",K="",Se="";function v(e){return g?"/a/"+encodeURIComponent(g)+e:e}const r=document.getElementById("sidebar-content"),H=document.getElementById("main-placeholder"),b=document.getElementById("terminal-container"),j=document.getElementById("file-editor"),Qe=document.getElementById("fe-path"),E=document.getElementById("fe-status"),O=document.getElementById("fe-content"),R=document.getElementById("fe-save"),et=document.getElementById("fe-delete"),tt=document.getElementById("fe-back"),Ce=document.getElementById("fe-new-name"),nt=document.getElementById("fe-new-btn"),ge=document.getElementById("settings-backdrop"),Ie=document.getElementById("settings-popover"),Be=document.querySelector(".sidebar"),xe="tmux-web-force-narrow";function Y(){try{return localStorage.getItem(xe)==="1"}catch{return!1}}function Te(){document.documentElement.classList.toggle("force-narrow",Y()),Y()&&Me()&&X()}function Me(){return Y()?!0:window.matchMedia("(max-width: 640px)").matches}function X(){Me()&&Be.classList.add("collapsed")}function He(){Be.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{He(),Re("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{He(),Re("files")});function Re(e){me=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"?(ve="",I()):vt()}let ve="";async function I(){if(me!=="sessions")return;try{const t=await(await fetch("/api/sidebar/sessions")).json(),s=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones});if(s===ve)return;ve=s,lt(t)}catch{r.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")}),Ee()}const Ne="tmux-web-sidebar-group-collapsed";function Ae(){try{return new Set(JSON.parse(localStorage.getItem(Ne)||"[]"))}catch{return new Set}}function st(e){try{localStorage.setItem(Ne,JSON.stringify([...e]))}catch{}}function it(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(c=>!c||c===e?!1:(t&&(c===t||c.startsWith(t+"/"))?"~"+c.slice(t.length):c).split("/").filter(Boolean).slice(-o).join("/")===a))return a}return s}function _e(e,n,t,s=!0){const i=new Map;for(const l of e){const c=l.path||"";i.has(c)||i.set(c,[]),i.get(c).push(l)}const o=[...i.keys()],a=Ae();for(const[l,c]of i){const f=it(l,o,n),L=a.has(l),h=document.createElement("div");h.className="session-group-header"+(L?" collapsed":""),h.title=l||"No working directory",h.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${d(f)}</span>`,h.addEventListener("click",()=>{const M=Ae(),ke=h.nextElementSibling;M.has(l)?(M.delete(l),h.classList.remove("collapsed"),ke?.classList.remove("collapsed")):(M.add(l),h.classList.add("collapsed"),ke?.classList.add("collapsed")),st(M)});const ue=document.createElement("div");ue.className="session-group-body"+(L?" collapsed":"");for(const M of c)ue.appendChild(t?ot(M,t,s):at(M));r.appendChild(h),r.appendChild(ue)}}function ot(e,n,t){const s=document.createElement("div");s.className="session-item"+(e.name===u&&g===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
2
  <span>${d(e.name)}</span>${t?"":'<span class="meta">offline</span>'}
3
- <button class="session-edit-btn" data-session="${d(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")||U(e.name,n)});const i=s.querySelector(".session-edit-btn");return i&&i.addEventListener("click",o=>{o.stopPropagation(),le(e.name,i,{agentId:n})}),s}function ot(e){const n=document.createElement("div");n.className="session-item"+(e.name===u&&!g?" 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>
3
+ <button class="session-edit-btn" data-session="${d(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")||U(e.name,n)});const i=s.querySelector(".session-edit-btn");return i&&i.addEventListener("click",o=>{o.stopPropagation(),le(e.name,i,{agentId:n})}),s}function at(e){const n=document.createElement("div");n.className="session-item"+(e.name===u&&!g?" 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>
4
4
  <span>${d(e.name)}</span>
5
5
  <button class="session-edit-btn" data-session="${d(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
- `,n.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||U(e.name)});const t=n.querySelector(".session-edit-btn");return t&&t.addEventListener("click",s=>{s.stopPropagation(),le(e.name,t)}),n}function at(e){r.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"+(P?" clickable":""),t.textContent=P?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",P&&(t.title="Back to hub",t.addEventListener("click",()=>{window.location.href="/"})),r.appendChild(t),_e(n,e.home);const s=e.agents||[];for(const o of s){if(!o.sessions||o.sessions.length===0)continue;const a=o.agentId===g,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)+"/"})),r.appendChild(l),_e(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",r.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>
6
+ `,n.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||U(e.name)});const t=n.querySelector(".session-edit-btn");return t&&t.addEventListener("click",s=>{s.stopPropagation(),le(e.name,t)}),n}function lt(e){r.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"+(P?" clickable":""),t.textContent=P?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",P&&(t.title="Back to hub",t.addEventListener("click",()=>{window.location.href="/"})),r.appendChild(t),_e(n,e.home);const s=e.agents||[];for(const o of s){if(!o.sessions||o.sessions.length===0)continue;const a=o.agentId===g,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)+"/"})),r.appendChild(l),_e(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",r.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
7
  <span>${d(a.name)}</span><span class="meta">\u5931\u6548${c}</span>
8
- <button class="session-edit-btn" data-session="${d(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",()=>{le(a.name,l,{tombstone:!0,agentId:a.agentId})});const f=l.querySelector(".session-edit-btn");f&&f.addEventListener("click",L=>{L.stopPropagation(),le(a.name,f,{tombstone:!0,agentId:a.agentId})}),r.appendChild(l)}}}function d(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function U(e,n){if(u===e&&p&&g===(n||null))return;j.style.display="none",H.style.display="none",b.style.display="",b.classList.add("terminal-pending"),X(),p&&(oe(),p.destroy(),p=null),u=e,g=n||null,window.__tmuxWebScopeAgent=g,window.__tmuxWebCurrentSession=u,Ht(e,n);const t=Le(e,n);Ke.set(t,Date.now()+Tt);const s=$.get(t);if(s&&s.state==="working"){s.state="idle",s.doneUntil=void 0,s.unread=!1;const i=r.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&&fe(i,t,s)}for(const i of r.querySelectorAll(".session-item"))i.classList.toggle("active",i.getAttribute("data-session")===e&&(i.getAttribute("data-agent")||null)===g);try{p=await Xe(b,e,{terminal:D.terminal,scrollback:D.scrollback,theme:D.theme,wsBase:g?"/ws/a/"+encodeURIComponent(g):D.wsBase||"/ws"}),Ge()}catch(i){console.error("[shell] terminal init failed:",i);const o=i&&typeof i=="object"&&"message"in i?i.message:String(i);b.textContent="Failed to open terminal for "+e+": "+o,b.classList.remove("terminal-pending")}}let Z=[],m=null,$e=!1;function lt(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 ct(e){$e=!0;try{const n=await fetch(v("/api/git/status?path="+encodeURIComponent(e)));n.ok?m=await n.json():m=null}catch{m=null}finally{$e=!1}}function rt(){if(!m||!m.branch)return"";const{branch:e,linesAdded:n,linesRemoved:t}=m;let s=`<div class="sidebar-git"><div class="git-branch-badge">
8
+ <button class="session-edit-btn" data-session="${d(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",()=>{le(a.name,l,{tombstone:!0,agentId:a.agentId})});const f=l.querySelector(".session-edit-btn");f&&f.addEventListener("click",L=>{L.stopPropagation(),le(a.name,f,{tombstone:!0,agentId:a.agentId})}),r.appendChild(l)}}}function d(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function U(e,n){if(u===e&&p&&g===(n||null))return;j.style.display="none",H.style.display="none",b.style.display="",b.classList.add("terminal-pending"),X(),p&&(oe(),p.destroy(),p=null),u=e,g=n||null,window.__tmuxWebScopeAgent=g,window.__tmuxWebCurrentSession=u,Rt(e,n);const t=Le(e,n);Ke.set(t,Date.now()+Mt);const s=$.get(t);if(s&&s.state==="working"){s.state="idle",s.doneUntil=void 0,s.unread=!1;const i=r.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&&fe(i,t,s)}for(const i of r.querySelectorAll(".session-item"))i.classList.toggle("active",i.getAttribute("data-session")===e&&(i.getAttribute("data-agent")||null)===g);try{p=await Xe(b,e,{terminal:D.terminal,scrollback:D.scrollback,theme:D.theme,wsBase:g?"/ws/a/"+encodeURIComponent(g):D.wsBase||"/ws"}),Ge()}catch(i){console.error("[shell] terminal init failed:",i);const o=i&&typeof i=="object"&&"message"in i?i.message:String(i);b.textContent="Failed to open terminal for "+e+": "+o,b.classList.remove("terminal-pending")}}let Z=[],m=null,$e=!1;function ct(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 rt(e){$e=!0;try{const n=await fetch(v("/api/git/status?path="+encodeURIComponent(e)));n.ok?m=await n.json():m=null}catch{m=null}finally{$e=!1}}function dt(){if(!m||!m.branch)return"";const{branch:e,linesAdded:n,linesRemoved:t}=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
- ${d(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>"}r.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&A&&m&&(e.stopPropagation(),Ue())});const W=document.getElementById("header-git"),De=document.getElementById("git-diff-view"),Pe=document.getElementById("gd-path"),Q=document.getElementById("gd-status"),ee=document.getElementById("gd-content"),dt=document.getElementById("gd-back");let A=null;function z(e){if(!e||!e.branch){W.style.display="none",A=null;return}A=e.repoRoot;const{branch:n,linesAdded:t,linesRemoved:s}=e;let i=`<span class="branch">${d(n)}</span>`;(t>0||s>0)&&(i+=`<span class="sep">\xB7</span>+<span class="diff-add">${t}</span> <span class="diff-del">-${s}</span>`),W.innerHTML=i,W.style.display="block"}W.addEventListener("click",e=>{A&&m&&(e.stopPropagation(),Ue())});const y=document.getElementById("git-popover"),te=document.getElementById("git-popover-backdrop");function ye(){const e=W.getBoundingClientRect();y.style.top=e.bottom+4+"px",y.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function je(){const e=A,n=document.getElementById("git-popover-browse");n&&n.addEventListener("click",()=>{if(se(),e){me="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));const t=document.getElementById("mode-files");t&&t.classList.add("active"),T(e)}})}let Oe="";function Ue(){if(!m)return;const e=m.files||[];if(!e.length)y.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
10
+ ${d(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>"}r.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&A&&m&&(e.stopPropagation(),Ue())});const W=document.getElementById("header-git"),De=document.getElementById("git-diff-view"),Pe=document.getElementById("gd-path"),Q=document.getElementById("gd-status"),ee=document.getElementById("gd-content"),pt=document.getElementById("gd-back");let A=null;function z(e){if(!e||!e.branch){W.style.display="none",A=null;return}A=e.repoRoot;const{branch:n,linesAdded:t,linesRemoved:s}=e;let i=`<span class="branch">${d(n)}</span>`;(t>0||s>0)&&(i+=`<span class="sep">\xB7</span>+<span class="diff-add">${t}</span> <span class="diff-del">-${s}</span>`),W.innerHTML=i,W.style.display="block"}W.addEventListener("click",e=>{A&&m&&(e.stopPropagation(),Ue())});const y=document.getElementById("git-popover"),te=document.getElementById("git-popover-backdrop");function ye(){const e=W.getBoundingClientRect();y.style.top=e.bottom+4+"px",y.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function je(){const e=A,n=document.getElementById("git-popover-browse");n&&n.addEventListener("click",()=>{if(se(),e){me="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));const t=document.getElementById("mode-files");t&&t.classList.add("active"),T(e)}})}let Oe="";function Ue(){if(!m)return;const e=m.files||[];if(!e.length)y.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
11
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}">
12
12
  ${a}<span class="file-path">${d(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>',Oe=n,y.innerHTML=n,y.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",()=>ze(i.path)))})}ye(),y.classList.add("open"),te.classList.add("open"),je()}function pt(){return window.innerWidth>=1024}function We(e,n){const s=(e+(n&&e?`
15
+ </div>`}n+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',Oe=n,y.innerHTML=n,y.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",()=>ze(i.path)))})}ye(),y.classList.add("open"),te.classList.add("open"),je()}function ft(){return window.innerWidth>=1024}function We(e,n){const s=(e+(n&&e?`
16
16
  `:"")+n).split(`
17
- `);let i="",o=0,a=0;for(const l of s){const c=l;if(c.startsWith("@@")){const f=c.match(/@@\s+-(\d+)[^+]*\+(\d+)/);f&&(o=parseInt(f[1],10)-1,a=parseInt(f[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${d(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">${d(c)}</span></div>`);continue}if(c.startsWith("+"))a++,i+=`<div class="diff-line add"><span class="ln-no">${a}</span><span class="ln-body">${d(c)}</span></div>`;else if(c.startsWith("-"))o++,i+=`<div class="diff-line del"><span class="ln-no">${o}</span><span class="ln-body">${d(c)}</span></div>`;else if(c.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${d(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">${d(c)}</span></div>`}}return{html:i,lineCount:s.length}}let ne=null;async function ze(e){const n=A;if(n)if(se(),pt()){b.style.display="none",p&&(oe(),p.destroy(),p=null,ne=u,u=null),z(null),j.style.display="none",H.style.display="none",De.style.display="flex",Pe.textContent=e,Q.textContent="Loading\u2026",ee.innerHTML="";try{const t=await fetch(v("/api/git/diff?path="+encodeURIComponent(n)+"&file="+encodeURIComponent(e)));if(!t.ok)throw new Error(await t.text());const s=await t.json();ut(e,s.diff,s.stagedDiff)}catch(t){const s=t instanceof Error?t.message:String(t);Q.textContent="Error",ee.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${d(s)}</div>`}}else{y.innerHTML=`<div class="git-diff-view"><div class="diff-header">
17
+ `);let i="",o=0,a=0;for(const l of s){const c=l;if(c.startsWith("@@")){const f=c.match(/@@\s+-(\d+)[^+]*\+(\d+)/);f&&(o=parseInt(f[1],10)-1,a=parseInt(f[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${d(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">${d(c)}</span></div>`);continue}if(c.startsWith("+"))a++,i+=`<div class="diff-line add"><span class="ln-no">${a}</span><span class="ln-body">${d(c)}</span></div>`;else if(c.startsWith("-"))o++,i+=`<div class="diff-line del"><span class="ln-no">${o}</span><span class="ln-body">${d(c)}</span></div>`;else if(c.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${d(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">${d(c)}</span></div>`}}return{html:i,lineCount:s.length}}let ne=null;async function ze(e){const n=A;if(n)if(se(),ft()){b.style.display="none",p&&(oe(),p.destroy(),p=null,ne=u,u=null),z(null),j.style.display="none",H.style.display="none",De.style.display="flex",Pe.textContent=e,Q.textContent="Loading\u2026",ee.innerHTML="";try{const t=await fetch(v("/api/git/diff?path="+encodeURIComponent(n)+"&file="+encodeURIComponent(e)));if(!t.ok)throw new Error(await t.text());const s=await t.json();mt(e,s.diff,s.stagedDiff)}catch(t){const s=t instanceof Error?t.message:String(t);Q.textContent="Error",ee.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${d(s)}</div>`}}else{y.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">${d(e)}</span>
20
20
  <span class="diff-loading">Loading\u2026</span>
21
- </div></div>`,ye(),y.classList.add("open"),te.classList.add("open");try{const t=await fetch(v("/api/git/diff?path="+encodeURIComponent(n)+"&file="+encodeURIComponent(e)));if(!t.ok)throw new Error(await t.text());const s=await t.json();ft(e,s.diff,s.stagedDiff)}catch(t){const s=t instanceof Error?t.message:String(t);y.innerHTML=`<div class="git-diff-view"><div class="diff-header">
21
+ </div></div>`,ye(),y.classList.add("open"),te.classList.add("open");try{const t=await fetch(v("/api/git/diff?path="+encodeURIComponent(n)+"&file="+encodeURIComponent(e)));if(!t.ok)throw new Error(await t.text());const s=await t.json();ut(e,s.diff,s.stagedDiff)}catch(t){const s=t instanceof Error?t.message:String(t);y.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">${d(e)}</span>
24
- </div><div class="diff-empty">Error loading diff: ${d(s)}</div></div>`}}}function ft(e,n,t){if(!n&&!t){y.innerHTML=`<div class="git-diff-view"><div class="diff-header">
24
+ </div><div class="diff-empty">Error loading diff: ${d(s)}</div></div>`}}}function ut(e,n,t){if(!n&&!t){y.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">${d(e)}</span>
27
27
  </div><div class="diff-empty">No diff content available</div></div>`;return}const{html:s,lineCount:i}=We(n,t);y.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">${d(e)}</span>
30
30
  <span class="diff-filesize">${i} lines</span>
31
- </div><div class="diff-content">${s}</div></div>`,y.querySelector(".diff-back")?.addEventListener("click",()=>{y.innerHTML=Oe,ye(),m&&y.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",()=>ze(l.path)))}),je()})}function ut(e,n,t){if(!n&&!t){Q.textContent="No diff",ee.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}=We(n,t);Pe.textContent=e,Q.textContent=i+" lines",ee.innerHTML=s}function mt(){De.style.display="none",ne?(b.style.display="",b.classList.add("terminal-pending"),U(ne),ne=null):u?(b.style.display="",b.classList.add("terminal-pending"),Ge()):H.style.display="flex"}dt.addEventListener("click",mt);function se(){y.classList.remove("open"),te.classList.remove("open")}te.addEventListener("click",se),document.addEventListener("keydown",e=>{e.key==="Escape"&&(se(),pe())});async function Fe(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,z(i);return}}}catch{}m=null,z(null)}let ie=null;function Ge(){oe(),u&&(Fe(u),ie=setInterval(()=>{u&&Fe(u)},3e4))}function oe(){ie&&(clearInterval(ie),ie=null)}function gt(){if(Z=D.fsRoots||[],Z.length===0){if(u){vt(u);return}r.innerHTML='<div class="file-tree-info">Open a session first, then switch to Files to browse its directory.</div>';return}r.innerHTML="";for(const e of Z){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> ${d(e)}`,n.addEventListener("click",()=>T(e)),r.appendChild(n)}}async function vt(e){r.innerHTML='<div class="file-tree-empty">Loading...</div>';try{const t=await(await fetch(v("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?T(t.path):r.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{r.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function T(e){x=e,r.innerHTML='<div class="file-tree-empty">Loading...</div>';const n=ct(e);try{const s=await(await fetch(v("/api/fs/list?path="+encodeURIComponent(e)))).json();await n,r.innerHTML="",z(m),r.innerHTML+=rt();const i=yt(e);if(i&&!Z.some(l=>e===l)){const l=document.createElement("div");l.className="file-tree-item",l.innerHTML="..",l.addEventListener("click",()=>T(i)),r.appendChild(l)}if(s.dirs)for(const a of s.dirs){const l=a.split("/").pop()||a.split("\\").pop(),c=document.createElement("div");c.className="file-tree-item",c.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${d(l)}`,c.addEventListener("click",()=>T(a)),r.appendChild(c)}else r.innerHTML="";const o=s.files||[];for(const a of o){const l=a.split("/").pop()||a.split("\\").pop(),c=lt(a);let f="",L="";if(c)switch(c){case"M":f="git-mod",L='<span class="git-file-status M">M</span>';break;case"A":f="git-add",L='<span class="git-file-status A">A</span>';break;case"D":f="git-del",L='<span class="git-file-status D">D</span>';break;case"?":f="git-untracked",L='<span class="git-file-status ?">?</span>';break;case"R":f="git-mod",L='<span class="git-file-status R">R</span>';break}const h=document.createElement("div");h.className="file-tree-item file"+(f?" "+f:""),h.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${L}${d(l)}`,h.addEventListener("click",()=>ht(a)),r.appendChild(h)}}catch{r.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function yt(e){const n=e.lastIndexOf("/");return n<=0?null:e.substring(0,n)}async function ht(e){J=e,b.style.display="none",p&&(oe(),p.destroy(),p=null,u=null),z(null),X(),H.style.display="none",j.style.display="flex",Ze.textContent=e,E.textContent="Loading...",R.style.display="none";try{const n=await fetch(v("/api/file?path="+encodeURIComponent(e)));if(!n.ok){const s=await n.json();E.textContent=s.error||"Failed to load",O.value="";return}const t=await n.json();O.value=t.content,K=t.content,Se=t.content,E.textContent=t.size+" bytes",R.style.display=""}catch{E.textContent="Failed to load",O.value=""}}O.addEventListener("input",()=>{K=O.value}),R.addEventListener("click",async()=>{R.textContent="Saving...",R.disabled=!0;try{const e=await fetch(v("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:J,content:K})});if(!e.ok){const n=await e.json();E.textContent=n.error||"Save failed";return}Se=K,E.textContent="Saved"}catch{E.textContent="Save failed"}finally{R.disabled=!1,R.textContent="Save"}}),Qe.addEventListener("click",async()=>{if(confirm("Delete "+J+"?"))try{const e=await fetch(v("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:J})});if(!e.ok){const n=await e.json();E.textContent=n.error||"Delete failed";return}j.style.display="none",H.style.display="flex",x&&T(x)}catch{E.textContent="Delete failed"}}),et.addEventListener("click",()=>{j.style.display="none",H.style.display="flex",x&&T(x)}),tt.addEventListener("click",async()=>{const e=Ce.value.trim();if(!e)return;const n=x+"/"+e;try{const t=await fetch(v("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n})});if(!t.ok){const s=await t.json();E.textContent=s.error||"Create failed";return}Ce.value="",x&&T(x)}catch{E.textContent="Create failed"}});const ae=document.getElementById("force-narrow-toggle");ae&&(ae.checked=Y(),ae.addEventListener("change",()=>{try{localStorage.setItem(xe,ae.checked?"1":"0")}catch{}Te(),I()})),Te(),document.getElementById("mode-settings").addEventListener("click",()=>{const e=Ie.classList.toggle("open");ge.classList.toggle("open",e)}),ge.addEventListener("click",()=>{Ie.classList.remove("open"),ge.classList.remove("open")});let w="",B=!1,k;const F=document.createElement("div");F.className="session-popover-backdrop",document.body.appendChild(F);const S=document.createElement("div");S.id="session-popover",S.className="session-popover",S.style.display="none",S.innerHTML=`<div class="sp-field">
31
+ </div><div class="diff-content">${s}</div></div>`,y.querySelector(".diff-back")?.addEventListener("click",()=>{y.innerHTML=Oe,ye(),m&&y.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",()=>ze(l.path)))}),je()})}function mt(e,n,t){if(!n&&!t){Q.textContent="No diff",ee.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}=We(n,t);Pe.textContent=e,Q.textContent=i+" lines",ee.innerHTML=s}function gt(){De.style.display="none",ne?(b.style.display="",b.classList.add("terminal-pending"),U(ne),ne=null):u?(b.style.display="",b.classList.add("terminal-pending"),Ge()):H.style.display="flex"}pt.addEventListener("click",gt);function se(){y.classList.remove("open"),te.classList.remove("open")}te.addEventListener("click",se),document.addEventListener("keydown",e=>{e.key==="Escape"&&(se(),pe())});async function Fe(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,z(i);return}}}catch{}m=null,z(null)}let ie=null;function Ge(){oe(),u&&(Fe(u),ie=setInterval(()=>{u&&Fe(u)},3e4))}function oe(){ie&&(clearInterval(ie),ie=null)}function vt(){if(Z=D.fsRoots||[],Z.length===0){if(u){yt(u);return}r.innerHTML='<div class="file-tree-info">Open a session first, then switch to Files to browse its directory.</div>';return}r.innerHTML="";for(const e of Z){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> ${d(e)}`,n.addEventListener("click",()=>T(e)),r.appendChild(n)}}async function yt(e){r.innerHTML='<div class="file-tree-empty">Loading...</div>';try{const t=await(await fetch(v("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?T(t.path):r.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{r.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function T(e){x=e,r.innerHTML='<div class="file-tree-empty">Loading...</div>';const n=rt(e);try{const s=await(await fetch(v("/api/fs/list?path="+encodeURIComponent(e)))).json();await n,r.innerHTML="",z(m),r.innerHTML+=dt();const i=ht(e);if(i&&!Z.some(l=>e===l)){const l=document.createElement("div");l.className="file-tree-item",l.innerHTML="..",l.addEventListener("click",()=>T(i)),r.appendChild(l)}if(s.dirs)for(const a of s.dirs){const l=a.split("/").pop()||a.split("\\").pop(),c=document.createElement("div");c.className="file-tree-item",c.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${d(l)}`,c.addEventListener("click",()=>T(a)),r.appendChild(c)}else r.innerHTML="";const o=s.files||[];for(const a of o){const l=a.split("/").pop()||a.split("\\").pop(),c=ct(a);let f="",L="";if(c)switch(c){case"M":f="git-mod",L='<span class="git-file-status M">M</span>';break;case"A":f="git-add",L='<span class="git-file-status A">A</span>';break;case"D":f="git-del",L='<span class="git-file-status D">D</span>';break;case"?":f="git-untracked",L='<span class="git-file-status ?">?</span>';break;case"R":f="git-mod",L='<span class="git-file-status R">R</span>';break}const h=document.createElement("div");h.className="file-tree-item file"+(f?" "+f:""),h.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${L}${d(l)}`,h.addEventListener("click",()=>bt(a)),r.appendChild(h)}}catch{r.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function ht(e){const n=e.lastIndexOf("/");return n<=0?null:e.substring(0,n)}async function bt(e){J=e,b.style.display="none",p&&(oe(),p.destroy(),p=null,u=null),z(null),X(),H.style.display="none",j.style.display="flex",Qe.textContent=e,E.textContent="Loading...",R.style.display="none";try{const n=await fetch(v("/api/file?path="+encodeURIComponent(e)));if(!n.ok){const s=await n.json();E.textContent=s.error||"Failed to load",O.value="";return}const t=await n.json();O.value=t.content,K=t.content,Se=t.content,E.textContent=t.size+" bytes",R.style.display=""}catch{E.textContent="Failed to load",O.value=""}}O.addEventListener("input",()=>{K=O.value}),R.addEventListener("click",async()=>{R.textContent="Saving...",R.disabled=!0;try{const e=await fetch(v("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:J,content:K})});if(!e.ok){const n=await e.json();E.textContent=n.error||"Save failed";return}Se=K,E.textContent="Saved"}catch{E.textContent="Save failed"}finally{R.disabled=!1,R.textContent="Save"}}),et.addEventListener("click",async()=>{if(confirm("Delete "+J+"?"))try{const e=await fetch(v("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:J})});if(!e.ok){const n=await e.json();E.textContent=n.error||"Delete failed";return}j.style.display="none",H.style.display="flex",x&&T(x)}catch{E.textContent="Delete failed"}}),tt.addEventListener("click",()=>{j.style.display="none",H.style.display="flex",x&&T(x)}),nt.addEventListener("click",async()=>{const e=Ce.value.trim();if(!e)return;const n=x+"/"+e;try{const t=await fetch(v("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n})});if(!t.ok){const s=await t.json();E.textContent=s.error||"Create failed";return}Ce.value="",x&&T(x)}catch{E.textContent="Create failed"}});const ae=document.getElementById("force-narrow-toggle");ae&&(ae.checked=Y(),ae.addEventListener("change",()=>{try{localStorage.setItem(xe,ae.checked?"1":"0")}catch{}Te(),I()})),Te(),document.getElementById("mode-settings").addEventListener("click",()=>{const e=Ie.classList.toggle("open");ge.classList.toggle("open",e)}),ge.addEventListener("click",()=>{Ie.classList.remove("open"),ge.classList.remove("open")});let w="",B=!1,k;const F=document.createElement("div");F.className="session-popover-backdrop",document.body.appendChild(F);const S=document.createElement("div");S.id="session-popover",S.className="session-popover",S.style.display="none",S.innerHTML=`<div class="sp-field">
32
32
  <label>Rename session</label>
33
33
  <input type="text" id="sp-name" />
34
34
  </div>
@@ -38,5 +38,5 @@ import{initTerminal as Xe}from"./terminal-core.js";const D=window.__TMUX_WEB_SHE
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 danger" id="sp-delete">Delete session</button>`,document.body.appendChild(S);function bt(e){const n=e.getBoundingClientRect(),t=window.innerHeight,s=S.offsetHeight||240;let i=n.bottom+4;i+s>t-8&&(i=Math.max(8,n.top-s-4)),S.style.top=i+"px",S.style.left=Math.max(8,Math.min(n.left,window.innerWidth-240))+"px"}function le(e,n,t){w=e,B=!!t?.tombstone,k=t?.agentId;const s=document.getElementById("sp-name");s.value=e;const i=S.querySelector(".sp-field label");i.textContent=B?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const o=document.getElementById("sp-rebuild");o.style.display=B?"":"none";const a=document.getElementById("sp-delete");a.textContent=B?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";const l=document.getElementById("sp-save");l.textContent=B?"\u91CD\u547D\u540D":"Save",F.classList.add("open"),S.style.display="block",bt(n),setTimeout(()=>s.focus(),50)}function N(){F.classList.remove("open"),S.style.display="none"}F.addEventListener("click",N),document.getElementById("sp-save").addEventListener("click",async()=>{const e=document.getElementById("sp-name").value.trim();if(!e||e===w){N();return}try{const n=B?{oldName:w,newName:e,agentId:k}:{oldName:w,newName:e,...k?{agentId:k}:{}};if(!(await fetch(v(B?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).ok)return;N(),I(),!B&&u===w&&(k??null)===g&&U(e,k)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+w+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{const e=await fetch(v("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:w,agentId:k})});if(!e.ok){const n=await e.json();alert(n.error||"\u91CD\u5EFA\u5931\u8D25");return}N(),I()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(B){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+w+'"\uFF1F'))return;try{if(!(await fetch(v("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:w,agentId:k})})).ok)return;N(),I()}catch{}return}if(confirm('Delete session "'+w+'"?'))try{if(!(await fetch(v("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:w,...k?{agentId:k}:{}})})).ok)return;N(),u===w&&(k??null)===g&&(p&&(p.destroy(),p=null),u=null,b.style.display="none",H.style.display="flex"),I()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",N);const qe={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"},ce=document.getElementById("mobile-keys"),wt=new Set(["up","down","left","right","tab","s-tab","space"]),Lt=400,Et=80;let G=0,re=0,de=!1;function kt(){G&&(clearTimeout(G),G=0),re&&(clearInterval(re),re=0)}ce.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),ce.addEventListener("pointerdown",e=>{const n=e.target.closest("button[data-key]");if(!n)return;const t=n.dataset.key;wt.has(t)&&(de=!1,G=setTimeout(()=>{G=0,de=!0,re=setInterval(()=>{const s=qe[t];s&&p&&p.sendInput(s)},Et)},Lt))});for(const e of["pointerup","pointercancel","pointerleave"])ce.addEventListener(e,kt);ce.addEventListener("click",e=>{const n=e.target.closest("button[data-key]");if(!n||!p)return;if(de){de=!1;return}const t=qe[n.dataset.key];t&&(p.sendInput(t),p.focus())});const C=document.getElementById("mk-input"),Ve=document.getElementById("mk-send");function Je(){if(!C||!p)return;const e=C.value;e&&(p.sendInput(e+"\r"),C.value="",C.rows=1,p.focus())}if(C&&(C.addEventListener("input",()=>{C.rows=1;const e=C.value.split(`
42
- `).length;C.rows=Math.min(e,4)}),C.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Je())})),Ve&&Ve.addEventListener("click",Je),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 he=document.getElementById("process-panel"),q=document.getElementById("proc-list"),St=document.getElementById("proc-close"),be=document.getElementById("proc-backdrop"),Ct=document.getElementById("header-ram");function It(){q.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(v("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){q.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="'+d(t.command)+'">'+d(t.command)+'</span><button class="proc-kill" title="Kill PID '+t.pid+'">&times;</button></div>'}q.innerHTML=n;for(const t of q.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(v("/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(()=>{q.innerHTML='<div class="proc-empty">Failed to load</div>'})}function Bt(){he.classList.add("open"),be.classList.add("open"),It()}function pe(){he.classList.remove("open"),be.classList.remove("open")}Ct.addEventListener("click",e=>{e.stopPropagation(),he.classList.contains("open")?pe():Bt()}),St.addEventListener("click",pe),be.addEventListener("click",pe);const xt=2e3;let V=null,we=null;const _=new Map,$=new Map,Tt=5e3,Ke=new Map;function Le(e,n){return(n?"a:"+n+":":"l:")+e}function Mt(e,n,t){const s=Le(e,n);if(t==="working"){const f=Ke.get(s);if(f&&Date.now()<f)return}const i=$.get(s),o=e===u&&(n??null)===g,a=t==="idle"&&i?.state==="working";$.set(s,{session:e,agentId:n,state:t,doneUntil:a?Date.now()+xt:void 0,unread:a?!o:!1});const l=n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',c=r.querySelector(l);c&&fe(c,s,$.get(s))}function fe(e,n,t){const s=_.get(n);s&&(clearTimeout(s),_.delete(n)),e.classList.remove("working","just-done");const i=t.session===u&&(t.agentId??null)===g;t.state==="working"?e.classList.add("working"):i&&t.doneUntil&&Date.now()<t.doneUntil?(e.classList.add("just-done"),_.set(n,setTimeout(()=>{e.classList.remove("just-done"),_.delete(n)},Math.max(0,t.doneUntil-Date.now())))):!i&&t.unread&&e.classList.add("just-done")}function Ee(){for(const[e,n]of $){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=r.querySelector(t);s&&fe(s,e,n)}}function Ht(e,n){const t=Le(e,n),s=$.get(t);if(!s)return;const i=_.get(t);i&&(clearTimeout(i),_.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=r.querySelector(o);a&&fe(a,t,s)}function Ye(){if(V||we)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);V=s,s.onmessage=i=>{try{const o=JSON.parse(String(i.data));o&&o.type==="session.activity"&&typeof o.session=="string"&&Mt(o.session,o.agentId||void 0,o.state==="working"?"working":"idle")}catch{}},s.onclose=()=>{V===s&&(V=null,we=setTimeout(()=>{we=null,Ye()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{V=null}}window.__openSession=U,window.__refreshSidebar=I,I(),X(),Ee(),Ye(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Ee()}),setInterval(()=>{document.visibilityState==="visible"&&I()},1e4);
41
+ <button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(S);function wt(e){const n=e.getBoundingClientRect(),t=window.innerHeight,s=S.offsetHeight||240;let i=n.bottom+4;i+s>t-8&&(i=Math.max(8,n.top-s-4)),S.style.top=i+"px",S.style.left=Math.max(8,Math.min(n.left,window.innerWidth-240))+"px"}function le(e,n,t){w=e,B=!!t?.tombstone,k=t?.agentId;const s=document.getElementById("sp-name");s.value=e;const i=S.querySelector(".sp-field label");i.textContent=B?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const o=document.getElementById("sp-rebuild");o.style.display=B?"":"none";const a=document.getElementById("sp-delete");a.textContent=B?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";const l=document.getElementById("sp-save");l.textContent=B?"\u91CD\u547D\u540D":"Save",F.classList.add("open"),S.style.display="block",wt(n),setTimeout(()=>s.focus(),50)}function N(){F.classList.remove("open"),S.style.display="none"}F.addEventListener("click",N),document.getElementById("sp-save").addEventListener("click",async()=>{const e=document.getElementById("sp-name").value.trim();if(!e||e===w){N();return}try{const n=B?{oldName:w,newName:e,agentId:k}:{oldName:w,newName:e,...k?{agentId:k}:{}};if(!(await fetch(v(B?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).ok)return;N(),I(),!B&&u===w&&(k??null)===g&&U(e,k)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+w+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{const e=await fetch(v("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:w,agentId:k})});if(!e.ok){const n=await e.json();alert(n.error||"\u91CD\u5EFA\u5931\u8D25");return}N(),I()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(B){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+w+'"\uFF1F'))return;try{if(!(await fetch(v("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:w,agentId:k})})).ok)return;N(),I()}catch{}return}if(confirm('Delete session "'+w+'"?'))try{if(!(await fetch(v("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:w,...k?{agentId:k}:{}})})).ok)return;N(),u===w&&(k??null)===g&&(p&&(p.destroy(),p=null),u=null,b.style.display="none",H.style.display="flex"),I()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",N);const qe={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"},ce=document.getElementById("mobile-keys"),Lt=new Set(["up","down","left","right","tab","s-tab","space"]),Et=400,kt=80;let G=0,re=0,de=!1;function St(){G&&(clearTimeout(G),G=0),re&&(clearInterval(re),re=0)}ce.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),ce.addEventListener("pointerdown",e=>{const n=e.target.closest("button[data-key]");if(!n)return;const t=n.dataset.key;Lt.has(t)&&(de=!1,G=setTimeout(()=>{G=0,de=!0,re=setInterval(()=>{const s=qe[t];s&&p&&p.sendInput(s)},kt)},Et))});for(const e of["pointerup","pointercancel","pointerleave"])ce.addEventListener(e,St);ce.addEventListener("click",e=>{const n=e.target.closest("button[data-key]");if(!n||!p)return;if(de){de=!1;return}const t=qe[n.dataset.key];t&&(p.sendInput(t),p.focus())});const C=document.getElementById("mk-input"),Ve=document.getElementById("mk-send");function Je(){if(!C||!p)return;const e=C.value;e&&(p.sendInput(e+"\r"),C.value="",C.rows=1,p.focus())}if(C&&(C.addEventListener("input",()=>{C.rows=1;const e=C.value.split(`
42
+ `).length;C.rows=Math.min(e,4)}),C.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Je())})),Ve&&Ve.addEventListener("click",Je),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 he=document.getElementById("process-panel"),q=document.getElementById("proc-list"),Ct=document.getElementById("proc-close"),be=document.getElementById("proc-backdrop"),It=document.getElementById("header-ram");function Bt(){q.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(v("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){q.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="'+d(t.command)+'">'+d(t.command)+'</span><button class="proc-kill" title="Kill PID '+t.pid+'">&times;</button></div>'}q.innerHTML=n;for(const t of q.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(v("/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(()=>{q.innerHTML='<div class="proc-empty">Failed to load</div>'})}function xt(){he.classList.add("open"),be.classList.add("open"),Bt()}function pe(){he.classList.remove("open"),be.classList.remove("open")}It.addEventListener("click",e=>{e.stopPropagation(),he.classList.contains("open")?pe():xt()}),Ct.addEventListener("click",pe),be.addEventListener("click",pe);const Tt=2e3;let V=null,we=null;const _=new Map,$=new Map,Mt=5e3,Ke=new Map;function Le(e,n){return(n?"a:"+n+":":"l:")+e}function Ht(e,n,t){const s=Le(e,n);if(t==="working"){const f=Ke.get(s);if(f&&Date.now()<f)return}const i=$.get(s),o=e===u&&(n??null)===g,a=t==="idle"&&i?.state==="working";$.set(s,{session:e,agentId:n,state:t,doneUntil:a?Date.now()+Tt:void 0,unread:a?!o:!1});const l=n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',c=r.querySelector(l);c&&fe(c,s,$.get(s))}function fe(e,n,t){const s=_.get(n);s&&(clearTimeout(s),_.delete(n)),e.classList.remove("working","just-done");const i=t.session===u&&(t.agentId??null)===g;t.state==="working"?e.classList.add("working"):i&&t.doneUntil&&Date.now()<t.doneUntil?(e.classList.add("just-done"),_.set(n,setTimeout(()=>{e.classList.remove("just-done"),_.delete(n)},Math.max(0,t.doneUntil-Date.now())))):!i&&t.unread&&e.classList.add("just-done")}function Ee(){for(const[e,n]of $){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=r.querySelector(t);s&&fe(s,e,n)}}function Rt(e,n){const t=Le(e,n),s=$.get(t);if(!s)return;const i=_.get(t);i&&(clearTimeout(i),_.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=r.querySelector(o);a&&fe(a,t,s)}function Ye(){if(V||we)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);V=s,s.onmessage=i=>{try{const o=JSON.parse(String(i.data));o&&o.type==="session.activity"&&typeof o.session=="string"&&Ht(o.session,o.agentId||void 0,o.state==="working"?"working":"idle")}catch{}},s.onclose=()=>{V===s&&(V=null,we=setTimeout(()=>{we=null,Ye()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{V=null}}window.__openSession=U,window.__refreshSidebar=I,I(),X(),Ee(),Ye(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Ee()}),setInterval(()=>{document.visibilityState==="visible"&&I()},1e4),Ze();
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import{chmodSync as he,existsSync as G,readdirSync as ge,statSync as ye}from"node:fs";import{createRequire as V}from"node:module";import{hostname as U,networkInterfaces as ke}from"node:os";const ve=V(import.meta.url),{version:Te}=ve("../package.json");import $ from"node:path";import{fileURLToPath as _e}from"node:url";import{serve as we}from"@hono/node-server";import{WebSocketServer as Se,WebSocket as E}from"ws";try{const e=$.dirname(V(import.meta.url).resolve("node-pty/package.json")),t=$.join(e,"prebuilds");if(G(t))for(const o of ge(t)){const n=$.join(t,o,"spawn-helper");G(n)&&!(ye(n).mode&73)&&he(n,493)}}catch{}import{loadSecurityConfig as Ae}from"./lib/security-config.js";import{TokenStore as Ce,hashPassword as be,verifyPassword as xe,validatePassword as Ie}from"./lib/auth.js";import{RateLimiter as Pe}from"./lib/rateLimiter.js";import{audit as d}from"./lib/auditLog.js";import{db as N}from"./lib/db.js";import{handleClientMessage as X}from"./lib/ws-message.js";import{loadDotEnv as Re}from"./lib/load-env.js";import{listSessions as Me,resolveTmuxSocketPath as Oe}from"./sessions.js";import{cmdSetup as $e,cmdTheme as Ne,printUsage as Y,printVersion as Le}from"./lib/cli.js";import{readSettings as Ue}from"./lib/settings.js";import{readActiveTheme as Ee}from"./lib/theme-store.js";import{buildApp as K}from"./lib/build-app.js";import{attachTerminal as Fe,killAllAttachedPtys as je}from"./lib/attach-terminal.js";import{acquireControlClient as Q,killAllControlClients as He}from"./lib/tmux-control.js";import{getSessionPaneTarget as Z,capturePaneTail as q,capturePaneHistoryChunk as ee,toCrlf as te}from"./lib/tmux-capture.js";import{readTerminalBufferConfig as Be}from"./lib/terminal-config.js";import{AgentRegistry as We}from"./lib/agent-registry.js";import{AgentChannel as Je,MAX_RELAY_CONNS_PER_AGENT as De}from"./lib/agent-relay.js";import{findAgentTokenByPlaintext as ze,listAgentTokens as Ge}from"./lib/agent-tokens.js";import{saveSecurityConfig as Ve}from"./lib/security-config.js";import{readFederationConfig as Xe,writeFederationConfig as Ye}from"./lib/federation-config.js";import{startAgentClient as Ke}from"./lib/agent-client.js";import{ActivityProbe as Qe}from"./lib/activity-probe.js";import{upsertSessionState as ne}from"./lib/session-state.js";import{sessionWorkingPath as Ze}from"./lib/sessions-sidebar.js";Re();const F=Be(),g=Ae(),v=new Ce,A=new Pe;let J=!1;const qe="tmux-web-token";function j(e){if(g.security.trustProxy){const t=(e.headers["x-forwarded-for"]||"").split(",")[0].trim();if(t)return t}return e.socket.remoteAddress||"unknown"}function H(e){const t=e.headers.authorization;if(typeof t=="string"&&t.startsWith("Bearer "))return t.slice(7);const o=e.headers.cookie;if(typeof o!="string")return null;const n=o.match(new RegExp(`(?:^|;\\s*)${qe}=([^;]+)`));return n?decodeURIComponent(n[1]):null}function Vt(e){const t=H(e);return t?v.validateToken(t):null}const R=new Map;function et(e){let t=0;for(const o of R.values())o.ip===e&&t++;return t}function b(e,t,o){try{e.close(t,o)}catch{}}function oe(e,t){e.readyState===E.OPEN&&e.send(JSON.stringify(t))}const re=process.argv.slice(2),L=re;if(L.length>0){const[e,t]=L;switch(e){case"setup":await $e(L),process.exit(0);case"theme":await Ne(L.slice(1)),process.exit(0);case"agent":{const o=$.join($.dirname(_e(import.meta.url)),"agent.js"),{spawn:n}=await import("node:child_process"),f=n(process.execPath,[o,...re],{stdio:"inherit"});f.on("error",s=>{console.error(s),process.exit(1)}),f.on("exit",s=>process.exit(s??0)),await new Promise(()=>{})}case"agent-token":await pt(L.slice(1)),process.exit(0);case"help":case"--help":case"-h":Y(),process.exit(0);case"-V":case"--version":case"-v":Le(),process.exit(0);default:console.error(`unknown argument: ${e}`),Y(),process.exit(1)}}function P(e,t){e.readyState===E.OPEN&&e.send(JSON.stringify(t))}const se=new Set;await N.read(),N.data.sessionAccess??=[],N.data.pinnedViews??=[],N.data.watchedPanes??=[],N.data.quickCommands??=[];const ae=await Ue();let tt=await Ee();const k=new We({onChange:()=>{}}),_=new Map;function ie(e){return k.get(e)?_.get(e)??null:null}const ce={activeTheme:tt,settingUpPassword:!1},nt=K({mode:"hub",securityConfig:g,tokenStore:v,rateLimiter:A,settings:ae,terminalBufferConfig:F,state:ce,federation:{getConfig:()=>x,setConfig:async e=>{x=e,await Ye(e),ue(e)},status:rt,hostname:U()},hub:{agents:k,getChannel:ie}}),ot=K({mode:"agent",securityConfig:g,tokenStore:v,rateLimiter:A,settings:ae,terminalBufferConfig:F,state:ce});let x=await Xe(),M=null;function le(){M&&(M.stop(),M=null)}function ue(e){le(),!(!e.enabled||!e.hub||!e.token)&&(M=Ke({hub:e.hub,token:e.token,name:e.name?.trim()||U(),version:Te,app:ot,listSessions:Me,terminalBufferConfig:F,getSessionPaneTarget:Z,capturePaneTail:q,capturePaneHistoryChunk:ee,toCrlf:te,handleClientMessage:X,acquireControlClient:Q}))}function rt(){return x.enabled?M?M.status():{state:"idle",agentId:null,hub:x.hub??"",name:x.name??U()}:{state:"idle",agentId:null,hub:x.hub??"",name:x.name??U()}}ue(x);const D=new Qe,B=new Map;setInterval(()=>{(async()=>{try{const e=await D.scan(),t=[];for(const[o,n]of e)B.get(o)!==n&&t.push({session:o,state:n});for(const o of B.keys())e.has(o)||t.push({session:o,state:"idle"});B.clear();for(const[o,n]of e)B.set(o,n);for(const o of t)de({type:"session.activity",session:o.session,state:o.state})}catch{}})()},D.scanMs);const st=parseInt(process.env.PORT||"21000",10);function at(){const e=[];try{for(const t of Object.values(ke()))for(const o of t??[])o.family==="IPv4"&&!o.internal&&e.push(o.address)}catch{}return e}const it=we({fetch:nt.fetch,port:st,hostname:"0.0.0.0"},e=>{console.log(`tmux-web running at http://localhost:${e.port}`);for(const t of at())console.log(` also on http://${t}:${e.port}`)}),O=new Se({noServer:!0}),z=new Set;function de(e){const t=JSON.stringify(e);for(const o of z)o.readyState===E.OPEN&&o.send(t)}function I(e,t,o){e.write(`HTTP/1.1 ${t} ${o}\r
2
+ import{chmodSync as he,existsSync as G,readdirSync as ge,statSync as ye}from"node:fs";import{createRequire as V}from"node:module";import{hostname as E,networkInterfaces as ke}from"node:os";const Te=V(import.meta.url),{version:ve}=Te("../package.json");import O from"node:path";import{fileURLToPath as we}from"node:url";import{serve as _e}from"@hono/node-server";import{WebSocketServer as Se,WebSocket as F}from"ws";try{const e=O.dirname(V(import.meta.url).resolve("node-pty/package.json")),t=O.join(e,"prebuilds");if(G(t))for(const o of ge(t)){const n=O.join(t,o,"spawn-helper");G(n)&&!(ye(n).mode&73)&&he(n,493)}}catch{}import{loadSecurityConfig as Ae}from"./lib/security-config.js";import{TokenStore as Ce,hashPassword as be,verifyPassword as Ie,validatePassword as xe}from"./lib/auth.js";import{RateLimiter as Pe}from"./lib/rateLimiter.js";import{audit as d}from"./lib/auditLog.js";import{db as U}from"./lib/db.js";import{handleClientMessage as X}from"./lib/ws-message.js";import{loadDotEnv as Re}from"./lib/load-env.js";import{listSessions as Me,resolveTmuxSocketPath as $e}from"./sessions.js";import{cmdSetup as Oe,cmdTheme as Ue,printUsage as Y,printVersion as Ne}from"./lib/cli.js";import{readSettings as Le}from"./lib/settings.js";import{readActiveTheme as Ee}from"./lib/theme-store.js";import{buildApp as K}from"./lib/build-app.js";import{getBotManager as Fe}from"./lib/bots/manager.js";import{attachTerminal as je,killAllAttachedPtys as He}from"./lib/attach-terminal.js";import{acquireControlClient as Q,killAllControlClients as Be}from"./lib/tmux-control.js";import{getSessionPaneTarget as Z,capturePaneTail as q,capturePaneHistoryChunk as ee,toCrlf as te}from"./lib/tmux-capture.js";import{readTerminalBufferConfig as We}from"./lib/terminal-config.js";import{AgentRegistry as Je}from"./lib/agent-registry.js";import{AgentChannel as ze,MAX_RELAY_CONNS_PER_AGENT as De}from"./lib/agent-relay.js";import{findAgentTokenByPlaintext as Ge,listAgentTokens as Ve}from"./lib/agent-tokens.js";import{saveSecurityConfig as Xe}from"./lib/security-config.js";import{readFederationConfig as Ye,writeFederationConfig as Ke}from"./lib/federation-config.js";import{startAgentClient as Qe}from"./lib/agent-client.js";import{ActivityProbe as Ze}from"./lib/activity-probe.js";import{upsertSessionState as ne}from"./lib/session-state.js";import{sessionWorkingPath as qe}from"./lib/sessions-sidebar.js";Re();const j=We(),g=Ae(),T=new Ce,S=new Pe;let J=!1;const et="tmux-web-token";function H(e){if(g.security.trustProxy){const t=(e.headers["x-forwarded-for"]||"").split(",")[0].trim();if(t)return t}return e.socket.remoteAddress||"unknown"}function N(e){const t=e.headers.authorization;if(typeof t=="string"&&t.startsWith("Bearer "))return t.slice(7);const o=e.headers.cookie;if(typeof o!="string")return null;const n=o.match(new RegExp(`(?:^|;\\s*)${et}=([^;]+)`));return n?decodeURIComponent(n[1]):null}function Yt(e){const t=N(e);return t?T.validateToken(t):null}const M=new Map;function tt(e){let t=0;for(const o of M.values())o.ip===e&&t++;return t}function b(e,t,o){try{e.close(t,o)}catch{}}function oe(e,t){e.readyState===F.OPEN&&e.send(JSON.stringify(t))}const re=process.argv.slice(2),L=re;if(L.length>0){const[e,t]=L;switch(e){case"setup":await Oe(L),process.exit(0);case"theme":await Ue(L.slice(1)),process.exit(0);case"agent":{const o=O.join(O.dirname(we(import.meta.url)),"agent.js"),{spawn:n}=await import("node:child_process"),l=n(process.execPath,[o,...re],{stdio:"inherit"});l.on("error",a=>{console.error(a),process.exit(1)}),l.on("exit",a=>process.exit(a??0)),await new Promise(()=>{})}case"agent-token":await ht(L.slice(1)),process.exit(0);case"help":case"--help":case"-h":Y(),process.exit(0);case"-V":case"--version":case"-v":Ne(),process.exit(0);default:console.error(`unknown argument: ${e}`),Y(),process.exit(1)}}function P(e,t){e.readyState===F.OPEN&&e.send(JSON.stringify(t))}const se=new Set;await U.read(),U.data.sessionAccess??=[],U.data.pinnedViews??=[],U.data.watchedPanes??=[],U.data.quickCommands??=[];const ae=await Le();let nt=await Ee();const k=new Je({onChange:()=>{}}),w=new Map;function ie(e){return k.get(e)?w.get(e)??null:null}const ce={activeTheme:nt,settingUpPassword:!1},ot=K({mode:"hub",securityConfig:g,tokenStore:T,rateLimiter:S,settings:ae,terminalBufferConfig:j,state:ce,federation:{getConfig:()=>x,setConfig:async e=>{x=e,await Ke(e),ue(e)},status:st,hostname:E()},hub:{agents:k,getChannel:ie}}),rt=K({mode:"agent",securityConfig:g,tokenStore:T,rateLimiter:S,settings:ae,terminalBufferConfig:j,state:ce});let x=await Ye(),$=null;function le(){$&&($.stop(),$=null)}function ue(e){le(),!(!e.enabled||!e.hub||!e.token)&&($=Qe({hub:e.hub,token:e.token,name:e.name?.trim()||E(),version:ve,app:rt,listSessions:Me,terminalBufferConfig:j,getSessionPaneTarget:Z,capturePaneTail:q,capturePaneHistoryChunk:ee,toCrlf:te,handleClientMessage:X,acquireControlClient:Q}))}function st(){return x.enabled?$?$.status():{state:"idle",agentId:null,hub:x.hub??"",name:x.name??E()}:{state:"idle",agentId:null,hub:x.hub??"",name:x.name??E()}}ue(x);const z=new Ze,B=new Map;setInterval(()=>{(async()=>{try{const e=await z.scan(),t=[];for(const[o,n]of e)B.get(o)!==n&&t.push({session:o,state:n});for(const o of B.keys())e.has(o)||t.push({session:o,state:"idle"});B.clear();for(const[o,n]of e)B.set(o,n);for(const o of t)de({type:"session.activity",session:o.session,state:o.state})}catch{}})()},z.scanMs);const at=parseInt(process.env.PORT||"21000",10);function it(){const e=[];try{for(const t of Object.values(ke()))for(const o of t??[])o.family==="IPv4"&&!o.internal&&e.push(o.address)}catch{}return e}const ct=_e({fetch:ot.fetch,port:at,hostname:"0.0.0.0"},e=>{console.log(`tmux-web running at http://localhost:${e.port}`);for(const t of it())console.log(` also on http://${t}:${e.port}`)}),R=new Se({noServer:!0}),D=new Set;function de(e){const t=JSON.stringify(e);for(const o of D)o.readyState===F.OPEN&&o.send(t)}function I(e,t,o){e.write(`HTTP/1.1 ${t} ${o}\r
3
3
  \r
4
- `),e.destroy()}it.on("upgrade",(e,t,o)=>{const n=new URL(e.url||"/",`http://${e.headers.host}`),f=n.pathname;if(f==="/ws/activity"){const w=j(e),a=H(e)||n.searchParams.get("token")||"";if(!(a?v.validateToken(a):null)){I(t,401,"Unauthorized");return}O.handleUpgrade(e,t,o,c=>{c.on("close",()=>z.delete(c)),z.add(c)});return}if(f==="/agent/ws"){dt(e,t,o);return}const s=f.match(/^\/ws\/a\/([^/]+)\/(.+)$/);if(s){ct(e,t,o,decodeURIComponent(s[1]),decodeURIComponent(s[2]));return}const i=f.match(/^\/ws\/(.+)$/);if(!i){t.destroy();return}const l=j(e),u=e.headers.origin,p=g.security.allowedOrigins;if(u&&!(u===`http://${e.headers.host}`||u===`https://${e.headers.host}`)&&(p.length===0||!p.includes(u))){d("ws_rejected_origin",{ip:l,origin:u}),I(t,403,"Origin not allowed");return}const m=et(l);if(m>=g.security.maxConnectionsPerIp){d("ws_rejected_per_ip_cap",{ip:l,liveFromIp:m}),I(t,429,"Too many connections");return}const y=H(e)||n.searchParams.get("token")||"",T=y?v.validateToken(y):null;O.handleUpgrade(e,t,o,w=>{O.emit("connection",w,e,decodeURIComponent(i[1]),l,T)})}),O.on("connection",(e,t,o,n,f)=>{const s={ws:e,ip:n,authenticated:!1,authTimeout:null},i=(()=>{try{const a=new URL(t.url||"/",`http://${t.headers.host}`).searchParams,r=Number(a.get("cols")),c=Number(a.get("rows"));if(Number.isInteger(r)&&Number.isInteger(c)&&r>0&&c>0&&r<=1e3&&c<=1e3)return{cols:r,rows:c}}catch{}})();R.set(e,s),d("ws_connected",{ip:n});let l=null,u=null;function p(a,r){s.authenticated=!0,s.authTimeout&&(clearTimeout(s.authTimeout),s.authTimeout=null),d("auth_success",{ip:n,method:a,tokenName:r}),P(e,{type:"auth.ok",setupMode:!g.passwordHash}),y()}function m(a,r={}){P(e,{type:"auth.failed",message:a,...r})}function y(){l||(D.suppress(o),ne(o,{path:Ze(o)}),l=Fe(o,{send:a=>P(e,a),onMessage:a=>{u=a},onClose:a=>{T=a}},{terminalBufferConfig:F,getSessionPaneTarget:Z,capturePaneTail:q,capturePaneHistoryChunk:ee,toCrlf:te,handleClientMessage:X,acquireControlClient:Q,initialCols:i?.cols,initialRows:i?.rows,tmuxSocketPath:Oe()??void 0,onPtyExit:(a,r)=>b(e,1e3,"pty exited"),onSpawnError:(a,r)=>b(e,1011,"pty spawn failed")}))}let T=null;async function w(a){let r;try{r=JSON.parse(a)}catch{return!1}if(r.type==="auth.token"&&typeof r.token=="string"){const c=v.validateToken(r.token);if(!c){d("token_auth_failed",{ip:n});const h=A.recordFailure(n);return h.permanentLock&&(v.revokeAll(),d("permanent_lock",{ip:n,failures:h.failures})),m("Invalid or expired token",{permanentLock:h.permanentLock,retryAfterMs:h.retryAfterMs}),!0}return v.touch(c.tokenHash),p("token",c.name),!0}if(r.type==="auth"&&typeof r.password=="string"){const c=A.check(n);if(!c.allowed)return d("rate_limited",{ip:n,retryAfterMs:c.retryAfterMs,permanentLock:c.permanentLock}),m("Too many attempts",{permanentLock:c.permanentLock,retryAfterMs:c.retryAfterMs}),!0;if(!g.passwordHash){if(!g.security.allowRemoteSetup&&!mt(n))return d("setup_rejected_remote",{ip:n}),m("First-run setup must be performed from localhost"),!0;if(J)return m("Password setup in progress"),!0;const C=Ie(r.password);if(C)return m(C),!0;J=!0;try{g.passwordHash=await be(r.password),Ve(g),d("password_set",{ip:n})}finally{J=!1}const{stored:W,plaintext:pe}=v.createAccessToken("setup",g.security.tokenTtlDays);return P(e,{type:"auth.ok",setupMode:!0,token:pe}),d("token_created",{ip:n,name:W.name,tokenId:W.id}),d("auth_success",{ip:n,method:"password",tokenName:W.name}),y(),!0}if(!g.passwordHash)return m("Server not configured"),!0;if(!await xe(r.password,g.passwordHash)){const C=A.recordFailure(n);return d("auth_failed",{ip:n,method:"password",failures:C.failures,permanentLock:C.permanentLock}),C.permanentLock&&(v.revokeAll(),d("permanent_lock",{ip:n,failures:C.failures})),m("Incorrect password",{permanentLock:C.permanentLock,retryAfterMs:C.retryAfterMs}),!0}A.recordSuccess(n);const S=`ws-${n}`,{plaintext:me}=v.createAccessToken(S,g.security.tokenTtlDays);return p("password",S),P(e,{type:"auth.ok",setupMode:!1,token:me}),!0}return!1}f?(v.touch(f.tokenHash),p("token",f.name)):(P(e,{type:"auth.required",setupMode:!g.passwordHash}),s.authTimeout=setTimeout(()=>{s.authenticated||(d("auth_timeout",{ip:n}),m("Authentication timeout"),b(e,4e3,"Auth timeout"))},g.security.authTimeoutMs)),e.on("message",async a=>{const r=typeof a=="string"?a:a.toString("utf-8");if(!s.authenticated){if(r.length>1e6){P(e,{type:"auth.failed",message:"Message too large"});return}await w(r)||m("Authentication required");return}if(u)try{u(r)}catch{}}),e.on("close",()=>{s.authTimeout&&clearTimeout(s.authTimeout),R.delete(e),d("ws_disconnected",{ip:n}),T?.(),l&&(l.dispose(),l=null)}),e.on("error",()=>{s.authTimeout&&clearTimeout(s.authTimeout),R.delete(e),T?.(),l&&(l.dispose(),l=null)})});function ct(e,t,o,n,f){const s=j(e),i=new URL(e.url||"/",`http://${e.headers.host}`),l=H(e)||i.searchParams.get("token")||"";if(!(l?v.validateToken(l):null)){d("ws_rejected_remote_auth",{ip:s,agentId:n}),I(t,401,"Unauthorized");return}const p=ie(n);if(!p){d("ws_rejected_remote_offline",{ip:s,agentId:n}),I(t,503,"Agent offline");return}if(p.relayCount>=De){I(t,429,"Too many connections to agent");return}const m=e.headers.origin,y=g.security.allowedOrigins;if(m&&!(m===`http://${e.headers.host}`||m===`https://${e.headers.host}`)&&(y.length===0||!y.includes(m))){I(t,403,"Origin not allowed");return}const T=ut(),w=(()=>{try{const a=new URL(e.url||"/",`http://${e.headers.host}`).searchParams,r=Number(a.get("cols")),c=Number(a.get("rows"));if(Number.isInteger(r)&&Number.isInteger(c)&&r>0&&c>0&&r<=1e3&&c<=1e3)return{cols:r,rows:c}}catch{}})();O.handleUpgrade(e,t,o,a=>{if(p.registerRelay(T,f,a),k.bumpRelayConns(n,1),ne(f,{agentId:n}),!p.attach(T,f,w)){a.send(JSON.stringify({type:"data",data:`\r
4
+ `),e.destroy()}ct.on("upgrade",(e,t,o)=>{const n=new URL(e.url||"/",`http://${e.headers.host}`),l=n.pathname;if(l==="/ws/activity"){const s=H(e),r=N(e)||n.searchParams.get("token")||"";if(!(r?T.validateToken(r):null)){I(t,401,"Unauthorized");return}R.handleUpgrade(e,t,o,m=>{m.on("close",()=>D.delete(m)),D.add(m)});return}const a=l.match(/^\/ws\/bots\/([^/]+)$/);if(a){const s=N(e)||n.searchParams.get("token")||"";if(!(s?T.validateToken(s):null)){I(t,401,"Unauthorized");return}const c=decodeURIComponent(a[1]);R.handleUpgrade(e,t,o,m=>{Fe().attachSocket(c,m)});return}if(l==="/agent/ws"){ft(e,t,o);return}const i=l.match(/^\/ws\/a\/([^/]+)\/(.+)$/);if(i){lt(e,t,o,decodeURIComponent(i[1]),decodeURIComponent(i[2]));return}const u=l.match(/^\/ws\/(.+)$/);if(!u){t.destroy();return}const f=H(e),p=e.headers.origin,h=g.security.allowedOrigins;if(p&&!(p===`http://${e.headers.host}`||p===`https://${e.headers.host}`)&&(h.length===0||!h.includes(p))){d("ws_rejected_origin",{ip:f,origin:p}),I(t,403,"Origin not allowed");return}const y=tt(f);if(y>=g.security.maxConnectionsPerIp){d("ws_rejected_per_ip_cap",{ip:f,liveFromIp:y}),I(t,429,"Too many connections");return}const v=N(e)||n.searchParams.get("token")||"",A=v?T.validateToken(v):null;R.handleUpgrade(e,t,o,s=>{R.emit("connection",s,e,decodeURIComponent(u[1]),f,A)})}),R.on("connection",(e,t,o,n,l)=>{const a={ws:e,ip:n,authenticated:!1,authTimeout:null},i=(()=>{try{const s=new URL(t.url||"/",`http://${t.headers.host}`).searchParams,r=Number(s.get("cols")),c=Number(s.get("rows"));if(Number.isInteger(r)&&Number.isInteger(c)&&r>0&&c>0&&r<=1e3&&c<=1e3)return{cols:r,rows:c}}catch{}})();M.set(e,a),d("ws_connected",{ip:n});let u=null,f=null;function p(s,r){a.authenticated=!0,a.authTimeout&&(clearTimeout(a.authTimeout),a.authTimeout=null),d("auth_success",{ip:n,method:s,tokenName:r}),P(e,{type:"auth.ok",setupMode:!g.passwordHash}),y()}function h(s,r={}){P(e,{type:"auth.failed",message:s,...r})}function y(){u||(z.suppress(o),ne(o,{path:qe(o)}),u=je(o,{send:s=>P(e,s),onMessage:s=>{f=s},onClose:s=>{v=s}},{terminalBufferConfig:j,getSessionPaneTarget:Z,capturePaneTail:q,capturePaneHistoryChunk:ee,toCrlf:te,handleClientMessage:X,acquireControlClient:Q,initialCols:i?.cols,initialRows:i?.rows,tmuxSocketPath:$e()??void 0,onPtyExit:(s,r)=>b(e,1e3,"pty exited"),onSpawnError:(s,r)=>b(e,1011,"pty spawn failed")}))}let v=null;async function A(s){let r;try{r=JSON.parse(s)}catch{return!1}if(r.type==="auth.token"&&typeof r.token=="string"){const c=T.validateToken(r.token);if(!c){d("token_auth_failed",{ip:n});const m=S.recordFailure(n);return m.permanentLock&&(T.revokeAll(),d("permanent_lock",{ip:n,failures:m.failures})),h("Invalid or expired token",{permanentLock:m.permanentLock,retryAfterMs:m.retryAfterMs}),!0}return T.touch(c.tokenHash),p("token",c.name),!0}if(r.type==="auth"&&typeof r.password=="string"){const c=S.check(n);if(!c.allowed)return d("rate_limited",{ip:n,retryAfterMs:c.retryAfterMs,permanentLock:c.permanentLock}),h("Too many attempts",{permanentLock:c.permanentLock,retryAfterMs:c.retryAfterMs}),!0;if(!g.passwordHash){if(!g.security.allowRemoteSetup&&!pt(n))return d("setup_rejected_remote",{ip:n}),h("First-run setup must be performed from localhost"),!0;if(J)return h("Password setup in progress"),!0;const C=xe(r.password);if(C)return h(C),!0;J=!0;try{g.passwordHash=await be(r.password),Xe(g),d("password_set",{ip:n})}finally{J=!1}const{stored:W,plaintext:pe}=T.createAccessToken("setup",g.security.tokenTtlDays);return P(e,{type:"auth.ok",setupMode:!0,token:pe}),d("token_created",{ip:n,name:W.name,tokenId:W.id}),d("auth_success",{ip:n,method:"password",tokenName:W.name}),y(),!0}if(!g.passwordHash)return h("Server not configured"),!0;if(!await Ie(r.password,g.passwordHash)){const C=S.recordFailure(n);return d("auth_failed",{ip:n,method:"password",failures:C.failures,permanentLock:C.permanentLock}),C.permanentLock&&(T.revokeAll(),d("permanent_lock",{ip:n,failures:C.failures})),h("Incorrect password",{permanentLock:C.permanentLock,retryAfterMs:C.retryAfterMs}),!0}S.recordSuccess(n);const _=`ws-${n}`,{plaintext:me}=T.createAccessToken(_,g.security.tokenTtlDays);return p("password",_),P(e,{type:"auth.ok",setupMode:!1,token:me}),!0}return!1}l?(T.touch(l.tokenHash),p("token",l.name)):(P(e,{type:"auth.required",setupMode:!g.passwordHash}),a.authTimeout=setTimeout(()=>{a.authenticated||(d("auth_timeout",{ip:n}),h("Authentication timeout"),b(e,4e3,"Auth timeout"))},g.security.authTimeoutMs)),e.on("message",async s=>{const r=typeof s=="string"?s:s.toString("utf-8");if(!a.authenticated){if(r.length>1e6){P(e,{type:"auth.failed",message:"Message too large"});return}await A(r)||h("Authentication required");return}if(f)try{f(r)}catch{}}),e.on("close",()=>{a.authTimeout&&clearTimeout(a.authTimeout),M.delete(e),d("ws_disconnected",{ip:n}),v?.(),u&&(u.dispose(),u=null)}),e.on("error",()=>{a.authTimeout&&clearTimeout(a.authTimeout),M.delete(e),v?.(),u&&(u.dispose(),u=null)})});function lt(e,t,o,n,l){const a=H(e),i=new URL(e.url||"/",`http://${e.headers.host}`),u=N(e)||i.searchParams.get("token")||"";if(!(u?T.validateToken(u):null)){d("ws_rejected_remote_auth",{ip:a,agentId:n}),I(t,401,"Unauthorized");return}const p=ie(n);if(!p){d("ws_rejected_remote_offline",{ip:a,agentId:n}),I(t,503,"Agent offline");return}if(p.relayCount>=De){I(t,429,"Too many connections to agent");return}const h=e.headers.origin,y=g.security.allowedOrigins;if(h&&!(h===`http://${e.headers.host}`||h===`https://${e.headers.host}`)&&(y.length===0||!y.includes(h))){I(t,403,"Origin not allowed");return}const v=dt(),A=(()=>{try{const s=new URL(e.url||"/",`http://${e.headers.host}`).searchParams,r=Number(s.get("cols")),c=Number(s.get("rows"));if(Number.isInteger(r)&&Number.isInteger(c)&&r>0&&c>0&&r<=1e3&&c<=1e3)return{cols:r,rows:c}}catch{}})();R.handleUpgrade(e,t,o,s=>{if(p.registerRelay(v,l,s),k.bumpRelayConns(n,1),ne(l,{agentId:n}),!p.attach(v,l,A)){s.send(JSON.stringify({type:"data",data:`\r
5
5
  \x1B[31magent offline\x1B[0m\r
6
- `})),a.close(1011,"agent offline"),p.relayClosed(T),k.bumpRelayConns(n,-1);return}a.on("message",c=>{const h=typeof c=="string"?c:c.toString("utf-8");let S;try{S=JSON.parse(h)}catch{return}(S.type==="input"||S.type==="resize"||S.type==="load_history")&&p.sendToAgent(T,S)});const r=()=>{p.relayClosed(T),k.bumpRelayConns(n,-1)};a.on("close",r),a.on("error",r)})}let lt=1;function ut(){return lt++}function dt(e,t,o){const n=j(e),f=e.headers.origin;if(f){d("agent_rejected_origin",{ip:n,origin:f}),I(t,403,"Origin not allowed");return}O.handleUpgrade(e,t,o,s=>{let i=null,l=setTimeout(()=>{d("agent_hello_timeout",{ip:n}),b(s,4e3,"hello timeout")},1e4);s.on("message",(u,p)=>{if(i){k.touch(i.agentId),p?i.handleData(Array.isArray(u)?Buffer.concat(u):Buffer.from(u)):i.handleMessage(typeof u=="string"?u:Buffer.from(u).toString("utf-8"));return}const m=typeof u=="string"?u:u.toString("utf-8");let y;try{y=JSON.parse(m)}catch{b(s,1008,"bad hello");return}if(y.type!=="hello"||typeof y.token!="string"){b(s,1008,"expected hello");return}if(!A.check(n).allowed){d("agent_rate_limited",{ip:n}),b(s,429,"Too many attempts");return}const w=ze(y.token);if(!w){A.recordFailure(n),d("agent_bad_token",{ip:n}),oe(s,{type:"hello_err",reason:"invalid token"}),b(s,4003,"invalid token");return}const a=typeof y.name=="string"&&y.name.trim()?y.name.trim().slice(0,64):"agent",r=w.id;if(!k.register(r,a,s,w.tokenHash)){d("agent_cap_reached",{ip:n}),oe(s,{type:"hello_err",reason:"too many agents"}),b(s,4004,"too many agents");return}clearTimeout(l),A.recordSuccess(n),d("agent_connected",{ip:n,agentId:r,name:a}),i=new Je(s,r,{onSessions:h=>k.setSessions(r,h),onActivity:h=>{for(const S of h)de({type:"session.activity",agentId:r,session:S.session,state:S.state})},onRebuildResult:h=>{console.log(`[agent ${r}] rebuild ${h.session}: ${h.ok?"ok":h.message}`)},onClose:h=>{_.get(r)===h&&_.delete(r)}}),_.set(r,i),k.touch(r),s.send(JSON.stringify({type:"hello_ok",agentId:r})),i.sendSessionsReq()}),s.on("close",()=>{i&&(i.dispose(),_.delete(i.agentId),k.unregister(i.agentId),d("agent_disconnected",{ip:n,agentId:i.agentId})),clearTimeout(l)}),s.on("error",()=>{i&&(i.dispose(),_.delete(i.agentId),k.unregister(i.agentId)),clearTimeout(l)})})}const ft=parseInt(process.env.TMUX_WEB_AGENT_OFFLINE_MS||"45000",10);setInterval(()=>{const e=k.pruneOffline(ft);for(const o of e){const n=k.peek(o);n&&n.ws.readyState===E.CLOSED&&(k.unregister(o),_.get(o)?.dispose(),_.delete(o))}const t=new Set(Ge().map(o=>o.tokenHash));for(const[o,n]of _){const f=k.peek(o);if(!(!f||t.has(f.tokenHash))){d("agent_token_revoked",{agentId:o}),n.dispose(),_.delete(o),k.unregister(o);try{f.ws.close(4003,"token revoked")}catch{}}}v.purgeExpired()},10*1e3).unref();function fe(){le(),He(),je();for(const e of _.values())e.dispose();_.clear();for(const[e,t]of R){try{e.close(1001,"Server shutting down")}catch{}t.authTimeout&&clearTimeout(t.authTimeout)}R.clear();for(const e of se)try{e.kill()}catch{}se.clear(),A.dispose(),process.exit(0)}process.on("SIGINT",fe),process.on("SIGTERM",fe);function mt(e){return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}async function pt(e){const{createAgentToken:t,listAgentTokens:o,removeAgentToken:n}=await import("./lib/agent-tokens.js"),[f,...s]=e;switch(f){case"add":{const i=s.find(p=>!p.startsWith("-"))||"agent",{id:l,token:u}=t(i);console.log("\u2713 agent token created"),console.log(` id: ${l}`),console.log(` name: ${i}`),console.log(` token: ${u}`),console.log(`
7
- Run on the remote machine:`),console.log(` tmux-web agent --hub wss://YOUR_HUB --token ${u} --name "${i}"`);return}case"list":{const i=o();if(!i.length){console.log("No agent tokens. Create one with: tmux-web agent-token add --name <name>");return}console.log("Agent tokens:");for(const l of i)console.log(` ${l.id} ${l.name} (created ${new Date(l.createdAt).toISOString()})`);return}case"remove":{const i=s.find(u=>!u.startsWith("-"));i||(console.error("usage: tmux-web agent-token remove <id>"),process.exit(1)),n(i)||(console.error(`no token with id ${i}`),process.exit(1)),console.log(`\u2713 token ${i} removed`);return}default:console.error("usage: tmux-web agent-token <add|list|remove>"),process.exit(1)}}
6
+ `})),s.close(1011,"agent offline"),p.relayClosed(v),k.bumpRelayConns(n,-1);return}s.on("message",c=>{const m=typeof c=="string"?c:c.toString("utf-8");let _;try{_=JSON.parse(m)}catch{return}(_.type==="input"||_.type==="resize"||_.type==="load_history")&&p.sendToAgent(v,_)});const r=()=>{p.relayClosed(v),k.bumpRelayConns(n,-1)};s.on("close",r),s.on("error",r)})}let ut=1;function dt(){return ut++}function ft(e,t,o){const n=H(e),l=e.headers.origin;if(l){d("agent_rejected_origin",{ip:n,origin:l}),I(t,403,"Origin not allowed");return}R.handleUpgrade(e,t,o,a=>{let i=null,u=setTimeout(()=>{d("agent_hello_timeout",{ip:n}),b(a,4e3,"hello timeout")},1e4);a.on("message",(f,p)=>{if(i){k.touch(i.agentId),p?i.handleData(Array.isArray(f)?Buffer.concat(f):Buffer.from(f)):i.handleMessage(typeof f=="string"?f:Buffer.from(f).toString("utf-8"));return}const h=typeof f=="string"?f:f.toString("utf-8");let y;try{y=JSON.parse(h)}catch{b(a,1008,"bad hello");return}if(y.type!=="hello"||typeof y.token!="string"){b(a,1008,"expected hello");return}if(!S.check(n).allowed){d("agent_rate_limited",{ip:n}),b(a,429,"Too many attempts");return}const A=Ge(y.token);if(!A){S.recordFailure(n),d("agent_bad_token",{ip:n}),oe(a,{type:"hello_err",reason:"invalid token"}),b(a,4003,"invalid token");return}const s=typeof y.name=="string"&&y.name.trim()?y.name.trim().slice(0,64):"agent",r=A.id;if(!k.register(r,s,a,A.tokenHash)){d("agent_cap_reached",{ip:n}),oe(a,{type:"hello_err",reason:"too many agents"}),b(a,4004,"too many agents");return}clearTimeout(u),S.recordSuccess(n),d("agent_connected",{ip:n,agentId:r,name:s}),i=new ze(a,r,{onSessions:m=>k.setSessions(r,m),onActivity:m=>{for(const _ of m)de({type:"session.activity",agentId:r,session:_.session,state:_.state})},onRebuildResult:m=>{console.log(`[agent ${r}] rebuild ${m.session}: ${m.ok?"ok":m.message}`)},onClose:m=>{w.get(r)===m&&w.delete(r)}}),w.set(r,i),k.touch(r),a.send(JSON.stringify({type:"hello_ok",agentId:r})),i.sendSessionsReq()}),a.on("close",()=>{i&&(i.dispose(),w.delete(i.agentId),k.unregister(i.agentId),d("agent_disconnected",{ip:n,agentId:i.agentId})),clearTimeout(u)}),a.on("error",()=>{i&&(i.dispose(),w.delete(i.agentId),k.unregister(i.agentId)),clearTimeout(u)})})}const mt=parseInt(process.env.TMUX_WEB_AGENT_OFFLINE_MS||"45000",10);setInterval(()=>{const e=k.pruneOffline(mt);for(const o of e){const n=k.peek(o);n&&n.ws.readyState===F.CLOSED&&(k.unregister(o),w.get(o)?.dispose(),w.delete(o))}const t=new Set(Ve().map(o=>o.tokenHash));for(const[o,n]of w){const l=k.peek(o);if(!(!l||t.has(l.tokenHash))){d("agent_token_revoked",{agentId:o}),n.dispose(),w.delete(o),k.unregister(o);try{l.ws.close(4003,"token revoked")}catch{}}}T.purgeExpired()},10*1e3).unref();function fe(){le(),Be(),He();for(const e of w.values())e.dispose();w.clear();for(const[e,t]of M){try{e.close(1001,"Server shutting down")}catch{}t.authTimeout&&clearTimeout(t.authTimeout)}M.clear();for(const e of se)try{e.kill()}catch{}se.clear(),S.dispose(),process.exit(0)}process.on("SIGINT",fe),process.on("SIGTERM",fe);function pt(e){return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}async function ht(e){const{createAgentToken:t,listAgentTokens:o,removeAgentToken:n}=await import("./lib/agent-tokens.js"),[l,...a]=e;switch(l){case"add":{const i=a.find(p=>!p.startsWith("-"))||"agent",{id:u,token:f}=t(i);console.log("\u2713 agent token created"),console.log(` id: ${u}`),console.log(` name: ${i}`),console.log(` token: ${f}`),console.log(`
7
+ Run on the remote machine:`),console.log(` tmux-web agent --hub wss://YOUR_HUB --token ${f} --name "${i}"`);return}case"list":{const i=o();if(!i.length){console.log("No agent tokens. Create one with: tmux-web agent-token add --name <name>");return}console.log("Agent tokens:");for(const u of i)console.log(` ${u.id} ${u.name} (created ${new Date(u.createdAt).toISOString()})`);return}case"remove":{const i=a.find(f=>!f.startsWith("-"));i||(console.error("usage: tmux-web agent-token remove <id>"),process.exit(1)),n(i)||(console.error(`no token with id ${i}`),process.exit(1)),console.log(`\u2713 token ${i} removed`);return}default:console.error("usage: tmux-web agent-token <add|list|remove>"),process.exit(1)}}
@@ -0,0 +1,16 @@
1
+ import{existsSync as c,mkdirSync as p,readFileSync as l,readdirSync as d,statSync as b,writeFileSync as m}from"node:fs";import s from"node:path";import{execFile as y}from"node:child_process";import{getBotStore as u}from"./store.js";const g=["builtin:mcp","builtin:codemode","builtin:llama.cpp","builtin:tool-search"],S=["read","bash","powershell","edit","write","grep","find","ls","codemode","tool_search"],j=["bot_create","bot_list","bot_status","bot_message","bot_wait","bot_result","bot_stop","bot_approvals","bot_approve"],E=new Set(["read","grep","find","ls","tool_search"]),w=[{id:"code-review",name:"code-review",description:"Review a diff for correctness, regressions and missing tests before committing.",body:["# Code review","","When asked to review code:","1. Read the diff and the surrounding code, not just the changed lines.","2. Look for correctness bugs, unhandled errors, and behaviour changes that callers rely on.","3. Check for missing tests and for tests that would keep passing if the change were reverted.","4. Report findings as a short list: file, problem, why it matters, suggested fix.","5. Say explicitly when you found nothing."].join(`
2
+ `)},{id:"test-runner",name:"test-runner",description:"Find and run the right tests for a change, then summarise failures.",body:["# Test runner","","1. Identify the test command from the project (package.json, Makefile, pytest.ini, ...).","2. Prefer running the narrowest tests that cover the change first.","3. On failure, quote the failing assertion and the smallest reproducer.","4. Never claim tests pass without showing the command and its exit status."].join(`
3
+ `)}],x=[{id:"handoff",name:"handoff",body:`# Handoff
4
+
5
+ Summarise the current state so another agent can continue:
6
+ - what is done
7
+ - what is in progress (with file paths)
8
+ - what is blocked, and why
9
+ - the next concrete step
10
+ `}];function v(){const i=s.join(u().root,"library"),t=["skills","extensions","prompts","mcp"];for(const e of t)p(s.join(i,e),{recursive:!0,mode:448});for(const e of w){const o=s.join(i,"skills",e.id);p(o,{recursive:!0,mode:448});const a=s.join(o,"SKILL.md");c(a)||m(a,`---
11
+ name: ${e.name}
12
+ description: ${e.description}
13
+ ---
14
+
15
+ ${e.body}
16
+ `,{mode:384})}for(const e of x){const o=s.join(i,"prompts",`${e.id}.md`);c(o)||m(o,e.body,{mode:384})}const n=s.join(i,"mcp","filesystem.json");return c(n)||m(n,JSON.stringify({name:"filesystem",mcpServers:{filesystem:{command:"npx",args:["-y","@modelcontextprotocol/server-filesystem","."]}}},null,2),{mode:384}),i}function f(i){const t=/^---\r?\n([\s\S]*?)\r?\n---/.exec(i);if(!t)return{};const n={};for(const e of t[1].split(/\r?\n/)){const o=/^(name|description)\s*:\s*(.+)$/.exec(e.trim());o&&(n[o[1]]=o[2].replace(/^["']|["']$/g,"").trim())}return n}function k(i){const t=s.join(i,"skills"),n=[];if(!c(t))return n;for(const e of d(t)){const o=s.join(t,e),a=s.join(o,"SKILL.md");if(c(a)){const r=f(l(a,"utf8"));n.push({id:e,name:r.name||e,description:r.description||"",path:o});continue}if(e.endsWith(".md")&&b(o).isFile()){const r=f(l(o,"utf8"));n.push({id:e.replace(/\.md$/,""),name:r.name||e.replace(/\.md$/,""),description:r.description||"",path:o})}}return n.sort((e,o)=>e.name.localeCompare(o.name))}function _(i){const t=s.join(i,"extensions"),n=g.map(e=>({id:e,name:e,kind:"builtin",description:"Bundled with Pi; enable or disable per template."}));if(!c(t))return n;for(const e of d(t)){const o=s.join(t,e);if(e.endsWith(".js")||e.endsWith(".ts")){n.push({id:e,name:e.replace(/\.(js|ts)$/,""),kind:"bundled",path:o});continue}["index.ts","index.js"].map(r=>s.join(o,r)).find(r=>c(r))&&n.push({id:e,name:e,kind:"bundled",path:o})}return n.sort((e,o)=>e.name.localeCompare(o.name))}function O(i){const t=s.join(i,"prompts");return c(t)?d(t).filter(n=>n.endsWith(".md")).map(n=>({id:n.replace(/\.md$/,""),name:n.replace(/\.md$/,""),path:s.join(t,n)})).sort((n,e)=>n.name.localeCompare(e.name)):[]}function L(i){const t=s.join(i,"mcp");if(!c(t))return[];const n=[];for(const e of d(t))if(e.endsWith(".json"))try{const o=JSON.parse(l(s.join(t,e),"utf8"));n.push({id:e.replace(/\.json$/,""),name:o.name||e.replace(/\.json$/,""),servers:o.mcpServers||{}})}catch{}return n}function h(i,t,n=8e3){return new Promise(e=>{y(i,t,{timeout:n,env:process.env},(o,a)=>{e(o?null:String(a))})})}async function N(){const i=v(),t=await h("pi",["--version"]),n=t?t.trim().split(/\s+/)[0]:null;let e=[];const o=await h("pi",["--list-models"]);if(o)for(const a of o.split(/\r?\n/)){const r=/^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(yes|no)\s+(yes|no)\s*$/.exec(a.trim());r&&e.push({provider:r[1],model:r[2],context:r[3],thinking:r[5]==="yes",images:r[6]==="yes"})}return{version:n,models:e,skills:k(i),extensions:_(i),prompts:O(i),mcp:L(i),tools:[...S.map(a=>({name:a,source:"builtin"})),...j.map(a=>({name:a,source:"orchestration"}))]}}function R(i,t){if(t.startsWith("/")||t.startsWith("~")||t.startsWith("builtin:")||t.startsWith("-builtin:")||t.startsWith("+builtin:"))return t;const n=s.join(u().root,"library",i);return s.join(n,t)}export{g as BUILTIN_EXTENSIONS,S as BUILTIN_TOOLS,j as ORCHESTRATION_TOOLS,E as READONLY_TOOLS,N as buildCatalog,R as resolveResource};
@@ -0,0 +1 @@
1
+ import{execFileSync as f}from"node:child_process";import{mkdirSync as g,rmSync as v}from"node:fs";import u from"node:path";import{getBotStore as w}from"./store.js";import{materialize as I}from"./materialize.js";import{PiRpc as k}from"./rpc.js";import{buildCatalog as _,ORCHESTRATION_TOOLS as E,READONLY_TOOLS as T}from"./catalog.js";import{TERMINAL_STATUSES as l}from"./types.js";const d=4,y=8;class x{store=w();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())!l.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 _()}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>d)throw new Error(`nesting depth limit is ${d}`)}const r=u.resolve(t.projectPath||s?.projectPath||process.env.HOME||"/"),i=this.store.newId(),n=t.isolation||"shared";let o=r;if(n==="worktree"){const h=u.join(this.store.root,"worktrees",i);try{g(u.dirname(h),{recursive:!0,mode:448}),f("git",["-C",r,"worktree","add","-b",`tw-bot/${i.slice(0,8)}`,h],{timeout:2e4,stdio:"ignore"}),o=h}catch{o=r}}const a=new Date().toISOString(),p={id:i,templateId:e.id,title:t.title||e.manifest.name,projectPath:r,workspacePath:o,isolation:n,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:u.join(this.store.sessionsDir(i),`${i}.jsonl`),createdAt:a,updatedAt:a,model:e.manifest.model};return g(this.store.sessionsDir(i),{recursive:!0,mode:448}),this.store.saveInstance(p),this.emit(p.id,{type:"status",status:"queued",at:a}),this.pump(),p}activeInProject(t){return this.store.listInstances().filter(e=>e.projectPath===t&&!l.includes(e.status)&&e.status!=="queued").length}pump(){for(const t of this.store.listInstances())t.status==="queued"&&(this.activeInProject(t.projectPath)>=y||this.start(t))}start(t){const e=this.getTemplate(t.templateId);if(!e){this.setStatus(t.id,"failed","template disappeared");return}const s=I(e,t,{apiBase:this.apiBase,token:this.token}),r=e.manifest.binaryPath||"pi",i=new k({command:r,args:s.args,cwd:t.workspacePath,env:s.env,onEvent:n=>this.handleEvent(t.id,n),onStderr:n=>{/error|failed/i.test(n)&&this.emit(t.id,{type:"notice",level:"warn",text:n.slice(0,500),at:new Date().toISOString()})},onExit:()=>{this.runtimes.delete(t.id);const n=this.store.getInstance(t.id);n&&!l.includes(n.status)&&this.setStatus(t.id,"failed","pi exited unexpectedly"),this.pump()}});this.runtimes.set(t.id,i),t.status="starting",t.pid=void 0,this.store.saveInstance(t),this.emit(t.id,{type:"status",status:"starting",at:new Date().toISOString()}),i.start()}handleEvent(t,e){const s=String(e.type||""),r=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 i=e.message;if(i){if(s==="message_end"&&i.role==="assistant"){const n=this.store.getInstance(t),o=B(i);n&&o&&(n.lastText=o,this.store.saveInstance(n))}this.emit(t,{type:"message",message:i,at:r})}break}case"message_update":{const i=e.assistantMessageEvent;if(!i)break;const n=i.type==="text_delta"?"text":i.type==="thinking_delta"?"thinking":i.type==="toolcall_delta"?"tool-args":null;if(!n)break;const o=e.message;this.emit(t,{type:"delta",kind:n,delta:String(i.delta||""),contentIndex:typeof i.contentIndex=="number"?i.contentIndex:void 0,messageId:typeof o?.id=="string"?o.id:void 0,at:r});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:r});break;case"tool_execution_update":this.emit(t,{type:"tool",phase:"update",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:S(e.partialResult),at:r});break;case"tool_execution_end":this.emit(t,{type:"tool",phase:"end",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:S(e.result),isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,at:r});break;case"extension_ui_request":this.handleUiRequest(t,e);break;default:break}}handleUiRequest(t,e){const s=String(e.method||""),r=new Date().toISOString(),i=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:r});return}if(!["confirm","select","input","editor"].includes(s))return;const n=String(e.id||""),o=n?this.approvals.get(t)?.get(n):void 0;if(o&&o.state==="pending")return;const a={id:String(e.id||""),botId:t,botTitle:i?.title||t,kind:s==="confirm"?"tool":"question",method:s,title:String(e.title||"Approval required"),message:typeof e.message=="string"?e.message:void 0,options:Array.isArray(e.options)?e.options.map(String):void 0,state:"pending",createdAt:r};this.approvals.has(t)||this.approvals.set(t,new Map),this.approvals.get(t).set(a.id,a),this.setStatus(t,"waiting_approval"),this.emit(t,{type:"approval",approval:a,at:r})}respondApproval(t,e,s,r,i="human"){const n=this.approvals.get(t)?.get(e);if(!n)throw new Error("approval not found");const o=this.runtimes.get(t);if(!o)throw new Error("bot is not running");const a={type:"extension_ui_response",id:e};n.method==="confirm"?a.confirmed=s:n.method==="select"?a.value=s?n.options?.[0]:n.options?.[1]||n.options?.[0]:s?a.value=r||"":a.cancelled=!0,o.send(a),n.state=s?"allowed":"denied",n.decidedBy=i,n.reason=r,n.decidedAt=new Date().toISOString();try{this.store.appendEvent(t,{type:"approval",approval:n,at:n.decidedAt})}catch{}return this.broadcast(t,{type:"approval",approval:n,at:n.decidedAt}),this.setStatus(t,"running"),n}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 r=this.store.getInstance(t);if(!r)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(p=>setTimeout(p,150))}const i=this.runtimes.get(t);if(!i)throw new Error("bot is not running");const n=new Date().toISOString();this.emit(t,{type:"user",text:e,at:n});const o={type:"prompt",message:e};s==="steer"&&(o.streamingBehavior="steer"),s==="follow_up"&&(o.streamingBehavior="followUp"),!o.streamingBehavior&&(r.status==="running"||r.status==="waiting_approval")&&(o.streamingBehavior="steer");try{await i.request(o,2e4)}catch(a){const p=a instanceof Error?a.message:String(a);if(!o.streamingBehavior&&/streaming/i.test(p)){await i.request({...o,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 r of this.children(t))this.stop(r.id,!0);try{this.runtimes.get(t)?.kill()}catch{}this.runtimes.delete(t),l.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 r of this.children(t))this.deleteBot(r.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{f("git",["-C",s.projectPath,"worktree","remove","--force",s.workspacePath],{timeout:2e4,stdio:"ignore"})}catch{}v(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(r=>r.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),r=new Set(t);for(;Date.now()<s;){const i=[...r].filter(n=>{const o=this.store.getInstance(n);return!o||l.includes(o.status)});if(i.length)return{bots:i.map(n=>this.result(n))};await new Promise(n=>setTimeout(n,250))}return{timeout:!0,bots:t.map(i=>{const n=this.store.getInstance(i);return{botId:i,status:n?.status||"missing",title:n?.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(r=>r.botId===t)}));for(const r of this.store.readEvents(t,400))e.send(JSON.stringify(r));e.on("close",()=>this.sockets.get(t)?.delete(e))}broadcast(t,e){const s=JSON.stringify(e);for(const r of this.sockets.get(t)||[])if(r.readyState===1)try{r.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 r of this.listeners)try{r(e)}catch{}}onEvent(t){return this.listeners.add(t),()=>this.listeners.delete(t)}setStatus(t,e,s){const r=this.store.getInstance(t);r&&(r.status=e,s&&(r.lastError=s),this.store.saveInstance(r),this.emit(t,{type:"status",status:e,at:new Date().toISOString(),error:s}),l.includes(e)&&this.pump())}}function B(c){const t=c.content;return Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&e.type==="text"?String(e.text||""):"").join("").trim():""}function S(c){if(c==null)return"";if(typeof c=="string")return c;try{return JSON.stringify(c).slice(0,4e3)}catch{return String(c)}}let m=null;function q(){if(!m){const c=Number(process.env.PORT)||21e3;m=new x(c)}return m}export{x as BotManager,y as MAX_CONCURRENT_PER_PROJECT,d as MAX_DEPTH,E as ORCHESTRATION_TOOLS,T as READONLY_TOOLS,q as getBotManager};
@@ -0,0 +1,109 @@
1
+ import{mkdirSync as v,writeFileSync as x,existsSync as T,readFileSync as I,symlinkSync as k}from"node:fs";import E from"node:os";import o from"node:path";import{getBotStore as N}from"./store.js";import{ORCHESTRATION_TOOLS as j,READONLY_TOOLS as D,resolveResource as f}from"./catalog.js";const P=`// Generated by tmux-weblink: tool-call approval gate for the bots channel.
2
+ export default function (pi) {
3
+ const mode = process.env.TW_RUNTIME_MODE || 'supervised';
4
+ const readonly = new Set(${JSON.stringify([...D])});
5
+ const edits = new Set(['edit', 'write']);
6
+ pi.on('tool_call', async (event, ctx) => {
7
+ if (mode === 'full-access') return;
8
+ const name = event.toolName || event.name || 'tool';
9
+ if (readonly.has(name)) return;
10
+ if (mode === 'auto-accept-edits' && edits.has(name)) return;
11
+ let summary = '';
12
+ try {
13
+ const input = event.input ?? event.args ?? {};
14
+ summary = JSON.stringify(input).slice(0, 1200);
15
+ } catch {}
16
+ const ok = await ctx.ui.confirm('Allow ' + name + '?', summary || name);
17
+ if (!ok) return { block: true, reason: 'Declined in tmux-weblink.' };
18
+ });
19
+ }
20
+ `,A=`// Generated by tmux-weblink: orchestration tools for super bots.
21
+ import { Type } from 'typebox';
22
+
23
+ export default function (pi) {
24
+ const api = process.env.TW_BOTS_API || '';
25
+ const token = process.env.TW_BOT_TOKEN || '';
26
+ const selfId = process.env.TW_BOT_ID || '';
27
+
28
+ async function call(action, body) {
29
+ if (!api) throw new Error('TW_BOTS_API is not configured');
30
+ const res = await fetch(api + action, {
31
+ method: 'POST',
32
+ headers: { 'content-type': 'application/json', 'x-bots-token': token },
33
+ body: JSON.stringify({ ...(body || {}), parentBotId: selfId }),
34
+ });
35
+ const text = await res.text();
36
+ let json;
37
+ try { json = JSON.parse(text); } catch { json = { raw: text }; }
38
+ if (!res.ok) throw new Error(json.error || ('HTTP ' + res.status));
39
+ return json;
40
+ }
41
+
42
+ function reply(value) {
43
+ const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
44
+ return { content: [{ type: 'text', text: text.slice(0, 8000) }], details: value };
45
+ }
46
+
47
+ function tool(name, label, description, parameters, run) {
48
+ pi.registerTool({
49
+ name, label, description, parameters,
50
+ async execute(_id, params) {
51
+ try { return reply(await run(params || {})); }
52
+ catch (error) { return { content: [{ type: 'text', text: 'Error: ' + (error && error.message ? error.message : String(error)) }], isError: true, details: {} }; }
53
+ },
54
+ });
55
+ }
56
+
57
+ tool('bot_create', 'Create bot', 'Create a child bot from a template and give it a task. Returns the new bot id.', Type.Object({
58
+ templateId: Type.String({ description: 'Template id from bot_list_templates' }),
59
+ title: Type.String(),
60
+ brief: Type.String({ description: 'Full task description for the child bot' }),
61
+ projectPath: Type.Optional(Type.String()),
62
+ isolation: Type.Optional(Type.Union([Type.Literal('shared'), Type.Literal('worktree')])),
63
+ }), (p) => call('/create', p));
64
+
65
+ tool('bot_list_templates', 'List templates', 'List bot templates that can be used with bot_create.', Type.Object({}), () => call('/list_templates', {}));
66
+
67
+ tool('bot_list', 'List bots', 'List child bots created by this bot (or all when no parent scope).', Type.Object({
68
+ status: Type.Optional(Type.String()),
69
+ }), (p) => call('/list', { parentOnly: true, status: p.status }));
70
+
71
+ tool('bot_status', 'Bot status', 'Status of one bot: state, last activity, pending approvals, last text.', Type.Object({
72
+ botId: Type.String(),
73
+ }), (p) => call('/status', p));
74
+
75
+ tool('bot_message', 'Message bot', 'Send a message to a running child bot. mode=steer interrupts after the current turn, follow_up waits until it stops.', Type.Object({
76
+ botId: Type.String(),
77
+ text: Type.String(),
78
+ mode: Type.Optional(Type.Union([Type.Literal('steer'), Type.Literal('follow_up')])),
79
+ }), (p) => call('/message', p));
80
+
81
+ tool('bot_wait', 'Wait for bots', 'Wait until one or all of the given bots reach a terminal state (max 45s).', Type.Object({
82
+ botIds: Type.Array(Type.String()),
83
+ timeoutMs: Type.Optional(Type.Number()),
84
+ }), (p) => call('/wait', p));
85
+
86
+ tool('bot_result', 'Bot result', 'Final answer and summary of a child bot.', Type.Object({ botId: Type.String() }), (p) => call('/result', p));
87
+
88
+ tool('bot_stop', 'Stop bot', 'Stop a child bot (and its descendants unless cascade is false).', Type.Object({
89
+ botId: Type.String(),
90
+ cascade: Type.Optional(Type.Boolean()),
91
+ }), (p) => call('/stop', p));
92
+
93
+ tool('bot_approvals', 'Pending approvals', 'List pending approval requests from child bots.', Type.Object({}), () => call('/approvals', {}));
94
+
95
+ tool('bot_approve', 'Approve request', 'Answer a pending approval from a child bot. Requires an explicit reason (audited).', Type.Object({
96
+ botId: Type.String(),
97
+ requestId: Type.String(),
98
+ allow: Type.Boolean(),
99
+ reason: Type.String(),
100
+ }), (p) => call('/approve', p));
101
+ }
102
+ `;function l(p,s){if(T(p))try{if(I(p,"utf8")===s)return}catch{}x(p,s,{mode:384})}function C(p,s,b){const g=N(),r=g.agentDir(s.id),c=g.sessionsDir(s.id),u=o.join(r,"extensions");v(u,{recursive:!0,mode:448}),v(c,{recursive:!0,mode:448});const t=p.manifest,i={sessionDir:c,defaultProjectTrust:"never"},h=(t.skills||[]).map(e=>f("skills",e)),S=(t.prompts||[]).map(e=>f("prompts",e)),_=(t.extensions||[]).map(e=>f("extensions",e));h.length&&(i.skills=h),S.length&&(i.prompts=S),_.length&&(i.extensions=_),t.packages&&t.packages.length&&(i.packages=t.packages);const y=t.tools?.allow&&t.tools.allow.length?t.tools.allow:void 0;y?i.defaultTools=t.orchestrator?[...y,...j]:y:t.orchestrator&&(i.defaultTools=[...j,"read","grep","find","ls"]),l(o.join(r,"settings.json"),`${JSON.stringify(i,null,2)}
103
+ `),t.mcp?.mcpServers&&Object.keys(t.mcp.mcpServers).length&&l(o.join(r,"mcp.json"),`${JSON.stringify({mcpServers:t.mcp.mcpServers},null,2)}
104
+ `),t.system&&l(o.join(r,"SYSTEM.md"),t.system.endsWith(`
105
+ `)?t.system:`${t.system}
106
+ `),t.appendSystem&&t.appendSystem.length&&l(o.join(r,"APPEND_SYSTEM.md"),`${t.appendSystem.join(`
107
+
108
+ `)}
109
+ `);const w=process.env.TMUX_WEB_BOTS_PI_HOME||o.join(E.homedir(),".pi","agent");for(const e of["auth.json","models.json"]){const m=o.join(w,e),O=o.join(r,e);if(T(m)&&!T(O))try{k(m,O)}catch{}}l(o.join(u,"tw-approval.js"),P),t.orchestrator&&l(o.join(u,"tw-orchestrator.js"),A);const n={};for(const[e,m]of Object.entries(process.env))e.startsWith("PI_")||e.startsWith("TW_")||m!==void 0&&(n[e]=m);n.PI_CODING_AGENT_DIR=r,n.PI_CODING_AGENT_SESSION_DIR=c,n.PI_TELEMETRY="0",n.TW_RUNTIME_MODE=s.runtimeMode,n.TW_BOT_ID=s.id,t.orchestrator&&(n.TW_BOTS_API=b.apiBase,n.TW_BOT_TOKEN=b.token);const d=["--mode","rpc","--session-dir",c,"--session",s.sessionFile];s.projectResources==="ignore"&&d.push("--no-approve","--no-context-files");const a=t.model;return a?.provider&&a?.id&&d.push("--provider",a.provider,"--model",a.id),a?.thinking&&d.push("--thinking",a.thinking),t.tools?.deny&&t.tools.deny.length&&d.push("--exclude-tools",...t.tools.deny),{agentDir:r,sessionsDir:c,env:n,args:d}}export{C as materialize};
@@ -0,0 +1 @@
1
+ function m(s,c){const{manager:o,userAuth:u}=c,a=async(t,r)=>{const e=t.req.header("x-bots-token");return e&&e===o.token?r():u()(t,r)},l=()=>a,n=()=>u();s.get("/api/bots/catalog",n(),async t=>t.json(await o.catalog())),s.get("/api/bots/templates",n(),t=>t.json(o.listTemplates())),s.post("/api/bots/templates",n(),async t=>{const r=await t.req.json().catch(()=>null);if(!r||!r.manifest||typeof r.manifest.name!="string")return t.json({error:"manifest.name is required"},400);try{const e=o.saveTemplate({id:typeof r.id=="string"?r.id:void 0,manifest:r.manifest});return t.json(e,200)}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},400)}}),s.delete("/api/bots/templates/:id",n(),t=>o.deleteTemplate(t.req.param("id"))?t.json({ok:!0}):t.json({error:"not found"},404)),s.get("/api/bots",a,t=>{const r=t.req.query("project")||void 0,e=t.req.query("parent")||void 0,d=t.req.query("status")||void 0;return t.json(o.listBots({project:r,parentBotId:e,parentOnly:!!e,status:d}))});const p=async t=>{const r=await t.req.json().catch(()=>null);if(!r||typeof r.templateId!="string")return t.json({error:"templateId is required"},400);try{const e=o.createInstance({templateId:r.templateId,title:typeof r.title=="string"?r.title:void 0,projectPath:typeof r.projectPath=="string"?r.projectPath:void 0,isolation:r.isolation==="worktree"?"worktree":"shared",parentBotId:typeof r.parentBotId=="string"?r.parentBotId:void 0,runtimeMode:r.runtimeMode});return t.json(e,201)}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},400)}};s.post("/api/bots",n(),p),s.post("/api/bots/create",l(),p),s.post("/api/bots/list_templates",a,t=>t.json(o.listTemplates().map(r=>({id:r.id,name:r.manifest.name,description:r.manifest.description,orchestrator:!!r.manifest.orchestrator})))),s.post("/api/bots/list",a,async t=>{const r=await t.req.json().catch(()=>({})),e=r.parentBotId,d=o.listBots({parentBotId:r.parentOnly&&e?e:void 0,status:r.status});return t.json(d.map(i=>({id:i.id,title:i.title,status:i.status,projectPath:i.projectPath,parentBotId:i.parentBotId,depth:i.depth,lastText:i.lastText?.slice(0,400),updatedAt:i.updatedAt})))}),s.post("/api/bots/status",a,async t=>{const r=await t.req.json().catch(()=>({}));if(!r.botId)return t.json({error:"botId is required"},400);try{return t.json(o.status(r.botId))}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},404)}}),s.post("/api/bots/message",a,async t=>{const r=await t.req.json().catch(()=>({}));if(!r.botId||typeof r.text!="string")return t.json({error:"botId and text are required"},400);try{return await o.input(r.botId,r.text,r.mode==="follow_up"?"follow_up":r.mode==="steer"?"steer":void 0),t.json({ok:!0})}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/wait",a,async t=>{const r=await t.req.json().catch(()=>({}));return!Array.isArray(r.botIds)||r.botIds.length===0?t.json({error:"botIds is required"},400):t.json(await o.waitFor(r.botIds,typeof r.timeoutMs=="number"?r.timeoutMs:void 0))}),s.post("/api/bots/result",a,async t=>{const r=await t.req.json().catch(()=>({}));if(!r.botId)return t.json({error:"botId is required"},400);try{return t.json(o.result(r.botId))}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},404)}}),s.post("/api/bots/stop",a,async t=>{const r=await t.req.json().catch(()=>({}));if(!r.botId)return t.json({error:"botId is required"},400);try{return o.stop(r.botId,r.cascade!==!1),t.json({ok:!0})}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/approvals",a,t=>t.json(o.listApprovals())),s.post("/api/bots/approve",a,async t=>{const r=await t.req.json().catch(()=>({}));if(!r.botId||!r.requestId)return t.json({error:"botId and requestId are required"},400);const e=t.req.header("x-bots-token")===o.token?"parent-bot":"human";if(e==="parent-bot"&&!r.reason)return t.json({error:"a reason is required when a bot approves"},400);try{return t.json(o.respondApproval(r.botId,r.requestId,r.allow===!0,r.reason,e))}catch(d){return t.json({error:d instanceof Error?d.message:String(d)},400)}}),s.get("/api/bots/approvals",n(),t=>t.json(o.listApprovals())),s.get("/api/bots/:id",n(),t=>{const r=o.getBot(t.req.param("id"));return r?t.json(r):t.json({error:"not found"},404)}),s.get("/api/bots/:id/events",n(),t=>{const r=Number(t.req.query("limit"))||400;return t.json(o.store.readEvents(t.req.param("id"),r))}),s.post("/api/bots/:id/input",n(),async t=>{const r=await t.req.json().catch(()=>({}));if(typeof r.text!="string"||!r.text.trim())return t.json({error:"text is required"},400);try{return await o.input(t.req.param("id"),r.text,r.mode==="follow_up"?"follow_up":r.mode==="steer"?"steer":void 0),t.json({ok:!0})}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/:id/stop",n(),t=>{try{return o.stop(t.req.param("id"),!0),t.json({ok:!0})}catch(r){return t.json({error:r instanceof Error?r.message:String(r)},400)}}),s.post("/api/bots/:id/resume",n(),t=>{try{return o.resume(t.req.param("id")),t.json({ok:!0})}catch(r){return t.json({error:r instanceof Error?r.message:String(r)},400)}}),s.post("/api/bots/:id/approve",n(),async t=>{const r=await t.req.json().catch(()=>({}));if(!r.requestId)return t.json({error:"requestId is required"},400);try{return t.json(o.respondApproval(t.req.param("id"),r.requestId,r.allow===!0,r.reason,"human"))}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},400)}}),s.delete("/api/bots/:id",n(),t=>{try{return o.deleteBot(t.req.param("id"),!0),t.json({ok:!0})}catch(r){return t.json({error:r instanceof Error?r.message:String(r)},400)}})}export{m as registerBotRoutes};
@@ -0,0 +1,4 @@
1
+ import{spawn as o}from"node:child_process";const p=3e4;class c{opts;proc=null;buffer="";seq=0;pending=new Map;killed=!1;constructor(t){this.opts=t}start(){const t=o(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:this.opts.env,stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32"});this.proc=t,t.stdout.setEncoding("utf8"),t.stdout.on("data",e=>this.consume(e)),t.stderr.setEncoding("utf8"),t.stderr.on("data",e=>{for(const i of String(e).split(/\r?\n/))i.trim()&&this.opts.onStderr?.(i)}),t.on("error",()=>{this.failAll("failed to spawn pi")}),t.on("exit",(e,i)=>{this.failAll(`pi exited (${e??i??"unknown"})`),this.opts.onExit(e,i)})}consume(t){this.buffer+=t;let e=this.buffer.indexOf(`
2
+ `);for(;e>=0;){const i=this.buffer.slice(0,e).replace(/\r$/,"");this.buffer=this.buffer.slice(e+1),i.trim()&&this.handleLine(i),e=this.buffer.indexOf(`
3
+ `)}}handleLine(t){let e;try{e=JSON.parse(t)}catch{this.opts.onStderr?.(t);return}const i=typeof e.id=="string"?e.id:void 0;if(e.type==="response"&&i){const s=this.pending.get(i);s&&(this.pending.delete(i),clearTimeout(s.timer),e.success===!1?s.reject(new Error(String(e.error||"command failed"))):s.resolve(e));return}this.opts.onEvent(e)}failAll(t){for(const[,e]of this.pending)clearTimeout(e.timer),e.reject(new Error(t));this.pending.clear()}send(t){!this.proc||this.killed||this.proc.stdin.write(`${JSON.stringify(t)}
4
+ `)}request(t,e=p){if(!this.proc||this.killed)return Promise.reject(new Error("pi is not running"));const i=typeof t.id=="string"?t.id:`r${++this.seq}`;return new Promise((s,r)=>{const n=setTimeout(()=>{this.pending.delete(i),r(new Error(`pi command ${String(t.type)} timed out`))},e);this.pending.set(i,{resolve:s,reject:r,timer:n}),this.send({...t,id:i})})}kill(){if(!this.proc||this.killed)return;this.killed=!0;const t=this.proc,e=i=>{try{process.platform!=="win32"&&t.pid?process.kill(-t.pid,i):t.kill(i)}catch{}};e("SIGTERM"),setTimeout(()=>{t.exitCode===null&&t.signalCode===null&&e("SIGKILL")},2e3).unref?.()}}export{c as PiRpc};
@@ -0,0 +1,3 @@
1
+ import{existsSync as r,mkdirSync as c,readFileSync as o,writeFileSync as l,readdirSync as d,rmSync as m,appendFileSync as S}from"node:fs";import n from"node:path";import{randomBytes as f,randomUUID as j}from"node:crypto";import{getDataRoot as D}from"../state-paths.js";class g{root;instancesFile;instances=new Map;token;constructor(t){this.root=t||n.join(D(),"bots"),c(this.root,{recursive:!0,mode:448}),c(n.join(this.root,"templates"),{recursive:!0,mode:448}),c(n.join(this.root,"instances"),{recursive:!0,mode:448}),this.instancesFile=n.join(this.root,"instances.json"),this.loadInstances(),this.token=this.loadOrCreateToken()}loadOrCreateToken(){const t=n.join(this.root,"api-token");if(r(t)){const s=o(t,"utf8").trim();if(s)return s}const e=f(24).toString("hex");return l(t,e,{mode:384}),e}templatesDir=()=>n.join(this.root,"templates");listTemplates(){const t=this.templatesDir();if(!r(t))return[];const e=[];for(const s of d(t))if(s.endsWith(".json"))try{const i=JSON.parse(o(n.join(t,s),"utf8"));i&&i.id&&i.manifest&&e.push(i)}catch{}return e.sort((s,i)=>s.manifest.name.localeCompare(i.manifest.name))}getTemplate(t){const e=n.join(this.templatesDir(),`${t}.json`);if(!r(e))return null;try{return JSON.parse(o(e,"utf8"))}catch{return null}}saveTemplate(t){const e=new Date().toISOString(),s=t.id||`${Date.now().toString(36)}-${f(3).toString("hex")}`,i=this.getTemplate(s),a={id:s,manifest:{...t.manifest,schema:1},createdAt:i?.createdAt||e,updatedAt:e};return l(n.join(this.templatesDir(),`${s}.json`),JSON.stringify(a,null,2),{mode:384}),a}deleteTemplate(t){const e=n.join(this.templatesDir(),`${t}.json`);return r(e)?(m(e),!0):!1}loadInstances(){if(r(this.instancesFile))try{const t=JSON.parse(o(this.instancesFile,"utf8"));for(const e of t)this.instances.set(e.id,e)}catch{}}persistInstances(){l(this.instancesFile,JSON.stringify([...this.instances.values()],null,2),{mode:384})}listInstances(){return[...this.instances.values()].sort((t,e)=>t.createdAt.localeCompare(e.createdAt))}getInstance(t){return this.instances.get(t)||null}saveInstance(t){t.updatedAt=new Date().toISOString(),this.instances.set(t.id,t),this.persistInstances()}deleteInstance(t){this.instances.delete(t),this.persistInstances(),m(this.instanceDir(t),{recursive:!0,force:!0})}instanceDir(t){return n.join(this.root,"instances",t)}agentDir(t){return n.join(this.instanceDir(t),"agent")}sessionsDir(t){return n.join(this.instanceDir(t),"sessions")}appendEvent(t,e){try{c(this.instanceDir(t),{recursive:!0,mode:448}),S(n.join(this.instanceDir(t),"events.jsonl"),`${JSON.stringify(e)}
2
+ `,{mode:384})}catch{}}readEvents(t,e=2e3){const s=n.join(this.instanceDir(t),"events.jsonl");if(!r(s))return[];const a=o(s,"utf8").split(`
3
+ `).filter(Boolean).slice(-e),h=[];for(const p of a)try{h.push(JSON.parse(p))}catch{}return h}newId(){return j()}}let u=null;function F(){return u||(u=new g),u}export{g as BotStore,F as getBotStore};
@@ -0,0 +1 @@
1
+ const e=["completed","failed","cancelled"];export{e as TERMINAL_STATUSES};