tmux-weblink 2.2.43 → 2.2.45

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 r={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function L(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function f(t,o){const i=await fetch(t,{...o,headers:{"content-type":"application/json",Authorization:`Bearer ${L()}`,...o?.headers||{}}}),n=await i.text(),s=n?JSON.parse(n):null;if(!i.ok)throw new Error(s&&s.error||`HTTP ${i.status}`);return s}function e(t,o,i){const n=document.createElement(t);return o&&(n.className=o),i!==void 0&&(n.textContent=i),n}function _(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 it(){const t=e("div","bots-section");t.id="bots-section";const o=e("div","bots-head"),i=e("span","bots-title","Bots"),n=e("span","bots-badge");n.hidden=!0,i.appendChild(n);const s=e("span","bots-head-actions"),d=e("button","bots-icon-btn","\u2699");d.title="Bot templates",d.onclick=()=>void J();const a=e("button","bots-icon-btn","+");a.title="New bot from template",a.onclick=()=>void bt(),s.append(d,a),o.append(i,s);const c=e("div","bots-list");c.id="bots-list",t.append(o,c);const l=document.querySelector(".sidebar"),u=document.querySelector(".sidebar-footer");return l&&l.insertBefore(t,u||null),{list:c,badge:n}}let $=null,P=null;function M(){if(!$)return;$.textContent="";const t=new Map;for(const n of r.bots){if(n.parentBotId)continue;const s=n.projectPath;t.has(s)||t.set(s,[]),t.get(s).push(n)}t.size===0&&$.appendChild(e("div","bots-empty","No bots yet"));for(const[n,s]of t){const d=e("div","bots-group"),a=e("div","bots-group-label",n.replace(/^.*\//,"")||n);a.title=n;const c=e("button","bots-icon-btn bots-group-add","+");c.title=`New bot in ${n}`,c.onclick=l=>{l.stopPropagation(),et(n)},a.appendChild(c),d.appendChild(a);for(const l of s){d.appendChild(z(l));for(const u of r.bots.filter(m=>m.parentBotId===l.id)){const m=z(u);m.classList.add("bots-row-child"),d.appendChild(m)}}$.appendChild(d)}const o=r.approvals.length;P&&(P.hidden=o===0,P.textContent=String(o));const i=document.getElementById("bv-inbox-count");i&&(i.textContent=o?`(${o})`:"")}function z(t){const o=e("div","bots-row");o.dataset.botId=t.id,t.id===r.activeId&&o.classList.add("active");const i=e("span","bots-dot");i.style.background=_(t.status);const n=e("span","bots-name",t.title),s=e("span","bots-meta",t.status.replace(/_/g," "));return o.append(i,n,s),o.onclick=()=>void K(t.id),o}function st(){const t=e("div","bots-view");t.id="bots-view",t.hidden=!0;const o=e("div","bots-view-head"),i=e("div","bv-title"),n=e("span","bots-dot");n.id="bv-dot";const s=e("span","bv-title-text");s.id="bv-title";const d=e("span","bv-status");d.id="bv-status",i.append(n,s,d);const a=e("div","bv-actions"),c=e("button","btn","Needs you "),l=e("span");l.id="bv-inbox-count",c.appendChild(l),c.onclick=()=>void nt();const u=e("button","btn","Resume");u.onclick=()=>void G(v=>f(`/api/bots/${v}/resume`,{method:"POST"}).then(()=>k(!0)));const m=e("button","btn danger","Stop");m.onclick=()=>void G(v=>f(`/api/bots/${v}/stop`,{method:"POST"}).then(()=>k(!0)));const h=e("button","btn","Delete");h.onclick=()=>{r.activeId&&confirm("Delete this bot and its session?")&&f(`/api/bots/${r.activeId}`,{method:"DELETE"}).then(()=>{R(),k(!0)})};const C=e("button","btn","\u2715");C.onclick=()=>R(),a.append(c,u,m,h,C),o.append(i,a);const B=e("div","bots-messages");B.id="bots-messages";const x=e("div","bots-composer"),g=e("textarea");g.id="bots-input",g.rows=1,g.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",g.onkeydown=v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),F())};const S=e("button","btn primary","Send");S.onclick=()=>void F(),x.append(g,S),t.append(o,B,x),document.querySelector(".main-area")?.appendChild(t),document.getElementById("bots-modal")||ut()}async function F(){const t=document.getElementById("bots-input");if(!t||!r.activeId||!t.value.trim())return;const o=t.value;t.value="";try{await f(`/api/bots/${r.activeId}/input`,{method:"POST",body:JSON.stringify({text:o})})}catch(i){T({kind:"notice",level:"error",text:i instanceof Error?i.message:String(i)})}}function G(t){r.activeId&&t(r.activeId).catch(o=>T({kind:"notice",level:"error",text:o instanceof Error?o.message:String(o)}))}function R(){r.activeId=null;const t=document.getElementById("bots-view");t&&(t.hidden=!0);try{r.ws?.close()}catch{}r.ws=null,M();const o=document.getElementById("main-placeholder");o&&(o.style.display="")}async function K(t){r.activeId=t,r.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 n=document.getElementById("terminal-container");n&&(n.style.display="none");const s=document.getElementById("file-editor");s&&(s.style.display="none"),M(),q();try{r.ws?.close()}catch{}const d=location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(`${d}//${location.host}/ws/bots/${encodeURIComponent(t)}?token=${encodeURIComponent(L())}`);r.ws=a,a.onmessage=c=>{try{X(JSON.parse(String(c.data)))}catch{}},a.onclose=()=>{r.activeId===t&&setTimeout(()=>{r.activeId===t&&k(!0)},1500)},await k(!0)}function V(){return r.bots.find(t=>t.id===r.activeId)||null}function Y(){const t=V();if(!t)return;const o=document.getElementById("bv-title"),i=document.getElementById("bv-status"),n=document.getElementById("bv-dot");o&&(o.textContent=t.title),i&&(i.textContent=`${t.status.replace(/_/g," ")} \xB7 ${t.templateId} \xB7 ${t.projectPath}`),n&&(n.style.background=_(t.status))}function T(t,o=r.activeId){if(!o)return;const i=r.items.get(o)||[];i.push(t),r.items.set(o,i),o===r.activeId&&I()}function I(){r.renderQueued||(r.renderQueued=!0,requestAnimationFrame(()=>{r.renderQueued=!1,q()}))}function q(){const t=document.getElementById("bots-messages");if(!t||!r.activeId)return;const o=r.items.get(r.activeId)||[];t.textContent="";let i=null;for(const n of o)if(n.kind==="user"){const s=e("div","bv-msg bv-user");s.textContent=n.text,t.appendChild(s),i=null}else if(n.kind==="assistant"){const s=e("div","bv-msg bv-assistant");if(n.thinking){const a=e("details","bv-thinking");a.appendChild(e("summary",void 0,"thinking")),a.appendChild(e("div",void 0,n.thinking)),s.appendChild(a)}const d=e("div","bv-text");d.textContent=n.text,s.appendChild(d),t.appendChild(s),i=d}else if(n.kind==="tool")t.appendChild(at(n)),i=null;else if(n.kind==="approval")t.appendChild(dt(n)),i=null;else if(n.kind==="notice"){const s=e("div",`bv-notice bv-notice-${n.level}`,n.text);t.appendChild(s)}i&&(i.scrollTop=i.scrollHeight),t.scrollTop=t.scrollHeight}function at(t){const o=e("details","bv-tool");o.open=t.phase!=="end"||!!t.isError;const i=e("summary"),n=e("span","bv-tool-name",t.name);if(i.appendChild(n),t.phase!=="end"&&i.appendChild(e("span","bv-tool-phase",t.phase)),t.isError&&i.appendChild(e("span","bv-tool-error","error")),typeof t.durationMs=="number"&&i.appendChild(e("span","bv-tool-meta",`${Math.round(t.durationMs)}ms`)),o.appendChild(i),t.args!==void 0){const s=e("pre","bv-pre");s.textContent=typeof t.args=="string"?t.args:JSON.stringify(t.args,null,2),o.appendChild(s)}if(t.output){const s=e("pre","bv-pre bv-output");s.textContent=t.output,o.appendChild(s)}return o}function dt(t){const o=e("div","bv-approval"),i=t.approval;if(o.appendChild(e("div","bv-approval-title",i.title)),i.message&&o.appendChild(e("pre","bv-pre",i.message)),t.decided)return o.appendChild(e("div","bv-approval-decided",t.decided==="allowed"?"Allowed":"Denied")),o;const n=e("input","bv-reason");n.placeholder="reason (optional)";const s=e("div","bv-approval-actions"),d=e("button","btn primary","Allow"),a=e("button","btn danger","Deny"),c=async l=>{try{await f(`/api/bots/${i.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:i.id,allow:l,reason:n.value||void 0})}),t.decided=l?"allowed":"denied",I(),k(!0)}catch(u){T({kind:"notice",level:"error",text:u instanceof Error?u.message:String(u)})}};return d.onclick=()=>void c(!0),a.onclick=()=>void c(!1),s.append(n,d,a),o.appendChild(s),o}function X(t){const o=String(t.type||""),i=r.activeId;if(!i)return;const n=r.items.get(i)||[];if(o==="snapshot")r.items.set(i,[]);else if(o==="user")T({kind:"user",text:String(t.text||"")});else if(o==="status"){const s=V();s&&(s.status=String(t.status||s.status)),Y(),ct()}else if(o==="message"){const s=t.message;if(!s||String(s.role||"")!=="assistant")return;const a=rt(s),c=lt(s),l=n[n.length-1];l&&l.kind==="assistant"?(l.text=a||l.text,l.thinking=c||l.thinking):n.push({kind:"assistant",text:a,thinking:c}),r.items.set(i,n),I()}else if(o==="delta"){const s=String(t.kind||""),d=String(t.delta||"");let a=n[n.length-1];(!a||a.kind!=="assistant")&&(n.push({kind:"assistant",text:"",thinking:""}),a=n[n.length-1]),a.kind==="assistant"&&(s==="text"?a.text+=d:s==="thinking"&&(a.thinking+=d)),r.items.set(i,n),I()}else if(o==="tool"){const s=String(t.callId||""),d=n.find(c=>c.kind==="tool"&&c.callId===s),a=String(t.phase||"start");d?(d.phase=a,a==="update"&&t.output&&(d.output=String(t.output)),a==="end"&&(t.output&&(d.output=String(t.output)),d.isError=t.isError===!0,typeof t.durationMs=="number"&&(d.durationMs=t.durationMs))):n.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}),r.items.set(i,n),I()}else if(o==="approval"){const s=t.approval;if(!s)return;const d=n;for(let a=d.length-1;a>=0;a--){const c=d[a];if(c.kind==="approval"&&c.approval.id===s.id){c.approval=s,s.state!=="pending"&&(c.decided=s.state==="allowed"?"allowed":"denied"),r.items.set(i,d),I();return}}d.push({kind:"approval",approval:s}),r.items.set(i,d),I()}else o==="notice"&&T({kind:"notice",level:String(t.level||"info"),text:String(t.text||"")})}function rt(t){const o=t.content;return Array.isArray(o)?o.map(i=>i&&typeof i=="object"&&i.type==="text"?String(i.text||""):"").join(""):String(t.text||"")}function lt(t){const o=t.content;return Array.isArray(o)?o.map(i=>i&&typeof i=="object"&&i.type==="thinking"?String(i.thinking||""):"").join(""):""}async function k(t=!1){try{const[o,i]=await Promise.all([f("/api/bots"),f("/api/bots/approvals")]);if(r.bots=o,r.approvals=i,M(),Y(),t&&r.activeId){const n=await f(`/api/bots/${r.activeId}/events?limit=300`);pt(n)}}catch{}}async function ct(){try{r.bots=await f("/api/bots"),M()}catch{}}function pt(t){if(r.activeId){r.items.set(r.activeId,[]);for(const o of t)X(o);q()}}function ut(){const t=e("div","bots-modal");t.id="bots-modal",t.hidden=!0;const o=e("div","bots-modal-card"),i=e("div","bots-modal-head"),n=e("span");n.id="bots-modal-title";const s=e("button","btn","\u2715");s.onclick=()=>A(),i.append(n,s);const d=e("div","bots-modal-body");d.id="bots-modal-body",o.append(i,d),t.appendChild(o),t.onclick=a=>{a.target===t&&A()},document.body.appendChild(t)}function H(t){const o=document.getElementById("bots-modal"),i=document.getElementById("bots-modal-title"),n=document.getElementById("bots-modal-body");if(!o||!n)throw new Error("modal missing");return i&&(i.textContent=t),n.textContent="",o.hidden=!1,n}function A(){const t=document.getElementById("bots-modal");t&&(t.hidden=!0)}async function mt(){return r.catalog||(r.catalog=await f("/api/bots/catalog")),r.catalog}async function Z(){return r.templates=await f("/api/bots/templates"),r.templates}async function J(){const t=H("Bot templates"),[o,i]=await Promise.all([mt(),Z()]),n=e("div","bv-template-list");for(const l of i){const u=e("div","bv-template-row");u.appendChild(e("span","bv-template-name",l.manifest.name)),u.appendChild(e("span","bv-template-desc",l.manifest.description||""));const m=e("button","btn","Edit");m.onclick=()=>tt(t,o,l);const h=e("button","btn danger","Delete");h.onclick=()=>{confirm(`Delete template ${l.manifest.name}?`)&&f(`/api/bots/templates/${l.id}`,{method:"DELETE"}).then(()=>J())};const C=e("span","bv-template-actions");C.append(m,h),u.appendChild(C),n.appendChild(u)}i.length===0&&n.appendChild(e("div","bots-empty","No templates yet")),t.appendChild(n);const s=e("div","bv-template-actions"),d=e("button","btn primary","New template");d.onclick=()=>tt(t,o,null);const a=e("button","btn","Export");a.title="Download templates + library as JSON",a.onclick=()=>{(async()=>{try{const l=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${L()}`}});if(!l.ok)throw new Error(`HTTP ${l.status}`);const u=await l.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(l){alert(l instanceof Error?l.message:String(l))}})()};const c=e("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 m=JSON.parse(await u.text()),h=await f("/api/bots/import",{method:"POST",body:JSON.stringify(m)});alert(`Imported ${h.templates} templates, ${h.files} library files (${h.skipped} kept)`),await J()}catch(m){alert(m instanceof Error?m.message:String(m))}})()},l.click()},s.append(d,a,c),t.appendChild(s)}function U(t,o,i){const n=e("div","bv-field");n.appendChild(e("label","bv-label",t));const s=e("div","bv-check-grid"),d=[];for(const a of o){const c=e("label","bv-check"),l=document.createElement("input");l.type="checkbox",l.checked=i.includes(a.id),c.append(l,e("span",void 0,a.label)),a.hint&&(c.title=a.hint),s.appendChild(c),d.push({id:a.id,input:l})}return n.appendChild(s),{element:n,get:()=>d.filter(a=>a.input.checked).map(a=>a.id)}}function tt(t,o,i){t.textContent="";const n=i?JSON.parse(JSON.stringify(i.manifest)):{name:"new-bot",description:""},s=e("input","bv-input");s.value=n.name,s.placeholder="Template name";const d=e("input","bv-input");d.value=n.description||"",d.placeholder="One line description";const a=e("textarea","bv-textarea");a.rows=6,a.value=n.system||"",a.placeholder="System prompt for this bot (written to SYSTEM.md)";const c=U("Skills",o.skills.map(p=>({id:p.id,label:p.name,hint:p.description})),n.skills||[]),l=U("Extensions (Pi builtins + library)",o.extensions.map(p=>({id:p.id,label:`${p.name}${p.kind==="builtin"?" (builtin)":""}`,hint:p.description})),(n.extensions||[]).map(p=>p.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),u=U("Prompt templates",o.prompts.map(p=>({id:p.id,label:p.name})),n.prompts||[]),m=e("select","bv-input");m.appendChild(new Option("none",""));for(const p of o.mcp)m.appendChild(new Option(p.name,p.id));n.mcp&&(m.value=o.mcp.find(p=>JSON.stringify(p.servers)===JSON.stringify(n.mcp?.mcpServers))?.id||"");const h=e("div","bv-field");h.appendChild(e("label","bv-label","Tools (allow list; deny always blocks)"));const C=e("div","bv-check-grid"),B=[];for(const p of o.tools){const E=e("label","bv-check"),y=document.createElement("input");y.type="checkbox",y.checked=(n.tools?.allow||[]).includes(p.name)||!n.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(p.name),E.append(y,e("span",void 0,p.name)),C.appendChild(E),B.push({name:p.name,input:y})}h.appendChild(C);const x=e("input","bv-input");x.value=(n.tools?.deny||[]).join(", "),x.placeholder="Always deny (comma separated), e.g. bash, write";const g=e("textarea","bv-textarea");g.rows=2,g.value=(n.packages||[]).join(`
2
- `),g.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";const S=e("select","bv-input");S.appendChild(new Option("default (Pi settings)",""));for(const p of o.models)S.appendChild(new Option(`${p.provider}/${p.model}`,`${p.provider}
3
- ${p.model}`));n.model?.provider&&n.model?.id&&(S.value=`${n.model.provider}
4
- ${n.model.id}`);const v=e("select","bv-input");for(const p of["","off","minimal","low","medium","high","xhigh","max"])v.appendChild(new Option(p||"default",p));n.model?.thinking&&(v.value=n.model.thinking);const N=e("select","bv-input");for(const p of["supervised","auto-accept-edits","full-access"])N.appendChild(new Option(p,p));N.value=n.permissions?.runtimeMode||"supervised";const O=e("select","bv-input");O.appendChild(new Option("ignore project .pi (recommended)","ignore")),O.appendChild(new Option("inherit project .pi (needs trust)","inherit")),O.value=n.projectResources||"ignore";const W=e("label","bv-check"),j=document.createElement("input");j.type="checkbox",j.checked=!!n.orchestrator,W.append(j,e("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));const w=(p,E)=>{const y=e("div","bv-field");return y.appendChild(e("label","bv-label",p)),y.appendChild(E),y};t.append(w("Name",s),w("Description",d),w("System prompt",a),c.element,l.element,u.element,w("MCP preset",m),h,w("Always deny tools",x),w("Packages",g),w("Model",S),w("Thinking level",v),w("Approval mode",N),w("Project resources",O),W);const Q=e("button","btn primary",i?"Save template":"Create template");Q.onclick=async()=>{const[p,E]=S.value.split(`
5
- `),y=o.mcp.find(b=>b.id===m.value),ot={name:s.value.trim()||"bot",description:d.value.trim()||void 0,system:a.value.trim()||void 0,skills:c.get(),extensions:l.get().map(b=>(b.startsWith("builtin:"),b)),prompts:u.get(),packages:g.value.split(`
6
- `).map(b=>b.trim()).filter(Boolean),mcp:y?{mcpServers:y.servers}:void 0,tools:{allow:B.filter(b=>b.input.checked).map(b=>b.name),deny:x.value.split(",").map(b=>b.trim()).filter(Boolean)},model:p?{provider:p,id:E,thinking:v.value||void 0}:void 0,permissions:{runtimeMode:N.value},projectResources:O.value==="inherit"?"inherit":"ignore",orchestrator:j.checked||void 0};try{await f("/api/bots/templates",{method:"POST",body:JSON.stringify({id:i?.id,manifest:ot})}),A(),await J()}catch(b){alert(b instanceof Error?b.message:String(b))}},t.appendChild(Q)}async function bt(){return et("")}async function et(t){const o=H("New bot"),i=await Z();if(i.length===0){o.appendChild(e("div","bots-empty","Create a template first (\u2699)."));return}const n=e("select","bv-input");for(const u of i)n.appendChild(new Option(u.manifest.name,u.id));const s=e("input","bv-input");s.placeholder="Title (defaults to template name)";const d=e("input","bv-input");d.placeholder="/path/to/project";const a=t||r.bots[0]?.projectPath||"";d.value=a;const c=e("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")),o.append(D("Template",n),D("Title",s),D("Project path",d),D("Workspace",c));const l=e("button","btn primary","Create bot");l.onclick=async()=>{try{const u=await f("/api/bots",{method:"POST",body:JSON.stringify({templateId:n.value,title:s.value.trim()||void 0,projectPath:d.value.trim()||void 0,isolation:c.value})});A(),await k(!0),await K(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},o.appendChild(l)}function D(t,o){const i=e("div","bv-field");return i.appendChild(e("label","bv-label",t)),i.appendChild(o),i}async function nt(){const t=H("Needs you");if(r.approvals=await f("/api/bots/approvals"),r.approvals.length===0){t.appendChild(e("div","bots-empty","Nothing waiting."));return}for(const o of r.approvals){const i=e("div","bv-approval");i.appendChild(e("div","bv-approval-title",`${o.botTitle}: ${o.title}`)),o.message&&i.appendChild(e("pre","bv-pre",o.message));const n=e("input","bv-reason");n.placeholder="reason (optional)";const s=e("div","bv-approval-actions"),d=e("button","btn primary","Allow"),a=e("button","btn danger","Deny"),c=async l=>{await f(`/api/bots/${o.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:o.id,allow:l,reason:n.value||void 0})}),await k(!0),await nt()};d.onclick=()=>void c(!0),a.onclick=()=>void c(!1),s.append(n,d,a),i.appendChild(s),t.appendChild(i)}}function ft(){if(document.getElementById("bots-section"))return;const t=it();$=t.list,P=t.badge,st(),document.addEventListener("click",o=>{const i=o.target;i&&i.closest(".session-item")&&r.activeId&&R()},!0),k(!0),r.pollTimer=window.setInterval(()=>{document.hidden||k()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(r.pollTimer))}export{ft as initBots,et as openNewBotForPath};
1
+ const d={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function L(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function f(t,n){const o=await fetch(t,{...n,headers:{"content-type":"application/json",Authorization:`Bearer ${L()}`,...n?.headers||{}}}),i=await o.text(),a=i?JSON.parse(i):null;if(!o.ok)throw new Error(a&&a.error||`HTTP ${o.status}`);return a}function e(t,n,o){const i=document.createElement(t);return n&&(i.className=n),o!==void 0&&(i.textContent=o),i}function F(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 nt(){const t=e("div","bots-section");t.id="bots-section";const n=e("div","bots-head"),o=e("span","bots-title","Bots"),i=e("span","bots-badge");i.hidden=!0,o.appendChild(i);const a=e("span","bots-head-actions"),l=e("button","bots-icon-btn","\u2699");l.title="Bot templates",l.onclick=()=>void J();const s=e("button","bots-icon-btn","+");s.title="New bot from template",s.onclick=()=>void ut(),a.append(l,s),n.append(o,a);const c=e("div","bots-list");c.id="bots-list",t.append(n,c);const r=document.querySelector(".sidebar"),u=document.querySelector(".sidebar-footer");return r&&r.insertBefore(t,u||null),{list:c,badge:i}}let R=null,P=null;function j(){R&&(R.textContent="");const t=d.approvals.length;P&&(P.hidden=t===0,P.textContent=String(t));const n=document.getElementById("bv-inbox-count");n&&(n.textContent=t?`(${t})`:""),window.__botsSnapshot=d.bots,window.__refreshSidebar?.()}function bt(t){const n=e("div","bots-row");n.dataset.botId=t.id,t.id===d.activeId&&n.classList.add("active");const o=e("span","bots-dot");o.style.background=F(t.status);const i=e("span","bots-name",t.title),a=e("span","bots-meta",t.status.replace(/_/g," "));return n.append(o,i,a),n.onclick=()=>void q(t.id),n}function ot(){const t=e("div","bots-view");t.id="bots-view",t.hidden=!0;const n=e("div","bots-view-head"),o=e("div","bv-title"),i=e("span","bots-dot");i.id="bv-dot";const a=e("span","bv-title-text");a.id="bv-title";const l=e("span","bv-status");l.id="bv-status",o.append(i,a,l);const s=e("div","bv-actions"),c=e("select","bv-mode-select");c.id="bv-mode",c.title="Approval mode for this bot";for(const[b,C]of[["supervised","Approve every tool"],["auto-accept-edits","Auto-accept edits"],["full-access","No approvals"]])c.appendChild(new Option(C,b));c.onchange=()=>{d.activeId&&f(`/api/bots/${d.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:c.value})}).then(()=>$({kind:"notice",level:"info",text:`Approval mode: ${c.value}`})).catch(b=>$({kind:"notice",level:"error",text:b instanceof Error?b.message:String(b)}))};const r=e("button","btn","Allow all");r.id="bv-allow-all",r.title="Approve every pending request for this bot",r.onclick=()=>{if(!d.activeId)return;const b=d.approvals.filter(C=>C.botId===d.activeId);Promise.all(b.map(C=>f(`/api/bots/${C.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:C.id,allow:!0})}))).finally(()=>void y(!0))};const u=e("button","btn","Needs you "),m=e("span");m.id="bv-inbox-count",u.appendChild(m),u.onclick=()=>void tt();const v=e("button","btn","Resume");v.onclick=()=>void G(b=>f(`/api/bots/${b}/resume`,{method:"POST"}).then(()=>y(!0)));const S=e("button","btn danger","Stop");S.onclick=()=>void G(b=>f(`/api/bots/${b}/stop`,{method:"POST"}).then(()=>y(!0)));const A=e("button","btn","Delete");A.onclick=()=>{d.activeId&&confirm("Delete this bot and its session?")&&f(`/api/bots/${d.activeId}`,{method:"DELETE"}).then(()=>{_(),y(!0)})};const E=e("button","btn","\u2715");E.onclick=()=>_(),s.append(c,r,u,v,S,A,E),n.append(o,s);const I=e("div","bots-messages");I.id="bots-messages";const x=e("div","bots-composer"),w=e("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(),z())};const O=e("button","btn primary","Send");O.onclick=()=>void z(),x.append(w,O),t.append(n,I,x),document.querySelector(".main-area")?.appendChild(t),document.getElementById("bots-modal")||ct()}async function z(){const t=document.getElementById("bots-input");if(!t||!d.activeId||!t.value.trim())return;const n=t.value;t.value="";try{await f(`/api/bots/${d.activeId}/input`,{method:"POST",body:JSON.stringify({text:n})})}catch(o){$({kind:"notice",level:"error",text:o instanceof Error?o.message:String(o)})}}function G(t){d.activeId&&t(d.activeId).catch(n=>$({kind:"notice",level:"error",text:n instanceof Error?n.message:String(n)}))}function _(){d.activeId=null;const t=document.getElementById("bots-view");t&&(t.hidden=!0);try{d.ws?.close()}catch{}d.ws=null,j();const n=document.getElementById("main-placeholder");n&&(n.style.display="")}async function q(t){d.activeId=t,d.items.set(t,[]);const n=document.getElementById("bots-view");n&&(n.hidden=!1);const o=document.getElementById("main-placeholder");o&&(o.style.display="none");const i=document.getElementById("terminal-container");i&&(i.style.display="none");const a=document.getElementById("file-editor");a&&(a.style.display="none"),j(),U();try{d.ws?.close()}catch{}const l=location.protocol==="https:"?"wss:":"ws:",s=new WebSocket(`${l}//${location.host}/ws/bots/${encodeURIComponent(t)}?token=${encodeURIComponent(L())}`);d.ws=s,s.onmessage=c=>{try{Y(JSON.parse(String(c.data)))}catch{}},s.onclose=()=>{d.activeId===t&&setTimeout(()=>{d.activeId===t&&y(!0)},1500)},await y(!0)}function K(){return d.bots.find(t=>t.id===d.activeId)||null}function V(){const t=K();if(!t)return;const n=document.getElementById("bv-title"),o=document.getElementById("bv-status"),i=document.getElementById("bv-dot");n&&(n.textContent=t.title),o&&(o.textContent=`${t.status.replace(/_/g," ")} \xB7 ${t.templateId} \xB7 ${t.projectPath}`);const a=document.getElementById("bv-mode");a&&t.runtimeMode&&(a.value=t.runtimeMode);const l=document.getElementById("bv-allow-all"),s=d.approvals.filter(c=>c.botId===t.id).length;l&&(l.hidden=s===0,l.textContent=`Allow all (${s})`),i&&(i.style.background=F(t.status))}function $(t,n=d.activeId){if(!n)return;const o=d.items.get(n)||[];o.push(t),d.items.set(n,o),n===d.activeId&&B()}function B(){d.renderQueued||(d.renderQueued=!0,requestAnimationFrame(()=>{d.renderQueued=!1,U()}))}function U(){const t=document.getElementById("bots-messages");if(!t||!d.activeId)return;const n=d.items.get(d.activeId)||[];t.textContent="";let o=null;for(const i of n)if(i.kind==="user"){const a=e("div","bv-msg bv-user");a.textContent=i.text,t.appendChild(a),o=null}else if(i.kind==="assistant"){const a=e("div","bv-msg bv-assistant");if(i.thinking){const s=e("details","bv-thinking");s.appendChild(e("summary",void 0,"thinking")),s.appendChild(e("div",void 0,i.thinking)),a.appendChild(s)}const l=e("div","bv-text");l.textContent=i.text,a.appendChild(l),t.appendChild(a),o=l}else if(i.kind==="tool")t.appendChild(it(i)),o=null;else if(i.kind==="approval")t.appendChild(at(i)),o=null;else if(i.kind==="notice"){const a=e("div",`bv-notice bv-notice-${i.level}`,i.text);t.appendChild(a)}o&&(o.scrollTop=o.scrollHeight),t.scrollTop=t.scrollHeight}function it(t){const n=e("details","bv-tool");n.open=t.phase!=="end"||!!t.isError;const o=e("summary"),i=e("span","bv-tool-name",t.name);if(o.appendChild(i),t.phase!=="end"&&o.appendChild(e("span","bv-tool-phase",t.phase)),t.isError&&o.appendChild(e("span","bv-tool-error","error")),typeof t.durationMs=="number"&&o.appendChild(e("span","bv-tool-meta",`${Math.round(t.durationMs)}ms`)),n.appendChild(o),t.args!==void 0){const a=e("pre","bv-pre");a.textContent=typeof t.args=="string"?t.args:JSON.stringify(t.args,null,2),n.appendChild(a)}if(t.output){const a=e("pre","bv-pre bv-output");a.textContent=t.output,n.appendChild(a)}return n}function at(t){const n=e("div","bv-approval"),o=t.approval;if(n.appendChild(e("div","bv-approval-title",o.title)),o.message&&n.appendChild(e("pre","bv-pre",o.message)),t.decided)return n.appendChild(e("div","bv-approval-decided",t.decided==="allowed"?"Allowed":"Denied")),n;const i=e("input","bv-reason");i.placeholder="reason (optional)";const a=e("div","bv-approval-actions"),l=e("button","btn primary","Allow"),s=e("button","btn",o.method==="confirm"&&/^Allow (.+?)\?$/.test(o.title)?`Always allow ${/^Allow (.+?)\?$/.exec(o.title)?.[1]}`:"Always allow");s.hidden=o.method!=="confirm";const c=e("button","btn danger","Deny"),r=async(u,m=!1)=>{try{await f(`/api/bots/${o.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:o.id,allow:u,always:m,reason:i.value||void 0})}),t.decided=u?"allowed":"denied",B(),y(!0)}catch(v){$({kind:"notice",level:"error",text:v instanceof Error?v.message:String(v)})}};return l.onclick=()=>void r(!0),s.onclick=()=>void r(!0,!0),c.onclick=()=>void r(!1),a.append(i,l,s,c),n.appendChild(a),n}function Y(t){const n=String(t.type||""),o=d.activeId;if(!o)return;const i=d.items.get(o)||[];if(n==="snapshot")d.items.set(o,[]);else if(n==="user")$({kind:"user",text:String(t.text||"")});else if(n==="status"){const a=K();a&&(a.status=String(t.status||a.status)),V(),lt()}else if(n==="message"){const a=t.message;if(!a||String(a.role||"")!=="assistant")return;const s=st(a),c=dt(a),r=i[i.length-1];r&&r.kind==="assistant"?(r.text=s||r.text,r.thinking=c||r.thinking):i.push({kind:"assistant",text:s,thinking:c}),d.items.set(o,i),B()}else if(n==="delta"){const a=String(t.kind||""),l=String(t.delta||"");let s=i[i.length-1];(!s||s.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),s=i[i.length-1]),s.kind==="assistant"&&(a==="text"?s.text+=l:a==="thinking"&&(s.thinking+=l)),d.items.set(o,i),B()}else if(n==="tool"){const a=String(t.callId||""),l=i.find(c=>c.kind==="tool"&&c.callId===a),s=String(t.phase||"start");l?(l.phase=s,s==="update"&&t.output&&(l.output=String(t.output)),s==="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:a,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:s}),d.items.set(o,i),B()}else if(n==="approval"){const a=t.approval;if(!a)return;const l=i;for(let s=l.length-1;s>=0;s--){const c=l[s];if(c.kind==="approval"&&c.approval.id===a.id){c.approval=a,a.state!=="pending"&&(c.decided=a.state==="allowed"?"allowed":"denied"),d.items.set(o,l),B();return}}l.push({kind:"approval",approval:a}),d.items.set(o,l),B()}else n==="notice"&&$({kind:"notice",level:String(t.level||"info"),text:String(t.text||"")})}function st(t){const n=t.content;return Array.isArray(n)?n.map(o=>o&&typeof o=="object"&&o.type==="text"?String(o.text||""):"").join(""):String(t.text||"")}function dt(t){const n=t.content;return Array.isArray(n)?n.map(o=>o&&typeof o=="object"&&o.type==="thinking"?String(o.thinking||""):"").join(""):""}async function y(t=!1){try{const[n,o]=await Promise.all([f("/api/bots"),f("/api/bots/approvals")]);if(d.bots=n,d.approvals=o,j(),V(),t&&d.activeId){const i=await f(`/api/bots/${d.activeId}/events?limit=300`);rt(i)}}catch{}}async function lt(){try{d.bots=await f("/api/bots"),j()}catch{}}function rt(t){if(d.activeId){d.items.set(d.activeId,[]);for(const n of t)Y(n);U()}}function ct(){const t=e("div","bots-modal");t.id="bots-modal",t.hidden=!0;const n=e("div","bots-modal-card"),o=e("div","bots-modal-head"),i=e("span");i.id="bots-modal-title";const a=e("button","btn","\u2715");a.onclick=()=>M(),o.append(i,a);const l=e("div","bots-modal-body");l.id="bots-modal-body",n.append(o,l),t.appendChild(n),t.onclick=s=>{s.target===t&&M()},document.body.appendChild(t)}function W(t){const n=document.getElementById("bots-modal"),o=document.getElementById("bots-modal-title"),i=document.getElementById("bots-modal-body");if(!n||!i)throw new Error("modal missing");return o&&(o.textContent=t),i.textContent="",n.hidden=!1,i}function M(){const t=document.getElementById("bots-modal");t&&(t.hidden=!0)}async function pt(){return d.catalog||(d.catalog=await f("/api/bots/catalog")),d.catalog}async function X(){return d.templates=await f("/api/bots/templates"),d.templates}async function J(){const t=W("Bot templates"),[n,o]=await Promise.all([pt(),X()]),i=e("div","bv-template-list");for(const r of o){const u=e("div","bv-template-row");u.appendChild(e("span","bv-template-name",r.manifest.name)),u.appendChild(e("span","bv-template-desc",r.manifest.description||""));const m=e("button","btn","Edit");m.onclick=()=>Z(t,n,r);const v=e("button","btn danger","Delete");v.onclick=()=>{confirm(`Delete template ${r.manifest.name}?`)&&f(`/api/bots/templates/${r.id}`,{method:"DELETE"}).then(()=>J())};const S=e("span","bv-template-actions");S.append(m,v),u.appendChild(S),i.appendChild(u)}o.length===0&&i.appendChild(e("div","bots-empty","No templates yet")),t.appendChild(i);const a=e("div","bv-template-actions"),l=e("button","btn primary","New template");l.onclick=()=>Z(t,n,null);const s=e("button","btn","Export");s.title="Download templates + library as JSON",s.onclick=()=>{(async()=>{try{const r=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${L()}`}});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 c=e("button","btn","Import");c.title="Restore templates from a JSON bundle",c.onclick=()=>{const r=document.createElement("input");r.type="file",r.accept="application/json,.json",r.onchange=()=>{const 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 J()}catch(m){alert(m instanceof Error?m.message:String(m))}})()},r.click()},a.append(l,s,c),t.appendChild(a)}function H(t,n,o){const i=e("div","bv-field");i.appendChild(e("label","bv-label",t));const a=e("div","bv-check-grid"),l=[];for(const s of n){const c=e("label","bv-check"),r=document.createElement("input");r.type="checkbox",r.checked=o.includes(s.id),c.append(r,e("span",void 0,s.label)),s.hint&&(c.title=s.hint),a.appendChild(c),l.push({id:s.id,input:r})}return i.appendChild(a),{element:i,get:()=>l.filter(s=>s.input.checked).map(s=>s.id)}}function Z(t,n,o){t.textContent="";const i=o?JSON.parse(JSON.stringify(o.manifest)):{name:"new-bot",description:""},a=e("input","bv-input");a.value=i.name,a.placeholder="Template name";const l=e("input","bv-input");l.value=i.description||"",l.placeholder="One line description";const s=e("textarea","bv-textarea");s.rows=6,s.value=i.system||"",s.placeholder="System prompt for this bot (written to SYSTEM.md)";const c=H("Skills",n.skills.map(p=>({id:p.id,label:p.name,hint:p.description})),i.skills||[]),r=H("Extensions (Pi builtins + library)",n.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=H("Prompt templates",n.prompts.map(p=>({id:p.id,label:p.name})),i.prompts||[]),m=e("select","bv-input");m.appendChild(new Option("none",""));for(const p of n.mcp)m.appendChild(new Option(p.name,p.id));i.mcp&&(m.value=n.mcp.find(p=>JSON.stringify(p.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");const v=e("div","bv-field");v.appendChild(e("label","bv-label","Tools (allow list; deny always blocks)"));const S=e("div","bv-check-grid"),A=[];for(const p of n.tools){const T=e("label","bv-check"),g=document.createElement("input");g.type="checkbox",g.checked=(i.tools?.allow||[]).includes(p.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(p.name),T.append(g,e("span",void 0,p.name)),S.appendChild(T),A.push({name:p.name,input:g})}v.appendChild(S);const E=e("input","bv-input");E.value=(i.tools?.deny||[]).join(", "),E.placeholder="Always deny (comma separated), e.g. bash, write";const I=e("textarea","bv-textarea");I.rows=2,I.value=(i.packages||[]).join(`
2
+ `),I.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";const x=e("select","bv-input");x.appendChild(new Option("default (Pi settings)",""));for(const p of n.models)x.appendChild(new Option(`${p.provider}/${p.model}`,`${p.provider}
3
+ ${p.model}`));i.model?.provider&&i.model?.id&&(x.value=`${i.model.provider}
4
+ ${i.model.id}`);const w=e("select","bv-input");for(const p of["","off","minimal","low","medium","high","xhigh","max"])w.appendChild(new Option(p||"default",p));i.model?.thinking&&(w.value=i.model.thinking);const O=e("select","bv-input");for(const p of["supervised","auto-accept-edits","full-access"])O.appendChild(new Option(p,p));O.value=i.permissions?.runtimeMode||"supervised";const b=e("select","bv-input");b.appendChild(new Option("ignore project .pi (recommended)","ignore")),b.appendChild(new Option("inherit project .pi (needs trust)","inherit")),b.value=i.projectResources||"ignore";const C=e("label","bv-check"),N=document.createElement("input");N.type="checkbox",N.checked=!!i.orchestrator,C.append(N,e("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));const k=(p,T)=>{const g=e("div","bv-field");return g.appendChild(e("label","bv-label",p)),g.appendChild(T),g};t.append(k("Name",a),k("Description",l),k("System prompt",s),c.element,r.element,u.element,k("MCP preset",m),v,k("Always deny tools",E),k("Packages",I),k("Model",x),k("Thinking level",w),k("Approval mode",O),k("Project resources",b),C);const Q=e("button","btn primary",o?"Save template":"Create template");Q.onclick=async()=>{const[p,T]=x.value.split(`
5
+ `),g=n.mcp.find(h=>h.id===m.value),et={name:a.value.trim()||"bot",description:l.value.trim()||void 0,system:s.value.trim()||void 0,skills:c.get(),extensions:r.get().map(h=>(h.startsWith("builtin:"),h)),prompts:u.get(),packages:I.value.split(`
6
+ `).map(h=>h.trim()).filter(Boolean),mcp:g?{mcpServers:g.servers}:void 0,tools:{allow:A.filter(h=>h.input.checked).map(h=>h.name),deny:E.value.split(",").map(h=>h.trim()).filter(Boolean)},model:p?{provider:p,id:T,thinking:w.value||void 0}:void 0,permissions:{runtimeMode:O.value},projectResources:b.value==="inherit"?"inherit":"ignore",orchestrator:N.checked||void 0};try{await f("/api/bots/templates",{method:"POST",body:JSON.stringify({id:o?.id,manifest:et})}),M(),await J()}catch(h){alert(h instanceof Error?h.message:String(h))}},t.appendChild(Q)}async function ut(){return mt("")}async function mt(t){const n=W("New bot"),o=await X();if(o.length===0){n.appendChild(e("div","bots-empty","Create a template first (\u2699)."));return}const i=e("select","bv-input");for(const u of o)i.appendChild(new Option(u.manifest.name,u.id));const a=e("input","bv-input");a.placeholder="Title (defaults to template name)";const l=e("input","bv-input");l.placeholder="/path/to/project";const s=t||d.bots[0]?.projectPath||"";l.value=s;const c=e("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")),n.append(D("Template",i),D("Title",a),D("Project path",l),D("Workspace",c));const r=e("button","btn primary","Create bot");r.onclick=async()=>{try{const u=await f("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:a.value.trim()||void 0,projectPath:l.value.trim()||void 0,isolation:c.value})});M(),await y(!0),await q(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},n.appendChild(r)}function D(t,n){const o=e("div","bv-field");return o.appendChild(e("label","bv-label",t)),o.appendChild(n),o}async function tt(){const t=W("Needs you");if(d.approvals=await f("/api/bots/approvals"),d.approvals.length===0){t.appendChild(e("div","bots-empty","Nothing waiting."));return}for(const n of d.approvals){const o=e("div","bv-approval");o.appendChild(e("div","bv-approval-title",`${n.botTitle}: ${n.title}`)),n.message&&o.appendChild(e("pre","bv-pre",n.message));const i=e("input","bv-reason");i.placeholder="reason (optional)";const a=e("div","bv-approval-actions"),l=e("button","btn primary","Allow"),s=e("button","btn danger","Deny"),c=async r=>{await f(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:r,reason:i.value||void 0})}),await y(!0),await tt()};l.onclick=()=>void c(!0),s.onclick=()=>void c(!1),a.append(i,l,s),o.appendChild(a),t.appendChild(o)}}function ft(){if(document.getElementById("bots-section"))return;const t=nt();R=t.list,P=t.badge,ot(),window.__openBot=q,document.addEventListener("click",n=>{const o=n.target;o&&o.closest(".session-item")&&d.activeId&&_()},!0),y(!0),d.pollTimer=window.setInterval(()=>{document.hidden||y()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(d.pollTimer))}export{ft as initBots,mt as openNewBotForPath};
@@ -1,34 +1,34 @@
1
- import{initTerminal as Qe}from"./terminal-core.js";import{initBots as et,openNewBotForPath as tt}from"./bots-client.js";const P=window.__TMUX_WEB_SHELL__;let f=null,u=null;const j=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let y=j;window.__tmuxWebScopeAgent=j;let me="sessions",I="",K="",Y="",Ce="";function g(e){return y?"/a/"+encodeURIComponent(y)+e:e}const r=document.getElementById("sidebar-content"),R=document.getElementById("main-placeholder"),w=document.getElementById("terminal-container"),O=document.getElementById("file-editor"),nt=document.getElementById("fe-path"),E=document.getElementById("fe-status"),U=document.getElementById("fe-content"),N=document.getElementById("fe-save"),st=document.getElementById("fe-delete"),it=document.getElementById("fe-back"),Se=document.getElementById("fe-new-name"),ot=document.getElementById("fe-new-btn"),ge=document.getElementById("settings-backdrop"),Ie=document.getElementById("settings-popover"),Be=document.querySelector(".sidebar"),xe="tmux-web-force-narrow";function X(){try{return localStorage.getItem(xe)==="1"}catch{return!1}}function Te(){document.documentElement.classList.toggle("force-narrow",X()),X()&&Me()&&Z()}function Me(){return X()?!0:window.matchMedia("(max-width: 640px)").matches}function Z(){Me()&&Be.classList.add("collapsed")}function He(){Be.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{He(),Re("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{He(),Re("files")});function Re(e){me=e,document.querySelectorAll(".mode-btn").forEach(n=>n.classList.remove("active"));const t=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");t&&t.classList.add("active"),e==="sessions"?(ve="",B()):bt()}let ve="";async function B(){if(me!=="sessions")return;try{const n=await(await fetch("/api/sidebar/sessions")).json(),s=JSON.stringify({recent:n.recent,agents:n.agents,tombstones:n.tombstones});if(s===ve)return;ve=s,dt(n)}catch{r.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}const e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{const t=window.__openNewSessionModal;typeof t=="function"?t():document.getElementById("new-session-modal")?.classList.add("open")}),Ee()}const Ne="tmux-web-sidebar-group-collapsed";function Ae(){try{return new Set(JSON.parse(localStorage.getItem(Ne)||"[]"))}catch{return new Set}}function at(e){try{localStorage.setItem(Ne,JSON.stringify([...e]))}catch{}}function lt(e,t,n){if(!e)return"\u2026";const s=n&&(e===n||e.startsWith(n+"/"))?"~"+e.slice(n.length):e,i=s.split("/").filter(Boolean);if(i.length===0)return e;for(let o=1;o<=i.length;o++){const l=i.slice(-o).join("/");if(!t.some(c=>!c||c===e?!1:(n&&(c===n||c.startsWith(n+"/"))?"~"+c.slice(n.length):c).split("/").filter(Boolean).slice(-o).join("/")===l))return l}return s}function $e(e,t,n,s=!0){const i=new Map;for(const a of e){const c=a.path||"";i.has(c)||i.set(c,[]),i.get(c).push(a)}const o=[...i.keys()],l=Ae();for(const[a,c]of i){const p=lt(a,o,t),b=l.has(a),v=document.createElement("div");v.className="session-group-header"+(b?" collapsed":""),v.title=a||"No working directory",v.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${d(p)}</span>`,v.addEventListener("click",()=>{const H=Ae(),ke=v.nextElementSibling;H.has(a)?(H.delete(a),v.classList.remove("collapsed"),ke?.classList.remove("collapsed")):(H.add(a),v.classList.add("collapsed"),ke?.classList.add("collapsed")),at(H)});const M=document.createElement("div");M.className="session-group-body"+(b?" collapsed":"");for(const H of c)M.appendChild(n?ct(H,n,s):rt(H));r.appendChild(v),r.appendChild(M)}}function ct(e,t,n){const s=document.createElement("div");s.className="session-item"+(e.name===u&&y===t?" active":"")+(n?"":" session-offline"),s.setAttribute("data-session",e.name),s.setAttribute("data-agent",t),s.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
2
- <span>${d(e.name)}</span>${n?"":'<span class="meta">offline</span>'}
3
- <button class="session-edit-btn" data-session="${d(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,n&&s.addEventListener("click",o=>{o.target.closest(".session-edit-btn")||W(e.name,t)});const i=s.querySelector(".session-edit-btn");return i&&i.addEventListener("click",o=>{o.stopPropagation(),ce(e.name,i,{agentId:t})}),s}function rt(e){const t=document.createElement("div");t.className="session-item"+(e.name===u&&!y?" active":""),t.setAttribute("data-session",e.name),t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
4
- <span>${d(e.name)}</span>
5
- <button class="session-edit-btn" data-session="${d(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>
6
- `,t.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||W(e.name)});const n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",s=>{s.stopPropagation(),ce(e.name,n)}),t}function dt(e){r.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';const t=e.recent||[],n=document.createElement("div");n.className="sidebar-section-label"+(j?" clickable":""),n.textContent=j?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",j&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),r.appendChild(n),$e(t,e.home);const s=e.agents||[];for(const o of s){if(!o.sessions||o.sessions.length===0)continue;const l=o.agentId===y,a=document.createElement("div");a.className="sidebar-section-label machine-label"+(o.online?"":" agent-offline-label")+(!l&&o.online?" clickable":""),a.textContent=o.agentName+(o.online?"":" (offline)"),!l&&o.online&&(a.title="\u6253\u5F00 "+o.agentName,a.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(o.agentId)+"/"})),r.appendChild(a),$e(o.sessions,e.home,o.agentId,o.online)}const i=e.tombstones||[];if(i.length>0){const o=document.createElement("div");o.className="sidebar-section-label tombstone-label",o.textContent="\u5931\u6548\u4F1A\u8BDD",r.appendChild(o);for(const l of i){const a=document.createElement("div");a.className="session-item session-tombstone",a.setAttribute("data-session",l.name),l.agentId&&a.setAttribute("data-agent",l.agentId);const c=l.agentId?l.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";a.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
7
- <span>${d(l.name)}</span><span class="meta">\u5931\u6548${c}</span>
8
- <button class="session-edit-btn" data-session="${d(l.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,a.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",a.addEventListener("click",()=>{ce(l.name,a,{tombstone:!0,agentId:l.agentId})});const p=a.querySelector(".session-edit-btn");p&&p.addEventListener("click",b=>{b.stopPropagation(),ce(l.name,p,{tombstone:!0,agentId:l.agentId})}),r.appendChild(a)}}}function d(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function W(e,t){if(u===e&&f&&y===(t||null))return;O.style.display="none",R.style.display="none",w.style.display="",w.classList.add("terminal-pending"),Z(),f&&(ae(),f.destroy(),f=null),u=e,y=t||null,window.__tmuxWebScopeAgent=y,window.__tmuxWebCurrentSession=u,$t(e,t);const n=Le(e,t);Xe.set(n,Date.now()+Nt);const s=D.get(n);if(s&&s.state==="working"){s.state="idle",s.doneUntil=void 0,s.unread=!1;const i=r.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');i&&ue(i,n,s)}for(const i of r.querySelectorAll(".session-item"))i.classList.toggle("active",i.getAttribute("data-session")===e&&(i.getAttribute("data-agent")||null)===y);try{f=await Qe(w,e,{terminal:P.terminal,scrollback:P.scrollback,theme:P.theme,wsBase:y?"/ws/a/"+encodeURIComponent(y):P.wsBase||"/ws"}),Ge()}catch(i){console.error("[shell] terminal init failed:",i);const o=i&&typeof i=="object"&&"message"in i?i.message:String(i);w.textContent="Failed to open terminal for "+e+": "+o,w.classList.remove("terminal-pending")}}let Q=[],m=null,_e=!1;function pt(e){if(!m||!m.files.length)return null;const t=m.repoRoot;if(!t||!e.startsWith(t))return null;const n=e.slice(t.length+1);for(const s of m.files)if(s.path===n)return s.status;return null}async function ft(e){_e=!0;try{const t=await fetch(g("/api/git/status?path="+encodeURIComponent(e)));t.ok?m=await t.json():m=null}catch{m=null}finally{_e=!1}}function ut(){if(!m||!m.branch)return"";const{branch:e,linesAdded:t,linesRemoved:n}=m;let s=`<div class="sidebar-git"><div class="git-branch-badge">
1
+ import{initTerminal as nt}from"./terminal-core.js";import{initBots as st,openNewBotForPath as it}from"./bots-client.js";const z=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 be="sessions",x="",Q="",ee="",xe="";function g(e){return h?"/a/"+encodeURIComponent(h)+e:e}const d=document.getElementById("sidebar-content"),$=document.getElementById("main-placeholder"),w=document.getElementById("terminal-container"),U=document.getElementById("file-editor"),ot=document.getElementById("fe-path"),k=document.getElementById("fe-status"),W=document.getElementById("fe-content"),_=document.getElementById("fe-save"),at=document.getElementById("fe-delete"),lt=document.getElementById("fe-back"),Te=document.getElementById("fe-new-name"),ct=document.getElementById("fe-new-btn"),we=document.getElementById("settings-backdrop"),Me=document.getElementById("settings-popover"),He=document.querySelector(".sidebar"),Ne="tmux-web-force-narrow";function te(){try{return localStorage.getItem(Ne)==="1"}catch{return!1}}function Re(){document.documentElement.classList.toggle("force-narrow",te()),te()&&$e()&&ne()}function $e(){return te()?!0:window.matchMedia("(max-width: 640px)").matches}function ne(){$e()&&He.classList.add("collapsed")}function _e(){He.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{_e(),Ae("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{_e(),Ae("files")});function Ae(e){be=e,document.querySelectorAll(".mode-btn").forEach(t=>t.classList.remove("active"));const n=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");n&&n.classList.add("active"),e==="sessions"?(Le="",T()):kt()}let Le="";async function T(){if(be!=="sessions")return;try{const t=await(await fetch("/api/sidebar/sessions")).json(),s=(window.__botsSnapshot||[]).map(o=>[o.id,o.title,o.status,o.projectPath]),i=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones,bots:s});if(i===Le)return;Le=i,mt(t)}catch{d.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}const e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{const n=window.__openNewSessionModal;typeof n=="function"?n():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,n,t){if(!e)return"\u2026";const s=t&&(e===t||e.startsWith(t+"/"))?"~"+e.slice(t.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(!n.some(l=>!l||l===e?!1:(t&&(l===t||l.startsWith(t+"/"))?"~"+l.slice(t.length):l).split("/").filter(Boolean).slice(-o).join("/")===a))return a}return s}function pt(e){const n=document.createElement("div");n.className="session-item bot-item",n.setAttribute("data-bot-id",e.id),n.title=`Bot \xB7 ${e.projectPath}`;const t=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 n.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:${t}"></span>`,n.addEventListener("click",s=>{s.stopPropagation(),window.__openBot?.(e.id)}),n}function je(e,n,t,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=t?[]: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 c=[...i.keys()],l=De();for(const[r,v]of i){const H=dt(r,c,n),R=l.has(r),I=document.createElement("div");if(I.className="session-group-header"+(R?" collapsed":""),I.title=r||"No working directory",I.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${p(H)}</span>`,!t&&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(),pe(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"+(R?" collapsed":"");for(const y of v)X.appendChild(t?ft(y,t,s):ut(y,r));for(const y of a.get(r)||[])X.appendChild(pt(y));d.appendChild(I),d.appendChild(X)}}function ft(e,n,t){const s=document.createElement("div");s.className="session-item"+(e.name===u&&h===n?" active":"")+(t?"":" session-offline"),s.setAttribute("data-session",e.name),s.setAttribute("data-agent",n),s.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
2
+ <span>${p(e.name)}</span>${t?"":'<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>`,t&&s.addEventListener("click",o=>{o.target.closest(".session-edit-btn")||F(e.name,n)});const i=s.querySelector(".session-edit-btn");return i&&i.addEventListener("click",o=>{o.stopPropagation(),ue(e.name,i,{agentId:n})}),s}function ut(e,n){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
+ <span>${p(e.name)}</span>
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",i=>{i.target.closest(".session-edit-btn")||F(e.name)});const s=t.querySelector(".session-edit-btn");return s&&s.addEventListener("click",i=>{i.stopPropagation(),ue(e.name,s,{sessionPath:n})}),t}function mt(e){d.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';const n=e.recent||[],t=document.createElement("div");t.className="sidebar-section-label"+(O?" clickable":""),t.textContent=O?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",O&&(t.title="Back to hub",t.addEventListener("click",()=>{window.location.href="/"})),d.appendChild(t),je(n,e.home);const s=e.agents||[];for(const o of s){if(!o.sessions||o.sessions.length===0)continue;const a=o.agentId===h,c=document.createElement("div");c.className="sidebar-section-label machine-label"+(o.online?"":" agent-offline-label")+(!a&&o.online?" clickable":""),c.textContent=o.agentName+(o.online?"":" (offline)"),!a&&o.online&&(c.title="\u6253\u5F00 "+o.agentName,c.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(o.agentId)+"/"})),d.appendChild(c),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 c=document.createElement("div");c.className="session-item session-tombstone",c.setAttribute("data-session",a.name),a.agentId&&c.setAttribute("data-agent",a.agentId);const l=a.agentId?a.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";c.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
7
+ <span>${p(a.name)}</span><span class="meta">\u5931\u6548${l}</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>`,c.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",c.addEventListener("click",()=>{ue(a.name,c,{tombstone:!0,agentId:a.agentId})});const r=c.querySelector(".session-edit-btn");r&&r.addEventListener("click",v=>{v.stopPropagation(),ue(a.name,r,{tombstone:!0,agentId:a.agentId})}),d.appendChild(c)}}}function p(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function F(e,n){if(u===e&&f&&h===(n||null))return;U.style.display="none",$.style.display="none",w.style.display="",w.classList.add("terminal-pending"),ne(),f&&(de(),f.destroy(),f=null),u=e,h=n||null,window.__tmuxWebScopeAgent=h,window.__tmuxWebCurrentSession=u,jt(e,n);const t=Be(e,n);et.set(t,Date.now()+Pt);const s=j.get(t);if(s&&s.state==="working"){s.state="idle",s.doneUntil=void 0,s.unread=!1;const i=d.querySelector(n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');i&&he(i,t,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:z.terminal,scrollback:z.scrollback,theme:z.theme,wsBase:h?"/ws/a/"+encodeURIComponent(h):z.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,ze=!1;function gt(e){if(!m||!m.files.length)return null;const n=m.repoRoot;if(!n||!e.startsWith(n))return null;const t=e.slice(n.length+1);for(const s of m.files)if(s.path===t)return s.status;return null}async function vt(e){ze=!0;try{const n=await fetch(g("/api/git/status?path="+encodeURIComponent(e)));n.ok?m=await n.json():m=null}catch{m=null}finally{ze=!1}}function yt(){if(!m||!m.branch)return"";const{branch:e,linesAdded:n,linesRemoved:t}=m;let s=`<div class="sidebar-git"><div class="git-branch-badge">
9
9
  <svg viewBox="0 0 16 16" fill="currentColor"><path d="M11.63 1.22a.75.75 0 00-1.06 0L5.99 5.8 4.12 3.93a.75.75 0 10-1.06 1.06L4.93 6.87A3.5 3.5 0 003 10.09v3.16a.75.75 0 001 0v-3.16a2.5 2.5 0 012.5-2.5h.27l-1.06 1.06a.75.75 0 001.06 1.06l2.37-2.38a.75.75 0 000-1.06L7.59 5.27l4.04-4.05a.75.75 0 000-1.06L11.63 1.22zM3.25 13.94a.75.75 0 01-.75-.75v-.69a.75.75 0 011.5 0v.69c0 .414-.336.75-.75.75z"/></svg>
10
- ${d(e)}</div>`;return(t>0||n>0)&&(s+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${n}</span></div>`),s+"</div>"}r.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&$&&m&&(e.stopPropagation(),Ue())});const z=document.getElementById("header-git"),De=document.getElementById("git-diff-view"),Pe=document.getElementById("gd-path"),ee=document.getElementById("gd-status"),te=document.getElementById("gd-content"),mt=document.getElementById("gd-back");let $=null;function F(e){if(!e||!e.branch){z.style.display="none",$=null;return}$=e.repoRoot;const{branch:t,linesAdded:n,linesRemoved:s}=e;let i=`<span class="branch">${d(t)}</span>`;(n>0||s>0)&&(i+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${s}</span>`),z.innerHTML=i,z.style.display="block"}z.addEventListener("click",e=>{$&&m&&(e.stopPropagation(),Ue())});const h=document.getElementById("git-popover"),ne=document.getElementById("git-popover-backdrop");function ye(){const e=z.getBoundingClientRect();h.style.top=e.bottom+4+"px",h.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function je(){const e=$,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(ie(),e){me="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));const n=document.getElementById("mode-files");n&&n.classList.add("active"),x(e)}})}let Oe="";function Ue(){if(!m)return;const e=m.files||[];if(!e.length)h.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
11
- <div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let t=`<div class="git-popover-header">${e.length} file${e.length>1?"s":""} changed</div>`;for(let n=0;n<e.length;n++){const s=e[n],i=s.additions||0,o=s.deletions||0;let l="";switch(s.status){case"M":l='<span class="git-file-status M">M</span>';break;case"A":l='<span class="git-file-status A">A</span>';break;case"D":l='<span class="git-file-status D">D</span>';break;case"?":l='<span class="git-file-status ?">?</span>';break;case"R":l='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
12
- ${l}<span class="file-path">${d(s.path)}</span>
10
+ ${p(e)}</div>`;return(n>0||t>0)&&(s+=`<div class="git-diff-stats">+<span class="add">${n}</span> <span class="del">-${t}</span></div>`),s+"</div>"}d.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&A&&m&&(e.stopPropagation(),Ge())});const G=document.getElementById("header-git"),Oe=document.getElementById("git-diff-view"),Ue=document.getElementById("gd-path"),ie=document.getElementById("gd-status"),oe=document.getElementById("gd-content"),ht=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:n,linesAdded:t,linesRemoved:s}=e;let i=`<span class="branch">${p(n)}</span>`;(t>0||s>0)&&(i+=`<span class="sep">\xB7</span>+<span class="diff-add">${t}</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 Ee(){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 We(){const e=A,n=document.getElementById("git-popover-browse");n&&n.addEventListener("click",()=>{if(ce(),e){be="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));const t=document.getElementById("mode-files");t&&t.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
+ <div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let n=`<div class="git-popover-header">${e.length} file${e.length>1?"s":""} changed</div>`;for(let t=0;t<e.length;t++){const s=e[t],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}n+=`<div class="git-popover-item" data-idx="${t}">
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>',Oe=t,h.innerHTML=t,h.querySelectorAll(".git-popover-item").forEach(n=>{const s=parseInt(n.dataset.idx||"0",10),i=e[s];!i||i.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>ze(i.path)))})}ye(),h.classList.add("open"),ne.classList.add("open"),je()}function gt(){return window.innerWidth>=1024}function We(e,t){const s=(e+(t&&e?`
16
- `:"")+t).split(`
17
- `);let i="",o=0,l=0;for(const a of s){const c=a;if(c.startsWith("@@")){const p=c.match(/@@\s+-(\d+)[^+]*\+(\d+)/);p&&(o=parseInt(p[1],10)-1,l=parseInt(p[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${d(c)}</span></div>`;continue}if(c.startsWith("diff --git")||c.startsWith("index ")||c.startsWith("--- ")||c.startsWith("+++ ")||c.startsWith("new file")||c.startsWith("deleted file")){c.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${d(c)}</span></div>`);continue}if(c.startsWith("+"))l++,i+=`<div class="diff-line add"><span class="ln-no">${l}</span><span class="ln-body">${d(c)}</span></div>`;else if(c.startsWith("-"))o++,i+=`<div class="diff-line del"><span class="ln-no">${o}</span><span class="ln-body">${d(c)}</span></div>`;else if(c.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${d(c)}</span></div>`;else{if(!c&&!o&&!l)continue;o++,l++,i+=`<div class="diff-line"><span class="ln-no">${o}</span><span class="ln-no" style="margin-right:12px">${l}</span><span class="ln-body">${d(c)}</span></div>`}}return{html:i,lineCount:s.length}}let se=null;async function ze(e){const t=$;if(t)if(ie(),gt()){w.style.display="none",f&&(ae(),f.destroy(),f=null,se=u,u=null),F(null),O.style.display="none",R.style.display="none",De.style.display="flex",Pe.textContent=e,ee.textContent="Loading\u2026",te.innerHTML="";try{const n=await fetch(g("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());const s=await n.json();yt(e,s.diff,s.stagedDiff)}catch(n){const s=n instanceof Error?n.message:String(n);ee.textContent="Error",te.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${d(s)}</div>`}}else{h.innerHTML=`<div class="git-diff-view"><div class="diff-header">
15
+ </div>`}n+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',Fe=n,b.innerHTML=n,b.querySelectorAll(".git-popover-item").forEach(t=>{const s=parseInt(t.dataset.idx||"0",10),i=e[s];!i||i.status==="D"||(t.classList.add("clickable"),t.style.cursor="pointer",t.addEventListener("click",()=>qe(i.path)))})}Ee(),b.classList.add("open"),ae.classList.add("open"),We()}function bt(){return window.innerWidth>=1024}function Ve(e,n){const s=(e+(n&&e?`
16
+ `:"")+n).split(`
17
+ `);let i="",o=0,a=0;for(const c of s){const l=c;if(l.startsWith("@@")){const r=l.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(l)}</span></div>`;continue}if(l.startsWith("diff --git")||l.startsWith("index ")||l.startsWith("--- ")||l.startsWith("+++ ")||l.startsWith("new file")||l.startsWith("deleted file")){l.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${p(l)}</span></div>`);continue}if(l.startsWith("+"))a++,i+=`<div class="diff-line add"><span class="ln-no">${a}</span><span class="ln-body">${p(l)}</span></div>`;else if(l.startsWith("-"))o++,i+=`<div class="diff-line del"><span class="ln-no">${o}</span><span class="ln-body">${p(l)}</span></div>`;else if(l.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${p(l)}</span></div>`;else{if(!l&&!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(l)}</span></div>`}}return{html:i,lineCount:s.length}}let le=null;async function qe(e){const n=A;if(n)if(ce(),bt()){w.style.display="none",f&&(de(),f.destroy(),f=null,le=u,u=null),V(null),U.style.display="none",$.style.display="none",Oe.style.display="flex",Ue.textContent=e,ie.textContent="Loading\u2026",oe.innerHTML="";try{const t=await fetch(g("/api/git/diff?path="+encodeURIComponent(n)+"&file="+encodeURIComponent(e)));if(!t.ok)throw new Error(await t.text());const s=await t.json();Lt(e,s.diff,s.stagedDiff)}catch(t){const s=t instanceof Error?t.message:String(t);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
- <span class="diff-filename">${d(e)}</span>
19
+ <span class="diff-filename">${p(e)}</span>
20
20
  <span class="diff-loading">Loading\u2026</span>
21
- </div></div>`,ye(),h.classList.add("open"),ne.classList.add("open");try{const n=await fetch(g("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());const s=await n.json();vt(e,s.diff,s.stagedDiff)}catch(n){const s=n instanceof Error?n.message:String(n);h.innerHTML=`<div class="git-diff-view"><div class="diff-header">
21
+ </div></div>`,Ee(),b.classList.add("open"),ae.classList.add("open");try{const t=await fetch(g("/api/git/diff?path="+encodeURIComponent(n)+"&file="+encodeURIComponent(e)));if(!t.ok)throw new Error(await t.text());const s=await t.json();wt(e,s.diff,s.stagedDiff)}catch(t){const s=t instanceof Error?t.message:String(t);b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
22
22
  <button class="diff-back">\u2190 Back</button>
23
- <span class="diff-filename">${d(e)}</span>
24
- </div><div class="diff-empty">Error loading diff: ${d(s)}</div></div>`}}}function vt(e,t,n){if(!t&&!n){h.innerHTML=`<div class="git-diff-view"><div class="diff-header">
23
+ <span class="diff-filename">${p(e)}</span>
24
+ </div><div class="diff-empty">Error loading diff: ${p(s)}</div></div>`}}}function wt(e,n,t){if(!n&&!t){b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
25
25
  <button class="diff-back">\u2190 Back</button>
26
- <span class="diff-filename">${d(e)}</span>
27
- </div><div class="diff-empty">No diff content available</div></div>`;return}const{html:s,lineCount:i}=We(t,n);h.innerHTML=`<div class="git-diff-view"><div class="diff-header">
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}=Ve(n,t);b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
28
28
  <button class="diff-back">\u2190 Back</button>
29
- <span class="diff-filename">${d(e)}</span>
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>`,h.querySelector(".diff-back")?.addEventListener("click",()=>{h.innerHTML=Oe,ye(),m&&h.querySelectorAll(".git-popover-item").forEach(o=>{const l=parseInt(o.dataset.idx||"0",10),a=m.files[l];!a||a.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>ze(a.path)))}),je()})}function yt(e,t,n){if(!t&&!n){ee.textContent="No diff",te.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}const{html:s,lineCount:i}=We(t,n);Pe.textContent=e,ee.textContent=i+" lines",te.innerHTML=s}function ht(){De.style.display="none",se?(w.style.display="",w.classList.add("terminal-pending"),W(se),se=null):u?(w.style.display="",w.classList.add("terminal-pending"),Ge()):R.style.display="flex"}mt.addEventListener("click",ht);function ie(){h.classList.remove("open"),ne.classList.remove("open")}ne.addEventListener("click",ie),document.addEventListener("keydown",e=>{e.key==="Escape"&&(ie(),fe())});async function Fe(e){try{const n=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(n.path){const s=await fetch("/api/git/status?path="+encodeURIComponent(n.path));if(s.ok){const i=await s.json();m=i,F(i);return}}}catch{}m=null,F(null)}let oe=null;function Ge(){ae(),u&&(Fe(u),oe=setInterval(()=>{u&&Fe(u)},3e4))}function ae(){oe&&(clearInterval(oe),oe=null)}async function qe(e){let t=e;if(t.startsWith("~"))try{const s=await(await fetch(g("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof s.path=="string"&&s.path&&(t=s.path)}catch{}t=t.replace(/\/+$/,"")||"/",tt(t)}function Ve(e,t){const n=document.createElement("button");n.className="file-tree-bot-btn",n.textContent="+",n.title=`Create bot in ${t}`,n.setAttribute("aria-label",`Create bot in ${t}`),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),qe(t)}),e.appendChild(n)}function bt(){if(Q=P.fsRoots||[],Q.length===0){if(u){wt(u);return}x("");return}r.innerHTML="";for(const e of Q){const t=document.createElement("div");t.className="file-tree-item",t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${d(e)}`,t.addEventListener("click",()=>x(e)),Ve(t,e),r.appendChild(t)}}async function wt(e){r.innerHTML='<div class="file-tree-empty">Loading...</div>';try{const n=await(await fetch(g("/api/fs/session-path?session="+encodeURIComponent(e)))).json();n.path?x(n.path):r.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{r.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function x(e){I=e,r.innerHTML='<div class="file-tree-empty">Loading...</div>';const t=ft(e);try{const s=await(await fetch(g("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof s.path=="string"&&s.path?s.path:e;if(i&&(I=i),await t,r.innerHTML="",i){const a=document.createElement("div");a.className="file-tree-item file-tree-create-bot",a.innerHTML='<span class="file-tree-bot-plus">+</span> Create bot in this folder',a.title=`Create bot in ${i}`,a.addEventListener("click",()=>void qe(i)),r.appendChild(a)}F(m),r.innerHTML+=ut();const o=Lt(i||e);if(o&&!Q.some(c=>i===c)){const c=document.createElement("div");c.className="file-tree-item",c.innerHTML="..",c.addEventListener("click",()=>x(o)),r.appendChild(c)}if(s.dirs)for(const a of s.dirs){const c=a.split("/").pop()||a.split("\\").pop(),p=document.createElement("div");p.className="file-tree-item",p.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${d(c)}`,p.addEventListener("click",()=>x(a)),Ve(p,a),r.appendChild(p)}else r.innerHTML="";const l=s.files||[];for(const a of l){const c=a.split("/").pop()||a.split("\\").pop(),p=pt(a);let b="",v="";if(p)switch(p){case"M":b="git-mod",v='<span class="git-file-status M">M</span>';break;case"A":b="git-add",v='<span class="git-file-status A">A</span>';break;case"D":b="git-del",v='<span class="git-file-status D">D</span>';break;case"?":b="git-untracked",v='<span class="git-file-status ?">?</span>';break;case"R":b="git-mod",v='<span class="git-file-status R">R</span>';break}const M=document.createElement("div");M.className="file-tree-item file"+(b?" "+b:""),M.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${v}${d(c)}`,M.addEventListener("click",()=>Et(a)),r.appendChild(M)}}catch{r.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function Lt(e){const t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function Et(e){K=e,w.style.display="none",f&&(ae(),f.destroy(),f=null,u=null),F(null),Z(),R.style.display="none",O.style.display="flex",nt.textContent=e,E.textContent="Loading...",N.style.display="none";try{const t=await fetch(g("/api/file?path="+encodeURIComponent(e)));if(!t.ok){const s=await t.json();E.textContent=s.error||"Failed to load",U.value="";return}const n=await t.json();U.value=n.content,Y=n.content,Ce=n.content,E.textContent=n.size+" bytes",N.style.display=""}catch{E.textContent="Failed to load",U.value=""}}U.addEventListener("input",()=>{Y=U.value}),N.addEventListener("click",async()=>{N.textContent="Saving...",N.disabled=!0;try{const e=await fetch(g("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:K,content:Y})});if(!e.ok){const t=await e.json();E.textContent=t.error||"Save failed";return}Ce=Y,E.textContent="Saved"}catch{E.textContent="Save failed"}finally{N.disabled=!1,N.textContent="Save"}}),st.addEventListener("click",async()=>{if(confirm("Delete "+K+"?"))try{const e=await fetch(g("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:K})});if(!e.ok){const t=await e.json();E.textContent=t.error||"Delete failed";return}O.style.display="none",R.style.display="flex",I&&x(I)}catch{E.textContent="Delete failed"}}),it.addEventListener("click",()=>{O.style.display="none",R.style.display="flex",I&&x(I)}),ot.addEventListener("click",async()=>{const e=Se.value.trim();if(!e)return;const t=I+"/"+e;try{const n=await fetch(g("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){const s=await n.json();E.textContent=s.error||"Create failed";return}Se.value="",I&&x(I)}catch{E.textContent="Create failed"}});const le=document.getElementById("force-narrow-toggle");le&&(le.checked=X(),le.addEventListener("change",()=>{try{localStorage.setItem(xe,le.checked?"1":"0")}catch{}Te(),B()})),Te(),document.getElementById("mode-settings").addEventListener("click",()=>{const e=Ie.classList.toggle("open");ge.classList.toggle("open",e)}),ge.addEventListener("click",()=>{Ie.classList.remove("open"),ge.classList.remove("open")});let L="",T=!1,k;const G=document.createElement("div");G.className="session-popover-backdrop",document.body.appendChild(G);const C=document.createElement("div");C.id="session-popover",C.className="session-popover",C.style.display="none",C.innerHTML=`<div class="sp-field">
31
+ </div><div class="diff-content">${s}</div></div>`,b.querySelector(".diff-back")?.addEventListener("click",()=>{b.innerHTML=Fe,Ee(),m&&b.querySelectorAll(".git-popover-item").forEach(o=>{const a=parseInt(o.dataset.idx||"0",10),c=m.files[a];!c||c.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>qe(c.path)))}),We()})}function Lt(e,n,t){if(!n&&!t){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}=Ve(n,t);Ue.textContent=e,ie.textContent=i+" lines",oe.innerHTML=s}function Et(){Oe.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()):$.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(),ye())});async function Je(e){try{const t=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(t.path){const s=await fetch("/api/git/status?path="+encodeURIComponent(t.path));if(s.ok){const i=await s.json();m=i,V(i);return}}}catch{}m=null,V(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 pe(e){let n=e;if(n.startsWith("~"))try{const s=await(await fetch(g("/api/fs/list?path="+encodeURIComponent(n)))).json();typeof s.path=="string"&&s.path&&(n=s.path)}catch{}n=n.replace(/\/+$/,"")||"/",it(n)}function Ye(e,n){const t=document.createElement("button");t.className="file-tree-bot-btn",t.textContent="+",t.title=`Create bot in ${n}`,t.setAttribute("aria-label",`Create bot in ${n}`),t.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),pe(n)}),e.appendChild(t)}function kt(){if(se=z.fsRoots||[],se.length===0){if(u){Ct(u);return}M("");return}d.innerHTML="";for(const e of se){const n=document.createElement("div");n.className="file-tree-item",n.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)}`,n.addEventListener("click",()=>M(e)),Ye(n,e),d.appendChild(n)}}async function Ct(e){d.innerHTML='<div class="file-tree-empty">Loading...</div>';try{const t=await(await fetch(g("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?M(t.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 n=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&&(x=i),await n,d.innerHTML="",i){const c=document.createElement("div");c.className="file-tree-item file-tree-create-bot",c.innerHTML='<span class="file-tree-bot-plus">+</span> Create bot in this folder',c.title=`Create bot in ${i}`,c.addEventListener("click",()=>void pe(i)),d.appendChild(c)}V(m),d.innerHTML+=yt();const o=St(i||e);if(o&&!se.some(l=>i===l)){const l=document.createElement("div");l.className="file-tree-item",l.innerHTML="..",l.addEventListener("click",()=>M(o)),d.appendChild(l)}if(s.dirs)for(const c of s.dirs){const l=c.split("/").pop()||c.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(l)}`,r.addEventListener("click",()=>M(c)),Ye(r,c),d.appendChild(r)}else d.innerHTML="";const a=s.files||[];for(const c of a){const l=c.split("/").pop()||c.split("\\").pop(),r=gt(c);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 R=document.createElement("div");R.className="file-tree-item file"+(v?" "+v:""),R.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${H}${p(l)}`,R.addEventListener("click",()=>Bt(c)),d.appendChild(R)}}catch{d.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function St(e){const n=e.lastIndexOf("/");return n<=0?null:e.substring(0,n)}async function Bt(e){Q=e,w.style.display="none",f&&(de(),f.destroy(),f=null,u=null),V(null),ne(),$.style.display="none",U.style.display="flex",ot.textContent=e,k.textContent="Loading...",_.style.display="none";try{const n=await fetch(g("/api/file?path="+encodeURIComponent(e)));if(!n.ok){const s=await n.json();k.textContent=s.error||"Failed to load",W.value="";return}const t=await n.json();W.value=t.content,ee=t.content,xe=t.content,k.textContent=t.size+" bytes",_.style.display=""}catch{k.textContent="Failed to load",W.value=""}}W.addEventListener("input",()=>{ee=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:Q,content:ee})});if(!e.ok){const n=await e.json();k.textContent=n.error||"Save failed";return}xe=ee,k.textContent="Saved"}catch{k.textContent="Save failed"}finally{_.disabled=!1,_.textContent="Save"}}),at.addEventListener("click",async()=>{if(confirm("Delete "+Q+"?"))try{const e=await fetch(g("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Q})});if(!e.ok){const n=await e.json();k.textContent=n.error||"Delete failed";return}U.style.display="none",$.style.display="flex",x&&M(x)}catch{k.textContent="Delete failed"}}),lt.addEventListener("click",()=>{U.style.display="none",$.style.display="flex",x&&M(x)}),ct.addEventListener("click",async()=>{const e=Te.value.trim();if(!e)return;const n=x+"/"+e;try{const t=await fetch(g("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n})});if(!t.ok){const s=await t.json();k.textContent=s.error||"Create failed";return}Te.value="",x&&M(x)}catch{k.textContent="Create failed"}});const fe=document.getElementById("force-narrow-toggle");fe&&(fe.checked=te(),fe.addEventListener("change",()=>{try{localStorage.setItem(Ne,fe.checked?"1":"0")}catch{}Re(),T()})),Re(),document.getElementById("mode-settings").addEventListener("click",()=>{const e=Me.classList.toggle("open");we.classList.toggle("open",e)}),we.addEventListener("click",()=>{Me.classList.remove("open"),we.classList.remove("open")});let L="",S=!1,E;const q=document.createElement("div");q.className="session-popover-backdrop",document.body.appendChild(q);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,6 @@ import{initTerminal as Qe}from"./terminal-core.js";import{initBots as et,openNew
38
38
  </div>
39
39
  <hr class="sp-divider" />
40
40
  <button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>
41
- <button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(C);function kt(e){const t=e.getBoundingClientRect(),n=window.innerHeight,s=C.offsetHeight||240;let i=t.bottom+4;i+s>n-8&&(i=Math.max(8,t.top-s-4)),C.style.top=i+"px",C.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}function ce(e,t,n){L=e,T=!!n?.tombstone,k=n?.agentId;const s=document.getElementById("sp-name");s.value=e;const i=C.querySelector(".sp-field label");i.textContent=T?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const o=document.getElementById("sp-rebuild");o.style.display=T?"":"none";const l=document.getElementById("sp-delete");l.textContent=T?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";const a=document.getElementById("sp-save");a.textContent=T?"\u91CD\u547D\u540D":"Save",G.classList.add("open"),C.style.display="block",kt(t),setTimeout(()=>s.focus(),50)}function A(){G.classList.remove("open"),C.style.display="none"}G.addEventListener("click",A),document.getElementById("sp-save").addEventListener("click",async()=>{const e=document.getElementById("sp-name").value.trim();if(!e||e===L){A();return}try{const t=T?{oldName:L,newName:e,agentId:k}:{oldName:L,newName:e,...k?{agentId:k}:{}};if(!(await fetch(g(T?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;A(),B(),!T&&u===L&&(k??null)===y&&W(e,k)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+L+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{const e=await fetch(g("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:k})});if(!e.ok){const t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}A(),B()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(T){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+L+'"\uFF1F'))return;try{if(!(await fetch(g("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:k})})).ok)return;A(),B()}catch{}return}if(confirm('Delete session "'+L+'"?'))try{if(!(await fetch(g("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,...k?{agentId:k}:{}})})).ok)return;A(),u===L&&(k??null)===y&&(f&&(f.destroy(),f=null),u=null,w.style.display="none",R.style.display="flex"),B()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",A);const Je={esc:"\x1B",tab:" ","s-tab":"\x1B[Z",up:"\x1B[A",down:"\x1B[B",left:"\x1B[D",right:"\x1B[C",space:" ",enter:"\r","ctrl-r":"","ctrl-c":"",btw:"/btw ",yes:"yes\r"},re=document.getElementById("mobile-keys"),Ct=new Set(["up","down","left","right","tab","s-tab","space"]),St=400,It=80;let q=0,de=0,pe=!1;function Bt(){q&&(clearTimeout(q),q=0),de&&(clearInterval(de),de=0)}re.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),re.addEventListener("pointerdown",e=>{const t=e.target.closest("button[data-key]");if(!t)return;const n=t.dataset.key;Ct.has(n)&&(pe=!1,q=setTimeout(()=>{q=0,pe=!0,de=setInterval(()=>{const s=Je[n];s&&f&&f.sendInput(s)},It)},St))});for(const e of["pointerup","pointercancel","pointerleave"])re.addEventListener(e,Bt);re.addEventListener("click",e=>{const t=e.target.closest("button[data-key]");if(!t||!f)return;if(pe){pe=!1;return}const n=Je[t.dataset.key];n&&(f.sendInput(n),f.focus())});const S=document.getElementById("mk-input"),Ke=document.getElementById("mk-send");function Ye(){if(!S||!f)return;const e=S.value;e&&(f.sendInput(e+"\r"),S.value="",S.rows=1,f.focus())}if(S&&(S.addEventListener("input",()=>{S.rows=1;const e=S.value.split(`
42
- `).length;S.rows=Math.min(e,4)}),S.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Ye())})),Ke&&Ke.addEventListener("click",Ye),window.visualViewport){const e=document.querySelector(".app-layout"),t=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",t),window.addEventListener("orientationchange",()=>setTimeout(t,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}const he=document.getElementById("process-panel"),V=document.getElementById("proc-list"),xt=document.getElementById("proc-close"),be=document.getElementById("proc-backdrop"),Tt=document.getElementById("header-ram");function Mt(){V.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(g("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){V.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(const n of e){const s=n.rss,i=s<1048576?(s/1024).toFixed(0)+"K":(s/1048576).toFixed(1)+"M";t+='<div class="proc-row" data-pid="'+n.pid+'"><span class="proc-mem">'+n.mem+'%</span><span class="proc-rss">'+i+'</span><span class="proc-cmd" title="'+d(n.command)+'">'+d(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">&times;</button></div>'}V.innerHTML=t;for(const n of V.querySelectorAll(".proc-row")){const s=n.querySelector(".proc-kill");s&&s.addEventListener("click",i=>{const o=i.target.closest(".proc-row");!o||!confirm("Kill PID "+o.dataset.pid+"?")||fetch(g("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(o.dataset.pid,10)})}).then(l=>l.json()).then(l=>{l.ok?o.style.opacity="0.3":alert("Failed: "+(l.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{V.innerHTML='<div class="proc-empty">Failed to load</div>'})}function Ht(){he.classList.add("open"),be.classList.add("open"),Mt()}function fe(){he.classList.remove("open"),be.classList.remove("open")}Tt.addEventListener("click",e=>{e.stopPropagation(),he.classList.contains("open")?fe():Ht()}),xt.addEventListener("click",fe),be.addEventListener("click",fe);const Rt=2e3;let J=null,we=null;const _=new Map,D=new Map,Nt=5e3,Xe=new Map;function Le(e,t){return(t?"a:"+t+":":"l:")+e}function At(e,t,n){const s=Le(e,t);if(n==="working"){const p=Xe.get(s);if(p&&Date.now()<p)return}const i=D.get(s),o=e===u&&(t??null)===y,l=n==="idle"&&i?.state==="working";D.set(s,{session:e,agentId:t,state:n,doneUntil:l?Date.now()+Rt:void 0,unread:l?!o:!1});const a=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',c=r.querySelector(a);c&&ue(c,s,D.get(s))}function ue(e,t,n){const s=_.get(t);s&&(clearTimeout(s),_.delete(t)),e.classList.remove("working","just-done");const i=n.session===u&&(n.agentId??null)===y;n.state==="working"?e.classList.add("working"):i&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),_.set(t,setTimeout(()=>{e.classList.remove("just-done"),_.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!i&&n.unread&&e.classList.add("just-done")}function Ee(){for(const[e,t]of D){const n=t.agentId?'.session-item[data-agent="'+CSS.escape(t.agentId)+'"][data-session="'+CSS.escape(t.session)+'"]':'.session-item[data-session="'+CSS.escape(t.session)+'"]:not([data-agent])',s=r.querySelector(n);s&&ue(s,e,t)}}function $t(e,t){const n=Le(e,t),s=D.get(n);if(!s)return;const i=_.get(n);i&&(clearTimeout(i),_.delete(n)),s.doneUntil=void 0,s.unread=!1;const o=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',l=r.querySelector(o);l&&ue(l,n,s)}function Ze(){if(J||we)return;const e=localStorage.getItem("tmux-web-token");let n=(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws/activity";e&&(n+="?token="+encodeURIComponent(e));try{const s=new WebSocket(n);J=s,s.onmessage=i=>{try{const o=JSON.parse(String(i.data));o&&o.type==="session.activity"&&typeof o.session=="string"&&At(o.session,o.agentId||void 0,o.state==="working"?"working":"idle")}catch{}},s.onclose=()=>{J===s&&(J=null,we=setTimeout(()=>{we=null,Ze()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{J=null}}window.__openSession=W,window.__refreshSidebar=B,B(),Z(),Ee(),Ze(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Ee()}),setInterval(()=>{document.visibilityState==="visible"&&B()},1e4),et();
41
+ <button class="btn" id="sp-create-bot" style="display:none">\uFF0B \u5728\u6B64\u76EE\u5F55\u521B\u5EFA Bot</button>
42
+ <button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(C);function It(e){const n=e.getBoundingClientRect(),t=window.innerHeight,s=C.offsetHeight||240;let i=n.bottom+4;i+s>t-8&&(i=Math.max(8,n.top-s-4)),C.style.top=i+"px",C.style.left=Math.max(8,Math.min(n.left,window.innerWidth-240))+"px"}let P="";function ue(e,n,t){L=e,S=!!t?.tombstone,E=t?.agentId,P=t?.sessionPath||"";const s=document.getElementById("sp-name");s.value=e;const i=C.querySelector(".sp-field label");i.textContent=S?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const o=document.getElementById("sp-rebuild");o.style.display=S?"":"none";const a=document.getElementById("sp-delete");a.textContent=S?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";const c=document.getElementById("sp-save");c.textContent=S?"\u91CD\u547D\u540D":"Save";const l=document.getElementById("sp-create-bot");l.style.display=!S&&!E&&P?"":"none",l.title=P?`Create bot in ${P}`:"",q.classList.add("open"),C.style.display="block",It(n),setTimeout(()=>s.focus(),50)}function N(){q.classList.remove("open"),C.style.display="none"}q.addEventListener("click",N),document.getElementById("sp-create-bot").addEventListener("click",()=>{if(!P)return;const e=P;N(),pe(e)}),document.getElementById("sp-save").addEventListener("click",async()=>{const e=document.getElementById("sp-name").value.trim();if(!e||e===L){N();return}try{const n=S?{oldName:L,newName:e,agentId:E}:{oldName:L,newName:e,...E?{agentId:E}:{}};if(!(await fetch(g(S?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).ok)return;N(),T(),!S&&u===L&&(E??null)===h&&F(e,E)}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:E})});if(!e.ok){const n=await e.json();alert(n.error||"\u91CD\u5EFA\u5931\u8D25");return}N(),T()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(S){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:E})})).ok)return;N(),T()}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,...E?{agentId:E}:{}})})).ok)return;N(),u===L&&(E??null)===h&&(f&&(f.destroy(),f=null),u=null,w.style.display="none",$.style.display="flex"),T()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",N);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"},me=document.getElementById("mobile-keys"),xt=new Set(["up","down","left","right","tab","s-tab","space"]),Tt=400,Mt=80;let J=0,ge=0,ve=!1;function Ht(){J&&(clearTimeout(J),J=0),ge&&(clearInterval(ge),ge=0)}me.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),me.addEventListener("pointerdown",e=>{const n=e.target.closest("button[data-key]");if(!n)return;const t=n.dataset.key;xt.has(t)&&(ve=!1,J=setTimeout(()=>{J=0,ve=!0,ge=setInterval(()=>{const s=Xe[t];s&&f&&f.sendInput(s)},Mt)},Tt))});for(const e of["pointerup","pointercancel","pointerleave"])me.addEventListener(e,Ht);me.addEventListener("click",e=>{const n=e.target.closest("button[data-key]");if(!n||!f)return;if(ve){ve=!1;return}const t=Xe[n.dataset.key];t&&(f.sendInput(t),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(`
43
+ `).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"),n=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",n),window.addEventListener("orientationchange",()=>setTimeout(n,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"),Ce=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 n="";for(const t of e){const s=t.rss,i=s<1048576?(s/1024).toFixed(0)+"K":(s/1048576).toFixed(1)+"M";n+='<div class="proc-row" data-pid="'+t.pid+'"><span class="proc-mem">'+t.mem+'%</span><span class="proc-rss">'+i+'</span><span class="proc-cmd" title="'+p(t.command)+'">'+p(t.command)+'</span><button class="proc-kill" title="Kill PID '+t.pid+'">&times;</button></div>'}K.innerHTML=n;for(const t of K.querySelectorAll(".proc-row")){const s=t.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"),Ce.classList.add("open"),$t()}function ye(){ke.classList.remove("open"),Ce.classList.remove("open")}Rt.addEventListener("click",e=>{e.stopPropagation(),ke.classList.contains("open")?ye():_t()}),Nt.addEventListener("click",ye),Ce.addEventListener("click",ye);const At=2e3;let Y=null,Se=null;const D=new Map,j=new Map,Pt=5e3,et=new Map;function Be(e,n){return(n?"a:"+n+":":"l:")+e}function Dt(e,n,t){const s=Be(e,n);if(t==="working"){const r=et.get(s);if(r&&Date.now()<r)return}const i=j.get(s),o=e===u&&(n??null)===h,a=t==="idle"&&i?.state==="working";j.set(s,{session:e,agentId:n,state:t,doneUntil:a?Date.now()+At:void 0,unread:a?!o:!1});const c=n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',l=d.querySelector(c);l&&he(l,s,j.get(s))}function he(e,n,t){const s=D.get(n);s&&(clearTimeout(s),D.delete(n)),e.classList.remove("working","just-done");const i=t.session===u&&(t.agentId??null)===h;t.state==="working"?e.classList.add("working"):i&&t.doneUntil&&Date.now()<t.doneUntil?(e.classList.add("just-done"),D.set(n,setTimeout(()=>{e.classList.remove("just-done"),D.delete(n)},Math.max(0,t.doneUntil-Date.now())))):!i&&t.unread&&e.classList.add("just-done")}function Ie(){for(const[e,n]of j){const t=n.agentId?'.session-item[data-agent="'+CSS.escape(n.agentId)+'"][data-session="'+CSS.escape(n.session)+'"]':'.session-item[data-session="'+CSS.escape(n.session)+'"]:not([data-agent])',s=d.querySelector(t);s&&he(s,e,n)}}function jt(e,n){const t=Be(e,n),s=j.get(t);if(!s)return;const i=D.get(t);i&&(clearTimeout(i),D.delete(t)),s.doneUntil=void 0,s.unread=!1;const o=n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',a=d.querySelector(o);a&&he(a,t,s)}function tt(){if(Y||Se)return;const e=localStorage.getItem("tmux-web-token");let t=(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws/activity";e&&(t+="?token="+encodeURIComponent(e));try{const s=new WebSocket(t);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,Se=setTimeout(()=>{Se=null,tt()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{Y=null}}window.__openSession=F,window.__refreshSidebar=T,T(),ne(),Ie(),tt(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Ie()}),setInterval(()=>{document.visibilityState==="visible"&&T()},1e4),st();
@@ -1 +1,3 @@
1
- import{execFileSync as g}from"node:child_process";import{mkdirSync as y,rmSync as I}from"node:fs";import u from"node:path";import S from"node:os";import{getBotStore as k}from"./store.js";import{materialize as _}from"./materialize.js";import{PiRpc as E}from"./rpc.js";import{buildCatalog as T,ORCHESTRATION_TOOLS as x,READONLY_TOOLS as B}from"./catalog.js";import{TERMINAL_STATUSES as l}from"./types.js";const m=4,v=8;class O{store=k();token;apiBase;runtimes=new Map;sockets=new Map;listeners=new Set;approvals=new Map;recent=new Map;constructor(t){this.token=this.store.token,this.apiBase=`http://127.0.0.1:${t}/api/bots`;for(const e of this.store.listInstances())!l.includes(e.status)&&e.status!=="queued"&&(e.status="stale",this.store.saveInstance(e))}listTemplates(){return this.store.listTemplates()}getTemplate(t){return this.store.getTemplate(t)}saveTemplate(t){return this.store.saveTemplate(t)}deleteTemplate(t){return this.store.deleteTemplate(t)}catalog(){return T()}listBots(t={}){return this.store.listInstances().filter(s=>!(t.project&&s.projectPath!==t.project||t.parentBotId&&s.parentBotId!==t.parentBotId||t.status&&s.status!==t.status))}getBot(t){return this.store.getInstance(t)}children(t){return this.store.listInstances().filter(e=>e.parentBotId===t)}createInstance(t){const e=this.getTemplate(t.templateId);if(!e)throw new Error(`unknown template: ${t.templateId}`);let s=null;if(t.parentBotId){if(s=this.getBot(t.parentBotId),!s)throw new Error("parent bot not found");if(s.depth+1>m)throw new Error(`nesting depth limit is ${m}`)}let r=t.projectPath||s?.projectPath||process.env.HOME||"/";r==="~"?r=S.homedir():r.startsWith("~/")&&(r=u.join(S.homedir(),r.slice(2)));const i=u.resolve(r),n=this.store.newId(),o=t.isolation||"shared";let a=i;if(o==="worktree"){const d=u.join(this.store.root,"worktrees",n);try{y(u.dirname(d),{recursive:!0,mode:448}),g("git",["-C",i,"worktree","add","-b",`tw-bot/${n.slice(0,8)}`,d],{timeout:2e4,stdio:"ignore"}),a=d}catch{a=i}}const p=new Date().toISOString(),h={id:n,templateId:e.id,title:t.title||e.manifest.name,projectPath:i,workspacePath:a,isolation:o,parentBotId:s?.id,depth:s?s.depth+1:0,runtimeMode:t.runtimeMode||e.manifest.permissions?.runtimeMode||"supervised",projectResources:e.manifest.projectResources||"ignore",status:"queued",sessionFile:u.join(this.store.sessionsDir(n),`${n}.jsonl`),createdAt:p,updatedAt:p,model:e.manifest.model};return y(this.store.sessionsDir(n),{recursive:!0,mode:448}),this.store.saveInstance(h),this.emit(h.id,{type:"status",status:"queued",at:p}),this.pump(),h}activeInProject(t){return this.store.listInstances().filter(e=>e.projectPath===t&&!l.includes(e.status)&&e.status!=="queued").length}pump(){for(const t of this.store.listInstances())t.status==="queued"&&(this.activeInProject(t.projectPath)>=v||this.start(t))}start(t){const e=this.getTemplate(t.templateId);if(!e){this.setStatus(t.id,"failed","template disappeared");return}const s=_(e,t,{apiBase:this.apiBase,token:this.token}),r=e.manifest.binaryPath||"pi",i=new E({command:r,args:s.args,cwd:t.workspacePath,env:s.env,onEvent:n=>this.handleEvent(t.id,n),onStderr:n=>{/error|failed/i.test(n)&&this.emit(t.id,{type:"notice",level:"warn",text:n.slice(0,500),at:new Date().toISOString()})},onExit:()=>{this.runtimes.delete(t.id);const n=this.store.getInstance(t.id);n&&!l.includes(n.status)&&this.setStatus(t.id,"failed","pi exited unexpectedly"),this.pump()}});this.runtimes.set(t.id,i),t.status="starting",t.pid=void 0,this.store.saveInstance(t),this.emit(t.id,{type:"status",status:"starting",at:new Date().toISOString()}),i.start()}handleEvent(t,e){const s=String(e.type||""),r=new Date().toISOString();switch(s){case"agent_start":this.setStatus(t,"running");break;case"agent_end":break;case"agent_settled":this.setStatus(t,e.aborted===!0?"cancelled":"completed");break;case"message_start":case"message_end":{const i=e.message;if(i){if(s==="message_end"&&i.role==="assistant"){const n=this.store.getInstance(t),o=A(i);n&&o&&(n.lastText=o,this.store.saveInstance(n))}this.emit(t,{type:"message",message:i,at:r})}break}case"message_update":{const i=e.assistantMessageEvent;if(!i)break;const n=i.type==="text_delta"?"text":i.type==="thinking_delta"?"thinking":i.type==="toolcall_delta"?"tool-args":null;if(!n)break;const o=e.message;this.emit(t,{type:"delta",kind:n,delta:String(i.delta||""),contentIndex:typeof i.contentIndex=="number"?i.contentIndex:void 0,messageId:typeof o?.id=="string"?o.id:void 0,at:r});break}case"tool_execution_start":this.emit(t,{type:"tool",phase:"start",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),args:e.args,at:r});break;case"tool_execution_update":this.emit(t,{type:"tool",phase:"update",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:w(e.partialResult),at:r});break;case"tool_execution_end":this.emit(t,{type:"tool",phase:"end",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:w(e.result),isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,at:r});break;case"extension_ui_request":this.handleUiRequest(t,e);break;default:break}}handleUiRequest(t,e){const s=String(e.method||""),r=new Date().toISOString(),i=this.store.getInstance(t);if(s==="notify"){this.emit(t,{type:"notice",level:e.notifyType==="error"?"error":e.notifyType==="warning"?"warn":"info",text:String(e.message||""),at:r});return}if(!["confirm","select","input","editor"].includes(s))return;const n=String(e.id||""),o=n?this.approvals.get(t)?.get(n):void 0;if(o&&o.state==="pending")return;const a={id:String(e.id||""),botId:t,botTitle:i?.title||t,kind:s==="confirm"?"tool":"question",method:s,title:String(e.title||"Approval required"),message:typeof e.message=="string"?e.message:void 0,options:Array.isArray(e.options)?e.options.map(String):void 0,state:"pending",createdAt:r};this.approvals.has(t)||this.approvals.set(t,new Map),this.approvals.get(t).set(a.id,a),this.setStatus(t,"waiting_approval"),this.emit(t,{type:"approval",approval:a,at:r})}respondApproval(t,e,s,r,i="human"){const n=this.approvals.get(t)?.get(e);if(!n)throw new Error("approval not found");const o=this.runtimes.get(t);if(!o)throw new Error("bot is not running");const a={type:"extension_ui_response",id:e};n.method==="confirm"?a.confirmed=s:n.method==="select"?a.value=s?n.options?.[0]:n.options?.[1]||n.options?.[0]:s?a.value=r||"":a.cancelled=!0,o.send(a),n.state=s?"allowed":"denied",n.decidedBy=i,n.reason=r,n.decidedAt=new Date().toISOString();try{this.store.appendEvent(t,{type:"approval",approval:n,at:n.decidedAt})}catch{}return this.broadcast(t,{type:"approval",approval:n,at:n.decidedAt}),this.setStatus(t,"running"),n}listApprovals(){const t=[];for(const[,e]of this.approvals)for(const s of e.values())s.state==="pending"&&t.push(s);return t.sort((e,s)=>e.createdAt.localeCompare(s.createdAt))}async input(t,e,s){const r=this.store.getInstance(t);if(!r)throw new Error("bot not found");if(!this.runtimes.has(t)){this.resume(t);const a=Date.now()+2e4;for(;!this.runtimes.has(t)&&Date.now()<a;)await new Promise(p=>setTimeout(p,150))}const i=this.runtimes.get(t);if(!i)throw new Error("bot is not running");const n=new Date().toISOString();this.emit(t,{type:"user",text:e,at:n});const o={type:"prompt",message:e};s==="steer"&&(o.streamingBehavior="steer"),s==="follow_up"&&(o.streamingBehavior="followUp"),!o.streamingBehavior&&(r.status==="running"||r.status==="waiting_approval")&&(o.streamingBehavior="steer");try{await i.request(o,2e4)}catch(a){const p=a instanceof Error?a.message:String(a);if(!o.streamingBehavior&&/streaming/i.test(p)){await i.request({...o,streamingBehavior:"steer"},2e4);return}throw a}}stop(t,e=!0){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");if(e)for(const r of this.children(t))this.stop(r.id,!0);try{this.runtimes.get(t)?.kill()}catch{}this.runtimes.delete(t),l.includes(s.status)||this.setStatus(t,"cancelled"),this.pump()}resume(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");this.runtimes.has(t)||(e.status="queued",this.store.saveInstance(e),this.emit(t,{type:"status",status:"queued",at:new Date().toISOString()}),this.pump())}deleteBot(t,e=!0){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");if(e)for(const r of this.children(t))this.deleteBot(r.id,!0);try{this.runtimes.get(t)?.kill()}catch{}if(this.runtimes.delete(t),this.store.deleteInstance(t),this.approvals.delete(t),this.recent.delete(t),s.isolation==="worktree"){try{g("git",["-C",s.projectPath,"worktree","remove","--force",s.workspacePath],{timeout:2e4,stdio:"ignore"})}catch{}I(s.workspacePath,{recursive:!0,force:!0})}this.pump()}status(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");const s=[...this.approvals.get(t)?.values()||[]].filter(r=>r.state==="pending");return{...e,pendingApprovals:s.length,lastText:e.lastText?.slice(0,4e3)}}result(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");return{botId:t,status:e.status,text:e.lastText||"",title:e.title}}async waitFor(t,e=45e3){const s=Date.now()+Math.min(e,45e3),r=new Set(t);for(;Date.now()<s;){const i=[...r].filter(n=>{const o=this.store.getInstance(n);return!o||l.includes(o.status)});if(i.length)return{bots:i.map(n=>this.result(n))};await new Promise(n=>setTimeout(n,250))}return{timeout:!0,bots:t.map(i=>{const n=this.store.getInstance(i);return{botId:i,status:n?.status||"missing",title:n?.title}})}}attachSocket(t,e){this.sockets.has(t)||this.sockets.set(t,new Set),this.sockets.get(t).add(e);const s=this.store.getInstance(t);e.send(JSON.stringify({type:"snapshot",bot:s,approvals:this.listApprovals().filter(r=>r.botId===t)}));for(const r of this.store.readEvents(t,400))e.send(JSON.stringify(r));e.on("close",()=>this.sockets.get(t)?.delete(e))}broadcast(t,e){const s=JSON.stringify(e);for(const r of this.sockets.get(t)||[])if(r.readyState===1)try{r.send(s)}catch{}}emit(t,e){this.store.appendEvent(t,e);const s=this.recent.get(t)||[];s.push(e),s.length>800&&s.splice(0,s.length-800),this.recent.set(t,s),this.broadcast(t,e);for(const r of this.listeners)try{r(e)}catch{}}onEvent(t){return this.listeners.add(t),()=>this.listeners.delete(t)}setStatus(t,e,s){const r=this.store.getInstance(t);r&&(r.status=e,s&&(r.lastError=s),this.store.saveInstance(r),this.emit(t,{type:"status",status:e,at:new Date().toISOString(),error:s}),l.includes(e)&&this.pump())}}function A(c){const t=c.content;return Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&e.type==="text"?String(e.text||""):"").join("").trim():""}function w(c){if(c==null)return"";if(typeof c=="string")return c;try{return JSON.stringify(c).slice(0,4e3)}catch{return String(c)}}let f=null;function J(){if(!f){const c=Number(process.env.PORT)||21e3;f=new O(c)}return f}export{O as BotManager,v as MAX_CONCURRENT_PER_PROJECT,m as MAX_DEPTH,x as ORCHESTRATION_TOOLS,B as READONLY_TOOLS,J as getBotManager};
1
+ import{execFileSync as y}from"node:child_process";import{mkdirSync as d,readFileSync as S,rmSync as E,writeFileSync as v}from"node:fs";import p from"node:path";import w from"node:os";import{getBotStore as _}from"./store.js";import{materialize as T}from"./materialize.js";import{PiRpc as x}from"./rpc.js";import{buildCatalog as A,ORCHESTRATION_TOOLS as O,READONLY_TOOLS as B}from"./catalog.js";import{TERMINAL_STATUSES as h}from"./types.js";const f=4,I=8;class j{store=_();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())!h.includes(e.status)&&e.status!=="queued"&&(e.status="stale",this.store.saveInstance(e))}listTemplates(){return this.store.listTemplates()}getTemplate(t){return this.store.getTemplate(t)}saveTemplate(t){return this.store.saveTemplate(t)}deleteTemplate(t){return this.store.deleteTemplate(t)}catalog(){return A()}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=w.homedir():n.startsWith("~/")&&(n=p.join(w.homedir(),n.slice(2)));const r=p.resolve(n),o=this.store.newId(),i=t.isolation||"shared";let a=r;if(i==="worktree"){const m=p.join(this.store.root,"worktrees",o);try{d(p.dirname(m),{recursive:!0,mode:448}),y("git",["-C",r,"worktree","add","-b",`tw-bot/${o.slice(0,8)}`,m],{timeout:2e4,stdio:"ignore"}),a=m}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:t.runtimeMode||e.manifest.permissions?.runtimeMode||"supervised",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 d(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&&!h.includes(e.status)&&e.status!=="queued").length}pump(){for(const t of this.store.listInstances())t.status==="queued"&&(this.activeInProject(t.projectPath)>=I||this.start(t))}start(t){const e=this.getTemplate(t.templateId);if(!e){this.setStatus(t.id,"failed","template disappeared");return}const s=T(e,t,{apiBase:this.apiBase,token:this.token}),n=e.manifest.binaryPath||"pi",r=new x({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&&!h.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=M(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:k(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:k(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};this.approvals.has(t)||this.approvals.set(t,new Map),this.approvals.get(t).set(u.id,u),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(S(n,"utf8")),Array.isArray(r)||(r=[])}catch{r=[]}return r.includes(e)||r.push(e),d(p.dirname(n),{recursive:!0,mode:448}),v(n,`${JSON.stringify(r)}
2
+ `,{mode:384}),r}allowedTools(t){try{const e=JSON.parse(S(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=e,this.store.saveInstance(s);const n=p.join(this.store.agentDir(t),".runtime-mode");d(p.dirname(n),{recursive:!0,mode:448}),v(n,`${e}
3
+ `,{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),h.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{y("git",["-C",s.projectPath,"worktree","remove","--force",s.workspacePath],{timeout:2e4,stdio:"ignore"})}catch{}E(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||h.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}),h.includes(e)&&this.pump())}}function M(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 k(l){if(l==null)return"";if(typeof l=="string")return l;try{return JSON.stringify(l).slice(0,4e3)}catch{return String(l)}}let g=null;function F(){if(!g){const l=Number(process.env.PORT)||21e3;g=new j(l)}return g}export{j as BotManager,I as MAX_CONCURRENT_PER_PROJECT,f as MAX_DEPTH,O as ORCHESTRATION_TOOLS,B as READONLY_TOOLS,F as getBotManager};
@@ -1,12 +1,24 @@
1
- import{mkdirSync as v,writeFileSync as x,existsSync as T,readFileSync as I,symlinkSync as k}from"node:fs";import E from"node:os";import o from"node:path";import{getBotStore as N}from"./store.js";import{ORCHESTRATION_TOOLS as j,READONLY_TOOLS as D,resolveResource as f}from"./catalog.js";const P=`// Generated by tmux-weblink: tool-call approval gate for the bots channel.
1
+ import{mkdirSync as w,writeFileSync as v,existsSync as u,readFileSync as I,symlinkSync as k}from"node:fs";import E from"node:os";import t from"node:path";import{getBotStore as N}from"./store.js";import{ORCHESTRATION_TOOLS as j,READONLY_TOOLS as D,resolveResource as T}from"./catalog.js";const A=`// Generated by tmux-weblink: tool-call approval gate for the bots channel.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
2
5
  export default function (pi) {
3
- const mode = process.env.TW_RUNTIME_MODE || 'supervised';
6
+ const agentDir = process.env.PI_CODING_AGENT_DIR || process.cwd();
7
+ const modeFile = path.join(agentDir, '.runtime-mode');
8
+ const allowFile = path.join(agentDir, '.allowed-tools');
9
+ const readText = (file, fallback) => { try { return fs.readFileSync(file, 'utf8').trim() || fallback; } catch { return fallback; } };
4
10
  const readonly = new Set(${JSON.stringify([...D])});
5
11
  const edits = new Set(['edit', 'write']);
6
12
  pi.on('tool_call', async (event, ctx) => {
13
+ // Mode and the "always allow" list are read per call, so the UI can change
14
+ // them without restarting the session.
15
+ const mode = readText(modeFile, process.env.TW_RUNTIME_MODE || 'supervised');
7
16
  if (mode === 'full-access') return;
8
17
  const name = event.toolName || event.name || 'tool';
9
18
  if (readonly.has(name)) return;
19
+ let allowed = [];
20
+ try { allowed = JSON.parse(readText(allowFile, '[]')); } catch {}
21
+ if (Array.isArray(allowed) && allowed.includes(name)) return;
10
22
  if (mode === 'auto-accept-edits' && edits.has(name)) return;
11
23
  let summary = '';
12
24
  try {
@@ -17,7 +29,7 @@ export default function (pi) {
17
29
  if (!ok) return { block: true, reason: 'Declined in tmux-weblink.' };
18
30
  });
19
31
  }
20
- `,A=`// Generated by tmux-weblink: orchestration tools for super bots.
32
+ `,P=`// Generated by tmux-weblink: orchestration tools for super bots.
21
33
  import { Type } from 'typebox';
22
34
 
23
35
  export default function (pi) {
@@ -99,11 +111,13 @@ export default function (pi) {
99
111
  reason: Type.String(),
100
112
  }), (p) => call('/approve', p));
101
113
  }
102
- `;function l(p,s){if(T(p))try{if(I(p,"utf8")===s)return}catch{}x(p,s,{mode:384})}function C(p,s,b){const g=N(),r=g.agentDir(s.id),c=g.sessionsDir(s.id),u=o.join(r,"extensions");v(u,{recursive:!0,mode:448}),v(c,{recursive:!0,mode:448});const t=p.manifest,i={sessionDir:c,defaultProjectTrust:"never"},h=(t.skills||[]).map(e=>f("skills",e)),S=(t.prompts||[]).map(e=>f("prompts",e)),_=(t.extensions||[]).map(e=>f("extensions",e));h.length&&(i.skills=h),S.length&&(i.prompts=S),_.length&&(i.extensions=_),t.packages&&t.packages.length&&(i.packages=t.packages);const y=t.tools?.allow&&t.tools.allow.length?t.tools.allow:void 0;y?i.defaultTools=t.orchestrator?[...y,...j]:y:t.orchestrator&&(i.defaultTools=[...j,"read","grep","find","ls"]),l(o.join(r,"settings.json"),`${JSON.stringify(i,null,2)}
103
- `),t.mcp?.mcpServers&&Object.keys(t.mcp.mcpServers).length&&l(o.join(r,"mcp.json"),`${JSON.stringify({mcpServers:t.mcp.mcpServers},null,2)}
104
- `),t.system&&l(o.join(r,"SYSTEM.md"),t.system.endsWith(`
105
- `)?t.system:`${t.system}
106
- `),t.appendSystem&&t.appendSystem.length&&l(o.join(r,"APPEND_SYSTEM.md"),`${t.appendSystem.join(`
114
+ `;function a(p,r){if(u(p))try{if(I(p,"utf8")===r)return}catch{}v(p,r,{mode:384})}function F(p,r,h){const b=N(),s=b.agentDir(r.id),c=b.sessionsDir(r.id),y=t.join(s,"extensions");w(y,{recursive:!0,mode:448}),w(c,{recursive:!0,mode:448});const e=p.manifest,i={sessionDir:c,defaultProjectTrust:"never"},g=(e.skills||[]).map(o=>T("skills",o)),S=(e.prompts||[]).map(o=>T("prompts",o)),_=(e.extensions||[]).map(o=>T("extensions",o));g.length&&(i.skills=g),S.length&&(i.prompts=S),_.length&&(i.extensions=_),e.packages&&e.packages.length&&(i.packages=e.packages);const f=e.tools?.allow&&e.tools.allow.length?e.tools.allow:void 0;f?i.defaultTools=e.orchestrator?[...f,...j]:f:e.orchestrator&&(i.defaultTools=[...j,"read","grep","find","ls"]),a(t.join(s,"settings.json"),`${JSON.stringify(i,null,2)}
115
+ `),e.mcp?.mcpServers&&Object.keys(e.mcp.mcpServers).length&&a(t.join(s,"mcp.json"),`${JSON.stringify({mcpServers:e.mcp.mcpServers},null,2)}
116
+ `),e.system&&a(t.join(s,"SYSTEM.md"),e.system.endsWith(`
117
+ `)?e.system:`${e.system}
118
+ `),e.appendSystem&&e.appendSystem.length&&a(t.join(s,"APPEND_SYSTEM.md"),`${e.appendSystem.join(`
107
119
 
108
120
  `)}
109
- `);const w=process.env.TMUX_WEB_BOTS_PI_HOME||o.join(E.homedir(),".pi","agent");for(const e of["auth.json","models.json"]){const m=o.join(w,e),O=o.join(r,e);if(T(m)&&!T(O))try{k(m,O)}catch{}}l(o.join(u,"tw-approval.js"),P),t.orchestrator&&l(o.join(u,"tw-orchestrator.js"),A);const n={};for(const[e,m]of Object.entries(process.env))e.startsWith("PI_")||e.startsWith("TW_")||m!==void 0&&(n[e]=m);n.PI_CODING_AGENT_DIR=r,n.PI_CODING_AGENT_SESSION_DIR=c,n.PI_TELEMETRY="0",n.TW_RUNTIME_MODE=s.runtimeMode,n.TW_BOT_ID=s.id,t.orchestrator&&(n.TW_BOTS_API=b.apiBase,n.TW_BOT_TOKEN=b.token);const d=["--mode","rpc","--session-dir",c,"--session",s.sessionFile];s.projectResources==="ignore"&&d.push("--no-approve","--no-context-files");const a=t.model;return a?.provider&&a?.id&&d.push("--provider",a.provider,"--model",a.id),a?.thinking&&d.push("--thinking",a.thinking),t.tools?.deny&&t.tools.deny.length&&d.push("--exclude-tools",...t.tools.deny),{agentDir:r,sessionsDir:c,env:n,args:d}}export{C as materialize};
121
+ `);const x=process.env.TMUX_WEB_BOTS_PI_HOME||t.join(E.homedir(),".pi","agent");for(const o of["auth.json","models.json"]){const m=t.join(x,o),O=t.join(s,o);if(u(m)&&!u(O))try{k(m,O)}catch{}}a(t.join(s,".runtime-mode"),r.runtimeMode+`
122
+ `),u(t.join(s,".allowed-tools"))||v(t.join(s,".allowed-tools"),`[]
123
+ `,{mode:384}),a(t.join(y,"tw-approval.js"),A),e.orchestrator&&a(t.join(y,"tw-orchestrator.js"),P);const n={};for(const[o,m]of Object.entries(process.env))o.startsWith("PI_")||o.startsWith("TW_")||m!==void 0&&(n[o]=m);n.PI_CODING_AGENT_DIR=s,n.PI_CODING_AGENT_SESSION_DIR=c,n.PI_TELEMETRY="0",n.TW_RUNTIME_MODE=r.runtimeMode,n.TW_BOT_ID=r.id,e.orchestrator&&(n.TW_BOTS_API=h.apiBase,n.TW_BOT_TOKEN=h.token);const d=["--mode","rpc","--session-dir",c,"--session",r.sessionFile];r.projectResources==="ignore"&&d.push("--no-approve","--no-context-files");const l=e.model;return l?.provider&&l?.id&&d.push("--provider",l.provider,"--model",l.id),l?.thinking&&d.push("--thinking",l.thinking),e.tools?.deny&&e.tools.deny.length&&d.push("--exclude-tools",...e.tools.deny),{agentDir:s,sessionsDir:c,env:n,args:d}}export{F as materialize};