tmux-weblink 3.2.1 → 3.2.3

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,6 +1,6 @@
1
- import{icon as H}from"../lib/icons.js";import{createMarkdownRenderer as Ft}from"./markdown.js";const mt=Ft(document),d={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,queues:new Map,ws:null,pollTimer:0,renderQueued:!1};let q=[],O=!0;const $t=200;let At=$t,Qt=!1,Bt=0;function ft(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function x(t,e){const n=await fetch(t,{...e,headers:{"content-type":"application/json",Authorization:`Bearer ${ft()}`,...e?.headers||{}}}),o=await n.text(),s=o?JSON.parse(o):null;if(!n.ok)throw new Error(s&&s.error||`HTTP ${n.status}`);return s}function i(t,e,n){const o=document.createElement(t);return e&&(o.className=e),n!==void 0&&(o.textContent=n),o}function Tt(t){return t==="running"?"var(--panel-success)":t==="waiting_approval"||t==="waiting_input"?"#e0a23c":t==="failed"?"var(--panel-danger, #e5534b)":t==="completed"?"var(--panel-accent)":"var(--panel-muted)"}function R(){ht||(ht=requestAnimationFrame(()=>{ht=0,zt()}))}let ht=0,Z="";function zt(){const t=document.getElementById("bots-view");if(!t)return;const e=window.visualViewport,n=window.matchMedia("(max-width: 640px)").matches,o=document.querySelector(".sidebar")?.classList.contains("open")===!0;if(d.activeId&&e&&n&&!o){const s=document.querySelector(".fixed-header"),a=s?Math.round(s.getBoundingClientRect().height):0,l=Math.round(e.offsetTop)+a,c=Math.round(e.offsetLeft),r=Math.round(e.width),p=Math.max(120,Math.round(e.height)-a),f=`fixed|${l}|${c}|${r}|${p}`;if(f===Z)return;Z=f,t.style.position="fixed",t.style.top=`${l}px`,t.style.left=`${c}px`,t.style.width=`${r}px`,t.style.height=`${p}px`,t.style.right="auto",t.style.bottom="auto"}else{if(Z==="")return;Z="",t.style.position="",t.style.top="",t.style.left="",t.style.width="",t.style.height="",t.style.right="",t.style.bottom=""}}window.visualViewport?.addEventListener("resize",R),window.visualViewport?.addEventListener("scroll",R),window.addEventListener("resize",R),document.addEventListener("click",R);const Mt=document.querySelector(".sidebar");Mt&&new MutationObserver(R).observe(Mt,{attributes:!0,attributeFilter:["class"]}),window.__syncBotsViewport=R;function tt(){const t=d.approvals.length,e=document.getElementById("bots-inbox-badge");e&&(e.style.display=t?"inline-block":"none",e.textContent=String(t));const n=document.getElementById("bv-inbox-count");n&&(n.textContent=t?`(${t})`:""),window.__botsSnapshot=d.bots,window.__refreshSidebar?.()}function Kt(){const t=document.getElementById("set-bot-templates"),e=document.getElementById("set-bot-new"),n=document.getElementById("set-bot-inbox"),o=()=>{document.getElementById("settings-popover")?.classList.remove("open"),document.getElementById("settings-backdrop")?.classList.remove("open")};t?.addEventListener("click",()=>{o(),X()}),e?.addEventListener("click",()=>{o(),ue()}),n?.addEventListener("click",()=>{o(),Et()})}function Gt(){const t=i("div","bots-view");t.id="bots-view",t.hidden=!0;const e=i("div","bots-view-head"),n=i("div","bv-title"),o=i("span","bots-dot");o.id="bv-dot";const s=i("span","bv-title-text");s.id="bv-title";const a=i("span","bv-status");a.id="bv-status",n.append(o,s,a);const l=i("div","bv-actions"),c=i("div","bv-mode"),r=i("button","bv-mode-btn");r.id="bv-mode-btn",r.type="button",r.setAttribute("aria-haspopup","menu"),r.setAttribute("aria-expanded","false"),Jt(r,"supervised");const p=i("div","bv-menu bv-mode-menu");p.id="bv-mode-menu",p.setAttribute("role","menu"),p.hidden=!0;for(const[u,k,B]of[["supervised","\u9ED8\u8BA4","\u53EA\u8BFB\u5DE5\u5177\uFF08read/grep/find/ls\uFF09\u76F4\u63A5\u653E\u884C\uFF1Bbash\u3001edit\u3001write\u3001\u6269\u5C55/MCP \u5DE5\u5177\u4F1A\u95EE\u4F60"],["parent-supervised","\u76D1\u7BA1","\u5176\u4F59\u5DE5\u5177\u4EA4\u7ED9\u4E0A\u7EA7 bot \u51B3\u5B9A\uFF08\u5E26\u7406\u7531\uFF09\uFF1B\u4F60\u4ECD\u7136\u80FD\u770B\u5230\u5E76\u56DE\u7B54\uFF0C\u5148\u7B54\u5148\u5F97\uFF1B\u6CA1\u6709\u4E0A\u7EA7\u65F6\u56DE\u843D\u5230\u9ED8\u8BA4"],["full-access","\u5168\u653E\u884C","\u6240\u6709\u5DE5\u5177\u76F4\u63A5\u6267\u884C\uFF0C\u4E0D\u518D\u8BE2\u95EE\u3002\u6CE8\u610F\u8FD9\u4E0D\u662F\u6C99\u7BB1"]]){const W=i("button","bv-menu-item");W.dataset.mode=u,W.setAttribute("role","menuitemradio"),W.innerHTML=`<span class="bv-menu-icon">${H(_t[u],'width="15" height="15"')}</span><span class="bv-menu-text"><b>${k}</b><span>${B}</span></span><span class="bv-menu-check">${H("check",'width="13" height="13"')}</span>`,W.onclick=()=>{f(!1),te(u)},p.appendChild(W)}const f=u=>{u&&L(!1),p.hidden=!u,r.setAttribute("aria-expanded",u?"true":"false")};r.onclick=u=>{u.stopPropagation(),f(p.hidden)},c.append(r);const b=i("button","btn bv-inbox");b.id="bv-inbox",b.title="Requests waiting for you";const v=i("span",void 0,"Needs you"),y=i("span","bv-inbox-count");y.id="bv-inbox-count",b.append(v,y),b.onclick=()=>void Et();const h=i("button","bv-icon-btn");h.id="bv-more-btn",h.type="button",h.title="More actions",h.setAttribute("aria-label","More actions"),h.setAttribute("aria-haspopup","menu"),h.setAttribute("aria-expanded","false"),h.innerHTML=H("dots",'width="16" height="16"');const S=i("div","bv-menu");S.id="bv-more-menu",S.setAttribute("role","menu"),S.hidden=!0;const C=(u,k,B,W)=>{const G=i("button",`bv-menu-item${u?` ${u}`:""}`);return G.type="button",G.setAttribute("role","menuitem"),G.innerHTML=`<span class="bv-menu-icon">${H(k,'width="15" height="15"')}</span><span class="bv-menu-text"><b>${B}</b></span>`,G.onclick=()=>{L(!1),W()},G},M=C("","check","Allow all",()=>{if(!d.activeId)return;const u=d.approvals.filter(k=>k.botId===d.activeId);Promise.all(u.map(k=>x(`/api/bots/${k.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:k.id,allow:!0})}))).finally(()=>void T(!0))});M.id="bv-allow-all",M.title="Approve every pending request for this bot";const Q=C("","refresh","Resume bot",()=>Dt(u=>x(`/api/bots/${u}/resume`,{method:"POST"}).then(()=>T(!0)))),J=C("","stop","Stop run",()=>Dt(u=>x(`/api/bots/${u}/stop`,{method:"POST"}).then(()=>T(!0)))),Y=C("danger","delete","Delete bot",()=>{d.activeId&&confirm("Delete this bot and its session?")&&x(`/api/bots/${d.activeId}`,{method:"DELETE"}).then(()=>{yt(),T(!0)})});S.append(M,Q,J,i("div","bv-menu-sep"),Y);const L=u=>{u&&f(!1),S.hidden=!u,h.setAttribute("aria-expanded",u?"true":"false")};h.onclick=u=>{u.stopPropagation(),L(S.hidden)},document.addEventListener("click",u=>{const k=u.target;k&&(!c.contains(k)&&!p.contains(k)&&f(!1),!h.contains(k)&&!S.contains(k)&&L(!1))}),l.append(c,b,h),e.append(n,l);const g=i("div","bots-messages");g.id="bots-messages";const $=i("button","bv-jump");$.type="button",$.id="bv-jump",$.innerHTML=`${H("chevron-down",'width="14" height="14"')}<span>Latest</span>`,$.title="Jump to the latest message",$.hidden=!0,$.onclick=()=>{O=!0,g.scrollTop=g.scrollHeight,$.hidden=!0};const m=()=>{O=g.scrollHeight-g.scrollTop-g.clientHeight<48,$.hidden=O};g.addEventListener("scroll",m,{passive:!0}),g.addEventListener("touchmove",()=>{O=!1,$.hidden=g.scrollHeight-g.clientHeight<1},{passive:!0}),g.addEventListener("wheel",()=>{O=!1},{passive:!0});const I=i("div","bots-composer-wrap"),E=i("div","bv-queue");E.id="bv-queue",E.hidden=!0;const lt=i("span","bv-queue-text"),w=i("button","bv-queue-clear","Clear");w.type="button",w.title="Drop the queued messages",w.onclick=()=>{d.activeId&&x(`/api/bots/${d.activeId}/queue/clear`,{method:"POST"}).then(()=>vt(),u=>P(u instanceof Error?u.message:String(u)))},E.append(lt,w);const dt=i("div","bv-attach-strip");dt.id="bv-attach-strip",dt.hidden=!0;const ct=i("div","bv-composer-error");ct.id="bv-composer-error",ct.hidden=!0;const pt=i("div","bv-suggest");pt.id="bv-suggest",pt.hidden=!0;const ut=i("div","bots-composer"),U=i("button","bv-attach-btn");U.type="button",U.id="bv-attach",U.title="Attach an image",U.setAttribute("aria-label","Attach an image"),U.innerHTML=H("attach",'width="18" height="18"');const N=i("input");N.type="file",N.accept="image/*",N.multiple=!0,N.hidden=!0,U.onclick=()=>N.click(),N.onchange=()=>{for(const u of Array.from(N.files??[]))bt(u);N.value=""};const A=i("textarea");A.id="bots-input",A.rows=1,A.placeholder="Message the bot\u2026",A.spellcheck=!1;const It=window.matchMedia("(pointer: coarse)").matches;It||(A.enterKeyHint="send"),A.onkeydown=u=>{Yt(u)||u.key!=="Enter"||u.shiftKey||u.isComposing||It||u.keyCode===229||(u.preventDefault(),jt())},A.oninput=()=>{P(null),et(A),qt()},A.onclick=()=>qt(),A.addEventListener("paste",u=>{const k=Array.from(u.clipboardData?.files??[]).filter(B=>B.type.startsWith("image/"));if(k.length!==0){u.preventDefault();for(const B of k)bt(B)}});const z=i("button","btn primary");z.id="bv-send",z.title="Send",z.setAttribute("aria-label","Send"),z.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V5M5 12l7-7 7 7"/></svg>',z.onclick=()=>void jt(),ut.append(U,A,z),ut.addEventListener("click",u=>{const k=u.target;k?.closest("button")&&_(),!k?.closest("button")&&document.activeElement!==A&&A.focus()}),I.addEventListener("dragover",u=>{u.dataTransfer&&(u.preventDefault(),I.classList.add("drop-target"))}),I.addEventListener("dragleave",()=>I.classList.remove("drop-target")),I.addEventListener("drop",u=>{u.preventDefault(),I.classList.remove("drop-target");const k=Array.from(u.dataTransfer?.files??[]).filter(B=>B.type.startsWith("image/"));for(const B of k)bt(B)}),I.append(E,dt,pt,ct,N,ut),t.append(e,g,$,I,p,S),document.querySelector(".main-area")?.appendChild(t),document.getElementById("bots-modal")||ce()}function P(t){const e=document.getElementById("bv-composer-error");e&&(e.textContent=t??"",e.hidden=!t)}function Ot(t){const e=document.getElementById("bv-send");e&&(e.disabled=t,e.setAttribute("aria-busy",t?"true":"false"),e.title=t?"Sending\u2026":"Send")}const j=[],Lt=4,Xt=4*1024*1024;function et(t){t.style.height="auto";const e=window.matchMedia("(max-width: 640px)").matches?132:160;t.style.height=`${Math.min(e,t.scrollHeight)}px`}function nt(){const t=document.getElementById("bv-attach-strip");t&&(t.textContent="",t.hidden=j.length===0,j.forEach((e,n)=>{const o=i("span","bv-attach-chip"),s=i("img");s.src=e.preview,s.alt=e.name;const a=i("button","bv-attach-remove","\xD7");a.type="button",a.title=`Remove ${e.name}`,a.setAttribute("aria-label",`Remove ${e.name}`),a.onclick=()=>{j.splice(n,1),nt()},o.append(s,a),t.appendChild(o)}))}async function bt(t){if(!t.type.startsWith("image/")){P("Only image attachments are supported.");return}if(j.length>=Lt){P(`At most ${Lt} images per message.`);return}if(t.size>Xt){P("Images must be smaller than 4 MB.");return}const e=await new Promise((o,s)=>{const a=new FileReader;a.onload=()=>o(String(a.result??"")),a.onerror=()=>s(new Error("could not read the image")),a.readAsDataURL(t)}),n=e.indexOf(",");j.push({data:e.slice(n+1),mimeType:t.type,name:t.name||"image",preview:e}),P(null),nt()}function vt(){const t=document.getElementById("bv-queue");if(!t)return;const e=d.activeId?d.queues.get(d.activeId):void 0,n=e?.steering.length??0,o=e?.followUp.length??0;if(n+o===0){t.hidden=!0;return}const s=[];n&&s.push(`${n} steering`),o&&s.push(`${o} follow-up`),t.hidden=!1;const a=t.querySelector(".bv-queue-text");a&&(a.textContent=`Queued \xB7 ${s.join(" \xB7 ")}`)}let D=[],K=0,ot=null,be=null;function _(){const t=document.getElementById("bv-suggest");t&&(t.hidden=!0),D=[],ot=null}function gt(){const t=document.getElementById("bv-suggest");if(t){if(t.textContent="",D.length===0){t.hidden=!0;return}t.hidden=!1,D.forEach((e,n)=>{const o=i("button",`bv-suggest-item${n===K?" active":""}`);o.type="button",o.innerHTML=`<span class="bv-suggest-kind">${e.kind==="file"?"@":"/"}</span><span class="bv-suggest-label">${Nt(e.label)}</span><span class="bv-suggest-detail">${Nt(e.detail)}</span>`,o.onmousedown=s=>s.preventDefault(),o.onclick=()=>Pt(n),t.appendChild(o)})}}function Nt(t){return t.replace(/[&<>"]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[e])}async function qt(){const t=document.getElementById("bots-input");if(!t)return;const e=t.selectionStart??t.value.length,n=t.value.slice(0,e),o=/(^|\s)([/@])([^\s]*)$/.exec(n);if(!o){_();return}const s=o[2],a=o[3];if(ot={start:e-a.length-1,end:e},s==="/"){const b=d.catalog,v=(b?.prompts??[]).map(h=>({kind:"prompt",label:`/${h.name}`,detail:"prompt template",value:`/${h.name} `})),y=(b?.skills??[]).map(h=>({kind:"skill",label:`/skill:${h.name}`,detail:h.description||"skill",value:`/skill:${h.name} `}));D=[...v,...y].filter(h=>h.label.toLowerCase().includes(a.toLowerCase())||h.detail.toLowerCase().includes(a.toLowerCase())).slice(0,8),K=0,gt();return}const c=it();if(!c){_();return}const r=a.lastIndexOf("/"),p=r>=0?`${c.projectPath}/${a.slice(0,r)}`:c.projectPath,f=r>=0?a.slice(r+1):a;try{D=((await x(`/api/fs/list?path=${encodeURIComponent(p)}`)).entries??[]).filter(y=>y.name.toLowerCase().startsWith(f.toLowerCase())).slice(0,8).map(y=>{const h=r>=0?a.slice(0,r+1):"";return{kind:"file",label:`@${h}${y.name}${y.type==="dir"?"/":""}`,detail:y.type==="dir"?"directory":"file",value:`@${h}${y.name}${y.type==="dir"?"/":" "}`}}),K=0,gt()}catch{_()}}function Pt(t){const e=document.getElementById("bots-input"),n=D[t];if(!e||!n||!ot)return;const{start:o,end:s}=ot;e.value=`${e.value.slice(0,o)}${n.value}${e.value.slice(s)}`;const a=o+n.value.length;_(),e.focus(),e.setSelectionRange(a,a),et(e)}function Yt(t){const e=document.getElementById("bv-suggest");if(!e||e.hidden||D.length===0)return!1;if(t.key==="ArrowDown"||t.key==="ArrowUp"){t.preventDefault();const n=t.key==="ArrowDown"?1:-1;return K=(K+n+D.length)%D.length,gt(),!0}return t.key==="Enter"||t.key==="Tab"?(t.preventDefault(),Pt(K),!0):t.key==="Escape"?(t.preventDefault(),_(),!0):!1}async function jt(){const t=document.getElementById("bots-input");if(!t||!d.activeId||Qt||!t.value.trim()&&j.length===0)return;const e=d.activeId,n=t.value.trim()?t.value:"See the attached image",o=j.map(({data:s,mimeType:a})=>({data:s,mimeType:a}));P(null),Ot(!0);try{await x(`/api/bots/${e}/input`,{method:"POST",body:JSON.stringify({text:n,images:o.length?o:void 0})}),t.value===n&&(t.value="",et(t)),_(),j.length=0,nt(),O=!0}catch(s){P(s instanceof Error?s.message:String(s))}finally{Ot(!1)}}function Dt(t){d.activeId&&t(d.activeId).catch(e=>V({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)}))}function yt(){d.activeId=null,q=[],O=!0,R();const t=document.getElementById("bots-view");t&&(t.hidden=!0);try{d.ws?.close()}catch{}d.ws=null,tt();const e=document.getElementById("terminal-container"),n=document.getElementById("main-placeholder"),o=!!document.querySelector(".session-item.active:not(.bot-item)");e&&o?(e.style.display="",n&&(n.style.display="none")):n&&(n.style.display="")}async function Ht(t){d.activeId=t,q=[],O=!0,j.length=0,nt(),vt(),_();const e=document.getElementById("bots-input");e&&(e.value="",et(e)),P(null);const n=document.getElementById("bv-jump");n&&(n.hidden=!0),window.__collapseSidebar?.(),R(),d.items.set(t,[]);const o=document.getElementById("bots-view");o&&(o.hidden=!1);const s=document.getElementById("main-placeholder");s&&(s.style.display="none");const a=document.getElementById("terminal-container");a&&(a.style.display="none");const l=document.getElementById("file-editor");l&&(l.style.display="none"),tt(),st();try{d.ws?.close()}catch{}const c=location.protocol==="https:"?"wss:":"ws:",r=new WebSocket(`${c}//${location.host}/ws/bots/${encodeURIComponent(t)}?token=${encodeURIComponent(ft())}`);d.ws=r,r.onmessage=p=>{try{Ut(JSON.parse(String(p.data)))}catch{}},r.onclose=()=>{d.activeId===t&&setTimeout(()=>{d.activeId===t&&T(!0)},1500)},await T(!0)}function it(){return d.bots.find(t=>t.id===d.activeId)||null}function wt(){const t=it();if(!t)return;const e=document.getElementById("bv-title"),n=document.getElementById("bv-status"),o=document.getElementById("bv-dot");e&&(e.textContent=t.title),n&&(n.textContent=Zt[t.status]??t.status.replace(/_/g," "),n.dataset.status=t.status,n.style.color=Tt(t.status),n.title=`${t.status.replace(/_/g," ")} \xB7 ${t.templateId} \xB7 ${t.projectPath}`);const s=document.getElementById("bv-mode-btn");s&&Jt(s,t.runtimeMode||"supervised");for(const c of document.querySelectorAll("#bv-mode-menu button")){const r=c.dataset.mode===t.runtimeMode;c.classList.toggle("active",r),c.setAttribute("aria-checked",r?"true":"false")}const a=document.getElementById("bv-allow-all"),l=d.approvals.filter(c=>c.botId===t.id).length;if(a){a.hidden=l===0;const c=a.querySelector(".bv-menu-text b");c&&(c.textContent=`Allow all (${l})`)}o&&(o.style.background=Tt(t.status))}const Zt={queued:"queued",starting:"starting",running:"running",waiting_input:"waiting",waiting_approval:"approval",completed:"done",failed:"failed",cancelled:"stopped",stale:"stale"},Rt={supervised:"\u9ED8\u8BA4","parent-supervised":"\u76D1\u7BA1","full-access":"\u5168\u653E\u884C"},_t={supervised:"shield","parent-supervised":"shield-up","full-access":"shield-alert"};function Jt(t,e){const n=_t[e]??"shield";t.dataset.mode=e,t.innerHTML=H(n,'width="15" height="15"');const o=`\u5BA1\u6279\u6A21\u5F0F\uFF1A${Rt[e]??e}`;t.title=`${o}\uFF08\u70B9\u5F00\u53EF\u5207\u6362\uFF09`,t.setAttribute("aria-label",o)}async function te(t){if(d.activeId)try{await x(`/api/bots/${d.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:t})});const e=it();e&&(e.runtimeMode=t),wt(),V({kind:"notice",level:"info",text:`\u5BA1\u6279\u6A21\u5F0F\uFF1A${Rt[t]||t}`})}catch(e){V({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)})}}function V(t,e=d.activeId){if(!e)return;const n=d.items.get(e)||[];n.push(t),d.items.set(e,n),e===d.activeId&&F()}function F(){if(d.renderQueued)return;d.renderQueued=!0;const t=Math.max(0,60-(performance.now()-Bt));window.setTimeout(()=>{d.renderQueued=!1,Bt=performance.now(),st()},t)}function kt(t){switch(t.kind){case"assistant":return{text:t.text,thinking:t.thinking};case"tool":return{phase:t.phase,output:t.output,error:t.isError,durationMs:t.durationMs};case"approval":return{decided:t.decided,approvalState:t.approval.state};default:return{}}}function ee(t,e){return t.text!==e.text||t.thinking!==e.thinking||t.phase!==e.phase||t.output!==e.output||t.error!==e.error||t.durationMs!==e.durationMs||t.decided!==e.decided||t.approvalState!==e.approvalState}function xt(t){if(t.kind==="user"){const e=i("div","bv-msg bv-user");return e.appendChild(mt(t.text)),e}if(t.kind==="assistant"){const e=i("div","bv-msg bv-assistant");if(t.thinking){const o=i("details","bv-thinking");o.appendChild(i("summary",void 0,"thinking")),o.appendChild(i("div",void 0,t.thinking)),e.appendChild(o)}const n=i("div","bv-text");return n.appendChild(mt(t.text)),e.appendChild(n),e}return t.kind==="tool"?ie(t):t.kind==="approval"?se(t):i("div",`bv-notice bv-notice-${t.level}`,t.text)}function ne(t,e){const n=t.querySelector("details.bv-thinking");if(e.thinking)if(n){const s=n.querySelector("div");s&&s.textContent!==e.thinking&&(s.textContent=e.thinking)}else{const s=i("details","bv-thinking");s.appendChild(i("summary",void 0,"thinking")),s.appendChild(i("div",void 0,e.thinking)),t.prepend(s)}else n&&n.remove();const o=t.querySelector(".bv-text");o&&o.replaceChildren(mt(e.text))}function st(){const t=document.getElementById("bots-messages");if(!t||!d.activeId||document.getElementById("bots-view")?.hidden)return;const e=d.items.get(d.activeId)||[],n=Math.max(0,e.length-At),o=n?e.slice(n):e,s=O;if(o.length<q.length||o.some((l,c)=>q[c]?.item!==l))t.textContent="",q=o.map(l=>{const c=xt(l);return t.appendChild(c),{item:l,snapshot:kt(l),node:c}});else{for(let l=q.length;l<o.length;l++){const c=o[l],r=xt(c);t.appendChild(r),q.push({item:c,snapshot:kt(c),node:r})}for(let l=0;l<o.length;l++){const c=o[l],r=q[l],p=kt(c);if(ee(r.snapshot,p)){if(c.kind==="assistant")ne(r.node,c);else{const f=xt(c);r.node.replaceWith(f),r.node=f}r.snapshot=p}}}oe(t,n),s&&(t.scrollTop=t.scrollHeight)}function oe(t,e){const n=t.querySelector(":scope > .bv-earlier");if(e===0){n?.remove();return}const o=`Show earlier messages (${e})`;if(n){n.textContent!==o&&(n.textContent=o);return}const s=i("button","bv-earlier",o);s.type="button",s.onclick=()=>{const a=t.scrollHeight,l=t.scrollTop;At+=$t,q=[],st(),t.scrollTop=l+(t.scrollHeight-a)},t.prepend(s)}function ie(t){const e=i("details","bv-tool");e.open=t.phase!=="end"||!!t.isError;const n=i("summary"),o=i("span","bv-tool-name",t.name);if(n.appendChild(o),t.phase!=="end"&&n.appendChild(i("span","bv-tool-phase",t.phase)),t.isError&&n.appendChild(i("span","bv-tool-error","error")),typeof t.durationMs=="number"&&n.appendChild(i("span","bv-tool-meta",`${Math.round(t.durationMs)}ms`)),e.appendChild(n),t.args!==void 0){const s=i("pre","bv-pre");s.textContent=typeof t.args=="string"?t.args:JSON.stringify(t.args,null,2),e.appendChild(s)}if(t.output){const s=i("pre","bv-pre bv-output");s.textContent=t.output,e.appendChild(s)}return e}function se(t){const e=i("div","bv-approval"),n=t.approval;if(e.appendChild(i("div","bv-approval-tag","Needs approval")),e.appendChild(i("div","bv-approval-title",n.title)),n.message){const v=i("pre","bv-pre bv-approval-detail");v.textContent=n.message,e.appendChild(v)}if(t.decided)return e.appendChild(i("div","bv-approval-decided",t.decided==="allowed"?"Allowed":"Denied")),e;const o=i("input","bv-reason");o.placeholder="reason (optional)",o.setAttribute("aria-label","Reason (optional)");const s=i("div","bv-approval-actions"),a=i("button","btn primary","Allow once"),l=/^Allow (.+?)\?$/.exec(n.title)?.[1],c=n.method==="confirm"?l&&l.length<=24?`Always allow ${l}`:"Always allow this tool":"Allow for this session",r=i("button","btn",c);r.hidden=n.method!=="confirm";const p=i("button","btn danger","Deny"),f=[a,r,p],b=async(v,y,h)=>{const S=h.textContent??"";for(const C of f)C.disabled=!0;h.textContent=v?"Allowing\u2026":"Denying\u2026";try{await x(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:v,always:y,reason:o.value||void 0})}),t.decided=v?"allowed":"denied",F(),T(!0)}catch(C){for(const M of f)M.disabled=!1;h.textContent=S,V({kind:"notice",level:"error",text:C instanceof Error?C.message:String(C)})}};return a.onclick=()=>void b(!0,!1,a),r.onclick=()=>void b(!0,!0,r),p.onclick=()=>void b(!1,!1,p),s.append(o,a,r,p),e.appendChild(s),e}function Ut(t){const e=String(t.type||""),n=d.activeId;if(!n)return;const o=d.items.get(n)||[];if(e==="snapshot")d.items.set(n,[]);else if(e==="queue")d.queues.set(n,{steering:Array.isArray(t.steering)?t.steering:[],followUp:Array.isArray(t.followUp)?t.followUp:[]}),vt();else if(e==="user")O=!0,V({kind:"user",text:String(t.text||"")});else if(e==="status"){const s=it();s&&(s.status=String(t.status||s.status)),wt(),le()}else if(e==="message"){const s=t.message;if(!s||String(s.role||"")!=="assistant")return;const l=ae(s),c=re(s),r=o[o.length-1];r&&r.kind==="assistant"?(r.text=l||r.text,r.thinking=c||r.thinking):o.push({kind:"assistant",text:l,thinking:c}),d.items.set(n,o),F()}else if(e==="delta"){const s=String(t.kind||""),a=String(t.delta||"");let l=o[o.length-1];(!l||l.kind!=="assistant")&&(o.push({kind:"assistant",text:"",thinking:""}),l=o[o.length-1]),l.kind==="assistant"&&(s==="text"?l.text+=a:s==="thinking"&&(l.thinking+=a)),d.items.set(n,o),F()}else if(e==="tool"){const s=String(t.callId||""),a=o.find(c=>c.kind==="tool"&&c.callId===s),l=String(t.phase||"start");a?(a.phase=l,l==="update"&&t.output&&(a.output=String(t.output)),l==="end"&&(t.output&&(a.output=String(t.output)),a.isError=t.isError===!0,typeof t.durationMs=="number"&&(a.durationMs=t.durationMs))):o.push({kind:"tool",callId:s,name:String(t.name||"tool"),args:t.args,output:t.output?String(t.output):void 0,isError:t.isError===!0,durationMs:typeof t.durationMs=="number"?t.durationMs:void 0,phase:l}),d.items.set(n,o),F()}else if(e==="approval"){const s=t.approval;if(!s)return;const a=o;for(let l=a.length-1;l>=0;l--){const c=a[l];if(c.kind==="approval"&&c.approval.id===s.id){c.approval=s,s.state!=="pending"&&(c.decided=s.state==="allowed"?"allowed":"denied"),d.items.set(n,a),F();return}}a.push({kind:"approval",approval:s}),d.items.set(n,a),F()}else e==="notice"&&V({kind:"notice",level:String(t.level||"info"),text:String(t.text||"")})}function ae(t){const e=t.content;return Array.isArray(e)?e.map(n=>n&&typeof n=="object"&&n.type==="text"?String(n.text||""):"").join(""):String(t.text||"")}function re(t){const e=t.content;return Array.isArray(e)?e.map(n=>n&&typeof n=="object"&&n.type==="thinking"?String(n.thinking||""):"").join(""):""}async function T(t=!1){try{const[e,n]=await Promise.all([x("/api/bots"),x("/api/bots/approvals")]);if(d.bots=e,d.approvals=n,tt(),wt(),t&&d.activeId){const o=await x(`/api/bots/${d.activeId}/events?limit=300`);de(o)}}catch{}}async function le(){try{d.bots=await x("/api/bots"),tt()}catch{}}function de(t){if(d.activeId){d.items.set(d.activeId,[]);for(const e of t)Ut(e);st()}}function ce(){const t=i("div","bots-modal");t.id="bots-modal",t.hidden=!0;const e=i("div","bots-modal-card"),n=i("div","bots-modal-head"),o=i("span");o.id="bots-modal-title";const s=i("button","btn");s.innerHTML=H("close",'width="14" height="14"'),s.title="Close",s.onclick=()=>at(),n.append(o,s);const a=i("div","bots-modal-body");a.id="bots-modal-body",e.append(n,a),t.appendChild(e),t.onclick=l=>{l.target===t&&at()},document.body.appendChild(t)}function St(t){const e=document.getElementById("bots-modal"),n=document.getElementById("bots-modal-title"),o=document.getElementById("bots-modal-body");if(!e||!o)throw new Error("modal missing");return n&&(n.textContent=t),o.textContent="",e.hidden=!1,o}function at(){const t=document.getElementById("bots-modal");t&&(t.hidden=!0)}async function pe(){return d.catalog||(d.catalog=await x("/api/bots/catalog")),d.catalog}async function Wt(){return d.templates=await x("/api/bots/templates"),d.templates}async function X(){const t=St("Bot templates"),[e,n]=await Promise.all([pe(),Wt()]),o=i("div","bv-template-list");for(const r of n){const p=i("div","bv-template-row");p.appendChild(i("span","bv-template-name",r.manifest.name)),p.appendChild(i("span","bv-template-desc",r.manifest.description||""));const f=i("button","btn","Edit");f.onclick=()=>Vt(t,e,r);const b=i("button","btn","Copy");b.title="Duplicate this template",b.onclick=()=>{const h=JSON.parse(JSON.stringify(r.manifest));h.name=`${r.manifest.name} copy`,x("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:h})}).then(()=>X()).catch(S=>alert(S instanceof Error?S.message:String(S)))};const v=i("button","btn danger","Delete");v.onclick=()=>{confirm(`Delete template ${r.manifest.name}?`)&&x(`/api/bots/templates/${r.id}`,{method:"DELETE"}).then(()=>X())};const y=i("span","bv-template-actions");y.append(f,b,v),p.appendChild(y),o.appendChild(p)}n.length===0&&o.appendChild(i("div","bots-empty","No templates yet")),t.appendChild(o);const s=i("div","bv-template-actions"),a=i("button","btn primary","New template");a.onclick=()=>Vt(t,e,null);const l=i("button","btn","Export");l.title="Download templates + library as JSON",l.onclick=()=>{(async()=>{try{const r=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${ft()}`}});if(!r.ok)throw new Error(`HTTP ${r.status}`);const p=await r.blob(),f=document.createElement("a");f.href=URL.createObjectURL(p),f.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,f.click(),setTimeout(()=>URL.revokeObjectURL(f.href),2e3)}catch(r){alert(r instanceof Error?r.message:String(r))}})()};const c=i("button","btn","Import");c.title="Restore templates from a JSON bundle",c.onclick=()=>{const r=document.createElement("input");r.type="file",r.accept="application/json,.json",r.onchange=()=>{const p=r.files?.[0];p&&(async()=>{try{const f=JSON.parse(await p.text()),b=await x("/api/bots/import",{method:"POST",body:JSON.stringify(f)});alert(`Imported ${b.templates} templates, ${b.files} library files (${b.skipped} kept)`),await X()}catch(f){alert(f instanceof Error?f.message:String(f))}})()},r.click()},s.append(a,l,c),t.appendChild(s)}function Ct(t,e,n){const o=i("div","bv-field");o.appendChild(i("label","bv-label",t));const s=i("div","bv-check-grid"),a=[];for(const l of e){const c=i("label","bv-check"),r=document.createElement("input");r.type="checkbox",r.checked=n.includes(l.id),c.append(r,i("span",void 0,l.label)),l.hint&&(c.title=l.hint),s.appendChild(c),a.push({id:l.id,input:r})}return o.appendChild(s),{element:o,get:()=>a.filter(l=>l.input.checked).map(l=>l.id)}}function Vt(t,e,n){t.textContent="";const o=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},s=i("input","bv-input");s.value=o.name,s.placeholder="Template name";const a=i("input","bv-input");a.value=o.description||"",a.placeholder="One line description";const l=i("textarea","bv-textarea");l.rows=6,l.value=o.system||"",l.placeholder="System prompt for this bot (written to SYSTEM.md)";const c=Ct("Skills",e.skills.map(m=>({id:m.id,label:m.name,hint:m.description})),o.skills||[]),r=Ct("Extensions (Pi builtins + library)",e.extensions.map(m=>({id:m.id,label:`${m.name}${m.kind==="builtin"?" (builtin)":""}`,hint:m.description})),(o.extensions||[]).map(m=>m.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),p=Ct("Prompt templates",e.prompts.map(m=>({id:m.id,label:m.name})),o.prompts||[]),f=i("select","bv-input");f.appendChild(new Option("none",""));for(const m of e.mcp)f.appendChild(new Option(m.name,m.id));o.mcp&&(f.value=e.mcp.find(m=>JSON.stringify(m.servers)===JSON.stringify(o.mcp?.mcpServers))?.id||"");const b=i("div","bv-field");b.appendChild(i("label","bv-label","Tools (allow list; deny always blocks)"));const v=i("div","bv-check-grid"),y=[];for(const m of e.tools){const I=i("label","bv-check"),E=document.createElement("input");E.type="checkbox",E.checked=(o.tools?.allow||[]).includes(m.name)||!o.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(m.name),I.append(E,i("span",void 0,m.name)),v.appendChild(I),y.push({name:m.name,input:E})}b.appendChild(v);const h=i("input","bv-input");h.value=(o.tools?.deny||[]).join(", "),h.placeholder="Always deny (comma separated), e.g. bash, write";const S=i("textarea","bv-textarea");S.rows=2,S.value=(o.packages||[]).join(`
2
- `),S.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";const C=i("select","bv-input");C.appendChild(new Option("default (Pi settings)",""));for(const m of e.models)C.appendChild(new Option(`${m.provider}/${m.model}`,`${m.provider}
3
- ${m.model}`));o.model?.provider&&o.model?.id&&(C.value=`${o.model.provider}
4
- ${o.model.id}`);const M=i("select","bv-input");for(const m of["","off","minimal","low","medium","high","xhigh","max"])M.appendChild(new Option(m||"default",m));o.model?.thinking&&(M.value=o.model.thinking);const Q=i("select","bv-input");for(const m of["supervised","auto-accept-edits","full-access"])Q.appendChild(new Option(m,m));Q.value=o.permissions?.runtimeMode||"supervised";const J=i("select","bv-input");J.appendChild(new Option("ignore project .pi (recommended)","ignore")),J.appendChild(new Option("inherit project .pi (needs trust)","inherit")),J.value=o.projectResources||"ignore";const Y=i("label","bv-check"),L=document.createElement("input");L.type="checkbox",L.checked=!!o.orchestrator,Y.append(L,i("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));const g=(m,I)=>{const E=i("div","bv-field");return E.appendChild(i("label","bv-label",m)),E.appendChild(I),E};t.append(g("Name",s),g("Description",a),g("System prompt",l),c.element,r.element,p.element,g("MCP preset",f),b,g("Always deny tools",h),g("Packages",S),g("Model",C),g("Thinking level",M),g("Approval mode",Q),g("Project resources",J),Y);const $=i("button","btn primary",n?"Save template":"Create template");$.onclick=async()=>{const[m,I]=C.value.split(`
5
- `),E=e.mcp.find(w=>w.id===f.value),lt={name:s.value.trim()||"bot",description:a.value.trim()||void 0,system:l.value.trim()||void 0,skills:c.get(),extensions:r.get().map(w=>(w.startsWith("builtin:"),w)),prompts:p.get(),packages:S.value.split(`
6
- `).map(w=>w.trim()).filter(Boolean),mcp:E?{mcpServers:E.servers}:void 0,tools:{allow:y.filter(w=>w.input.checked).map(w=>w.name),deny:h.value.split(",").map(w=>w.trim()).filter(Boolean)},model:m?{provider:m,id:I,thinking:M.value||void 0}:void 0,permissions:{runtimeMode:Q.value},projectResources:J.value==="inherit"?"inherit":"ignore",orchestrator:L.checked||void 0};try{await x("/api/bots/templates",{method:"POST",body:JSON.stringify({id:n?.id,manifest:lt})}),at(),await X()}catch(w){alert(w instanceof Error?w.message:String(w))}},t.appendChild($)}async function ue(){return me("")}async function me(t){const e=St("New bot"),n=await Wt();if(n.length===0){e.appendChild(i("div","bots-empty","No templates yet \u2014 create one with \u201CNew template\u201D."));return}const o=i("select","bv-input");for(const p of n)o.appendChild(new Option(p.manifest.name,p.id));const s=i("input","bv-input");s.placeholder="Title (defaults to template name)";const a=i("input","bv-input");a.placeholder="/path/to/project";const l=t||d.bots[0]?.projectPath||"";a.value=l;const c=i("select","bv-input");c.appendChild(new Option("shared \u2014 run in the project folder","shared")),c.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),e.append(rt("Template",o),rt("Title",s),rt("Project path",a),rt("Workspace",c));const r=i("button","btn primary","Create bot");r.onclick=async()=>{try{const p=await x("/api/bots",{method:"POST",body:JSON.stringify({templateId:o.value,title:s.value.trim()||void 0,projectPath:a.value.trim()||void 0,isolation:c.value})});at(),await T(!0),await Ht(p.id)}catch(p){alert(p instanceof Error?p.message:String(p))}},e.appendChild(r)}function rt(t,e){const n=i("div","bv-field");return n.appendChild(i("label","bv-label",t)),n.appendChild(e),n}async function Et(){const t=St("Needs you");if(d.approvals=await x("/api/bots/approvals"),d.approvals.length===0){t.appendChild(i("div","bots-empty","Nothing waiting."));return}for(const e of d.approvals){const n=i("div","bv-approval");if(n.appendChild(i("div","bv-approval-tag",e.botTitle)),n.appendChild(i("div","bv-approval-title",e.title)),e.message){const p=i("pre","bv-pre bv-approval-detail");p.textContent=e.message,n.appendChild(p)}const o=i("input","bv-reason");o.placeholder="reason (optional)",o.setAttribute("aria-label","Reason (optional)");const s=i("div","bv-approval-actions"),a=i("button","btn primary","Allow once"),l=i("button","btn danger","Deny"),c=[a,l],r=async(p,f)=>{const b=f.textContent??"";for(const v of c)v.disabled=!0;f.textContent=p?"Allowing\u2026":"Denying\u2026";try{await x(`/api/bots/${e.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:e.id,allow:p,reason:o.value||void 0})}),await T(!0),await Et()}catch(v){for(const y of c)y.disabled=!1;f.textContent=b,V({kind:"notice",level:"error",text:v instanceof Error?v.message:String(v)})}};a.onclick=()=>void r(!0,a),l.onclick=()=>void r(!1,l),s.append(o,a,l),n.appendChild(s),t.appendChild(n)}}function ve(){window.__botsInited||(window.__botsInited=!0,Gt(),Kt(),window.__openBot=Ht,document.addEventListener("click",t=>{const e=t.target;e&&(e.closest(".session-item.bot-item")||e.closest(".session-item")&&d.activeId&&setTimeout(()=>yt(),0))},!0),document.addEventListener("click",t=>{const e=t.target;!e||!d.activeId||(e.closest("#mode-files")||e.closest(".file-tree-item")||e.closest(".file-roots-list li"))&&yt()}),T(!0),d.pollTimer=window.setInterval(()=>{document.hidden||T()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(d.pollTimer)))}export{ve as initBots,me as openNewBotForPath};
1
+ import{icon as H}from"../lib/icons.js";import{createMarkdownRenderer as Qe}from"./markdown.js";const fe=Qe(document),d={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,queues:new Map,ws:null,pollTimer:0,renderQueued:!1};let L=[],M=!0;const Be=200;let Ae=Be,ze=!1,Te=0;function he(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function g(e,t){const n=await fetch(e,{...t,headers:{"content-type":"application/json",Authorization:`Bearer ${he()}`,...t?.headers||{}}}),o=await n.text(),s=o?JSON.parse(o):null;if(!n.ok)throw new Error(s&&s.error||`HTTP ${n.status}`);return s}function i(e,t,n){const o=document.createElement(e);return t&&(o.className=t),n!==void 0&&(o.textContent=n),o}function Me(e){return e==="running"?"var(--panel-success)":e==="waiting_approval"||e==="waiting_input"?"#e0a23c":e==="failed"?"var(--panel-danger, #e5534b)":e==="completed"?"var(--panel-accent)":"var(--panel-muted)"}function R(){be||(be=requestAnimationFrame(()=>{be=0,Ke()}))}let be=0,ne="";function Ke(){const e=document.getElementById("bots-view");if(!e)return;const t=window.visualViewport,n=window.matchMedia("(max-width: 640px)").matches,o=document.querySelector(".sidebar")?.classList.contains("open")===!0;if(d.activeId&&t&&n&&!o){const s=document.querySelector(".fixed-header"),a=s?Math.round(s.getBoundingClientRect().height):0,l=Math.round(t.offsetTop)+a,c=Math.round(t.offsetLeft),r=Math.round(t.width),p=Math.max(120,Math.round(t.height)-a),f=`fixed|${l}|${c}|${r}|${p}`;if(f===ne)return;ne=f,e.style.position="fixed",e.style.top=`${l}px`,e.style.left=`${c}px`,e.style.width=`${r}px`,e.style.height=`${p}px`,e.style.right="auto",e.style.bottom="auto"}else{if(ne==="")return;ne="",e.style.position="",e.style.top="",e.style.left="",e.style.width="",e.style.height="",e.style.right="",e.style.bottom=""}}window.visualViewport?.addEventListener("resize",R),window.visualViewport?.addEventListener("scroll",R),window.addEventListener("resize",R),document.addEventListener("click",R);const Oe=document.querySelector(".sidebar");Oe&&new MutationObserver(R).observe(Oe,{attributes:!0,attributeFilter:["class"]}),window.__syncBotsViewport=R;function oe(){const e=d.approvals.length,t=document.getElementById("bots-inbox-badge");t&&(t.style.display=e?"inline-block":"none",t.textContent=String(e));const n=document.getElementById("bv-inbox-count");n&&(n.textContent=e?`(${e})`:""),window.__botsSnapshot=d.bots,window.__refreshSidebar?.()}function Ge(){const e=document.getElementById("set-bot-templates"),t=document.getElementById("set-bot-new"),n=document.getElementById("set-bot-inbox"),o=()=>{document.getElementById("settings-popover")?.classList.remove("open"),document.getElementById("settings-backdrop")?.classList.remove("open")};e?.addEventListener("click",()=>{o(),Z()}),t?.addEventListener("click",()=>{o(),mt()}),n?.addEventListener("click",()=>{o(),Ie()})}function Xe(){const e=i("div","bots-view");e.id="bots-view",e.hidden=!0;const t=i("div","bots-view-head"),n=i("div","bv-title"),o=i("span","bots-dot");o.id="bv-dot";const s=i("span","bv-title-text");s.id="bv-title";const a=i("span","bv-status");a.id="bv-status",n.append(o,s,a);const l=i("div","bv-actions"),c=i("div","bv-mode"),r=i("button","bv-mode-btn");r.id="bv-mode-btn",r.type="button",r.setAttribute("aria-haspopup","menu"),r.setAttribute("aria-expanded","false"),Ue(r,"supervised");const p=i("div","bv-menu bv-mode-menu");p.id="bv-mode-menu",p.setAttribute("role","menu"),p.hidden=!0;for(const[m,w,T]of[["supervised","\u9ED8\u8BA4","\u53EA\u8BFB\u5DE5\u5177\uFF08read/grep/find/ls\uFF09\u76F4\u63A5\u653E\u884C\uFF1Bbash\u3001edit\u3001write\u3001\u6269\u5C55/MCP \u5DE5\u5177\u4F1A\u95EE\u4F60"],["parent-supervised","\u76D1\u7BA1","\u5176\u4F59\u5DE5\u5177\u4EA4\u7ED9\u4E0A\u7EA7 bot \u51B3\u5B9A\uFF08\u5E26\u7406\u7531\uFF09\uFF1B\u4F60\u4ECD\u7136\u80FD\u770B\u5230\u5E76\u56DE\u7B54\uFF0C\u5148\u7B54\u5148\u5F97\uFF1B\u6CA1\u6709\u4E0A\u7EA7\u65F6\u56DE\u843D\u5230\u9ED8\u8BA4"],["full-access","\u5168\u653E\u884C","\u6240\u6709\u5DE5\u5177\u76F4\u63A5\u6267\u884C\uFF0C\u4E0D\u518D\u8BE2\u95EE\u3002\u6CE8\u610F\u8FD9\u4E0D\u662F\u6C99\u7BB1"]]){const W=i("button","bv-menu-item");W.dataset.mode=m,W.setAttribute("role","menuitemradio"),W.innerHTML=`<span class="bv-menu-icon">${H(Je[m],'width="15" height="15"')}</span><span class="bv-menu-text"><b>${w}</b><span>${T}</span></span><span class="bv-menu-check">${H("check",'width="13" height="13"')}</span>`,W.onclick=()=>{f(!1),tt(m)},p.appendChild(W)}const f=m=>{m&&E(!1),p.hidden=!m,r.setAttribute("aria-expanded",m?"true":"false")};r.onclick=m=>{m.stopPropagation(),f(p.hidden)},c.append(r);const h=i("button","btn bv-resume","Resume");h.id="bv-resume",h.type="button",h.title="Continue this bot from its session",h.onclick=()=>{d.activeId&&(h.disabled=!0,g(`/api/bots/${d.activeId}/resume`,{method:"POST"}).then(()=>B(!0)).finally(()=>{h.disabled=!1}))},h.hidden=!0;const b=i("button","btn bv-inbox");b.id="bv-inbox",b.title="Requests waiting for you";const k=i("span",void 0,"Needs you"),v=i("span","bv-inbox-count");v.id="bv-inbox-count",b.append(k,v),b.onclick=()=>void Ie();const y=i("button","bv-icon-btn");y.id="bv-more-btn",y.type="button",y.title="More actions",y.setAttribute("aria-label","More actions"),y.setAttribute("aria-haspopup","menu"),y.setAttribute("aria-expanded","false"),y.innerHTML=H("dots",'width="16" height="16"');const x=i("div","bv-menu");x.id="bv-more-menu",x.setAttribute("role","menu"),x.hidden=!0;const A=(m,w,T,W)=>{const X=i("button",`bv-menu-item${m?` ${m}`:""}`);return X.type="button",X.setAttribute("role","menuitem"),X.innerHTML=`<span class="bv-menu-icon">${H(w,'width="15" height="15"')}</span><span class="bv-menu-text"><b>${T}</b></span>`,X.onclick=()=>{E(!1),W()},X},j=A("","check","Allow all",()=>{if(!d.activeId)return;const m=d.approvals.filter(w=>w.botId===d.activeId);Promise.all(m.map(w=>g(`/api/bots/${w.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:w.id,allow:!0})}))).finally(()=>void B(!0))});j.id="bv-allow-all",j.title="Approve every pending request for this bot";const J=A("","refresh","Resume bot",()=>He(m=>g(`/api/bots/${m}/resume`,{method:"POST"}).then(()=>B(!0)))),ee=A("","stop","Stop run",()=>He(m=>g(`/api/bots/${m}/stop`,{method:"POST"}).then(()=>B(!0)))),Q=A("danger","delete","Delete bot",()=>{d.activeId&&confirm("Delete this bot and its session?")&&g(`/api/bots/${d.activeId}`,{method:"DELETE"}).then(()=>{we(),B(!0)})});x.append(j,J,ee,i("div","bv-menu-sep"),Q);const E=m=>{m&&f(!1),x.hidden=!m,y.setAttribute("aria-expanded",m?"true":"false")};y.onclick=m=>{m.stopPropagation(),E(x.hidden)},document.addEventListener("click",m=>{const w=m.target;w&&(!c.contains(w)&&!p.contains(w)&&f(!1),!y.contains(w)&&!x.contains(w)&&E(!1))}),l.append(c,h,b,y),t.append(n,l);const I=i("div","bots-messages");I.id="bots-messages";const u=i("button","bv-jump");u.type="button",u.id="bv-jump",u.innerHTML=`${H("chevron-down",'width="14" height="14"')}<span>Latest</span>`,u.title="Jump to the latest message",u.hidden=!0,u.onclick=()=>{M=!0,I.scrollTop=I.scrollHeight,u.hidden=!0};const D=()=>{M=I.scrollHeight-I.scrollTop-I.clientHeight<48,u.hidden=M};I.addEventListener("scroll",D,{passive:!0}),I.addEventListener("touchmove",()=>{M=!1,u.hidden=I.scrollHeight-I.clientHeight<1},{passive:!0}),I.addEventListener("wheel",()=>{M=!1},{passive:!0});const S=i("div","bots-composer-wrap"),z=i("div","bv-queue");z.id="bv-queue",z.hidden=!0;const C=i("span","bv-queue-text"),te=i("button","bv-queue-clear","Clear");te.type="button",te.title="Drop the queued messages",te.onclick=()=>{d.activeId&&g(`/api/bots/${d.activeId}/queue/clear`,{method:"POST"}).then(()=>ge(),m=>N(m instanceof Error?m.message:String(m)))},z.append(C,te);const ce=i("div","bv-attach-strip");ce.id="bv-attach-strip",ce.hidden=!0;const pe=i("div","bv-composer-error");pe.id="bv-composer-error",pe.hidden=!0;const ue=i("div","bv-suggest");ue.id="bv-suggest",ue.hidden=!0;const me=i("div","bots-composer"),U=i("button","bv-attach-btn");U.type="button",U.id="bv-attach",U.title="Attach an image",U.setAttribute("aria-label","Attach an image"),U.innerHTML=H("attach",'width="18" height="18"');const O=i("input");O.type="file",O.accept="image/*",O.multiple=!0,O.hidden=!0,U.onclick=()=>O.click(),O.onchange=()=>{for(const m of Array.from(O.files??[]))ve(m);O.value=""};const $=i("textarea");$.id="bots-input",$.rows=1,$.placeholder="Message the bot\u2026",$.spellcheck=!1;const $e=window.matchMedia("(pointer: coarse)").matches;$e||($.enterKeyHint="send"),$.onkeydown=m=>{Ze(m)||m.key!=="Enter"||m.shiftKey||m.isComposing||$e||m.keyCode===229||(m.preventDefault(),De())},$.oninput=()=>{N(null),ie($),qe()},$.onclick=()=>qe(),$.addEventListener("paste",m=>{const w=Array.from(m.clipboardData?.files??[]).filter(T=>T.type.startsWith("image/"));if(w.length!==0){m.preventDefault();for(const T of w)ve(T)}});const K=i("button","btn primary");K.id="bv-send",K.title="Send",K.setAttribute("aria-label","Send"),K.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V5M5 12l7-7 7 7"/></svg>',K.onclick=()=>void De(),me.append(U,$,K),me.addEventListener("click",m=>{const w=m.target;w?.closest("button")&&_(),!w?.closest("button")&&document.activeElement!==$&&$.focus()}),S.addEventListener("dragover",m=>{m.dataTransfer&&(m.preventDefault(),S.classList.add("drop-target"))}),S.addEventListener("dragleave",()=>S.classList.remove("drop-target")),S.addEventListener("drop",m=>{m.preventDefault(),S.classList.remove("drop-target");const w=Array.from(m.dataTransfer?.files??[]).filter(T=>T.type.startsWith("image/"));for(const T of w)ve(T)}),S.append(z,ce,ue,pe,O,me),e.append(t,I,u,S,p,x),document.querySelector(".main-area")?.appendChild(e),document.getElementById("bots-modal")||pt()}function N(e){const t=document.getElementById("bv-composer-error");t&&(t.textContent=e??"",t.hidden=!e)}function Le(e){const t=document.getElementById("bv-send");t&&(t.disabled=e,t.setAttribute("aria-busy",e?"true":"false"),t.title=e?"Sending\u2026":"Send")}const P=[],Ne=4,Ye=4*1024*1024;function ie(e){e.style.height="auto";const t=window.matchMedia("(max-width: 640px)").matches?132:160;e.style.height=`${Math.min(t,e.scrollHeight)}px`}function se(){const e=document.getElementById("bv-attach-strip");e&&(e.textContent="",e.hidden=P.length===0,P.forEach((t,n)=>{const o=i("span","bv-attach-chip"),s=i("img");s.src=t.preview,s.alt=t.name;const a=i("button","bv-attach-remove","\xD7");a.type="button",a.title=`Remove ${t.name}`,a.setAttribute("aria-label",`Remove ${t.name}`),a.onclick=()=>{P.splice(n,1),se()},o.append(s,a),e.appendChild(o)}))}async function ve(e){if(!e.type.startsWith("image/")){N("Only image attachments are supported.");return}if(P.length>=Ne){N(`At most ${Ne} images per message.`);return}if(e.size>Ye){N("Images must be smaller than 4 MB.");return}const t=await new Promise((o,s)=>{const a=new FileReader;a.onload=()=>o(String(a.result??"")),a.onerror=()=>s(new Error("could not read the image")),a.readAsDataURL(e)}),n=t.indexOf(",");P.push({data:t.slice(n+1),mimeType:e.type,name:e.name||"image",preview:t}),N(null),se()}function ge(){const e=document.getElementById("bv-queue");if(!e)return;const t=d.activeId?d.queues.get(d.activeId):void 0,n=t?.steering.length??0,o=t?.followUp.length??0;if(n+o===0){e.hidden=!0;return}const s=[];n&&s.push(`${n} steering`),o&&s.push(`${o} follow-up`),e.hidden=!1;const a=e.querySelector(".bv-queue-text");a&&(a.textContent=`Queued \xB7 ${s.join(" \xB7 ")}`)}let q=[],G=0,ae=null,vt=null;function _(){const e=document.getElementById("bv-suggest");e&&(e.hidden=!0),q=[],ae=null}function ye(){const e=document.getElementById("bv-suggest");if(e){if(e.textContent="",q.length===0){e.hidden=!0;return}e.hidden=!1,q.forEach((t,n)=>{const o=i("button",`bv-suggest-item${n===G?" active":""}`);o.type="button",o.innerHTML=`<span class="bv-suggest-kind">${t.kind==="file"?"@":"/"}</span><span class="bv-suggest-label">${Pe(t.label)}</span><span class="bv-suggest-detail">${Pe(t.detail)}</span>`,o.onmousedown=s=>s.preventDefault(),o.onclick=()=>je(n),e.appendChild(o)})}}function Pe(e){return e.replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t])}async function qe(){const e=document.getElementById("bots-input");if(!e)return;const t=e.selectionStart??e.value.length,n=e.value.slice(0,t),o=/(^|\s)([/@])([^\s]*)$/.exec(n);if(!o){_();return}const s=o[2],a=o[3];if(ae={start:t-a.length-1,end:t},s==="/"){const h=d.catalog,b=(h?.prompts??[]).map(v=>({kind:"prompt",label:`/${v.name}`,detail:"prompt template",value:`/${v.name} `})),k=(h?.skills??[]).map(v=>({kind:"skill",label:`/skill:${v.name}`,detail:v.description||"skill",value:`/skill:${v.name} `}));q=[...b,...k].filter(v=>v.label.toLowerCase().includes(a.toLowerCase())||v.detail.toLowerCase().includes(a.toLowerCase())).slice(0,8),G=0,ye();return}const c=Y();if(!c){_();return}const r=a.lastIndexOf("/"),p=r>=0?`${c.projectPath}/${a.slice(0,r)}`:c.projectPath,f=r>=0?a.slice(r+1):a;try{q=((await g(`/api/fs/list?path=${encodeURIComponent(p)}`)).entries??[]).filter(k=>k.name.toLowerCase().startsWith(f.toLowerCase())).slice(0,8).map(k=>{const v=r>=0?a.slice(0,r+1):"";return{kind:"file",label:`@${v}${k.name}${k.type==="dir"?"/":""}`,detail:k.type==="dir"?"directory":"file",value:`@${v}${k.name}${k.type==="dir"?"/":" "}`}}),G=0,ye()}catch{_()}}function je(e){const t=document.getElementById("bots-input"),n=q[e];if(!t||!n||!ae)return;const{start:o,end:s}=ae;t.value=`${t.value.slice(0,o)}${n.value}${t.value.slice(s)}`;const a=o+n.value.length;_(),t.focus(),t.setSelectionRange(a,a),ie(t)}function Ze(e){const t=document.getElementById("bv-suggest");if(!t||t.hidden||q.length===0)return!1;if(e.key==="ArrowDown"||e.key==="ArrowUp"){e.preventDefault();const n=e.key==="ArrowDown"?1:-1;return G=(G+n+q.length)%q.length,ye(),!0}return e.key==="Enter"||e.key==="Tab"?(e.preventDefault(),je(G),!0):e.key==="Escape"?(e.preventDefault(),_(),!0):!1}async function De(){const e=document.getElementById("bots-input");if(!e||!d.activeId||ze||!e.value.trim()&&P.length===0)return;const t=d.activeId,n=e.value.trim()?e.value:"See the attached image",o=P.map(({data:s,mimeType:a})=>({data:s,mimeType:a}));N(null),Le(!0);try{await g(`/api/bots/${t}/input`,{method:"POST",body:JSON.stringify({text:n,images:o.length?o:void 0})}),e.value===n&&(e.value="",ie(e)),_(),P.length=0,se(),M=!0}catch(s){N(s instanceof Error?s.message:String(s))}finally{Le(!1)}}function He(e){d.activeId&&e(d.activeId).catch(t=>V({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)}))}function we(){d.activeId=null,L=[],M=!0,R();const e=document.getElementById("bots-view");e&&(e.hidden=!0);try{d.ws?.close()}catch{}d.ws=null,oe();const t=document.getElementById("terminal-container"),n=document.getElementById("main-placeholder"),o=!!document.querySelector(".session-item.active:not(.bot-item)");t&&o?(t.style.display="",n&&(n.style.display="none")):n&&(n.style.display="")}async function Re(e){d.activeId=e,L=[],M=!0,P.length=0,se(),ge(),_();const t=document.getElementById("bots-input");t&&(t.value="",ie(t)),N(null);const n=document.getElementById("bv-jump");n&&(n.hidden=!0),window.__collapseSidebar?.(),R(),d.items.set(e,[]);const o=document.getElementById("bots-view");o&&(o.hidden=!1);const s=document.getElementById("main-placeholder");s&&(s.style.display="none");const a=document.getElementById("terminal-container");a&&(a.style.display="none");const l=document.getElementById("file-editor");l&&(l.style.display="none"),oe(),re();const c=Y();c&&c.status==="stale"&&g(`/api/bots/${e}/resume`,{method:"POST"}).then(()=>B(!0)).catch(()=>{});try{d.ws?.close()}catch{}const r=location.protocol==="https:"?"wss:":"ws:",p=new WebSocket(`${r}//${location.host}/ws/bots/${encodeURIComponent(e)}?token=${encodeURIComponent(he())}`);d.ws=p,p.onmessage=f=>{try{We(JSON.parse(String(f.data)))}catch{}},p.onclose=()=>{d.activeId===e&&setTimeout(()=>{d.activeId===e&&B(!0)},1500)},await B(!0)}function Y(){return d.bots.find(e=>e.id===d.activeId)||null}function ke(){const e=Y();if(!e)return;const t=document.getElementById("bv-title"),n=document.getElementById("bv-status"),o=document.getElementById("bv-dot");t&&(t.textContent=e.title),n&&(n.textContent=et[e.status]??e.status.replace(/_/g," "),n.dataset.status=e.status,n.style.color=Me(e.status),n.title=`${e.status.replace(/_/g," ")} \xB7 ${e.templateId} \xB7 ${e.projectPath}`);const s=document.getElementById("bv-mode-btn");s&&Ue(s,e.runtimeMode||"supervised");for(const r of document.querySelectorAll("#bv-mode-menu button")){const p=r.dataset.mode===e.runtimeMode;r.classList.toggle("active",p),r.setAttribute("aria-checked",p?"true":"false")}const a=document.getElementById("bv-resume");a&&(a.hidden=!["stale","completed","failed","cancelled"].includes(e.status));const l=document.getElementById("bv-allow-all"),c=d.approvals.filter(r=>r.botId===e.id).length;if(l){l.hidden=c===0;const r=l.querySelector(".bv-menu-text b");r&&(r.textContent=`Allow all (${c})`)}o&&(o.style.background=Me(e.status))}const et={queued:"queued",starting:"starting",running:"running",waiting_input:"waiting",waiting_approval:"approval",completed:"done",failed:"failed",cancelled:"stopped",stale:"stale"},_e={supervised:"\u9ED8\u8BA4","parent-supervised":"\u76D1\u7BA1","full-access":"\u5168\u653E\u884C"},Je={supervised:"shield","parent-supervised":"shield-up","full-access":"shield-alert"};function Ue(e,t){const n=Je[t]??"shield";e.dataset.mode=t,e.innerHTML=H(n,'width="15" height="15"');const o=`\u5BA1\u6279\u6A21\u5F0F\uFF1A${_e[t]??t}`;e.title=`${o}\uFF08\u70B9\u5F00\u53EF\u5207\u6362\uFF09`,e.setAttribute("aria-label",o)}async function tt(e){if(d.activeId)try{await g(`/api/bots/${d.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:e})});const t=Y();t&&(t.runtimeMode=e),ke(),V({kind:"notice",level:"info",text:`\u5BA1\u6279\u6A21\u5F0F\uFF1A${_e[e]||e}`})}catch(t){V({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)})}}function V(e,t=d.activeId){if(!t)return;const n=d.items.get(t)||[];n.push(e),d.items.set(t,n),t===d.activeId&&F()}function F(){if(d.renderQueued)return;d.renderQueued=!0;const e=Math.max(0,60-(performance.now()-Te));window.setTimeout(()=>{d.renderQueued=!1,Te=performance.now(),re()},e)}function xe(e){switch(e.kind){case"assistant":return{text:e.text,thinking:e.thinking};case"tool":return{phase:e.phase,output:e.output,error:e.isError,durationMs:e.durationMs};case"approval":return{decided:e.decided,approvalState:e.approval.state};default:return{}}}function nt(e,t){return e.text!==t.text||e.thinking!==t.thinking||e.phase!==t.phase||e.output!==t.output||e.error!==t.error||e.durationMs!==t.durationMs||e.decided!==t.decided||e.approvalState!==t.approvalState}function Se(e){if(e.kind==="user"){const t=i("div","bv-msg bv-user");return t.appendChild(fe(e.text)),t}if(e.kind==="assistant"){const t=i("div","bv-msg bv-assistant");if(e.thinking){const o=i("details","bv-thinking");o.appendChild(i("summary",void 0,"thinking")),o.appendChild(i("div",void 0,e.thinking)),t.appendChild(o)}const n=i("div","bv-text");return n.appendChild(fe(e.text)),t.appendChild(n),t}return e.kind==="tool"?st(e):e.kind==="approval"?at(e):i("div",`bv-notice bv-notice-${e.level}`,e.text)}function ot(e,t){const n=e.querySelector("details.bv-thinking");if(t.thinking)if(n){const s=n.querySelector("div");s&&s.textContent!==t.thinking&&(s.textContent=t.thinking)}else{const s=i("details","bv-thinking");s.appendChild(i("summary",void 0,"thinking")),s.appendChild(i("div",void 0,t.thinking)),e.prepend(s)}else n&&n.remove();const o=e.querySelector(".bv-text");o&&o.replaceChildren(fe(t.text))}function re(){const e=document.getElementById("bots-messages");if(!e||!d.activeId||document.getElementById("bots-view")?.hidden)return;const t=d.items.get(d.activeId)||[],n=Math.max(0,t.length-Ae),o=n?t.slice(n):t,s=M;if(o.length<L.length||o.some((l,c)=>L[c]?.item!==l))e.textContent="",L=o.map(l=>{const c=Se(l);return e.appendChild(c),{item:l,snapshot:xe(l),node:c}});else{for(let l=L.length;l<o.length;l++){const c=o[l],r=Se(c);e.appendChild(r),L.push({item:c,snapshot:xe(c),node:r})}for(let l=0;l<o.length;l++){const c=o[l],r=L[l],p=xe(c);if(nt(r.snapshot,p)){if(c.kind==="assistant")ot(r.node,c);else{const f=Se(c);r.node.replaceWith(f),r.node=f}r.snapshot=p}}}it(e,n),s&&(e.scrollTop=e.scrollHeight)}function it(e,t){const n=e.querySelector(":scope > .bv-earlier");if(t===0){n?.remove();return}const o=`Show earlier messages (${t})`;if(n){n.textContent!==o&&(n.textContent=o);return}const s=i("button","bv-earlier",o);s.type="button",s.onclick=()=>{const a=e.scrollHeight,l=e.scrollTop;Ae+=Be,L=[],re(),e.scrollTop=l+(e.scrollHeight-a)},e.prepend(s)}function st(e){const t=i("details","bv-tool");t.open=e.phase!=="end"||!!e.isError;const n=i("summary"),o=i("span","bv-tool-name",e.name);if(n.appendChild(o),e.phase!=="end"&&n.appendChild(i("span","bv-tool-phase",e.phase)),e.isError&&n.appendChild(i("span","bv-tool-error","error")),typeof e.durationMs=="number"&&n.appendChild(i("span","bv-tool-meta",`${Math.round(e.durationMs)}ms`)),t.appendChild(n),e.args!==void 0){const s=i("pre","bv-pre");s.textContent=typeof e.args=="string"?e.args:JSON.stringify(e.args,null,2),t.appendChild(s)}if(e.output){const s=i("pre","bv-pre bv-output");s.textContent=e.output,t.appendChild(s)}return t}function at(e){const t=i("div","bv-approval"),n=e.approval;if(t.appendChild(i("div","bv-approval-tag","Needs approval")),t.appendChild(i("div","bv-approval-title",n.title)),n.message){const b=i("pre","bv-pre bv-approval-detail");b.textContent=n.message,t.appendChild(b)}if(e.decided)return t.appendChild(i("div","bv-approval-decided",e.decided==="allowed"?"Allowed":"Denied")),t;const o=i("input","bv-reason");o.placeholder="reason (optional)",o.setAttribute("aria-label","Reason (optional)");const s=i("div","bv-approval-actions"),a=i("button","btn primary","Allow once"),l=/^Allow (.+?)\?$/.exec(n.title)?.[1],c=n.method==="confirm"?l&&l.length<=24?`Always allow ${l}`:"Always allow this tool":"Allow for this session",r=i("button","btn",c);r.hidden=n.method!=="confirm";const p=i("button","btn danger","Deny"),f=[a,r,p],h=async(b,k,v)=>{const y=v.textContent??"";for(const x of f)x.disabled=!0;v.textContent=b?"Allowing\u2026":"Denying\u2026";try{await g(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:b,always:k,reason:o.value||void 0})}),e.decided=b?"allowed":"denied",F(),B(!0)}catch(x){for(const A of f)A.disabled=!1;v.textContent=y,V({kind:"notice",level:"error",text:x instanceof Error?x.message:String(x)})}};return a.onclick=()=>void h(!0,!1,a),r.onclick=()=>void h(!0,!0,r),p.onclick=()=>void h(!1,!1,p),s.append(o,a,r,p),t.appendChild(s),t}function We(e){const t=String(e.type||""),n=d.activeId;if(!n)return;const o=d.items.get(n)||[];if(t==="snapshot")d.items.set(n,[]);else if(t==="queue")d.queues.set(n,{steering:Array.isArray(e.steering)?e.steering:[],followUp:Array.isArray(e.followUp)?e.followUp:[]}),ge();else if(t==="user")M=!0,V({kind:"user",text:String(e.text||"")});else if(t==="status"){const s=Y();s&&(s.status=String(e.status||s.status)),ke(),dt()}else if(t==="message"){const s=e.message;if(!s||String(s.role||"")!=="assistant")return;const l=rt(s),c=lt(s),r=o[o.length-1];r&&r.kind==="assistant"?(r.text=l||r.text,r.thinking=c||r.thinking):o.push({kind:"assistant",text:l,thinking:c}),d.items.set(n,o),F()}else if(t==="delta"){const s=String(e.kind||""),a=String(e.delta||"");let l=o[o.length-1];(!l||l.kind!=="assistant")&&(o.push({kind:"assistant",text:"",thinking:""}),l=o[o.length-1]),l.kind==="assistant"&&(s==="text"?l.text+=a:s==="thinking"&&(l.thinking+=a)),d.items.set(n,o),F()}else if(t==="tool"){const s=String(e.callId||""),a=o.find(c=>c.kind==="tool"&&c.callId===s),l=String(e.phase||"start");a?(a.phase=l,l==="update"&&e.output&&(a.output=String(e.output)),l==="end"&&(e.output&&(a.output=String(e.output)),a.isError=e.isError===!0,typeof e.durationMs=="number"&&(a.durationMs=e.durationMs))):o.push({kind:"tool",callId:s,name:String(e.name||"tool"),args:e.args,output:e.output?String(e.output):void 0,isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,phase:l}),d.items.set(n,o),F()}else if(t==="approval"){const s=e.approval;if(!s)return;const a=o;for(let l=a.length-1;l>=0;l--){const c=a[l];if(c.kind==="approval"&&c.approval.id===s.id){c.approval=s,s.state!=="pending"&&(c.decided=s.state==="allowed"?"allowed":"denied"),d.items.set(n,a),F();return}}a.push({kind:"approval",approval:s}),d.items.set(n,a),F()}else t==="notice"&&V({kind:"notice",level:String(e.level||"info"),text:String(e.text||"")})}function rt(e){const t=e.content;return Array.isArray(t)?t.map(n=>n&&typeof n=="object"&&n.type==="text"?String(n.text||""):"").join(""):String(e.text||"")}function lt(e){const t=e.content;return Array.isArray(t)?t.map(n=>n&&typeof n=="object"&&n.type==="thinking"?String(n.thinking||""):"").join(""):""}async function B(e=!1){try{const[t,n]=await Promise.all([g("/api/bots"),g("/api/bots/approvals")]);if(d.bots=t,d.approvals=n,oe(),ke(),e&&d.activeId){const o=await g(`/api/bots/${d.activeId}/events?limit=300`);ct(o)}}catch{}}async function dt(){try{d.bots=await g("/api/bots"),oe()}catch{}}function ct(e){if(d.activeId){d.items.set(d.activeId,[]);for(const t of e)We(t);re()}}function pt(){const e=i("div","bots-modal");e.id="bots-modal",e.hidden=!0;const t=i("div","bots-modal-card"),n=i("div","bots-modal-head"),o=i("span");o.id="bots-modal-title";const s=i("button","btn");s.innerHTML=H("close",'width="14" height="14"'),s.title="Close",s.onclick=()=>le(),n.append(o,s);const a=i("div","bots-modal-body");a.id="bots-modal-body",t.append(n,a),e.appendChild(t),e.onclick=l=>{l.target===e&&le()},document.body.appendChild(e)}function Ce(e){const t=document.getElementById("bots-modal"),n=document.getElementById("bots-modal-title"),o=document.getElementById("bots-modal-body");if(!t||!o)throw new Error("modal missing");return n&&(n.textContent=e),o.textContent="",t.hidden=!1,o}function le(){const e=document.getElementById("bots-modal");e&&(e.hidden=!0)}async function ut(){return d.catalog||(d.catalog=await g("/api/bots/catalog")),d.catalog}async function Ve(){return d.templates=await g("/api/bots/templates"),d.templates}async function Z(){const e=Ce("Bot templates"),[t,n]=await Promise.all([ut(),Ve()]),o=i("div","bv-template-list");for(const r of n){const p=i("div","bv-template-row");p.appendChild(i("span","bv-template-name",r.manifest.name)),p.appendChild(i("span","bv-template-desc",r.manifest.description||""));const f=i("button","btn","Edit");f.onclick=()=>Fe(e,t,r);const h=i("button","btn","Copy");h.title="Duplicate this template",h.onclick=()=>{const v=JSON.parse(JSON.stringify(r.manifest));v.name=`${r.manifest.name} copy`,g("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:v})}).then(()=>Z()).catch(y=>alert(y instanceof Error?y.message:String(y)))};const b=i("button","btn danger","Delete");b.onclick=()=>{confirm(`Delete template ${r.manifest.name}?`)&&g(`/api/bots/templates/${r.id}`,{method:"DELETE"}).then(()=>Z())};const k=i("span","bv-template-actions");k.append(f,h,b),p.appendChild(k),o.appendChild(p)}n.length===0&&o.appendChild(i("div","bots-empty","No templates yet")),e.appendChild(o);const s=i("div","bv-template-actions"),a=i("button","btn primary","New template");a.onclick=()=>Fe(e,t,null);const l=i("button","btn","Export");l.title="Download templates + library as JSON",l.onclick=()=>{(async()=>{try{const r=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${he()}`}});if(!r.ok)throw new Error(`HTTP ${r.status}`);const p=await r.blob(),f=document.createElement("a");f.href=URL.createObjectURL(p),f.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,f.click(),setTimeout(()=>URL.revokeObjectURL(f.href),2e3)}catch(r){alert(r instanceof Error?r.message:String(r))}})()};const c=i("button","btn","Import");c.title="Restore templates from a JSON bundle",c.onclick=()=>{const r=document.createElement("input");r.type="file",r.accept="application/json,.json",r.onchange=()=>{const p=r.files?.[0];p&&(async()=>{try{const f=JSON.parse(await p.text()),h=await g("/api/bots/import",{method:"POST",body:JSON.stringify(f)});alert(`Imported ${h.templates} templates, ${h.files} library files (${h.skipped} kept)`),await Z()}catch(f){alert(f instanceof Error?f.message:String(f))}})()},r.click()},s.append(a,l,c),e.appendChild(s)}function Ee(e,t,n){const o=i("div","bv-field");o.appendChild(i("label","bv-label",e));const s=i("div","bv-check-grid"),a=[];for(const l of t){const c=i("label","bv-check"),r=document.createElement("input");r.type="checkbox",r.checked=n.includes(l.id),c.append(r,i("span",void 0,l.label)),l.hint&&(c.title=l.hint),s.appendChild(c),a.push({id:l.id,input:r})}return o.appendChild(s),{element:o,get:()=>a.filter(l=>l.input.checked).map(l=>l.id)}}function Fe(e,t,n){e.textContent="";const o=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},s=i("input","bv-input");s.value=o.name,s.placeholder="Template name";const a=i("input","bv-input");a.value=o.description||"",a.placeholder="One line description";const l=i("textarea","bv-textarea");l.rows=6,l.value=o.system||"",l.placeholder="System prompt for this bot (written to SYSTEM.md)";const c=Ee("Skills",t.skills.map(u=>({id:u.id,label:u.name,hint:u.description})),o.skills||[]),r=Ee("Extensions (Pi builtins + library)",t.extensions.map(u=>({id:u.id,label:`${u.name}${u.kind==="builtin"?" (builtin)":""}`,hint:u.description})),(o.extensions||[]).map(u=>u.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),p=Ee("Prompt templates",t.prompts.map(u=>({id:u.id,label:u.name})),o.prompts||[]),f=i("select","bv-input");f.appendChild(new Option("none",""));for(const u of t.mcp)f.appendChild(new Option(u.name,u.id));o.mcp&&(f.value=t.mcp.find(u=>JSON.stringify(u.servers)===JSON.stringify(o.mcp?.mcpServers))?.id||"");const h=i("div","bv-field");h.appendChild(i("label","bv-label","Tools (allow list; deny always blocks)"));const b=i("div","bv-check-grid"),k=[];for(const u of t.tools){const D=i("label","bv-check"),S=document.createElement("input");S.type="checkbox",S.checked=(o.tools?.allow||[]).includes(u.name)||!o.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(u.name),D.append(S,i("span",void 0,u.name)),b.appendChild(D),k.push({name:u.name,input:S})}h.appendChild(b);const v=i("input","bv-input");v.value=(o.tools?.deny||[]).join(", "),v.placeholder="Always deny (comma separated), e.g. bash, write";const y=i("textarea","bv-textarea");y.rows=2,y.value=(o.packages||[]).join(`
2
+ `),y.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";const x=i("select","bv-input");x.appendChild(new Option("default (Pi settings)",""));for(const u of t.models)x.appendChild(new Option(`${u.provider}/${u.model}`,`${u.provider}
3
+ ${u.model}`));o.model?.provider&&o.model?.id&&(x.value=`${o.model.provider}
4
+ ${o.model.id}`);const A=i("select","bv-input");for(const u of["","off","minimal","low","medium","high","xhigh","max"])A.appendChild(new Option(u||"default",u));o.model?.thinking&&(A.value=o.model.thinking);const j=i("select","bv-input");for(const u of["supervised","auto-accept-edits","full-access"])j.appendChild(new Option(u,u));j.value=o.permissions?.runtimeMode||"supervised";const J=i("select","bv-input");J.appendChild(new Option("ignore project .pi (recommended)","ignore")),J.appendChild(new Option("inherit project .pi (needs trust)","inherit")),J.value=o.projectResources||"ignore";const ee=i("label","bv-check"),Q=document.createElement("input");Q.type="checkbox",Q.checked=!!o.orchestrator,ee.append(Q,i("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));const E=(u,D)=>{const S=i("div","bv-field");return S.appendChild(i("label","bv-label",u)),S.appendChild(D),S};e.append(E("Name",s),E("Description",a),E("System prompt",l),c.element,r.element,p.element,E("MCP preset",f),h,E("Always deny tools",v),E("Packages",y),E("Model",x),E("Thinking level",A),E("Approval mode",j),E("Project resources",J),ee);const I=i("button","btn primary",n?"Save template":"Create template");I.onclick=async()=>{const[u,D]=x.value.split(`
5
+ `),S=t.mcp.find(C=>C.id===f.value),z={name:s.value.trim()||"bot",description:a.value.trim()||void 0,system:l.value.trim()||void 0,skills:c.get(),extensions:r.get().map(C=>(C.startsWith("builtin:"),C)),prompts:p.get(),packages:y.value.split(`
6
+ `).map(C=>C.trim()).filter(Boolean),mcp:S?{mcpServers:S.servers}:void 0,tools:{allow:k.filter(C=>C.input.checked).map(C=>C.name),deny:v.value.split(",").map(C=>C.trim()).filter(Boolean)},model:u?{provider:u,id:D,thinking:A.value||void 0}:void 0,permissions:{runtimeMode:j.value},projectResources:J.value==="inherit"?"inherit":"ignore",orchestrator:Q.checked||void 0};try{await g("/api/bots/templates",{method:"POST",body:JSON.stringify({id:n?.id,manifest:z})}),le(),await Z()}catch(C){alert(C instanceof Error?C.message:String(C))}},e.appendChild(I)}async function mt(){return ft("")}async function ft(e){const t=Ce("New bot"),n=await Ve();if(n.length===0){t.appendChild(i("div","bots-empty","No templates yet \u2014 create one with \u201CNew template\u201D."));return}const o=i("select","bv-input");for(const p of n)o.appendChild(new Option(p.manifest.name,p.id));const s=i("input","bv-input");s.placeholder="Title (defaults to template name)";const a=i("input","bv-input");a.placeholder="/path/to/project";const l=e||d.bots[0]?.projectPath||"";a.value=l;const c=i("select","bv-input");c.appendChild(new Option("shared \u2014 run in the project folder","shared")),c.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),t.append(de("Template",o),de("Title",s),de("Project path",a),de("Workspace",c));const r=i("button","btn primary","Create bot");r.onclick=async()=>{try{const p=await g("/api/bots",{method:"POST",body:JSON.stringify({templateId:o.value,title:s.value.trim()||void 0,projectPath:a.value.trim()||void 0,isolation:c.value})});le(),await B(!0),await Re(p.id)}catch(p){alert(p instanceof Error?p.message:String(p))}},t.appendChild(r)}function de(e,t){const n=i("div","bv-field");return n.appendChild(i("label","bv-label",e)),n.appendChild(t),n}async function Ie(){const e=Ce("Needs you");if(d.approvals=await g("/api/bots/approvals"),d.approvals.length===0){e.appendChild(i("div","bots-empty","Nothing waiting."));return}for(const t of d.approvals){const n=i("div","bv-approval");if(n.appendChild(i("div","bv-approval-tag",t.botTitle)),n.appendChild(i("div","bv-approval-title",t.title)),t.message){const p=i("pre","bv-pre bv-approval-detail");p.textContent=t.message,n.appendChild(p)}const o=i("input","bv-reason");o.placeholder="reason (optional)",o.setAttribute("aria-label","Reason (optional)");const s=i("div","bv-approval-actions"),a=i("button","btn primary","Allow once"),l=i("button","btn danger","Deny"),c=[a,l],r=async(p,f)=>{const h=f.textContent??"";for(const b of c)b.disabled=!0;f.textContent=p?"Allowing\u2026":"Denying\u2026";try{await g(`/api/bots/${t.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:t.id,allow:p,reason:o.value||void 0})}),await B(!0),await Ie()}catch(b){for(const k of c)k.disabled=!1;f.textContent=h,V({kind:"notice",level:"error",text:b instanceof Error?b.message:String(b)})}};a.onclick=()=>void r(!0,a),l.onclick=()=>void r(!1,l),s.append(o,a,l),n.appendChild(s),e.appendChild(n)}}function gt(){window.__botsInited||(window.__botsInited=!0,Xe(),Ge(),window.__openBot=Re,document.addEventListener("click",e=>{const t=e.target;t&&(t.closest(".session-item.bot-item")||t.closest(".session-item")&&d.activeId&&setTimeout(()=>we(),0))},!0),document.addEventListener("click",e=>{const t=e.target;!t||!d.activeId||(t.closest("#mode-files")||t.closest(".file-tree-item")||t.closest(".file-roots-list li"))&&we()}),B(!0),d.pollTimer=window.setInterval(()=>{document.hidden||B()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(d.pollTimer)))}export{gt as initBots,ft as openNewBotForPath};
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 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
2
+ import{chmodSync as ye,existsSync as D,mkdirSync as ke,readdirSync as we,readFileSync as V,statSync as Te,unlinkSync as ve,writeFileSync as Se}from"node:fs";import{createRequire as X}from"node:module";import{hostname as E,networkInterfaces as _e}from"node:os";const be=X(import.meta.url),{version:Ae}=be("../package.json");import P from"node:path";import{fileURLToPath as Ce}from"node:url";import{serve as xe}from"@hono/node-server";import{WebSocketServer as Ie,WebSocket as F}from"ws";try{const e=P.dirname(X(import.meta.url).resolve("node-pty/package.json")),t=P.join(e,"prebuilds");if(D(t))for(const o of we(t)){const n=P.join(t,o,"spawn-helper");D(n)&&!(Te(n).mode&73)&&ye(n,493)}}catch{}import{loadSecurityConfig as Pe}from"./lib/security-config.js";import{TokenStore as Re,hashPassword as $e,verifyPassword as Me,validatePassword as Oe}from"./lib/auth.js";import{RateLimiter as Ne}from"./lib/rateLimiter.js";import{audit as d}from"./lib/auditLog.js";import{db as N}from"./lib/db.js";import{handleClientMessage as Y}from"./lib/ws-message.js";import{loadDotEnv as Ue}from"./lib/load-env.js";import{listSessions as Le,resolveTmuxSocketPath as Ee}from"./sessions.js";import{cmdSetup as Fe,cmdTheme as je,printUsage as K,printVersion as He}from"./lib/cli.js";import{readSettings as Be}from"./lib/settings.js";import{readActiveTheme as We}from"./lib/theme-store.js";import{buildApp as Q}from"./lib/build-app.js";import{getDataRoot as Z}from"./lib/state-paths.js";import{getBotManager as De}from"./lib/bots/manager.js";import{attachTerminal as Je,killAllAttachedPtys as ze}from"./lib/attach-terminal.js";import{acquireControlClient as q,killAllControlClients as Ge}from"./lib/tmux-control.js";import{getSessionPaneTarget as ee,capturePaneTail as te,capturePaneHistoryChunk as ne,toCrlf as oe}from"./lib/tmux-capture.js";import{readTerminalBufferConfig as Ve}from"./lib/terminal-config.js";import{AgentRegistry as Xe}from"./lib/agent-registry.js";import{AgentChannel as Ye,MAX_RELAY_CONNS_PER_AGENT as Ke}from"./lib/agent-relay.js";import{findAgentTokenByPlaintext as Qe,listAgentTokens as Ze}from"./lib/agent-tokens.js";import{saveSecurityConfig as qe}from"./lib/security-config.js";import{readFederationConfig as et,writeFederationConfig as tt}from"./lib/federation-config.js";import{startAgentClient as nt}from"./lib/agent-client.js";import{ActivityProbe as ot}from"./lib/activity-probe.js";import{upsertSessionState as re}from"./lib/session-state.js";import{sessionWorkingPath as rt}from"./lib/sessions-sidebar.js";Ue();const j=Ve(),g=Pe(),w=new Re,_=new Ne;let J=!1;const st="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 U(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*)${st}=([^;]+)`));return n?decodeURIComponent(n[1]):null}function nn(e){const t=U(e);return t?w.validateToken(t):null}const M=new Map;function at(e){let t=0;for(const o of M.values())o.ip===e&&t++;return t}function C(e,t,o){try{e.close(t,o)}catch{}}function se(e,t){e.readyState===F.OPEN&&e.send(JSON.stringify(t))}const ae=process.argv.slice(2),L=ae;if(L.length>0){const[e,t]=L;switch(e){case"setup":await Fe(L),process.exit(0);case"theme":await je(L.slice(1)),process.exit(0);case"agent":{const o=P.join(P.dirname(Ce(import.meta.url)),"agent.js"),{spawn:n}=await import("node:child_process"),l=n(process.execPath,[o,...ae],{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 vt(L.slice(1)),process.exit(0);case"help":case"--help":case"-h":K(),process.exit(0);case"-V":case"--version":case"-v":He(),process.exit(0);default:console.error(`unknown argument: ${e}`),K(),process.exit(1)}}function R(e,t){e.readyState===F.OPEN&&e.send(JSON.stringify(t))}const ie=new Set;await N.read(),N.data.sessionAccess??=[],N.data.pinnedViews??=[],N.data.watchedPanes??=[],N.data.quickCommands??=[];const ce=await Be();let it=await We();const k=new Xe({onChange:()=>{}}),v=new Map;function le(e){return k.get(e)?v.get(e)??null:null}const ue={activeTheme:it,settingUpPassword:!1},ct=Q({mode:"hub",securityConfig:g,tokenStore:w,rateLimiter:_,settings:ce,terminalBufferConfig:j,state:ue,federation:{getConfig:()=>I,setConfig:async e=>{I=e,await tt(e),fe(e)},status:ut,hostname:E()},hub:{agents:k,getChannel:le}}),lt=Q({mode:"agent",securityConfig:g,tokenStore:w,rateLimiter:_,settings:ce,terminalBufferConfig:j,state:ue});let I=await et(),O=null;function de(){O&&(O.stop(),O=null)}function fe(e){de(),!(!e.enabled||!e.hub||!e.token)&&(O=nt({hub:e.hub,token:e.token,name:e.name?.trim()||E(),version:Ae,app:lt,listSessions:Le,terminalBufferConfig:j,getSessionPaneTarget:ee,capturePaneTail:te,capturePaneHistoryChunk:ne,toCrlf:oe,handleClientMessage:Y,acquireControlClient:q}))}function ut(){return I.enabled?O?O.status():{state:"idle",agentId:null,hub:I.hub??"",name:I.name??E()}:{state:"idle",agentId:null,hub:I.hub??"",name:I.name??E()}}fe(I);const z=new ot,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)me({type:"session.activity",session:o.session,state:o.state})}catch{}})()},z.scanMs);const dt=parseInt(process.env.PORT||"21000",10);function ft(){const e=[];try{for(const t of Object.values(_e()))for(const o of t??[])o.family==="IPv4"&&!o.internal&&e.push(o.address)}catch{}return e}function mt(){try{const e=P.join(Z(),"hub.pid");if(ke(P.dirname(e),{recursive:!0}),D(e)){const t=Number(V(e,"utf8").trim());if(Number.isFinite(t)&&t>0&&t!==process.pid)try{process.kill(t,0),console.warn(`[hub] warning: another tmux-weblink (pid ${t}) is using ${Z()}. Two hubs sharing a data directory will pause or resume each other's bots.`)}catch{}}Se(e,String(process.pid),{mode:384}),process.once("exit",()=>{try{V(e,"utf8").trim()===String(process.pid)&&ve(e)}catch{}})}catch{}}mt();const pt=xe({fetch:ct.fetch,port:dt,hostname:"0.0.0.0"},e=>{console.log(`tmux-web running at http://localhost:${e.port}`);for(const t of ft())console.log(` also on http://${t}:${e.port}`)}),$=new Ie({noServer:!0}),G=new Set;function me(e){const t=JSON.stringify(e);for(const o of G)o.readyState===F.OPEN&&o.send(t)}function x(e,t,o){e.write(`HTTP/1.1 ${t} ${o}\r
3
3
  \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
4
+ `),e.destroy()}pt.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=U(e)||n.searchParams.get("token")||"";if(!(r?w.validateToken(r):null)){x(t,401,"Unauthorized");return}$.handleUpgrade(e,t,o,m=>{m.on("close",()=>G.delete(m)),G.add(m)});return}const a=l.match(/^\/ws\/bots\/([^/]+)$/);if(a){const s=U(e)||n.searchParams.get("token")||"";if(!(s?w.validateToken(s):null)){x(t,401,"Unauthorized");return}const c=decodeURIComponent(a[1]);$.handleUpgrade(e,t,o,m=>{De().attachSocket(c,m)});return}if(l==="/agent/ws"){kt(e,t,o);return}const i=l.match(/^\/ws\/a\/([^/]+)\/(.+)$/);if(i){ht(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}),x(t,403,"Origin not allowed");return}const y=at(f);if(y>=g.security.maxConnectionsPerIp){d("ws_rejected_per_ip_cap",{ip:f,liveFromIp:y}),x(t,429,"Too many connections");return}const T=U(e)||n.searchParams.get("token")||"",b=T?w.validateToken(T):null;$.handleUpgrade(e,t,o,s=>{$.emit("connection",s,e,decodeURIComponent(u[1]),f,b)})}),$.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}),R(e,{type:"auth.ok",setupMode:!g.passwordHash}),y()}function h(s,r={}){R(e,{type:"auth.failed",message:s,...r})}function y(){u||(z.suppress(o),re(o,{path:rt(o)}),u=Je(o,{send:s=>R(e,s),onMessage:s=>{f=s},onClose:s=>{T=s}},{terminalBufferConfig:j,getSessionPaneTarget:ee,capturePaneTail:te,capturePaneHistoryChunk:ne,toCrlf:oe,handleClientMessage:Y,acquireControlClient:q,initialCols:i?.cols,initialRows:i?.rows,tmuxSocketPath:Ee()??void 0,onPtyExit:(s,r)=>C(e,1e3,"pty exited"),onSpawnError:(s,r)=>C(e,1011,"pty spawn failed")}))}let T=null;async function b(s){let r;try{r=JSON.parse(s)}catch{return!1}if(r.type==="auth.token"&&typeof r.token=="string"){const c=w.validateToken(r.token);if(!c){d("token_auth_failed",{ip:n});const m=_.recordFailure(n);return m.permanentLock&&(w.revokeAll(),d("permanent_lock",{ip:n,failures:m.failures})),h("Invalid or expired token",{permanentLock:m.permanentLock,retryAfterMs:m.retryAfterMs}),!0}return w.touch(c.tokenHash),p("token",c.name),!0}if(r.type==="auth"&&typeof r.password=="string"){const c=_.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&&!Tt(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 A=Oe(r.password);if(A)return h(A),!0;J=!0;try{g.passwordHash=await $e(r.password),qe(g),d("password_set",{ip:n})}finally{J=!1}const{stored:W,plaintext:ge}=w.createAccessToken("setup",g.security.tokenTtlDays);return R(e,{type:"auth.ok",setupMode:!0,token:ge}),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 Me(r.password,g.passwordHash)){const A=_.recordFailure(n);return d("auth_failed",{ip:n,method:"password",failures:A.failures,permanentLock:A.permanentLock}),A.permanentLock&&(w.revokeAll(),d("permanent_lock",{ip:n,failures:A.failures})),h("Incorrect password",{permanentLock:A.permanentLock,retryAfterMs:A.retryAfterMs}),!0}_.recordSuccess(n);const S=`ws-${n}`,{plaintext:he}=w.createAccessToken(S,g.security.tokenTtlDays);return p("password",S),R(e,{type:"auth.ok",setupMode:!1,token:he}),!0}return!1}l?(w.touch(l.tokenHash),p("token",l.name)):(R(e,{type:"auth.required",setupMode:!g.passwordHash}),a.authTimeout=setTimeout(()=>{a.authenticated||(d("auth_timeout",{ip:n}),h("Authentication timeout"),C(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){R(e,{type:"auth.failed",message:"Message too large"});return}await b(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}),T?.(),u&&(u.dispose(),u=null)}),e.on("error",()=>{a.authTimeout&&clearTimeout(a.authTimeout),M.delete(e),T?.(),u&&(u.dispose(),u=null)})});function ht(e,t,o,n,l){const a=H(e),i=new URL(e.url||"/",`http://${e.headers.host}`),u=U(e)||i.searchParams.get("token")||"";if(!(u?w.validateToken(u):null)){d("ws_rejected_remote_auth",{ip:a,agentId:n}),x(t,401,"Unauthorized");return}const p=le(n);if(!p){d("ws_rejected_remote_offline",{ip:a,agentId:n}),x(t,503,"Agent offline");return}if(p.relayCount>=Ke){x(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))){x(t,403,"Origin not allowed");return}const T=yt(),b=(()=>{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{}})();$.handleUpgrade(e,t,o,s=>{if(p.registerRelay(T,l,s),k.bumpRelayConns(n,1),re(l,{agentId:n}),!p.attach(T,l,b)){s.send(JSON.stringify({type:"data",data:`\r
5
5
  \x1B[31magent offline\x1B[0m\r
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(`
6
+ `})),s.close(1011,"agent offline"),p.relayClosed(T),k.bumpRelayConns(n,-1);return}s.on("message",c=>{const m=typeof c=="string"?c:c.toString("utf-8");let S;try{S=JSON.parse(m)}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)};s.on("close",r),s.on("error",r)})}let gt=1;function yt(){return gt++}function kt(e,t,o){const n=H(e),l=e.headers.origin;if(l){d("agent_rejected_origin",{ip:n,origin:l}),x(t,403,"Origin not allowed");return}$.handleUpgrade(e,t,o,a=>{let i=null,u=setTimeout(()=>{d("agent_hello_timeout",{ip:n}),C(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{C(a,1008,"bad hello");return}if(y.type!=="hello"||typeof y.token!="string"){C(a,1008,"expected hello");return}if(!_.check(n).allowed){d("agent_rate_limited",{ip:n}),C(a,429,"Too many attempts");return}const b=Qe(y.token);if(!b){_.recordFailure(n),d("agent_bad_token",{ip:n}),se(a,{type:"hello_err",reason:"invalid token"}),C(a,4003,"invalid token");return}const s=typeof y.name=="string"&&y.name.trim()?y.name.trim().slice(0,64):"agent",r=b.id;if(!k.register(r,s,a,b.tokenHash)){d("agent_cap_reached",{ip:n}),se(a,{type:"hello_err",reason:"too many agents"}),C(a,4004,"too many agents");return}clearTimeout(u),_.recordSuccess(n),d("agent_connected",{ip:n,agentId:r,name:s}),i=new Ye(a,r,{onSessions:m=>k.setSessions(r,m),onActivity:m=>{for(const S of m)me({type:"session.activity",agentId:r,session:S.session,state:S.state})},onRebuildResult:m=>{console.log(`[agent ${r}] rebuild ${m.session}: ${m.ok?"ok":m.message}`)},onClose:m=>{v.get(r)===m&&v.delete(r)}}),v.set(r,i),k.touch(r),a.send(JSON.stringify({type:"hello_ok",agentId:r})),i.sendSessionsReq()}),a.on("close",()=>{i&&(i.dispose(),v.delete(i.agentId),k.unregister(i.agentId),d("agent_disconnected",{ip:n,agentId:i.agentId})),clearTimeout(u)}),a.on("error",()=>{i&&(i.dispose(),v.delete(i.agentId),k.unregister(i.agentId)),clearTimeout(u)})})}const wt=parseInt(process.env.TMUX_WEB_AGENT_OFFLINE_MS||"45000",10);setInterval(()=>{const e=k.pruneOffline(wt);for(const o of e){const n=k.peek(o);n&&n.ws.readyState===F.CLOSED&&(k.unregister(o),v.get(o)?.dispose(),v.delete(o))}const t=new Set(Ze().map(o=>o.tokenHash));for(const[o,n]of v){const l=k.peek(o);if(!(!l||t.has(l.tokenHash))){d("agent_token_revoked",{agentId:o}),n.dispose(),v.delete(o),k.unregister(o);try{l.ws.close(4003,"token revoked")}catch{}}}w.purgeExpired()},10*1e3).unref();function pe(){de(),Ge(),ze();for(const e of v.values())e.dispose();v.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 ie)try{e.kill()}catch{}ie.clear(),_.dispose(),process.exit(0)}process.on("SIGINT",pe),process.on("SIGTERM",pe);function Tt(e){return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}async function vt(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
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)}}
@@ -1,4 +1,4 @@
1
- import{execFileSync as v}from"node:child_process";import{mkdirSync as m,readFileSync as I,rmSync as A,writeFileSync as _}from"node:fs";import h from"node:path";import k from"node:os";import{getBotStore as B}from"./store.js";import{materialize as j}from"./materialize.js";import{PiRpc as M}from"./rpc.js";import{buildCatalog as O,ORCHESTRATION_TOOLS as b,READONLY_TOOLS as q}from"./catalog.js";import{TERMINAL_STATUSES as d}from"./types.js";const g=4,T=8,D=["starting","running","waiting_input","waiting_approval"];function f(c){return Array.isArray(c)?c.map(t=>{if(typeof t=="string")return t;if(!t||typeof t!="object")return"";const e=t;if(typeof e.text=="string")return e.text;const s=e.content;return Array.isArray(s)?s.map(n=>n&&typeof n=="object"&&typeof n.text=="string"?String(n.text):"").join(""):""}).map(t=>t.replace(/\s+/g," ").trim()).filter(Boolean):[]}class P{store=B();token;apiBase;runtimes=new Map;sockets=new Map;listeners=new Set;approvals=new Map;recent=new Map;streaming=new Set;constructor(t){this.token=this.store.token,this.apiBase=`http://127.0.0.1:${t}/api/bots`;for(const e of this.store.listInstances()){let s=!1;!d.includes(e.status)&&e.status!=="queued"&&(e.status="stale",s=!0);const n=y(e.runtimeMode);n!==e.runtimeMode&&(e.runtimeMode=n,s=!0),s&&this.store.saveInstance(e)}}listTemplates(){return this.store.listTemplates()}getTemplate(t){return this.store.getTemplate(t)}saveTemplate(t){return this.store.saveTemplate(t)}deleteTemplate(t){return this.store.deleteTemplate(t)}catalog(){return O()}listBots(t={}){return this.store.listInstances().filter(s=>!(t.project&&s.projectPath!==t.project||t.parentBotId&&s.parentBotId!==t.parentBotId||t.status&&s.status!==t.status))}getBot(t){return this.store.getInstance(t)}children(t){return this.store.listInstances().filter(e=>e.parentBotId===t)}createInstance(t){const e=this.getTemplate(t.templateId);if(!e)throw new Error(`unknown template: ${t.templateId}`);let s=null;if(t.parentBotId){if(s=this.getBot(t.parentBotId),!s)throw new Error("parent bot not found");if(s.depth+1>g)throw new Error(`nesting depth limit is ${g}`)}let n=t.projectPath||s?.projectPath||process.env.HOME||"/";n==="~"?n=k.homedir():n.startsWith("~/")&&(n=h.join(k.homedir(),n.slice(2)));const r=h.resolve(n),i=this.store.newId(),o=t.isolation||"shared";let l=r;if(o==="worktree"){const p=h.join(this.store.root,"worktrees",i);try{m(h.dirname(p),{recursive:!0,mode:448}),v("git",["-C",r,"worktree","add","-b",`tw-bot/${i.slice(0,8)}`,p],{timeout:2e4,stdio:"ignore"}),l=p}catch{l=r}}const u=new Date().toISOString(),a={id:i,templateId:e.id,title:t.title||e.manifest.name,projectPath:r,workspacePath:l,isolation:o,parentBotId:s?.id,depth:s?s.depth+1:0,runtimeMode:y(t.runtimeMode||e.manifest.permissions?.runtimeMode),projectResources:e.manifest.projectResources||"ignore",status:"queued",sessionFile:h.join(this.store.sessionsDir(i),`${i}.jsonl`),createdAt:u,updatedAt:u,model:e.manifest.model};return m(this.store.sessionsDir(i),{recursive:!0,mode:448}),this.store.saveInstance(a),this.emit(a.id,{type:"status",status:"queued",at:u}),this.pump(),a}activeInProject(t){return this.store.listInstances().filter(e=>e.projectPath===t&&!d.includes(e.status)&&e.status!=="queued").length}pump(){for(const t of this.store.listInstances())t.status==="queued"&&(this.activeInProject(t.projectPath)>=T||this.start(t))}start(t){const e=this.getTemplate(t.templateId);if(!e){this.setStatus(t.id,"failed","template disappeared");return}const s=j(e,t,{apiBase:this.apiBase,token:this.token}),n=e.manifest.binaryPath||"pi",r=new M({command:n,args:s.args,cwd:t.workspacePath,env:s.env,onEvent:i=>this.handleEvent(t.id,i),onStderr:i=>{/error|failed/i.test(i)&&this.emit(t.id,{type:"notice",level:"warn",text:i.slice(0,500),at:new Date().toISOString()})},onExit:()=>{this.runtimes.delete(t.id),this.streaming.delete(t.id);const i=this.store.getInstance(t.id);i&&!d.includes(i.status)&&this.setStatus(t.id,"failed","pi exited unexpectedly"),this.pump()}});this.runtimes.set(t.id,r),t.status="starting",t.pid=void 0,this.store.saveInstance(t),this.emit(t.id,{type:"status",status:"starting",at:new Date().toISOString()}),r.start()}handleEvent(t,e){const s=String(e.type||""),n=new Date().toISOString();switch(s){case"agent_start":this.streaming.add(t),this.setStatus(t,"running");break;case"agent_end":break;case"agent_settled":this.streaming.delete(t),this.setStatus(t,e.aborted===!0?"cancelled":"completed");break;case"message_start":case"message_end":{const r=e.message;if(r){if(s==="message_end"&&r.role==="assistant"){const i=this.store.getInstance(t),o=N(r);i&&o&&(i.lastText=o,this.store.saveInstance(i))}this.emit(t,{type:"message",message:r,at:n})}break}case"message_update":{const r=e.assistantMessageEvent;if(!r)break;const i=r.type==="text_delta"?"text":r.type==="thinking_delta"?"thinking":r.type==="toolcall_delta"?"tool-args":null;if(!i)break;const o=e.message;this.emit(t,{type:"delta",kind:i,delta:String(r.delta||""),contentIndex:typeof r.contentIndex=="number"?r.contentIndex:void 0,messageId:typeof o?.id=="string"?o.id:void 0,at:n});break}case"tool_execution_start":this.emit(t,{type:"tool",phase:"start",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),args:e.args,at:n});break;case"tool_execution_update":this.emit(t,{type:"tool",phase:"update",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:E(e.partialResult),at:n});break;case"tool_execution_end":this.emit(t,{type:"tool",phase:"end",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:E(e.result),isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,at:n});break;case"queue_update":this.emit(t,{type:"queue",steering:f(e.steering),followUp:f(e.followUp),at:n});break;case"extension_ui_request":this.handleUiRequest(t,e);break;default:break}}handleUiRequest(t,e){const s=String(e.method||""),n=new Date().toISOString(),r=this.store.getInstance(t);if(s==="notify"){this.emit(t,{type:"notice",level:e.notifyType==="error"?"error":e.notifyType==="warning"?"warn":"info",text:String(e.message||""),at:n});return}if(!["confirm","select","input","editor"].includes(s))return;const i=String(e.id||""),o=i?this.approvals.get(t)?.get(i):void 0;if(o&&o.state==="pending")return;const l=String(e.title||"Approval required"),u=/^Allow (.+?)\?$/.exec(l),a={id:String(e.id||""),botId:t,botTitle:r?.title||t,kind:s==="confirm"?"tool":"question",method:s,title:l,toolName:u?u[1]:void 0,message:typeof e.message=="string"?e.message:void 0,options:Array.isArray(e.options)?e.options.map(String):void 0,state:"pending",createdAt:n};if(this.approvals.has(t)||this.approvals.set(t,new Map),this.approvals.get(t).set(a.id,a),r&&r.runtimeMode==="parent-supervised"&&r.parentBotId){const p=this.store.getInstance(r.parentBotId);if(p){a.escalatedTo=p.id;const w=a.message?a.message.slice(0,500):"",x=[`Child bot "${r.title}" (${r.id}) needs approval: ${a.title}`,w?`Arguments: ${w}`:"",`Decide with bot_approve({ botId: "${r.id}", requestId: "${a.id}", allow: true|false, reason: "..." }).`,"If you do nothing the user will answer it."].filter(Boolean).join(`
2
- `);this.input(p.id,x,"steer").catch(()=>{this.emit(t,{type:"notice",level:"warn",text:"Could not reach the supervising bot; waiting for the user.",at:n})})}}this.setStatus(t,"waiting_approval"),this.emit(t,{type:"approval",approval:a,at:n})}allowTool(t,e){if(!this.store.getInstance(t))throw new Error("bot not found");const n=h.join(this.store.agentDir(t),".allowed-tools");let r=[];try{r=JSON.parse(I(n,"utf8")),Array.isArray(r)||(r=[])}catch{r=[]}return r.includes(e)||r.push(e),m(h.dirname(n),{recursive:!0,mode:448}),_(n,`${JSON.stringify(r)}
3
- `,{mode:384}),r}allowedTools(t){try{const e=JSON.parse(I(h.join(this.store.agentDir(t),".allowed-tools"),"utf8"));return Array.isArray(e)?e.map(String):[]}catch{return[]}}setRuntimeMode(t,e){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");s.runtimeMode=y(e),this.store.saveInstance(s);const n=h.join(this.store.agentDir(t),".runtime-mode");m(h.dirname(n),{recursive:!0,mode:448}),_(n,`${s.runtimeMode}
4
- `,{mode:384}),this.emit(t,{type:"notice",level:"info",text:`Approval mode: ${e}`,at:new Date().toISOString()})}respondApproval(t,e,s,n,r="human",i=!1){const o=this.approvals.get(t)?.get(e);if(!o)throw new Error("approval not found");const l=this.runtimes.get(t);if(!l)throw new Error("bot is not running");const u={type:"extension_ui_response",id:e};o.method==="confirm"?u.confirmed=s:o.method==="select"?u.value=s?o.options?.[0]:o.options?.[1]||o.options?.[0]:s?u.value=n||"":u.cancelled=!0,l.send(u),s&&i&&o.toolName&&this.allowTool(t,o.toolName),o.state=s?"allowed":"denied",o.decidedBy=r,o.reason=n,o.decidedAt=new Date().toISOString();try{this.store.appendEvent(t,{type:"approval",approval:o,at:o.decidedAt})}catch{}return this.broadcast(t,{type:"approval",approval:o,at:o.decidedAt}),this.setStatus(t,"running"),o}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,n){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()+1e4;for(;!this.runtimes.has(t)&&Date.now()<a;)await new Promise(p=>setTimeout(p,150))}const i=this.runtimes.get(t);if(!i){const a=this.store.getInstance(t)?.status;throw new Error(a==="queued"?"bot is queued behind other bots in this project; send again once it starts":"bot is still starting; send again in a moment")}const o=new Date().toISOString();this.emit(t,{type:"user",text:e,at:o});const l={type:"prompt",message:e};n?.length&&(l.images=n.map(a=>({type:"image",data:a.data,mimeType:a.mimeType})));const u=this.streaming.has(t)||D.includes(r.status);s==="follow_up"?l.streamingBehavior="followUp":(s==="steer"||u)&&(l.streamingBehavior="steer");try{await i.request(l,3e4)}catch(a){const p=a instanceof Error?a.message:String(a);if(!l.streamingBehavior&&/stream/i.test(p)){await i.request({...l,streamingBehavior:"steer"},3e4);return}throw a}}async clearQueue(t){const e=this.runtimes.get(t);if(!e)throw new Error("bot is not running");const n=(await e.request({type:"clear_queue"},1e4)).data??{};return[...f(n.steering),...f(n.followUp)]}stop(t,e=!0){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");if(e)for(const n of this.children(t))this.stop(n.id,!0);try{this.runtimes.get(t)?.kill()}catch{}this.runtimes.delete(t),this.streaming.delete(t),d.includes(s.status)||this.setStatus(t,"cancelled"),this.pump()}resume(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");this.runtimes.has(t)||(e.status="queued",this.store.saveInstance(e),this.emit(t,{type:"status",status:"queued",at:new Date().toISOString()}),this.pump())}deleteBot(t,e=!0){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");if(e)for(const n of this.children(t))this.deleteBot(n.id,!0);try{this.runtimes.get(t)?.kill()}catch{}if(this.runtimes.delete(t),this.streaming.delete(t),this.store.deleteInstance(t),this.approvals.delete(t),this.recent.delete(t),s.isolation==="worktree"){try{v("git",["-C",s.projectPath,"worktree","remove","--force",s.workspacePath],{timeout:2e4,stdio:"ignore"})}catch{}A(s.workspacePath,{recursive:!0,force:!0})}this.pump()}status(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");const s=[...this.approvals.get(t)?.values()||[]].filter(n=>n.state==="pending");return{...e,pendingApprovals:s.length,lastText:e.lastText?.slice(0,4e3)}}result(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");return{botId:t,status:e.status,text:e.lastText||"",title:e.title}}async waitFor(t,e=45e3){const s=Date.now()+Math.min(e,45e3),n=new Set(t);for(;Date.now()<s;){const r=[...n].filter(i=>{const o=this.store.getInstance(i);return!o||d.includes(o.status)});if(r.length)return{bots:r.map(i=>this.result(i))};await new Promise(i=>setTimeout(i,250))}return{timeout:!0,bots:t.map(r=>{const i=this.store.getInstance(r);return{botId:r,status:i?.status||"missing",title:i?.title}})}}attachSocket(t,e){this.sockets.has(t)||this.sockets.set(t,new Set),this.sockets.get(t).add(e);const s=this.store.getInstance(t);e.send(JSON.stringify({type:"snapshot",bot:s,approvals:this.listApprovals().filter(n=>n.botId===t)}));for(const n of this.store.readEvents(t,400))e.send(JSON.stringify(n));e.on("close",()=>this.sockets.get(t)?.delete(e))}broadcast(t,e){const s=JSON.stringify(e);for(const n of this.sockets.get(t)||[])if(n.readyState===1)try{n.send(s)}catch{}}emit(t,e){this.store.appendEvent(t,e);const s=this.recent.get(t)||[];s.push(e),s.length>800&&s.splice(0,s.length-800),this.recent.set(t,s),this.broadcast(t,e);for(const n of this.listeners)try{n(e)}catch{}}onEvent(t){return this.listeners.add(t),()=>this.listeners.delete(t)}setStatus(t,e,s){const n=this.store.getInstance(t);n&&(n.status=e,s&&(n.lastError=s),this.store.saveInstance(n),this.emit(t,{type:"status",status:e,at:new Date().toISOString(),error:s}),d.includes(e)&&this.pump())}}function y(c){return c==="full-access"?"full-access":c==="parent-supervised"?"parent-supervised":"supervised"}function N(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 E(c){if(c==null)return"";if(typeof c=="string")return c;try{return JSON.stringify(c).slice(0,4e3)}catch{return String(c)}}let S=null;function X(){if(!S){const c=Number(process.env.PORT)||21e3;S=new P(c)}return S}export{P as BotManager,T as MAX_CONCURRENT_PER_PROJECT,g as MAX_DEPTH,b as ORCHESTRATION_TOOLS,q as READONLY_TOOLS,X as getBotManager};
1
+ import{execFileSync as v}from"node:child_process";import{mkdirSync as m,readFileSync as I,rmSync as A,writeFileSync as T}from"node:fs";import h from"node:path";import _ from"node:os";import{getBotStore as B}from"./store.js";import{materialize as O}from"./materialize.js";import{PiRpc as j}from"./rpc.js";import{buildCatalog as M,ORCHESTRATION_TOOLS as b,READONLY_TOOLS as D}from"./catalog.js";import{TERMINAL_STATUSES as d}from"./types.js";const g=4,k=8,P=["starting","running","waiting_input","waiting_approval"];function f(c){return Array.isArray(c)?c.map(t=>{if(typeof t=="string")return t;if(!t||typeof t!="object")return"";const e=t;if(typeof e.text=="string")return e.text;const s=e.content;return Array.isArray(s)?s.map(n=>n&&typeof n=="object"&&typeof n.text=="string"?String(n.text):"").join(""):""}).map(t=>t.replace(/\s+/g," ").trim()).filter(Boolean):[]}class q{store=B();token;apiBase;runtimes=new Map;sockets=new Map;listeners=new Set;approvals=new Map;recent=new Map;streaming=new Set;constructor(t){this.token=this.store.token,this.apiBase=`http://127.0.0.1:${t}/api/bots`;for(const e of this.store.listInstances()){let s=!1,n=!1;!d.includes(e.status)&&e.status!=="queued"&&(e.status="stale",n=!0,s=!0);const r=y(e.runtimeMode);if(r!==e.runtimeMode&&(e.runtimeMode=r,s=!0),s&&this.store.saveInstance(e),n){const i=new Date().toISOString();this.emit(e.id,{type:"status",status:"stale",at:i}),this.emit(e.id,{type:"notice",level:"warn",text:"The hub restarted while this bot was running, so it is paused. Press Resume or send a message to continue from its session.",at:i})}}}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 M()}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>g)throw new Error(`nesting depth limit is ${g}`)}let n=t.projectPath||s?.projectPath||process.env.HOME||"/";n==="~"?n=_.homedir():n.startsWith("~/")&&(n=h.join(_.homedir(),n.slice(2)));const r=h.resolve(n),i=this.store.newId(),o=t.isolation||"shared";let l=r;if(o==="worktree"){const p=h.join(this.store.root,"worktrees",i);try{m(h.dirname(p),{recursive:!0,mode:448}),v("git",["-C",r,"worktree","add","-b",`tw-bot/${i.slice(0,8)}`,p],{timeout:2e4,stdio:"ignore"}),l=p}catch{l=r}}const u=new Date().toISOString(),a={id:i,templateId:e.id,title:t.title||e.manifest.name,projectPath:r,workspacePath:l,isolation:o,parentBotId:s?.id,depth:s?s.depth+1:0,runtimeMode:y(t.runtimeMode||e.manifest.permissions?.runtimeMode),projectResources:e.manifest.projectResources||"ignore",status:"queued",sessionFile:h.join(this.store.sessionsDir(i),`${i}.jsonl`),createdAt:u,updatedAt:u,model:e.manifest.model};return m(this.store.sessionsDir(i),{recursive:!0,mode:448}),this.store.saveInstance(a),this.emit(a.id,{type:"status",status:"queued",at:u}),this.pump(),a}activeInProject(t){return this.store.listInstances().filter(e=>e.projectPath===t&&!d.includes(e.status)&&e.status!=="queued").length}pump(){for(const t of this.store.listInstances())t.status==="queued"&&(this.activeInProject(t.projectPath)>=k||this.start(t))}start(t){const e=this.getTemplate(t.templateId);if(!e){this.setStatus(t.id,"failed","template disappeared");return}const s=O(e,t,{apiBase:this.apiBase,token:this.token}),n=e.manifest.binaryPath||"pi",r=new j({command:n,args:s.args,cwd:t.workspacePath,env:s.env,onEvent:i=>this.handleEvent(t.id,i),onStderr:i=>{/error|failed/i.test(i)&&this.emit(t.id,{type:"notice",level:"warn",text:i.slice(0,500),at:new Date().toISOString()})},onExit:()=>{this.runtimes.delete(t.id),this.streaming.delete(t.id);const i=this.store.getInstance(t.id);i&&!d.includes(i.status)&&this.setStatus(t.id,"failed","pi exited unexpectedly"),this.pump()}});this.runtimes.set(t.id,r),t.status="starting",t.pid=void 0,this.store.saveInstance(t),this.emit(t.id,{type:"status",status:"starting",at:new Date().toISOString()}),r.start()}handleEvent(t,e){const s=String(e.type||""),n=new Date().toISOString();switch(s){case"agent_start":this.streaming.add(t),this.setStatus(t,"running");break;case"agent_end":break;case"agent_settled":this.streaming.delete(t),this.setStatus(t,e.aborted===!0?"cancelled":"completed");break;case"message_start":case"message_end":{const r=e.message;if(r){if(s==="message_end"&&r.role==="assistant"){const i=this.store.getInstance(t),o=N(r);i&&o&&(i.lastText=o,this.store.saveInstance(i))}this.emit(t,{type:"message",message:r,at:n})}break}case"message_update":{const r=e.assistantMessageEvent;if(!r)break;const i=r.type==="text_delta"?"text":r.type==="thinking_delta"?"thinking":r.type==="toolcall_delta"?"tool-args":null;if(!i)break;const o=e.message;this.emit(t,{type:"delta",kind:i,delta:String(r.delta||""),contentIndex:typeof r.contentIndex=="number"?r.contentIndex:void 0,messageId:typeof o?.id=="string"?o.id:void 0,at:n});break}case"tool_execution_start":this.emit(t,{type:"tool",phase:"start",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),args:e.args,at:n});break;case"tool_execution_update":this.emit(t,{type:"tool",phase:"update",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:x(e.partialResult),at:n});break;case"tool_execution_end":this.emit(t,{type:"tool",phase:"end",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:x(e.result),isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,at:n});break;case"queue_update":this.emit(t,{type:"queue",steering:f(e.steering),followUp:f(e.followUp),at:n});break;case"extension_ui_request":this.handleUiRequest(t,e);break;default:break}}handleUiRequest(t,e){const s=String(e.method||""),n=new Date().toISOString(),r=this.store.getInstance(t);if(s==="notify"){this.emit(t,{type:"notice",level:e.notifyType==="error"?"error":e.notifyType==="warning"?"warn":"info",text:String(e.message||""),at:n});return}if(!["confirm","select","input","editor"].includes(s))return;const i=String(e.id||""),o=i?this.approvals.get(t)?.get(i):void 0;if(o&&o.state==="pending")return;const l=String(e.title||"Approval required"),u=/^Allow (.+?)\?$/.exec(l),a={id:String(e.id||""),botId:t,botTitle:r?.title||t,kind:s==="confirm"?"tool":"question",method:s,title:l,toolName:u?u[1]:void 0,message:typeof e.message=="string"?e.message:void 0,options:Array.isArray(e.options)?e.options.map(String):void 0,state:"pending",createdAt:n};if(this.approvals.has(t)||this.approvals.set(t,new Map),this.approvals.get(t).set(a.id,a),r&&r.runtimeMode==="parent-supervised"&&r.parentBotId){const p=this.store.getInstance(r.parentBotId);if(p){a.escalatedTo=p.id;const w=a.message?a.message.slice(0,500):"",E=[`Child bot "${r.title}" (${r.id}) needs approval: ${a.title}`,w?`Arguments: ${w}`:"",`Decide with bot_approve({ botId: "${r.id}", requestId: "${a.id}", allow: true|false, reason: "..." }).`,"If you do nothing the user will answer it."].filter(Boolean).join(`
2
+ `);this.input(p.id,E,"steer").catch(()=>{this.emit(t,{type:"notice",level:"warn",text:"Could not reach the supervising bot; waiting for the user.",at:n})})}}this.setStatus(t,"waiting_approval"),this.emit(t,{type:"approval",approval:a,at:n})}allowTool(t,e){if(!this.store.getInstance(t))throw new Error("bot not found");const n=h.join(this.store.agentDir(t),".allowed-tools");let r=[];try{r=JSON.parse(I(n,"utf8")),Array.isArray(r)||(r=[])}catch{r=[]}return r.includes(e)||r.push(e),m(h.dirname(n),{recursive:!0,mode:448}),T(n,`${JSON.stringify(r)}
3
+ `,{mode:384}),r}allowedTools(t){try{const e=JSON.parse(I(h.join(this.store.agentDir(t),".allowed-tools"),"utf8"));return Array.isArray(e)?e.map(String):[]}catch{return[]}}setRuntimeMode(t,e){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");s.runtimeMode=y(e),this.store.saveInstance(s);const n=h.join(this.store.agentDir(t),".runtime-mode");m(h.dirname(n),{recursive:!0,mode:448}),T(n,`${s.runtimeMode}
4
+ `,{mode:384}),this.emit(t,{type:"notice",level:"info",text:`Approval mode: ${e}`,at:new Date().toISOString()})}respondApproval(t,e,s,n,r="human",i=!1){const o=this.approvals.get(t)?.get(e);if(!o)throw new Error("approval not found");const l=this.runtimes.get(t);if(!l)throw new Error("bot is not running");const u={type:"extension_ui_response",id:e};o.method==="confirm"?u.confirmed=s:o.method==="select"?u.value=s?o.options?.[0]:o.options?.[1]||o.options?.[0]:s?u.value=n||"":u.cancelled=!0,l.send(u),s&&i&&o.toolName&&this.allowTool(t,o.toolName),o.state=s?"allowed":"denied",o.decidedBy=r,o.reason=n,o.decidedAt=new Date().toISOString();try{this.store.appendEvent(t,{type:"approval",approval:o,at:o.decidedAt})}catch{}return this.broadcast(t,{type:"approval",approval:o,at:o.decidedAt}),this.setStatus(t,"running"),o}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,n){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()+1e4;for(;!this.runtimes.has(t)&&Date.now()<a;)await new Promise(p=>setTimeout(p,150))}const i=this.runtimes.get(t);if(!i){const a=this.store.getInstance(t)?.status;throw new Error(a==="queued"?"bot is queued behind other bots in this project; send again once it starts":"bot is still starting; send again in a moment")}const o=new Date().toISOString();this.emit(t,{type:"user",text:e,at:o});const l={type:"prompt",message:e};n?.length&&(l.images=n.map(a=>({type:"image",data:a.data,mimeType:a.mimeType})));const u=this.streaming.has(t)||P.includes(r.status);s==="follow_up"?l.streamingBehavior="followUp":(s==="steer"||u)&&(l.streamingBehavior="steer");try{await i.request(l,3e4)}catch(a){const p=a instanceof Error?a.message:String(a);if(!l.streamingBehavior&&/stream/i.test(p)){await i.request({...l,streamingBehavior:"steer"},3e4);return}throw a}}async clearQueue(t){const e=this.runtimes.get(t);if(!e)throw new Error("bot is not running");const n=(await e.request({type:"clear_queue"},1e4)).data??{};return[...f(n.steering),...f(n.followUp)]}stop(t,e=!0){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");if(e)for(const n of this.children(t))this.stop(n.id,!0);try{this.runtimes.get(t)?.kill()}catch{}this.runtimes.delete(t),this.streaming.delete(t),d.includes(s.status)||this.setStatus(t,"cancelled"),this.pump()}resume(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");this.runtimes.has(t)||(e.status="queued",this.store.saveInstance(e),this.emit(t,{type:"status",status:"queued",at:new Date().toISOString()}),this.pump())}deleteBot(t,e=!0){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");if(e)for(const n of this.children(t))this.deleteBot(n.id,!0);try{this.runtimes.get(t)?.kill()}catch{}if(this.runtimes.delete(t),this.streaming.delete(t),this.store.deleteInstance(t),this.approvals.delete(t),this.recent.delete(t),s.isolation==="worktree"){try{v("git",["-C",s.projectPath,"worktree","remove","--force",s.workspacePath],{timeout:2e4,stdio:"ignore"})}catch{}A(s.workspacePath,{recursive:!0,force:!0})}this.pump()}status(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");const s=[...this.approvals.get(t)?.values()||[]].filter(n=>n.state==="pending");return{...e,pendingApprovals:s.length,lastText:e.lastText?.slice(0,4e3)}}result(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");return{botId:t,status:e.status,text:e.lastText||"",title:e.title}}async waitFor(t,e=45e3){const s=Date.now()+Math.min(e,45e3),n=new Set(t);for(;Date.now()<s;){const r=[...n].filter(i=>{const o=this.store.getInstance(i);return!o||d.includes(o.status)});if(r.length)return{bots:r.map(i=>this.result(i))};await new Promise(i=>setTimeout(i,250))}return{timeout:!0,bots:t.map(r=>{const i=this.store.getInstance(r);return{botId:r,status:i?.status||"missing",title:i?.title}})}}attachSocket(t,e){this.sockets.has(t)||this.sockets.set(t,new Set),this.sockets.get(t).add(e);const s=this.store.getInstance(t);e.send(JSON.stringify({type:"snapshot",bot:s,approvals:this.listApprovals().filter(n=>n.botId===t)}));for(const n of this.store.readEvents(t,400))e.send(JSON.stringify(n));e.on("close",()=>this.sockets.get(t)?.delete(e))}broadcast(t,e){const s=JSON.stringify(e);for(const n of this.sockets.get(t)||[])if(n.readyState===1)try{n.send(s)}catch{}}emit(t,e){this.store.appendEvent(t,e);const s=this.recent.get(t)||[];s.push(e),s.length>800&&s.splice(0,s.length-800),this.recent.set(t,s),this.broadcast(t,e);for(const n of this.listeners)try{n(e)}catch{}}onEvent(t){return this.listeners.add(t),()=>this.listeners.delete(t)}setStatus(t,e,s){const n=this.store.getInstance(t);n&&(n.status=e,s&&(n.lastError=s),this.store.saveInstance(n),this.emit(t,{type:"status",status:e,at:new Date().toISOString(),error:s}),d.includes(e)&&this.pump())}}function y(c){return c==="full-access"?"full-access":c==="parent-supervised"?"parent-supervised":"supervised"}function N(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 x(c){if(c==null)return"";if(typeof c=="string")return c;try{return JSON.stringify(c).slice(0,4e3)}catch{return String(c)}}let S=null;function X(){if(!S){const c=Number(process.env.PORT)||21e3;S=new q(c)}return S}export{q as BotManager,k as MAX_CONCURRENT_PER_PROJECT,g as MAX_DEPTH,b as ORCHESTRATION_TOOLS,D as READONLY_TOOLS,X as getBotManager};