tmux-weblink 3.2.5 → 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 Ge}from"./markdown.js";const ve=Ge(document),l={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,queues:new Map,ws:null,lastSocketAt:0,pollTimer:0,renderQueued:!1};let L=[],M=!0;const Te=200;let Me=Te,Xe=!1,Oe=0;function ge(){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 ${ge()}`,...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 Le(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 _(){ye||(ye=requestAnimationFrame(()=>{ye=0,Ye()}))}let ye=0,oe="";function Ye(){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===oe)return;oe=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(oe==="")return;oe="",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",_),window.visualViewport?.addEventListener("scroll",_),window.addEventListener("resize",_),document.addEventListener("click",_);const Ne=document.querySelector(".sidebar");Ne&&new MutationObserver(_).observe(Ne,{attributes:!0,attributeFilter:["class"]}),window.__syncBotsViewport=_;function ie(){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?`(${e})`:""),window.__botsSnapshot=l.bots,window.__refreshSidebar?.()}function Ze(){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(),bt()}),n?.addEventListener("click",()=>{o(),Ae()})}function et(){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"),Fe(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(Ve[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),it(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=()=>{l.activeId&&(h.disabled=!0,g(`/api/bots/${l.activeId}/resume`,{method:"POST"}).then(()=>A(!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 Ae();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 S=i("div","bv-menu");S.id="bv-more-menu",S.setAttribute("role","menu"),S.hidden=!0;const B=(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},D=B("","check","Allow all",()=>{if(!l.activeId)return;const m=l.approvals.filter(w=>w.botId===l.activeId);Promise.all(m.map(w=>g(`/api/bots/${w.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:w.id,allow:!0})}))).finally(()=>void A(!0))});D.id="bv-allow-all",D.title="Approve every pending request for this bot";const J=B("","refresh","Resume bot",()=>Re(m=>g(`/api/bots/${m}/resume`,{method:"POST"}).then(()=>A(!0)))),te=B("","stop","Stop run",()=>Re(m=>g(`/api/bots/${m}/stop`,{method:"POST"}).then(()=>A(!0)))),Q=B("danger","delete","Delete bot",()=>{l.activeId&&confirm("Delete this bot and its session?")&&g(`/api/bots/${l.activeId}`,{method:"DELETE"}).then(()=>{Se(),A(!0)})});S.append(D,J,te,i("div","bv-menu-sep"),Q);const E=m=>{m&&f(!1),S.hidden=!m,y.setAttribute("aria-expanded",m?"true":"false")};y.onclick=m=>{m.stopPropagation(),E(S.hidden)},document.addEventListener("click",m=>{const w=m.target;w&&(!c.contains(w)&&!p.contains(w)&&f(!1),!y.contains(w)&&!S.contains(w)&&E(!1))}),d.append(c,h,b,y),t.append(n,d);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 j=()=>{M=I.scrollHeight-I.scrollTop-I.clientHeight<48,u.hidden=M};I.addEventListener("scroll",j,{passive:!0}),I.addEventListener("touchmove",()=>{M=!1,u.hidden=I.scrollHeight-I.clientHeight<1},{passive:!0}),I.addEventListener("wheel",()=>{M=!1},{passive:!0});const x=i("div","bots-composer-wrap"),z=i("div","bv-queue");z.id="bv-queue",z.hidden=!0;const C=i("span","bv-queue-text"),ne=i("button","bv-queue-clear","Clear");ne.type="button",ne.title="Drop the queued messages",ne.onclick=()=>{l.activeId&&g(`/api/bots/${l.activeId}/queue/clear`,{method:"POST"}).then(()=>re(),m=>N(m instanceof Error?m.message:String(m)))},z.append(C,ne);const me=i("div","bv-attach-strip");me.id="bv-attach-strip",me.hidden=!0;const fe=i("div","bv-composer-error");fe.id="bv-composer-error",fe.hidden=!0;const he=i("div","bv-suggest");he.id="bv-suggest",he.hidden=!0;const be=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??[]))we(m);O.value=""};const $=i("textarea");$.id="bots-input",$.rows=1,$.placeholder="Message the bot\u2026",$.spellcheck=!1;const Be=window.matchMedia("(pointer: coarse)").matches;Be||($.enterKeyHint="send"),$.onkeydown=m=>{nt(m)||m.key!=="Enter"||m.shiftKey||m.isComposing||Be||m.keyCode===229||(m.preventDefault(),_e())},$.oninput=()=>{N(null),se($),je()},$.onclick=()=>je(),$.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)we(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 _e(),be.append(U,$,K),be.addEventListener("click",m=>{const w=m.target;w?.closest("button")&&R(),!w?.closest("button")&&document.activeElement!==$&&$.focus()}),x.addEventListener("dragover",m=>{m.dataTransfer&&(m.preventDefault(),x.classList.add("drop-target"))}),x.addEventListener("dragleave",()=>x.classList.remove("drop-target")),x.addEventListener("drop",m=>{m.preventDefault(),x.classList.remove("drop-target");const w=Array.from(m.dataTransfer?.files??[]).filter(T=>T.type.startsWith("image/"));for(const T of w)we(T)}),x.append(z,me,he,fe,O,be),e.append(t,I,u,x,p,S),document.querySelector(".main-area")?.appendChild(e),document.getElementById("bots-modal")||ft()}function N(e){const t=document.getElementById("bv-composer-error");t&&(t.textContent=e??"",t.hidden=!e)}function Pe(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=[],qe=4,tt=4*1024*1024;function se(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 ae(){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),ae()},o.append(s,a),e.appendChild(o)}))}async function we(e){if(!e.type.startsWith("image/")){N("Only image attachments are supported.");return}if(P.length>=qe){N(`At most ${qe} images per message.`);return}if(e.size>tt){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),ae()}function re(){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 q=[],G=0,le=null,wt=null;function R(){const e=document.getElementById("bv-suggest");e&&(e.hidden=!0),q=[],le=null}function ke(){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">${De(t.label)}</span><span class="bv-suggest-detail">${De(t.detail)}</span>`,o.onmousedown=s=>s.preventDefault(),o.onclick=()=>He(n),e.appendChild(o)})}}function De(e){return e.replace(/[&<>"]/g,t=>({"&":"&","<":"<",">":">",'"':"""})[t])}async function je(){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){R();return}const s=o[2],a=o[3];if(le={start:t-a.length-1,end:t},s==="/"){const h=l.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,ke();return}const c=Z();if(!c){R();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,ke()}catch{R()}}function He(e){const t=document.getElementById("bots-input"),n=q[e];if(!t||!n||!le)return;const{start:o,end:s}=le;t.value=`${t.value.slice(0,o)}${n.value}${t.value.slice(s)}`;const a=o+n.value.length;R(),t.focus(),t.setSelectionRange(a,a),se(t)}function nt(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,ke(),!0}return e.key==="Enter"||e.key==="Tab"?(e.preventDefault(),He(G),!0):e.key==="Escape"?(e.preventDefault(),R(),!0):!1}async function _e(){const e=document.getElementById("bots-input");if(!e||!l.activeId||Xe||!e.value.trim()&&P.length===0)return;const t=l.activeId,n=e.value.trim()?e.value:"See the attached image",o=P.map(({data:s,mimeType:a})=>({data:s,mimeType:a}));N(null),Pe(!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="",se(e)),R(),P.length=0,ae(),M=!0}catch(s){N(s instanceof Error?s.message:String(s))}finally{Pe(!1)}}function Re(e){l.activeId&&e(l.activeId).catch(t=>V({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)}))}function Se(){l.activeId=null,L=[],M=!0,_();const e=document.getElementById("bots-view");e&&(e.hidden=!0);try{l.ws?.close()}catch{}l.ws=null,ie();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 Je(e){l.activeId=e,L=[],M=!0,l.queues.delete(e),P.length=0,ae(),re(),R();const t=document.getElementById("bots-input");t&&(t.value="",se(t)),N(null);const n=document.getElementById("bv-jump");n&&(n.hidden=!0),window.__collapseSidebar?.(),_(),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"),ie(),ce();const c=Z();c&&c.status==="stale"&&g(`/api/bots/${e}/resume`,{method:"POST"}).then(()=>A(!0)).catch(()=>{}),Ue(e),await A(!0)}function Ue(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(ge())}`);l.ws=n,l.lastSocketAt=Date.now(),n.onmessage=o=>{l.lastSocketAt=Date.now();try{Qe(JSON.parse(String(o.data)))}catch{}},n.onclose=()=>{l.activeId===e&&setTimeout(()=>{l.activeId===e&&Y()},1500)}}let de=0;function Y(){const e=l.activeId;if(!e)return;const t=de?Date.now()-de:0;de=0;const n=l.ws;(!n||n.readyState!==WebSocket.OPEN||t>1e4||Date.now()-l.lastSocketAt>6e4)&&Ue(e),A(!0)}document.addEventListener("visibilitychange",()=>{if(document.hidden){de=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 xe(){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=ot[e.status]??e.status.replace(/_/g," "),n.dataset.status=e.status,n.style.color=Le(e.status),n.title=`${e.status.replace(/_/g," ")} \xB7 ${e.templateId} \xB7 ${e.projectPath}`);const s=document.getElementById("bv-mode-btn");s&&Fe(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=Le(e.status))}const ot={queued:"queued",starting:"starting",running:"running",waiting_input:"waiting",waiting_approval:"approval",completed:"done",failed:"failed",cancelled:"stopped",stale:"stale"},We={supervised:"\u9ED8\u8BA4","parent-supervised":"\u76D1\u7BA1","full-access":"\u5168\u653E\u884C"},Ve={supervised:"shield","parent-supervised":"shield-up","full-access":"shield-alert"};function Fe(e,t){const n=Ve[t]??"shield";e.dataset.mode=t,e.innerHTML=H(n,'width="15" height="15"');const o=`\u5BA1\u6279\u6A21\u5F0F\uFF1A${We[t]??t}`;e.title=`${o}\uFF08\u70B9\u5F00\u53EF\u5207\u6362\uFF09`,e.setAttribute("aria-label",o)}async function it(e){if(l.activeId)try{await g(`/api/bots/${l.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:e})});const t=Z();t&&(t.runtimeMode=e),xe(),V({kind:"notice",level:"info",text:`\u5BA1\u6279\u6A21\u5F0F\uFF1A${We[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()-Oe));window.setTimeout(()=>{l.renderQueued=!1,Oe=performance.now(),ce()},e)}function Ce(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 st(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 Ee(e){if(e.kind==="user"){const t=i("div","bv-msg bv-user");return t.appendChild(ve(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(ve(e.text)),t.appendChild(n),t}return e.kind==="tool"?lt(e):e.kind==="approval"?dt(e):i("div",`bv-notice bv-notice-${e.level}`,e.text)}function at(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(ve(t.text))}function ce(){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-Me),o=n?t.slice(n):t,s=M;if(o.length<L.length||o.some((d,c)=>L[c]?.item!==d))e.textContent="",L=o.map(d=>{const c=Ee(d);return e.appendChild(c),{item:d,snapshot:Ce(d),node:c}});else{for(let d=L.length;d<o.length;d++){const c=o[d],r=Ee(c);e.appendChild(r),L.push({item:c,snapshot:Ce(c),node:r})}for(let d=0;d<o.length;d++){const c=o[d],r=L[d],p=Ce(c);if(st(r.snapshot,p)){if(c.kind==="assistant")at(r.node,c);else{const f=Ee(c);r.node.replaceWith(f),r.node=f}r.snapshot=p}}}rt(e,n),s&&(e.scrollTop=e.scrollHeight)}function rt(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;Me+=Te,L=[],ce(),e.scrollTop=d+(e.scrollHeight-a)},e.prepend(s)}function lt(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 dt(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"),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],h=async(b,k,v)=>{const y=v.textContent??"";for(const S of f)S.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(),A(!0)}catch(S){for(const B of f)B.disabled=!1;v.textContent=y,V({kind:"notice",level:"error",text:S instanceof Error?S.message:String(S)})}};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 Qe(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:[]}),re();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),re()),xe(),ut()}else if(t==="message"){const s=e.message;if(!s||String(s.role||"")!=="assistant")return;const d=ct(s),c=pt(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 ct(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 pt(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([g("/api/bots"),g("/api/bots/approvals")]);if(l.bots=t,l.approvals=n,ie(),xe(),e&&l.activeId){const o=await g(`/api/bots/${l.activeId}/events?limit=300`);mt(o)}}catch{}}async function ut(){try{l.bots=await g("/api/bots"),ie()}catch{}}function mt(e){if(l.activeId){l.items.set(l.activeId,[]);for(const t of e)Qe(t);ce()}}function ft(){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=()=>pe(),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&&pe()},document.body.appendChild(e)}function Ie(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 pe(){const e=document.getElementById("bots-modal");e&&(e.hidden=!0)}async function ht(){return l.catalog||(l.catalog=await g("/api/bots/catalog")),l.catalog}async function ze(){return l.templates=await g("/api/bots/templates"),l.templates}async function ee(){const e=Ie("Bot templates"),[t,n]=await Promise.all([ht(),ze()]),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=()=>Ke(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(()=>ee()).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(()=>ee())};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=()=>Ke(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 ${ge()}`}});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 ee()}catch(f){alert(f instanceof Error?f.message:String(f))}})()},r.click()},s.append(a,d,c),e.appendChild(s)}function $e(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 Ke(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=$e("Skills",t.skills.map(u=>({id:u.id,label:u.name,hint:u.description})),o.skills||[]),r=$e("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=$e("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 j=i("label","bv-check"),x=document.createElement("input");x.type="checkbox",x.checked=(o.tools?.allow||[]).includes(u.name)||!o.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(u.name),j.append(x,i("span",void 0,u.name)),b.appendChild(j),k.push({name:u.name,input:x})}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
|
-
`),
|
|
3
|
-
${
|
|
4
|
-
${o.model.id}`);const
|
|
5
|
-
`),
|
|
6
|
-
`).map(
|
|
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=>({"&":"&","<":"<",">":">",'"':"""})[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};
|
package/dist/lib/pages/shell.js
CHANGED
|
@@ -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
|
-
|
|
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 {
|