tmux-weblink 2.2.40 → 2.2.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/shell-client.js +35 -30
- package/dist/browser/bots-client.js +6 -0
- package/dist/browser/shell-client.js +18 -18
- package/dist/index.js +4 -4
- package/dist/lib/bots/catalog.js +16 -0
- package/dist/lib/bots/manager.js +1 -0
- package/dist/lib/bots/materialize.js +109 -0
- package/dist/lib/bots/routes.js +1 -0
- package/dist/lib/bots/rpc.js +4 -0
- package/dist/lib/bots/store.js +3 -0
- package/dist/lib/bots/types.js +1 -0
- package/dist/lib/build-app.js +4 -4
- package/dist/lib/pages/shell.js +107 -12
- package/package.json +1 -1
|
@@ -1,34 +1,34 @@
|
|
|
1
|
-
import{initTerminal as
|
|
2
|
-
<span>${d(e.name)}</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>`,
|
|
1
|
+
import{initTerminal as Qe}from"./terminal-core.js";import{initBots as et,openNewBotForPath as tt}from"./bots-client.js";const P=window.__TMUX_WEB_SHELL__;let f=null,u=null;const j=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let y=j;window.__tmuxWebScopeAgent=j;let me="sessions",I="",K="",Y="",Ce="";function g(e){return y?"/a/"+encodeURIComponent(y)+e:e}const r=document.getElementById("sidebar-content"),R=document.getElementById("main-placeholder"),w=document.getElementById("terminal-container"),O=document.getElementById("file-editor"),nt=document.getElementById("fe-path"),E=document.getElementById("fe-status"),U=document.getElementById("fe-content"),N=document.getElementById("fe-save"),st=document.getElementById("fe-delete"),it=document.getElementById("fe-back"),Se=document.getElementById("fe-new-name"),ot=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 X(){try{return localStorage.getItem(xe)==="1"}catch{return!1}}function Te(){document.documentElement.classList.toggle("force-narrow",X()),X()&&Me()&&Z()}function Me(){return X()?!0:window.matchMedia("(max-width: 640px)").matches}function Z(){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(n=>n.classList.remove("active"));const t=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");t&&t.classList.add("active"),e==="sessions"?(ve="",B()):bt()}let ve="";async function B(){if(me!=="sessions")return;try{const n=await(await fetch("/api/sidebar/sessions")).json(),s=JSON.stringify({recent:n.recent,agents:n.agents,tombstones:n.tombstones});if(s===ve)return;ve=s,dt(n)}catch{r.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}const e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{const t=window.__openNewSessionModal;typeof t=="function"?t():document.getElementById("new-session-modal")?.classList.add("open")}),Ee()}const Ne="tmux-web-sidebar-group-collapsed";function Ae(){try{return new Set(JSON.parse(localStorage.getItem(Ne)||"[]"))}catch{return new Set}}function at(e){try{localStorage.setItem(Ne,JSON.stringify([...e]))}catch{}}function lt(e,t,n){if(!e)return"\u2026";const s=n&&(e===n||e.startsWith(n+"/"))?"~"+e.slice(n.length):e,i=s.split("/").filter(Boolean);if(i.length===0)return e;for(let o=1;o<=i.length;o++){const l=i.slice(-o).join("/");if(!t.some(c=>!c||c===e?!1:(n&&(c===n||c.startsWith(n+"/"))?"~"+c.slice(n.length):c).split("/").filter(Boolean).slice(-o).join("/")===l))return l}return s}function $e(e,t,n,s=!0){const i=new Map;for(const a of e){const c=a.path||"";i.has(c)||i.set(c,[]),i.get(c).push(a)}const o=[...i.keys()],l=Ae();for(const[a,c]of i){const p=lt(a,o,t),b=l.has(a),v=document.createElement("div");v.className="session-group-header"+(b?" collapsed":""),v.title=a||"No working directory",v.innerHTML=`<span class="sg-folder">📁</span><span class="sg-label">${d(p)}</span>`,v.addEventListener("click",()=>{const H=Ae(),ke=v.nextElementSibling;H.has(a)?(H.delete(a),v.classList.remove("collapsed"),ke?.classList.remove("collapsed")):(H.add(a),v.classList.add("collapsed"),ke?.classList.add("collapsed")),at(H)});const M=document.createElement("div");M.className="session-group-body"+(b?" collapsed":"");for(const H of c)M.appendChild(n?ct(H,n,s):rt(H));r.appendChild(v),r.appendChild(M)}}function ct(e,t,n){const s=document.createElement("div");s.className="session-item"+(e.name===u&&y===t?" active":"")+(n?"":" session-offline"),s.setAttribute("data-session",e.name),s.setAttribute("data-agent",t),s.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
|
|
2
|
+
<span>${d(e.name)}</span>${n?"":'<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>`,n&&s.addEventListener("click",o=>{o.target.closest(".session-edit-btn")||W(e.name,t)});const i=s.querySelector(".session-edit-btn");return i&&i.addEventListener("click",o=>{o.stopPropagation(),ce(e.name,i,{agentId:t})}),s}function rt(e){const t=document.createElement("div");t.className="session-item"+(e.name===u&&!y?" active":""),t.setAttribute("data-session",e.name),t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
|
|
4
4
|
<span>${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
|
-
`,
|
|
7
|
-
<span>${d(
|
|
8
|
-
<button class="session-edit-btn" data-session="${d(
|
|
6
|
+
`,t.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||W(e.name)});const n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",s=>{s.stopPropagation(),ce(e.name,n)}),t}function dt(e){r.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';const t=e.recent||[],n=document.createElement("div");n.className="sidebar-section-label"+(j?" clickable":""),n.textContent=j?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",j&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),r.appendChild(n),$e(t,e.home);const s=e.agents||[];for(const o of s){if(!o.sessions||o.sessions.length===0)continue;const l=o.agentId===y,a=document.createElement("div");a.className="sidebar-section-label machine-label"+(o.online?"":" agent-offline-label")+(!l&&o.online?" clickable":""),a.textContent=o.agentName+(o.online?"":" (offline)"),!l&&o.online&&(a.title="\u6253\u5F00 "+o.agentName,a.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(o.agentId)+"/"})),r.appendChild(a),$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 l of i){const a=document.createElement("div");a.className="session-item session-tombstone",a.setAttribute("data-session",l.name),l.agentId&&a.setAttribute("data-agent",l.agentId);const c=l.agentId?l.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";a.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
|
|
7
|
+
<span>${d(l.name)}</span><span class="meta">\u5931\u6548${c}</span>
|
|
8
|
+
<button class="session-edit-btn" data-session="${d(l.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,a.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",a.addEventListener("click",()=>{ce(l.name,a,{tombstone:!0,agentId:l.agentId})});const p=a.querySelector(".session-edit-btn");p&&p.addEventListener("click",b=>{b.stopPropagation(),ce(l.name,p,{tombstone:!0,agentId:l.agentId})}),r.appendChild(a)}}}function d(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}async function W(e,t){if(u===e&&f&&y===(t||null))return;O.style.display="none",R.style.display="none",w.style.display="",w.classList.add("terminal-pending"),Z(),f&&(ae(),f.destroy(),f=null),u=e,y=t||null,window.__tmuxWebScopeAgent=y,window.__tmuxWebCurrentSession=u,$t(e,t);const n=Le(e,t);Xe.set(n,Date.now()+Nt);const s=D.get(n);if(s&&s.state==="working"){s.state="idle",s.doneUntil=void 0,s.unread=!1;const i=r.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');i&&ue(i,n,s)}for(const i of r.querySelectorAll(".session-item"))i.classList.toggle("active",i.getAttribute("data-session")===e&&(i.getAttribute("data-agent")||null)===y);try{f=await Qe(w,e,{terminal:P.terminal,scrollback:P.scrollback,theme:P.theme,wsBase:y?"/ws/a/"+encodeURIComponent(y):P.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);w.textContent="Failed to open terminal for "+e+": "+o,w.classList.remove("terminal-pending")}}let Q=[],m=null,_e=!1;function pt(e){if(!m||!m.files.length)return null;const t=m.repoRoot;if(!t||!e.startsWith(t))return null;const n=e.slice(t.length+1);for(const s of m.files)if(s.path===n)return s.status;return null}async function ft(e){_e=!0;try{const t=await fetch(g("/api/git/status?path="+encodeURIComponent(e)));t.ok?m=await t.json():m=null}catch{m=null}finally{_e=!1}}function ut(){if(!m||!m.branch)return"";const{branch:e,linesAdded:t,linesRemoved:n}=m;let s=`<div class="sidebar-git"><div class="git-branch-badge">
|
|
9
9
|
<svg viewBox="0 0 16 16" fill="currentColor"><path d="M11.63 1.22a.75.75 0 00-1.06 0L5.99 5.8 4.12 3.93a.75.75 0 10-1.06 1.06L4.93 6.87A3.5 3.5 0 003 10.09v3.16a.75.75 0 001 0v-3.16a2.5 2.5 0 012.5-2.5h.27l-1.06 1.06a.75.75 0 001.06 1.06l2.37-2.38a.75.75 0 000-1.06L7.59 5.27l4.04-4.05a.75.75 0 000-1.06L11.63 1.22zM3.25 13.94a.75.75 0 01-.75-.75v-.69a.75.75 0 011.5 0v.69c0 .414-.336.75-.75.75z"/></svg>
|
|
10
|
-
${d(e)}</div>`;return(
|
|
11
|
-
<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let
|
|
12
|
-
${
|
|
10
|
+
${d(e)}</div>`;return(t>0||n>0)&&(s+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${n}</span></div>`),s+"</div>"}r.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&$&&m&&(e.stopPropagation(),Ue())});const z=document.getElementById("header-git"),De=document.getElementById("git-diff-view"),Pe=document.getElementById("gd-path"),ee=document.getElementById("gd-status"),te=document.getElementById("gd-content"),mt=document.getElementById("gd-back");let $=null;function F(e){if(!e||!e.branch){z.style.display="none",$=null;return}$=e.repoRoot;const{branch:t,linesAdded:n,linesRemoved:s}=e;let i=`<span class="branch">${d(t)}</span>`;(n>0||s>0)&&(i+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${s}</span>`),z.innerHTML=i,z.style.display="block"}z.addEventListener("click",e=>{$&&m&&(e.stopPropagation(),Ue())});const h=document.getElementById("git-popover"),ne=document.getElementById("git-popover-backdrop");function ye(){const e=z.getBoundingClientRect();h.style.top=e.bottom+4+"px",h.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function je(){const e=$,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(ie(),e){me="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));const n=document.getElementById("mode-files");n&&n.classList.add("active"),x(e)}})}let Oe="";function Ue(){if(!m)return;const e=m.files||[];if(!e.length)h.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
|
|
11
|
+
<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let t=`<div class="git-popover-header">${e.length} file${e.length>1?"s":""} changed</div>`;for(let n=0;n<e.length;n++){const s=e[n],i=s.additions||0,o=s.deletions||0;let l="";switch(s.status){case"M":l='<span class="git-file-status M">M</span>';break;case"A":l='<span class="git-file-status A">A</span>';break;case"D":l='<span class="git-file-status D">D</span>';break;case"?":l='<span class="git-file-status ?">?</span>';break;case"R":l='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
|
|
12
|
+
${l}<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>`}
|
|
16
|
-
`:"")+
|
|
17
|
-
`);let i="",o=0,
|
|
15
|
+
</div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',Oe=t,h.innerHTML=t,h.querySelectorAll(".git-popover-item").forEach(n=>{const s=parseInt(n.dataset.idx||"0",10),i=e[s];!i||i.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>ze(i.path)))})}ye(),h.classList.add("open"),ne.classList.add("open"),je()}function gt(){return window.innerWidth>=1024}function We(e,t){const s=(e+(t&&e?`
|
|
16
|
+
`:"")+t).split(`
|
|
17
|
+
`);let i="",o=0,l=0;for(const a of s){const c=a;if(c.startsWith("@@")){const p=c.match(/@@\s+-(\d+)[^+]*\+(\d+)/);p&&(o=parseInt(p[1],10)-1,l=parseInt(p[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("+"))l++,i+=`<div class="diff-line add"><span class="ln-no">${l}</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&&!l)continue;o++,l++,i+=`<div class="diff-line"><span class="ln-no">${o}</span><span class="ln-no" style="margin-right:12px">${l}</span><span class="ln-body">${d(c)}</span></div>`}}return{html:i,lineCount:s.length}}let se=null;async function ze(e){const t=$;if(t)if(ie(),gt()){w.style.display="none",f&&(ae(),f.destroy(),f=null,se=u,u=null),F(null),O.style.display="none",R.style.display="none",De.style.display="flex",Pe.textContent=e,ee.textContent="Loading\u2026",te.innerHTML="";try{const n=await fetch(g("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());const s=await n.json();yt(e,s.diff,s.stagedDiff)}catch(n){const s=n instanceof Error?n.message:String(n);ee.textContent="Error",te.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${d(s)}</div>`}}else{h.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(),
|
|
21
|
+
</div></div>`,ye(),h.classList.add("open"),ne.classList.add("open");try{const n=await fetch(g("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());const s=await n.json();vt(e,s.diff,s.stagedDiff)}catch(n){const s=n instanceof Error?n.message:String(n);h.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
|
|
24
|
+
</div><div class="diff-empty">Error loading diff: ${d(s)}</div></div>`}}}function vt(e,t,n){if(!t&&!n){h.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
|
-
</div><div class="diff-empty">No diff content available</div></div>`;return}const{html:s,lineCount:i}=We(n
|
|
27
|
+
</div><div class="diff-empty">No diff content available</div></div>`;return}const{html:s,lineCount:i}=We(t,n);h.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>`,
|
|
31
|
+
</div><div class="diff-content">${s}</div></div>`,h.querySelector(".diff-back")?.addEventListener("click",()=>{h.innerHTML=Oe,ye(),m&&h.querySelectorAll(".git-popover-item").forEach(o=>{const l=parseInt(o.dataset.idx||"0",10),a=m.files[l];!a||a.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>ze(a.path)))}),je()})}function yt(e,t,n){if(!t&&!n){ee.textContent="No diff",te.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(t,n);Pe.textContent=e,ee.textContent=i+" lines",te.innerHTML=s}function ht(){De.style.display="none",se?(w.style.display="",w.classList.add("terminal-pending"),W(se),se=null):u?(w.style.display="",w.classList.add("terminal-pending"),Ge()):R.style.display="flex"}mt.addEventListener("click",ht);function ie(){h.classList.remove("open"),ne.classList.remove("open")}ne.addEventListener("click",ie),document.addEventListener("keydown",e=>{e.key==="Escape"&&(ie(),fe())});async function Fe(e){try{const n=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(n.path){const s=await fetch("/api/git/status?path="+encodeURIComponent(n.path));if(s.ok){const i=await s.json();m=i,F(i);return}}}catch{}m=null,F(null)}let oe=null;function Ge(){ae(),u&&(Fe(u),oe=setInterval(()=>{u&&Fe(u)},3e4))}function ae(){oe&&(clearInterval(oe),oe=null)}async function qe(e){let t=e;if(t.startsWith("~"))try{const s=await(await fetch(g("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof s.path=="string"&&s.path&&(t=s.path)}catch{}t=t.replace(/\/+$/,"")||"/",tt(t)}function Ve(e,t){const n=document.createElement("button");n.className="file-tree-bot-btn",n.textContent="+",n.title=`Create bot in ${t}`,n.setAttribute("aria-label",`Create bot in ${t}`),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),qe(t)}),e.appendChild(n)}function bt(){if(Q=P.fsRoots||[],Q.length===0){if(u){wt(u);return}x("");return}r.innerHTML="";for(const e of Q){const t=document.createElement("div");t.className="file-tree-item",t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${d(e)}`,t.addEventListener("click",()=>x(e)),Ve(t,e),r.appendChild(t)}}async function wt(e){r.innerHTML='<div class="file-tree-empty">Loading...</div>';try{const n=await(await fetch(g("/api/fs/session-path?session="+encodeURIComponent(e)))).json();n.path?x(n.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 x(e){I=e,r.innerHTML='<div class="file-tree-empty">Loading...</div>';const t=ft(e);try{const s=await(await fetch(g("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof s.path=="string"&&s.path?s.path:e;if(i&&(I=i),await t,r.innerHTML="",i){const a=document.createElement("div");a.className="file-tree-item file-tree-create-bot",a.innerHTML='<span class="file-tree-bot-plus">+</span> Create bot in this folder',a.title=`Create bot in ${i}`,a.addEventListener("click",()=>void qe(i)),r.appendChild(a)}F(m),r.innerHTML+=ut();const o=Lt(i||e);if(o&&!Q.some(c=>i===c)){const c=document.createElement("div");c.className="file-tree-item",c.innerHTML="..",c.addEventListener("click",()=>x(o)),r.appendChild(c)}if(s.dirs)for(const a of s.dirs){const c=a.split("/").pop()||a.split("\\").pop(),p=document.createElement("div");p.className="file-tree-item",p.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${d(c)}`,p.addEventListener("click",()=>x(a)),Ve(p,a),r.appendChild(p)}else r.innerHTML="";const l=s.files||[];for(const a of l){const c=a.split("/").pop()||a.split("\\").pop(),p=pt(a);let b="",v="";if(p)switch(p){case"M":b="git-mod",v='<span class="git-file-status M">M</span>';break;case"A":b="git-add",v='<span class="git-file-status A">A</span>';break;case"D":b="git-del",v='<span class="git-file-status D">D</span>';break;case"?":b="git-untracked",v='<span class="git-file-status ?">?</span>';break;case"R":b="git-mod",v='<span class="git-file-status R">R</span>';break}const M=document.createElement("div");M.className="file-tree-item file"+(b?" "+b:""),M.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${v}${d(c)}`,M.addEventListener("click",()=>Et(a)),r.appendChild(M)}}catch{r.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function Lt(e){const t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function Et(e){K=e,w.style.display="none",f&&(ae(),f.destroy(),f=null,u=null),F(null),Z(),R.style.display="none",O.style.display="flex",nt.textContent=e,E.textContent="Loading...",N.style.display="none";try{const t=await fetch(g("/api/file?path="+encodeURIComponent(e)));if(!t.ok){const s=await t.json();E.textContent=s.error||"Failed to load",U.value="";return}const n=await t.json();U.value=n.content,Y=n.content,Ce=n.content,E.textContent=n.size+" bytes",N.style.display=""}catch{E.textContent="Failed to load",U.value=""}}U.addEventListener("input",()=>{Y=U.value}),N.addEventListener("click",async()=>{N.textContent="Saving...",N.disabled=!0;try{const e=await fetch(g("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:K,content:Y})});if(!e.ok){const t=await e.json();E.textContent=t.error||"Save failed";return}Ce=Y,E.textContent="Saved"}catch{E.textContent="Save failed"}finally{N.disabled=!1,N.textContent="Save"}}),st.addEventListener("click",async()=>{if(confirm("Delete "+K+"?"))try{const e=await fetch(g("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:K})});if(!e.ok){const t=await e.json();E.textContent=t.error||"Delete failed";return}O.style.display="none",R.style.display="flex",I&&x(I)}catch{E.textContent="Delete failed"}}),it.addEventListener("click",()=>{O.style.display="none",R.style.display="flex",I&&x(I)}),ot.addEventListener("click",async()=>{const e=Se.value.trim();if(!e)return;const t=I+"/"+e;try{const n=await fetch(g("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){const s=await n.json();E.textContent=s.error||"Create failed";return}Se.value="",I&&x(I)}catch{E.textContent="Create failed"}});const le=document.getElementById("force-narrow-toggle");le&&(le.checked=X(),le.addEventListener("change",()=>{try{localStorage.setItem(xe,le.checked?"1":"0")}catch{}Te(),B()})),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 L="",T=!1,k;const G=document.createElement("div");G.className="session-popover-backdrop",document.body.appendChild(G);const C=document.createElement("div");C.id="session-popover",C.className="session-popover",C.style.display="none",C.innerHTML=`<div class="sp-field">
|
|
32
32
|
<label>Rename session</label>
|
|
33
33
|
<input type="text" id="sp-name" />
|
|
34
34
|
</div>
|
|
@@ -38,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(
|
|
42
|
-
`).length;
|
|
41
|
+
<button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(C);function kt(e){const t=e.getBoundingClientRect(),n=window.innerHeight,s=C.offsetHeight||240;let i=t.bottom+4;i+s>n-8&&(i=Math.max(8,t.top-s-4)),C.style.top=i+"px",C.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}function ce(e,t,n){L=e,T=!!n?.tombstone,k=n?.agentId;const s=document.getElementById("sp-name");s.value=e;const i=C.querySelector(".sp-field label");i.textContent=T?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const o=document.getElementById("sp-rebuild");o.style.display=T?"":"none";const l=document.getElementById("sp-delete");l.textContent=T?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";const a=document.getElementById("sp-save");a.textContent=T?"\u91CD\u547D\u540D":"Save",G.classList.add("open"),C.style.display="block",kt(t),setTimeout(()=>s.focus(),50)}function A(){G.classList.remove("open"),C.style.display="none"}G.addEventListener("click",A),document.getElementById("sp-save").addEventListener("click",async()=>{const e=document.getElementById("sp-name").value.trim();if(!e||e===L){A();return}try{const t=T?{oldName:L,newName:e,agentId:k}:{oldName:L,newName:e,...k?{agentId:k}:{}};if(!(await fetch(g(T?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;A(),B(),!T&&u===L&&(k??null)===y&&W(e,k)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+L+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{const e=await fetch(g("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:k})});if(!e.ok){const t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}A(),B()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(T){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+L+'"\uFF1F'))return;try{if(!(await fetch(g("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:k})})).ok)return;A(),B()}catch{}return}if(confirm('Delete session "'+L+'"?'))try{if(!(await fetch(g("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,...k?{agentId:k}:{}})})).ok)return;A(),u===L&&(k??null)===y&&(f&&(f.destroy(),f=null),u=null,w.style.display="none",R.style.display="flex"),B()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",A);const Je={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"},re=document.getElementById("mobile-keys"),Ct=new Set(["up","down","left","right","tab","s-tab","space"]),St=400,It=80;let q=0,de=0,pe=!1;function Bt(){q&&(clearTimeout(q),q=0),de&&(clearInterval(de),de=0)}re.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),re.addEventListener("pointerdown",e=>{const t=e.target.closest("button[data-key]");if(!t)return;const n=t.dataset.key;Ct.has(n)&&(pe=!1,q=setTimeout(()=>{q=0,pe=!0,de=setInterval(()=>{const s=Je[n];s&&f&&f.sendInput(s)},It)},St))});for(const e of["pointerup","pointercancel","pointerleave"])re.addEventListener(e,Bt);re.addEventListener("click",e=>{const t=e.target.closest("button[data-key]");if(!t||!f)return;if(pe){pe=!1;return}const n=Je[t.dataset.key];n&&(f.sendInput(n),f.focus())});const S=document.getElementById("mk-input"),Ke=document.getElementById("mk-send");function Ye(){if(!S||!f)return;const e=S.value;e&&(f.sendInput(e+"\r"),S.value="",S.rows=1,f.focus())}if(S&&(S.addEventListener("input",()=>{S.rows=1;const e=S.value.split(`
|
|
42
|
+
`).length;S.rows=Math.min(e,4)}),S.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Ye())})),Ke&&Ke.addEventListener("click",Ye),window.visualViewport){const e=document.querySelector(".app-layout"),t=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",t),window.addEventListener("orientationchange",()=>setTimeout(t,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}const he=document.getElementById("process-panel"),V=document.getElementById("proc-list"),xt=document.getElementById("proc-close"),be=document.getElementById("proc-backdrop"),Tt=document.getElementById("header-ram");function Mt(){V.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(g("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){V.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(const n of e){const s=n.rss,i=s<1048576?(s/1024).toFixed(0)+"K":(s/1048576).toFixed(1)+"M";t+='<div class="proc-row" data-pid="'+n.pid+'"><span class="proc-mem">'+n.mem+'%</span><span class="proc-rss">'+i+'</span><span class="proc-cmd" title="'+d(n.command)+'">'+d(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">×</button></div>'}V.innerHTML=t;for(const n of V.querySelectorAll(".proc-row")){const s=n.querySelector(".proc-kill");s&&s.addEventListener("click",i=>{const o=i.target.closest(".proc-row");!o||!confirm("Kill PID "+o.dataset.pid+"?")||fetch(g("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(o.dataset.pid,10)})}).then(l=>l.json()).then(l=>{l.ok?o.style.opacity="0.3":alert("Failed: "+(l.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{V.innerHTML='<div class="proc-empty">Failed to load</div>'})}function Ht(){he.classList.add("open"),be.classList.add("open"),Mt()}function fe(){he.classList.remove("open"),be.classList.remove("open")}Tt.addEventListener("click",e=>{e.stopPropagation(),he.classList.contains("open")?fe():Ht()}),xt.addEventListener("click",fe),be.addEventListener("click",fe);const Rt=2e3;let J=null,we=null;const _=new Map,D=new Map,Nt=5e3,Xe=new Map;function Le(e,t){return(t?"a:"+t+":":"l:")+e}function At(e,t,n){const s=Le(e,t);if(n==="working"){const p=Xe.get(s);if(p&&Date.now()<p)return}const i=D.get(s),o=e===u&&(t??null)===y,l=n==="idle"&&i?.state==="working";D.set(s,{session:e,agentId:t,state:n,doneUntil:l?Date.now()+Rt:void 0,unread:l?!o:!1});const a=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',c=r.querySelector(a);c&&ue(c,s,D.get(s))}function ue(e,t,n){const s=_.get(t);s&&(clearTimeout(s),_.delete(t)),e.classList.remove("working","just-done");const i=n.session===u&&(n.agentId??null)===y;n.state==="working"?e.classList.add("working"):i&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),_.set(t,setTimeout(()=>{e.classList.remove("just-done"),_.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!i&&n.unread&&e.classList.add("just-done")}function Ee(){for(const[e,t]of D){const n=t.agentId?'.session-item[data-agent="'+CSS.escape(t.agentId)+'"][data-session="'+CSS.escape(t.session)+'"]':'.session-item[data-session="'+CSS.escape(t.session)+'"]:not([data-agent])',s=r.querySelector(n);s&&ue(s,e,t)}}function $t(e,t){const n=Le(e,t),s=D.get(n);if(!s)return;const i=_.get(n);i&&(clearTimeout(i),_.delete(n)),s.doneUntil=void 0,s.unread=!1;const o=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',l=r.querySelector(o);l&&ue(l,n,s)}function Ze(){if(J||we)return;const e=localStorage.getItem("tmux-web-token");let n=(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws/activity";e&&(n+="?token="+encodeURIComponent(e));try{const s=new WebSocket(n);J=s,s.onmessage=i=>{try{const o=JSON.parse(String(i.data));o&&o.type==="session.activity"&&typeof o.session=="string"&&At(o.session,o.agentId||void 0,o.state==="working"?"working":"idle")}catch{}},s.onclose=()=>{J===s&&(J=null,we=setTimeout(()=>{we=null,Ze()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{J=null}}window.__openSession=W,window.__refreshSidebar=B,B(),Z(),Ee(),Ze(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Ee()}),setInterval(()=>{document.visibilityState==="visible"&&B()},1e4),et();
|
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
|
|
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()}
|
|
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
|
-
`})),
|
|
7
|
-
Run on the remote machine:`),console.log(` tmux-web agent --hub wss://YOUR_HUB --token ${
|
|
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 g}from"node:child_process";import{mkdirSync as y,rmSync as I}from"node:fs";import u from"node:path";import S from"node:os";import{getBotStore as k}from"./store.js";import{materialize as _}from"./materialize.js";import{PiRpc as E}from"./rpc.js";import{buildCatalog as T,ORCHESTRATION_TOOLS as x,READONLY_TOOLS as B}from"./catalog.js";import{TERMINAL_STATUSES as l}from"./types.js";const m=4,v=8;class O{store=k();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 T()}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>m)throw new Error(`nesting depth limit is ${m}`)}let r=t.projectPath||s?.projectPath||process.env.HOME||"/";r==="~"?r=S.homedir():r.startsWith("~/")&&(r=u.join(S.homedir(),r.slice(2)));const i=u.resolve(r),n=this.store.newId(),o=t.isolation||"shared";let a=i;if(o==="worktree"){const d=u.join(this.store.root,"worktrees",n);try{y(u.dirname(d),{recursive:!0,mode:448}),g("git",["-C",i,"worktree","add","-b",`tw-bot/${n.slice(0,8)}`,d],{timeout:2e4,stdio:"ignore"}),a=d}catch{a=i}}const p=new Date().toISOString(),h={id:n,templateId:e.id,title:t.title||e.manifest.name,projectPath:i,workspacePath:a,isolation:o,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(n),`${n}.jsonl`),createdAt:p,updatedAt:p,model:e.manifest.model};return y(this.store.sessionsDir(n),{recursive:!0,mode:448}),this.store.saveInstance(h),this.emit(h.id,{type:"status",status:"queued",at:p}),this.pump(),h}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)>=v||this.start(t))}start(t){const e=this.getTemplate(t.templateId);if(!e){this.setStatus(t.id,"failed","template disappeared");return}const s=_(e,t,{apiBase:this.apiBase,token:this.token}),r=e.manifest.binaryPath||"pi",i=new E({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=A(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:w(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:w(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{g("git",["-C",s.projectPath,"worktree","remove","--force",s.workspacePath],{timeout:2e4,stdio:"ignore"})}catch{}I(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 A(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 w(c){if(c==null)return"";if(typeof c=="string")return c;try{return JSON.stringify(c).slice(0,4e3)}catch{return String(c)}}let f=null;function J(){if(!f){const c=Number(process.env.PORT)||21e3;f=new O(c)}return f}export{O as BotManager,v as MAX_CONCURRENT_PER_PROJECT,m as MAX_DEPTH,x as ORCHESTRATION_TOOLS,B as READONLY_TOOLS,J 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};
|