tmux-weblink 3.2.3 → 3.2.4

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/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import{chmodSync as ye,existsSync as D,mkdirSync as ke,readdirSync as we,readFileSync as V,statSync as Te,unlinkSync as ve,writeFileSync as Se}from"node:fs";import{createRequire as X}from"node:module";import{hostname as E,networkInterfaces as _e}from"node:os";const be=X(import.meta.url),{version:Ae}=be("../package.json");import P from"node:path";import{fileURLToPath as Ce}from"node:url";import{serve as xe}from"@hono/node-server";import{WebSocketServer as Ie,WebSocket as F}from"ws";try{const e=P.dirname(X(import.meta.url).resolve("node-pty/package.json")),t=P.join(e,"prebuilds");if(D(t))for(const o of we(t)){const n=P.join(t,o,"spawn-helper");D(n)&&!(Te(n).mode&73)&&ye(n,493)}}catch{}import{loadSecurityConfig as Pe}from"./lib/security-config.js";import{TokenStore as Re,hashPassword as $e,verifyPassword as Me,validatePassword as Oe}from"./lib/auth.js";import{RateLimiter as Ne}from"./lib/rateLimiter.js";import{audit as d}from"./lib/auditLog.js";import{db as N}from"./lib/db.js";import{handleClientMessage as Y}from"./lib/ws-message.js";import{loadDotEnv as Ue}from"./lib/load-env.js";import{listSessions as Le,resolveTmuxSocketPath as Ee}from"./sessions.js";import{cmdSetup as Fe,cmdTheme as je,printUsage as K,printVersion as He}from"./lib/cli.js";import{readSettings as Be}from"./lib/settings.js";import{readActiveTheme as We}from"./lib/theme-store.js";import{buildApp as Q}from"./lib/build-app.js";import{getDataRoot as Z}from"./lib/state-paths.js";import{getBotManager as De}from"./lib/bots/manager.js";import{attachTerminal as Je,killAllAttachedPtys as ze}from"./lib/attach-terminal.js";import{acquireControlClient as q,killAllControlClients as Ge}from"./lib/tmux-control.js";import{getSessionPaneTarget as ee,capturePaneTail as te,capturePaneHistoryChunk as ne,toCrlf as oe}from"./lib/tmux-capture.js";import{readTerminalBufferConfig as Ve}from"./lib/terminal-config.js";import{AgentRegistry as Xe}from"./lib/agent-registry.js";import{AgentChannel as Ye,MAX_RELAY_CONNS_PER_AGENT as Ke}from"./lib/agent-relay.js";import{findAgentTokenByPlaintext as Qe,listAgentTokens as Ze}from"./lib/agent-tokens.js";import{saveSecurityConfig as qe}from"./lib/security-config.js";import{readFederationConfig as et,writeFederationConfig as tt}from"./lib/federation-config.js";import{startAgentClient as nt}from"./lib/agent-client.js";import{ActivityProbe as ot}from"./lib/activity-probe.js";import{upsertSessionState as re}from"./lib/session-state.js";import{sessionWorkingPath as rt}from"./lib/sessions-sidebar.js";Ue();const j=Ve(),g=Pe(),w=new Re,_=new Ne;let J=!1;const st="tmux-web-token";function H(e){if(g.security.trustProxy){const t=(e.headers["x-forwarded-for"]||"").split(",")[0].trim();if(t)return t}return e.socket.remoteAddress||"unknown"}function U(e){const t=e.headers.authorization;if(typeof t=="string"&&t.startsWith("Bearer "))return t.slice(7);const o=e.headers.cookie;if(typeof o!="string")return null;const n=o.match(new RegExp(`(?:^|;\\s*)${st}=([^;]+)`));return n?decodeURIComponent(n[1]):null}function nn(e){const t=U(e);return t?w.validateToken(t):null}const M=new Map;function at(e){let t=0;for(const o of M.values())o.ip===e&&t++;return t}function C(e,t,o){try{e.close(t,o)}catch{}}function se(e,t){e.readyState===F.OPEN&&e.send(JSON.stringify(t))}const ae=process.argv.slice(2),L=ae;if(L.length>0){const[e,t]=L;switch(e){case"setup":await Fe(L),process.exit(0);case"theme":await je(L.slice(1)),process.exit(0);case"agent":{const o=P.join(P.dirname(Ce(import.meta.url)),"agent.js"),{spawn:n}=await import("node:child_process"),l=n(process.execPath,[o,...ae],{stdio:"inherit"});l.on("error",a=>{console.error(a),process.exit(1)}),l.on("exit",a=>process.exit(a??0)),await new Promise(()=>{})}case"agent-token":await vt(L.slice(1)),process.exit(0);case"help":case"--help":case"-h":K(),process.exit(0);case"-V":case"--version":case"-v":He(),process.exit(0);default:console.error(`unknown argument: ${e}`),K(),process.exit(1)}}function R(e,t){e.readyState===F.OPEN&&e.send(JSON.stringify(t))}const ie=new Set;await N.read(),N.data.sessionAccess??=[],N.data.pinnedViews??=[],N.data.watchedPanes??=[],N.data.quickCommands??=[];const ce=await Be();let it=await We();const k=new Xe({onChange:()=>{}}),v=new Map;function le(e){return k.get(e)?v.get(e)??null:null}const ue={activeTheme:it,settingUpPassword:!1},ct=Q({mode:"hub",securityConfig:g,tokenStore:w,rateLimiter:_,settings:ce,terminalBufferConfig:j,state:ue,federation:{getConfig:()=>I,setConfig:async e=>{I=e,await tt(e),fe(e)},status:ut,hostname:E()},hub:{agents:k,getChannel:le}}),lt=Q({mode:"agent",securityConfig:g,tokenStore:w,rateLimiter:_,settings:ce,terminalBufferConfig:j,state:ue});let I=await et(),O=null;function de(){O&&(O.stop(),O=null)}function fe(e){de(),!(!e.enabled||!e.hub||!e.token)&&(O=nt({hub:e.hub,token:e.token,name:e.name?.trim()||E(),version:Ae,app:lt,listSessions:Le,terminalBufferConfig:j,getSessionPaneTarget:ee,capturePaneTail:te,capturePaneHistoryChunk:ne,toCrlf:oe,handleClientMessage:Y,acquireControlClient:q}))}function ut(){return I.enabled?O?O.status():{state:"idle",agentId:null,hub:I.hub??"",name:I.name??E()}:{state:"idle",agentId:null,hub:I.hub??"",name:I.name??E()}}fe(I);const z=new ot,B=new Map;setInterval(()=>{(async()=>{try{const e=await z.scan(),t=[];for(const[o,n]of e)B.get(o)!==n&&t.push({session:o,state:n});for(const o of B.keys())e.has(o)||t.push({session:o,state:"idle"});B.clear();for(const[o,n]of e)B.set(o,n);for(const o of t)me({type:"session.activity",session:o.session,state:o.state})}catch{}})()},z.scanMs);const dt=parseInt(process.env.PORT||"21000",10);function ft(){const e=[];try{for(const t of Object.values(_e()))for(const o of t??[])o.family==="IPv4"&&!o.internal&&e.push(o.address)}catch{}return e}function mt(){try{const e=P.join(Z(),"hub.pid");if(ke(P.dirname(e),{recursive:!0}),D(e)){const t=Number(V(e,"utf8").trim());if(Number.isFinite(t)&&t>0&&t!==process.pid)try{process.kill(t,0),console.warn(`[hub] warning: another tmux-weblink (pid ${t}) is using ${Z()}. Two hubs sharing a data directory will pause or resume each other's bots.`)}catch{}}Se(e,String(process.pid),{mode:384}),process.once("exit",()=>{try{V(e,"utf8").trim()===String(process.pid)&&ve(e)}catch{}})}catch{}}mt();const pt=xe({fetch:ct.fetch,port:dt,hostname:"0.0.0.0"},e=>{console.log(`tmux-web running at http://localhost:${e.port}`);for(const t of ft())console.log(` also on http://${t}:${e.port}`)}),$=new Ie({noServer:!0}),G=new Set;function me(e){const t=JSON.stringify(e);for(const o of G)o.readyState===F.OPEN&&o.send(t)}function x(e,t,o){e.write(`HTTP/1.1 ${t} ${o}\r
2
+ import{chmodSync as ye,existsSync as D,mkdirSync as ke,readdirSync as we,readFileSync as V,statSync as Te,unlinkSync as ve,writeFileSync as Se}from"node:fs";import{createRequire as X}from"node:module";import{hostname as E,networkInterfaces as _e}from"node:os";const be=X(import.meta.url),{version:Ae}=be("../package.json");import P from"node:path";import{fileURLToPath as Ce}from"node:url";import{serve as xe}from"@hono/node-server";import{WebSocketServer as Ie,WebSocket as F}from"ws";try{const e=P.dirname(X(import.meta.url).resolve("node-pty/package.json")),t=P.join(e,"prebuilds");if(D(t))for(const o of we(t)){const n=P.join(t,o,"spawn-helper");D(n)&&!(Te(n).mode&73)&&ye(n,493)}}catch{}import{loadSecurityConfig as Pe}from"./lib/security-config.js";import{TokenStore as Re,hashPassword as $e,verifyPassword as Me,validatePassword as Oe}from"./lib/auth.js";import{RateLimiter as Ne}from"./lib/rateLimiter.js";import{audit as d}from"./lib/auditLog.js";import{db as N}from"./lib/db.js";import{handleClientMessage as Y}from"./lib/ws-message.js";import{loadDotEnv as Ue}from"./lib/load-env.js";import{listSessions as Le,resolveTmuxSocketPath as Ee}from"./sessions.js";import{cmdSetup as Fe,cmdTheme as je,printUsage as K,printVersion as He}from"./lib/cli.js";import{readSettings as Be}from"./lib/settings.js";import{readActiveTheme as We}from"./lib/theme-store.js";import{buildApp as Q}from"./lib/build-app.js";import{shutdownBots as De}from"./lib/bots/manager.js";import{getDataRoot as Z}from"./lib/state-paths.js";import{getBotManager as Je}from"./lib/bots/manager.js";import{attachTerminal as ze,killAllAttachedPtys as Ge}from"./lib/attach-terminal.js";import{acquireControlClient as q,killAllControlClients as Ve}from"./lib/tmux-control.js";import{getSessionPaneTarget as ee,capturePaneTail as te,capturePaneHistoryChunk as ne,toCrlf as oe}from"./lib/tmux-capture.js";import{readTerminalBufferConfig as Xe}from"./lib/terminal-config.js";import{AgentRegistry as Ye}from"./lib/agent-registry.js";import{AgentChannel as Ke,MAX_RELAY_CONNS_PER_AGENT as Qe}from"./lib/agent-relay.js";import{findAgentTokenByPlaintext as Ze,listAgentTokens as qe}from"./lib/agent-tokens.js";import{saveSecurityConfig as et}from"./lib/security-config.js";import{readFederationConfig as tt,writeFederationConfig as nt}from"./lib/federation-config.js";import{startAgentClient as ot}from"./lib/agent-client.js";import{ActivityProbe as rt}from"./lib/activity-probe.js";import{upsertSessionState as re}from"./lib/session-state.js";import{sessionWorkingPath as st}from"./lib/sessions-sidebar.js";Ue();const j=Xe(),g=Pe(),w=new Re,_=new Ne;let J=!1;const at="tmux-web-token";function H(e){if(g.security.trustProxy){const t=(e.headers["x-forwarded-for"]||"").split(",")[0].trim();if(t)return t}return e.socket.remoteAddress||"unknown"}function U(e){const t=e.headers.authorization;if(typeof t=="string"&&t.startsWith("Bearer "))return t.slice(7);const o=e.headers.cookie;if(typeof o!="string")return null;const n=o.match(new RegExp(`(?:^|;\\s*)${at}=([^;]+)`));return n?decodeURIComponent(n[1]):null}function rn(e){const t=U(e);return t?w.validateToken(t):null}const M=new Map;function it(e){let t=0;for(const o of M.values())o.ip===e&&t++;return t}function C(e,t,o){try{e.close(t,o)}catch{}}function se(e,t){e.readyState===F.OPEN&&e.send(JSON.stringify(t))}const ae=process.argv.slice(2),L=ae;if(L.length>0){const[e,t]=L;switch(e){case"setup":await Fe(L),process.exit(0);case"theme":await je(L.slice(1)),process.exit(0);case"agent":{const o=P.join(P.dirname(Ce(import.meta.url)),"agent.js"),{spawn:n}=await import("node:child_process"),l=n(process.execPath,[o,...ae],{stdio:"inherit"});l.on("error",a=>{console.error(a),process.exit(1)}),l.on("exit",a=>process.exit(a??0)),await new Promise(()=>{})}case"agent-token":await St(L.slice(1)),process.exit(0);case"help":case"--help":case"-h":K(),process.exit(0);case"-V":case"--version":case"-v":He(),process.exit(0);default:console.error(`unknown argument: ${e}`),K(),process.exit(1)}}function R(e,t){e.readyState===F.OPEN&&e.send(JSON.stringify(t))}const ie=new Set;await N.read(),N.data.sessionAccess??=[],N.data.pinnedViews??=[],N.data.watchedPanes??=[],N.data.quickCommands??=[];const ce=await Be();let ct=await We();const k=new Ye({onChange:()=>{}}),v=new Map;function le(e){return k.get(e)?v.get(e)??null:null}const ue={activeTheme:ct,settingUpPassword:!1},lt=Q({mode:"hub",securityConfig:g,tokenStore:w,rateLimiter:_,settings:ce,terminalBufferConfig:j,state:ue,federation:{getConfig:()=>I,setConfig:async e=>{I=e,await nt(e),fe(e)},status:dt,hostname:E()},hub:{agents:k,getChannel:le}}),ut=Q({mode:"agent",securityConfig:g,tokenStore:w,rateLimiter:_,settings:ce,terminalBufferConfig:j,state:ue});let I=await tt(),O=null;function de(){O&&(O.stop(),O=null)}function fe(e){de(),!(!e.enabled||!e.hub||!e.token)&&(O=ot({hub:e.hub,token:e.token,name:e.name?.trim()||E(),version:Ae,app:ut,listSessions:Le,terminalBufferConfig:j,getSessionPaneTarget:ee,capturePaneTail:te,capturePaneHistoryChunk:ne,toCrlf:oe,handleClientMessage:Y,acquireControlClient:q}))}function dt(){return I.enabled?O?O.status():{state:"idle",agentId:null,hub:I.hub??"",name:I.name??E()}:{state:"idle",agentId:null,hub:I.hub??"",name:I.name??E()}}fe(I);const z=new rt,B=new Map;setInterval(()=>{(async()=>{try{const e=await z.scan(),t=[];for(const[o,n]of e)B.get(o)!==n&&t.push({session:o,state:n});for(const o of B.keys())e.has(o)||t.push({session:o,state:"idle"});B.clear();for(const[o,n]of e)B.set(o,n);for(const o of t)me({type:"session.activity",session:o.session,state:o.state})}catch{}})()},z.scanMs);const ft=parseInt(process.env.PORT||"21000",10);function mt(){const e=[];try{for(const t of Object.values(_e()))for(const o of t??[])o.family==="IPv4"&&!o.internal&&e.push(o.address)}catch{}return e}function pt(){try{const e=P.join(Z(),"hub.pid");if(ke(P.dirname(e),{recursive:!0}),D(e)){const t=Number(V(e,"utf8").trim());if(Number.isFinite(t)&&t>0&&t!==process.pid)try{process.kill(t,0),console.warn(`[hub] warning: another tmux-weblink (pid ${t}) is using ${Z()}. Two hubs sharing a data directory will pause or resume each other's bots.`)}catch{}}Se(e,String(process.pid),{mode:384}),process.once("exit",()=>{try{V(e,"utf8").trim()===String(process.pid)&&ve(e)}catch{}})}catch{}}pt();const ht=xe({fetch:lt.fetch,port:ft,hostname:"0.0.0.0"},e=>{console.log(`tmux-web running at http://localhost:${e.port}`);for(const t of mt())console.log(` also on http://${t}:${e.port}`)}),$=new Ie({noServer:!0}),G=new Set;function me(e){const t=JSON.stringify(e);for(const o of G)o.readyState===F.OPEN&&o.send(t)}function x(e,t,o){e.write(`HTTP/1.1 ${t} ${o}\r
3
3
  \r
4
- `),e.destroy()}pt.on("upgrade",(e,t,o)=>{const n=new URL(e.url||"/",`http://${e.headers.host}`),l=n.pathname;if(l==="/ws/activity"){const s=H(e),r=U(e)||n.searchParams.get("token")||"";if(!(r?w.validateToken(r):null)){x(t,401,"Unauthorized");return}$.handleUpgrade(e,t,o,m=>{m.on("close",()=>G.delete(m)),G.add(m)});return}const a=l.match(/^\/ws\/bots\/([^/]+)$/);if(a){const s=U(e)||n.searchParams.get("token")||"";if(!(s?w.validateToken(s):null)){x(t,401,"Unauthorized");return}const c=decodeURIComponent(a[1]);$.handleUpgrade(e,t,o,m=>{De().attachSocket(c,m)});return}if(l==="/agent/ws"){kt(e,t,o);return}const i=l.match(/^\/ws\/a\/([^/]+)\/(.+)$/);if(i){ht(e,t,o,decodeURIComponent(i[1]),decodeURIComponent(i[2]));return}const u=l.match(/^\/ws\/(.+)$/);if(!u){t.destroy();return}const f=H(e),p=e.headers.origin,h=g.security.allowedOrigins;if(p&&!(p===`http://${e.headers.host}`||p===`https://${e.headers.host}`)&&(h.length===0||!h.includes(p))){d("ws_rejected_origin",{ip:f,origin:p}),x(t,403,"Origin not allowed");return}const y=at(f);if(y>=g.security.maxConnectionsPerIp){d("ws_rejected_per_ip_cap",{ip:f,liveFromIp:y}),x(t,429,"Too many connections");return}const T=U(e)||n.searchParams.get("token")||"",b=T?w.validateToken(T):null;$.handleUpgrade(e,t,o,s=>{$.emit("connection",s,e,decodeURIComponent(u[1]),f,b)})}),$.on("connection",(e,t,o,n,l)=>{const a={ws:e,ip:n,authenticated:!1,authTimeout:null},i=(()=>{try{const s=new URL(t.url||"/",`http://${t.headers.host}`).searchParams,r=Number(s.get("cols")),c=Number(s.get("rows"));if(Number.isInteger(r)&&Number.isInteger(c)&&r>0&&c>0&&r<=1e3&&c<=1e3)return{cols:r,rows:c}}catch{}})();M.set(e,a),d("ws_connected",{ip:n});let u=null,f=null;function p(s,r){a.authenticated=!0,a.authTimeout&&(clearTimeout(a.authTimeout),a.authTimeout=null),d("auth_success",{ip:n,method:s,tokenName:r}),R(e,{type:"auth.ok",setupMode:!g.passwordHash}),y()}function h(s,r={}){R(e,{type:"auth.failed",message:s,...r})}function y(){u||(z.suppress(o),re(o,{path:rt(o)}),u=Je(o,{send:s=>R(e,s),onMessage:s=>{f=s},onClose:s=>{T=s}},{terminalBufferConfig:j,getSessionPaneTarget:ee,capturePaneTail:te,capturePaneHistoryChunk:ne,toCrlf:oe,handleClientMessage:Y,acquireControlClient:q,initialCols:i?.cols,initialRows:i?.rows,tmuxSocketPath:Ee()??void 0,onPtyExit:(s,r)=>C(e,1e3,"pty exited"),onSpawnError:(s,r)=>C(e,1011,"pty spawn failed")}))}let T=null;async function b(s){let r;try{r=JSON.parse(s)}catch{return!1}if(r.type==="auth.token"&&typeof r.token=="string"){const c=w.validateToken(r.token);if(!c){d("token_auth_failed",{ip:n});const m=_.recordFailure(n);return m.permanentLock&&(w.revokeAll(),d("permanent_lock",{ip:n,failures:m.failures})),h("Invalid or expired token",{permanentLock:m.permanentLock,retryAfterMs:m.retryAfterMs}),!0}return w.touch(c.tokenHash),p("token",c.name),!0}if(r.type==="auth"&&typeof r.password=="string"){const c=_.check(n);if(!c.allowed)return d("rate_limited",{ip:n,retryAfterMs:c.retryAfterMs,permanentLock:c.permanentLock}),h("Too many attempts",{permanentLock:c.permanentLock,retryAfterMs:c.retryAfterMs}),!0;if(!g.passwordHash){if(!g.security.allowRemoteSetup&&!Tt(n))return d("setup_rejected_remote",{ip:n}),h("First-run setup must be performed from localhost"),!0;if(J)return h("Password setup in progress"),!0;const A=Oe(r.password);if(A)return h(A),!0;J=!0;try{g.passwordHash=await $e(r.password),qe(g),d("password_set",{ip:n})}finally{J=!1}const{stored:W,plaintext:ge}=w.createAccessToken("setup",g.security.tokenTtlDays);return R(e,{type:"auth.ok",setupMode:!0,token:ge}),d("token_created",{ip:n,name:W.name,tokenId:W.id}),d("auth_success",{ip:n,method:"password",tokenName:W.name}),y(),!0}if(!g.passwordHash)return h("Server not configured"),!0;if(!await Me(r.password,g.passwordHash)){const A=_.recordFailure(n);return d("auth_failed",{ip:n,method:"password",failures:A.failures,permanentLock:A.permanentLock}),A.permanentLock&&(w.revokeAll(),d("permanent_lock",{ip:n,failures:A.failures})),h("Incorrect password",{permanentLock:A.permanentLock,retryAfterMs:A.retryAfterMs}),!0}_.recordSuccess(n);const S=`ws-${n}`,{plaintext:he}=w.createAccessToken(S,g.security.tokenTtlDays);return p("password",S),R(e,{type:"auth.ok",setupMode:!1,token:he}),!0}return!1}l?(w.touch(l.tokenHash),p("token",l.name)):(R(e,{type:"auth.required",setupMode:!g.passwordHash}),a.authTimeout=setTimeout(()=>{a.authenticated||(d("auth_timeout",{ip:n}),h("Authentication timeout"),C(e,4e3,"Auth timeout"))},g.security.authTimeoutMs)),e.on("message",async s=>{const r=typeof s=="string"?s:s.toString("utf-8");if(!a.authenticated){if(r.length>1e6){R(e,{type:"auth.failed",message:"Message too large"});return}await b(r)||h("Authentication required");return}if(f)try{f(r)}catch{}}),e.on("close",()=>{a.authTimeout&&clearTimeout(a.authTimeout),M.delete(e),d("ws_disconnected",{ip:n}),T?.(),u&&(u.dispose(),u=null)}),e.on("error",()=>{a.authTimeout&&clearTimeout(a.authTimeout),M.delete(e),T?.(),u&&(u.dispose(),u=null)})});function ht(e,t,o,n,l){const a=H(e),i=new URL(e.url||"/",`http://${e.headers.host}`),u=U(e)||i.searchParams.get("token")||"";if(!(u?w.validateToken(u):null)){d("ws_rejected_remote_auth",{ip:a,agentId:n}),x(t,401,"Unauthorized");return}const p=le(n);if(!p){d("ws_rejected_remote_offline",{ip:a,agentId:n}),x(t,503,"Agent offline");return}if(p.relayCount>=Ke){x(t,429,"Too many connections to agent");return}const h=e.headers.origin,y=g.security.allowedOrigins;if(h&&!(h===`http://${e.headers.host}`||h===`https://${e.headers.host}`)&&(y.length===0||!y.includes(h))){x(t,403,"Origin not allowed");return}const T=yt(),b=(()=>{try{const s=new URL(e.url||"/",`http://${e.headers.host}`).searchParams,r=Number(s.get("cols")),c=Number(s.get("rows"));if(Number.isInteger(r)&&Number.isInteger(c)&&r>0&&c>0&&r<=1e3&&c<=1e3)return{cols:r,rows:c}}catch{}})();$.handleUpgrade(e,t,o,s=>{if(p.registerRelay(T,l,s),k.bumpRelayConns(n,1),re(l,{agentId:n}),!p.attach(T,l,b)){s.send(JSON.stringify({type:"data",data:`\r
4
+ `),e.destroy()}ht.on("upgrade",(e,t,o)=>{const n=new URL(e.url||"/",`http://${e.headers.host}`),l=n.pathname;if(l==="/ws/activity"){const s=H(e),r=U(e)||n.searchParams.get("token")||"";if(!(r?w.validateToken(r):null)){x(t,401,"Unauthorized");return}$.handleUpgrade(e,t,o,m=>{m.on("close",()=>G.delete(m)),G.add(m)});return}const a=l.match(/^\/ws\/bots\/([^/]+)$/);if(a){const s=U(e)||n.searchParams.get("token")||"";if(!(s?w.validateToken(s):null)){x(t,401,"Unauthorized");return}const c=decodeURIComponent(a[1]);$.handleUpgrade(e,t,o,m=>{Je().attachSocket(c,m)});return}if(l==="/agent/ws"){wt(e,t,o);return}const i=l.match(/^\/ws\/a\/([^/]+)\/(.+)$/);if(i){gt(e,t,o,decodeURIComponent(i[1]),decodeURIComponent(i[2]));return}const u=l.match(/^\/ws\/(.+)$/);if(!u){t.destroy();return}const f=H(e),p=e.headers.origin,h=g.security.allowedOrigins;if(p&&!(p===`http://${e.headers.host}`||p===`https://${e.headers.host}`)&&(h.length===0||!h.includes(p))){d("ws_rejected_origin",{ip:f,origin:p}),x(t,403,"Origin not allowed");return}const y=it(f);if(y>=g.security.maxConnectionsPerIp){d("ws_rejected_per_ip_cap",{ip:f,liveFromIp:y}),x(t,429,"Too many connections");return}const T=U(e)||n.searchParams.get("token")||"",b=T?w.validateToken(T):null;$.handleUpgrade(e,t,o,s=>{$.emit("connection",s,e,decodeURIComponent(u[1]),f,b)})}),$.on("connection",(e,t,o,n,l)=>{const a={ws:e,ip:n,authenticated:!1,authTimeout:null},i=(()=>{try{const s=new URL(t.url||"/",`http://${t.headers.host}`).searchParams,r=Number(s.get("cols")),c=Number(s.get("rows"));if(Number.isInteger(r)&&Number.isInteger(c)&&r>0&&c>0&&r<=1e3&&c<=1e3)return{cols:r,rows:c}}catch{}})();M.set(e,a),d("ws_connected",{ip:n});let u=null,f=null;function p(s,r){a.authenticated=!0,a.authTimeout&&(clearTimeout(a.authTimeout),a.authTimeout=null),d("auth_success",{ip:n,method:s,tokenName:r}),R(e,{type:"auth.ok",setupMode:!g.passwordHash}),y()}function h(s,r={}){R(e,{type:"auth.failed",message:s,...r})}function y(){u||(z.suppress(o),re(o,{path:st(o)}),u=ze(o,{send:s=>R(e,s),onMessage:s=>{f=s},onClose:s=>{T=s}},{terminalBufferConfig:j,getSessionPaneTarget:ee,capturePaneTail:te,capturePaneHistoryChunk:ne,toCrlf:oe,handleClientMessage:Y,acquireControlClient:q,initialCols:i?.cols,initialRows:i?.rows,tmuxSocketPath:Ee()??void 0,onPtyExit:(s,r)=>C(e,1e3,"pty exited"),onSpawnError:(s,r)=>C(e,1011,"pty spawn failed")}))}let T=null;async function b(s){let r;try{r=JSON.parse(s)}catch{return!1}if(r.type==="auth.token"&&typeof r.token=="string"){const c=w.validateToken(r.token);if(!c){d("token_auth_failed",{ip:n});const m=_.recordFailure(n);return m.permanentLock&&(w.revokeAll(),d("permanent_lock",{ip:n,failures:m.failures})),h("Invalid or expired token",{permanentLock:m.permanentLock,retryAfterMs:m.retryAfterMs}),!0}return w.touch(c.tokenHash),p("token",c.name),!0}if(r.type==="auth"&&typeof r.password=="string"){const c=_.check(n);if(!c.allowed)return d("rate_limited",{ip:n,retryAfterMs:c.retryAfterMs,permanentLock:c.permanentLock}),h("Too many attempts",{permanentLock:c.permanentLock,retryAfterMs:c.retryAfterMs}),!0;if(!g.passwordHash){if(!g.security.allowRemoteSetup&&!vt(n))return d("setup_rejected_remote",{ip:n}),h("First-run setup must be performed from localhost"),!0;if(J)return h("Password setup in progress"),!0;const A=Oe(r.password);if(A)return h(A),!0;J=!0;try{g.passwordHash=await $e(r.password),et(g),d("password_set",{ip:n})}finally{J=!1}const{stored:W,plaintext:ge}=w.createAccessToken("setup",g.security.tokenTtlDays);return R(e,{type:"auth.ok",setupMode:!0,token:ge}),d("token_created",{ip:n,name:W.name,tokenId:W.id}),d("auth_success",{ip:n,method:"password",tokenName:W.name}),y(),!0}if(!g.passwordHash)return h("Server not configured"),!0;if(!await Me(r.password,g.passwordHash)){const A=_.recordFailure(n);return d("auth_failed",{ip:n,method:"password",failures:A.failures,permanentLock:A.permanentLock}),A.permanentLock&&(w.revokeAll(),d("permanent_lock",{ip:n,failures:A.failures})),h("Incorrect password",{permanentLock:A.permanentLock,retryAfterMs:A.retryAfterMs}),!0}_.recordSuccess(n);const S=`ws-${n}`,{plaintext:he}=w.createAccessToken(S,g.security.tokenTtlDays);return p("password",S),R(e,{type:"auth.ok",setupMode:!1,token:he}),!0}return!1}l?(w.touch(l.tokenHash),p("token",l.name)):(R(e,{type:"auth.required",setupMode:!g.passwordHash}),a.authTimeout=setTimeout(()=>{a.authenticated||(d("auth_timeout",{ip:n}),h("Authentication timeout"),C(e,4e3,"Auth timeout"))},g.security.authTimeoutMs)),e.on("message",async s=>{const r=typeof s=="string"?s:s.toString("utf-8");if(!a.authenticated){if(r.length>1e6){R(e,{type:"auth.failed",message:"Message too large"});return}await b(r)||h("Authentication required");return}if(f)try{f(r)}catch{}}),e.on("close",()=>{a.authTimeout&&clearTimeout(a.authTimeout),M.delete(e),d("ws_disconnected",{ip:n}),T?.(),u&&(u.dispose(),u=null)}),e.on("error",()=>{a.authTimeout&&clearTimeout(a.authTimeout),M.delete(e),T?.(),u&&(u.dispose(),u=null)})});function gt(e,t,o,n,l){const a=H(e),i=new URL(e.url||"/",`http://${e.headers.host}`),u=U(e)||i.searchParams.get("token")||"";if(!(u?w.validateToken(u):null)){d("ws_rejected_remote_auth",{ip:a,agentId:n}),x(t,401,"Unauthorized");return}const p=le(n);if(!p){d("ws_rejected_remote_offline",{ip:a,agentId:n}),x(t,503,"Agent offline");return}if(p.relayCount>=Qe){x(t,429,"Too many connections to agent");return}const h=e.headers.origin,y=g.security.allowedOrigins;if(h&&!(h===`http://${e.headers.host}`||h===`https://${e.headers.host}`)&&(y.length===0||!y.includes(h))){x(t,403,"Origin not allowed");return}const T=kt(),b=(()=>{try{const s=new URL(e.url||"/",`http://${e.headers.host}`).searchParams,r=Number(s.get("cols")),c=Number(s.get("rows"));if(Number.isInteger(r)&&Number.isInteger(c)&&r>0&&c>0&&r<=1e3&&c<=1e3)return{cols:r,rows:c}}catch{}})();$.handleUpgrade(e,t,o,s=>{if(p.registerRelay(T,l,s),k.bumpRelayConns(n,1),re(l,{agentId:n}),!p.attach(T,l,b)){s.send(JSON.stringify({type:"data",data:`\r
5
5
  \x1B[31magent offline\x1B[0m\r
6
- `})),s.close(1011,"agent offline"),p.relayClosed(T),k.bumpRelayConns(n,-1);return}s.on("message",c=>{const m=typeof c=="string"?c:c.toString("utf-8");let S;try{S=JSON.parse(m)}catch{return}(S.type==="input"||S.type==="resize"||S.type==="load_history")&&p.sendToAgent(T,S)});const r=()=>{p.relayClosed(T),k.bumpRelayConns(n,-1)};s.on("close",r),s.on("error",r)})}let gt=1;function yt(){return gt++}function kt(e,t,o){const n=H(e),l=e.headers.origin;if(l){d("agent_rejected_origin",{ip:n,origin:l}),x(t,403,"Origin not allowed");return}$.handleUpgrade(e,t,o,a=>{let i=null,u=setTimeout(()=>{d("agent_hello_timeout",{ip:n}),C(a,4e3,"hello timeout")},1e4);a.on("message",(f,p)=>{if(i){k.touch(i.agentId),p?i.handleData(Array.isArray(f)?Buffer.concat(f):Buffer.from(f)):i.handleMessage(typeof f=="string"?f:Buffer.from(f).toString("utf-8"));return}const h=typeof f=="string"?f:f.toString("utf-8");let y;try{y=JSON.parse(h)}catch{C(a,1008,"bad hello");return}if(y.type!=="hello"||typeof y.token!="string"){C(a,1008,"expected hello");return}if(!_.check(n).allowed){d("agent_rate_limited",{ip:n}),C(a,429,"Too many attempts");return}const b=Qe(y.token);if(!b){_.recordFailure(n),d("agent_bad_token",{ip:n}),se(a,{type:"hello_err",reason:"invalid token"}),C(a,4003,"invalid token");return}const s=typeof y.name=="string"&&y.name.trim()?y.name.trim().slice(0,64):"agent",r=b.id;if(!k.register(r,s,a,b.tokenHash)){d("agent_cap_reached",{ip:n}),se(a,{type:"hello_err",reason:"too many agents"}),C(a,4004,"too many agents");return}clearTimeout(u),_.recordSuccess(n),d("agent_connected",{ip:n,agentId:r,name:s}),i=new Ye(a,r,{onSessions:m=>k.setSessions(r,m),onActivity:m=>{for(const S of m)me({type:"session.activity",agentId:r,session:S.session,state:S.state})},onRebuildResult:m=>{console.log(`[agent ${r}] rebuild ${m.session}: ${m.ok?"ok":m.message}`)},onClose:m=>{v.get(r)===m&&v.delete(r)}}),v.set(r,i),k.touch(r),a.send(JSON.stringify({type:"hello_ok",agentId:r})),i.sendSessionsReq()}),a.on("close",()=>{i&&(i.dispose(),v.delete(i.agentId),k.unregister(i.agentId),d("agent_disconnected",{ip:n,agentId:i.agentId})),clearTimeout(u)}),a.on("error",()=>{i&&(i.dispose(),v.delete(i.agentId),k.unregister(i.agentId)),clearTimeout(u)})})}const wt=parseInt(process.env.TMUX_WEB_AGENT_OFFLINE_MS||"45000",10);setInterval(()=>{const e=k.pruneOffline(wt);for(const o of e){const n=k.peek(o);n&&n.ws.readyState===F.CLOSED&&(k.unregister(o),v.get(o)?.dispose(),v.delete(o))}const t=new Set(Ze().map(o=>o.tokenHash));for(const[o,n]of v){const l=k.peek(o);if(!(!l||t.has(l.tokenHash))){d("agent_token_revoked",{agentId:o}),n.dispose(),v.delete(o),k.unregister(o);try{l.ws.close(4003,"token revoked")}catch{}}}w.purgeExpired()},10*1e3).unref();function pe(){de(),Ge(),ze();for(const e of v.values())e.dispose();v.clear();for(const[e,t]of M){try{e.close(1001,"Server shutting down")}catch{}t.authTimeout&&clearTimeout(t.authTimeout)}M.clear();for(const e of ie)try{e.kill()}catch{}ie.clear(),_.dispose(),process.exit(0)}process.on("SIGINT",pe),process.on("SIGTERM",pe);function Tt(e){return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}async function vt(e){const{createAgentToken:t,listAgentTokens:o,removeAgentToken:n}=await import("./lib/agent-tokens.js"),[l,...a]=e;switch(l){case"add":{const i=a.find(p=>!p.startsWith("-"))||"agent",{id:u,token:f}=t(i);console.log("\u2713 agent token created"),console.log(` id: ${u}`),console.log(` name: ${i}`),console.log(` token: ${f}`),console.log(`
6
+ `})),s.close(1011,"agent offline"),p.relayClosed(T),k.bumpRelayConns(n,-1);return}s.on("message",c=>{const m=typeof c=="string"?c:c.toString("utf-8");let S;try{S=JSON.parse(m)}catch{return}(S.type==="input"||S.type==="resize"||S.type==="load_history")&&p.sendToAgent(T,S)});const r=()=>{p.relayClosed(T),k.bumpRelayConns(n,-1)};s.on("close",r),s.on("error",r)})}let yt=1;function kt(){return yt++}function wt(e,t,o){const n=H(e),l=e.headers.origin;if(l){d("agent_rejected_origin",{ip:n,origin:l}),x(t,403,"Origin not allowed");return}$.handleUpgrade(e,t,o,a=>{let i=null,u=setTimeout(()=>{d("agent_hello_timeout",{ip:n}),C(a,4e3,"hello timeout")},1e4);a.on("message",(f,p)=>{if(i){k.touch(i.agentId),p?i.handleData(Array.isArray(f)?Buffer.concat(f):Buffer.from(f)):i.handleMessage(typeof f=="string"?f:Buffer.from(f).toString("utf-8"));return}const h=typeof f=="string"?f:f.toString("utf-8");let y;try{y=JSON.parse(h)}catch{C(a,1008,"bad hello");return}if(y.type!=="hello"||typeof y.token!="string"){C(a,1008,"expected hello");return}if(!_.check(n).allowed){d("agent_rate_limited",{ip:n}),C(a,429,"Too many attempts");return}const b=Ze(y.token);if(!b){_.recordFailure(n),d("agent_bad_token",{ip:n}),se(a,{type:"hello_err",reason:"invalid token"}),C(a,4003,"invalid token");return}const s=typeof y.name=="string"&&y.name.trim()?y.name.trim().slice(0,64):"agent",r=b.id;if(!k.register(r,s,a,b.tokenHash)){d("agent_cap_reached",{ip:n}),se(a,{type:"hello_err",reason:"too many agents"}),C(a,4004,"too many agents");return}clearTimeout(u),_.recordSuccess(n),d("agent_connected",{ip:n,agentId:r,name:s}),i=new Ke(a,r,{onSessions:m=>k.setSessions(r,m),onActivity:m=>{for(const S of m)me({type:"session.activity",agentId:r,session:S.session,state:S.state})},onRebuildResult:m=>{console.log(`[agent ${r}] rebuild ${m.session}: ${m.ok?"ok":m.message}`)},onClose:m=>{v.get(r)===m&&v.delete(r)}}),v.set(r,i),k.touch(r),a.send(JSON.stringify({type:"hello_ok",agentId:r})),i.sendSessionsReq()}),a.on("close",()=>{i&&(i.dispose(),v.delete(i.agentId),k.unregister(i.agentId),d("agent_disconnected",{ip:n,agentId:i.agentId})),clearTimeout(u)}),a.on("error",()=>{i&&(i.dispose(),v.delete(i.agentId),k.unregister(i.agentId)),clearTimeout(u)})})}const Tt=parseInt(process.env.TMUX_WEB_AGENT_OFFLINE_MS||"45000",10);setInterval(()=>{const e=k.pruneOffline(Tt);for(const o of e){const n=k.peek(o);n&&n.ws.readyState===F.CLOSED&&(k.unregister(o),v.get(o)?.dispose(),v.delete(o))}const t=new Set(qe().map(o=>o.tokenHash));for(const[o,n]of v){const l=k.peek(o);if(!(!l||t.has(l.tokenHash))){d("agent_token_revoked",{agentId:o}),n.dispose(),v.delete(o),k.unregister(o);try{l.ws.close(4003,"token revoked")}catch{}}}w.purgeExpired()},10*1e3).unref();function pe(){De(),de(),Ve(),Ge();for(const e of v.values())e.dispose();v.clear();for(const[e,t]of M){try{e.close(1001,"Server shutting down")}catch{}t.authTimeout&&clearTimeout(t.authTimeout)}M.clear();for(const e of ie)try{e.kill()}catch{}ie.clear(),_.dispose(),process.exit(0)}process.on("SIGINT",pe),process.on("SIGTERM",pe);function vt(e){return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}async function St(e){const{createAgentToken:t,listAgentTokens:o,removeAgentToken:n}=await import("./lib/agent-tokens.js"),[l,...a]=e;switch(l){case"add":{const i=a.find(p=>!p.startsWith("-"))||"agent",{id:u,token:f}=t(i);console.log("\u2713 agent token created"),console.log(` id: ${u}`),console.log(` name: ${i}`),console.log(` token: ${f}`),console.log(`
7
7
  Run on the remote machine:`),console.log(` tmux-web agent --hub wss://YOUR_HUB --token ${f} --name "${i}"`);return}case"list":{const i=o();if(!i.length){console.log("No agent tokens. Create one with: tmux-web agent-token add --name <name>");return}console.log("Agent tokens:");for(const u of i)console.log(` ${u.id} ${u.name} (created ${new Date(u.createdAt).toISOString()})`);return}case"remove":{const i=a.find(f=>!f.startsWith("-"));i||(console.error("usage: tmux-web agent-token remove <id>"),process.exit(1)),n(i)||(console.error(`no token with id ${i}`),process.exit(1)),console.log(`\u2713 token ${i} removed`);return}default:console.error("usage: tmux-web agent-token <add|list|remove>"),process.exit(1)}}
@@ -1,4 +1,4 @@
1
- import{execFileSync as v}from"node:child_process";import{mkdirSync as m,readFileSync as I,rmSync as A,writeFileSync as T}from"node:fs";import h from"node:path";import _ from"node:os";import{getBotStore as B}from"./store.js";import{materialize as O}from"./materialize.js";import{PiRpc as j}from"./rpc.js";import{buildCatalog as M,ORCHESTRATION_TOOLS as b,READONLY_TOOLS as D}from"./catalog.js";import{TERMINAL_STATUSES as d}from"./types.js";const g=4,k=8,P=["starting","running","waiting_input","waiting_approval"];function f(c){return Array.isArray(c)?c.map(t=>{if(typeof t=="string")return t;if(!t||typeof t!="object")return"";const e=t;if(typeof e.text=="string")return e.text;const s=e.content;return Array.isArray(s)?s.map(n=>n&&typeof n=="object"&&typeof n.text=="string"?String(n.text):"").join(""):""}).map(t=>t.replace(/\s+/g," ").trim()).filter(Boolean):[]}class q{store=B();token;apiBase;runtimes=new Map;sockets=new Map;listeners=new Set;approvals=new Map;recent=new Map;streaming=new Set;constructor(t){this.token=this.store.token,this.apiBase=`http://127.0.0.1:${t}/api/bots`;for(const e of this.store.listInstances()){let s=!1,n=!1;!d.includes(e.status)&&e.status!=="queued"&&(e.status="stale",n=!0,s=!0);const r=y(e.runtimeMode);if(r!==e.runtimeMode&&(e.runtimeMode=r,s=!0),s&&this.store.saveInstance(e),n){const i=new Date().toISOString();this.emit(e.id,{type:"status",status:"stale",at:i}),this.emit(e.id,{type:"notice",level:"warn",text:"The hub restarted while this bot was running, so it is paused. Press Resume or send a message to continue from its session.",at:i})}}}listTemplates(){return this.store.listTemplates()}getTemplate(t){return this.store.getTemplate(t)}saveTemplate(t){return this.store.saveTemplate(t)}deleteTemplate(t){return this.store.deleteTemplate(t)}catalog(){return M()}listBots(t={}){return this.store.listInstances().filter(s=>!(t.project&&s.projectPath!==t.project||t.parentBotId&&s.parentBotId!==t.parentBotId||t.status&&s.status!==t.status))}getBot(t){return this.store.getInstance(t)}children(t){return this.store.listInstances().filter(e=>e.parentBotId===t)}createInstance(t){const e=this.getTemplate(t.templateId);if(!e)throw new Error(`unknown template: ${t.templateId}`);let s=null;if(t.parentBotId){if(s=this.getBot(t.parentBotId),!s)throw new Error("parent bot not found");if(s.depth+1>g)throw new Error(`nesting depth limit is ${g}`)}let n=t.projectPath||s?.projectPath||process.env.HOME||"/";n==="~"?n=_.homedir():n.startsWith("~/")&&(n=h.join(_.homedir(),n.slice(2)));const r=h.resolve(n),i=this.store.newId(),o=t.isolation||"shared";let l=r;if(o==="worktree"){const p=h.join(this.store.root,"worktrees",i);try{m(h.dirname(p),{recursive:!0,mode:448}),v("git",["-C",r,"worktree","add","-b",`tw-bot/${i.slice(0,8)}`,p],{timeout:2e4,stdio:"ignore"}),l=p}catch{l=r}}const u=new Date().toISOString(),a={id:i,templateId:e.id,title:t.title||e.manifest.name,projectPath:r,workspacePath:l,isolation:o,parentBotId:s?.id,depth:s?s.depth+1:0,runtimeMode:y(t.runtimeMode||e.manifest.permissions?.runtimeMode),projectResources:e.manifest.projectResources||"ignore",status:"queued",sessionFile:h.join(this.store.sessionsDir(i),`${i}.jsonl`),createdAt:u,updatedAt:u,model:e.manifest.model};return m(this.store.sessionsDir(i),{recursive:!0,mode:448}),this.store.saveInstance(a),this.emit(a.id,{type:"status",status:"queued",at:u}),this.pump(),a}activeInProject(t){return this.store.listInstances().filter(e=>e.projectPath===t&&!d.includes(e.status)&&e.status!=="queued").length}pump(){for(const t of this.store.listInstances())t.status==="queued"&&(this.activeInProject(t.projectPath)>=k||this.start(t))}start(t){const e=this.getTemplate(t.templateId);if(!e){this.setStatus(t.id,"failed","template disappeared");return}const s=O(e,t,{apiBase:this.apiBase,token:this.token}),n=e.manifest.binaryPath||"pi",r=new j({command:n,args:s.args,cwd:t.workspacePath,env:s.env,onEvent:i=>this.handleEvent(t.id,i),onStderr:i=>{/error|failed/i.test(i)&&this.emit(t.id,{type:"notice",level:"warn",text:i.slice(0,500),at:new Date().toISOString()})},onExit:()=>{this.runtimes.delete(t.id),this.streaming.delete(t.id);const i=this.store.getInstance(t.id);i&&!d.includes(i.status)&&this.setStatus(t.id,"failed","pi exited unexpectedly"),this.pump()}});this.runtimes.set(t.id,r),t.status="starting",t.pid=void 0,this.store.saveInstance(t),this.emit(t.id,{type:"status",status:"starting",at:new Date().toISOString()}),r.start()}handleEvent(t,e){const s=String(e.type||""),n=new Date().toISOString();switch(s){case"agent_start":this.streaming.add(t),this.setStatus(t,"running");break;case"agent_end":break;case"agent_settled":this.streaming.delete(t),this.setStatus(t,e.aborted===!0?"cancelled":"completed");break;case"message_start":case"message_end":{const r=e.message;if(r){if(s==="message_end"&&r.role==="assistant"){const i=this.store.getInstance(t),o=N(r);i&&o&&(i.lastText=o,this.store.saveInstance(i))}this.emit(t,{type:"message",message:r,at:n})}break}case"message_update":{const r=e.assistantMessageEvent;if(!r)break;const i=r.type==="text_delta"?"text":r.type==="thinking_delta"?"thinking":r.type==="toolcall_delta"?"tool-args":null;if(!i)break;const o=e.message;this.emit(t,{type:"delta",kind:i,delta:String(r.delta||""),contentIndex:typeof r.contentIndex=="number"?r.contentIndex:void 0,messageId:typeof o?.id=="string"?o.id:void 0,at:n});break}case"tool_execution_start":this.emit(t,{type:"tool",phase:"start",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),args:e.args,at:n});break;case"tool_execution_update":this.emit(t,{type:"tool",phase:"update",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:x(e.partialResult),at:n});break;case"tool_execution_end":this.emit(t,{type:"tool",phase:"end",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:x(e.result),isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,at:n});break;case"queue_update":this.emit(t,{type:"queue",steering:f(e.steering),followUp:f(e.followUp),at:n});break;case"extension_ui_request":this.handleUiRequest(t,e);break;default:break}}handleUiRequest(t,e){const s=String(e.method||""),n=new Date().toISOString(),r=this.store.getInstance(t);if(s==="notify"){this.emit(t,{type:"notice",level:e.notifyType==="error"?"error":e.notifyType==="warning"?"warn":"info",text:String(e.message||""),at:n});return}if(!["confirm","select","input","editor"].includes(s))return;const i=String(e.id||""),o=i?this.approvals.get(t)?.get(i):void 0;if(o&&o.state==="pending")return;const l=String(e.title||"Approval required"),u=/^Allow (.+?)\?$/.exec(l),a={id:String(e.id||""),botId:t,botTitle:r?.title||t,kind:s==="confirm"?"tool":"question",method:s,title:l,toolName:u?u[1]:void 0,message:typeof e.message=="string"?e.message:void 0,options:Array.isArray(e.options)?e.options.map(String):void 0,state:"pending",createdAt:n};if(this.approvals.has(t)||this.approvals.set(t,new Map),this.approvals.get(t).set(a.id,a),r&&r.runtimeMode==="parent-supervised"&&r.parentBotId){const p=this.store.getInstance(r.parentBotId);if(p){a.escalatedTo=p.id;const w=a.message?a.message.slice(0,500):"",E=[`Child bot "${r.title}" (${r.id}) needs approval: ${a.title}`,w?`Arguments: ${w}`:"",`Decide with bot_approve({ botId: "${r.id}", requestId: "${a.id}", allow: true|false, reason: "..." }).`,"If you do nothing the user will answer it."].filter(Boolean).join(`
2
- `);this.input(p.id,E,"steer").catch(()=>{this.emit(t,{type:"notice",level:"warn",text:"Could not reach the supervising bot; waiting for the user.",at:n})})}}this.setStatus(t,"waiting_approval"),this.emit(t,{type:"approval",approval:a,at:n})}allowTool(t,e){if(!this.store.getInstance(t))throw new Error("bot not found");const n=h.join(this.store.agentDir(t),".allowed-tools");let r=[];try{r=JSON.parse(I(n,"utf8")),Array.isArray(r)||(r=[])}catch{r=[]}return r.includes(e)||r.push(e),m(h.dirname(n),{recursive:!0,mode:448}),T(n,`${JSON.stringify(r)}
3
- `,{mode:384}),r}allowedTools(t){try{const e=JSON.parse(I(h.join(this.store.agentDir(t),".allowed-tools"),"utf8"));return Array.isArray(e)?e.map(String):[]}catch{return[]}}setRuntimeMode(t,e){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");s.runtimeMode=y(e),this.store.saveInstance(s);const n=h.join(this.store.agentDir(t),".runtime-mode");m(h.dirname(n),{recursive:!0,mode:448}),T(n,`${s.runtimeMode}
4
- `,{mode:384}),this.emit(t,{type:"notice",level:"info",text:`Approval mode: ${e}`,at:new Date().toISOString()})}respondApproval(t,e,s,n,r="human",i=!1){const o=this.approvals.get(t)?.get(e);if(!o)throw new Error("approval not found");const l=this.runtimes.get(t);if(!l)throw new Error("bot is not running");const u={type:"extension_ui_response",id:e};o.method==="confirm"?u.confirmed=s:o.method==="select"?u.value=s?o.options?.[0]:o.options?.[1]||o.options?.[0]:s?u.value=n||"":u.cancelled=!0,l.send(u),s&&i&&o.toolName&&this.allowTool(t,o.toolName),o.state=s?"allowed":"denied",o.decidedBy=r,o.reason=n,o.decidedAt=new Date().toISOString();try{this.store.appendEvent(t,{type:"approval",approval:o,at:o.decidedAt})}catch{}return this.broadcast(t,{type:"approval",approval:o,at:o.decidedAt}),this.setStatus(t,"running"),o}listApprovals(){const t=[];for(const[,e]of this.approvals)for(const s of e.values())s.state==="pending"&&t.push(s);return t.sort((e,s)=>e.createdAt.localeCompare(s.createdAt))}async input(t,e,s,n){const r=this.store.getInstance(t);if(!r)throw new Error("bot not found");if(!this.runtimes.has(t)){this.resume(t);const a=Date.now()+1e4;for(;!this.runtimes.has(t)&&Date.now()<a;)await new Promise(p=>setTimeout(p,150))}const i=this.runtimes.get(t);if(!i){const a=this.store.getInstance(t)?.status;throw new Error(a==="queued"?"bot is queued behind other bots in this project; send again once it starts":"bot is still starting; send again in a moment")}const o=new Date().toISOString();this.emit(t,{type:"user",text:e,at:o});const l={type:"prompt",message:e};n?.length&&(l.images=n.map(a=>({type:"image",data:a.data,mimeType:a.mimeType})));const u=this.streaming.has(t)||P.includes(r.status);s==="follow_up"?l.streamingBehavior="followUp":(s==="steer"||u)&&(l.streamingBehavior="steer");try{await i.request(l,3e4)}catch(a){const p=a instanceof Error?a.message:String(a);if(!l.streamingBehavior&&/stream/i.test(p)){await i.request({...l,streamingBehavior:"steer"},3e4);return}throw a}}async clearQueue(t){const e=this.runtimes.get(t);if(!e)throw new Error("bot is not running");const n=(await e.request({type:"clear_queue"},1e4)).data??{};return[...f(n.steering),...f(n.followUp)]}stop(t,e=!0){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");if(e)for(const n of this.children(t))this.stop(n.id,!0);try{this.runtimes.get(t)?.kill()}catch{}this.runtimes.delete(t),this.streaming.delete(t),d.includes(s.status)||this.setStatus(t,"cancelled"),this.pump()}resume(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");this.runtimes.has(t)||(e.status="queued",this.store.saveInstance(e),this.emit(t,{type:"status",status:"queued",at:new Date().toISOString()}),this.pump())}deleteBot(t,e=!0){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");if(e)for(const n of this.children(t))this.deleteBot(n.id,!0);try{this.runtimes.get(t)?.kill()}catch{}if(this.runtimes.delete(t),this.streaming.delete(t),this.store.deleteInstance(t),this.approvals.delete(t),this.recent.delete(t),s.isolation==="worktree"){try{v("git",["-C",s.projectPath,"worktree","remove","--force",s.workspacePath],{timeout:2e4,stdio:"ignore"})}catch{}A(s.workspacePath,{recursive:!0,force:!0})}this.pump()}status(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");const s=[...this.approvals.get(t)?.values()||[]].filter(n=>n.state==="pending");return{...e,pendingApprovals:s.length,lastText:e.lastText?.slice(0,4e3)}}result(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");return{botId:t,status:e.status,text:e.lastText||"",title:e.title}}async waitFor(t,e=45e3){const s=Date.now()+Math.min(e,45e3),n=new Set(t);for(;Date.now()<s;){const r=[...n].filter(i=>{const o=this.store.getInstance(i);return!o||d.includes(o.status)});if(r.length)return{bots:r.map(i=>this.result(i))};await new Promise(i=>setTimeout(i,250))}return{timeout:!0,bots:t.map(r=>{const i=this.store.getInstance(r);return{botId:r,status:i?.status||"missing",title:i?.title}})}}attachSocket(t,e){this.sockets.has(t)||this.sockets.set(t,new Set),this.sockets.get(t).add(e);const s=this.store.getInstance(t);e.send(JSON.stringify({type:"snapshot",bot:s,approvals:this.listApprovals().filter(n=>n.botId===t)}));for(const n of this.store.readEvents(t,400))e.send(JSON.stringify(n));e.on("close",()=>this.sockets.get(t)?.delete(e))}broadcast(t,e){const s=JSON.stringify(e);for(const n of this.sockets.get(t)||[])if(n.readyState===1)try{n.send(s)}catch{}}emit(t,e){this.store.appendEvent(t,e);const s=this.recent.get(t)||[];s.push(e),s.length>800&&s.splice(0,s.length-800),this.recent.set(t,s),this.broadcast(t,e);for(const n of this.listeners)try{n(e)}catch{}}onEvent(t){return this.listeners.add(t),()=>this.listeners.delete(t)}setStatus(t,e,s){const n=this.store.getInstance(t);n&&(n.status=e,s&&(n.lastError=s),this.store.saveInstance(n),this.emit(t,{type:"status",status:e,at:new Date().toISOString(),error:s}),d.includes(e)&&this.pump())}}function y(c){return c==="full-access"?"full-access":c==="parent-supervised"?"parent-supervised":"supervised"}function N(c){const t=c.content;return Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&e.type==="text"?String(e.text||""):"").join("").trim():""}function x(c){if(c==null)return"";if(typeof c=="string")return c;try{return JSON.stringify(c).slice(0,4e3)}catch{return String(c)}}let S=null;function X(){if(!S){const c=Number(process.env.PORT)||21e3;S=new q(c)}return S}export{q as BotManager,k as MAX_CONCURRENT_PER_PROJECT,g as MAX_DEPTH,b as ORCHESTRATION_TOOLS,D as READONLY_TOOLS,X as getBotManager};
1
+ import{execFileSync as v}from"node:child_process";import{mkdirSync as m,readFileSync as I,rmSync as A,writeFileSync as k}from"node:fs";import h from"node:path";import T from"node:os";import{getBotStore as B}from"./store.js";import{materialize as O}from"./materialize.js";import{PiRpc as j}from"./rpc.js";import{buildCatalog as M,ORCHESTRATION_TOOLS as b,READONLY_TOOLS as D}from"./catalog.js";import{TERMINAL_STATUSES as d}from"./types.js";const y=4,_=8,P=["starting","running","waiting_input","waiting_approval"];function f(c){return Array.isArray(c)?c.map(t=>{if(typeof t=="string")return t;if(!t||typeof t!="object")return"";const e=t;if(typeof e.text=="string")return e.text;const s=e.content;return Array.isArray(s)?s.map(n=>n&&typeof n=="object"&&typeof n.text=="string"?String(n.text):"").join(""):""}).map(t=>t.replace(/\s+/g," ").trim()).filter(Boolean):[]}class q{store=B();token;apiBase;runtimes=new Map;sockets=new Map;listeners=new Set;approvals=new Map;recent=new Map;streaming=new Set;constructor(t){this.token=this.store.token,this.apiBase=`http://127.0.0.1:${t}/api/bots`;for(const e of this.store.listInstances()){let s=!1,n=!1;!d.includes(e.status)&&e.status!=="queued"&&(e.status="stale",n=!0,s=!0);const r=w(e.runtimeMode);if(r!==e.runtimeMode&&(e.runtimeMode=r,s=!0),s&&this.store.saveInstance(e),n){const i=new Date().toISOString();this.emit(e.id,{type:"status",status:"stale",at:i}),this.emit(e.id,{type:"notice",level:"warn",text:"The hub restarted while this bot was running, so it is paused. Press Resume or send a message to continue from its session.",at:i})}}}listTemplates(){return this.store.listTemplates()}getTemplate(t){return this.store.getTemplate(t)}saveTemplate(t){return this.store.saveTemplate(t)}deleteTemplate(t){return this.store.deleteTemplate(t)}catalog(){return M()}listBots(t={}){return this.store.listInstances().filter(s=>!(t.project&&s.projectPath!==t.project||t.parentBotId&&s.parentBotId!==t.parentBotId||t.status&&s.status!==t.status))}getBot(t){return this.store.getInstance(t)}children(t){return this.store.listInstances().filter(e=>e.parentBotId===t)}createInstance(t){const e=this.getTemplate(t.templateId);if(!e)throw new Error(`unknown template: ${t.templateId}`);let s=null;if(t.parentBotId){if(s=this.getBot(t.parentBotId),!s)throw new Error("parent bot not found");if(s.depth+1>y)throw new Error(`nesting depth limit is ${y}`)}let n=t.projectPath||s?.projectPath||process.env.HOME||"/";n==="~"?n=T.homedir():n.startsWith("~/")&&(n=h.join(T.homedir(),n.slice(2)));const r=h.resolve(n),i=this.store.newId(),o=t.isolation||"shared";let l=r;if(o==="worktree"){const p=h.join(this.store.root,"worktrees",i);try{m(h.dirname(p),{recursive:!0,mode:448}),v("git",["-C",r,"worktree","add","-b",`tw-bot/${i.slice(0,8)}`,p],{timeout:2e4,stdio:"ignore"}),l=p}catch{l=r}}const u=new Date().toISOString(),a={id:i,templateId:e.id,title:t.title||e.manifest.name,projectPath:r,workspacePath:l,isolation:o,parentBotId:s?.id,depth:s?s.depth+1:0,runtimeMode:w(t.runtimeMode||e.manifest.permissions?.runtimeMode),projectResources:e.manifest.projectResources||"ignore",status:"queued",sessionFile:h.join(this.store.sessionsDir(i),`${i}.jsonl`),createdAt:u,updatedAt:u,model:e.manifest.model};return m(this.store.sessionsDir(i),{recursive:!0,mode:448}),this.store.saveInstance(a),this.emit(a.id,{type:"status",status:"queued",at:u}),this.pump(),a}activeInProject(t){return this.store.listInstances().filter(e=>e.projectPath===t&&!d.includes(e.status)&&e.status!=="queued").length}pump(){for(const t of this.store.listInstances())t.status==="queued"&&(this.activeInProject(t.projectPath)>=_||this.start(t))}start(t){const e=this.getTemplate(t.templateId);if(!e){this.setStatus(t.id,"failed","template disappeared");return}const s=O(e,t,{apiBase:this.apiBase,token:this.token}),n=e.manifest.binaryPath||"pi",r=new j({command:n,args:s.args,cwd:t.workspacePath,env:s.env,onEvent:i=>this.handleEvent(t.id,i),onStderr:i=>{/error|failed/i.test(i)&&this.emit(t.id,{type:"notice",level:"warn",text:i.slice(0,500),at:new Date().toISOString()})},onExit:()=>{this.runtimes.delete(t.id),this.streaming.delete(t.id);const i=this.store.getInstance(t.id);i&&!d.includes(i.status)&&this.setStatus(t.id,"failed","pi exited unexpectedly"),this.pump()}});this.runtimes.set(t.id,r),t.status="starting",t.pid=void 0,this.store.saveInstance(t),this.emit(t.id,{type:"status",status:"starting",at:new Date().toISOString()}),r.start()}handleEvent(t,e){const s=String(e.type||""),n=new Date().toISOString();switch(s){case"agent_start":this.streaming.add(t),this.setStatus(t,"running");break;case"agent_end":break;case"agent_settled":this.streaming.delete(t),this.setStatus(t,e.aborted===!0?"cancelled":"completed");break;case"message_start":case"message_end":{const r=e.message;if(r){if(s==="message_end"&&r.role==="assistant"){const i=this.store.getInstance(t),o=N(r);i&&o&&(i.lastText=o,this.store.saveInstance(i))}this.emit(t,{type:"message",message:r,at:n})}break}case"message_update":{const r=e.assistantMessageEvent;if(!r)break;const i=r.type==="text_delta"?"text":r.type==="thinking_delta"?"thinking":r.type==="toolcall_delta"?"tool-args":null;if(!i)break;const o=e.message;this.emit(t,{type:"delta",kind:i,delta:String(r.delta||""),contentIndex:typeof r.contentIndex=="number"?r.contentIndex:void 0,messageId:typeof o?.id=="string"?o.id:void 0,at:n});break}case"tool_execution_start":this.emit(t,{type:"tool",phase:"start",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),args:e.args,at:n});break;case"tool_execution_update":this.emit(t,{type:"tool",phase:"update",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:x(e.partialResult),at:n});break;case"tool_execution_end":this.emit(t,{type:"tool",phase:"end",callId:String(e.toolCallId||""),name:String(e.toolName||"tool"),output:x(e.result),isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,at:n});break;case"queue_update":this.emit(t,{type:"queue",steering:f(e.steering),followUp:f(e.followUp),at:n});break;case"extension_ui_request":this.handleUiRequest(t,e);break;default:break}}handleUiRequest(t,e){const s=String(e.method||""),n=new Date().toISOString(),r=this.store.getInstance(t);if(s==="notify"){this.emit(t,{type:"notice",level:e.notifyType==="error"?"error":e.notifyType==="warning"?"warn":"info",text:String(e.message||""),at:n});return}if(!["confirm","select","input","editor"].includes(s))return;const i=String(e.id||""),o=i?this.approvals.get(t)?.get(i):void 0;if(o&&o.state==="pending")return;const l=String(e.title||"Approval required"),u=/^Allow (.+?)\?$/.exec(l),a={id:String(e.id||""),botId:t,botTitle:r?.title||t,kind:s==="confirm"?"tool":"question",method:s,title:l,toolName:u?u[1]:void 0,message:typeof e.message=="string"?e.message:void 0,options:Array.isArray(e.options)?e.options.map(String):void 0,state:"pending",createdAt:n};if(this.approvals.has(t)||this.approvals.set(t,new Map),this.approvals.get(t).set(a.id,a),r&&r.runtimeMode==="parent-supervised"&&r.parentBotId){const p=this.store.getInstance(r.parentBotId);if(p){a.escalatedTo=p.id;const S=a.message?a.message.slice(0,500):"",E=[`Child bot "${r.title}" (${r.id}) needs approval: ${a.title}`,S?`Arguments: ${S}`:"",`Decide with bot_approve({ botId: "${r.id}", requestId: "${a.id}", allow: true|false, reason: "..." }).`,"If you do nothing the user will answer it."].filter(Boolean).join(`
2
+ `);this.input(p.id,E,"steer").catch(()=>{this.emit(t,{type:"notice",level:"warn",text:"Could not reach the supervising bot; waiting for the user.",at:n})})}}this.setStatus(t,"waiting_approval"),this.emit(t,{type:"approval",approval:a,at:n})}allowTool(t,e){if(!this.store.getInstance(t))throw new Error("bot not found");const n=h.join(this.store.agentDir(t),".allowed-tools");let r=[];try{r=JSON.parse(I(n,"utf8")),Array.isArray(r)||(r=[])}catch{r=[]}return r.includes(e)||r.push(e),m(h.dirname(n),{recursive:!0,mode:448}),k(n,`${JSON.stringify(r)}
3
+ `,{mode:384}),r}allowedTools(t){try{const e=JSON.parse(I(h.join(this.store.agentDir(t),".allowed-tools"),"utf8"));return Array.isArray(e)?e.map(String):[]}catch{return[]}}setRuntimeMode(t,e){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");s.runtimeMode=w(e),this.store.saveInstance(s);const n=h.join(this.store.agentDir(t),".runtime-mode");m(h.dirname(n),{recursive:!0,mode:448}),k(n,`${s.runtimeMode}
4
+ `,{mode:384}),this.emit(t,{type:"notice",level:"info",text:`Approval mode: ${e}`,at:new Date().toISOString()})}respondApproval(t,e,s,n,r="human",i=!1){const o=this.approvals.get(t)?.get(e);if(!o)throw new Error("approval not found");const l=this.runtimes.get(t);if(!l)throw new Error("bot is not running");const u={type:"extension_ui_response",id:e};o.method==="confirm"?u.confirmed=s:o.method==="select"?u.value=s?o.options?.[0]:o.options?.[1]||o.options?.[0]:s?u.value=n||"":u.cancelled=!0,l.send(u),s&&i&&o.toolName&&this.allowTool(t,o.toolName),o.state=s?"allowed":"denied",o.decidedBy=r,o.reason=n,o.decidedAt=new Date().toISOString();try{this.store.appendEvent(t,{type:"approval",approval:o,at:o.decidedAt})}catch{}return this.broadcast(t,{type:"approval",approval:o,at:o.decidedAt}),this.setStatus(t,"running"),o}listApprovals(){const t=[];for(const[,e]of this.approvals)for(const s of e.values())s.state==="pending"&&t.push(s);return t.sort((e,s)=>e.createdAt.localeCompare(s.createdAt))}async input(t,e,s,n){const r=this.store.getInstance(t);if(!r)throw new Error("bot not found");if(!this.runtimes.has(t)){this.resume(t);const a=Date.now()+1e4;for(;!this.runtimes.has(t)&&Date.now()<a;)await new Promise(p=>setTimeout(p,150))}const i=this.runtimes.get(t);if(!i){const a=this.store.getInstance(t)?.status;throw new Error(a==="queued"?"bot is queued behind other bots in this project; send again once it starts":"bot is still starting; send again in a moment")}const o=new Date().toISOString();this.emit(t,{type:"user",text:e,at:o});const l={type:"prompt",message:e};n?.length&&(l.images=n.map(a=>({type:"image",data:a.data,mimeType:a.mimeType})));const u=this.streaming.has(t)||P.includes(r.status);s==="follow_up"?l.streamingBehavior="followUp":(s==="steer"||u)&&(l.streamingBehavior="steer");try{await i.request(l,3e4)}catch(a){const p=a instanceof Error?a.message:String(a);if(!l.streamingBehavior&&/stream/i.test(p)){await i.request({...l,streamingBehavior:"steer"},3e4);return}throw a}}async clearQueue(t){const e=this.runtimes.get(t);if(!e)throw new Error("bot is not running");const n=(await e.request({type:"clear_queue"},1e4)).data??{};return[...f(n.steering),...f(n.followUp)]}shutdown(){for(const[t,e]of this.runtimes){try{e.kill()}catch{}this.streaming.delete(t)}this.runtimes.clear()}stop(t,e=!0){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");if(e)for(const n of this.children(t))this.stop(n.id,!0);try{this.runtimes.get(t)?.kill()}catch{}this.runtimes.delete(t),this.streaming.delete(t),d.includes(s.status)||this.setStatus(t,"cancelled"),this.pump()}resume(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");this.runtimes.has(t)||(e.status="queued",this.store.saveInstance(e),this.emit(t,{type:"status",status:"queued",at:new Date().toISOString()}),this.pump())}deleteBot(t,e=!0){const s=this.store.getInstance(t);if(!s)throw new Error("bot not found");if(e)for(const n of this.children(t))this.deleteBot(n.id,!0);try{this.runtimes.get(t)?.kill()}catch{}if(this.runtimes.delete(t),this.streaming.delete(t),this.store.deleteInstance(t),this.approvals.delete(t),this.recent.delete(t),s.isolation==="worktree"){try{v("git",["-C",s.projectPath,"worktree","remove","--force",s.workspacePath],{timeout:2e4,stdio:"ignore"})}catch{}A(s.workspacePath,{recursive:!0,force:!0})}this.pump()}status(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");const s=[...this.approvals.get(t)?.values()||[]].filter(n=>n.state==="pending");return{...e,pendingApprovals:s.length,lastText:e.lastText?.slice(0,4e3)}}result(t){const e=this.store.getInstance(t);if(!e)throw new Error("bot not found");return{botId:t,status:e.status,text:e.lastText||"",title:e.title}}async waitFor(t,e=45e3){const s=Date.now()+Math.min(e,45e3),n=new Set(t);for(;Date.now()<s;){const r=[...n].filter(i=>{const o=this.store.getInstance(i);return!o||d.includes(o.status)});if(r.length)return{bots:r.map(i=>this.result(i))};await new Promise(i=>setTimeout(i,250))}return{timeout:!0,bots:t.map(r=>{const i=this.store.getInstance(r);return{botId:r,status:i?.status||"missing",title:i?.title}})}}attachSocket(t,e){this.sockets.has(t)||this.sockets.set(t,new Set),this.sockets.get(t).add(e);const s=this.store.getInstance(t);e.send(JSON.stringify({type:"snapshot",bot:s,approvals:this.listApprovals().filter(n=>n.botId===t)}));for(const n of this.store.readEvents(t,400))e.send(JSON.stringify(n));e.on("close",()=>this.sockets.get(t)?.delete(e))}broadcast(t,e){const s=JSON.stringify(e);for(const n of this.sockets.get(t)||[])if(n.readyState===1)try{n.send(s)}catch{}}emit(t,e){this.store.appendEvent(t,e);const s=this.recent.get(t)||[];s.push(e),s.length>800&&s.splice(0,s.length-800),this.recent.set(t,s),this.broadcast(t,e);for(const n of this.listeners)try{n(e)}catch{}}onEvent(t){return this.listeners.add(t),()=>this.listeners.delete(t)}setStatus(t,e,s){const n=this.store.getInstance(t);n&&(n.status=e,s&&(n.lastError=s),this.store.saveInstance(n),this.emit(t,{type:"status",status:e,at:new Date().toISOString(),error:s}),d.includes(e)&&this.pump())}}function w(c){return c==="full-access"?"full-access":c==="parent-supervised"?"parent-supervised":"supervised"}function N(c){const t=c.content;return Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&e.type==="text"?String(e.text||""):"").join("").trim():""}function x(c){if(c==null)return"";if(typeof c=="string")return c;try{return JSON.stringify(c).slice(0,4e3)}catch{return String(c)}}let g=null;function X(){if(!g){const c=Number(process.env.PORT)||21e3;g=new q(c)}return g}function Y(){g?.shutdown()}export{q as BotManager,_ as MAX_CONCURRENT_PER_PROJECT,y as MAX_DEPTH,b as ORCHESTRATION_TOOLS,D as READONLY_TOOLS,X as getBotManager,Y as shutdownBots};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tmux-weblink",
3
- "version": "3.2.3",
3
+ "version": "3.2.4",
4
4
  "description": "Access your tmux sessions from the browser. A continuation of tmux-web and persalink.",
5
5
  "type": "module",
6
6
  "bin": {