tmux-weblink 3.2.4 → 3.2.6

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 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};
1
+ import{icon as L}from"../lib/icons.js";import{createMarkdownRenderer as Ke}from"./markdown.js";const he=Ke(document),l={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,queues:new Map,ws:null,lastSocketAt:0,pollTimer:0,renderQueued:!1};let N=[],M=!0;const Ae=200;let Be=Ae,Ge=!1,Te=0;function be(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function y(e,t){const n=await fetch(e,{...t,headers:{"content-type":"application/json",Authorization:`Bearer ${be()}`,...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 H(){ve||(ve=requestAnimationFrame(()=>{ve=0,Xe()}))}let ve=0,ne="";function Xe(){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(l.activeId&&t&&n&&!o){const s=document.querySelector(".fixed-header"),a=s?Math.round(s.getBoundingClientRect().height):0,d=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|${d}|${c}|${r}|${p}`;if(f===ne)return;ne=f,e.style.position="fixed",e.style.top=`${d}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",H),window.visualViewport?.addEventListener("scroll",H),window.addEventListener("resize",H),document.addEventListener("click",H);const Oe=document.querySelector(".sidebar");Oe&&new MutationObserver(H).observe(Oe,{attributes:!0,attributeFilter:["class"]}),window.__syncBotsViewport=H;function oe(){const e=l.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?String(e):"",n.hidden=e===0);const o=document.getElementById("bv-inbox");o&&Le(o,e),window.__botsSnapshot=l.bots,window.__refreshSidebar?.()}function Le(e,t){const n=t>0?`Needs you (${t})`:"Needs you";e.title=t>0?`${t} request${t===1?"":"s"} waiting for you`:"Nothing waiting for you",e.setAttribute("aria-label",n)}function Ye(){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(),ee()}),t?.addEventListener("click",()=>{o(),ht()}),n?.addEventListener("click",()=>{o(),Ie()})}function Ze(){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 d=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"),Ve(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,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=u,W.setAttribute("role","menuitemradio"),W.innerHTML=`<span class="bv-menu-icon">${L(We[u],'width="15" height="15"')}</span><span class="bv-menu-text"><b>${w}</b><span>${T}</span></span><span class="bv-menu-check">${L("check",'width="13" height="13"')}</span>`,W.onclick=()=>{f(!1),ot(u)},p.appendChild(W)}const f=u=>{u&&J(!1),p.hidden=!u,r.setAttribute("aria-expanded",u?"true":"false")};r.onclick=u=>{u.stopPropagation(),f(p.hidden)},c.append(r);const v=i("button","btn bv-resume","Resume");v.id="bv-resume",v.type="button",v.title="Continue this bot from its session",v.onclick=()=>{l.activeId&&(v.disabled=!0,y(`/api/bots/${l.activeId}/resume`,{method:"POST"}).then(()=>A(!0)).finally(()=>{v.disabled=!1}))},v.hidden=!0;const g=i("button","bv-icon-btn bv-inbox-btn");g.id="bv-inbox",g.type="button",Le(g,0),g.innerHTML=`${L("inbox",'width="16" height="16"')}<span class="bv-inbox-badge" id="bv-inbox-count" hidden></span>`,g.onclick=()=>void Ie();const b=i("button","bv-icon-btn");b.id="bv-more-btn",b.type="button",b.title="More actions",b.setAttribute("aria-label","More actions"),b.setAttribute("aria-haspopup","menu"),b.setAttribute("aria-expanded","false"),b.innerHTML=L("dots",'width="16" height="16"');const h=i("div","bv-menu");h.id="bv-more-menu",h.setAttribute("role","menu"),h.hidden=!0;const E=(u,w,T,W)=>{const X=i("button",`bv-menu-item${u?` ${u}`:""}`);return X.type="button",X.setAttribute("role","menuitem"),X.innerHTML=`<span class="bv-menu-icon">${L(w,'width="15" height="15"')}</span><span class="bv-menu-text"><b>${T}</b></span>`,X.onclick=()=>{J(!1),W()},X},C=E("","check","Allow all",()=>{if(!l.activeId)return;const u=l.approvals.filter(w=>w.botId===l.activeId);Promise.all(u.map(w=>y(`/api/bots/${w.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:w.id,allow:!0})}))).finally(()=>void A(!0))});C.id="bv-allow-all",C.title="Approve every pending request for this bot";const j=E("","refresh","Resume bot",()=>_e(u=>y(`/api/bots/${u}/resume`,{method:"POST"}).then(()=>A(!0)))),Q=E("","stop","Stop run",()=>_e(u=>y(`/api/bots/${u}/stop`,{method:"POST"}).then(()=>A(!0)))),R=E("danger","delete","Delete bot",()=>{l.activeId&&confirm("Delete this bot and its session?")&&y(`/api/bots/${l.activeId}`,{method:"DELETE"}).then(()=>{we(),A(!0)})});h.append(C,j,Q,i("div","bv-menu-sep"),R);const J=u=>{u&&f(!1),h.hidden=!u,b.setAttribute("aria-expanded",u?"true":"false")};b.onclick=u=>{u.stopPropagation(),J(h.hidden)},document.addEventListener("click",u=>{const w=u.target;w&&(!c.contains(w)&&!p.contains(w)&&f(!1),!b.contains(w)&&!h.contains(w)&&J(!1))}),d.append(c,v,g,b),t.append(n,d);const x=i("div","bots-messages");x.id="bots-messages";const k=i("button","bv-jump");k.type="button",k.id="bv-jump",k.innerHTML=`${L("chevron-down",'width="14" height="14"')}<span>Latest</span>`,k.title="Jump to the latest message",k.hidden=!0,k.onclick=()=>{M=!0,x.scrollTop=x.scrollHeight,k.hidden=!0};const te=()=>{M=x.scrollHeight-x.scrollTop-x.clientHeight<48,k.hidden=M};x.addEventListener("scroll",te,{passive:!0}),x.addEventListener("touchmove",()=>{M=!1,k.hidden=x.scrollHeight-x.clientHeight<1},{passive:!0}),x.addEventListener("wheel",()=>{M=!1},{passive:!0});const m=i("div","bots-composer-wrap"),B=i("div","bv-queue");B.id="bv-queue",B.hidden=!0;const I=i("span","bv-queue-text"),z=i("button","bv-queue-clear","Clear");z.type="button",z.title="Drop the queued messages",z.onclick=()=>{l.activeId&&y(`/api/bots/${l.activeId}/queue/clear`,{method:"POST"}).then(()=>ae(),u=>P(u instanceof Error?u.message:String(u)))},B.append(I,z);const S=i("div","bv-attach-strip");S.id="bv-attach-strip",S.hidden=!0;const ue=i("div","bv-composer-error");ue.id="bv-composer-error",ue.hidden=!0;const me=i("div","bv-suggest");me.id="bv-suggest",me.hidden=!0;const fe=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=L("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 u of Array.from(O.files??[]))ge(u);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=u=>{tt(u)||u.key!=="Enter"||u.shiftKey||u.isComposing||$e||u.keyCode===229||(u.preventDefault(),He())},$.oninput=()=>{P(null),ie($),De()},$.onclick=()=>De(),$.addEventListener("paste",u=>{const w=Array.from(u.clipboardData?.files??[]).filter(T=>T.type.startsWith("image/"));if(w.length!==0){u.preventDefault();for(const T of w)ge(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 He(),fe.append(U,$,K),fe.addEventListener("click",u=>{const w=u.target;w?.closest("button")&&_(),!w?.closest("button")&&document.activeElement!==$&&$.focus()}),m.addEventListener("dragover",u=>{u.dataTransfer&&(u.preventDefault(),m.classList.add("drop-target"))}),m.addEventListener("dragleave",()=>m.classList.remove("drop-target")),m.addEventListener("drop",u=>{u.preventDefault(),m.classList.remove("drop-target");const w=Array.from(u.dataTransfer?.files??[]).filter(T=>T.type.startsWith("image/"));for(const T of w)ge(T)}),m.append(B,S,me,ue,O,fe),e.append(t,x,k,m,p,h),document.querySelector(".main-area")?.appendChild(e),document.getElementById("bots-modal")||mt()}function P(e){const t=document.getElementById("bv-composer-error");t&&(t.textContent=e??"",t.hidden=!e)}function Ne(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 q=[],Pe=4,et=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=q.length===0,q.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=()=>{q.splice(n,1),se()},o.append(s,a),e.appendChild(o)}))}async function ge(e){if(!e.type.startsWith("image/")){P("Only image attachments are supported.");return}if(q.length>=Pe){P(`At most ${Pe} images per message.`);return}if(e.size>et){P("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(",");q.push({data:t.slice(n+1),mimeType:e.type,name:e.name||"image",preview:t}),P(null),se()}function ae(){const e=document.getElementById("bv-queue");if(!e)return;const t=l.activeId?l.queues.get(l.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 D=[],G=0,re=null,yt=null;function _(){const e=document.getElementById("bv-suggest");e&&(e.hidden=!0),D=[],re=null}function ye(){const e=document.getElementById("bv-suggest");if(e){if(e.textContent="",D.length===0){e.hidden=!0;return}e.hidden=!1,D.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">${qe(t.label)}</span><span class="bv-suggest-detail">${qe(t.detail)}</span>`,o.onmousedown=s=>s.preventDefault(),o.onclick=()=>je(n),e.appendChild(o)})}}function qe(e){return e.replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t])}async function De(){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(re={start:t-a.length-1,end:t},s==="/"){const v=l.catalog,g=(v?.prompts??[]).map(h=>({kind:"prompt",label:`/${h.name}`,detail:"prompt template",value:`/${h.name} `})),b=(v?.skills??[]).map(h=>({kind:"skill",label:`/skill:${h.name}`,detail:h.description||"skill",value:`/skill:${h.name} `}));D=[...g,...b].filter(h=>h.label.toLowerCase().includes(a.toLowerCase())||h.detail.toLowerCase().includes(a.toLowerCase())).slice(0,8),G=0,ye();return}const c=Z();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 y(`/api/fs/list?path=${encodeURIComponent(p)}`)).entries??[]).filter(b=>b.name.toLowerCase().startsWith(f.toLowerCase())).slice(0,8).map(b=>{const h=r>=0?a.slice(0,r+1):"";return{kind:"file",label:`@${h}${b.name}${b.type==="dir"?"/":""}`,detail:b.type==="dir"?"directory":"file",value:`@${h}${b.name}${b.type==="dir"?"/":" "}`}}),G=0,ye()}catch{_()}}function je(e){const t=document.getElementById("bots-input"),n=D[e];if(!t||!n||!re)return;const{start:o,end:s}=re;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 tt(e){const t=document.getElementById("bv-suggest");if(!t||t.hidden||D.length===0)return!1;if(e.key==="ArrowDown"||e.key==="ArrowUp"){e.preventDefault();const n=e.key==="ArrowDown"?1:-1;return G=(G+n+D.length)%D.length,ye(),!0}return e.key==="Enter"||e.key==="Tab"?(e.preventDefault(),je(G),!0):e.key==="Escape"?(e.preventDefault(),_(),!0):!1}async function He(){const e=document.getElementById("bots-input");if(!e||!l.activeId||Ge||!e.value.trim()&&q.length===0)return;const t=l.activeId,n=e.value.trim()?e.value:"See the attached image",o=q.map(({data:s,mimeType:a})=>({data:s,mimeType:a}));P(null),Ne(!0);try{await y(`/api/bots/${t}/input`,{method:"POST",body:JSON.stringify({text:n,images:o.length?o:void 0})}),e.value===n&&(e.value="",ie(e)),_(),q.length=0,se(),M=!0}catch(s){P(s instanceof Error?s.message:String(s))}finally{Ne(!1)}}function _e(e){l.activeId&&e(l.activeId).catch(t=>V({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)}))}function we(){l.activeId=null,N=[],M=!0,H();const e=document.getElementById("bots-view");e&&(e.hidden=!0);try{l.ws?.close()}catch{}l.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){l.activeId=e,N=[],M=!0,l.queues.delete(e),q.length=0,se(),ae(),_();const t=document.getElementById("bots-input");t&&(t.value="",ie(t)),P(null);const n=document.getElementById("bv-jump");n&&(n.hidden=!0),window.__collapseSidebar?.(),H(),l.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 d=document.getElementById("file-editor");d&&(d.style.display="none"),oe(),de();const c=Z();c&&c.status==="stale"&&y(`/api/bots/${e}/resume`,{method:"POST"}).then(()=>A(!0)).catch(()=>{}),Je(e),await A(!0)}function Je(e){try{l.ws?.close()}catch{}const t=location.protocol==="https:"?"wss:":"ws:",n=new WebSocket(`${t}//${location.host}/ws/bots/${encodeURIComponent(e)}?token=${encodeURIComponent(be())}`);l.ws=n,l.lastSocketAt=Date.now(),n.onmessage=o=>{l.lastSocketAt=Date.now();try{Fe(JSON.parse(String(o.data)))}catch{}},n.onclose=()=>{l.activeId===e&&setTimeout(()=>{l.activeId===e&&Y()},1500)}}let le=0;function Y(){const e=l.activeId;if(!e)return;const t=le?Date.now()-le:0;le=0;const n=l.ws;(!n||n.readyState!==WebSocket.OPEN||t>1e4||Date.now()-l.lastSocketAt>6e4)&&Je(e),A(!0)}document.addEventListener("visibilitychange",()=>{if(document.hidden){le=Date.now();return}Y()}),window.addEventListener("pageshow",e=>{e.persisted&&Y()}),window.addEventListener("online",()=>Y()),window.setInterval(()=>{if(document.hidden||!l.activeId)return;const e=l.ws;(!e||e.readyState!==WebSocket.OPEN)&&Y()},2e4);function Z(){return l.bots.find(e=>e.id===l.activeId)||null}function ke(){const e=Z();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=nt[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&&Ve(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 d=document.getElementById("bv-allow-all"),c=l.approvals.filter(r=>r.botId===e.id).length;if(d){d.hidden=c===0;const r=d.querySelector(".bv-menu-text b");r&&(r.textContent=`Allow all (${c})`)}o&&(o.style.background=Me(e.status))}const nt={queued:"queued",starting:"starting",running:"running",waiting_input:"waiting",waiting_approval:"approval",completed:"done",failed:"failed",cancelled:"stopped",stale:"stale"},Ue={supervised:"\u9ED8\u8BA4","parent-supervised":"\u76D1\u7BA1","full-access":"\u5168\u653E\u884C"},We={supervised:"shield","parent-supervised":"shield-up","full-access":"shield-alert"};function Ve(e,t){const n=We[t]??"shield";e.dataset.mode=t,e.innerHTML=L(n,'width="15" height="15"');const o=`\u5BA1\u6279\u6A21\u5F0F\uFF1A${Ue[t]??t}`;e.title=`${o}\uFF08\u70B9\u5F00\u53EF\u5207\u6362\uFF09`,e.setAttribute("aria-label",o)}async function ot(e){if(l.activeId)try{await y(`/api/bots/${l.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:e})});const t=Z();t&&(t.runtimeMode=e),ke(),V({kind:"notice",level:"info",text:`\u5BA1\u6279\u6A21\u5F0F\uFF1A${Ue[e]||e}`})}catch(t){V({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)})}}function V(e,t=l.activeId){if(!t)return;const n=l.items.get(t)||[];n.push(e),l.items.set(t,n),t===l.activeId&&F()}function F(){if(l.renderQueued)return;l.renderQueued=!0;const e=Math.max(0,60-(performance.now()-Te));window.setTimeout(()=>{l.renderQueued=!1,Te=performance.now(),de()},e)}function Se(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 it(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 xe(e){if(e.kind==="user"){const t=i("div","bv-msg bv-user");return t.appendChild(he(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(he(e.text)),t.appendChild(n),t}return e.kind==="tool"?rt(e):e.kind==="approval"?lt(e):i("div",`bv-notice bv-notice-${e.level}`,e.text)}function st(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(he(t.text))}function de(){const e=document.getElementById("bots-messages");if(!e||!l.activeId||document.getElementById("bots-view")?.hidden)return;const t=l.items.get(l.activeId)||[],n=Math.max(0,t.length-Be),o=n?t.slice(n):t,s=M;if(o.length<N.length||o.some((d,c)=>N[c]?.item!==d))e.textContent="",N=o.map(d=>{const c=xe(d);return e.appendChild(c),{item:d,snapshot:Se(d),node:c}});else{for(let d=N.length;d<o.length;d++){const c=o[d],r=xe(c);e.appendChild(r),N.push({item:c,snapshot:Se(c),node:r})}for(let d=0;d<o.length;d++){const c=o[d],r=N[d],p=Se(c);if(it(r.snapshot,p)){if(c.kind==="assistant")st(r.node,c);else{const f=xe(c);r.node.replaceWith(f),r.node=f}r.snapshot=p}}}at(e,n),s&&(e.scrollTop=e.scrollHeight)}function at(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,d=e.scrollTop;Be+=Ae,N=[],de(),e.scrollTop=d+(e.scrollHeight-a)},e.prepend(s)}function rt(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 lt(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 g=i("pre","bv-pre bv-approval-detail");g.textContent=n.message,t.appendChild(g)}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"),d=/^Allow (.+?)\?$/.exec(n.title)?.[1],c=n.method==="confirm"?d&&d.length<=24?`Always allow ${d}`:"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],v=async(g,b,h)=>{const E=h.textContent??"";for(const C of f)C.disabled=!0;h.textContent=g?"Allowing\u2026":"Denying\u2026";try{await y(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:g,always:b,reason:o.value||void 0})}),e.decided=g?"allowed":"denied",F(),A(!0)}catch(C){for(const j of f)j.disabled=!1;h.textContent=E,V({kind:"notice",level:"error",text:C instanceof Error?C.message:String(C)})}};return a.onclick=()=>void v(!0,!1,a),r.onclick=()=>void v(!0,!0,r),p.onclick=()=>void v(!1,!1,p),s.append(o,a,r,p),t.appendChild(s),t}function Fe(e){const t=String(e.type||""),n=l.activeId;if(!n)return;const o=l.items.get(n)||[];if(t==="snapshot")l.items.set(n,[]);else if(t==="queue")l.queues.set(n,{steering:Array.isArray(e.steering)?e.steering:[],followUp:Array.isArray(e.followUp)?e.followUp:[]}),ae();else if(t==="user")M=!0,V({kind:"user",text:String(e.text||"")});else if(t==="status"){const s=Z(),a=String(e.status||"");s&&(s.status=a||s.status),["completed","failed","cancelled","stale"].includes(a)&&(l.queues.delete(n),ae()),ke(),pt()}else if(t==="message"){const s=e.message;if(!s||String(s.role||"")!=="assistant")return;const d=dt(s),c=ct(s),r=o[o.length-1];r&&r.kind==="assistant"?(r.text=d||r.text,r.thinking=c||r.thinking):o.push({kind:"assistant",text:d,thinking:c}),l.items.set(n,o),F()}else if(t==="delta"){const s=String(e.kind||""),a=String(e.delta||"");let d=o[o.length-1];(!d||d.kind!=="assistant")&&(o.push({kind:"assistant",text:"",thinking:""}),d=o[o.length-1]),d.kind==="assistant"&&(s==="text"?d.text+=a:s==="thinking"&&(d.thinking+=a)),l.items.set(n,o),F()}else if(t==="tool"){const s=String(e.callId||""),a=o.find(c=>c.kind==="tool"&&c.callId===s),d=String(e.phase||"start");a?(a.phase=d,d==="update"&&e.output&&(a.output=String(e.output)),d==="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:d}),l.items.set(n,o),F()}else if(t==="approval"){const s=e.approval;if(!s)return;const a=o;for(let d=a.length-1;d>=0;d--){const c=a[d];if(c.kind==="approval"&&c.approval.id===s.id){c.approval=s,s.state!=="pending"&&(c.decided=s.state==="allowed"?"allowed":"denied"),l.items.set(n,a),F();return}}a.push({kind:"approval",approval:s}),l.items.set(n,a),F()}else t==="notice"&&V({kind:"notice",level:String(e.level||"info"),text:String(e.text||"")})}function dt(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 ct(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 A(e=!1){try{const[t,n]=await Promise.all([y("/api/bots"),y("/api/bots/approvals")]);if(l.bots=t,l.approvals=n,oe(),ke(),e&&l.activeId){const o=await y(`/api/bots/${l.activeId}/events?limit=300`);ut(o)}}catch{}}async function pt(){try{l.bots=await y("/api/bots"),oe()}catch{}}function ut(e){if(l.activeId){l.items.set(l.activeId,[]);for(const t of e)Fe(t);de()}}function mt(){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=L("close",'width="14" height="14"'),s.title="Close",s.onclick=()=>ce(),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=d=>{d.target===e&&ce()},document.body.appendChild(e)}function Ee(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 ce(){const e=document.getElementById("bots-modal");e&&(e.hidden=!0)}async function ft(){return l.catalog||(l.catalog=await y("/api/bots/catalog")),l.catalog}async function Qe(){return l.templates=await y("/api/bots/templates"),l.templates}async function ee(){const e=Ee("Bot templates"),[t,n]=await Promise.all([ft(),Qe()]),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=()=>ze(e,t,r);const v=i("button","btn","Copy");v.title="Duplicate this template",v.onclick=()=>{const h=JSON.parse(JSON.stringify(r.manifest));h.name=`${r.manifest.name} copy`,y("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:h})}).then(()=>ee()).catch(E=>alert(E instanceof Error?E.message:String(E)))};const g=i("button","btn danger","Delete");g.onclick=()=>{confirm(`Delete template ${r.manifest.name}?`)&&y(`/api/bots/templates/${r.id}`,{method:"DELETE"}).then(()=>ee())};const b=i("span","bv-template-actions");b.append(f,v,g),p.appendChild(b),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=()=>ze(e,t,null);const d=i("button","btn","Export");d.title="Download templates + library as JSON",d.onclick=()=>{(async()=>{try{const r=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${be()}`}});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()),v=await y("/api/bots/import",{method:"POST",body:JSON.stringify(f)});alert(`Imported ${v.templates} templates, ${v.files} library files (${v.skipped} kept)`),await ee()}catch(f){alert(f instanceof Error?f.message:String(f))}})()},r.click()},s.append(a,d,c),e.appendChild(s)}function Ce(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 d of t){const c=i("label","bv-check"),r=document.createElement("input");r.type="checkbox",r.checked=n.includes(d.id),c.append(r,i("span",void 0,d.label)),d.hint&&(c.title=d.hint),s.appendChild(c),a.push({id:d.id,input:r})}return o.appendChild(s),{element:o,get:()=>a.filter(d=>d.input.checked).map(d=>d.id)}}function ze(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 d=i("textarea","bv-textarea");d.rows=6,d.value=o.system||"",d.placeholder="System prompt for this bot (written to SYSTEM.md)";const c=Ce("Skills",t.skills.map(m=>({id:m.id,label:m.name,hint:m.description})),o.skills||[]),r=Ce("Extensions (Pi builtins + library)",t.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=Ce("Prompt templates",t.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 t.mcp)f.appendChild(new Option(m.name,m.id));o.mcp&&(f.value=t.mcp.find(m=>JSON.stringify(m.servers)===JSON.stringify(o.mcp?.mcpServers))?.id||"");const v=i("div","bv-field");v.appendChild(i("label","bv-label","Tools (allow list; deny always blocks)"));const g=i("div","bv-check-grid"),b=[];for(const m of t.tools){const B=i("label","bv-check"),I=document.createElement("input");I.type="checkbox",I.checked=(o.tools?.allow||[]).includes(m.name)||!o.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(m.name),B.append(I,i("span",void 0,m.name)),g.appendChild(B),b.push({name:m.name,input:I})}v.appendChild(g);const h=i("input","bv-input");h.value=(o.tools?.deny||[]).join(", "),h.placeholder="Always deny (comma separated), e.g. bash, write";const E=i("textarea","bv-textarea");E.rows=2,E.value=(o.packages||[]).join(`
2
+ `),E.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 t.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 j=i("select","bv-input");for(const m of["","off","minimal","low","medium","high","xhigh","max"])j.appendChild(new Option(m||"default",m));o.model?.thinking&&(j.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 R=i("select","bv-input");R.appendChild(new Option("ignore project .pi (recommended)","ignore")),R.appendChild(new Option("inherit project .pi (needs trust)","inherit")),R.value=o.projectResources||"ignore";const J=i("label","bv-check"),x=document.createElement("input");x.type="checkbox",x.checked=!!o.orchestrator,J.append(x,i("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));const k=(m,B)=>{const I=i("div","bv-field");return I.appendChild(i("label","bv-label",m)),I.appendChild(B),I};e.append(k("Name",s),k("Description",a),k("System prompt",d),c.element,r.element,p.element,k("MCP preset",f),v,k("Always deny tools",h),k("Packages",E),k("Model",C),k("Thinking level",j),k("Approval mode",Q),k("Project resources",R),J);const te=i("button","btn primary",n?"Save template":"Create template");te.onclick=async()=>{const[m,B]=C.value.split(`
5
+ `),I=t.mcp.find(S=>S.id===f.value),z={name:s.value.trim()||"bot",description:a.value.trim()||void 0,system:d.value.trim()||void 0,skills:c.get(),extensions:r.get().map(S=>(S.startsWith("builtin:"),S)),prompts:p.get(),packages:E.value.split(`
6
+ `).map(S=>S.trim()).filter(Boolean),mcp:I?{mcpServers:I.servers}:void 0,tools:{allow:b.filter(S=>S.input.checked).map(S=>S.name),deny:h.value.split(",").map(S=>S.trim()).filter(Boolean)},model:m?{provider:m,id:B,thinking:j.value||void 0}:void 0,permissions:{runtimeMode:Q.value},projectResources:R.value==="inherit"?"inherit":"ignore",orchestrator:x.checked||void 0};try{await y("/api/bots/templates",{method:"POST",body:JSON.stringify({id:n?.id,manifest:z})}),ce(),await ee()}catch(S){alert(S instanceof Error?S.message:String(S))}},e.appendChild(te)}async function ht(){return bt("")}async function bt(e){const t=Ee("New bot"),n=await Qe();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 d=e||l.bots[0]?.projectPath||"";a.value=d;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(pe("Template",o),pe("Title",s),pe("Project path",a),pe("Workspace",c));const r=i("button","btn primary","Create bot");r.onclick=async()=>{try{const p=await y("/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})});ce(),await A(!0),await Re(p.id)}catch(p){alert(p instanceof Error?p.message:String(p))}},t.appendChild(r)}function pe(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=Ee("Needs you");if(l.approvals=await y("/api/bots/approvals"),l.approvals.length===0){e.appendChild(i("div","bots-empty","Nothing waiting."));return}for(const t of l.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"),d=i("button","btn danger","Deny"),c=[a,d],r=async(p,f)=>{const v=f.textContent??"";for(const g of c)g.disabled=!0;f.textContent=p?"Allowing\u2026":"Denying\u2026";try{await y(`/api/bots/${t.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:t.id,allow:p,reason:o.value||void 0})}),await A(!0),await Ie()}catch(g){for(const b of c)b.disabled=!1;f.textContent=v,V({kind:"notice",level:"error",text:g instanceof Error?g.message:String(g)})}};a.onclick=()=>void r(!0,a),d.onclick=()=>void r(!1,d),s.append(o,a,d),n.appendChild(s),e.appendChild(n)}}function wt(){window.__botsInited||(window.__botsInited=!0,Ze(),Ye(),window.__openBot=Re,document.addEventListener("click",e=>{const t=e.target;t&&(t.closest(".session-item.bot-item")||t.closest(".session-item")&&l.activeId&&setTimeout(()=>we(),0))},!0),document.addEventListener("click",e=>{const t=e.target;!t||!l.activeId||(t.closest("#mode-files")||t.closest(".file-tree-item")||t.closest(".file-roots-list li"))&&we()}),A(!0),l.pollTimer=window.setInterval(()=>{document.hidden||A()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(l.pollTimer)))}export{wt as initBots,bt as openNewBotForPath};
@@ -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 k}from"node:fs";import h from"node:path";import T 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 y=4,_=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=w(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>y)throw new Error(`nesting depth limit is ${y}`)}let n=t.projectPath||s?.projectPath||process.env.HOME||"/";n==="~"?n=T.homedir():n.startsWith("~/")&&(n=h.join(T.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:w(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)>=_||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 S=a.message?a.message.slice(0,500):"",E=[`Child bot "${r.title}" (${r.id}) needs approval: ${a.title}`,S?`Arguments: ${S}`:"",`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}),k(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=w(e),this.store.saveInstance(s);const n=h.join(this.store.agentDir(t),".runtime-mode");m(h.dirname(n),{recursive:!0,mode:448}),k(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)]}shutdown(){for(const[t,e]of this.runtimes){try{e.kill()}catch{}this.streaming.delete(t)}this.runtimes.clear()}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 w(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 g=null;function X(){if(!g){const c=Number(process.env.PORT)||21e3;g=new q(c)}return g}function Y(){g?.shutdown()}export{q as BotManager,_ as MAX_CONCURRENT_PER_PROJECT,y as MAX_DEPTH,b as ORCHESTRATION_TOOLS,D as READONLY_TOOLS,X as getBotManager,Y as shutdownBots};
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 q}from"./store.js";import{materialize as O}from"./materialize.js";import{PiRpc as B}from"./rpc.js";import{buildCatalog as M,ORCHESTRATION_TOOLS as j,READONLY_TOOLS as D}from"./catalog.js";import{TERMINAL_STATUSES as d}from"./types.js";const y=4,T=8,b=["starting","running","waiting_input","waiting_approval"];function f(u){return Array.isArray(u)?u.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=q();token;apiBase;runtimes=new Map;sockets=new Map;listeners=new Set;approvals=new Map;recent=new Map;streaming=new Set;queues=new Map;constructor(t){this.token=this.store.token,this.apiBase=`http://127.0.0.1:${t}/api/bots`;for(const e of this.store.listInstances()){let s=!1,n=!1;!d.includes(e.status)&&e.status!=="queued"&&(e.status="stale",n=!0,s=!0);const r=S(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>y)throw new Error(`nesting depth limit is ${y}`)}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 c=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:S(t.runtimeMode||e.manifest.permissions?.runtimeMode),projectResources:e.manifest.projectResources||"ignore",status:"queued",sessionFile:h.join(this.store.sessionsDir(i),`${i}.jsonl`),createdAt:c,updatedAt:c,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:c}),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=O(e,t,{apiBase:this.apiBase,token:this.token}),n=e.manifest.binaryPath||"pi",r=new B({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),this.clearQueueState(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),this.queues.delete(t.id),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.clearQueueState(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.queues.set(t,{steering:f(e.steering),followUp:f(e.followUp)}),this.emit(t,{type:"queue",...this.queues.get(t),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"),c=/^Allow (.+?)\?$/.exec(l),a={id:String(e.id||""),botId:t,botTitle:r?.title||t,kind:s==="confirm"?"tool":"question",method:s,title:l,toolName:c?c[1]:void 0,message:typeof e.message=="string"?e.message:void 0,options:Array.isArray(e.options)?e.options.map(String):void 0,state:"pending",createdAt:n};if(this.approvals.has(t)||this.approvals.set(t,new Map),this.approvals.get(t).set(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}),_(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=S(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 c={type:"extension_ui_response",id:e};o.method==="confirm"?c.confirmed=s:o.method==="select"?c.value=s?o.options?.[0]:o.options?.[1]||o.options?.[0]:s?c.value=n||"":c.cancelled=!0,l.send(c),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 c=this.streaming.has(t)||b.includes(r.status);s==="follow_up"?l.streamingBehavior="followUp":(s==="steer"||c)&&(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)]}shutdown(){for(const[t,e]of this.runtimes){try{e.kill()}catch{}this.streaming.delete(t)}this.runtimes.clear(),this.queues.clear()}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),this.clearQueueState(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(o=>o.botId===t)}));for(const o of this.store.readEvents(t,400))e.send(JSON.stringify(o));const n=this.queues.get(t)??{steering:[],followUp:[]};e.send(JSON.stringify({type:"queue",steering:n.steering,followUp:n.followUp,at:new Date().toISOString()})),e.on("close",()=>this.sockets.get(t)?.delete(e));const r={value:!0};e.on("pong",()=>{r.value=!0});const i=setInterval(()=>{if(e.readyState===1){if(!r.value){try{e.terminate()}catch{}clearInterval(i);return}r.value=!1;try{e.ping()}catch{}}},3e4);i.unref?.(),e.on("close",()=>clearInterval(i))}clearQueueState(t){const e=this.queues.get(t);if(!e||e.steering.length===0&&e.followUp.length===0){this.queues.delete(t);return}this.queues.set(t,{steering:[],followUp:[]}),this.emit(t,{type:"queue",steering:[],followUp:[],at:new Date().toISOString()})}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 S(u){return u==="full-access"?"full-access":u==="parent-supervised"?"parent-supervised":"supervised"}function N(u){const t=u.content;return Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&e.type==="text"?String(e.text||""):"").join("").trim():""}function x(u){if(u==null)return"";if(typeof u=="string")return u;try{return JSON.stringify(u).slice(0,4e3)}catch{return String(u)}}let g=null;function z(){if(!g){const u=Number(process.env.PORT)||21e3;g=new P(u)}return g}function X(){g?.shutdown()}export{P as BotManager,T as MAX_CONCURRENT_PER_PROJECT,y as MAX_DEPTH,j as ORCHESTRATION_TOOLS,D as READONLY_TOOLS,z as getBotManager,X as shutdownBots};
@@ -821,12 +821,22 @@ import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as b,newSes
821
821
  background: color-mix(in srgb, currentColor 12%, transparent);
822
822
  }
823
823
  .bv-actions { display: flex; gap: 6px; flex-shrink: 0; align-items: center; }
824
- .bv-inbox-count { margin-left: 5px; font-size: 10.5px; color: var(--panel-accent); }
824
+ /* Inbox icon with a count badge, same geometry as the other header icons. */
825
+ .bv-inbox-btn { position: relative; }
826
+ .bv-inbox-badge {
827
+ position: absolute; top: -5px; right: -5px;
828
+ min-width: 15px; height: 15px; padding: 0 3px;
829
+ border-radius: 999px; background: #e0a23c; color: #1b1b1b;
830
+ font-family: var(--font-sans); font-size: 9.5px; font-weight: 600;
831
+ line-height: 15px; text-align: center;
832
+ box-shadow: 0 0 0 2px var(--page-bg);
833
+ pointer-events: none;
834
+ }
835
+ .bv-inbox-badge[hidden] { display: none; }
825
836
  /* Paused after a restart: bring the bot back in one tap. */
826
837
  .bv-resume { color: var(--panel-accent); border-color: color-mix(in srgb, var(--panel-accent) 45%, var(--panel-border)); }
827
838
  .bv-resume:hover { background: color-mix(in srgb, var(--panel-accent) 10%, transparent); }
828
839
  .bv-resume:disabled { opacity: 0.5; }
829
- .bv-inbox-count:empty { display: none; }
830
840
  .bots-dot { width: 7px; height: 7px; border-radius: 50%; flex: 0 0 auto; background: var(--panel-muted); }
831
841
 
832
842
  .bots-messages {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tmux-weblink",
3
- "version": "3.2.4",
3
+ "version": "3.2.6",
4
4
  "description": "Access your tmux sessions from the browser. A continuation of tmux-web and persalink.",
5
5
  "type": "module",
6
6
  "bin": {