tmux-weblink 2.2.41 → 2.2.43
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.
- package/dist/assets/shell-client.js +35 -35
- package/dist/browser/bots-client.js +6 -6
- package/dist/browser/shell-client.js +18 -18
- package/dist/lib/bots/manager.js +1 -1
- package/dist/lib/bots/routes.js +1 -1
- package/dist/lib/bots/store.js +3 -3
- package/dist/lib/bots/transfer.js +1 -0
- package/dist/lib/build-app.js +3 -3
- package/dist/lib/pages/shell.js +21 -4
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
const l={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function _(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function b(t,e){const i=await fetch(t,{...e,headers:{"content-type":"application/json",Authorization:`Bearer ${_()}`,...e?.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 o(t,e,i){const n=document.createElement(t);return e&&(n.className=e),i!==void 0&&(n.textContent=i),n}function z(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 ot(){const t=o("div","bots-section");t.id="bots-section";const e=o("div","bots-head"),i=o("span","bots-title","Bots"),n=o("span","bots-badge");n.hidden=!0,i.appendChild(n);const s=o("span","bots-head-actions"),d=o("button","bots-icon-btn","\u2699");d.title="Bot templates",d.onclick=()=>void q();const a=o("button","bots-icon-btn","+");a.title="New bot from template",a.onclick=()=>void mt(),s.append(d,a),e.append(i,s);const r=o("div","bots-list");r.id="bots-list",t.append(e,r);const p=document.querySelector(".sidebar"),u=document.querySelector(".sidebar-footer");return p&&p.insertBefore(t,u||null),{list:r,badge:n}}let T=null,P=null;function M(){if(!T)return;T.textContent="";const t=new Map;for(const n of l.bots){if(n.parentBotId)continue;const s=n.projectPath;t.has(s)||t.set(s,[]),t.get(s).push(n)}t.size===0&&T.appendChild(o("div","bots-empty","No bots yet"));for(const[n,s]of t){const d=o("div","bots-group"),a=o("div","bots-group-label",n.replace(/^.*\//,"")||n);a.title=n,d.appendChild(a);for(const r of s){d.appendChild(F(r));for(const p of l.bots.filter(u=>u.parentBotId===r.id)){const u=F(p);u.classList.add("bots-row-child"),d.appendChild(u)}}T.appendChild(d)}const e=l.approvals.length;P&&(P.hidden=e===0,P.textContent=String(e));const i=document.getElementById("bv-inbox-count");i&&(i.textContent=e?`(${e})`:"")}function F(t){const e=o("div","bots-row");e.dataset.botId=t.id,t.id===l.activeId&&e.classList.add("active");const i=o("span","bots-dot");i.style.background=z(t.status);const n=o("span","bots-name",t.title),s=o("span","bots-meta",t.status.replace(/_/g," "));return e.append(i,n,s),e.onclick=()=>void K(t.id),e}function it(){const t=o("div","bots-view");t.id="bots-view",t.hidden=!0;const e=o("div","bots-view-head"),i=o("div","bv-title"),n=o("span","bots-dot");n.id="bv-dot";const s=o("span","bv-title-text");s.id="bv-title";const d=o("span","bv-status");d.id="bv-status",i.append(n,s,d);const a=o("div","bv-actions"),r=o("button","btn","Needs you "),p=o("span");p.id="bv-inbox-count",r.appendChild(p),r.onclick=()=>void et();const u=o("button","btn","Resume");u.onclick=()=>void G(f=>b(`/api/bots/${f}/resume`,{method:"POST"}).then(()=>y(!0)));const w=o("button","btn danger","Stop");w.onclick=()=>void G(f=>b(`/api/bots/${f}/stop`,{method:"POST"}).then(()=>y(!0)));const x=o("button","btn","Delete");x.onclick=()=>{l.activeId&&confirm("Delete this bot and its session?")&&b(`/api/bots/${l.activeId}`,{method:"DELETE"}).then(()=>{D(),y(!0)})};const E=o("button","btn","\u2715");E.onclick=()=>D(),a.append(r,u,w,x,E),e.append(i,a);const B=o("div","bots-messages");B.id="bots-messages";const C=o("div","bots-composer"),h=o("textarea");h.id="bots-input",h.rows=1,h.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",h.onkeydown=f=>{f.key==="Enter"&&!f.shiftKey&&(f.preventDefault(),U())};const k=o("button","btn primary","Send");k.onclick=()=>void U(),C.append(h,k),t.append(e,B,C),document.querySelector(".main-area")?.appendChild(t),document.getElementById("bots-modal")||ct()}async function U(){const t=document.getElementById("bots-input");if(!t||!l.activeId||!t.value.trim())return;const e=t.value;t.value="";try{await b(`/api/bots/${l.activeId}/input`,{method:"POST",body:JSON.stringify({text:e})})}catch(i){$({kind:"notice",level:"error",text:i instanceof Error?i.message:String(i)})}}function G(t){l.activeId&&t(l.activeId).catch(e=>$({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)}))}function D(){l.activeId=null;const t=document.getElementById("bots-view");t&&(t.hidden=!0);try{l.ws?.close()}catch{}l.ws=null,M();const e=document.getElementById("main-placeholder");e&&(e.style.display="")}async function K(t){l.activeId=t,l.items.set(t,[]);const e=document.getElementById("bots-view");e&&(e.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(),L();try{l.ws?.close()}catch{}const d=location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(`${d}//${location.host}/ws/bots/${encodeURIComponent(t)}?token=${encodeURIComponent(_())}`);l.ws=a,a.onmessage=r=>{try{X(JSON.parse(String(r.data)))}catch{}},a.onclose=()=>{l.activeId===t&&setTimeout(()=>{l.activeId===t&&y(!0)},1500)},await y(!0)}function V(){return l.bots.find(t=>t.id===l.activeId)||null}function Y(){const t=V();if(!t)return;const e=document.getElementById("bv-title"),i=document.getElementById("bv-status"),n=document.getElementById("bv-dot");e&&(e.textContent=t.title),i&&(i.textContent=`${t.status.replace(/_/g," ")} \xB7 ${t.templateId} \xB7 ${t.projectPath}`),n&&(n.style.background=z(t.status))}function $(t,e=l.activeId){if(!e)return;const i=l.items.get(e)||[];i.push(t),l.items.set(e,i),e===l.activeId&&S()}function S(){l.renderQueued||(l.renderQueued=!0,requestAnimationFrame(()=>{l.renderQueued=!1,L()}))}function L(){const t=document.getElementById("bots-messages");if(!t||!l.activeId)return;const e=l.items.get(l.activeId)||[];t.textContent="";let i=null;for(const n of e)if(n.kind==="user"){const s=o("div","bv-msg bv-user");s.textContent=n.text,t.appendChild(s),i=null}else if(n.kind==="assistant"){const s=o("div","bv-msg bv-assistant");if(n.thinking){const a=o("details","bv-thinking");a.appendChild(o("summary",void 0,"thinking")),a.appendChild(o("div",void 0,n.thinking)),s.appendChild(a)}const d=o("div","bv-text");d.textContent=n.text,s.appendChild(d),t.appendChild(s),i=d}else if(n.kind==="tool")t.appendChild(st(n)),i=null;else if(n.kind==="approval")t.appendChild(at(n)),i=null;else if(n.kind==="notice"){const s=o("div",`bv-notice bv-notice-${n.level}`,n.text);t.appendChild(s)}i&&(i.scrollTop=i.scrollHeight),t.scrollTop=t.scrollHeight}function st(t){const e=o("details","bv-tool");e.open=t.phase!=="end"||!!t.isError;const i=o("summary"),n=o("span","bv-tool-name",t.name);if(i.appendChild(n),t.phase!=="end"&&i.appendChild(o("span","bv-tool-phase",t.phase)),t.isError&&i.appendChild(o("span","bv-tool-error","error")),typeof t.durationMs=="number"&&i.appendChild(o("span","bv-tool-meta",`${Math.round(t.durationMs)}ms`)),e.appendChild(i),t.args!==void 0){const s=o("pre","bv-pre");s.textContent=typeof t.args=="string"?t.args:JSON.stringify(t.args,null,2),e.appendChild(s)}if(t.output){const s=o("pre","bv-pre bv-output");s.textContent=t.output,e.appendChild(s)}return e}function at(t){const e=o("div","bv-approval"),i=t.approval;if(e.appendChild(o("div","bv-approval-title",i.title)),i.message&&e.appendChild(o("pre","bv-pre",i.message)),t.decided)return e.appendChild(o("div","bv-approval-decided",t.decided==="allowed"?"Allowed":"Denied")),e;const n=o("input","bv-reason");n.placeholder="reason (optional)";const s=o("div","bv-approval-actions"),d=o("button","btn primary","Allow"),a=o("button","btn danger","Deny"),r=async p=>{try{await b(`/api/bots/${i.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:i.id,allow:p,reason:n.value||void 0})}),t.decided=p?"allowed":"denied",S(),y(!0)}catch(u){$({kind:"notice",level:"error",text:u instanceof Error?u.message:String(u)})}};return d.onclick=()=>void r(!0),a.onclick=()=>void r(!1),s.append(n,d,a),e.appendChild(s),e}function X(t){const e=String(t.type||""),i=l.activeId;if(!i)return;const n=l.items.get(i)||[];if(e==="snapshot")l.items.set(i,[]);else if(e==="user")$({kind:"user",text:String(t.text||"")});else if(e==="status"){const s=V();s&&(s.status=String(t.status||s.status)),Y(),rt()}else if(e==="message"){const s=t.message;if(!s||String(s.role||"")!=="assistant")return;const a=dt(s),r=lt(s),p=n[n.length-1];p&&p.kind==="assistant"?(p.text=a||p.text,p.thinking=r||p.thinking):n.push({kind:"assistant",text:a,thinking:r}),l.items.set(i,n),S()}else if(e==="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)),l.items.set(i,n),S()}else if(e==="tool"){const s=String(t.callId||""),d=n.find(r=>r.kind==="tool"&&r.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}),l.items.set(i,n),S()}else if(e==="approval"){const s=t.approval;if(!s)return;const d=n;for(let a=d.length-1;a>=0;a--){const r=d[a];if(r.kind==="approval"&&r.approval.id===s.id){r.approval=s,s.state!=="pending"&&(r.decided=s.state==="allowed"?"allowed":"denied"),l.items.set(i,d),S();return}}d.push({kind:"approval",approval:s}),l.items.set(i,d),S()}else e==="notice"&&$({kind:"notice",level:String(t.level||"info"),text:String(t.text||"")})}function dt(t){const e=t.content;return Array.isArray(e)?e.map(i=>i&&typeof i=="object"&&i.type==="text"?String(i.text||""):"").join(""):String(t.text||"")}function lt(t){const e=t.content;return Array.isArray(e)?e.map(i=>i&&typeof i=="object"&&i.type==="thinking"?String(i.thinking||""):"").join(""):""}async function y(t=!1){try{const[e,i]=await Promise.all([b("/api/bots"),b("/api/bots/approvals")]);if(l.bots=e,l.approvals=i,M(),Y(),t&&l.activeId){const n=await b(`/api/bots/${l.activeId}/events?limit=300`);pt(n)}}catch{}}async function rt(){try{l.bots=await b("/api/bots"),M()}catch{}}function pt(t){if(l.activeId){l.items.set(l.activeId,[]);for(const e of t)X(e);L()}}function ct(){const t=o("div","bots-modal");t.id="bots-modal",t.hidden=!0;const e=o("div","bots-modal-card"),i=o("div","bots-modal-head"),n=o("span");n.id="bots-modal-title";const s=o("button","btn","\u2715");s.onclick=()=>A(),i.append(n,s);const d=o("div","bots-modal-body");d.id="bots-modal-body",e.append(i,d),t.appendChild(e),t.onclick=a=>{a.target===t&&A()},document.body.appendChild(t)}function R(t){const e=document.getElementById("bots-modal"),i=document.getElementById("bots-modal-title"),n=document.getElementById("bots-modal-body");if(!e||!n)throw new Error("modal missing");return i&&(i.textContent=t),n.textContent="",e.hidden=!1,n}function A(){const t=document.getElementById("bots-modal");t&&(t.hidden=!0)}async function ut(){return l.catalog||(l.catalog=await b("/api/bots/catalog")),l.catalog}async function Z(){return l.templates=await b("/api/bots/templates"),l.templates}async function q(){const t=R("Bot templates"),[e,i]=await Promise.all([ut(),Z()]),n=o("div","bv-template-list");for(const d of i){const a=o("div","bv-template-row");a.appendChild(o("span","bv-template-name",d.manifest.name)),a.appendChild(o("span","bv-template-desc",d.manifest.description||""));const r=o("button","btn","Edit");r.onclick=()=>tt(t,e,d);const p=o("button","btn danger","Delete");p.onclick=()=>{confirm(`Delete template ${d.manifest.name}?`)&&b(`/api/bots/templates/${d.id}`,{method:"DELETE"}).then(()=>q())};const u=o("span","bv-template-actions");u.append(r,p),a.appendChild(u),n.appendChild(a)}i.length===0&&n.appendChild(o("div","bots-empty","No templates yet")),t.appendChild(n);const s=o("button","btn primary","New template");s.onclick=()=>tt(t,e,null),t.appendChild(s)}function W(t,e,i){const n=o("div","bv-field");n.appendChild(o("label","bv-label",t));const s=o("div","bv-check-grid"),d=[];for(const a of e){const r=o("label","bv-check"),p=document.createElement("input");p.type="checkbox",p.checked=i.includes(a.id),r.append(p,o("span",void 0,a.label)),a.hint&&(r.title=a.hint),s.appendChild(r),d.push({id:a.id,input:p})}return n.appendChild(s),{element:n,get:()=>d.filter(a=>a.input.checked).map(a=>a.id)}}function tt(t,e,i){t.textContent="";const n=i?JSON.parse(JSON.stringify(i.manifest)):{name:"new-bot",description:""},s=o("input","bv-input");s.value=n.name,s.placeholder="Template name";const d=o("input","bv-input");d.value=n.description||"",d.placeholder="One line description";const a=o("textarea","bv-textarea");a.rows=6,a.value=n.system||"",a.placeholder="System prompt for this bot (written to SYSTEM.md)";const r=W("Skills",e.skills.map(c=>({id:c.id,label:c.name,hint:c.description})),n.skills||[]),p=W("Extensions (Pi builtins + library)",e.extensions.map(c=>({id:c.id,label:`${c.name}${c.kind==="builtin"?" (builtin)":""}`,hint:c.description})),(n.extensions||[]).map(c=>c.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),u=W("Prompt templates",e.prompts.map(c=>({id:c.id,label:c.name})),n.prompts||[]),w=o("select","bv-input");w.appendChild(new Option("none",""));for(const c of e.mcp)w.appendChild(new Option(c.name,c.id));n.mcp&&(w.value=e.mcp.find(c=>JSON.stringify(c.servers)===JSON.stringify(n.mcp?.mcpServers))?.id||"");const x=o("div","bv-field");x.appendChild(o("label","bv-label","Tools (allow list; deny always blocks)"));const E=o("div","bv-check-grid"),B=[];for(const c of e.tools){const I=o("label","bv-check"),v=document.createElement("input");v.type="checkbox",v.checked=(n.tools?.allow||[]).includes(c.name)||!n.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(c.name),I.append(v,o("span",void 0,c.name)),E.appendChild(I),B.push({name:c.name,input:v})}x.appendChild(E);const C=o("input","bv-input");C.value=(n.tools?.deny||[]).join(", "),C.placeholder="Always deny (comma separated), e.g. bash, write";const h=o("textarea","bv-textarea");h.rows=2,h.value=(n.packages||[]).join(`
|
|
2
|
-
`),
|
|
3
|
-
${
|
|
4
|
-
${n.model.id}`);const
|
|
5
|
-
`),
|
|
6
|
-
`).map(
|
|
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,34 +1,34 @@
|
|
|
1
|
-
import{initTerminal as
|
|
2
|
-
<span>${d(e.name)}</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>`,
|
|
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">📁</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
4
|
<span>${d(e.name)}</span>
|
|
5
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
|
-
`,
|
|
7
|
-
<span>${d(
|
|
8
|
-
<button class="session-edit-btn" data-session="${d(
|
|
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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}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">
|
|
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(
|
|
11
|
-
<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let
|
|
12
|
-
${
|
|
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>
|
|
13
13
|
<span class="file-add">${i>0?"+"+i:""}</span>
|
|
14
14
|
<span class="file-del">${o>0?"-"+o:""}</span>
|
|
15
|
-
</div>`}
|
|
16
|
-
`:"")+
|
|
17
|
-
`);let i="",o=0,
|
|
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">
|
|
18
18
|
<button class="diff-back">\u2190 Back</button>
|
|
19
19
|
<span class="diff-filename">${d(e)}</span>
|
|
20
20
|
<span class="diff-loading">Loading\u2026</span>
|
|
21
|
-
</div></div>`,ye(),
|
|
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">
|
|
22
22
|
<button class="diff-back">\u2190 Back</button>
|
|
23
23
|
<span class="diff-filename">${d(e)}</span>
|
|
24
|
-
</div><div class="diff-empty">Error loading diff: ${d(s)}</div></div>`}}}function
|
|
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">
|
|
25
25
|
<button class="diff-back">\u2190 Back</button>
|
|
26
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(n
|
|
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">
|
|
28
28
|
<button class="diff-back">\u2190 Back</button>
|
|
29
29
|
<span class="diff-filename">${d(e)}</span>
|
|
30
30
|
<span class="diff-filesize">${i} lines</span>
|
|
31
|
-
</div><div class="diff-content">${s}</div></div>`,
|
|
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">
|
|
32
32
|
<label>Rename session</label>
|
|
33
33
|
<input type="text" id="sp-name" />
|
|
34
34
|
</div>
|
|
@@ -38,5 +38,5 @@ import{initTerminal as Xe}from"./terminal-core.js";import{initBots as Ze}from"./
|
|
|
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(
|
|
42
|
-
`).length;
|
|
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+'">×</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();
|
package/dist/lib/bots/manager.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFileSync as f}from"node:child_process";import{mkdirSync as g,rmSync as v}from"node:fs";import u from"node:path";import{getBotStore as w}from"./store.js";import{materialize as I}from"./materialize.js";import{PiRpc as k}from"./rpc.js";import{buildCatalog as _,ORCHESTRATION_TOOLS as E,READONLY_TOOLS as T}from"./catalog.js";import{TERMINAL_STATUSES as l}from"./types.js";const d=4,y=8;class x{store=w();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 _()}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>d)throw new Error(`nesting depth limit is ${d}`)}const r=u.resolve(t.projectPath||s?.projectPath||process.env.HOME||"/"),i=this.store.newId(),n=t.isolation||"shared";let o=r;if(n==="worktree"){const h=u.join(this.store.root,"worktrees",i);try{g(u.dirname(h),{recursive:!0,mode:448}),f("git",["-C",r,"worktree","add","-b",`tw-bot/${i.slice(0,8)}`,h],{timeout:2e4,stdio:"ignore"}),o=h}catch{o=r}}const a=new Date().toISOString(),p={id:i,templateId:e.id,title:t.title||e.manifest.name,projectPath:r,workspacePath:o,isolation:n,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(i),`${i}.jsonl`),createdAt:a,updatedAt:a,model:e.manifest.model};return g(this.store.sessionsDir(i),{recursive:!0,mode:448}),this.store.saveInstance(p),this.emit(p.id,{type:"status",status:"queued",at:a}),this.pump(),p}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)>=y||this.start(t))}start(t){const e=this.getTemplate(t.templateId);if(!e){this.setStatus(t.id,"failed","template disappeared");return}const s=I(e,t,{apiBase:this.apiBase,token:this.token}),r=e.manifest.binaryPath||"pi",i=new k({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=B(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:S(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:S(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{f("git",["-C",s.projectPath,"worktree","remove","--force",s.workspacePath],{timeout:2e4,stdio:"ignore"})}catch{}v(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 B(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 S(c){if(c==null)return"";if(typeof c=="string")return c;try{return JSON.stringify(c).slice(0,4e3)}catch{return String(c)}}let m=null;function q(){if(!m){const c=Number(process.env.PORT)||21e3;m=new x(c)}return m}export{x as BotManager,y as MAX_CONCURRENT_PER_PROJECT,d as MAX_DEPTH,E as ORCHESTRATION_TOOLS,T as READONLY_TOOLS,q as getBotManager};
|
|
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};
|
package/dist/lib/bots/routes.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
import{exportBots as m,importBots as b}from"./transfer.js";function f(s,c){const{manager:o,userAuth:u}=c,a=async(r,t)=>{const e=r.req.header("x-bots-token");return e&&e===o.token?t():u()(r,t)},l=()=>a,n=()=>u();s.get("/api/bots/catalog",n(),async r=>r.json(await o.catalog())),s.get("/api/bots/templates",n(),r=>r.json(o.listTemplates())),s.post("/api/bots/templates",n(),async r=>{const t=await r.req.json().catch(()=>null);if(!t||!t.manifest||typeof t.manifest.name!="string")return r.json({error:"manifest.name is required"},400);try{const e=o.saveTemplate({id:typeof t.id=="string"?t.id:void 0,manifest:t.manifest});return r.json(e,200)}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.get("/api/bots/export",n(),r=>{const t=m(o.store);return r.json(t,200,{"content-disposition":`attachment; filename="tmux-weblink-bots-${t.exportedAt.slice(0,10)}.json"`})}),s.post("/api/bots/import",n(),async r=>{const t=await r.req.json().catch(()=>null);if(!t)return r.json({error:"invalid bundle"},400);try{return r.json(b(o.store,t,{overwriteLibrary:t.overwriteLibrary===!0}))}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.delete("/api/bots/templates/:id",n(),r=>o.deleteTemplate(r.req.param("id"))?r.json({ok:!0}):r.json({error:"not found"},404)),s.get("/api/bots",a,r=>{const t=r.req.query("project")||void 0,e=r.req.query("parent")||void 0,d=r.req.query("status")||void 0;return r.json(o.listBots({project:t,parentBotId:e,parentOnly:!!e,status:d}))});const p=async r=>{const t=await r.req.json().catch(()=>null);if(!t||typeof t.templateId!="string")return r.json({error:"templateId is required"},400);try{const e=o.createInstance({templateId:t.templateId,title:typeof t.title=="string"?t.title:void 0,projectPath:typeof t.projectPath=="string"?t.projectPath:void 0,isolation:t.isolation==="worktree"?"worktree":"shared",parentBotId:typeof t.parentBotId=="string"?t.parentBotId:void 0,runtimeMode:t.runtimeMode});return r.json(e,201)}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}};s.post("/api/bots",n(),p),s.post("/api/bots/create",l(),p),s.post("/api/bots/list_templates",a,r=>r.json(o.listTemplates().map(t=>({id:t.id,name:t.manifest.name,description:t.manifest.description,orchestrator:!!t.manifest.orchestrator})))),s.post("/api/bots/list",a,async r=>{const t=await r.req.json().catch(()=>({})),e=t.parentBotId,d=o.listBots({parentBotId:t.parentOnly&&e?e:void 0,status:t.status});return r.json(d.map(i=>({id:i.id,title:i.title,status:i.status,projectPath:i.projectPath,parentBotId:i.parentBotId,depth:i.depth,lastText:i.lastText?.slice(0,400),updatedAt:i.updatedAt})))}),s.post("/api/bots/status",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId)return r.json({error:"botId is required"},400);try{return r.json(o.status(t.botId))}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},404)}}),s.post("/api/bots/message",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId||typeof t.text!="string")return r.json({error:"botId and text are required"},400);try{return await o.input(t.botId,t.text,t.mode==="follow_up"?"follow_up":t.mode==="steer"?"steer":void 0),r.json({ok:!0})}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/wait",a,async r=>{const t=await r.req.json().catch(()=>({}));return!Array.isArray(t.botIds)||t.botIds.length===0?r.json({error:"botIds is required"},400):r.json(await o.waitFor(t.botIds,typeof t.timeoutMs=="number"?t.timeoutMs:void 0))}),s.post("/api/bots/result",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId)return r.json({error:"botId is required"},400);try{return r.json(o.result(t.botId))}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},404)}}),s.post("/api/bots/stop",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId)return r.json({error:"botId is required"},400);try{return o.stop(t.botId,t.cascade!==!1),r.json({ok:!0})}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/approvals",a,r=>r.json(o.listApprovals())),s.post("/api/bots/approve",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId||!t.requestId)return r.json({error:"botId and requestId are required"},400);const e=r.req.header("x-bots-token")===o.token?"parent-bot":"human";if(e==="parent-bot"&&!t.reason)return r.json({error:"a reason is required when a bot approves"},400);try{return r.json(o.respondApproval(t.botId,t.requestId,t.allow===!0,t.reason,e))}catch(d){return r.json({error:d instanceof Error?d.message:String(d)},400)}}),s.get("/api/bots/approvals",n(),r=>r.json(o.listApprovals())),s.get("/api/bots/:id",n(),r=>{const t=o.getBot(r.req.param("id"));return t?r.json(t):r.json({error:"not found"},404)}),s.get("/api/bots/:id/events",n(),r=>{const t=Number(r.req.query("limit"))||400;return r.json(o.store.readEvents(r.req.param("id"),t))}),s.post("/api/bots/:id/input",n(),async r=>{const t=await r.req.json().catch(()=>({}));if(typeof t.text!="string"||!t.text.trim())return r.json({error:"text is required"},400);try{return await o.input(r.req.param("id"),t.text,t.mode==="follow_up"?"follow_up":t.mode==="steer"?"steer":void 0),r.json({ok:!0})}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/:id/stop",n(),r=>{try{return o.stop(r.req.param("id"),!0),r.json({ok:!0})}catch(t){return r.json({error:t instanceof Error?t.message:String(t)},400)}}),s.post("/api/bots/:id/resume",n(),r=>{try{return o.resume(r.req.param("id")),r.json({ok:!0})}catch(t){return r.json({error:t instanceof Error?t.message:String(t)},400)}}),s.post("/api/bots/:id/approve",n(),async r=>{const t=await r.req.json().catch(()=>({}));if(!t.requestId)return r.json({error:"requestId is required"},400);try{return r.json(o.respondApproval(r.req.param("id"),t.requestId,t.allow===!0,t.reason,"human"))}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.delete("/api/bots/:id",n(),r=>{try{return o.deleteBot(r.req.param("id"),!0),r.json({ok:!0})}catch(t){return r.json({error:t instanceof Error?t.message:String(t)},400)}})}export{f as registerBotRoutes};
|
package/dist/lib/bots/store.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{existsSync as
|
|
2
|
-
`,{mode:384})}catch{}}readEvents(t,e=2e3){const s=n.join(this.instanceDir(t),"events.jsonl");if(!
|
|
3
|
-
`).filter(Boolean).slice(-e),
|
|
1
|
+
import{existsSync as o,mkdirSync as a,readFileSync as c,writeFileSync as h,readdirSync as u,rmSync as m,appendFileSync as j,copyFileSync as S}from"node:fs";import n from"node:path";import{randomBytes as f,randomUUID as D}from"node:crypto";import{getDataRoot as y}from"../state-paths.js";class g{root;instancesFile;instances=new Map;token;constructor(t){this.root=t||process.env.TMUX_WEB_BOTS_DIR||n.join(y(),"bots"),a(this.root,{recursive:!0,mode:448}),a(n.join(this.root,"templates"),{recursive:!0,mode:448}),a(n.join(this.root,"templates",".history"),{recursive:!0,mode:448}),a(n.join(this.root,"instances"),{recursive:!0,mode:448}),this.instancesFile=n.join(this.root,"instances.json"),this.loadInstances(),this.token=this.loadOrCreateToken()}loadOrCreateToken(){const t=n.join(this.root,"api-token");if(o(t)){const s=c(t,"utf8").trim();if(s)return s}const e=f(24).toString("hex");return h(t,e,{mode:384}),e}templatesDir=()=>n.join(this.root,"templates");listTemplates(){const t=this.templatesDir();if(!o(t))return[];const e=[];for(const s of u(t))if(s.endsWith(".json"))try{const i=JSON.parse(c(n.join(t,s),"utf8"));i&&i.id&&i.manifest&&e.push(i)}catch{}return e.sort((s,i)=>s.manifest.name.localeCompare(i.manifest.name))}getTemplate(t){const e=n.join(this.templatesDir(),`${t}.json`);if(!o(e))return null;try{return JSON.parse(c(e,"utf8"))}catch{return null}}saveTemplate(t){const e=new Date().toISOString(),s=t.id||`${Date.now().toString(36)}-${f(3).toString("hex")}`,i=this.getTemplate(s);i&&this.snapshotTemplate(n.join(this.templatesDir(),`${s}.json`),s);const r={id:s,manifest:{...t.manifest,schema:1},createdAt:i?.createdAt||e,updatedAt:e};return h(n.join(this.templatesDir(),`${s}.json`),JSON.stringify(r,null,2),{mode:384}),r}deleteTemplate(t){const e=n.join(this.templatesDir(),`${t}.json`);return o(e)?(this.snapshotTemplate(e,t),m(e),!0):!1}snapshotTemplate(t,e){try{const s=n.join(this.templatesDir(),".history",e);a(s,{recursive:!0,mode:448});const i=new Date().toISOString().replace(/[:.]/g,"-");S(t,n.join(s,`${i}.json`));const r=u(s).sort();for(const l of r.slice(0,Math.max(0,r.length-10)))m(n.join(s,l),{force:!0})}catch{}}listTemplateHistory(t){const e=n.join(this.templatesDir(),".history",t);return o(e)?u(e).sort():[]}loadInstances(){if(o(this.instancesFile))try{const t=JSON.parse(c(this.instancesFile,"utf8"));for(const e of t)this.instances.set(e.id,e)}catch{}}persistInstances(){h(this.instancesFile,JSON.stringify([...this.instances.values()],null,2),{mode:384})}listInstances(){return[...this.instances.values()].sort((t,e)=>t.createdAt.localeCompare(e.createdAt))}getInstance(t){return this.instances.get(t)||null}saveInstance(t){t.updatedAt=new Date().toISOString(),this.instances.set(t.id,t),this.persistInstances()}deleteInstance(t){this.instances.delete(t),this.persistInstances(),m(this.instanceDir(t),{recursive:!0,force:!0})}instanceDir(t){return n.join(this.root,"instances",t)}agentDir(t){return n.join(this.instanceDir(t),"agent")}sessionsDir(t){return n.join(this.instanceDir(t),"sessions")}appendEvent(t,e){try{a(this.instanceDir(t),{recursive:!0,mode:448}),j(n.join(this.instanceDir(t),"events.jsonl"),`${JSON.stringify(e)}
|
|
2
|
+
`,{mode:384})}catch{}}readEvents(t,e=2e3){const s=n.join(this.instanceDir(t),"events.jsonl");if(!o(s))return[];const r=c(s,"utf8").split(`
|
|
3
|
+
`).filter(Boolean).slice(-e),l=[];for(const d of r)try{l.push(JSON.parse(d))}catch{}return l}newId(){return D()}}let p=null;function F(){return p||(p=new g),p}export{g as BotStore,F as getBotStore};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as l,mkdirSync as u,readFileSync as y,readdirSync as h,statSync as S,writeFileSync as d}from"node:fs";import n from"node:path";const b=512*1024;function m(e,t=""){if(!l(e))return[];const o=[];for(const r of h(e)){if(r.startsWith("."))continue;const s=n.join(e,r),a=t?`${t}/${r}`:r,c=S(s);c.isDirectory()?o.push(...m(s,a)):c.size<=b&&o.push(a)}return o}function x(e){const t=n.join(e.root,"library"),o={};for(const r of m(t))try{o[r]=y(n.join(t,r),"utf8")}catch{}return{schema:1,exportedAt:new Date().toISOString(),templates:e.listTemplates(),library:o}}function D(e,t,o={}){if(!t||t.schema!==1)throw new Error("unsupported bundle");const r=n.join(e.root,"library");let s=0,a=0;for(const[i,p]of Object.entries(t.library||{})){const f=n.join(r,i);if(l(f)&&!o.overwriteLibrary){a+=1;continue}u(n.dirname(f),{recursive:!0,mode:448}),d(f,p,{mode:384}),s+=1}let c=0;for(const i of t.templates||[])!i||!i.manifest||typeof i.manifest.name!="string"||(e.saveTemplate({id:i.id,manifest:i.manifest}),c+=1);return{templates:c,files:s,skipped:a}}export{x as exportBots,D as importBots};
|