tmux-weblink 2.2.49 → 3.0.0

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
- const a={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function D(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function f(t,e){const n=await fetch(t,{...e,headers:{"content-type":"application/json",Authorization:`Bearer ${D()}`,...e?.headers||{}}}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok)throw new Error(s&&s.error||`HTTP ${n.status}`);return s}function o(t,e,n){const i=document.createElement(t);return e&&(i.className=e),n!==void 0&&(i.textContent=n),i}function et(t){return t==="running"?"var(--panel-success)":t==="waiting_approval"||t==="waiting_input"?"#e0a23c":t==="failed"?"var(--panel-danger, #e5534b)":t==="completed"?"var(--panel-accent)":"var(--panel-muted)"}function P(){const t=document.getElementById("bots-view");if(!t)return;const e=window.visualViewport,n=window.matchMedia("(max-width: 640px)").matches,i=!document.querySelector(".sidebar")?.classList.contains("collapsed");if(a.activeId&&e&&n&&!i){const s=document.querySelector(".fixed-header"),l=s?Math.round(s.getBoundingClientRect().height):0;t.style.position="fixed",t.style.top=`${Math.round(e.offsetTop)+l}px`,t.style.left=`${Math.round(e.offsetLeft)}px`,t.style.width=`${Math.round(e.width)}px`,t.style.height=`${Math.max(120,Math.round(e.height)-l)}px`,t.style.right="auto",t.style.bottom="auto"}else t.style.position="",t.style.top="",t.style.left="",t.style.width="",t.style.height="",t.style.right="",t.style.bottom=""}window.visualViewport?.addEventListener("resize",P),window.visualViewport?.addEventListener("scroll",P),window.addEventListener("resize",P),document.addEventListener("click",()=>setTimeout(P,0));function L(){const t=a.approvals.length,e=document.getElementById("bots-inbox-badge");e&&(e.style.display=t?"inline-block":"none",e.textContent=String(t));const n=document.getElementById("bv-inbox-count");n&&(n.textContent=t?`(${t})`:""),window.__botsSnapshot=a.bots,window.__refreshSidebar?.()}function nt(){const t=document.getElementById("set-bot-templates"),e=document.getElementById("set-bot-new"),n=document.getElementById("set-bot-inbox"),i=()=>{document.getElementById("settings-popover")?.classList.remove("open"),document.getElementById("settings-backdrop")?.classList.remove("open")};t?.addEventListener("click",()=>{i(),A()}),e?.addEventListener("click",()=>{i(),mt()}),n?.addEventListener("click",()=>{i(),z()})}function ot(){const t=o("div","bots-view");t.id="bots-view",t.hidden=!0;const e=o("div","bots-view-head"),n=o("div","bv-title"),i=o("span","bots-dot");i.id="bv-dot";const s=o("span","bv-title-text");s.id="bv-title";const l=o("span","bv-status");l.id="bv-status",n.append(i,s,l);const d=o("div","bv-actions"),p=o("div","bv-mode"),r=o("button","bv-mode-btn");r.id="bv-mode-btn",r.type="button",r.title="\u5BA1\u6279\u6A21\u5F0F\uFF08\u70B9\u5F00\u770B\u8BF4\u660E\uFF09";const u=o("div","bv-mode-menu");u.id="bv-mode-menu",u.hidden=!0;for(const[b,h,j]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 c=o("button");c.dataset.mode=b,c.innerHTML=`<b>${h}</b><span>${j}</span>`,c.onclick=()=>{u.hidden=!0,it(b)},u.appendChild(c)}r.onclick=b=>{b.stopPropagation(),u.hidden=!u.hidden},p.append(r,u),document.addEventListener("click",b=>{p.contains(b.target)||(u.hidden=!0)});const m=o("button","btn","Allow all");m.id="bv-allow-all",m.title="Approve every pending request for this bot",m.onclick=()=>{if(!a.activeId)return;const b=a.approvals.filter(h=>h.botId===a.activeId);Promise.all(b.map(h=>f(`/api/bots/${h.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:h.id,allow:!0})}))).finally(()=>void S(!0))};const v=o("button","btn","Needs you "),C=o("span");C.id="bv-inbox-count",v.appendChild(C),v.onclick=()=>void z();const I=o("button","btn","Resume");I.onclick=()=>void F(b=>f(`/api/bots/${b}/resume`,{method:"POST"}).then(()=>S(!0)));const x=o("button","btn danger","Stop");x.onclick=()=>void F(b=>f(`/api/bots/${b}/stop`,{method:"POST"}).then(()=>S(!0)));const y=o("button","btn","Delete");y.onclick=()=>{a.activeId&&confirm("Delete this bot and its session?")&&f(`/api/bots/${a.activeId}`,{method:"DELETE"}).then(()=>{R(),S(!0)})};const E=o("button","btn","\u2715");E.onclick=()=>R(),d.append(p,m,v,I,x,y,E),e.append(n,d);const B=o("div","bots-messages");B.id="bots-messages";const O=o("div","bots-composer"),w=o("textarea");w.id="bots-input",w.rows=1,w.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",w.onkeydown=b=>{b.key==="Enter"&&!b.shiftKey&&(b.preventDefault(),Q())};const $=o("button","btn primary");$.title="Send",$.setAttribute("aria-label","Send"),$.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>',$.onclick=()=>void Q(),O.append(w,$),t.append(e,B,O),document.querySelector(".main-area")?.appendChild(t),document.getElementById("bots-modal")||pt()}async function Q(){const t=document.getElementById("bots-input");if(!t||!a.activeId||!t.value.trim())return;const e=t.value;t.value="";try{await f(`/api/bots/${a.activeId}/input`,{method:"POST",body:JSON.stringify({text:e})})}catch(n){T({kind:"notice",level:"error",text:n instanceof Error?n.message:String(n)})}}function F(t){a.activeId&&t(a.activeId).catch(e=>T({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)}))}function R(){a.activeId=null,P();const t=document.getElementById("bots-view");t&&(t.hidden=!0);try{a.ws?.close()}catch{}a.ws=null,L();const e=document.getElementById("terminal-container"),n=document.getElementById("main-placeholder"),i=!!document.querySelector(".session-item.active:not(.bot-item)");e&&i?(e.style.display="",n&&(n.style.display="none")):n&&(n.style.display="")}async function G(t){a.activeId=t,window.__collapseSidebar?.(),P(),a.items.set(t,[]);const e=document.getElementById("bots-view");e&&(e.hidden=!1);const n=document.getElementById("main-placeholder");n&&(n.style.display="none");const i=document.getElementById("terminal-container");i&&(i.style.display="none");const s=document.getElementById("file-editor");s&&(s.style.display="none"),L(),W();try{a.ws?.close()}catch{}const l=location.protocol==="https:"?"wss:":"ws:",d=new WebSocket(`${l}//${location.host}/ws/bots/${encodeURIComponent(t)}?token=${encodeURIComponent(D())}`);a.ws=d,d.onmessage=p=>{try{Y(JSON.parse(String(p.data)))}catch{}},d.onclose=()=>{a.activeId===t&&setTimeout(()=>{a.activeId===t&&S(!0)},1500)},await S(!0)}function q(){return a.bots.find(t=>t.id===a.activeId)||null}function H(){const t=q();if(!t)return;const e=document.getElementById("bv-title"),n=document.getElementById("bv-status"),i=document.getElementById("bv-dot");e&&(e.textContent=t.title),n&&(n.textContent=`${t.status.replace(/_/g," ")} \xB7 ${t.templateId} \xB7 ${t.projectPath}`);const s=document.getElementById("bv-mode-btn");s&&t.runtimeMode&&(s.textContent=`${K[t.runtimeMode]||t.runtimeMode} \u25BE`);for(const p of document.querySelectorAll("#bv-mode-menu button"))p.classList.toggle("active",p.dataset.mode===t.runtimeMode);const l=document.getElementById("bv-allow-all"),d=a.approvals.filter(p=>p.botId===t.id).length;l&&(l.hidden=d===0,l.textContent=`Allow all (${d})`),i&&(i.style.background=et(t.status))}const K={supervised:"\u9ED8\u8BA4","parent-supervised":"\u76D1\u7BA1","full-access":"\u5168\u653E\u884C"};async function it(t){if(a.activeId)try{await f(`/api/bots/${a.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:t})});const e=q();e&&(e.runtimeMode=t),H(),T({kind:"notice",level:"info",text:`\u5BA1\u6279\u6A21\u5F0F\uFF1A${K[t]||t}`})}catch(e){T({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)})}}function T(t,e=a.activeId){if(!e)return;const n=a.items.get(e)||[];n.push(t),a.items.set(e,n),e===a.activeId&&M()}function M(){a.renderQueued||(a.renderQueued=!0,requestAnimationFrame(()=>{a.renderQueued=!1,W()}))}function W(){const t=document.getElementById("bots-messages");if(!t||!a.activeId)return;const e=a.items.get(a.activeId)||[];t.textContent="";let n=null;for(const i of e)if(i.kind==="user"){const s=o("div","bv-msg bv-user");s.textContent=i.text,t.appendChild(s),n=null}else if(i.kind==="assistant"){const s=o("div","bv-msg bv-assistant");if(i.thinking){const d=o("details","bv-thinking");d.appendChild(o("summary",void 0,"thinking")),d.appendChild(o("div",void 0,i.thinking)),s.appendChild(d)}const l=o("div","bv-text");l.textContent=i.text,s.appendChild(l),t.appendChild(s),n=l}else if(i.kind==="tool")t.appendChild(st(i)),n=null;else if(i.kind==="approval")t.appendChild(at(i)),n=null;else if(i.kind==="notice"){const s=o("div",`bv-notice bv-notice-${i.level}`,i.text);t.appendChild(s)}n&&(n.scrollTop=n.scrollHeight),t.scrollTop=t.scrollHeight}function st(t){const e=o("details","bv-tool");e.open=t.phase!=="end"||!!t.isError;const n=o("summary"),i=o("span","bv-tool-name",t.name);if(n.appendChild(i),t.phase!=="end"&&n.appendChild(o("span","bv-tool-phase",t.phase)),t.isError&&n.appendChild(o("span","bv-tool-error","error")),typeof t.durationMs=="number"&&n.appendChild(o("span","bv-tool-meta",`${Math.round(t.durationMs)}ms`)),e.appendChild(n),t.args!==void 0){const s=o("pre","bv-pre");s.textContent=typeof t.args=="string"?t.args:JSON.stringify(t.args,null,2),e.appendChild(s)}if(t.output){const s=o("pre","bv-pre bv-output");s.textContent=t.output,e.appendChild(s)}return e}function at(t){const e=o("div","bv-approval"),n=t.approval;if(e.appendChild(o("div","bv-approval-title",n.title)),n.message&&e.appendChild(o("pre","bv-pre",n.message)),t.decided)return e.appendChild(o("div","bv-approval-decided",t.decided==="allowed"?"Allowed":"Denied")),e;const i=o("input","bv-reason");i.placeholder="reason (optional)";const s=o("div","bv-approval-actions"),l=o("button","btn primary","Allow"),d=o("button","btn",n.method==="confirm"&&/^Allow (.+?)\?$/.test(n.title)?`Always allow ${/^Allow (.+?)\?$/.exec(n.title)?.[1]}`:"Always allow");d.hidden=n.method!=="confirm";const p=o("button","btn danger","Deny"),r=async(u,m=!1)=>{try{await f(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:u,always:m,reason:i.value||void 0})}),t.decided=u?"allowed":"denied",M(),S(!0)}catch(v){T({kind:"notice",level:"error",text:v instanceof Error?v.message:String(v)})}};return l.onclick=()=>void r(!0),d.onclick=()=>void r(!0,!0),p.onclick=()=>void r(!1),s.append(i,l,d,p),e.appendChild(s),e}function Y(t){const e=String(t.type||""),n=a.activeId;if(!n)return;const i=a.items.get(n)||[];if(e==="snapshot")a.items.set(n,[]);else if(e==="user")T({kind:"user",text:String(t.text||"")});else if(e==="status"){const s=q();s&&(s.status=String(t.status||s.status)),H(),rt()}else if(e==="message"){const s=t.message;if(!s||String(s.role||"")!=="assistant")return;const d=dt(s),p=lt(s),r=i[i.length-1];r&&r.kind==="assistant"?(r.text=d||r.text,r.thinking=p||r.thinking):i.push({kind:"assistant",text:d,thinking:p}),a.items.set(n,i),M()}else if(e==="delta"){const s=String(t.kind||""),l=String(t.delta||"");let d=i[i.length-1];(!d||d.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),d=i[i.length-1]),d.kind==="assistant"&&(s==="text"?d.text+=l:s==="thinking"&&(d.thinking+=l)),a.items.set(n,i),M()}else if(e==="tool"){const s=String(t.callId||""),l=i.find(p=>p.kind==="tool"&&p.callId===s),d=String(t.phase||"start");l?(l.phase=d,d==="update"&&t.output&&(l.output=String(t.output)),d==="end"&&(t.output&&(l.output=String(t.output)),l.isError=t.isError===!0,typeof t.durationMs=="number"&&(l.durationMs=t.durationMs))):i.push({kind:"tool",callId:s,name:String(t.name||"tool"),args:t.args,output:t.output?String(t.output):void 0,isError:t.isError===!0,durationMs:typeof t.durationMs=="number"?t.durationMs:void 0,phase:d}),a.items.set(n,i),M()}else if(e==="approval"){const s=t.approval;if(!s)return;const l=i;for(let d=l.length-1;d>=0;d--){const p=l[d];if(p.kind==="approval"&&p.approval.id===s.id){p.approval=s,s.state!=="pending"&&(p.decided=s.state==="allowed"?"allowed":"denied"),a.items.set(n,l),M();return}}l.push({kind:"approval",approval:s}),a.items.set(n,l),M()}else e==="notice"&&T({kind:"notice",level:String(t.level||"info"),text:String(t.text||"")})}function dt(t){const e=t.content;return Array.isArray(e)?e.map(n=>n&&typeof n=="object"&&n.type==="text"?String(n.text||""):"").join(""):String(t.text||"")}function lt(t){const e=t.content;return Array.isArray(e)?e.map(n=>n&&typeof n=="object"&&n.type==="thinking"?String(n.thinking||""):"").join(""):""}async function S(t=!1){try{const[e,n]=await Promise.all([f("/api/bots"),f("/api/bots/approvals")]);if(a.bots=e,a.approvals=n,L(),H(),t&&a.activeId){const i=await f(`/api/bots/${a.activeId}/events?limit=300`);ct(i)}}catch{}}async function rt(){try{a.bots=await f("/api/bots"),L()}catch{}}function ct(t){if(a.activeId){a.items.set(a.activeId,[]);for(const e of t)Y(e);W()}}function pt(){const t=o("div","bots-modal");t.id="bots-modal",t.hidden=!0;const e=o("div","bots-modal-card"),n=o("div","bots-modal-head"),i=o("span");i.id="bots-modal-title";const s=o("button","btn","\u2715");s.onclick=()=>J(),n.append(i,s);const l=o("div","bots-modal-body");l.id="bots-modal-body",e.append(n,l),t.appendChild(e),t.onclick=d=>{d.target===t&&J()},document.body.appendChild(t)}function U(t){const e=document.getElementById("bots-modal"),n=document.getElementById("bots-modal-title"),i=document.getElementById("bots-modal-body");if(!e||!i)throw new Error("modal missing");return n&&(n.textContent=t),i.textContent="",e.hidden=!1,i}function J(){const t=document.getElementById("bots-modal");t&&(t.hidden=!0)}async function ut(){return a.catalog||(a.catalog=await f("/api/bots/catalog")),a.catalog}async function X(){return a.templates=await f("/api/bots/templates"),a.templates}async function A(){const t=U("Bot templates"),[e,n]=await Promise.all([ut(),X()]),i=o("div","bv-template-list");for(const r of n){const u=o("div","bv-template-row");u.appendChild(o("span","bv-template-name",r.manifest.name)),u.appendChild(o("span","bv-template-desc",r.manifest.description||""));const m=o("button","btn","Edit");m.onclick=()=>Z(t,e,r);const v=o("button","btn","Copy");v.title="Duplicate this template",v.onclick=()=>{const x=JSON.parse(JSON.stringify(r.manifest));x.name=`${r.manifest.name} copy`,f("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:x})}).then(()=>A()).catch(y=>alert(y instanceof Error?y.message:String(y)))};const C=o("button","btn danger","Delete");C.onclick=()=>{confirm(`Delete template ${r.manifest.name}?`)&&f(`/api/bots/templates/${r.id}`,{method:"DELETE"}).then(()=>A())};const I=o("span","bv-template-actions");I.append(m,v,C),u.appendChild(I),i.appendChild(u)}n.length===0&&i.appendChild(o("div","bots-empty","No templates yet")),t.appendChild(i);const s=o("div","bv-template-actions"),l=o("button","btn primary","New template");l.onclick=()=>Z(t,e,null);const d=o("button","btn","Export");d.title="Download templates + library as JSON",d.onclick=()=>{(async()=>{try{const r=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${D()}`}});if(!r.ok)throw new Error(`HTTP ${r.status}`);const u=await r.blob(),m=document.createElement("a");m.href=URL.createObjectURL(u),m.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,m.click(),setTimeout(()=>URL.revokeObjectURL(m.href),2e3)}catch(r){alert(r instanceof Error?r.message:String(r))}})()};const p=o("button","btn","Import");p.title="Restore templates from a JSON bundle",p.onclick=()=>{const r=document.createElement("input");r.type="file",r.accept="application/json,.json",r.onchange=()=>{const u=r.files?.[0];u&&(async()=>{try{const m=JSON.parse(await u.text()),v=await f("/api/bots/import",{method:"POST",body:JSON.stringify(m)});alert(`Imported ${v.templates} templates, ${v.files} library files (${v.skipped} kept)`),await A()}catch(m){alert(m instanceof Error?m.message:String(m))}})()},r.click()},s.append(l,d,p),t.appendChild(s)}function V(t,e,n){const i=o("div","bv-field");i.appendChild(o("label","bv-label",t));const s=o("div","bv-check-grid"),l=[];for(const d of e){const p=o("label","bv-check"),r=document.createElement("input");r.type="checkbox",r.checked=n.includes(d.id),p.append(r,o("span",void 0,d.label)),d.hint&&(p.title=d.hint),s.appendChild(p),l.push({id:d.id,input:r})}return i.appendChild(s),{element:i,get:()=>l.filter(d=>d.input.checked).map(d=>d.id)}}function Z(t,e,n){t.textContent="";const i=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},s=o("input","bv-input");s.value=i.name,s.placeholder="Template name";const l=o("input","bv-input");l.value=i.description||"",l.placeholder="One line description";const d=o("textarea","bv-textarea");d.rows=6,d.value=i.system||"",d.placeholder="System prompt for this bot (written to SYSTEM.md)";const p=V("Skills",e.skills.map(c=>({id:c.id,label:c.name,hint:c.description})),i.skills||[]),r=V("Extensions (Pi builtins + library)",e.extensions.map(c=>({id:c.id,label:`${c.name}${c.kind==="builtin"?" (builtin)":""}`,hint:c.description})),(i.extensions||[]).map(c=>c.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),u=V("Prompt templates",e.prompts.map(c=>({id:c.id,label:c.name})),i.prompts||[]),m=o("select","bv-input");m.appendChild(new Option("none",""));for(const c of e.mcp)m.appendChild(new Option(c.name,c.id));i.mcp&&(m.value=e.mcp.find(c=>JSON.stringify(c.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");const v=o("div","bv-field");v.appendChild(o("label","bv-label","Tools (allow list; deny always blocks)"));const C=o("div","bv-check-grid"),I=[];for(const c of e.tools){const N=o("label","bv-check"),k=document.createElement("input");k.type="checkbox",k.checked=(i.tools?.allow||[]).includes(c.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(c.name),N.append(k,o("span",void 0,c.name)),C.appendChild(N),I.push({name:c.name,input:k})}v.appendChild(C);const x=o("input","bv-input");x.value=(i.tools?.deny||[]).join(", "),x.placeholder="Always deny (comma separated), e.g. bash, write";const y=o("textarea","bv-textarea");y.rows=2,y.value=(i.packages||[]).join(`
2
- `),y.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";const E=o("select","bv-input");E.appendChild(new Option("default (Pi settings)",""));for(const c of e.models)E.appendChild(new Option(`${c.provider}/${c.model}`,`${c.provider}
3
- ${c.model}`));i.model?.provider&&i.model?.id&&(E.value=`${i.model.provider}
4
- ${i.model.id}`);const B=o("select","bv-input");for(const c of["","off","minimal","low","medium","high","xhigh","max"])B.appendChild(new Option(c||"default",c));i.model?.thinking&&(B.value=i.model.thinking);const O=o("select","bv-input");for(const c of["supervised","auto-accept-edits","full-access"])O.appendChild(new Option(c,c));O.value=i.permissions?.runtimeMode||"supervised";const w=o("select","bv-input");w.appendChild(new Option("ignore project .pi (recommended)","ignore")),w.appendChild(new Option("inherit project .pi (needs trust)","inherit")),w.value=i.projectResources||"ignore";const $=o("label","bv-check"),b=document.createElement("input");b.type="checkbox",b.checked=!!i.orchestrator,$.append(b,o("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));const h=(c,N)=>{const k=o("div","bv-field");return k.appendChild(o("label","bv-label",c)),k.appendChild(N),k};t.append(h("Name",s),h("Description",l),h("System prompt",d),p.element,r.element,u.element,h("MCP preset",m),v,h("Always deny tools",x),h("Packages",y),h("Model",E),h("Thinking level",B),h("Approval mode",O),h("Project resources",w),$);const j=o("button","btn primary",n?"Save template":"Create template");j.onclick=async()=>{const[c,N]=E.value.split(`
5
- `),k=e.mcp.find(g=>g.id===m.value),tt={name:s.value.trim()||"bot",description:l.value.trim()||void 0,system:d.value.trim()||void 0,skills:p.get(),extensions:r.get().map(g=>(g.startsWith("builtin:"),g)),prompts:u.get(),packages:y.value.split(`
6
- `).map(g=>g.trim()).filter(Boolean),mcp:k?{mcpServers:k.servers}:void 0,tools:{allow:I.filter(g=>g.input.checked).map(g=>g.name),deny:x.value.split(",").map(g=>g.trim()).filter(Boolean)},model:c?{provider:c,id:N,thinking:B.value||void 0}:void 0,permissions:{runtimeMode:O.value},projectResources:w.value==="inherit"?"inherit":"ignore",orchestrator:b.checked||void 0};try{await f("/api/bots/templates",{method:"POST",body:JSON.stringify({id:n?.id,manifest:tt})}),J(),await A()}catch(g){alert(g instanceof Error?g.message:String(g))}},t.appendChild(j)}async function mt(){return bt("")}async function bt(t){const e=U("New bot"),n=await X();if(n.length===0){e.appendChild(o("div","bots-empty","Create a template first (\u2699)."));return}const i=o("select","bv-input");for(const u of n)i.appendChild(new Option(u.manifest.name,u.id));const s=o("input","bv-input");s.placeholder="Title (defaults to template name)";const l=o("input","bv-input");l.placeholder="/path/to/project";const d=t||a.bots[0]?.projectPath||"";l.value=d;const p=o("select","bv-input");p.appendChild(new Option("shared \u2014 run in the project folder","shared")),p.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),e.append(_("Template",i),_("Title",s),_("Project path",l),_("Workspace",p));const r=o("button","btn primary","Create bot");r.onclick=async()=>{try{const u=await f("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:s.value.trim()||void 0,projectPath:l.value.trim()||void 0,isolation:p.value})});J(),await S(!0),await G(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},e.appendChild(r)}function _(t,e){const n=o("div","bv-field");return n.appendChild(o("label","bv-label",t)),n.appendChild(e),n}async function z(){const t=U("Needs you");if(a.approvals=await f("/api/bots/approvals"),a.approvals.length===0){t.appendChild(o("div","bots-empty","Nothing waiting."));return}for(const e of a.approvals){const n=o("div","bv-approval");n.appendChild(o("div","bv-approval-title",`${e.botTitle}: ${e.title}`)),e.message&&n.appendChild(o("pre","bv-pre",e.message));const i=o("input","bv-reason");i.placeholder="reason (optional)";const s=o("div","bv-approval-actions"),l=o("button","btn primary","Allow"),d=o("button","btn danger","Deny"),p=async r=>{await f(`/api/bots/${e.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:e.id,allow:r,reason:i.value||void 0})}),await S(!0),await z()};l.onclick=()=>void p(!0),d.onclick=()=>void p(!1),s.append(i,l,d),n.appendChild(s),t.appendChild(n)}}function ft(){window.__botsInited||(window.__botsInited=!0,ot(),nt(),window.__openBot=G,document.addEventListener("click",t=>{const e=t.target;e&&(e.closest(".session-item.bot-item")||e.closest(".session-item")&&a.activeId&&setTimeout(()=>R(),0))},!0),S(!0),a.pollTimer=window.setInterval(()=>{document.hidden||S()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(a.pollTimer)))}export{ft as initBots,bt as openNewBotForPath};
1
+ import{icon as D}from"../lib/icons.js";import{createMarkdownRenderer as ht}from"./markdown.js";const F=ht(document),d={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};let L=[],B=!0,bt=!1,it=0;function U(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function b(t,e){const o=await fetch(t,{...e,headers:{"content-type":"application/json",Authorization:`Bearer ${U()}`,...e?.headers||{}}}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok)throw new Error(s&&s.error||`HTTP ${o.status}`);return s}function n(t,e,o){const i=document.createElement(t);return e&&(i.className=e),o!==void 0&&(i.textContent=o),i}function ft(t){return t==="running"?"var(--panel-success)":t==="waiting_approval"||t==="waiting_input"?"#e0a23c":t==="failed"?"var(--panel-danger, #e5534b)":t==="completed"?"var(--panel-accent)":"var(--panel-muted)"}function N(){z||(z=requestAnimationFrame(()=>{z=0,vt()}))}let z=0,R="";function vt(){const t=document.getElementById("bots-view");if(!t)return;const e=window.visualViewport,o=window.matchMedia("(max-width: 640px)").matches,i=!document.querySelector(".sidebar")?.classList.contains("collapsed");if(d.activeId&&e&&o&&!i){const s=document.querySelector(".fixed-header"),r=s?Math.round(s.getBoundingClientRect().height):0,a=Math.round(e.offsetTop)+r,c=Math.round(e.offsetLeft),l=Math.round(e.width),u=Math.max(120,Math.round(e.height)-r),h=`fixed|${a}|${c}|${l}|${u}`;if(h===R)return;R=h,t.style.position="fixed",t.style.top=`${a}px`,t.style.left=`${c}px`,t.style.width=`${l}px`,t.style.height=`${u}px`,t.style.right="auto",t.style.bottom="auto"}else{if(R==="")return;R="",t.style.position="",t.style.top="",t.style.left="",t.style.width="",t.style.height="",t.style.right="",t.style.bottom=""}}window.visualViewport?.addEventListener("resize",N),window.visualViewport?.addEventListener("scroll",N),window.addEventListener("resize",N),document.addEventListener("click",N);const st=document.querySelector(".sidebar");st&&new MutationObserver(N).observe(st,{attributes:!0,attributeFilter:["class"]}),window.__syncBotsViewport=N;function q(){const t=d.approvals.length,e=document.getElementById("bots-inbox-badge");e&&(e.style.display=t?"inline-block":"none",e.textContent=String(t));const o=document.getElementById("bv-inbox-count");o&&(o.textContent=t?`(${t})`:""),window.__botsSnapshot=d.bots,window.__refreshSidebar?.()}function gt(){const t=document.getElementById("set-bot-templates"),e=document.getElementById("set-bot-new"),o=document.getElementById("set-bot-inbox"),i=()=>{document.getElementById("settings-popover")?.classList.remove("open"),document.getElementById("settings-backdrop")?.classList.remove("open")};t?.addEventListener("click",()=>{i(),H()}),e?.addEventListener("click",()=>{i(),Tt()}),o?.addEventListener("click",()=>{i(),ot()})}function yt(){const t=n("div","bots-view");t.id="bots-view",t.hidden=!0;const e=n("div","bots-view-head"),o=n("div","bv-title"),i=n("span","bots-dot");i.id="bv-dot";const s=n("span","bv-title-text");s.id="bv-title";const r=n("span","bv-status");r.id="bv-status",o.append(i,s,r);const a=n("div","bv-actions"),c=n("div","bv-mode"),l=n("button","bv-mode-btn");l.id="bv-mode-btn",l.type="button",l.title="\u5BA1\u6279\u6A21\u5F0F\uFF08\u70B9\u5F00\u770B\u8BF4\u660E\uFF09",l.innerHTML=`<span id="bv-mode-label"></span>${D("chevron-down",'width="12" height="12"')}`;const u=n("div","bv-mode-menu");u.id="bv-mode-menu",u.hidden=!0;for(const[m,$,v]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 _=n("button");_.dataset.mode=m,_.innerHTML=`<b>${$}</b><span>${v}</span>`,_.onclick=()=>{u.hidden=!0,wt(m)},u.appendChild(_)}l.onclick=m=>{m.stopPropagation(),u.hidden=!u.hidden},c.append(l,u),document.addEventListener("click",m=>{c.contains(m.target)||(u.hidden=!0)});const h=n("button","btn","Allow all");h.id="bv-allow-all",h.title="Approve every pending request for this bot",h.onclick=()=>{if(!d.activeId)return;const m=d.approvals.filter($=>$.botId===d.activeId);Promise.all(m.map($=>b(`/api/bots/${$.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:$.id,allow:!0})}))).finally(()=>void C(!0))};const f=n("button","btn","Needs you "),O=n("span");O.id="bv-inbox-count",f.appendChild(O),f.onclick=()=>void ot();const M=n("button","btn","Resume");M.onclick=()=>void dt(m=>b(`/api/bots/${m}/resume`,{method:"POST"}).then(()=>C(!0)));const I=n("button","btn danger","Stop");I.onclick=()=>void dt(m=>b(`/api/bots/${m}/stop`,{method:"POST"}).then(()=>C(!0)));const x=n("button","btn","Delete");x.onclick=()=>{d.activeId&&confirm("Delete this bot and its session?")&&b(`/api/bots/${d.activeId}`,{method:"DELETE"}).then(()=>{K(),C(!0)})};const E=n("button","btn");E.innerHTML=D("close",'width="14" height="14"'),E.title="Close bot view",E.onclick=()=>K(),a.append(c,h,f,M,I,x,E),e.append(o,a);const g=n("div","bots-messages");g.id="bots-messages";const y=n("button","bv-jump");y.type="button",y.id="bv-jump",y.innerHTML=`${D("chevron-down",'width="14" height="14"')}<span>Latest</span>`,y.title="Jump to the latest message",y.hidden=!0,y.onclick=()=>{B=!0,g.scrollTop=g.scrollHeight,y.hidden=!0};const j=()=>{B=g.scrollHeight-g.scrollTop-g.clientHeight<48,y.hidden=B};g.addEventListener("scroll",j,{passive:!0}),g.addEventListener("touchmove",()=>{B=!1,y.hidden=g.scrollHeight-g.clientHeight<1},{passive:!0}),g.addEventListener("wheel",()=>{B=!1},{passive:!0});const J=n("div","bots-composer-wrap"),T=n("div","bv-composer-error");T.id="bv-composer-error",T.hidden=!0;const w=n("div","bots-composer"),k=n("textarea");k.id="bots-input",k.rows=1,k.placeholder="Message the bot\u2026",k.spellcheck=!1;const p=window.matchMedia("(pointer: coarse)").matches;p||(k.enterKeyHint="send"),k.onkeydown=m=>{m.key!=="Enter"||m.shiftKey||m.isComposing||p||m.keyCode===229||(m.preventDefault(),rt())},k.oninput=()=>Q(null);const S=n("button","btn primary");S.id="bv-send",S.title="Send",S.setAttribute("aria-label","Send"),S.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>',S.onclick=()=>void rt(),w.append(k,S),w.addEventListener("click",m=>{m.target?.closest("button")||document.activeElement!==k&&k.focus()}),J.append(T,w),t.append(e,g,y,J),document.querySelector(".main-area")?.appendChild(t),document.getElementById("bots-modal")||Ot()}function Q(t){const e=document.getElementById("bv-composer-error");e&&(e.textContent=t??"",e.hidden=!t)}function at(t){const e=document.getElementById("bv-send");e&&(e.disabled=t,e.setAttribute("aria-busy",t?"true":"false"),e.title=t?"Sending\u2026":"Send")}async function rt(){const t=document.getElementById("bots-input");if(!t||!d.activeId||bt||!t.value.trim())return;const e=d.activeId,o=t.value;Q(null),at(!0);try{await b(`/api/bots/${e}/input`,{method:"POST",body:JSON.stringify({text:o})}),t.value===o&&(t.value=""),B=!0}catch(i){Q(i instanceof Error?i.message:String(i))}finally{at(!1)}}function dt(t){d.activeId&&t(d.activeId).catch(e=>P({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)}))}function K(){d.activeId=null,L=[],B=!0,N();const t=document.getElementById("bots-view");t&&(t.hidden=!0);try{d.ws?.close()}catch{}d.ws=null,q();const e=document.getElementById("terminal-container"),o=document.getElementById("main-placeholder"),i=!!document.querySelector(".session-item.active:not(.bot-item)");e&&i?(e.style.display="",o&&(o.style.display="none")):o&&(o.style.display="")}async function lt(t){d.activeId=t,L=[],B=!0;const e=document.getElementById("bv-jump");e&&(e.hidden=!0),window.__collapseSidebar?.(),N(),d.items.set(t,[]);const o=document.getElementById("bots-view");o&&(o.hidden=!1);const i=document.getElementById("main-placeholder");i&&(i.style.display="none");const s=document.getElementById("terminal-container");s&&(s.style.display="none");const r=document.getElementById("file-editor");r&&(r.style.display="none"),q(),tt();try{d.ws?.close()}catch{}const a=location.protocol==="https:"?"wss:":"ws:",c=new WebSocket(`${a}//${location.host}/ws/bots/${encodeURIComponent(t)}?token=${encodeURIComponent(U())}`);d.ws=c,c.onmessage=l=>{try{pt(JSON.parse(String(l.data)))}catch{}},c.onclose=()=>{d.activeId===t&&setTimeout(()=>{d.activeId===t&&C(!0)},1500)},await C(!0)}function G(){return d.bots.find(t=>t.id===d.activeId)||null}function Y(){const t=G();if(!t)return;const e=document.getElementById("bv-title"),o=document.getElementById("bv-status"),i=document.getElementById("bv-dot");e&&(e.textContent=t.title),o&&(o.textContent=`${t.status.replace(/_/g," ")} \xB7 ${t.templateId} \xB7 ${t.projectPath}`);const s=document.getElementById("bv-mode-label");s&&t.runtimeMode&&(s.textContent=ct[t.runtimeMode]||t.runtimeMode);for(const c of document.querySelectorAll("#bv-mode-menu button"))c.classList.toggle("active",c.dataset.mode===t.runtimeMode);const r=document.getElementById("bv-allow-all"),a=d.approvals.filter(c=>c.botId===t.id).length;r&&(r.hidden=a===0,r.textContent=`Allow all (${a})`),i&&(i.style.background=ft(t.status))}const ct={supervised:"\u9ED8\u8BA4","parent-supervised":"\u76D1\u7BA1","full-access":"\u5168\u653E\u884C"};async function wt(t){if(d.activeId)try{await b(`/api/bots/${d.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:t})});const e=G();e&&(e.runtimeMode=t),Y(),P({kind:"notice",level:"info",text:`\u5BA1\u6279\u6A21\u5F0F\uFF1A${ct[t]||t}`})}catch(e){P({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)})}}function P(t,e=d.activeId){if(!e)return;const o=d.items.get(e)||[];o.push(t),d.items.set(e,o),e===d.activeId&&A()}function A(){if(d.renderQueued)return;d.renderQueued=!0;const t=Math.max(0,60-(performance.now()-it));window.setTimeout(()=>{d.renderQueued=!1,it=performance.now(),tt()},t)}function X(t){switch(t.kind){case"assistant":return{text:t.text,thinking:t.thinking};case"tool":return{phase:t.phase,output:t.output,error:t.isError,durationMs:t.durationMs};case"approval":return{decided:t.decided,approvalState:t.approval.state};default:return{}}}function kt(t,e){return t.text!==e.text||t.thinking!==e.thinking||t.phase!==e.phase||t.output!==e.output||t.error!==e.error||t.durationMs!==e.durationMs||t.decided!==e.decided||t.approvalState!==e.approvalState}function Z(t){if(t.kind==="user"){const e=n("div","bv-msg bv-user");return e.appendChild(F(t.text)),e}if(t.kind==="assistant"){const e=n("div","bv-msg bv-assistant");if(t.thinking){const i=n("details","bv-thinking");i.appendChild(n("summary",void 0,"thinking")),i.appendChild(n("div",void 0,t.thinking)),e.appendChild(i)}const o=n("div","bv-text");return o.appendChild(F(t.text)),e.appendChild(o),e}return t.kind==="tool"?xt(t):t.kind==="approval"?Ct(t):n("div",`bv-notice bv-notice-${t.level}`,t.text)}function St(t,e){const o=t.querySelector("details.bv-thinking");if(e.thinking)if(o){const s=o.querySelector("div");s&&s.textContent!==e.thinking&&(s.textContent=e.thinking)}else{const s=n("details","bv-thinking");s.appendChild(n("summary",void 0,"thinking")),s.appendChild(n("div",void 0,e.thinking)),t.prepend(s)}else o&&o.remove();const i=t.querySelector(".bv-text");i&&i.replaceChildren(F(e.text))}function tt(){const t=document.getElementById("bots-messages");if(!t||!d.activeId||document.getElementById("bots-view")?.hidden)return;const e=d.items.get(d.activeId)||[],o=B;if(e.length<L.length||e.some((s,r)=>L[r]?.item!==s))t.textContent="",L=e.map(s=>{const r=Z(s);return t.appendChild(r),{item:s,snapshot:X(s),node:r}});else{for(let s=L.length;s<e.length;s++){const r=e[s],a=Z(r);t.appendChild(a),L.push({item:r,snapshot:X(r),node:a})}for(let s=0;s<e.length;s++){const r=e[s],a=L[s],c=X(r);if(kt(a.snapshot,c)){if(r.kind==="assistant")St(a.node,r);else{const l=Z(r);a.node.replaceWith(l),a.node=l}a.snapshot=c}}}o&&(t.scrollTop=t.scrollHeight)}function xt(t){const e=n("details","bv-tool");e.open=t.phase!=="end"||!!t.isError;const o=n("summary"),i=n("span","bv-tool-name",t.name);if(o.appendChild(i),t.phase!=="end"&&o.appendChild(n("span","bv-tool-phase",t.phase)),t.isError&&o.appendChild(n("span","bv-tool-error","error")),typeof t.durationMs=="number"&&o.appendChild(n("span","bv-tool-meta",`${Math.round(t.durationMs)}ms`)),e.appendChild(o),t.args!==void 0){const s=n("pre","bv-pre");s.textContent=typeof t.args=="string"?t.args:JSON.stringify(t.args,null,2),e.appendChild(s)}if(t.output){const s=n("pre","bv-pre bv-output");s.textContent=t.output,e.appendChild(s)}return e}function Ct(t){const e=n("div","bv-approval"),o=t.approval;if(e.appendChild(n("div","bv-approval-title",o.title)),o.message&&e.appendChild(n("pre","bv-pre",o.message)),t.decided)return e.appendChild(n("div","bv-approval-decided",t.decided==="allowed"?"Allowed":"Denied")),e;const i=n("input","bv-reason");i.placeholder="reason (optional)";const s=n("div","bv-approval-actions"),r=n("button","btn primary","Allow"),a=n("button","btn",o.method==="confirm"&&/^Allow (.+?)\?$/.test(o.title)?`Always allow ${/^Allow (.+?)\?$/.exec(o.title)?.[1]}`:"Always allow");a.hidden=o.method!=="confirm";const c=n("button","btn danger","Deny"),l=async(u,h=!1)=>{try{await b(`/api/bots/${o.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:o.id,allow:u,always:h,reason:i.value||void 0})}),t.decided=u?"allowed":"denied",A(),C(!0)}catch(f){P({kind:"notice",level:"error",text:f instanceof Error?f.message:String(f)})}};return r.onclick=()=>void l(!0),a.onclick=()=>void l(!0,!0),c.onclick=()=>void l(!1),s.append(i,r,a,c),e.appendChild(s),e}function pt(t){const e=String(t.type||""),o=d.activeId;if(!o)return;const i=d.items.get(o)||[];if(e==="snapshot")d.items.set(o,[]);else if(e==="user")B=!0,P({kind:"user",text:String(t.text||"")});else if(e==="status"){const s=G();s&&(s.status=String(t.status||s.status)),Y(),Bt()}else if(e==="message"){const s=t.message;if(!s||String(s.role||"")!=="assistant")return;const a=It(s),c=Et(s),l=i[i.length-1];l&&l.kind==="assistant"?(l.text=a||l.text,l.thinking=c||l.thinking):i.push({kind:"assistant",text:a,thinking:c}),d.items.set(o,i),A()}else if(e==="delta"){const s=String(t.kind||""),r=String(t.delta||"");let a=i[i.length-1];(!a||a.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),a=i[i.length-1]),a.kind==="assistant"&&(s==="text"?a.text+=r:s==="thinking"&&(a.thinking+=r)),d.items.set(o,i),A()}else if(e==="tool"){const s=String(t.callId||""),r=i.find(c=>c.kind==="tool"&&c.callId===s),a=String(t.phase||"start");r?(r.phase=a,a==="update"&&t.output&&(r.output=String(t.output)),a==="end"&&(t.output&&(r.output=String(t.output)),r.isError=t.isError===!0,typeof t.durationMs=="number"&&(r.durationMs=t.durationMs))):i.push({kind:"tool",callId:s,name:String(t.name||"tool"),args:t.args,output:t.output?String(t.output):void 0,isError:t.isError===!0,durationMs:typeof t.durationMs=="number"?t.durationMs:void 0,phase:a}),d.items.set(o,i),A()}else if(e==="approval"){const s=t.approval;if(!s)return;const r=i;for(let a=r.length-1;a>=0;a--){const c=r[a];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(o,r),A();return}}r.push({kind:"approval",approval:s}),d.items.set(o,r),A()}else e==="notice"&&P({kind:"notice",level:String(t.level||"info"),text:String(t.text||"")})}function It(t){const e=t.content;return Array.isArray(e)?e.map(o=>o&&typeof o=="object"&&o.type==="text"?String(o.text||""):"").join(""):String(t.text||"")}function Et(t){const e=t.content;return Array.isArray(e)?e.map(o=>o&&typeof o=="object"&&o.type==="thinking"?String(o.thinking||""):"").join(""):""}async function C(t=!1){try{const[e,o]=await Promise.all([b("/api/bots"),b("/api/bots/approvals")]);if(d.bots=e,d.approvals=o,q(),Y(),t&&d.activeId){const i=await b(`/api/bots/${d.activeId}/events?limit=300`);$t(i)}}catch{}}async function Bt(){try{d.bots=await b("/api/bots"),q()}catch{}}function $t(t){if(d.activeId){d.items.set(d.activeId,[]);for(const e of t)pt(e);tt()}}function Ot(){const t=n("div","bots-modal");t.id="bots-modal",t.hidden=!0;const e=n("div","bots-modal-card"),o=n("div","bots-modal-head"),i=n("span");i.id="bots-modal-title";const s=n("button","btn");s.innerHTML=D("close",'width="14" height="14"'),s.title="Close",s.onclick=()=>V(),o.append(i,s);const r=n("div","bots-modal-body");r.id="bots-modal-body",e.append(o,r),t.appendChild(e),t.onclick=a=>{a.target===t&&V()},document.body.appendChild(t)}function et(t){const e=document.getElementById("bots-modal"),o=document.getElementById("bots-modal-title"),i=document.getElementById("bots-modal-body");if(!e||!i)throw new Error("modal missing");return o&&(o.textContent=t),i.textContent="",e.hidden=!1,i}function V(){const t=document.getElementById("bots-modal");t&&(t.hidden=!0)}async function Mt(){return d.catalog||(d.catalog=await b("/api/bots/catalog")),d.catalog}async function ut(){return d.templates=await b("/api/bots/templates"),d.templates}async function H(){const t=et("Bot templates"),[e,o]=await Promise.all([Mt(),ut()]),i=n("div","bv-template-list");for(const l of o){const u=n("div","bv-template-row");u.appendChild(n("span","bv-template-name",l.manifest.name)),u.appendChild(n("span","bv-template-desc",l.manifest.description||""));const h=n("button","btn","Edit");h.onclick=()=>mt(t,e,l);const f=n("button","btn","Copy");f.title="Duplicate this template",f.onclick=()=>{const I=JSON.parse(JSON.stringify(l.manifest));I.name=`${l.manifest.name} copy`,b("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:I})}).then(()=>H()).catch(x=>alert(x instanceof Error?x.message:String(x)))};const O=n("button","btn danger","Delete");O.onclick=()=>{confirm(`Delete template ${l.manifest.name}?`)&&b(`/api/bots/templates/${l.id}`,{method:"DELETE"}).then(()=>H())};const M=n("span","bv-template-actions");M.append(h,f,O),u.appendChild(M),i.appendChild(u)}o.length===0&&i.appendChild(n("div","bots-empty","No templates yet")),t.appendChild(i);const s=n("div","bv-template-actions"),r=n("button","btn primary","New template");r.onclick=()=>mt(t,e,null);const a=n("button","btn","Export");a.title="Download templates + library as JSON",a.onclick=()=>{(async()=>{try{const l=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${U()}`}});if(!l.ok)throw new Error(`HTTP ${l.status}`);const u=await l.blob(),h=document.createElement("a");h.href=URL.createObjectURL(u),h.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,h.click(),setTimeout(()=>URL.revokeObjectURL(h.href),2e3)}catch(l){alert(l instanceof Error?l.message:String(l))}})()};const c=n("button","btn","Import");c.title="Restore templates from a JSON bundle",c.onclick=()=>{const l=document.createElement("input");l.type="file",l.accept="application/json,.json",l.onchange=()=>{const u=l.files?.[0];u&&(async()=>{try{const h=JSON.parse(await u.text()),f=await b("/api/bots/import",{method:"POST",body:JSON.stringify(h)});alert(`Imported ${f.templates} templates, ${f.files} library files (${f.skipped} kept)`),await H()}catch(h){alert(h instanceof Error?h.message:String(h))}})()},l.click()},s.append(r,a,c),t.appendChild(s)}function nt(t,e,o){const i=n("div","bv-field");i.appendChild(n("label","bv-label",t));const s=n("div","bv-check-grid"),r=[];for(const a of e){const c=n("label","bv-check"),l=document.createElement("input");l.type="checkbox",l.checked=o.includes(a.id),c.append(l,n("span",void 0,a.label)),a.hint&&(c.title=a.hint),s.appendChild(c),r.push({id:a.id,input:l})}return i.appendChild(s),{element:i,get:()=>r.filter(a=>a.input.checked).map(a=>a.id)}}function mt(t,e,o){t.textContent="";const i=o?JSON.parse(JSON.stringify(o.manifest)):{name:"new-bot",description:""},s=n("input","bv-input");s.value=i.name,s.placeholder="Template name";const r=n("input","bv-input");r.value=i.description||"",r.placeholder="One line description";const a=n("textarea","bv-textarea");a.rows=6,a.value=i.system||"",a.placeholder="System prompt for this bot (written to SYSTEM.md)";const c=nt("Skills",e.skills.map(p=>({id:p.id,label:p.name,hint:p.description})),i.skills||[]),l=nt("Extensions (Pi builtins + library)",e.extensions.map(p=>({id:p.id,label:`${p.name}${p.kind==="builtin"?" (builtin)":""}`,hint:p.description})),(i.extensions||[]).map(p=>p.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),u=nt("Prompt templates",e.prompts.map(p=>({id:p.id,label:p.name})),i.prompts||[]),h=n("select","bv-input");h.appendChild(new Option("none",""));for(const p of e.mcp)h.appendChild(new Option(p.name,p.id));i.mcp&&(h.value=e.mcp.find(p=>JSON.stringify(p.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");const f=n("div","bv-field");f.appendChild(n("label","bv-label","Tools (allow list; deny always blocks)"));const O=n("div","bv-check-grid"),M=[];for(const p of e.tools){const S=n("label","bv-check"),m=document.createElement("input");m.type="checkbox",m.checked=(i.tools?.allow||[]).includes(p.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(p.name),S.append(m,n("span",void 0,p.name)),O.appendChild(S),M.push({name:p.name,input:m})}f.appendChild(O);const I=n("input","bv-input");I.value=(i.tools?.deny||[]).join(", "),I.placeholder="Always deny (comma separated), e.g. bash, write";const x=n("textarea","bv-textarea");x.rows=2,x.value=(i.packages||[]).join(`
2
+ `),x.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";const E=n("select","bv-input");E.appendChild(new Option("default (Pi settings)",""));for(const p of e.models)E.appendChild(new Option(`${p.provider}/${p.model}`,`${p.provider}
3
+ ${p.model}`));i.model?.provider&&i.model?.id&&(E.value=`${i.model.provider}
4
+ ${i.model.id}`);const g=n("select","bv-input");for(const p of["","off","minimal","low","medium","high","xhigh","max"])g.appendChild(new Option(p||"default",p));i.model?.thinking&&(g.value=i.model.thinking);const y=n("select","bv-input");for(const p of["supervised","auto-accept-edits","full-access"])y.appendChild(new Option(p,p));y.value=i.permissions?.runtimeMode||"supervised";const j=n("select","bv-input");j.appendChild(new Option("ignore project .pi (recommended)","ignore")),j.appendChild(new Option("inherit project .pi (needs trust)","inherit")),j.value=i.projectResources||"ignore";const J=n("label","bv-check"),T=document.createElement("input");T.type="checkbox",T.checked=!!i.orchestrator,J.append(T,n("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));const w=(p,S)=>{const m=n("div","bv-field");return m.appendChild(n("label","bv-label",p)),m.appendChild(S),m};t.append(w("Name",s),w("Description",r),w("System prompt",a),c.element,l.element,u.element,w("MCP preset",h),f,w("Always deny tools",I),w("Packages",x),w("Model",E),w("Thinking level",g),w("Approval mode",y),w("Project resources",j),J);const k=n("button","btn primary",o?"Save template":"Create template");k.onclick=async()=>{const[p,S]=E.value.split(`
5
+ `),m=e.mcp.find(v=>v.id===h.value),$={name:s.value.trim()||"bot",description:r.value.trim()||void 0,system:a.value.trim()||void 0,skills:c.get(),extensions:l.get().map(v=>(v.startsWith("builtin:"),v)),prompts:u.get(),packages:x.value.split(`
6
+ `).map(v=>v.trim()).filter(Boolean),mcp:m?{mcpServers:m.servers}:void 0,tools:{allow:M.filter(v=>v.input.checked).map(v=>v.name),deny:I.value.split(",").map(v=>v.trim()).filter(Boolean)},model:p?{provider:p,id:S,thinking:g.value||void 0}:void 0,permissions:{runtimeMode:y.value},projectResources:j.value==="inherit"?"inherit":"ignore",orchestrator:T.checked||void 0};try{await b("/api/bots/templates",{method:"POST",body:JSON.stringify({id:o?.id,manifest:$})}),V(),await H()}catch(v){alert(v instanceof Error?v.message:String(v))}},t.appendChild(k)}async function Tt(){return Lt("")}async function Lt(t){const e=et("New bot"),o=await ut();if(o.length===0){e.appendChild(n("div","bots-empty","No templates yet \u2014 create one with \u201CNew template\u201D."));return}const i=n("select","bv-input");for(const u of o)i.appendChild(new Option(u.manifest.name,u.id));const s=n("input","bv-input");s.placeholder="Title (defaults to template name)";const r=n("input","bv-input");r.placeholder="/path/to/project";const a=t||d.bots[0]?.projectPath||"";r.value=a;const c=n("select","bv-input");c.appendChild(new Option("shared \u2014 run in the project folder","shared")),c.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),e.append(W("Template",i),W("Title",s),W("Project path",r),W("Workspace",c));const l=n("button","btn primary","Create bot");l.onclick=async()=>{try{const u=await b("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:s.value.trim()||void 0,projectPath:r.value.trim()||void 0,isolation:c.value})});V(),await C(!0),await lt(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},e.appendChild(l)}function W(t,e){const o=n("div","bv-field");return o.appendChild(n("label","bv-label",t)),o.appendChild(e),o}async function ot(){const t=et("Needs you");if(d.approvals=await b("/api/bots/approvals"),d.approvals.length===0){t.appendChild(n("div","bots-empty","Nothing waiting."));return}for(const e of d.approvals){const o=n("div","bv-approval");o.appendChild(n("div","bv-approval-title",`${e.botTitle}: ${e.title}`)),e.message&&o.appendChild(n("pre","bv-pre",e.message));const i=n("input","bv-reason");i.placeholder="reason (optional)";const s=n("div","bv-approval-actions"),r=n("button","btn primary","Allow"),a=n("button","btn danger","Deny"),c=async l=>{await b(`/api/bots/${e.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:e.id,allow:l,reason:i.value||void 0})}),await C(!0),await ot()};r.onclick=()=>void c(!0),a.onclick=()=>void c(!1),s.append(i,r,a),o.appendChild(s),t.appendChild(o)}}function At(){window.__botsInited||(window.__botsInited=!0,yt(),gt(),window.__openBot=lt,document.addEventListener("click",t=>{const e=t.target;e&&(e.closest(".session-item.bot-item")||e.closest(".session-item")&&d.activeId&&setTimeout(()=>K(),0))},!0),C(!0),d.pollTimer=window.setInterval(()=>{document.hidden||C()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(d.pollTimer)))}export{At as initBots,Lt as openNewBotForPath};
@@ -0,0 +1,2 @@
1
+ import{marked as R}from"marked";const H=new Set(["http:","https:","mailto:"]);function x(a){const s=(a??"").trim();if(!s||s.startsWith("//"))return null;if(!/^[a-z][a-z0-9+.-]*:/i.test(s))return s;try{return H.has(new URL(s).protocol)?s:null}catch{return null}}const y=a=>/^[a-z][a-z0-9+.-]*:/i.test(a)&&!a.startsWith("mailto:"),w=4e5,M=200;function z(a){const s=new Map;let E=0;function N(n,e){const t=n.length+M;if(!(t>w/4)){s.set(n,{fragment:e,chars:t}),E+=t;for(const r of s.keys()){if(E<=w)break;const c=s.get(r);c&&(s.delete(r),E-=c.chars)}}}function g(n,e){e.split(`
2
+ `).forEach((r,c)=>{c>0&&n.appendChild(a.createElement("br")),r&&n.appendChild(a.createTextNode(r))})}function o(n,e){switch(e.type){case"text":{if(e.tokens?.length){for(const t of e.tokens)o(n,t);return}g(n,e.text??e.raw??"");return}case"escape":n.appendChild(a.createTextNode(e.text??""));return;case"strong":case"em":case"del":{const t=a.createElement(e.type==="strong"?"strong":e.type==="em"?"em":"del");for(const r of e.tokens??[])o(t,r);n.appendChild(t);return}case"codespan":{const t=a.createElement("code");t.textContent=e.text??"",n.appendChild(t);return}case"br":n.appendChild(a.createElement("br"));return;case"link":{const t=e.tokens??[],r=x(e.href);if(!r){for(const l of t)o(n,l);return}const c=a.createElement("a");c.href=r,c.rel="noreferrer noopener",e.title&&(c.title=e.title),y(r)&&(c.target="_blank");for(const l of t)o(c,l);n.appendChild(c);return}case"image":{const t=x(e.href),r=e.text?.trim()||e.href||"image";if(!t){n.appendChild(a.createTextNode(r));return}const c=a.createElement("a");c.href=t,c.textContent=r,c.rel="noreferrer noopener",y(t)&&(c.target="_blank"),n.appendChild(c);return}case"html":n.appendChild(a.createTextNode(e.raw??e.text??""));return;default:if(e.tokens?.length){for(const t of e.tokens)o(n,t);return}g(n,e.text??e.raw??"")}}function v(n){const e=a.createElement("div");e.className="bv-code";const t=a.createElement("div");t.className="bv-code-head";const r=(n.lang??"").trim().split(/\s+/)[0]??"",c=a.createElement("span");c.className="bv-code-lang",c.textContent=r||"text";const l=a.createElement("button");l.type="button",l.className="bv-code-copy",l.textContent="Copy";const f=n.text??"";l.addEventListener("click",()=>{const i=navigator.clipboard?.writeText(f);i&&i.then(()=>{l.textContent="Copied",window.setTimeout(()=>{l.textContent="Copy"},1200)},()=>{})}),t.append(c,l);const p=a.createElement("pre"),d=a.createElement("code");return r&&(d.className=`language-${r}`),d.textContent=f,p.appendChild(d),e.append(t,p),e}function T(n,e){const t=a.createElement("div");t.className="bv-table";const r=a.createElement("table"),c=a.createElement("thead"),l=a.createElement("tr"),f=e.align??[],p=(i,h,C)=>{const u=a.createElement(i);f[C]&&(u.style.textAlign=f[C]);for(const A of h.tokens??[])o(u,A);return u};(e.header??[]).forEach((i,h)=>l.appendChild(p("th",i,h))),c.appendChild(l);const d=a.createElement("tbody");for(const i of e.rows??[]){const h=a.createElement("tr");i.forEach((C,u)=>h.appendChild(p("td",C,u))),d.appendChild(h)}r.append(c,d),t.appendChild(r),n.appendChild(t)}function b(n,e){const t=a.createElement("li");if(e.task){const r=a.createElement("input");r.type="checkbox",r.disabled=!0,r.checked=e.checked===!0,t.appendChild(r)}for(const r of e.tokens??[])if(r.type==="text")o(t,r);else if(r.type==="paragraph")for(const c of r.tokens??[])o(t,c);else m(t,r);n.appendChild(t)}function m(n,e){switch(e.type){case"space":return;case"heading":{const t=Math.min(Math.max(e.depth??1,1),6),r=a.createElement(`h${t}`);for(const c of e.tokens??[])o(r,c);n.appendChild(r);return}case"paragraph":{const t=a.createElement("p");for(const r of e.tokens??[])o(t,r);n.appendChild(t);return}case"text":o(n,e);return;case"code":n.appendChild(v(e));return;case"blockquote":{const t=a.createElement("blockquote");for(const r of e.tokens??[])m(t,r);n.appendChild(t);return}case"list":{const t=e.items??e.tokens??[];if(e.ordered){const r=a.createElement("ol");typeof e.start=="number"&&e.start!==1&&(r.start=e.start);for(const c of t)b(r,c);n.appendChild(r)}else{const r=a.createElement("ul");for(const c of t)b(r,c);n.appendChild(r)}return}case"table":T(n,e);return;case"hr":n.appendChild(a.createElement("hr"));return;case"html":case"escape":n.appendChild(a.createTextNode(e.raw??e.text??""));return;default:if(e.tokens?.length){for(const t of e.tokens)m(n,t);return}e.text&&n.appendChild(a.createTextNode(e.text))}}function _(n){const e=a.createDocumentFragment();try{const t=R.lexer(n);for(const r of t)m(e,r)}catch{e.replaceChildren(a.createTextNode(n))}return e}return n=>{const e=s.get(n);if(e)return s.delete(n),s.set(n,e),e.fragment.cloneNode(!0);const t=_(n);return N(n,t),t.cloneNode(!0)}}export{z as createMarkdownRenderer,x as safeHref};
@@ -1,34 +1,34 @@
1
- import{initTerminal as tt}from"./terminal-core.js";import{initBots as nt,openNewBotForPath as st}from"./bots-client.js";const j=window.__TMUX_WEB_SHELL__;let f=null,u=null;const z=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let h=z;window.__tmuxWebScopeAgent=z;let ye="sessions",x="",Q="",ee="",Ie="";function v(e){return h?"/a/"+encodeURIComponent(h)+e:e}const d=document.getElementById("sidebar-content"),R=document.getElementById("main-placeholder"),w=document.getElementById("terminal-container"),O=document.getElementById("file-editor"),it=document.getElementById("fe-path"),E=document.getElementById("fe-status"),U=document.getElementById("fe-content"),_=document.getElementById("fe-save"),ot=document.getElementById("fe-delete"),at=document.getElementById("fe-back"),xe=document.getElementById("fe-new-name"),lt=document.getElementById("fe-new-btn"),he=document.getElementById("settings-backdrop"),Te=document.getElementById("settings-popover"),Me=document.querySelector(".sidebar"),He="tmux-web-force-narrow";function te(){try{return localStorage.getItem(He)==="1"}catch{return!1}}function Ne(){document.documentElement.classList.toggle("force-narrow",te()),te()&&Re()&&W()}function Re(){return te()?!0:window.matchMedia("(max-width: 640px)").matches}function W(){Re()&&Me.classList.add("collapsed")}function _e(){Me.classList.remove("collapsed")}window.__collapseSidebar=W,document.getElementById("mode-sessions").addEventListener("click",()=>{_e(),$e("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{_e(),$e("files")});function $e(e){ye=e,document.querySelectorAll(".mode-btn").forEach(n=>n.classList.remove("active"));const t=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");t&&t.classList.add("active"),e==="sessions"?(be="",T()):Et()}let be="";async function T(){if(ye!=="sessions")return;try{const n=await(await fetch("/api/sidebar/sessions")).json(),s=(window.__botsSnapshot||[]).map(o=>[o.id,o.title,o.status,o.projectPath]),i=JSON.stringify({recent:n.recent,agents:n.agents,tombstones:n.tombstones,bots:s});if(i===be)return;be=i,ut(n)}catch{d.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}const e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{const t=window.__openNewSessionModal;typeof t=="function"?t():document.getElementById("new-session-modal")?.classList.add("open")}),Be()}const Ae="tmux-web-sidebar-group-collapsed";function Pe(){try{return new Set(JSON.parse(localStorage.getItem(Ae)||"[]"))}catch{return new Set}}function ct(e){try{localStorage.setItem(Ae,JSON.stringify([...e]))}catch{}}function rt(e,t,n){if(!e)return"\u2026";const s=n&&(e===n||e.startsWith(n+"/"))?"~"+e.slice(n.length):e,i=s.split("/").filter(Boolean);if(i.length===0)return e;for(let o=1;o<=i.length;o++){const a=i.slice(-o).join("/");if(!t.some(c=>!c||c===e?!1:(n&&(c===n||c.startsWith(n+"/"))?"~"+c.slice(n.length):c).split("/").filter(Boolean).slice(-o).join("/")===a))return a}return s}function dt(e){const t=document.createElement("div");t.className="session-item bot-item",t.setAttribute("data-bot-id",e.id),t.title=`Bot \xB7 ${e.projectPath}`;const n=e.status==="running"?"var(--panel-success)":e.status==="waiting_approval"||e.status==="waiting_input"?"#e0a23c":e.status==="failed"?"var(--panel-danger, #e5534b)":"var(--panel-muted)";return t.innerHTML=`<svg class="bot-icon" viewBox="0 0 24 24" fill="currentColor"><path d="M11 2h2v3h2a3 3 0 0 1 3 3v1h1a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-1v1a3 3 0 0 1-3 3H9a3 3 0 0 1-3-3v-1H5a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2h1V8a3 3 0 0 1 3-3h2V2zm-2 6v1h6V8H9zm-2 5a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3zm10 0a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3z"/></svg><span>${p(e.title)}</span><span class="bot-status-dot" style="background:${n}"></span>`,t.addEventListener("click",s=>{s.stopPropagation(),window.__openBot?.(e.id)}),t}function De(e,t,n,s=!0){const i=new Map;for(const r of e){const g=r.path||"";i.has(g)||i.set(g,[]),i.get(g).push(r)}const o=n?[]:window.__botsSnapshot||[],a=new Map;for(const r of o)i.has(r.projectPath)||i.set(r.projectPath,[]),a.has(r.projectPath)||a.set(r.projectPath,[]),a.get(r.projectPath).push(r);const l=[...i.keys()],c=Pe();for(const[r,g]of i){const H=rt(r,l,t),N=c.has(r),I=document.createElement("div");if(I.className="session-group-header"+(N?" collapsed":""),I.title=r||"No working directory",I.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${p(H)}</span>`,!n&&r){const y=document.createElement("button");y.className="sg-add-bot",y.textContent="+",y.title=`New bot in ${r}`,y.addEventListener("click",Z=>{Z.stopPropagation(),Le(r)}),I.appendChild(y)}I.addEventListener("click",()=>{const y=Pe(),Z=I.nextElementSibling;y.has(r)?(y.delete(r),I.classList.remove("collapsed"),Z?.classList.remove("collapsed")):(y.add(r),I.classList.add("collapsed"),Z?.classList.add("collapsed")),ct(y)});const X=document.createElement("div");X.className="session-group-body"+(N?" collapsed":"");for(const y of g)X.appendChild(n?pt(y,n,s):ft(y));for(const y of a.get(r)||[])X.appendChild(dt(y));d.appendChild(I),d.appendChild(X)}}function pt(e,t,n){const s=document.createElement("div");s.className="session-item"+(e.name===u&&h===t?" active":"")+(n?"":" session-offline"),s.setAttribute("data-session",e.name),s.setAttribute("data-agent",t),s.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
1
+ import{initTerminal as nt}from"./terminal-core.js";import{initBots as st,openNewBotForPath as it}from"./bots-client.js";import{icon as Q}from"../lib/icons.js";const j=window.__TMUX_WEB_SHELL__;let f=null,u=null;const O=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let h=O;window.__tmuxWebScopeAgent=O;let he="sessions",T="",ee="",te="",Te="";function g(e){return h?"/a/"+encodeURIComponent(h)+e:e}const d=document.getElementById("sidebar-content"),R=document.getElementById("main-placeholder"),w=document.getElementById("terminal-container"),U=document.getElementById("file-editor"),ot=document.getElementById("fe-path"),E=document.getElementById("fe-status"),W=document.getElementById("fe-content"),_=document.getElementById("fe-save"),at=document.getElementById("fe-delete"),lt=document.getElementById("fe-back"),xe=document.getElementById("fe-new-name"),ct=document.getElementById("fe-new-btn"),be=document.getElementById("settings-backdrop"),Me=document.getElementById("settings-popover"),He=document.querySelector(".sidebar"),Ne="tmux-web-force-narrow";function ne(){try{return localStorage.getItem(Ne)==="1"}catch{return!1}}function Re(){document.documentElement.classList.toggle("force-narrow",ne()),ne()&&_e()&&z()}function _e(){return ne()?!0:window.matchMedia("(max-width: 640px)").matches}function z(){_e()&&He.classList.add("collapsed")}function $e(){He.classList.remove("collapsed")}window.__collapseSidebar=z,document.getElementById("mode-sessions").addEventListener("click",()=>{$e(),Ae("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{$e(),Ae("files")});function Ae(e){he=e,document.querySelectorAll(".mode-btn").forEach(n=>n.classList.remove("active"));const t=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");t&&t.classList.add("active"),e==="sessions"?(we="",x()):kt()}let we="";async function x(){if(he!=="sessions")return;try{const n=await(await fetch("/api/sidebar/sessions")).json(),s=(window.__botsSnapshot||[]).map(o=>[o.id,o.title,o.status,o.projectPath]),i=JSON.stringify({recent:n.recent,agents:n.agents,tombstones:n.tombstones,bots:s});if(i===we)return;we=i,mt(n)}catch{d.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}const e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{const t=window.__openNewSessionModal;typeof t=="function"?t():document.getElementById("new-session-modal")?.classList.add("open")}),Ie()}const Pe="tmux-web-sidebar-group-collapsed";function De(){try{return new Set(JSON.parse(localStorage.getItem(Pe)||"[]"))}catch{return new Set}}function rt(e){try{localStorage.setItem(Pe,JSON.stringify([...e]))}catch{}}function dt(e,t,n){if(!e)return"\u2026";const s=n&&(e===n||e.startsWith(n+"/"))?"~"+e.slice(n.length):e,i=s.split("/").filter(Boolean);if(i.length===0)return e;for(let o=1;o<=i.length;o++){const a=i.slice(-o).join("/");if(!t.some(c=>!c||c===e?!1:(n&&(c===n||c.startsWith(n+"/"))?"~"+c.slice(n.length):c).split("/").filter(Boolean).slice(-o).join("/")===a))return a}return s}function pt(e){const t=document.createElement("div");t.className="session-item bot-item",t.setAttribute("data-bot-id",e.id),t.title=`Bot \xB7 ${e.projectPath}`;const n=e.status==="running"?"var(--panel-success)":e.status==="waiting_approval"||e.status==="waiting_input"?"#e0a23c":e.status==="failed"?"var(--panel-danger, #e5534b)":"var(--panel-muted)";return t.innerHTML=`${Q("bot",'class="bot-icon"')}<span>${p(e.title)}</span><span class="bot-status-dot" style="background:${n}"></span>`,t.addEventListener("click",s=>{s.stopPropagation(),window.__openBot?.(e.id)}),t}function je(e,t,n,s=!0){const i=new Map;for(const r of e){const v=r.path||"";i.has(v)||i.set(v,[]),i.get(v).push(r)}const o=n?[]:window.__botsSnapshot||[],a=new Map;for(const r of o)i.has(r.projectPath)||i.set(r.projectPath,[]),a.has(r.projectPath)||a.set(r.projectPath,[]),a.get(r.projectPath).push(r);const l=[...i.keys()],c=De();for(const[r,v]of i){const H=dt(r,l,t),N=c.has(r),I=document.createElement("div");if(I.className="session-group-header"+(N?" collapsed":""),I.title=r||"No working directory",I.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${p(H)}</span>`,!n&&r){const y=document.createElement("button");y.className="sg-add-bot",y.innerHTML=Q("add",'width="12" height="12"'),y.title=`New bot in ${r}`,y.addEventListener("click",Z=>{Z.stopPropagation(),Ee(r)}),I.appendChild(y)}I.addEventListener("click",()=>{const y=De(),Z=I.nextElementSibling;y.has(r)?(y.delete(r),I.classList.remove("collapsed"),Z?.classList.remove("collapsed")):(y.add(r),I.classList.add("collapsed"),Z?.classList.add("collapsed")),rt(y)});const X=document.createElement("div");X.className="session-group-body"+(N?" collapsed":"");for(const y of v)X.appendChild(n?ft(y,n,s):ut(y));for(const y of a.get(r)||[])X.appendChild(pt(y));d.appendChild(I),d.appendChild(X)}}function ft(e,t,n){const s=document.createElement("div");s.className="session-item"+(e.name===u&&h===t?" active":"")+(n?"":" session-offline"),s.setAttribute("data-session",e.name),s.setAttribute("data-agent",t),s.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
2
2
  <span>${p(e.name)}</span>${n?"":'<span class="meta">offline</span>'}
3
- <button class="session-edit-btn" data-session="${p(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,n&&s.addEventListener("click",o=>{o.target.closest(".session-edit-btn")||F(e.name,t)});const i=s.querySelector(".session-edit-btn");return i&&i.addEventListener("click",o=>{o.stopPropagation(),pe(e.name,i,{agentId:t})}),s}function ft(e){const t=document.createElement("div");t.className="session-item"+(e.name===u&&!h?" active":""),t.setAttribute("data-session",e.name),t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
3
+ <button class="session-edit-btn" data-session="${p(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,n&&s.addEventListener("click",o=>{o.target.closest(".session-edit-btn")||F(e.name,t)});const i=s.querySelector(".session-edit-btn");return i&&i.addEventListener("click",o=>{o.stopPropagation(),fe(e.name,i,{agentId:t})}),s}function ut(e){const t=document.createElement("div");t.className="session-item"+(e.name===u&&!h?" active":""),t.setAttribute("data-session",e.name),t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
4
4
  <span>${p(e.name)}</span>
5
5
  <button class="session-edit-btn" data-session="${p(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>
6
- `,t.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||F(e.name)});const n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",s=>{s.stopPropagation(),pe(e.name,n)}),t}function ut(e){d.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';const t=e.recent||[],n=document.createElement("div");n.className="sidebar-section-label"+(z?" clickable":""),n.textContent=z?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",z&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),d.appendChild(n),De(t,e.home);const s=e.agents||[];for(const o of s){if(!o.sessions||o.sessions.length===0)continue;const a=o.agentId===h,l=document.createElement("div");l.className="sidebar-section-label machine-label"+(o.online?"":" agent-offline-label")+(!a&&o.online?" clickable":""),l.textContent=o.agentName+(o.online?"":" (offline)"),!a&&o.online&&(l.title="\u6253\u5F00 "+o.agentName,l.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(o.agentId)+"/"})),d.appendChild(l),De(o.sessions,e.home,o.agentId,o.online)}const i=e.tombstones||[];if(i.length>0){const o=document.createElement("div");o.className="sidebar-section-label tombstone-label",o.textContent="\u5931\u6548\u4F1A\u8BDD",d.appendChild(o);for(const a of i){const l=document.createElement("div");l.className="session-item session-tombstone",l.setAttribute("data-session",a.name),a.agentId&&l.setAttribute("data-agent",a.agentId);const c=a.agentId?a.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";l.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
6
+ `,t.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||F(e.name)});const n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",s=>{s.stopPropagation(),fe(e.name,n)}),t}function mt(e){d.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';const t=e.recent||[],n=document.createElement("div");n.className="sidebar-section-label"+(O?" clickable":""),n.textContent=O?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",O&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),d.appendChild(n),je(t,e.home);const s=e.agents||[];for(const o of s){if(!o.sessions||o.sessions.length===0)continue;const a=o.agentId===h,l=document.createElement("div");l.className="sidebar-section-label machine-label"+(o.online?"":" agent-offline-label")+(!a&&o.online?" clickable":""),l.textContent=o.agentName+(o.online?"":" (offline)"),!a&&o.online&&(l.title="\u6253\u5F00 "+o.agentName,l.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(o.agentId)+"/"})),d.appendChild(l),je(o.sessions,e.home,o.agentId,o.online)}const i=e.tombstones||[];if(i.length>0){const o=document.createElement("div");o.className="sidebar-section-label tombstone-label",o.textContent="\u5931\u6548\u4F1A\u8BDD",d.appendChild(o);for(const a of i){const l=document.createElement("div");l.className="session-item session-tombstone",l.setAttribute("data-session",a.name),a.agentId&&l.setAttribute("data-agent",a.agentId);const c=a.agentId?a.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";l.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
7
7
  <span>${p(a.name)}</span><span class="meta">\u5931\u6548${c}</span>
8
- <button class="session-edit-btn" data-session="${p(a.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,l.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",l.addEventListener("click",()=>{pe(a.name,l,{tombstone:!0,agentId:a.agentId})});const r=l.querySelector(".session-edit-btn");r&&r.addEventListener("click",g=>{g.stopPropagation(),pe(a.name,r,{tombstone:!0,agentId:a.agentId})}),d.appendChild(l)}}}function p(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function F(e,t){if(u===e&&f&&h===(t||null))return;O.style.display="none",R.style.display="none",w.style.display="",w.classList.add("terminal-pending"),W(),f&&(re(),f.destroy(),f=null),u=e,h=t||null,window.__tmuxWebScopeAgent=h,window.__tmuxWebCurrentSession=u,Dt(e,t);const n=Se(e,t);Qe.set(n,Date.now()+At);const s=D.get(n);if(s&&s.state==="working"){s.state="idle",s.doneUntil=void 0,s.unread=!1;const i=d.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');i&&ge(i,n,s)}for(const i of d.querySelectorAll(".session-item"))i.classList.toggle("active",i.getAttribute("data-session")===e&&(i.getAttribute("data-agent")||null)===h);try{f=await tt(w,e,{terminal:j.terminal,scrollback:j.scrollback,theme:j.theme,wsBase:h?"/ws/a/"+encodeURIComponent(h):j.wsBase||"/ws"}),Je()}catch(i){console.error("[shell] terminal init failed:",i);const o=i&&typeof i=="object"&&"message"in i?i.message:String(i);w.textContent="Failed to open terminal for "+e+": "+o,w.classList.remove("terminal-pending")}}let ne=[],m=null,je=!1;function mt(e){if(!m||!m.files.length)return null;const t=m.repoRoot;if(!t||!e.startsWith(t))return null;const n=e.slice(t.length+1);for(const s of m.files)if(s.path===n)return s.status;return null}async function vt(e){je=!0;try{const t=await fetch(v("/api/git/status?path="+encodeURIComponent(e)));t.ok?m=await t.json():m=null}catch{m=null}finally{je=!1}}function gt(){if(!m||!m.branch)return"";const{branch:e,linesAdded:t,linesRemoved:n}=m;let s=`<div class="sidebar-git"><div class="git-branch-badge">
8
+ <button class="session-edit-btn" data-session="${p(a.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,l.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",l.addEventListener("click",()=>{fe(a.name,l,{tombstone:!0,agentId:a.agentId})});const r=l.querySelector(".session-edit-btn");r&&r.addEventListener("click",v=>{v.stopPropagation(),fe(a.name,r,{tombstone:!0,agentId:a.agentId})}),d.appendChild(l)}}}function p(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function F(e,t){if(u===e&&f&&h===(t||null))return;U.style.display="none",R.style.display="none",w.style.display="",w.classList.add("terminal-pending"),z(),f&&(de(),f.destroy(),f=null),u=e,h=t||null,window.__tmuxWebScopeAgent=h,window.__tmuxWebCurrentSession=u,jt(e,t);const n=Be(e,t);et.set(n,Date.now()+Pt);const s=D.get(n);if(s&&s.state==="working"){s.state="idle",s.doneUntil=void 0,s.unread=!1;const i=d.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');i&&ye(i,n,s)}for(const i of d.querySelectorAll(".session-item"))i.classList.toggle("active",i.getAttribute("data-session")===e&&(i.getAttribute("data-agent")||null)===h);try{f=await nt(w,e,{terminal:j.terminal,scrollback:j.scrollback,theme:j.theme,wsBase:h?"/ws/a/"+encodeURIComponent(h):j.wsBase||"/ws"}),Ke()}catch(i){console.error("[shell] terminal init failed:",i);const o=i&&typeof i=="object"&&"message"in i?i.message:String(i);w.textContent="Failed to open terminal for "+e+": "+o,w.classList.remove("terminal-pending")}}let se=[],m=null,Oe=!1;function gt(e){if(!m||!m.files.length)return null;const t=m.repoRoot;if(!t||!e.startsWith(t))return null;const n=e.slice(t.length+1);for(const s of m.files)if(s.path===n)return s.status;return null}async function vt(e){Oe=!0;try{const t=await fetch(g("/api/git/status?path="+encodeURIComponent(e)));t.ok?m=await t.json():m=null}catch{m=null}finally{Oe=!1}}function yt(){if(!m||!m.branch)return"";const{branch:e,linesAdded:t,linesRemoved:n}=m;let s=`<div class="sidebar-git"><div class="git-branch-badge">
9
9
  <svg viewBox="0 0 16 16" fill="currentColor"><path d="M11.63 1.22a.75.75 0 00-1.06 0L5.99 5.8 4.12 3.93a.75.75 0 10-1.06 1.06L4.93 6.87A3.5 3.5 0 003 10.09v3.16a.75.75 0 001 0v-3.16a2.5 2.5 0 012.5-2.5h.27l-1.06 1.06a.75.75 0 001.06 1.06l2.37-2.38a.75.75 0 000-1.06L7.59 5.27l4.04-4.05a.75.75 0 000-1.06L11.63 1.22zM3.25 13.94a.75.75 0 01-.75-.75v-.69a.75.75 0 011.5 0v.69c0 .414-.336.75-.75.75z"/></svg>
10
- ${p(e)}</div>`;return(t>0||n>0)&&(s+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${n}</span></div>`),s+"</div>"}d.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&A&&m&&(e.stopPropagation(),Fe())});const G=document.getElementById("header-git"),ze=document.getElementById("git-diff-view"),Oe=document.getElementById("gd-path"),se=document.getElementById("gd-status"),ie=document.getElementById("gd-content"),yt=document.getElementById("gd-back");let A=null;function V(e){if(!e||!e.branch){G.style.display="none",A=null;return}A=e.repoRoot;const{branch:t,linesAdded:n,linesRemoved:s}=e;let i=`<span class="branch">${p(t)}</span>`;(n>0||s>0)&&(i+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${s}</span>`),G.innerHTML=i,G.style.display="block"}G.addEventListener("click",e=>{A&&m&&(e.stopPropagation(),Fe())});const b=document.getElementById("git-popover"),oe=document.getElementById("git-popover-backdrop");function we(){const e=G.getBoundingClientRect();b.style.top=e.bottom+4+"px",b.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function Ue(){const e=A,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(le(),e){ye="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));const n=document.getElementById("mode-files");n&&n.classList.add("active"),M(e)}})}let We="";function Fe(){if(!m)return;const e=m.files||[];if(!e.length)b.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
10
+ ${p(e)}</div>`;return(t>0||n>0)&&(s+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${n}</span></div>`),s+"</div>"}d.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&A&&m&&(e.stopPropagation(),Ge())});const G=document.getElementById("header-git"),Ue=document.getElementById("git-diff-view"),We=document.getElementById("gd-path"),ie=document.getElementById("gd-status"),oe=document.getElementById("gd-content"),ht=document.getElementById("gd-back");let A=null;function q(e){if(!e||!e.branch){G.style.display="none",A=null;return}A=e.repoRoot;const{branch:t,linesAdded:n,linesRemoved:s}=e;let i=`<span class="branch">${p(t)}</span>`;(n>0||s>0)&&(i+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${s}</span>`),G.innerHTML=i,G.style.display="block"}G.addEventListener("click",e=>{A&&m&&(e.stopPropagation(),Ge())});const b=document.getElementById("git-popover"),ae=document.getElementById("git-popover-backdrop");function Le(){const e=G.getBoundingClientRect();b.style.top=e.bottom+4+"px",b.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function ze(){const e=A,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(ce(),e){he="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));const n=document.getElementById("mode-files");n&&n.classList.add("active"),M(e)}})}let Fe="";function Ge(){if(!m)return;const e=m.files||[];if(!e.length)b.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
11
11
  <div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let t=`<div class="git-popover-header">${e.length} file${e.length>1?"s":""} changed</div>`;for(let n=0;n<e.length;n++){const s=e[n],i=s.additions||0,o=s.deletions||0;let a="";switch(s.status){case"M":a='<span class="git-file-status M">M</span>';break;case"A":a='<span class="git-file-status A">A</span>';break;case"D":a='<span class="git-file-status D">D</span>';break;case"?":a='<span class="git-file-status ?">?</span>';break;case"R":a='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
12
12
  ${a}<span class="file-path">${p(s.path)}</span>
13
13
  <span class="file-add">${i>0?"+"+i:""}</span>
14
14
  <span class="file-del">${o>0?"-"+o:""}</span>
15
- </div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',We=t,b.innerHTML=t,b.querySelectorAll(".git-popover-item").forEach(n=>{const s=parseInt(n.dataset.idx||"0",10),i=e[s];!i||i.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>Ve(i.path)))})}we(),b.classList.add("open"),oe.classList.add("open"),Ue()}function ht(){return window.innerWidth>=1024}function Ge(e,t){const s=(e+(t&&e?`
15
+ </div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',Fe=t,b.innerHTML=t,b.querySelectorAll(".git-popover-item").forEach(n=>{const s=parseInt(n.dataset.idx||"0",10),i=e[s];!i||i.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>Ve(i.path)))})}Le(),b.classList.add("open"),ae.classList.add("open"),ze()}function bt(){return window.innerWidth>=1024}function qe(e,t){const s=(e+(t&&e?`
16
16
  `:"")+t).split(`
17
- `);let i="",o=0,a=0;for(const l of s){const c=l;if(c.startsWith("@@")){const r=c.match(/@@\s+-(\d+)[^+]*\+(\d+)/);r&&(o=parseInt(r[1],10)-1,a=parseInt(r[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${p(c)}</span></div>`;continue}if(c.startsWith("diff --git")||c.startsWith("index ")||c.startsWith("--- ")||c.startsWith("+++ ")||c.startsWith("new file")||c.startsWith("deleted file")){c.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${p(c)}</span></div>`);continue}if(c.startsWith("+"))a++,i+=`<div class="diff-line add"><span class="ln-no">${a}</span><span class="ln-body">${p(c)}</span></div>`;else if(c.startsWith("-"))o++,i+=`<div class="diff-line del"><span class="ln-no">${o}</span><span class="ln-body">${p(c)}</span></div>`;else if(c.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${p(c)}</span></div>`;else{if(!c&&!o&&!a)continue;o++,a++,i+=`<div class="diff-line"><span class="ln-no">${o}</span><span class="ln-no" style="margin-right:12px">${a}</span><span class="ln-body">${p(c)}</span></div>`}}return{html:i,lineCount:s.length}}let ae=null;async function Ve(e){const t=A;if(t)if(le(),ht()){w.style.display="none",f&&(re(),f.destroy(),f=null,ae=u,u=null),V(null),O.style.display="none",R.style.display="none",ze.style.display="flex",Oe.textContent=e,se.textContent="Loading\u2026",ie.innerHTML="";try{const n=await fetch(v("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());const s=await n.json();wt(e,s.diff,s.stagedDiff)}catch(n){const s=n instanceof Error?n.message:String(n);se.textContent="Error",ie.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${p(s)}</div>`}}else{b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
17
+ `);let i="",o=0,a=0;for(const l of s){const c=l;if(c.startsWith("@@")){const r=c.match(/@@\s+-(\d+)[^+]*\+(\d+)/);r&&(o=parseInt(r[1],10)-1,a=parseInt(r[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${p(c)}</span></div>`;continue}if(c.startsWith("diff --git")||c.startsWith("index ")||c.startsWith("--- ")||c.startsWith("+++ ")||c.startsWith("new file")||c.startsWith("deleted file")){c.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${p(c)}</span></div>`);continue}if(c.startsWith("+"))a++,i+=`<div class="diff-line add"><span class="ln-no">${a}</span><span class="ln-body">${p(c)}</span></div>`;else if(c.startsWith("-"))o++,i+=`<div class="diff-line del"><span class="ln-no">${o}</span><span class="ln-body">${p(c)}</span></div>`;else if(c.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${p(c)}</span></div>`;else{if(!c&&!o&&!a)continue;o++,a++,i+=`<div class="diff-line"><span class="ln-no">${o}</span><span class="ln-no" style="margin-right:12px">${a}</span><span class="ln-body">${p(c)}</span></div>`}}return{html:i,lineCount:s.length}}let le=null;async function Ve(e){const t=A;if(t)if(ce(),bt()){w.style.display="none",f&&(de(),f.destroy(),f=null,le=u,u=null),q(null),U.style.display="none",R.style.display="none",Ue.style.display="flex",We.textContent=e,ie.textContent="Loading\u2026",oe.innerHTML="";try{const n=await fetch(g("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());const s=await n.json();Lt(e,s.diff,s.stagedDiff)}catch(n){const s=n instanceof Error?n.message:String(n);ie.textContent="Error",oe.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${p(s)}</div>`}}else{b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
18
18
  <button class="diff-back">\u2190 Back</button>
19
19
  <span class="diff-filename">${p(e)}</span>
20
20
  <span class="diff-loading">Loading\u2026</span>
21
- </div></div>`,we(),b.classList.add("open"),oe.classList.add("open");try{const n=await fetch(v("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());const s=await n.json();bt(e,s.diff,s.stagedDiff)}catch(n){const s=n instanceof Error?n.message:String(n);b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
21
+ </div></div>`,Le(),b.classList.add("open"),ae.classList.add("open");try{const n=await fetch(g("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());const s=await n.json();wt(e,s.diff,s.stagedDiff)}catch(n){const s=n instanceof Error?n.message:String(n);b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
22
22
  <button class="diff-back">\u2190 Back</button>
23
23
  <span class="diff-filename">${p(e)}</span>
24
- </div><div class="diff-empty">Error loading diff: ${p(s)}</div></div>`}}}function bt(e,t,n){if(!t&&!n){b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
24
+ </div><div class="diff-empty">Error loading diff: ${p(s)}</div></div>`}}}function wt(e,t,n){if(!t&&!n){b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
25
25
  <button class="diff-back">\u2190 Back</button>
26
26
  <span class="diff-filename">${p(e)}</span>
27
- </div><div class="diff-empty">No diff content available</div></div>`;return}const{html:s,lineCount:i}=Ge(t,n);b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
27
+ </div><div class="diff-empty">No diff content available</div></div>`;return}const{html:s,lineCount:i}=qe(t,n);b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
28
28
  <button class="diff-back">\u2190 Back</button>
29
29
  <span class="diff-filename">${p(e)}</span>
30
30
  <span class="diff-filesize">${i} lines</span>
31
- </div><div class="diff-content">${s}</div></div>`,b.querySelector(".diff-back")?.addEventListener("click",()=>{b.innerHTML=We,we(),m&&b.querySelectorAll(".git-popover-item").forEach(o=>{const a=parseInt(o.dataset.idx||"0",10),l=m.files[a];!l||l.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>Ve(l.path)))}),Ue()})}function wt(e,t,n){if(!t&&!n){se.textContent="No diff",ie.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}const{html:s,lineCount:i}=Ge(t,n);Oe.textContent=e,se.textContent=i+" lines",ie.innerHTML=s}function Lt(){ze.style.display="none",ae?(w.style.display="",w.classList.add("terminal-pending"),F(ae),ae=null):u?(w.style.display="",w.classList.add("terminal-pending"),Je()):R.style.display="flex"}yt.addEventListener("click",Lt);function le(){b.classList.remove("open"),oe.classList.remove("open")}oe.addEventListener("click",le),document.addEventListener("keydown",e=>{e.key==="Escape"&&(le(),ve())});async function qe(e){try{const n=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(n.path){const s=await fetch("/api/git/status?path="+encodeURIComponent(n.path));if(s.ok){const i=await s.json();m=i,V(i);return}}}catch{}m=null,V(null)}let ce=null;function Je(){re(),u&&(qe(u),ce=setInterval(()=>{u&&qe(u)},3e4))}function re(){ce&&(clearInterval(ce),ce=null)}async function Le(e){let t=e;if(t.startsWith("~"))try{const s=await(await fetch(v("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof s.path=="string"&&s.path&&(t=s.path)}catch{}t=t.replace(/\/+$/,"")||"/",st(t)}function Ke(e,t){const n=document.createElement("button");n.className="file-tree-bot-btn",n.textContent="+",n.title=`Create bot in ${t}`,n.setAttribute("aria-label",`Create bot in ${t}`),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),Le(t)}),e.appendChild(n)}function Et(){if(ne=j.fsRoots||[],ne.length===0){if(u){kt(u);return}M("");return}d.innerHTML="";for(const e of ne){const t=document.createElement("div");t.className="file-tree-item",t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${p(e)}`,t.addEventListener("click",()=>M(e)),Ke(t,e),d.appendChild(t)}}async function kt(e){d.innerHTML='<div class="file-tree-empty">Loading...</div>';try{const n=await(await fetch(v("/api/fs/session-path?session="+encodeURIComponent(e)))).json();n.path?M(n.path):d.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{d.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function M(e){x=e,d.innerHTML='<div class="file-tree-empty">Loading...</div>';const t=vt(e);try{const s=await(await fetch(v("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof s.path=="string"&&s.path?s.path:e;if(i&&(x=i),await t,d.innerHTML="",i){const l=document.createElement("div");l.className="file-tree-item file-tree-create-bot",l.innerHTML='<span class="file-tree-bot-plus">+</span> Create bot in this folder',l.title=`Create bot in ${i}`,l.addEventListener("click",()=>void Le(i)),d.appendChild(l)}V(m),d.innerHTML+=gt();const o=Ct(i||e);if(o&&!ne.some(c=>i===c)){const c=document.createElement("div");c.className="file-tree-item",c.innerHTML="..",c.addEventListener("click",()=>M(o)),d.appendChild(c)}if(s.dirs)for(const l of s.dirs){const c=l.split("/").pop()||l.split("\\").pop(),r=document.createElement("div");r.className="file-tree-item",r.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${p(c)}`,r.addEventListener("click",()=>M(l)),Ke(r,l),d.appendChild(r)}else d.innerHTML="";const a=s.files||[];for(const l of a){const c=l.split("/").pop()||l.split("\\").pop(),r=mt(l);let g="",H="";if(r)switch(r){case"M":g="git-mod",H='<span class="git-file-status M">M</span>';break;case"A":g="git-add",H='<span class="git-file-status A">A</span>';break;case"D":g="git-del",H='<span class="git-file-status D">D</span>';break;case"?":g="git-untracked",H='<span class="git-file-status ?">?</span>';break;case"R":g="git-mod",H='<span class="git-file-status R">R</span>';break}const N=document.createElement("div");N.className="file-tree-item file"+(g?" "+g:""),N.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${H}${p(c)}`,N.addEventListener("click",()=>St(l)),d.appendChild(N)}}catch{d.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function Ct(e){const t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function St(e){Q=e,w.style.display="none",f&&(re(),f.destroy(),f=null,u=null),V(null),W(),R.style.display="none",O.style.display="flex",it.textContent=e,E.textContent="Loading...",_.style.display="none";try{const t=await fetch(v("/api/file?path="+encodeURIComponent(e)));if(!t.ok){const s=await t.json();E.textContent=s.error||"Failed to load",U.value="";return}const n=await t.json();U.value=n.content,ee=n.content,Ie=n.content,E.textContent=n.size+" bytes",_.style.display=""}catch{E.textContent="Failed to load",U.value=""}}U.addEventListener("input",()=>{ee=U.value}),_.addEventListener("click",async()=>{_.textContent="Saving...",_.disabled=!0;try{const e=await fetch(v("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Q,content:ee})});if(!e.ok){const t=await e.json();E.textContent=t.error||"Save failed";return}Ie=ee,E.textContent="Saved"}catch{E.textContent="Save failed"}finally{_.disabled=!1,_.textContent="Save"}}),ot.addEventListener("click",async()=>{if(confirm("Delete "+Q+"?"))try{const e=await fetch(v("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Q})});if(!e.ok){const t=await e.json();E.textContent=t.error||"Delete failed";return}O.style.display="none",R.style.display="flex",x&&M(x)}catch{E.textContent="Delete failed"}}),at.addEventListener("click",()=>{O.style.display="none",R.style.display="flex",x&&M(x)}),lt.addEventListener("click",async()=>{const e=xe.value.trim();if(!e)return;const t=x+"/"+e;try{const n=await fetch(v("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){const s=await n.json();E.textContent=s.error||"Create failed";return}xe.value="",x&&M(x)}catch{E.textContent="Create failed"}});const de=document.getElementById("force-narrow-toggle");de&&(de.checked=te(),de.addEventListener("change",()=>{try{localStorage.setItem(He,de.checked?"1":"0")}catch{}Ne(),T()})),Ne(),document.getElementById("mode-settings").addEventListener("click",()=>{const e=Te.classList.toggle("open");he.classList.toggle("open",e)}),he.addEventListener("click",()=>{Te.classList.remove("open"),he.classList.remove("open")});let L="",k=!1,C;const q=document.createElement("div");q.className="session-popover-backdrop",document.body.appendChild(q);const S=document.createElement("div");S.id="session-popover",S.className="session-popover",S.style.display="none",S.innerHTML=`<div class="sp-field">
31
+ </div><div class="diff-content">${s}</div></div>`,b.querySelector(".diff-back")?.addEventListener("click",()=>{b.innerHTML=Fe,Le(),m&&b.querySelectorAll(".git-popover-item").forEach(o=>{const a=parseInt(o.dataset.idx||"0",10),l=m.files[a];!l||l.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>Ve(l.path)))}),ze()})}function Lt(e,t,n){if(!t&&!n){ie.textContent="No diff",oe.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}const{html:s,lineCount:i}=qe(t,n);We.textContent=e,ie.textContent=i+" lines",oe.innerHTML=s}function Et(){Ue.style.display="none",le?(w.style.display="",w.classList.add("terminal-pending"),F(le),le=null):u?(w.style.display="",w.classList.add("terminal-pending"),Ke()):R.style.display="flex"}ht.addEventListener("click",Et);function ce(){b.classList.remove("open"),ae.classList.remove("open")}ae.addEventListener("click",ce),document.addEventListener("keydown",e=>{e.key==="Escape"&&(ce(),ve())});async function Je(e){try{const n=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(n.path){const s=await fetch("/api/git/status?path="+encodeURIComponent(n.path));if(s.ok){const i=await s.json();m=i,q(i);return}}}catch{}m=null,q(null)}let re=null;function Ke(){de(),u&&(Je(u),re=setInterval(()=>{u&&Je(u)},3e4))}function de(){re&&(clearInterval(re),re=null)}async function Ee(e){let t=e;if(t.startsWith("~"))try{const s=await(await fetch(g("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof s.path=="string"&&s.path&&(t=s.path)}catch{}t=t.replace(/\/+$/,"")||"/",it(t)}function Ye(e,t){const n=document.createElement("button");n.className="file-tree-bot-btn",n.innerHTML=Q("add",'width="12" height="12"'),n.title=`Create bot in ${t}`,n.setAttribute("aria-label",`Create bot in ${t}`),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),Ee(t)}),e.appendChild(n)}function kt(){if(se=j.fsRoots||[],se.length===0){if(u){St(u);return}M("");return}d.innerHTML="";for(const e of se){const t=document.createElement("div");t.className="file-tree-item",t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${p(e)}`,t.addEventListener("click",()=>M(e)),Ye(t,e),d.appendChild(t)}}async function St(e){d.innerHTML='<div class="file-tree-empty">Loading...</div>';try{const n=await(await fetch(g("/api/fs/session-path?session="+encodeURIComponent(e)))).json();n.path?M(n.path):d.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{d.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function M(e){T=e,d.innerHTML='<div class="file-tree-empty">Loading...</div>';const t=vt(e);try{const s=await(await fetch(g("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof s.path=="string"&&s.path?s.path:e;if(i&&(T=i),await t,d.innerHTML="",i){const l=document.createElement("div");l.className="file-tree-item file-tree-create-bot",l.innerHTML=`<span class="file-tree-bot-plus">${Q("add",'width="11" height="11"')}</span> Create bot in this folder`,l.title=`Create bot in ${i}`,l.addEventListener("click",()=>void Ee(i)),d.appendChild(l)}q(m),d.innerHTML+=yt();const o=Ct(i||e);if(o&&!se.some(c=>i===c)){const c=document.createElement("div");c.className="file-tree-item",c.innerHTML="..",c.addEventListener("click",()=>M(o)),d.appendChild(c)}if(s.dirs)for(const l of s.dirs){const c=l.split("/").pop()||l.split("\\").pop(),r=document.createElement("div");r.className="file-tree-item",r.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${p(c)}`,r.addEventListener("click",()=>M(l)),Ye(r,l),d.appendChild(r)}else d.innerHTML="";const a=s.files||[];for(const l of a){const c=l.split("/").pop()||l.split("\\").pop(),r=gt(l);let v="",H="";if(r)switch(r){case"M":v="git-mod",H='<span class="git-file-status M">M</span>';break;case"A":v="git-add",H='<span class="git-file-status A">A</span>';break;case"D":v="git-del",H='<span class="git-file-status D">D</span>';break;case"?":v="git-untracked",H='<span class="git-file-status ?">?</span>';break;case"R":v="git-mod",H='<span class="git-file-status R">R</span>';break}const N=document.createElement("div");N.className="file-tree-item file"+(v?" "+v:""),N.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${H}${p(c)}`,N.addEventListener("click",()=>Bt(l)),d.appendChild(N)}}catch{d.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function Ct(e){const t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function Bt(e){ee=e,w.style.display="none",f&&(de(),f.destroy(),f=null,u=null),q(null),z(),R.style.display="none",U.style.display="flex",ot.textContent=e,E.textContent="Loading...",_.style.display="none";try{const t=await fetch(g("/api/file?path="+encodeURIComponent(e)));if(!t.ok){const s=await t.json();E.textContent=s.error||"Failed to load",W.value="";return}const n=await t.json();W.value=n.content,te=n.content,Te=n.content,E.textContent=n.size+" bytes",_.style.display=""}catch{E.textContent="Failed to load",W.value=""}}W.addEventListener("input",()=>{te=W.value}),_.addEventListener("click",async()=>{_.textContent="Saving...",_.disabled=!0;try{const e=await fetch(g("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:ee,content:te})});if(!e.ok){const t=await e.json();E.textContent=t.error||"Save failed";return}Te=te,E.textContent="Saved"}catch{E.textContent="Save failed"}finally{_.disabled=!1,_.textContent="Save"}}),at.addEventListener("click",async()=>{if(confirm("Delete "+ee+"?"))try{const e=await fetch(g("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:ee})});if(!e.ok){const t=await e.json();E.textContent=t.error||"Delete failed";return}U.style.display="none",R.style.display="flex",T&&M(T)}catch{E.textContent="Delete failed"}}),lt.addEventListener("click",()=>{U.style.display="none",R.style.display="flex",T&&M(T)}),ct.addEventListener("click",async()=>{const e=xe.value.trim();if(!e)return;const t=T+"/"+e;try{const n=await fetch(g("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){const s=await n.json();E.textContent=s.error||"Create failed";return}xe.value="",T&&M(T)}catch{E.textContent="Create failed"}});const pe=document.getElementById("force-narrow-toggle");pe&&(pe.checked=ne(),pe.addEventListener("change",()=>{try{localStorage.setItem(Ne,pe.checked?"1":"0")}catch{}Re(),x()})),Re(),document.getElementById("mode-settings").addEventListener("click",()=>{const e=Me.classList.toggle("open");be.classList.toggle("open",e)}),be.addEventListener("click",()=>{Me.classList.remove("open"),be.classList.remove("open")});let L="",k=!1,S;const V=document.createElement("div");V.className="session-popover-backdrop",document.body.appendChild(V);const C=document.createElement("div");C.id="session-popover",C.className="session-popover",C.style.display="none",C.innerHTML=`<div class="sp-field">
32
32
  <label>Rename session</label>
33
33
  <input type="text" id="sp-name" />
34
34
  </div>
@@ -38,5 +38,5 @@ import{initTerminal as tt}from"./terminal-core.js";import{initBots as nt,openNew
38
38
  <button class="btn danger sp-delete" id="sp-delete">Delete</button>
39
39
  </div>
40
40
  <hr class="sp-divider" id="sp-divider" />
41
- <button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>`,document.body.appendChild(S);function Bt(e){const t=e.getBoundingClientRect(),n=window.innerHeight,s=S.offsetHeight||240;let i=t.bottom+4;i+s>n-8&&(i=Math.max(8,t.top-s-4)),S.style.top=i+"px",S.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}let Ot="";function pe(e,t,n){L=e,k=!!n?.tombstone,C=n?.agentId;const s=document.getElementById("sp-name");s.value=e;const i=S.querySelector(".sp-field label");i.textContent=k?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const o=document.getElementById("sp-rebuild");o.style.display=k?"":"none";const a=document.getElementById("sp-delete");a.textContent=k?"\u5220\u9664\u8BB0\u5F55":"Delete",a.title=k?"\u5220\u9664\u5931\u6548\u8BB0\u5F55\uFF08\u5893\u7891\u6D88\u5931\uFF09":"Delete session";const l=document.getElementById("sp-divider");l&&(l.style.display=k?"":"none");const c=document.getElementById("sp-save");c.textContent=k?"\u91CD\u547D\u540D":"Save",q.classList.add("open"),S.style.display="block",Bt(t),setTimeout(()=>s.focus(),50)}function $(){q.classList.remove("open"),S.style.display="none"}q.addEventListener("click",$),document.getElementById("sp-save").addEventListener("click",async()=>{const e=document.getElementById("sp-name").value.trim();if(!e||e===L){$();return}try{const t=k?{oldName:L,newName:e,agentId:C}:{oldName:L,newName:e,...C?{agentId:C}:{}};if(!(await fetch(v(k?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;$(),T(),!k&&u===L&&(C??null)===h&&F(e,C)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+L+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{const e=await fetch(v("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:C})});if(!e.ok){const t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}$(),T()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(k){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+L+'"\uFF1F'))return;try{if(!(await fetch(v("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:C})})).ok)return;$(),T()}catch{}return}if(confirm('Delete session "'+L+'"?'))try{if(!(await fetch(v("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,...C?{agentId:C}:{}})})).ok)return;$(),u===L&&(C??null)===h&&(f&&(f.destroy(),f=null),u=null,w.style.display="none",R.style.display="flex"),T()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",$);const Ye={esc:"\x1B",tab:" ","s-tab":"\x1B[Z",up:"\x1B[A",down:"\x1B[B",left:"\x1B[D",right:"\x1B[C",space:" ",enter:"\r","ctrl-r":"","ctrl-c":"",btw:"/btw ",yes:"yes\r"},fe=document.getElementById("mobile-keys"),It=new Set(["up","down","left","right","tab","s-tab","space"]),xt=400,Tt=80;let J=0,ue=0,me=!1;function Mt(){J&&(clearTimeout(J),J=0),ue&&(clearInterval(ue),ue=0)}fe.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),fe.addEventListener("pointerdown",e=>{const t=e.target.closest("button[data-key]");if(!t)return;const n=t.dataset.key;It.has(n)&&(me=!1,J=setTimeout(()=>{J=0,me=!0,ue=setInterval(()=>{const s=Ye[n];s&&f&&f.sendInput(s)},Tt)},xt))});for(const e of["pointerup","pointercancel","pointerleave"])fe.addEventListener(e,Mt);fe.addEventListener("click",e=>{const t=e.target.closest("button[data-key]");if(!t||!f)return;if(me){me=!1;return}const n=Ye[t.dataset.key];n&&(f.sendInput(n),f.focus())});const B=document.getElementById("mk-input"),Xe=document.getElementById("mk-send");function Ze(){if(!B||!f)return;const e=B.value;e&&(f.sendInput(e+"\r"),B.value="",B.rows=1,f.focus())}if(B&&(B.addEventListener("input",()=>{B.rows=1;const e=B.value.split(`
42
- `).length;B.rows=Math.min(e,4)}),B.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Ze())})),Xe&&Xe.addEventListener("click",Ze),window.visualViewport){const e=document.querySelector(".app-layout"),t=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",t),window.addEventListener("orientationchange",()=>setTimeout(t,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}const Ee=document.getElementById("process-panel"),K=document.getElementById("proc-list"),Ht=document.getElementById("proc-close"),ke=document.getElementById("proc-backdrop"),Nt=document.getElementById("header-ram");function Rt(){K.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(v("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){K.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(const n of e){const s=n.rss,i=s<1048576?(s/1024).toFixed(0)+"K":(s/1048576).toFixed(1)+"M";t+='<div class="proc-row" data-pid="'+n.pid+'"><span class="proc-mem">'+n.mem+'%</span><span class="proc-rss">'+i+'</span><span class="proc-cmd" title="'+p(n.command)+'">'+p(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">&times;</button></div>'}K.innerHTML=t;for(const n of K.querySelectorAll(".proc-row")){const s=n.querySelector(".proc-kill");s&&s.addEventListener("click",i=>{const o=i.target.closest(".proc-row");!o||!confirm("Kill PID "+o.dataset.pid+"?")||fetch(v("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(o.dataset.pid,10)})}).then(a=>a.json()).then(a=>{a.ok?o.style.opacity="0.3":alert("Failed: "+(a.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{K.innerHTML='<div class="proc-empty">Failed to load</div>'})}function _t(){Ee.classList.add("open"),ke.classList.add("open"),Rt()}function ve(){Ee.classList.remove("open"),ke.classList.remove("open")}Nt.addEventListener("click",e=>{e.stopPropagation(),Ee.classList.contains("open")?ve():_t()}),Ht.addEventListener("click",ve),ke.addEventListener("click",ve);const $t=2e3;let Y=null,Ce=null;const P=new Map,D=new Map,At=5e3,Qe=new Map;function Se(e,t){return(t?"a:"+t+":":"l:")+e}function Pt(e,t,n){const s=Se(e,t);if(n==="working"){const r=Qe.get(s);if(r&&Date.now()<r)return}const i=D.get(s),o=e===u&&(t??null)===h,a=n==="idle"&&i?.state==="working";D.set(s,{session:e,agentId:t,state:n,doneUntil:a?Date.now()+$t:void 0,unread:a?!o:!1});const l=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',c=d.querySelector(l);c&&ge(c,s,D.get(s))}function ge(e,t,n){const s=P.get(t);s&&(clearTimeout(s),P.delete(t)),e.classList.remove("working","just-done");const i=n.session===u&&(n.agentId??null)===h;n.state==="working"?e.classList.add("working"):i&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),P.set(t,setTimeout(()=>{e.classList.remove("just-done"),P.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!i&&n.unread&&e.classList.add("just-done")}function Be(){for(const[e,t]of D){const n=t.agentId?'.session-item[data-agent="'+CSS.escape(t.agentId)+'"][data-session="'+CSS.escape(t.session)+'"]':'.session-item[data-session="'+CSS.escape(t.session)+'"]:not([data-agent])',s=d.querySelector(n);s&&ge(s,e,t)}}function Dt(e,t){const n=Se(e,t),s=D.get(n);if(!s)return;const i=P.get(n);i&&(clearTimeout(i),P.delete(n)),s.doneUntil=void 0,s.unread=!1;const o=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',a=d.querySelector(o);a&&ge(a,n,s)}function et(){if(Y||Ce)return;const e=localStorage.getItem("tmux-web-token");let n=(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws/activity";e&&(n+="?token="+encodeURIComponent(e));try{const s=new WebSocket(n);Y=s,s.onmessage=i=>{try{const o=JSON.parse(String(i.data));o&&o.type==="session.activity"&&typeof o.session=="string"&&Pt(o.session,o.agentId||void 0,o.state==="working"?"working":"idle")}catch{}},s.onclose=()=>{Y===s&&(Y=null,Ce=setTimeout(()=>{Ce=null,et()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{Y=null}}window.__openSession=F,window.__refreshSidebar=T,T(),W(),Be(),et(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Be()}),setInterval(()=>{document.visibilityState==="visible"&&T()},1e4),nt();
41
+ <button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>`,document.body.appendChild(C);function It(e){const t=e.getBoundingClientRect(),n=window.innerHeight,s=C.offsetHeight||240;let i=t.bottom+4;i+s>n-8&&(i=Math.max(8,t.top-s-4)),C.style.top=i+"px",C.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}let zt="";function fe(e,t,n){L=e,k=!!n?.tombstone,S=n?.agentId;const s=document.getElementById("sp-name");s.value=e;const i=C.querySelector(".sp-field label");i.textContent=k?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const o=document.getElementById("sp-rebuild");o.style.display=k?"":"none";const a=document.getElementById("sp-delete");a.textContent=k?"\u5220\u9664\u8BB0\u5F55":"Delete",a.title=k?"\u5220\u9664\u5931\u6548\u8BB0\u5F55\uFF08\u5893\u7891\u6D88\u5931\uFF09":"Delete session";const l=document.getElementById("sp-divider");l&&(l.style.display=k?"":"none");const c=document.getElementById("sp-save");c.textContent=k?"\u91CD\u547D\u540D":"Save",V.classList.add("open"),C.style.display="block",It(t),setTimeout(()=>s.focus(),50)}function $(){V.classList.remove("open"),C.style.display="none"}V.addEventListener("click",$),document.getElementById("sp-save").addEventListener("click",async()=>{const e=document.getElementById("sp-name").value.trim();if(!e||e===L){$();return}try{const t=k?{oldName:L,newName:e,agentId:S}:{oldName:L,newName:e,...S?{agentId:S}:{}};if(!(await fetch(g(k?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;$(),x(),!k&&u===L&&(S??null)===h&&F(e,S)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+L+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{const e=await fetch(g("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:S})});if(!e.ok){const t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}$(),x()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(k){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+L+'"\uFF1F'))return;try{if(!(await fetch(g("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:S})})).ok)return;$(),x()}catch{}return}if(confirm('Delete session "'+L+'"?'))try{if(!(await fetch(g("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,...S?{agentId:S}:{}})})).ok)return;$(),u===L&&(S??null)===h&&(f&&(f.destroy(),f=null),u=null,w.style.display="none",R.style.display="flex"),x()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",$);const Xe={esc:"\x1B",tab:" ","s-tab":"\x1B[Z",up:"\x1B[A",down:"\x1B[B",left:"\x1B[D",right:"\x1B[C",space:" ",enter:"\r","ctrl-r":"","ctrl-c":"",btw:"/btw ",yes:"yes\r"},ue=document.getElementById("mobile-keys"),Tt=new Set(["up","down","left","right","tab","s-tab","space"]),xt=400,Mt=80;let J=0,me=0,ge=!1;function Ht(){J&&(clearTimeout(J),J=0),me&&(clearInterval(me),me=0)}ue.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),ue.addEventListener("pointerdown",e=>{const t=e.target.closest("button[data-key]");if(!t)return;const n=t.dataset.key;Tt.has(n)&&(ge=!1,J=setTimeout(()=>{J=0,ge=!0,me=setInterval(()=>{const s=Xe[n];s&&f&&f.sendInput(s)},Mt)},xt))});for(const e of["pointerup","pointercancel","pointerleave"])ue.addEventListener(e,Ht);ue.addEventListener("click",e=>{const t=e.target.closest("button[data-key]");if(!t||!f)return;if(ge){ge=!1;return}const n=Xe[t.dataset.key];n&&(f.sendInput(n),f.focus())});const B=document.getElementById("mk-input"),Ze=document.getElementById("mk-send");function Qe(){if(!B||!f)return;const e=B.value;e&&(f.sendInput(e+"\r"),B.value="",B.rows=1,f.focus())}if(B&&(B.addEventListener("input",()=>{B.rows=1;const e=B.value.split(`
42
+ `).length;B.rows=Math.min(e,4)}),B.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Qe())})),Ze&&Ze.addEventListener("click",Qe),window.visualViewport){const e=document.querySelector(".app-layout"),t=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",t),window.addEventListener("orientationchange",()=>setTimeout(t,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}const ke=document.getElementById("process-panel"),K=document.getElementById("proc-list"),Nt=document.getElementById("proc-close"),Se=document.getElementById("proc-backdrop"),Rt=document.getElementById("header-ram");function _t(){K.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(g("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){K.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(const n of e){const s=n.rss,i=s<1048576?(s/1024).toFixed(0)+"K":(s/1048576).toFixed(1)+"M";t+='<div class="proc-row" data-pid="'+n.pid+'"><span class="proc-mem">'+n.mem+'%</span><span class="proc-rss">'+i+'</span><span class="proc-cmd" title="'+p(n.command)+'">'+p(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">&times;</button></div>'}K.innerHTML=t;for(const n of K.querySelectorAll(".proc-row")){const s=n.querySelector(".proc-kill");s&&s.addEventListener("click",i=>{const o=i.target.closest(".proc-row");!o||!confirm("Kill PID "+o.dataset.pid+"?")||fetch(g("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(o.dataset.pid,10)})}).then(a=>a.json()).then(a=>{a.ok?o.style.opacity="0.3":alert("Failed: "+(a.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{K.innerHTML='<div class="proc-empty">Failed to load</div>'})}function $t(){ke.classList.add("open"),Se.classList.add("open"),_t()}function ve(){ke.classList.remove("open"),Se.classList.remove("open")}Rt.addEventListener("click",e=>{e.stopPropagation(),ke.classList.contains("open")?ve():$t()}),Nt.addEventListener("click",ve),Se.addEventListener("click",ve);const At=2e3;let Y=null,Ce=null;const P=new Map,D=new Map,Pt=5e3,et=new Map;function Be(e,t){return(t?"a:"+t+":":"l:")+e}function Dt(e,t,n){const s=Be(e,t);if(n==="working"){const r=et.get(s);if(r&&Date.now()<r)return}const i=D.get(s),o=e===u&&(t??null)===h,a=n==="idle"&&i?.state==="working";D.set(s,{session:e,agentId:t,state:n,doneUntil:a?Date.now()+At:void 0,unread:a?!o:!1});const l=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',c=d.querySelector(l);c&&ye(c,s,D.get(s))}function ye(e,t,n){const s=P.get(t);s&&(clearTimeout(s),P.delete(t)),e.classList.remove("working","just-done");const i=n.session===u&&(n.agentId??null)===h;n.state==="working"?e.classList.add("working"):i&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),P.set(t,setTimeout(()=>{e.classList.remove("just-done"),P.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!i&&n.unread&&e.classList.add("just-done")}function Ie(){for(const[e,t]of D){const n=t.agentId?'.session-item[data-agent="'+CSS.escape(t.agentId)+'"][data-session="'+CSS.escape(t.session)+'"]':'.session-item[data-session="'+CSS.escape(t.session)+'"]:not([data-agent])',s=d.querySelector(n);s&&ye(s,e,t)}}function jt(e,t){const n=Be(e,t),s=D.get(n);if(!s)return;const i=P.get(n);i&&(clearTimeout(i),P.delete(n)),s.doneUntil=void 0,s.unread=!1;const o=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',a=d.querySelector(o);a&&ye(a,n,s)}function tt(){if(Y||Ce)return;const e=localStorage.getItem("tmux-web-token");let n=(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws/activity";e&&(n+="?token="+encodeURIComponent(e));try{const s=new WebSocket(n);Y=s,s.onmessage=i=>{try{const o=JSON.parse(String(i.data));o&&o.type==="session.activity"&&typeof o.session=="string"&&Dt(o.session,o.agentId||void 0,o.state==="working"?"working":"idle")}catch{}},s.onclose=()=>{Y===s&&(Y=null,Ce=setTimeout(()=>{Ce=null,tt()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{Y=null}}window.__openSession=F,window.__refreshSidebar=x,x(),z(),Ie(),tt(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Ie()}),setInterval(()=>{document.visibilityState==="visible"&&x()},1e4),st();
@@ -1,4 +1,4 @@
1
- import{execFileSync as v}from"node:child_process";import{mkdirSync as m,readFileSync as w,rmSync as x,writeFileSync as I}from"node:fs";import p from"node:path";import k from"node:os";import{getBotStore as A}from"./store.js";import{materialize as B}from"./materialize.js";import{PiRpc as M}from"./rpc.js";import{buildCatalog as O,ORCHESTRATION_TOOLS as j,READONLY_TOOLS as D}from"./catalog.js";import{TERMINAL_STATUSES as d}from"./types.js";const f=4,E=8;class P{store=A();token;apiBase;runtimes=new Map;sockets=new Map;listeners=new Set;approvals=new Map;recent=new Map;constructor(t){this.token=this.store.token,this.apiBase=`http://127.0.0.1:${t}/api/bots`;for(const e of this.store.listInstances()){let s=!1;!d.includes(e.status)&&e.status!=="queued"&&(e.status="stale",s=!0);const n=g(e.runtimeMode);n!==e.runtimeMode&&(e.runtimeMode=n,s=!0),s&&this.store.saveInstance(e)}}listTemplates(){return this.store.listTemplates()}getTemplate(t){return this.store.getTemplate(t)}saveTemplate(t){return this.store.saveTemplate(t)}deleteTemplate(t){return this.store.deleteTemplate(t)}catalog(){return O()}listBots(t={}){return this.store.listInstances().filter(s=>!(t.project&&s.projectPath!==t.project||t.parentBotId&&s.parentBotId!==t.parentBotId||t.status&&s.status!==t.status))}getBot(t){return this.store.getInstance(t)}children(t){return this.store.listInstances().filter(e=>e.parentBotId===t)}createInstance(t){const e=this.getTemplate(t.templateId);if(!e)throw new Error(`unknown template: ${t.templateId}`);let s=null;if(t.parentBotId){if(s=this.getBot(t.parentBotId),!s)throw new Error("parent bot not found");if(s.depth+1>f)throw new Error(`nesting depth limit is ${f}`)}let n=t.projectPath||s?.projectPath||process.env.HOME||"/";n==="~"?n=k.homedir():n.startsWith("~/")&&(n=p.join(k.homedir(),n.slice(2)));const r=p.resolve(n),o=this.store.newId(),i=t.isolation||"shared";let a=r;if(i==="worktree"){const h=p.join(this.store.root,"worktrees",o);try{m(p.dirname(h),{recursive:!0,mode:448}),v("git",["-C",r,"worktree","add","-b",`tw-bot/${o.slice(0,8)}`,h],{timeout:2e4,stdio:"ignore"}),a=h}catch{a=r}}const c=new Date().toISOString(),u={id:o,templateId:e.id,title:t.title||e.manifest.name,projectPath:r,workspacePath:a,isolation:i,parentBotId:s?.id,depth:s?s.depth+1:0,runtimeMode:g(t.runtimeMode||e.manifest.permissions?.runtimeMode),projectResources:e.manifest.projectResources||"ignore",status:"queued",sessionFile:p.join(this.store.sessionsDir(o),`${o}.jsonl`),createdAt:c,updatedAt:c,model:e.manifest.model};return m(this.store.sessionsDir(o),{recursive:!0,mode:448}),this.store.saveInstance(u),this.emit(u.id,{type:"status",status:"queued",at:c}),this.pump(),u}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)>=E||this.start(t))}start(t){const e=this.getTemplate(t.templateId);if(!e){this.setStatus(t.id,"failed","template disappeared");return}const s=B(e,t,{apiBase:this.apiBase,token:this.token}),n=e.manifest.binaryPath||"pi",r=new M({command:n,args:s.args,cwd:t.workspacePath,env:s.env,onEvent:o=>this.handleEvent(t.id,o),onStderr:o=>{/error|failed/i.test(o)&&this.emit(t.id,{type:"notice",level:"warn",text:o.slice(0,500),at:new Date().toISOString()})},onExit:()=>{this.runtimes.delete(t.id);const o=this.store.getInstance(t.id);o&&!d.includes(o.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.setStatus(t,"running");break;case"agent_end":break;case"agent_settled":this.setStatus(t,e.aborted===!0?"cancelled":"completed");break;case"message_start":case"message_end":{const r=e.message;if(r){if(s==="message_end"&&r.role==="assistant"){const o=this.store.getInstance(t),i=b(r);o&&i&&(o.lastText=i,this.store.saveInstance(o))}this.emit(t,{type:"message",message:r,at:n})}break}case"message_update":{const r=e.assistantMessageEvent;if(!r)break;const o=r.type==="text_delta"?"text":r.type==="thinking_delta"?"thinking":r.type==="toolcall_delta"?"tool-args":null;if(!o)break;const i=e.message;this.emit(t,{type:"delta",kind:o,delta:String(r.delta||""),contentIndex:typeof r.contentIndex=="number"?r.contentIndex:void 0,messageId:typeof i?.id=="string"?i.id:void 0,at:n});break}case"tool_execution_start":this.emit(t,{type:"tool",phase:"start",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),args:e.args,at:n});break;case"tool_execution_update":this.emit(t,{type:"tool",phase:"update",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:_(e.partialResult),at:n});break;case"tool_execution_end":this.emit(t,{type:"tool",phase:"end",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:_(e.result),isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,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 o=String(e.id||""),i=o?this.approvals.get(t)?.get(o):void 0;if(i&&i.state==="pending")return;const a=String(e.title||"Approval required"),c=/^Allow (.+?)\?$/.exec(a),u={id:String(e.id||""),botId:t,botTitle:r?.title||t,kind:s==="confirm"?"tool":"question",method:s,title:a,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(u.id,u),r&&r.runtimeMode==="parent-supervised"&&r.parentBotId){const h=this.store.getInstance(r.parentBotId);if(h){u.escalatedTo=h.id;const S=u.message?u.message.slice(0,500):"",T=[`Child bot "${r.title}" (${r.id}) needs approval: ${u.title}`,S?`Arguments: ${S}`:"",`Decide with bot_approve({ botId: "${r.id}", requestId: "${u.id}", allow: true|false, reason: "..." }).`,"If you do nothing the user will answer it."].filter(Boolean).join(`
2
- `);this.input(h.id,T,"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:u,at:n})}allowTool(t,e){if(!this.store.getInstance(t))throw new Error("bot not found");const n=p.join(this.store.agentDir(t),".allowed-tools");let r=[];try{r=JSON.parse(w(n,"utf8")),Array.isArray(r)||(r=[])}catch{r=[]}return r.includes(e)||r.push(e),m(p.dirname(n),{recursive:!0,mode:448}),I(n,`${JSON.stringify(r)}
1
+ import{execFileSync as v}from"node:child_process";import{mkdirSync as m,readFileSync as w,rmSync as x,writeFileSync as I}from"node:fs";import p from"node:path";import k from"node:os";import{getBotStore as A}from"./store.js";import{materialize as B}from"./materialize.js";import{PiRpc as M}from"./rpc.js";import{buildCatalog as O,ORCHESTRATION_TOOLS as j,READONLY_TOOLS as D}from"./catalog.js";import{TERMINAL_STATUSES as d}from"./types.js";const f=4,_=8,P=["starting","running","waiting_input","waiting_approval"];class b{store=A();token;apiBase;runtimes=new Map;sockets=new Map;listeners=new Set;approvals=new Map;recent=new Map;streaming=new Set;constructor(t){this.token=this.store.token,this.apiBase=`http://127.0.0.1:${t}/api/bots`;for(const e of this.store.listInstances()){let s=!1;!d.includes(e.status)&&e.status!=="queued"&&(e.status="stale",s=!0);const n=g(e.runtimeMode);n!==e.runtimeMode&&(e.runtimeMode=n,s=!0),s&&this.store.saveInstance(e)}}listTemplates(){return this.store.listTemplates()}getTemplate(t){return this.store.getTemplate(t)}saveTemplate(t){return this.store.saveTemplate(t)}deleteTemplate(t){return this.store.deleteTemplate(t)}catalog(){return O()}listBots(t={}){return this.store.listInstances().filter(s=>!(t.project&&s.projectPath!==t.project||t.parentBotId&&s.parentBotId!==t.parentBotId||t.status&&s.status!==t.status))}getBot(t){return this.store.getInstance(t)}children(t){return this.store.listInstances().filter(e=>e.parentBotId===t)}createInstance(t){const e=this.getTemplate(t.templateId);if(!e)throw new Error(`unknown template: ${t.templateId}`);let s=null;if(t.parentBotId){if(s=this.getBot(t.parentBotId),!s)throw new Error("parent bot not found");if(s.depth+1>f)throw new Error(`nesting depth limit is ${f}`)}let n=t.projectPath||s?.projectPath||process.env.HOME||"/";n==="~"?n=k.homedir():n.startsWith("~/")&&(n=p.join(k.homedir(),n.slice(2)));const r=p.resolve(n),o=this.store.newId(),i=t.isolation||"shared";let u=r;if(i==="worktree"){const h=p.join(this.store.root,"worktrees",o);try{m(p.dirname(h),{recursive:!0,mode:448}),v("git",["-C",r,"worktree","add","-b",`tw-bot/${o.slice(0,8)}`,h],{timeout:2e4,stdio:"ignore"}),u=h}catch{u=r}}const a=new Date().toISOString(),c={id:o,templateId:e.id,title:t.title||e.manifest.name,projectPath:r,workspacePath:u,isolation:i,parentBotId:s?.id,depth:s?s.depth+1:0,runtimeMode:g(t.runtimeMode||e.manifest.permissions?.runtimeMode),projectResources:e.manifest.projectResources||"ignore",status:"queued",sessionFile:p.join(this.store.sessionsDir(o),`${o}.jsonl`),createdAt:a,updatedAt:a,model:e.manifest.model};return m(this.store.sessionsDir(o),{recursive:!0,mode:448}),this.store.saveInstance(c),this.emit(c.id,{type:"status",status:"queued",at:a}),this.pump(),c}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=B(e,t,{apiBase:this.apiBase,token:this.token}),n=e.manifest.binaryPath||"pi",r=new M({command:n,args:s.args,cwd:t.workspacePath,env:s.env,onEvent:o=>this.handleEvent(t.id,o),onStderr:o=>{/error|failed/i.test(o)&&this.emit(t.id,{type:"notice",level:"warn",text:o.slice(0,500),at:new Date().toISOString()})},onExit:()=>{this.runtimes.delete(t.id),this.streaming.delete(t.id);const o=this.store.getInstance(t.id);o&&!d.includes(o.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 o=this.store.getInstance(t),i=N(r);o&&i&&(o.lastText=i,this.store.saveInstance(o))}this.emit(t,{type:"message",message:r,at:n})}break}case"message_update":{const r=e.assistantMessageEvent;if(!r)break;const o=r.type==="text_delta"?"text":r.type==="thinking_delta"?"thinking":r.type==="toolcall_delta"?"tool-args":null;if(!o)break;const i=e.message;this.emit(t,{type:"delta",kind:o,delta:String(r.delta||""),contentIndex:typeof r.contentIndex=="number"?r.contentIndex:void 0,messageId:typeof i?.id=="string"?i.id:void 0,at:n});break}case"tool_execution_start":this.emit(t,{type:"tool",phase:"start",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),args:e.args,at:n});break;case"tool_execution_update":this.emit(t,{type:"tool",phase:"update",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:E(e.partialResult),at:n});break;case"tool_execution_end":this.emit(t,{type:"tool",phase:"end",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:E(e.result),isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,at:n});break;case"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 o=String(e.id||""),i=o?this.approvals.get(t)?.get(o):void 0;if(i&&i.state==="pending")return;const u=String(e.title||"Approval required"),a=/^Allow (.+?)\?$/.exec(u),c={id:String(e.id||""),botId:t,botTitle:r?.title||t,kind:s==="confirm"?"tool":"question",method:s,title:u,toolName:a?a[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(c.id,c),r&&r.runtimeMode==="parent-supervised"&&r.parentBotId){const h=this.store.getInstance(r.parentBotId);if(h){c.escalatedTo=h.id;const S=c.message?c.message.slice(0,500):"",T=[`Child bot "${r.title}" (${r.id}) needs approval: ${c.title}`,S?`Arguments: ${S}`:"",`Decide with bot_approve({ botId: "${r.id}", requestId: "${c.id}", allow: true|false, reason: "..." }).`,"If you do nothing the user will answer it."].filter(Boolean).join(`
2
+ `);this.input(h.id,T,"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:c,at:n})}allowTool(t,e){if(!this.store.getInstance(t))throw new Error("bot not found");const n=p.join(this.store.agentDir(t),".allowed-tools");let r=[];try{r=JSON.parse(w(n,"utf8")),Array.isArray(r)||(r=[])}catch{r=[]}return r.includes(e)||r.push(e),m(p.dirname(n),{recursive:!0,mode:448}),I(n,`${JSON.stringify(r)}
3
3
  `,{mode:384}),r}allowedTools(t){try{const e=JSON.parse(w(p.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=g(e),this.store.saveInstance(s);const n=p.join(this.store.agentDir(t),".runtime-mode");m(p.dirname(n),{recursive:!0,mode:448}),I(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",o=!1){const i=this.approvals.get(t)?.get(e);if(!i)throw new Error("approval not found");const a=this.runtimes.get(t);if(!a)throw new Error("bot is not running");const c={type:"extension_ui_response",id:e};i.method==="confirm"?c.confirmed=s:i.method==="select"?c.value=s?i.options?.[0]:i.options?.[1]||i.options?.[0]:s?c.value=n||"":c.cancelled=!0,a.send(c),s&&o&&i.toolName&&this.allowTool(t,i.toolName),i.state=s?"allowed":"denied",i.decidedBy=r,i.reason=n,i.decidedAt=new Date().toISOString();try{this.store.appendEvent(t,{type:"approval",approval:i,at:i.decidedAt})}catch{}return this.broadcast(t,{type:"approval",approval:i,at:i.decidedAt}),this.setStatus(t,"running"),i}listApprovals(){const t=[];for(const[,e]of this.approvals)for(const s of e.values())s.state==="pending"&&t.push(s);return t.sort((e,s)=>e.createdAt.localeCompare(s.createdAt))}async input(t,e,s){const n=this.store.getInstance(t);if(!n)throw new Error("bot not found");if(!this.runtimes.has(t)){this.resume(t);const a=Date.now()+2e4;for(;!this.runtimes.has(t)&&Date.now()<a;)await new Promise(c=>setTimeout(c,150))}const r=this.runtimes.get(t);if(!r)throw new Error("bot is not running");const o=new Date().toISOString();this.emit(t,{type:"user",text:e,at:o});const i={type:"prompt",message:e};s==="steer"&&(i.streamingBehavior="steer"),s==="follow_up"&&(i.streamingBehavior="followUp"),!i.streamingBehavior&&(n.status==="running"||n.status==="waiting_approval")&&(i.streamingBehavior="steer");try{await r.request(i,2e4)}catch(a){const c=a instanceof Error?a.message:String(a);if(!i.streamingBehavior&&/streaming/i.test(c)){await r.request({...i,streamingBehavior:"steer"},2e4);return}throw a}}stop(t,e=!0){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");if(e)for(const n of this.children(t))this.stop(n.id,!0);try{this.runtimes.get(t)?.kill()}catch{}this.runtimes.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.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{}x(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(o=>{const i=this.store.getInstance(o);return!i||d.includes(i.status)});if(r.length)return{bots:r.map(o=>this.result(o))};await new Promise(o=>setTimeout(o,250))}return{timeout:!0,bots:t.map(r=>{const o=this.store.getInstance(r);return{botId:r,status:o?.status||"missing",title:o?.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 g(l){return l==="full-access"?"full-access":l==="parent-supervised"?"parent-supervised":"supervised"}function b(l){const t=l.content;return Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&e.type==="text"?String(e.text||""):"").join("").trim():""}function _(l){if(l==null)return"";if(typeof l=="string")return l;try{return JSON.stringify(l).slice(0,4e3)}catch{return String(l)}}let y=null;function H(){if(!y){const l=Number(process.env.PORT)||21e3;y=new P(l)}return y}export{P as BotManager,E as MAX_CONCURRENT_PER_PROJECT,f as MAX_DEPTH,j as ORCHESTRATION_TOOLS,D as READONLY_TOOLS,H as getBotManager};
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",o=!1){const i=this.approvals.get(t)?.get(e);if(!i)throw new Error("approval not found");const u=this.runtimes.get(t);if(!u)throw new Error("bot is not running");const a={type:"extension_ui_response",id:e};i.method==="confirm"?a.confirmed=s:i.method==="select"?a.value=s?i.options?.[0]:i.options?.[1]||i.options?.[0]:s?a.value=n||"":a.cancelled=!0,u.send(a),s&&o&&i.toolName&&this.allowTool(t,i.toolName),i.state=s?"allowed":"denied",i.decidedBy=r,i.reason=n,i.decidedAt=new Date().toISOString();try{this.store.appendEvent(t,{type:"approval",approval:i,at:i.decidedAt})}catch{}return this.broadcast(t,{type:"approval",approval:i,at:i.decidedAt}),this.setStatus(t,"running"),i}listApprovals(){const t=[];for(const[,e]of this.approvals)for(const s of e.values())s.state==="pending"&&t.push(s);return t.sort((e,s)=>e.createdAt.localeCompare(s.createdAt))}async input(t,e,s){const n=this.store.getInstance(t);if(!n)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(c=>setTimeout(c,150))}const r=this.runtimes.get(t);if(!r){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 i={type:"prompt",message:e},u=this.streaming.has(t)||P.includes(n.status);s==="follow_up"?i.streamingBehavior="followUp":(s==="steer"||u)&&(i.streamingBehavior="steer");try{await r.request(i,3e4)}catch(a){const c=a instanceof Error?a.message:String(a);if(!i.streamingBehavior&&/stream/i.test(c)){await r.request({...i,streamingBehavior:"steer"},3e4);return}throw a}}stop(t,e=!0){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");if(e)for(const 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{}x(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(o=>{const i=this.store.getInstance(o);return!i||d.includes(i.status)});if(r.length)return{bots:r.map(o=>this.result(o))};await new Promise(o=>setTimeout(o,250))}return{timeout:!0,bots:t.map(r=>{const o=this.store.getInstance(r);return{botId:r,status:o?.status||"missing",title:o?.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 g(l){return l==="full-access"?"full-access":l==="parent-supervised"?"parent-supervised":"supervised"}function N(l){const t=l.content;return Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&e.type==="text"?String(e.text||""):"").join("").trim():""}function E(l){if(l==null)return"";if(typeof l=="string")return l;try{return JSON.stringify(l).slice(0,4e3)}catch{return String(l)}}let y=null;function z(){if(!y){const l=Number(process.env.PORT)||21e3;y=new b(l)}return y}export{b as BotManager,_ as MAX_CONCURRENT_PER_PROJECT,f as MAX_DEPTH,j as ORCHESTRATION_TOOLS,D as READONLY_TOOLS,z as getBotManager};
package/dist/lib/icons.js CHANGED
@@ -1 +1 @@
1
- const a={menu:"M3 6h18v2H3V6zm0 5h18v2H3v-2zm0 5h18v2H3v-2z",close:"M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7a1 1 0 1 0-1.41 1.41L10.59 12l-4.89 4.89a1 1 0 1 0 1.41 1.41L12 13.41l4.89 4.89a1 1 0 1 0 1.41-1.41L13.41 12l4.89-4.89a1 1 0 0 0 0-1.4z",search:"M15.5 14h-.79l-.28-.27A6.47 6.47 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z",refresh:"M17.65 6.35A7.96 7.96 0 0 0 12 4a8 8 0 1 0 8 8h-2a6 6 0 1 1-6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z",add:"M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z",edit:"M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM5.92 19H5v-.92l9.06-9.06.92.92L5.92 19zm13.66-12.83a1 1 0 0 0 0-1.41l-1.34-1.34a1 1 0 0 0-1.41 0l-1.05 1.05 2.75 2.75 1.05-1.05z",delete:"M15 4V3H9v1H4v2h1.5l.81 13.05A2 2 0 0 0 8.3 21h7.4a2 2 0 0 0 1.99-1.95L18.5 6H20V4h-5zm-5.5 2h5l-.75 12h-3.5L9.5 6z",check:"M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z",sessions:"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z",notes:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6zm-1 2 5 5h-5V4zM6 20V4h5v7h7v9H6z",schedule:"M19 4h-1V2h-2v2H8V2H6v2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 16H5V10h14v10zM9 14H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2zm-8 4H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2z",agents:"M12 2a5 5 0 1 0 0 10 5 5 0 0 0 0-10zm0 8a3 3 0 1 1 0-6 3 3 0 0 1 0 6zm-7 13v-2a5 5 0 0 1 5-5h4a5 5 0 0 1 5 5v2h2v-2a7 7 0 0 0-7-7H10a7 7 0 0 0-7 7v2h2z",history:"M13 3a9 9 0 0 0-9 9H1l4 4 4-4H6a7 7 0 1 1 7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.96 8.96 0 0 0 13 21a9 9 0 0 0 0-18zm-1 5v5l4.25 2.55.75-1.23-3.5-2.08V8H12z","quick-commands":"M13 3 4 14h7l-1 7 9-11h-7l1-7z",windows:"M4 6h16v2H4V6zm0 5h10v2H4v-2zm0 5h16v2H4v-2z",terminal:"M4 17.6 6.4 20l8-8-8-8L4 6.4 11.6 12 4 17.6zM20 18h-8v2h8v-2z",microphone:"M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5-3c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z",keyboard:"M20 5H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-9 3h2v2h-2V8zm0 3h2v2h-2v-2zM8 8h2v2H8V8zm0 3h2v2H8v-2zm-1 2H5v-2h2v2zm0-3H5V8h2v2zm9 7H8v-2h8v2zm0-4h-2v-2h2v2zm0-3h-2V8h2v2zm3 3h-2v-2h2v2zm0-3h-2V8h2v2z",settings:"M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.488.488 0 0 0-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.484.484 0 0 0-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6a3.6 3.6 0 1 1 0-7.2 3.6 3.6 0 0 1 0 7.2z",pin:"M16 12V4h1V2H7v2h1v8l-4 4v2h5.2v6h1.6v-6H20v-2l-4-4z","pin-outline":"M16 12V4h1V2H7v2h1v8l-4 4v2h5.2v6h1.6v-6H20v-2l-4-4zm-4.8 7.2V11l2-2V4h1.6v5l2 2v5.2H11.2z",folder:"M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z",file:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6zm-1 2 5 5h-5V4zM6 20V4h5v7h7v9H6z",worktree:"M6 3a3 3 0 0 0-1 5.83v6.34a3 3 0 1 0 2 0V8.83A3 3 0 0 0 6 3zm0 2a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm0 12a1 1 0 1 1 0 2 1 1 0 0 1 0-2zM18 3a3 3 0 0 0-1 5.83V9a4 4 0 0 1-4 4h-2a3 3 0 1 0 0 2h2a6 6 0 0 0 6-6v-.17A3 3 0 0 0 18 3zm0 2a1 1 0 1 1 0 2 1 1 0 0 1 0-2zM9 13a1 1 0 1 1 0 2 1 1 0 0 1 0-2z",copy:"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z",export:"M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z",chevronRight:"M9.29 6.71a1 1 0 0 0 0 1.41L13.17 12l-3.88 3.88a1 1 0 1 0 1.41 1.41l4.59-4.59a1 1 0 0 0 0-1.41L10.7 6.7a1 1 0 0 0-1.41.01z",lightning:"M11 21h-1l1-7H7.5c-.58 0-.57-.32-.38-.66.19-.33.51-.89.73-1.27L13 3h1l-1 7h3.5c.49 0 .56.33.47.51l-.07.15c-.22.46-.58 1.18-.78 1.58L11 21z","git-branch":"M13.5 7a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0zm0 10a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0zM11 9.5v5.1a4.03 4.03 0 0 0-3-.1V9.4a4.03 4.03 0 0 0 3 .1z",external:"M14 3h7v7h-2V6l-9.29 9.29-1.41-1.41L17.59 4.5H14V3zm4 16H5V5h7V3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7h-2v7z",play:"M8 5v14l11-7L8 5z",stop:"M6 6h12v12H6V6z",warning:"M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z",info:"M11 7h2v2h-2V7zm0 4h2v6h-2v-6zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z",spinner:"M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46A7.93 7.93 0 0 0 20 12c0-4.42-3.58-8-8-8z",dots:"M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"};function l(h){return a[h]??a.menu}function c(h,v=""){return`<svg viewBox="0 0 24 24" fill="currentColor"${v?" "+v:""}><path d="${l(h)}"/></svg>`}function H(h){return`<path d="${l(h)}"/>`}const m={};function n(h,v){const z=m[h];return z?c(z):v?.trim().startsWith("<svg")?v:`<span style="font-size:18px;line-height:1">${v??""}</span>`}export{n as extIcon,c as icon,l as iconPath,H as iconPathString};
1
+ const a={menu:"M3 6h18v2H3V6zm0 5h18v2H3v-2zm0 5h18v2H3v-2z",close:"M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7a1 1 0 1 0-1.41 1.41L10.59 12l-4.89 4.89a1 1 0 1 0 1.41 1.41L12 13.41l4.89 4.89a1 1 0 1 0 1.41-1.41L13.41 12l4.89-4.89a1 1 0 0 0 0-1.4z",search:"M15.5 14h-.79l-.28-.27A6.47 6.47 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z",refresh:"M17.65 6.35A7.96 7.96 0 0 0 12 4a8 8 0 1 0 8 8h-2a6 6 0 1 1-6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z",add:"M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z",edit:"M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM5.92 19H5v-.92l9.06-9.06.92.92L5.92 19zm13.66-12.83a1 1 0 0 0 0-1.41l-1.34-1.34a1 1 0 0 0-1.41 0l-1.05 1.05 2.75 2.75 1.05-1.05z",delete:"M15 4V3H9v1H4v2h1.5l.81 13.05A2 2 0 0 0 8.3 21h7.4a2 2 0 0 0 1.99-1.95L18.5 6H20V4h-5zm-5.5 2h5l-.75 12h-3.5L9.5 6z",check:"M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z",sessions:"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z",notes:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6zm-1 2 5 5h-5V4zM6 20V4h5v7h7v9H6z",schedule:"M19 4h-1V2h-2v2H8V2H6v2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 16H5V10h14v10zM9 14H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2zm-8 4H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2z",agents:"M12 2a5 5 0 1 0 0 10 5 5 0 0 0 0-10zm0 8a3 3 0 1 1 0-6 3 3 0 0 1 0 6zm-7 13v-2a5 5 0 0 1 5-5h4a5 5 0 0 1 5 5v2h2v-2a7 7 0 0 0-7-7H10a7 7 0 0 0-7 7v2h2z",history:"M13 3a9 9 0 0 0-9 9H1l4 4 4-4H6a7 7 0 1 1 7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.96 8.96 0 0 0 13 21a9 9 0 0 0 0-18zm-1 5v5l4.25 2.55.75-1.23-3.5-2.08V8H12z","quick-commands":"M13 3 4 14h7l-1 7 9-11h-7l1-7z",windows:"M4 6h16v2H4V6zm0 5h10v2H4v-2zm0 5h16v2H4v-2z",terminal:"M4 17.6 6.4 20l8-8-8-8L4 6.4 11.6 12 4 17.6zM20 18h-8v2h8v-2z",microphone:"M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5-3c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z",keyboard:"M20 5H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-9 3h2v2h-2V8zm0 3h2v2h-2v-2zM8 8h2v2H8V8zm0 3h2v2H8v-2zm-1 2H5v-2h2v2zm0-3H5V8h2v2zm9 7H8v-2h8v2zm0-4h-2v-2h2v2zm0-3h-2V8h2v2zm3 3h-2v-2h2v2zm0-3h-2V8h2v2z",bot:"M11 2h2v3h2a3 3 0 0 1 3 3v1h1a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-1v1a3 3 0 0 1-3 3H9a3 3 0 0 1-3-3v-1H5a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2h1V8a3 3 0 0 1 3-3h2V2zm-2 6v1h6V8H9zm-2 5a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3zm10 0a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3z",layers:"M12 2 2 7l10 5 10-5-10-5zm0 7.5L4.5 5.8 12 2l7.5 3.8L12 9.5zM2 12l10 5 10-5-1.9-.95L12 14.9l-8.1-3.85L2 12zm0 4.5 10 5 10-5-1.9-.95L12 19.4l-8.1-3.85-1.9.95z",inbox:"M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2zm0 16H5v-3h3.6a3.5 3.5 0 0 0 6.8 0H19v3zm0-5h-4.7a3.5 3.5 0 0 1-6.6 0H5V5h14v9z","chevron-down":"M7.4 8.6 12 13.2l4.6-4.6L18 10l-6 6-6-6 1.4-1.4z",settings:"M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.488.488 0 0 0-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.484.484 0 0 0-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6a3.6 3.6 0 1 1 0-7.2 3.6 3.6 0 0 1 0 7.2z",pin:"M16 12V4h1V2H7v2h1v8l-4 4v2h5.2v6h1.6v-6H20v-2l-4-4z","pin-outline":"M16 12V4h1V2H7v2h1v8l-4 4v2h5.2v6h1.6v-6H20v-2l-4-4zm-4.8 7.2V11l2-2V4h1.6v5l2 2v5.2H11.2z",folder:"M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z",file:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6zm-1 2 5 5h-5V4zM6 20V4h5v7h7v9H6z",worktree:"M6 3a3 3 0 0 0-1 5.83v6.34a3 3 0 1 0 2 0V8.83A3 3 0 0 0 6 3zm0 2a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm0 12a1 1 0 1 1 0 2 1 1 0 0 1 0-2zM18 3a3 3 0 0 0-1 5.83V9a4 4 0 0 1-4 4h-2a3 3 0 1 0 0 2h2a6 6 0 0 0 6-6v-.17A3 3 0 0 0 18 3zm0 2a1 1 0 1 1 0 2 1 1 0 0 1 0-2zM9 13a1 1 0 1 1 0 2 1 1 0 0 1 0-2z",copy:"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z",export:"M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z",chevronRight:"M9.29 6.71a1 1 0 0 0 0 1.41L13.17 12l-3.88 3.88a1 1 0 1 0 1.41 1.41l4.59-4.59a1 1 0 0 0 0-1.41L10.7 6.7a1 1 0 0 0-1.41.01z",lightning:"M11 21h-1l1-7H7.5c-.58 0-.57-.32-.38-.66.19-.33.51-.89.73-1.27L13 3h1l-1 7h3.5c.49 0 .56.33.47.51l-.07.15c-.22.46-.58 1.18-.78 1.58L11 21z","git-branch":"M13.5 7a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0zm0 10a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0zM11 9.5v5.1a4.03 4.03 0 0 0-3-.1V9.4a4.03 4.03 0 0 0 3 .1z",external:"M14 3h7v7h-2V6l-9.29 9.29-1.41-1.41L17.59 4.5H14V3zm4 16H5V5h7V3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7h-2v7z",play:"M8 5v14l11-7L8 5z",stop:"M6 6h12v12H6V6z",warning:"M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z",info:"M11 7h2v2h-2V7zm0 4h2v6h-2v-6zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z",spinner:"M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46A7.93 7.93 0 0 0 20 12c0-4.42-3.58-8-8-8z",dots:"M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"};function l(h){return a[h]??a.menu}function c(h,v=""){return`<svg viewBox="0 0 24 24" fill="currentColor"${v?" "+v:""}><path d="${l(h)}"/></svg>`}function H(h){return`<path d="${l(h)}"/>`}const m={};function V(h,v){const z=m[h];return z?c(z):v?.trim().startsWith("<svg")?v:`<span style="font-size:18px;line-height:1">${v??""}</span>`}export{V as extIcon,c as icon,l as iconPath,H as iconPathString};