@aicommander/agent 1.0.20 → 1.0.23

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/bin/agent.js CHANGED
@@ -1,17 +1,25 @@
1
1
  #!/usr/bin/env node
2
- import{program as T}from"commander";var O="1.0.20";import tn from"os";function nn(e){try{let t=JSON.parse(e);return typeof t.code=="string"?t.code:null}catch{return null}}var we=class extends Error{constructor(r,s){super(`Registration failed (${r}): ${s}`);this.status=r;this.body=s;this.name="RegistrationError",this.code=nn(s)}status;body;code};async function Ae(e,t,r={}){let s={hostname:tn.hostname(),platform:process.platform,arch:process.arch,agentVersion:O,...t?{deviceId:t.deviceId,deviceSecret:t.deviceSecret}:{},...r.forceNew?{forceNew:!0}:r.currentCode?{currentCode:r.currentCode}:{}},i=await fetch(`${e}/api/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!i.ok){let o=await i.text();throw new we(i.status,o)}return i.json()}import yn from"ws";import En from"os";import{spawn as Ye}from"child_process";var se="https://aicommander.dev";var w="aicommander-exec";var Xe="ABCDEFGHJKMNPQRSTVWXYZ0123456789";var rr=Math.floor(256/Xe.length)*Xe.length;var rn=/^AIC-[ABCDEFGHJKMNPQRSTVWXYZ0-9]{4}-[ABCDEFGHJKMNPQRSTVWXYZ0-9]{4}-[ABCDEFGHJKMNPQRSTVWXYZ0-9]{4}$/;function on(e){return rn.test(e.trim().toUpperCase())}function j(e){return on(e)?`AIC-${e.slice(4,8)}-***-***`:e}var qe=process.platform==="win32";function Ze(e,t,r,s){let i=Date.now(),o=Ye(e,[],{shell:!0,cwd:t??process.env.HOME,env:{...process.env,...r??{}},stdio:["ignore","pipe","pipe"],detached:!qe}),a=!1,c=null,l=()=>{c&&(clearTimeout(c),c=null)};o.stdout?.on("data",u=>{s.onOutput(u.toString("base64"),"stdout")}),o.stderr?.on("data",u=>{s.onOutput(u.toString("base64"),"stderr")}),o.on("close",u=>{a=!0,l(),s.onDone(u??-1,Date.now()-i)}),o.on("error",u=>{a=!0,l(),s.onError(u.message)});let d=u=>{if(!(a||o.pid==null))try{qe?Ye("taskkill",["/pid",String(o.pid),"/T","/F"],{stdio:"ignore"}):process.kill(-o.pid,u)}catch{}};return{kill:()=>{a||(d("SIGTERM"),l(),c=setTimeout(()=>{c=null,d("SIGKILL")},5e3),c.unref?.())}}}import{spawn as un}from"node:child_process";import{readFileSync as mn}from"node:fs";import{isAbsolute as fn}from"node:path";import{spawn as sn}from"node:child_process";import{createRequire as an}from"node:module";import{constants as cn}from"node:os";var ln=an(import.meta.url),Te="__secure-exec-drop",dn="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";function Qe(){let e=!1;try{e=ln("node:sea").isSea()}catch{}return e}function ze(e){let t=process.argv[1],r=!Qe()&&t?[t,Te,...e]:[Te,...e];return{cmd:process.execPath,args:r}}function et(e){let t=Qe()?1:2;if(e[t]!==Te)return!1;let[r,s,i,o,...a]=e.slice(t+1),c=Number(r),l=Number(s),d=process;try{if(!Number.isInteger(c)||!Number.isInteger(l)||c===0||!i||!o)throw new Error("invalid drop arguments");if(typeof d.initgroups!="function"||typeof d.setgid!="function"||typeof d.setuid!="function")throw new Error("privilege-drop syscalls unavailable on this platform");if(d.initgroups(i,l),d.setgid(l),d.setuid(c),d.getuid?.()===0||d.getgid?.()===0)throw new Error("privilege drop did not take effect");if(typeof d.getgroups=="function"){let p=d.getgroups();if(Array.isArray(p)&&p.includes(0))throw new Error("privilege drop left root's supplementary groups in place")}}catch(p){process.stderr.write(`secure-exec: privilege drop failed: ${p instanceof Error?p.message:String(p)}
3
- `),process.exit(127)}let u={...process.env,PATH:dn},f=sn(o,a,{stdio:"inherit",env:u,shell:!1}),m=!1;return f.on("error",p=>{m||(m=!0,process.stderr.write(`secure-exec: spawn failed: ${p.message}
4
- `),process.exit(127))}),f.on("exit",(p,E)=>{if(!m){if(m=!0,E){let S=cn.signals[E];process.exit(128+(typeof S=="number"?S:0))}process.exit(p??0)}}),!0}function pn(){let e;try{e=mn("/etc/passwd","utf8")}catch{throw new Error("cannot read /etc/passwd to resolve the secure-exec user")}let t=e.split(`
5
- `).filter(l=>l.startsWith(`${w}:`));if(t.length===0)throw new Error(`secure exec user "${w}" not found in /etc/passwd \u2014 reinstall the agent to create it`);if(t.length>1)throw new Error(`multiple /etc/passwd entries for "${w}" \u2014 refusing to guess which is the sandbox user`);let r=t[0].split(":");if(r.length!==7)throw new Error(`malformed passwd entry for ${w}`);let s=r[2],i=r[3];if(!/^\d+$/.test(s)||!/^\d+$/.test(i))throw new Error(`could not resolve uid/gid for ${w}`);let o=Number(s),a=Number(i),c=r[5]||"/tmp";if(!Number.isInteger(o)||!Number.isInteger(a))throw new Error(`could not resolve uid/gid for ${w}`);if(o===0)throw new Error("refusing to run secure exec as uid 0");if(a===0)throw new Error("refusing to run secure exec as gid 0");return{uid:o,gid:a,home:c,name:w}}var gn="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",Sn=new Set(["NODE_OPTIONS","BASH_ENV","ENV","IFS","PYTHONSTARTUP","PYTHONPATH","PERL5OPT","RUBYOPT","GIT_EXTERNAL_DIFF","PATH","HOME","USER","LOGNAME"]),hn=e=>/^LD_/.test(e)||Sn.has(e);function nt(e,t){if(process.platform!=="linux")throw new Error("secure exec is only supported on Linux");if(typeof process.getuid=="function"&&process.getuid()!==0)throw new Error("secure exec requires the agent to run as root (to drop privilege)");let r=e.argv;if(!Array.isArray(r)||r.length===0||typeof r[0]!="string")throw new Error("secure exec requires a non-empty argv");let s=r[0];if(s.includes("/"))throw new Error(`command "${s}" must be a bare command name (no path separators)`);if(!e.allowedCommands.includes(s))throw new Error(`command "${s}" is not in this token's allowlist`);if(e.cwd!=null&&!fn(e.cwd))throw new Error(`cwd "${e.cwd}" must be an absolute path`);let i=null;if(e.input!=null&&(i=Buffer.from(e.input,"base64"),i.length>262144))throw new Error(`stdin payload ${i.length}B exceeds limit ${262144}B`);let o=pn(),a={HOME:o.home,USER:o.name,LOGNAME:o.name,PATH:gn},c={};for(let[h,b]of Object.entries(e.env??{}))hn(h)||(c[h]=b);let l={...c,...a},d=Date.now(),{cmd:u,args:f}=ze([String(o.uid),String(o.gid),o.name,s,...r.slice(1)]),m=un(u,f,{cwd:e.cwd??o.home,env:l,stdio:["pipe","pipe","pipe"],detached:!0,shell:!1});i&&m.stdin?(m.stdin.on("error",()=>{}),m.stdin.end(i)):m.stdin?.end();let p=!1,E=null,S=()=>{E&&(clearTimeout(E),E=null)};m.stdout?.on("data",h=>{t.onOutput(h.toString("base64"),"stdout")}),m.stderr?.on("data",h=>{t.onOutput(h.toString("base64"),"stderr")}),m.on("close",h=>{p=!0,S(),t.onDone(h??-1,Date.now()-d)}),m.on("error",h=>{p=!0,S(),t.onError(h.message)});let _=h=>{if(!(p||m.pid==null))try{process.kill(-m.pid,h)}catch{}};return{kill:()=>{p||(_("SIGTERM"),S(),E=setTimeout(()=>{E=null,_("SIGKILL")},5e3),E.unref?.())}}}import A from"chalk";function rt(e,t,r=!1){console.clear(),console.log(),console.log(A.bold.cyan(" AI Commander \u2014 Remote Agent")),console.log(),console.log(A.gray(" Session code:")),console.log(),console.log(A.bold.greenBright(` ${r?e:j(e)}`)),console.log(),r||console.log(A.gray(" Reveal the full code: sudo aicommander-agent status --reveal")),console.log(A.gray(" Then give it to your admin to connect.")),console.log(A.yellow(" \u26A0 Keep this code secret \u2014 anyone who has it can run commands as root here.")),console.log(A.gray(` Server: ${t}`)),console.log(A.gray(" Press Ctrl+C to disconnect.")),console.log(),console.log(A.yellow(" Waiting for admin connection...")),console.log()}function ot(e,t){console.log(A.yellow(` Reconnecting in ${Math.round(t/1e3)}s (attempt ${e})...`))}function st(){console.log(A.green(" Connected to relay \u2014 ready for commands."))}function xe(e){console.log(A.cyan(` > ${e}`))}function ke(e,t){let r=e===0?A.green:A.red;console.log(r(` Done. Exit ${e} in ${t}ms`))}var _e={capable:!1,enabled:!1,expiresAt:null},ct=360*60*1e3;function vn(e,t){return new Promise((r,s)=>{if(t.aborted){s(new DOMException("Aborted","AbortError"));return}let i=setTimeout(r,e);t.addEventListener("abort",()=>{clearTimeout(i),s(new DOMException("Aborted","AbortError"))},{once:!0})})}async function lt(e){let t=1e3,r=3e4,s=0,i=e.agentToken;for(;!e.signal?.aborted;){s++;try{let o=await bn(e,i);if(t=1e3,s=0,o&&e.reauth&&!e.signal?.aborted)try{i=await e.reauth()}catch{}}catch(o){if(o.name==="AbortError")break;let a=.8+Math.random()*.4,c=Math.min(t*a,r);e.silent||ot(s,c);try{await vn(c,e.signal??new AbortController().signal)}catch(l){if(l.name==="AbortError")break}t=Math.min(t*2,r)}}}async function bn(e,t){let{serverUrl:r,sessionCode:s}=e,i=`${r.replace(/^http/,"ws")}/ws/agent/${s}?token=${t}`,o=l=>{try{e.onStatus?.(l)}catch{}},a=l=>{try{e.onActivity?.(l)}catch{}},c=()=>{try{e.onHeartbeat?.()}catch{}};return o("connecting"),new Promise((l,d)=>{let u=new yn(i),f=null,m=null,p=null,E=!1,S=null,_=!1,h=()=>{p&&(clearTimeout(p),p=null)},b=()=>{S&&(clearInterval(S),S=null)},C=()=>{if(!e.reauthIntervalMs||!e.reauth)return;let y=()=>{if(f){p=setTimeout(y,3e4);return}E=!0,u.close(1e3,"reauth")};p=setTimeout(y,e.reauthIntervalMs)},G=()=>{_||(_=!0,h(),b(),l(E))},U=y=>{_||(_=!0,h(),b(),d(y))},ne=()=>{c(),m&&clearTimeout(m),m=setTimeout(()=>{u.terminate(),U(new Error("Ping timeout"))},9e4)};e.signal?.addEventListener("abort",()=>u.close(1e3,"disabled"),{once:!0});let ye=()=>{if(_)return;let y={type:"agent:screen_state",screenShare:e.screenShare?.getState()??_e};try{u.send(JSON.stringify(y))}catch{}};u.on("open",()=>{o("connected"),ne(),C();let y={type:"agent:register",hostname:En.hostname(),platform:process.platform,arch:process.arch,agentVersion:O,screenShare:e.screenShare?.getState()??_e};u.send(JSON.stringify(y)),e.screenShare?.on("change",ye),e.silent||st()}),u.on("message",y=>{let x;try{x=JSON.parse(String(y))}catch{return}switch(x.type){case"do:ping":ne();let zt={type:"agent:pong",ts:x.ts};u.send(JSON.stringify(zt));break;case"do:exec":{xe(x.command),a(!0);let{commandId:D,command:V,cwd:Ee,env:ve}=x,re=Date.now(),q=!1;b(),S=setInterval(()=>{let R=Date.now()-re;if(R>=3e5&&!q){q=!0;let g={type:"agent:exec_idle",commandId:D,idleMs:R};u.send(JSON.stringify(g))}},3e5),S.unref?.(),f=Ze(V,Ee,ve,{onOutput:(R,g)=>{re=Date.now(),q=!1;let k={type:"agent:output",commandId:D,chunk:R,stream:g};u.send(JSON.stringify(k))},onDone:(R,g)=>{f=null,b(),a(!1),ke(R,g);let k={type:"agent:done",commandId:D,exitCode:R,durationMs:g};u.send(JSON.stringify(k))},onError:R=>{f=null,b(),a(!1);let g={type:"agent:error",commandId:D,error:R};u.send(JSON.stringify(g))}}).kill;break}case"do:secure_exec":{let{commandId:D,argv:V,allowedCommands:Ee,input:ve,cwd:re,env:q}=x,Je=(g,k)=>{f=null,b(),a(!1),ke(g,k);let Z={type:"agent:done",commandId:D,exitCode:g,durationMs:k};u.send(JSON.stringify(Z))},R=g=>{f=null,b(),a(!1);let k={type:"agent:error",commandId:D,error:g};u.send(JSON.stringify(k))};try{let g=Array.isArray(V)?V.join(" "):String(V);xe(g),a(!0);let k=Date.now(),Z=!1;b(),S=setInterval(()=>{let oe=Date.now()-k;if(oe>=3e5&&!Z){Z=!0;let be={type:"agent:exec_idle",commandId:D,idleMs:oe};u.send(JSON.stringify(be))}},3e5),S.unref?.(),f=nt({argv:V,allowedCommands:Ee,input:ve,cwd:re,env:q},{onOutput:(oe,be)=>{k=Date.now(),Z=!1;let en={type:"agent:output",commandId:D,chunk:oe,stream:be};u.send(JSON.stringify(en))},onDone:Je,onError:R}).kill}catch(g){R(g instanceof Error?g.message:String(g))}break}case"do:kill":f&&(f(),f=null);break;case"do:screenshot":wn(u,x.requestId,e.screenShare);break}}),u.on("close",(y,x)=>{m&&clearTimeout(m),b(),e.screenShare?.off("change",ye),f&&(f(),f=null,a(!1)),o("disconnected"),y===1e3||y===4001?G():U(new Error(`WS closed: ${y} ${String(x)}`))}),u.on("error",y=>{m&&clearTimeout(m),b(),e.screenShare?.off("change",ye),o("disconnected"),U(y)}),u.on("unexpected-response",(y,x)=>{d(new Error(`Unexpected HTTP response: ${x.statusCode}`))})})}async function wn(e,t,r){let s=a=>{try{e.send(JSON.stringify(a))}catch{}},i=a=>s({type:"agent:screenshot_error",requestId:t,error:a}),o=r?.getState()??_e;if(!r||!o.capable){i("This machine cannot share its screen (desktop macOS/Windows only).");return}if(!o.enabled){i("Screen sharing is turned off on this machine.");return}try{let{data:a,mimeType:c}=await r.capture();if(a.length>10485760){let d=(a.length/1048576).toFixed(1);i(`Screenshot is ${d} MB, which exceeds the ${10485760/(1024*1024)} MB limit.`);return}let l=a.toString("base64");for(let d=0;d<l.length;d+=524288)s({type:"agent:screenshot_chunk",requestId:t,chunk:l.slice(d,d+524288)});s({type:"agent:screenshot_done",requestId:t,mimeType:c,totalBytes:a.length})}catch(a){i(`Screenshot failed: ${a.message}`)}}import N from"node:fs/promises";import mt from"node:path";var ae="/var/run/aicommander-agent",ce=mt.join(ae,"state.json"),dt=448,ut=384;async function ft(e){let t=null;try{await N.mkdir(ae,{recursive:!0,mode:dt}),await N.chmod(ae,dt),t=mt.join(ae,`.state.${process.pid}.${Date.now()}.tmp`);let r=await N.open(t,"wx",ut);try{await r.writeFile(JSON.stringify(e,null,2),"utf8")}finally{await r.close()}await N.rename(t,ce),t=null,await N.chmod(ce,ut)}catch{}finally{t&&await N.rm(t,{force:!0}).catch(()=>{})}}async function pt(){try{await N.rm(ce,{force:!0})}catch{}}async function I(){try{let e=await N.readFile(ce,"utf8");return JSON.parse(e)}catch{return null}}import De from"node:fs";import Q from"node:path";import An from"node:os";import{randomUUID as Rn,randomBytes as Tn}from"node:crypto";var gt="/etc/aicommander-agent",St=Q.join(An.homedir(),".config","aicommander-agent"),le="device.json";function ht(){return{deviceId:Rn(),deviceSecret:Tn(32).toString("base64url")}}function xn(e){return typeof e=="object"&&e!==null&&typeof e.deviceId=="string"&&e.deviceId.length>0&&typeof e.deviceSecret=="string"&&e.deviceSecret.length>0}function Ie(e){try{let t=De.readFileSync(e,"utf8"),r=JSON.parse(t);if(xn(r))return{deviceId:r.deviceId,deviceSecret:r.deviceSecret}}catch{}return null}function Ce(e,t){try{return De.mkdirSync(e,{recursive:!0,mode:448}),De.writeFileSync(Q.join(e,le),JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),!0}catch{return!1}}function K(e){if(e){let i=Ie(Q.join(e,le));if(i)return i;let o=ht();return Ce(e,o),o}let t=Ie(Q.join(gt,le));if(t)return t;let r=Ie(Q.join(St,le));if(r)return r;let s=ht();return Ce(gt,s)||Ce(St,s),s}import M from"node:fs";import W from"node:path";import kn from"node:os";var _n="/etc/aicommander-agent",In=W.join(kn.homedir(),".config","aicommander-agent"),Oe="session.json",yt=".rotate";function Cn(e){return typeof e=="object"&&e!==null&&typeof e.sessionCode=="string"&&e.sessionCode.length>0&&typeof e.agentToken=="string"&&e.agentToken.length>0}function Dn(e){try{let t=M.readFileSync(e,"utf8"),r=JSON.parse(t);if(Cn(r))return{sessionCode:r.sessionCode,agentToken:r.agentToken}}catch{}return null}function On(e,t){try{return M.mkdirSync(e,{recursive:!0,mode:448}),M.writeFileSync(W.join(e,Oe),JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),!0}catch{return!1}}function z(e){return e?[e]:[_n,In]}function Et(e){for(let t of z(e)){let r=Dn(W.join(t,Oe));if(r)return r}return null}function Ne(e,t){for(let r of z(t))if(On(r,e))return}function vt(e){for(let t of z(e))try{M.rmSync(W.join(t,Oe),{force:!0})}catch{}}function bt(e){for(let t of z(e))try{M.mkdirSync(t,{recursive:!0,mode:448}),M.writeFileSync(W.join(t,yt),"",{mode:384});return}catch{}}function wt(e){let t=!1;for(let r of z(e)){let s=W.join(r,yt);try{M.existsSync(s)&&(t=!0,M.rmSync(s,{force:!0}))}catch{}}return t}import{spawn as Hn}from"child_process";import de from"fs";import At from"path";import Mn from"os";function ue(e){if(e)return At.join(e,"heartbeat");if(process.platform==="linux")try{return de.mkdirSync("/run/aicommander-agent",{recursive:!0}),"/run/aicommander-agent/heartbeat"}catch{}return At.join(Mn.tmpdir(),"aicommander-agent-heartbeat")}function Rt(e){try{let t=`${e}.tmp`;de.writeFileSync(t,String(Date.now())),de.renameSync(t,e)}catch{}}var ee=null;function Tt(e,t=5e3){Me(),Rt(e),ee=setInterval(()=>Rt(e),t),ee.unref?.()}function Me(){ee&&(clearInterval(ee),ee=null)}function xt(e){try{let t=de.readFileSync(e,"utf8").trim(),r=Number(t);return Number.isFinite(r)?r:null}catch{return null}}async function _t(e={}){let t=e.heartbeatPath??ue(e.configDir),r=e.spawnWorker??(u=>Hn(process.execPath,process.argv.slice(1),{env:u,stdio:"inherit"})),s=null,i=0,o=!1,a=0,c=[],l=null,d=null;await new Promise(u=>{let f=null,m=null,p=()=>{l&&(clearInterval(l),l=null),d&&(clearTimeout(d),d=null),f&&(process.removeListener("SIGINT",f),f=null),m&&(process.removeListener("SIGTERM",m),m=null)},E=()=>{p(),u()},S=()=>{i=Date.now(),a++;let C={...process.env,AIC_ROLE:"worker",AIC_HEARTBEAT:t};s=r(C),s.on("exit",(G,U)=>{if(s=null,o){E();return}if(e.maxSpawns!=null&&a>=e.maxSpawns){E();return}_(`worker exited (code=${G??"null"} signal=${U??"null"})`)}),s.on("error",()=>{})},_=C=>{let G=Date.now();c=c.filter(ne=>G-ne<3e5),c.push(G);let U=c.length>5?6e4:0;d&&clearTimeout(d),d=setTimeout(()=>{d=null,o||S()},U),d.unref?.()},h=()=>{if(s)try{s.kill("SIGKILL")}catch{}};l=setInterval(()=>{if(o||!s||Date.now()-i<3e4)return;let C=xt(t);C!=null&&Date.now()-C>3e4&&h()},1e4),l.unref?.();let b=C=>{if(o=!0,l&&(clearInterval(l),l=null),d&&(clearTimeout(d),d=null),s)try{s.kill(C)}catch{}else E()};f=()=>b("SIGINT"),m=()=>b("SIGTERM"),process.on("SIGINT",f),process.on("SIGTERM",m),S()})}function Fn(e,t){let r=e.split(".").map(o=>parseInt(o,10)||0),s=t.split(".").map(o=>parseInt(o,10)||0),i=Math.max(r.length,s.length);for(let o=0;o<i;o++){let a=(r[o]??0)-(s[o]??0);if(a!==0)return a>0?1:-1}return 0}function It(e,t){return Fn(e,t)>0}async function Ct(e,t=1e4){let r=new AbortController,s=setTimeout(()=>r.abort(),t);try{let i=await fetch(`${e.replace(/\/+$/,"")}/dist/latest`,{signal:r.signal,headers:{Accept:"application/json"}});if(!i.ok)return null;let o=await i.json();return{version:typeof o.version=="string"?o.version:null,mac:typeof o.mac=="string"?o.mac:null,win:typeof o.win=="string"?o.win:null,agentLinuxX64:typeof o.agentLinuxX64=="string"?o.agentLinuxX64:null,agentLinuxArm64:typeof o.agentLinuxArm64=="string"?o.agentLinuxArm64:null}}catch{return null}finally{clearTimeout(s)}}var H=process.env.AICOMMANDER_SERVER??se,Bn=1440*60*1e3;async function Dt(){let e=await Ct(H);e?.version&&It(e.version,O)&&console.warn(`
2
+ import{program as x}from"commander";var O="1.0.23";import cn from"os";function ln(e){try{let t=JSON.parse(e);return typeof t.code=="string"?t.code:null}catch{return null}}var we=class extends Error{constructor(r,s){super(`Registration failed (${r}): ${s}`);this.status=r;this.body=s;this.name="RegistrationError",this.code=ln(s)}status;body;code};async function Re(e,t,r={}){let s={hostname:cn.hostname(),platform:process.platform,arch:process.arch,agentVersion:O,...t?{deviceId:t.deviceId,deviceSecret:t.deviceSecret}:{},...r.forceNew?{forceNew:!0}:r.currentCode?{currentCode:r.currentCode}:{}},i=await fetch(`${e}/api/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!i.ok){let o=await i.text();throw new we(i.status,o)}return i.json()}import Tn from"ws";import _n from"os";import{spawn as Ze}from"child_process";var k="https://aicommander.dev";var v="aicommander-exec";var qe="ABCDEFGHJKMNPQRSTVWXYZ0123456789";var dr=Math.floor(256/qe.length)*qe.length;var dn=/^AIC-[ABCDEFGHJKMNPQRSTVWXYZ0-9]{4}-[ABCDEFGHJKMNPQRSTVWXYZ0-9]{4}-[ABCDEFGHJKMNPQRSTVWXYZ0-9]{4}$/;function un(e){return dn.test(e.trim().toUpperCase())}function j(e){return un(e)?`AIC-${e.slice(4,8)}-***-***`:e}var Qe=process.platform==="win32";function ze(e,t,r,s){let i=Date.now(),o=Ze(e,[],{shell:!0,cwd:t??process.env.HOME,env:{...process.env,...r??{}},stdio:["ignore","pipe","pipe"],detached:!Qe}),l=!1,a=null,d=()=>{a&&(clearTimeout(a),a=null)};o.stdout?.on("data",p=>{s.onOutput(p.toString("base64"),"stdout")}),o.stderr?.on("data",p=>{s.onOutput(p.toString("base64"),"stderr")}),o.on("close",p=>{l=!0,d(),s.onDone(p??-1,Date.now()-i)}),o.on("error",p=>{l=!0,d(),s.onError(p.message)});let c=p=>{if(!(l||o.pid==null))try{Qe?Ze("taskkill",["/pid",String(o.pid),"/T","/F"],{stdio:"ignore"}):process.kill(-o.pid,p)}catch{}};return{kill:()=>{l||(c("SIGTERM"),d(),a=setTimeout(()=>{a=null,c("SIGKILL")},5e3),a.unref?.())}}}import{spawn as hn}from"node:child_process";import{readFileSync as yn}from"node:fs";import{isAbsolute as En}from"node:path";import{spawn as mn}from"node:child_process";import{createRequire as fn}from"node:module";import{constants as pn}from"node:os";var gn=fn(import.meta.url),Te="__secure-exec-drop",Sn="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";function et(){let e=!1;try{e=gn("node:sea").isSea()}catch{}return e}function tt(e){let t=process.argv[1],r=!et()&&t?[t,Te,...e]:[Te,...e];return{cmd:process.execPath,args:r}}function nt(e){let t=et()?1:2;if(e[t]!==Te)return!1;let[r,s,i,o,...l]=e.slice(t+1),a=Number(r),d=Number(s),c=process;try{if(!Number.isInteger(a)||!Number.isInteger(d)||a===0||!i||!o)throw new Error("invalid drop arguments");if(typeof c.initgroups!="function"||typeof c.setgid!="function"||typeof c.setuid!="function")throw new Error("privilege-drop syscalls unavailable on this platform");if(c.initgroups(i,d),c.setgid(d),c.setuid(a),c.getuid?.()===0||c.getgid?.()===0)throw new Error("privilege drop did not take effect");if(typeof c.getgroups=="function"){let f=c.getgroups();if(Array.isArray(f)&&f.includes(0))throw new Error("privilege drop left root's supplementary groups in place")}}catch(f){process.stderr.write(`secure-exec: privilege drop failed: ${f instanceof Error?f.message:String(f)}
3
+ `),process.exit(127)}let p={...process.env,PATH:Sn},m=mn(o,l,{stdio:"inherit",env:p,shell:!1}),u=!1;return m.on("error",f=>{u||(u=!0,process.stderr.write(`secure-exec: spawn failed: ${f.message}
4
+ `),process.exit(127))}),m.on("exit",(f,S)=>{if(!u){if(u=!0,S){let A=pn.signals[S];process.exit(128+(typeof A=="number"?A:0))}process.exit(f??0)}}),!0}function vn(){let e;try{e=yn("/etc/passwd","utf8")}catch{throw new Error("cannot read /etc/passwd to resolve the secure-exec user")}let t=e.split(`
5
+ `).filter(d=>d.startsWith(`${v}:`));if(t.length===0)throw new Error(`secure exec user "${v}" not found in /etc/passwd \u2014 reinstall the agent to create it`);if(t.length>1)throw new Error(`multiple /etc/passwd entries for "${v}" \u2014 refusing to guess which is the sandbox user`);let r=t[0].split(":");if(r.length!==7)throw new Error(`malformed passwd entry for ${v}`);let s=r[2],i=r[3];if(!/^\d+$/.test(s)||!/^\d+$/.test(i))throw new Error(`could not resolve uid/gid for ${v}`);let o=Number(s),l=Number(i),a=r[5]||"/tmp";if(!Number.isInteger(o)||!Number.isInteger(l))throw new Error(`could not resolve uid/gid for ${v}`);if(o===0)throw new Error("refusing to run secure exec as uid 0");if(l===0)throw new Error("refusing to run secure exec as gid 0");return{uid:o,gid:l,home:a,name:v}}var bn="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",wn=new Set(["NODE_OPTIONS","BASH_ENV","ENV","IFS","PYTHONSTARTUP","PYTHONPATH","PERL5OPT","RUBYOPT","GIT_EXTERNAL_DIFF","PATH","HOME","USER","LOGNAME"]),Rn=e=>/^LD_/.test(e)||wn.has(e);function ot(e,t){if(process.platform!=="linux")throw new Error("secure exec is only supported on Linux");if(typeof process.getuid=="function"&&process.getuid()!==0)throw new Error("secure exec requires the agent to run as root (to drop privilege)");let r=e.argv;if(!Array.isArray(r)||r.length===0||typeof r[0]!="string")throw new Error("secure exec requires a non-empty argv");let s=r[0];if(s.includes("/"))throw new Error(`command "${s}" must be a bare command name (no path separators)`);if(!e.allowedCommands.includes(s))throw new Error(`command "${s}" is not in this token's allowlist`);if(e.cwd!=null&&!En(e.cwd))throw new Error(`cwd "${e.cwd}" must be an absolute path`);let i=null;if(e.input!=null&&(i=Buffer.from(e.input,"base64"),i.length>262144))throw new Error(`stdin payload ${i.length}B exceeds limit ${262144}B`);let o=vn(),l={HOME:o.home,USER:o.name,LOGNAME:o.name,PATH:bn},a={};for(let[g,U]of Object.entries(e.env??{}))Rn(g)||(a[g]=U);let d={...a,...l},c=Date.now(),{cmd:p,args:m}=tt([String(o.uid),String(o.gid),o.name,s,...r.slice(1)]),u=hn(p,m,{cwd:e.cwd??o.home,env:d,stdio:["pipe","pipe","pipe"],detached:!0,shell:!1});i&&u.stdin?(u.stdin.on("error",()=>{}),u.stdin.end(i)):u.stdin?.end();let f=!1,S=null,A=()=>{S&&(clearTimeout(S),S=null)};u.stdout?.on("data",g=>{t.onOutput(g.toString("base64"),"stdout")}),u.stderr?.on("data",g=>{t.onOutput(g.toString("base64"),"stderr")}),u.on("close",g=>{f=!0,A(),t.onDone(g??-1,Date.now()-c)}),u.on("error",g=>{f=!0,A(),t.onError(g.message)});let T=g=>{if(!(f||u.pid==null))try{process.kill(-u.pid,g)}catch{}};return{kill:()=>{f||(T("SIGTERM"),A(),S=setTimeout(()=>{S=null,T("SIGKILL")},5e3),S.unref?.())}}}import w from"chalk";function st(e,t,r=!1){console.clear(),console.log(),console.log(w.bold.cyan(" AI Commander \u2014 Remote Agent")),console.log(),console.log(w.gray(" Session code:")),console.log(),console.log(w.bold.greenBright(` ${r?e:j(e)}`)),console.log(),r||console.log(w.gray(" Reveal the full code: sudo aicommander-agent status --reveal")),console.log(w.gray(" Then give it to your admin to connect.")),console.log(w.yellow(" \u26A0 Keep this code secret \u2014 anyone who has it can run commands as root here.")),console.log(w.gray(` Server: ${t}`)),console.log(w.gray(" Press Ctrl+C to disconnect.")),console.log(),console.log(w.yellow(" Waiting for admin connection...")),console.log()}function it(e,t){console.log(w.yellow(` Reconnecting in ${Math.round(t/1e3)}s (attempt ${e})...`))}function at(){console.log(w.green(" Connected to relay \u2014 ready for commands."))}function _e(e){console.log(w.cyan(` > ${e}`))}function xe(e,t){let r=e===0?w.green:w.red;console.log(r(` Done. Exit ${e} in ${t}ms`))}function An(){let e=process.env.AICOMMANDER_DEV;return e==="1"||e==="true"}function lt(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function ct(){return new URL(k).origin}function dt(e){let t=(e??"").trim();if(!t)return k;let r;try{r=new URL(t)}catch{return console.warn(`
6
+ \u26A0 Ignoring malformed AICOMMANDER_SERVER (${t}); using ${k}.
7
+ `),k}if(r.origin===ct())return k;let s=lt(r.hostname);return!An()&&!s?(console.warn(`
8
+ \u26A0 AICOMMANDER_SERVER override to "${r.origin}" ignored for safety \u2014
9
+ the agent runs as root and is host-locked to ${ct()}.
10
+ Set AICOMMANDER_DEV=1 to allow a custom relay for development.
11
+ `),k):r.protocol!=="https:"&&!s?(console.warn(`
12
+ \u26A0 Refusing plaintext relay "${r.origin}" (https required); using ${k}.
13
+ `),k):t.replace(/\/+$/,"")}function ut(e){let t;try{t=new URL(e)}catch{throw new Error("Refusing to connect: malformed relay WebSocket URL.")}if(t.protocol!=="wss:"&&!(t.protocol==="ws:"&&lt(t.hostname)))throw new Error(`Refusing to open a plaintext relay socket (${t.protocol}//${t.host}); wss:// required.`)}var Ie={capable:!1,enabled:!1,expiresAt:null},pt=360*60*1e3;function xn(e,t){return new Promise((r,s)=>{if(t.aborted){s(new DOMException("Aborted","AbortError"));return}let i=setTimeout(r,e);t.addEventListener("abort",()=>{clearTimeout(i),s(new DOMException("Aborted","AbortError"))},{once:!0})})}async function gt(e){let t=1e3,r=3e4,s=0,i=e.agentToken;for(;!e.signal?.aborted;){s++;try{let o=await In(e,i);if(t=1e3,s=0,o&&e.reauth&&!e.signal?.aborted)try{i=await e.reauth()}catch{}}catch(o){if(o.name==="AbortError")break;let l=.8+Math.random()*.4,a=Math.min(t*l,r);e.silent||it(s,a);try{await xn(a,e.signal??new AbortController().signal)}catch(d){if(d.name==="AbortError")break}t=Math.min(t*2,r)}}}async function In(e,t){let{serverUrl:r,sessionCode:s}=e,i=`${r.replace(/^http/,"ws")}/ws/agent/${s}?token=${t}`;ut(i);let o=c=>{try{e.onStatus?.(c)}catch{}},l=c=>{try{e.onActivity?.(c)}catch{}},a=c=>{if(c)try{e.onRemoteActivity?.(c)}catch{}},d=()=>{try{e.onHeartbeat?.()}catch{}};return o("connecting"),new Promise((c,p)=>{let m=new Tn(i),u=null,f=null,S=null,A=!1,T=null,g=!1,U=()=>{S&&(clearTimeout(S),S=null)},y=()=>{T&&(clearInterval(T),T=null)},V=()=>{if(!e.reauthIntervalMs||!e.reauth)return;let E=()=>{if(u){S=setTimeout(E,3e4);return}A=!0,m.close(1e3,"reauth")};S=setTimeout(E,e.reauthIntervalMs)},Z=()=>{g||(g=!0,U(),y(),c(A))},Q=E=>{g||(g=!0,U(),y(),p(E))},Xe=()=>{d(),f&&clearTimeout(f),f=setTimeout(()=>{m.terminate(),Q(new Error("Ping timeout"))},9e4)};e.signal?.addEventListener("abort",()=>m.close(1e3,"disabled"),{once:!0});let ye=()=>{if(g)return;let E={type:"agent:screen_state",screenShare:e.screenShare?.getState()??Ie};try{m.send(JSON.stringify(E))}catch{}};m.on("open",()=>{o("connected"),Xe(),V();let E={type:"agent:register",hostname:_n.hostname(),platform:process.platform,arch:process.arch,agentVersion:O,screenShare:e.screenShare?.getState()??Ie};m.send(JSON.stringify(E)),e.screenShare?.on("change",ye),e.silent||at()}),m.on("message",E=>{let R;try{R=JSON.parse(String(E))}catch{return}switch(R.type){case"do:ping":Xe();let sn={type:"agent:pong",ts:R.ts};m.send(JSON.stringify(sn));break;case"do:exec":{_e(R.command),l(!0),a(R.operator);let{commandId:D,command:W,cwd:Ee,env:ve}=R,oe=Date.now(),z=!1;y(),T=setInterval(()=>{let _=Date.now()-oe;if(_>=3e5&&!z){z=!0;let h={type:"agent:exec_idle",commandId:D,idleMs:_};m.send(JSON.stringify(h))}},3e5),T.unref?.(),u=ze(W,Ee,ve,{onOutput:(_,h)=>{oe=Date.now(),z=!1;let I={type:"agent:output",commandId:D,chunk:_,stream:h};m.send(JSON.stringify(I))},onDone:(_,h)=>{u=null,y(),l(!1),xe(_,h);let I={type:"agent:done",commandId:D,exitCode:_,durationMs:h};m.send(JSON.stringify(I))},onError:_=>{u=null,y(),l(!1);let h={type:"agent:error",commandId:D,error:_};m.send(JSON.stringify(h))}}).kill;break}case"do:secure_exec":{let{commandId:D,argv:W,allowedCommands:Ee,input:ve,cwd:oe,env:z}=R,Ye=(h,I)=>{u=null,y(),l(!1),xe(h,I);let ee={type:"agent:done",commandId:D,exitCode:h,durationMs:I};m.send(JSON.stringify(ee))},_=h=>{u=null,y(),l(!1);let I={type:"agent:error",commandId:D,error:h};m.send(JSON.stringify(I))};try{let h=Array.isArray(W)?W.join(" "):String(W);_e(h),l(!0);let I=Date.now(),ee=!1;y(),T=setInterval(()=>{let se=Date.now()-I;if(se>=3e5&&!ee){ee=!0;let be={type:"agent:exec_idle",commandId:D,idleMs:se};m.send(JSON.stringify(be))}},3e5),T.unref?.(),u=ot({argv:W,allowedCommands:Ee,input:ve,cwd:oe,env:z},{onOutput:(se,be)=>{I=Date.now(),ee=!1;let an={type:"agent:output",commandId:D,chunk:se,stream:be};m.send(JSON.stringify(an))},onDone:Ye,onError:_}).kill}catch(h){_(h instanceof Error?h.message:String(h))}break}case"do:kill":u&&(u(),u=null);break;case"do:screenshot":a(R.operator),kn(m,R.requestId,e.screenShare);break}}),m.on("close",(E,R)=>{f&&clearTimeout(f),y(),e.screenShare?.off("change",ye),u&&(u(),u=null,l(!1)),o("disconnected"),E===1e3||E===4001?Z():Q(new Error(`WS closed: ${E} ${String(R)}`))}),m.on("error",E=>{f&&clearTimeout(f),y(),e.screenShare?.off("change",ye),o("disconnected"),Q(E)}),m.on("unexpected-response",(E,R)=>{p(new Error(`Unexpected HTTP response: ${R.statusCode}`))})})}async function kn(e,t,r){let s=l=>{try{e.send(JSON.stringify(l))}catch{}},i=l=>s({type:"agent:screenshot_error",requestId:t,error:l}),o=r?.getState()??Ie;if(!r||!o.capable){i("This machine cannot share its screen (desktop macOS/Windows only).");return}if(!o.enabled){i("Screen sharing is turned off on this machine.");return}try{let{data:l,mimeType:a}=await r.capture();if(l.length>10485760){let c=(l.length/1048576).toFixed(1);i(`Screenshot is ${c} MB, which exceeds the ${10485760/(1024*1024)} MB limit.`);return}let d=l.toString("base64");for(let c=0;c<d.length;c+=524288)s({type:"agent:screenshot_chunk",requestId:t,chunk:d.slice(c,c+524288)});s({type:"agent:screenshot_done",requestId:t,mimeType:a,totalBytes:l.length})}catch(l){i(`Screenshot failed: ${l.message}`)}}import N from"node:fs/promises";import yt from"node:path";var ae="/var/run/aicommander-agent",ce=yt.join(ae,"state.json"),St=448,ht=384;async function Et(e){let t=null;try{await N.mkdir(ae,{recursive:!0,mode:St}),await N.chmod(ae,St),t=yt.join(ae,`.state.${process.pid}.${Date.now()}.tmp`);let r=await N.open(t,"wx",ht);try{await r.writeFile(JSON.stringify(e,null,2),"utf8")}finally{await r.close()}await N.rename(t,ce),t=null,await N.chmod(ce,ht)}catch{}finally{t&&await N.rm(t,{force:!0}).catch(()=>{})}}async function vt(){try{await N.rm(ce,{force:!0})}catch{}}async function C(){try{let e=await N.readFile(ce,"utf8");return JSON.parse(e)}catch{return null}}import De from"node:fs";import te from"node:path";import Cn from"node:os";import{randomUUID as Dn,randomBytes as On}from"node:crypto";var bt="/etc/aicommander-agent",wt=te.join(Cn.homedir(),".config","aicommander-agent"),le="device.json";function Rt(){return{deviceId:Dn(),deviceSecret:On(32).toString("base64url")}}function Nn(e){return typeof e=="object"&&e!==null&&typeof e.deviceId=="string"&&e.deviceId.length>0&&typeof e.deviceSecret=="string"&&e.deviceSecret.length>0}function ke(e){try{let t=De.readFileSync(e,"utf8"),r=JSON.parse(t);if(Nn(r))return{deviceId:r.deviceId,deviceSecret:r.deviceSecret}}catch{}return null}function Ce(e,t){try{return De.mkdirSync(e,{recursive:!0,mode:448}),De.writeFileSync(te.join(e,le),JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),!0}catch{return!1}}function K(e){if(e){let i=ke(te.join(e,le));if(i)return i;let o=Rt();return Ce(e,o),o}let t=ke(te.join(bt,le));if(t)return t;let r=ke(te.join(wt,le));if(r)return r;let s=Rt();return Ce(bt,s)||Ce(wt,s),s}import M from"node:fs";import J from"node:path";import Mn from"node:os";var Ln="/etc/aicommander-agent",$n=J.join(Mn.homedir(),".config","aicommander-agent"),Oe="session.json",At=".rotate";function Pn(e){return typeof e=="object"&&e!==null&&typeof e.sessionCode=="string"&&e.sessionCode.length>0&&typeof e.agentToken=="string"&&e.agentToken.length>0}function Un(e){try{let t=M.readFileSync(e,"utf8"),r=JSON.parse(t);if(Pn(r))return{sessionCode:r.sessionCode,agentToken:r.agentToken}}catch{}return null}function Hn(e,t){try{return M.mkdirSync(e,{recursive:!0,mode:448}),M.writeFileSync(J.join(e,Oe),JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),!0}catch{return!1}}function ne(e){return e?[e]:[Ln,$n]}function Tt(e){for(let t of ne(e)){let r=Un(J.join(t,Oe));if(r)return r}return null}function Ne(e,t){for(let r of ne(t))if(Hn(r,e))return}function _t(e){for(let t of ne(e))try{M.rmSync(J.join(t,Oe),{force:!0})}catch{}}function xt(e){for(let t of ne(e))try{M.mkdirSync(t,{recursive:!0,mode:448}),M.writeFileSync(J.join(t,At),"",{mode:384});return}catch{}}function It(e){let t=!1;for(let r of ne(e)){let s=J.join(r,At);try{M.existsSync(s)&&(t=!0,M.rmSync(s,{force:!0}))}catch{}}return t}import{spawn as Kn}from"child_process";import de from"fs";import kt from"path";import Gn from"os";function ue(e){if(e)return kt.join(e,"heartbeat");if(process.platform==="linux")try{return de.mkdirSync("/run/aicommander-agent",{recursive:!0}),"/run/aicommander-agent/heartbeat"}catch{}return kt.join(Gn.tmpdir(),"aicommander-agent-heartbeat")}function Ct(e){try{let t=`${e}.tmp`;de.writeFileSync(t,String(Date.now())),de.renameSync(t,e)}catch{}}var re=null;function Dt(e,t=5e3){Me(),Ct(e),re=setInterval(()=>Ct(e),t),re.unref?.()}function Me(){re&&(clearInterval(re),re=null)}function Ot(e){try{let t=de.readFileSync(e,"utf8").trim(),r=Number(t);return Number.isFinite(r)?r:null}catch{return null}}async function Mt(e={}){let t=e.heartbeatPath??ue(e.configDir),r=e.spawnWorker??(p=>Kn(process.execPath,process.argv.slice(1),{env:p,stdio:"inherit"})),s=null,i=0,o=!1,l=0,a=[],d=null,c=null;await new Promise(p=>{let m=null,u=null,f=()=>{d&&(clearInterval(d),d=null),c&&(clearTimeout(c),c=null),m&&(process.removeListener("SIGINT",m),m=null),u&&(process.removeListener("SIGTERM",u),u=null)},S=()=>{f(),p()},A=()=>{i=Date.now(),l++;let y={...process.env,AIC_ROLE:"worker",AIC_HEARTBEAT:t};s=r(y),s.on("exit",(V,Z)=>{if(s=null,o){S();return}if(e.maxSpawns!=null&&l>=e.maxSpawns){S();return}T(`worker exited (code=${V??"null"} signal=${Z??"null"})`)}),s.on("error",()=>{})},T=y=>{let V=Date.now();a=a.filter(Q=>V-Q<3e5),a.push(V);let Z=a.length>5?6e4:0;c&&clearTimeout(c),c=setTimeout(()=>{c=null,o||A()},Z),c.unref?.()},g=()=>{if(s)try{s.kill("SIGKILL")}catch{}};d=setInterval(()=>{if(o||!s||Date.now()-i<3e4)return;let y=Ot(t);y!=null&&Date.now()-y>3e4&&g()},1e4),d.unref?.();let U=y=>{if(o=!0,d&&(clearInterval(d),d=null),c&&(clearTimeout(c),c=null),s)try{s.kill(y)}catch{}else S()};m=()=>U("SIGINT"),u=()=>U("SIGTERM"),process.on("SIGINT",m),process.on("SIGTERM",u),A()})}function Jn(e,t){let r=e.split(".").map(o=>parseInt(o,10)||0),s=t.split(".").map(o=>parseInt(o,10)||0),i=Math.max(r.length,s.length);for(let o=0;o<i;o++){let l=(r[o]??0)-(s[o]??0);if(l!==0)return l>0?1:-1}return 0}function Lt(e,t){return Jn(e,t)>0}async function $t(e,t=1e4){let r=new AbortController,s=setTimeout(()=>r.abort(),t);try{let i=await fetch(`${e.replace(/\/+$/,"")}/dist/latest`,{signal:r.signal,headers:{Accept:"application/json"}});if(!i.ok)return null;let o=await i.json();return{version:typeof o.version=="string"?o.version:null,mac:typeof o.mac=="string"?o.mac:null,win:typeof o.win=="string"?o.win:null,agentLinuxX64:typeof o.agentLinuxX64=="string"?o.agentLinuxX64:null,agentLinuxArm64:typeof o.agentLinuxArm64=="string"?o.agentLinuxArm64:null}}catch{return null}finally{clearTimeout(s)}}var H=dt(process.env.AICOMMANDER_SERVER),Xn=1440*60*1e3;async function Pt(){let e=await $t(H);e?.version&&Lt(e.version,O)&&console.warn(`
6
14
  \u2B06 A newer AI Commander agent is available (v${e.version}; you have v${O}).
7
15
  Update: curl -fsSL ${H}/install | sudo bash
8
- `)}async function Ot(){process.env.AIC_ROLE==="worker"?await Gn():await _t()}async function Gn(){let e=process.env.AIC_ROLE==="worker";e&&Tt(process.env.AIC_HEARTBEAT||ue());let t=()=>{e&&Me(),pt(),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t),typeof process.getuid=="function"&&process.getuid()!==0&&console.warn(`
16
+ `)}async function Ut(){process.env.AIC_ROLE==="worker"?await Yn():await Mt()}async function Yn(){let e=process.env.AIC_ROLE==="worker";e&&Dt(process.env.AIC_HEARTBEAT||ue());let t=()=>{e&&Me(),vt(),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t),typeof process.getuid=="function"&&process.getuid()!==0&&console.warn(`
9
17
  \u26A0 Warning: not running as root.
10
18
  Commands requiring sudo (apt, systemctl, brew cask\u2026) will fail.
11
19
  Recommended: sudo aicommander-agent
12
- `);let r=K(),s=wt(),i=s?null:Et(),o,a;try{let l=await Ae(H,r,{forceNew:s,...i?{currentCode:i.sessionCode}:{}});o=l.sessionCode,a=l.agentToken,Ne({sessionCode:o,agentToken:a})}catch(l){console.error(` Failed to register: ${String(l)}`),process.exit(1)}rt(o,H,!0),ft({sessionCode:o,pid:process.pid,startedAt:new Date().toISOString(),serverUrl:H}),Dt(),setInterval(()=>{Dt()},Bn).unref?.(),await lt({serverUrl:H,sessionCode:o,agentToken:a,reauthIntervalMs:ct,reauth:async()=>{let l=await Ae(H,r,{currentCode:o});return Ne({sessionCode:l.sessionCode,agentToken:l.agentToken}),l.agentToken}})}import te from"node:fs";import{execFileSync as $t}from"node:child_process";import Pt from"chalk";import{execFileSync as Le}from"node:child_process";var L="aicommander-agent";function F(e){Le("systemctl",e,{stdio:"inherit"})}function J(){try{return Le("systemctl",["is-active",L],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return"inactive"}}function Nt(){try{return Le("systemctl",["is-enabled",L],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="enabled"}catch{return!1}}function me(){F(["start",L])}function X(){F(["stop",L])}function fe(){F(["enable",L])}function pe(){F(["disable",L])}function Y(){F(["restart",L])}function ge(){F(["daemon-reload"])}function Mt(){F(["kill","--signal=SIGKILL",L])}import $ from"chalk";import Vn from"node:readline";var n={header:e=>console.log($.bold.cyan(`
20
+ `);let r=K(),s=It(),i=s?null:Tt(),o,l;try{let c=await Re(H,r,{forceNew:s,...i?{currentCode:i.sessionCode}:{}});o=c.sessionCode,l=c.agentToken,Ne({sessionCode:o,agentToken:l})}catch(c){console.error(` Failed to register: ${String(c)}`),process.exit(1)}let a=!!(process.env.INVOCATION_ID||process.env.JOURNAL_STREAM);st(o,H,process.stdout.isTTY===!0||!a),Et({sessionCode:o,pid:process.pid,startedAt:new Date().toISOString(),serverUrl:H}),Pt(),setInterval(()=>{Pt()},Xn).unref?.(),await gt({serverUrl:H,sessionCode:o,agentToken:l,reauthIntervalMs:pt,reauth:async()=>{let c=await Re(H,r,{currentCode:o});return Ne({sessionCode:c.sessionCode,agentToken:c.agentToken}),c.agentToken}})}import G from"node:fs";import{execFileSync as $e}from"node:child_process";import Bt from"chalk";import{execFileSync as Le}from"node:child_process";var L="aicommander-agent";function F(e){Le("systemctl",e,{stdio:"inherit"})}function X(){try{return Le("systemctl",["is-active",L],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return"inactive"}}function Ht(){try{return Le("systemctl",["is-enabled",L],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="enabled"}catch{return!1}}function me(){F(["start",L])}function Y(){F(["stop",L])}function fe(){F(["enable",L])}function pe(){F(["disable",L])}function q(){F(["restart",L])}function ge(){F(["daemon-reload"])}function Ft(){F(["kill","--signal=SIGKILL",L])}import $ from"chalk";import qn from"node:readline";var n={header:e=>console.log($.bold.cyan(`
13
21
  ${e}
14
- `)),ok:e=>console.log($.green(` \u2713 ${e}`)),warn:e=>console.log($.yellow(` \u26A0 ${e}`)),error:e=>console.error($.red(` \u2717 ${e}`)),info:(e,t)=>console.log(` ${$.gray(e.padEnd(14))} ${$.white(t)}`),step:e=>console.log($.gray(` ${e}`)),blank:()=>console.log()};function v(){process.getuid?.()!==0&&(n.error("This command must be run as root."),console.error($.gray(" Re-run with: sudo aicommander-agent <command>")),process.exit(1))}async function Lt(e){if(!process.stdin.isTTY)return!1;let t=Vn.createInterface({input:process.stdin,output:process.stdout});try{let r=await new Promise(s=>t.question(` ${e} [y/N] `,s));return/^y(es)?$/i.test(r.trim())}finally{t.close()}}var Ut="/etc/systemd/system/aicommander-agent.service",$e="/etc/aicommander-agent";function jn(e){/[\u0000-\u001f\u007f]/.test(e)&&(n.error(`Invalid --server URL: contains control characters: ${JSON.stringify(e)}`),process.exit(1));let t;try{t=new URL(e)}catch{n.error(`Invalid --server URL: not a valid URL: ${JSON.stringify(e)}`),process.exit(1)}return t.protocol!=="http:"&&t.protocol!=="https:"&&(n.error(`Invalid --server URL: protocol must be http: or https: (got ${t.protocol})`),process.exit(1)),e.replace(/%/g,"%%")}function Ht(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`}function Kn(){n.step(`Ensuring sandbox user "${w}"\u2026`);try{$t("getent",["passwd",w],{stdio:"ignore"}),n.ok(`Sandbox user "${w}" already exists.`);return}catch{}let e=["/usr/sbin/nologin","/sbin/nologin","/bin/false"].find(t=>te.existsSync(t))??"/bin/false";try{$t("useradd",["--system","--create-home","--shell",e,w],{stdio:"ignore"}),n.ok(`Sandbox user "${w}" created.`)}catch{n.warn(`Could not create sandbox user "${w}" \u2014 secure exec will be unavailable until it exists.`)}}async function Pe(e){v(),process.platform!=="linux"&&(n.error(`The systemd service installer supports Linux only. Detected: ${process.platform}`),n.blank(),n.step("For an ephemeral foreground run on this platform, use:"),n.step(" npx @aicommander/agent (or: aicommander-agent run)"),n.step("For a production root install on Linux, the canonical path is:"),n.step(" curl -fsSL https://aicommander.dev/install | sudo bash"),process.exit(1));let t=jn(e.server??process.env.AICOMMANDER_SERVER??se),r=te.realpathSync(process.argv[1]),s=`${Ht(process.execPath)} ${Ht(r)} run`;n.header("AI Commander Agent \u2014 systemd install"),n.info("Server",t),n.info("ExecStart",s),n.blank(),n.step("Creating device identity dir\u2026"),te.mkdirSync($e,{recursive:!0}),te.chmodSync($e,448),n.ok(`Device identity dir ready (${$e}).`),Kn(),n.step(`Writing systemd service to ${Ut}\u2026`);let i=`[Unit]
22
+ `)),ok:e=>console.log($.green(` \u2713 ${e}`)),warn:e=>console.log($.yellow(` \u26A0 ${e}`)),error:e=>console.error($.red(` \u2717 ${e}`)),info:(e,t)=>console.log(` ${$.gray(e.padEnd(14))} ${$.white(t)}`),step:e=>console.log($.gray(` ${e}`)),blank:()=>console.log()};function b(){process.getuid?.()!==0&&(n.error("This command must be run as root."),console.error($.gray(" Re-run with: sudo aicommander-agent <command>")),process.exit(1))}async function Gt(e){if(!process.stdin.isTTY)return!1;let t=qn.createInterface({input:process.stdin,output:process.stdout});try{let r=await new Promise(s=>t.question(` ${e} [y/N] `,s));return/^y(es)?$/i.test(r.trim())}finally{t.close()}}var Vt="/etc/systemd/system/aicommander-agent.service",Pe="/etc/aicommander-agent";function Zn(e){/[\u0000-\u001f\u007f]/.test(e)&&(n.error(`Invalid --server URL: contains control characters: ${JSON.stringify(e)}`),process.exit(1));let t;try{t=new URL(e)}catch{n.error(`Invalid --server URL: not a valid URL: ${JSON.stringify(e)}`),process.exit(1)}return t.protocol!=="http:"&&t.protocol!=="https:"&&(n.error(`Invalid --server URL: protocol must be http: or https: (got ${t.protocol})`),process.exit(1)),e.replace(/%/g,"%%")}function Wt(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`}function Qn(){n.step(`Ensuring sandbox user "${v}"\u2026`);try{$e("getent",["passwd",v],{stdio:"ignore"}),n.ok(`Sandbox user "${v}" already exists.`);return}catch{}let e=["/usr/sbin/nologin","/sbin/nologin","/bin/false"].find(t=>G.existsSync(t))??"/bin/false";try{$e("useradd",["--system","--create-home","--shell",e,v],{stdio:"ignore"});try{let t=$e("getent",["passwd",v]).toString().trim().split(":")[5];t&&G.existsSync(t)&&G.chmodSync(t,448)}catch{}n.ok(`Sandbox user "${v}" created.`)}catch{n.warn(`Could not create sandbox user "${v}" \u2014 secure exec will be unavailable until it exists.`)}}async function Ue(e){b(),process.platform!=="linux"&&(n.error(`The systemd service installer supports Linux only. Detected: ${process.platform}`),n.blank(),n.step("For an ephemeral foreground run on this platform, use:"),n.step(" npx @aicommander/agent (or: aicommander-agent run)"),n.step("For a production root install on Linux, the canonical path is:"),n.step(" curl -fsSL https://aicommander.dev/install | sudo bash"),process.exit(1));let t=Zn(e.server??process.env.AICOMMANDER_SERVER??k),r=G.realpathSync(process.argv[1]),s=`${Wt(process.execPath)} ${Wt(r)} run`;n.header("AI Commander Agent \u2014 systemd install"),n.info("Server",t),n.info("ExecStart",s),n.blank(),n.step("Creating device identity dir\u2026"),G.mkdirSync(Pe,{recursive:!0}),G.chmodSync(Pe,448),n.ok(`Device identity dir ready (${Pe}).`),Qn(),n.step(`Writing systemd service to ${Vt}\u2026`);let i=`[Unit]
15
23
  Description=AI Commander Remote Agent
16
24
  After=network-online.target
17
25
  Wants=network-online.target
@@ -35,4 +43,4 @@ KillSignal=SIGINT
35
43
 
36
44
  [Install]
37
45
  WantedBy=multi-user.target
38
- `;te.writeFileSync(Ut,i,{mode:420}),n.ok("Service file written."),n.step("Reloading systemd\u2026");try{ge()}catch{n.error("daemon-reload failed. Inspect: journalctl -u aicommander-agent -n 50"),process.exit(1)}n.step("Enabling service on boot\u2026");try{fe()}catch{n.warn("Could not enable the service on boot (non-critical).")}n.step("Restarting service\u2026");try{Y()}catch{n.warn("Graceful restart failed \u2014 forcing stop then start\u2026");try{X()}catch{}try{Mt()}catch{}try{me()}catch{n.error("Could not start aicommander-agent. Inspect: journalctl -u aicommander-agent -n 50"),process.exit(1)}}J()!=="active"&&(n.error("Service is not active after restart. Inspect: journalctl -u aicommander-agent -n 50"),process.exit(1)),n.ok("Service started."),n.blank(),n.step("Waiting for session code\u2026");let o=null;for(let a=0;a<30;a++){let c=await I();if(c?.sessionCode){o=c.sessionCode;break}await new Promise(l=>setTimeout(l,500))}n.blank(),o?(n.ok(Pt.bold("AI Commander ready!")),n.blank(),n.info("Session code",Pt.bold.greenBright(j(o))),n.blank(),n.step("Reveal full code: sudo aicommander-agent status --reveal"),n.step("Then use in Claude: 'execute df -h on <code>'"),n.step("Service logs: journalctl -u aicommander-agent -f"),n.step("Manage: sudo aicommander-agent status"),n.step("Uninstall: sudo aicommander-agent uninstall --force"),n.blank(),n.warn("Keep this code secret. Anyone who has it can run commands as root on this machine.")):(n.warn("The session code did not appear within 15 seconds."),n.step("The service is running \u2014 the code should appear shortly."),n.step("Status: sudo aicommander-agent status"),n.step("Logs: journalctl -u aicommander-agent -f")),n.blank()}import P from"chalk";function Wn(e){if(e<60)return`${e}s`;if(e<3600)return`${Math.floor(e/60)}m`;let t=Math.floor(e/3600),r=Math.floor(e%3600/60);return r>0?`${t}h ${r}m`:`${t}h`}async function Ue(e={}){n.header("AI Commander \u2014 Agent Status");let t;try{t=J()}catch{n.error("systemd is not available on this system."),process.exit(1)}let r=Nt(),s=await I();if(n.info("State",t==="active"?P.green("running"):P.red(t)),s){e.reveal?(v(),n.info("Session code",P.bold.cyan(s.sessionCode)),n.step(P.yellow(" \u26A0 Keep this secret \u2014 anyone with it can run commands as root here."))):(n.info("Session code",P.bold.cyan(j(s.sessionCode))),n.step(P.gray(" (run with --reveal to show the full code)"))),n.info("PID",String(s.pid));let i=new Date(s.startedAt),o=Math.floor((Date.now()-i.getTime())/1e3);n.info("Started",`${s.startedAt} (${Wn(o)} ago)`),n.info("Server",s.serverUrl)}else t==="active"&&n.warn("Session code not yet available (agent still starting)");n.info("Enabled",r?P.green("yes"):P.yellow("no")),n.blank()}function He(){v(),J()==="active"?(n.warn("Service is already running \u2014 restarting to load the current binary."),Y()):me(),fe(),n.ok("Service started and enabled to run on boot."),n.blank()}function Fe(){v(),X(),pe(),n.ok("Service stopped and disabled."),n.blank()}import Jn from"chalk";async function Be(e={}){if(v(),!e.yes){if(!process.stdin.isTTY){n.error("Refusing to reset the code non-interactively."),n.info("To proceed","re-run with --yes (this unlinks ALL linked accounts)"),process.exitCode=1;return}if(!await Lt("Resetting the access code will UNLINK ALL linked accounts. Continue?")){n.info("Cancelled","no changes made");return}}n.step("Restarting agent to get a new session code\u2026"),bt(),vt(),Y();let t=Date.now()+1e4,r=null;for(;Date.now()<t&&(await new Promise(s=>setTimeout(s,500)),r=await I(),!r););r?n.ok(`New session code: ${Jn.bold.greenBright(r.sessionCode)}`):(n.warn("Service restarted. Session code not yet available."),n.info("Check","aicommander-agent status")),n.blank()}import Ge from"node:fs";import Xn from"chalk";var Ft="/etc/systemd/system/aicommander-agent.service",Bt="/usr/local/bin/aicommander-agent",Gt="/usr/local/bin/aicommander-ctl",Vt="/var/run/aicommander-agent",jt="/etc/aicommander-agent",Kt="/etc/aicommander-agent/session.json",Wt="/etc/aicommander-agent/.rotate";function B(e,t){try{if(Ge.existsSync(e)||Ge.lstatSync(e)){Ge.rmSync(e,{recursive:!0,force:!0}),n.ok(`${t} removed.`);return}}catch{}n.warn(`${t} not found (already removed?).`)}function Ve(e){v(),e.force||(n.warn("This will fully remove the AI Commander agent."),n.error("Add --force to confirm: sudo aicommander-agent uninstall --force"),process.exit(1)),n.step("Stopping and disabling service\u2026");try{X()}catch{}try{pe()}catch{}n.ok("Service stopped."),n.step("Removing service file\u2026"),B(Ft,Ft),n.step("Reloading systemd\u2026");try{ge(),n.ok("daemon-reload complete.")}catch{n.warn("daemon-reload failed (non-critical).")}n.step("Removing agent binary\u2026"),B(Gt,Gt),B(Bt,Bt),B(Vt,Vt),B(Kt,Kt),B(Wt,Wt),B(jt,jt),n.blank(),n.ok(Xn.bold("AI Commander agent fully removed.")),n.blank()}function Jt(e){return{"X-Device-Id":e.deviceId,"X-Device-Secret":e.deviceSecret}}async function Se(e,t){let r=await fetch(`${e}/api/device/admins`,{headers:Jt(t)});if(!r.ok)throw new Error(`Failed to list linked accounts (HTTP ${r.status}).`);return await r.json()}async function Xt(e,t,r,s){let i=await fetch(`${e}/api/device/${r}`,{method:"POST",headers:{...Jt(t),"Content-Type":"application/json"},body:JSON.stringify({userId:s})}),o;try{o=await i.json()}catch{o={ok:!1,error:`http_${i.status}`}}return{...o,ok:i.ok}}function Yt(e,t,r){return Xt(e,t,"block",r)}function qt(e,t,r){return Xt(e,t,"unblock",r)}function he(e){return[...e.filter(t=>!t.blocked),...e.filter(t=>t.blocked)]}function Zt(e,t){let r=t.trim();if(!r)return{kind:"not_found"};if(/^\d+$/.test(r)){let o=Number(r)-1;return o>=0&&o<e.length?{kind:"ok",admin:e[o]}:{kind:"not_found"}}let s=e.find(o=>o.userId===r);if(s)return{kind:"ok",admin:s};let i=e.filter(o=>o.userId.startsWith(r));return i.length===1?{kind:"ok",admin:i[0]}:i.length>1?{kind:"ambiguous",matches:i}:{kind:"not_found"}}async function Yn(){return(await I())?.serverUrl??process.env.AICOMMANDER_SERVER??"https://aicommander.dev"}async function je(){v();let e=await Yn(),t=K(),r;try{r=await Se(e,t)}catch(c){n.error(c.message),process.exitCode=1;return}if(r.admins.length===0){n.header("Linked accounts"),n.info("None","no accounts are linked to this device"),n.blank();return}let s=he(r.admins),i=(c,l)=>{let d=String(l+1).padStart(2," "),u=c.linkedAt.slice(0,10);n.info(`${d}. ${c.maskedEmail}`,`${c.alias} \xB7 linked ${u} \xB7 id ${c.userId.slice(0,8)}\u2026`)},o=s.filter(c=>!c.blocked),a=s.filter(c=>c.blocked);n.header("Linked accounts"),o.forEach(c=>i(c,s.indexOf(c))),o.length===0&&n.info("None active","every linked account is blocked"),n.blank(),a.length>0&&(n.header("Blocked"),a.forEach(c=>i(c,s.indexOf(c))),n.blank()),n.step("Block one with: aicommander-agent block-admin <number|id>"),a.length>0&&n.step("Unblock one with: aicommander-agent unblock-admin <number|id>"),n.blank()}async function qn(){return(await I())?.serverUrl??process.env.AICOMMANDER_SERVER??"https://aicommander.dev"}async function Qt(e,t){v();let r=await qn(),s=K(),i;try{i=await Se(r,s)}catch(d){n.error(d.message),process.exitCode=1;return}let o=he(i.admins),a=Zt(o,e);if(a.kind==="not_found"){n.error(`No linked account matches "${e}".`),n.info("See options","aicommander-agent list-admins"),process.exitCode=1;return}if(a.kind==="ambiguous"){n.error(`"${e}" is ambiguous \u2014 it matches ${a.matches.length} accounts.`),n.info("Disambiguate","use the list number or a longer id"),process.exitCode=1;return}let c=a.admin,l=t==="block"?await Yt(r,s,c.userId):await qt(r,s,c.userId);l.ok?t==="block"?(n.ok(`Blocked ${c.maskedEmail} (${c.alias}).`),n.info("Note","their access is cut off; run unblock-admin anytime to restore it")):n.ok(`Unblocked ${c.maskedEmail} (${c.alias}) \u2014 access restored.`):l.error==="not_found"?n.warn(t==="block"?"That account isn't linked (or is already blocked).":"That account isn't blocked."):(n.error(l.message??`Failed to ${t} the account.`),process.exitCode=1),n.blank()}function Ke(e){return Qt(e,"block")}function We(e){return Qt(e,"unblock")}et(process.argv)||(T.name("aicommander-agent").description("AI Commander remote agent + service controller").version(O),T.command("run",{isDefault:!0}).description("Run the agent: register with the relay and listen for commands").action(async()=>{await Ot()}),T.command("install").description("Install and start the agent as a systemd service (Linux, root)").option("--server <url>","Relay server URL baked into the service unit").action(async e=>{await Pe(e)}),T.command("status").description("Show agent status, session code, and uptime").option("--reveal","Show the full session code (otherwise masked)").action(async e=>{await Ue(e)}),T.command("enable").description("Start and enable the agent service").action(()=>{He()}),T.command("disable").description("Stop and disable the agent service").action(()=>{Fe()}),T.command("change-code").aliases(["reset-code"]).description("Reset the access code \u2014 mint a new code and remove ALL access (unlinks every linked account)").option("-y, --yes","Skip the confirmation prompt").action(async e=>{await Be(e)}),T.command("list-admins").description("List the accounts (admins) linked to this device").action(async()=>{await je()}),T.command("block-admin <account>").aliases(["revoke-admin"]).description("Block one account on this device (by list number or id) \u2014 refuses access; unblock anytime").action(async e=>{await Ke(e)}),T.command("unblock-admin <account>").description("Restore a blocked account's access (by list number or id)").action(async e=>{await We(e)}),T.command("uninstall").description("Fully remove the agent (stop, disable, delete files)").option("-f, --force","Skip confirmation requirement").action(e=>{Ve(e)}),T.parseAsync().catch(e=>{console.error("Fatal error:",e),process.exit(1)}));
46
+ `;G.writeFileSync(Vt,i,{mode:420}),n.ok("Service file written."),n.step("Reloading systemd\u2026");try{ge()}catch{n.error("daemon-reload failed. Inspect: journalctl -u aicommander-agent -n 50"),process.exit(1)}n.step("Enabling service on boot\u2026");try{fe()}catch{n.warn("Could not enable the service on boot (non-critical).")}n.step("Restarting service\u2026");try{q()}catch{n.warn("Graceful restart failed \u2014 forcing stop then start\u2026");try{Y()}catch{}try{Ft()}catch{}try{me()}catch{n.error("Could not start aicommander-agent. Inspect: journalctl -u aicommander-agent -n 50"),process.exit(1)}}X()!=="active"&&(n.error("Service is not active after restart. Inspect: journalctl -u aicommander-agent -n 50"),process.exit(1)),n.ok("Service started."),n.blank(),n.step("Waiting for session code\u2026");let o=null;for(let l=0;l<30;l++){let a=await C();if(a?.sessionCode){o=a.sessionCode;break}await new Promise(d=>setTimeout(d,500))}n.blank(),o?(n.ok(Bt.bold("AI Commander ready!")),n.blank(),n.info("Session code",Bt.bold.greenBright(j(o))),n.blank(),n.step("Reveal full code: sudo aicommander-agent status --reveal"),n.step("Then use in Claude: 'execute df -h on <code>'"),n.step("Service logs: journalctl -u aicommander-agent -f"),n.step("Manage: sudo aicommander-agent status"),n.step("Uninstall: sudo aicommander-agent uninstall --force"),n.blank(),n.warn("Keep this code secret. Anyone who has it can run commands as root on this machine.")):(n.warn("The session code did not appear within 15 seconds."),n.step("The service is running \u2014 the code should appear shortly."),n.step("Status: sudo aicommander-agent status"),n.step("Logs: journalctl -u aicommander-agent -f")),n.blank()}import P from"chalk";function zn(e){if(e<60)return`${e}s`;if(e<3600)return`${Math.floor(e/60)}m`;let t=Math.floor(e/3600),r=Math.floor(e%3600/60);return r>0?`${t}h ${r}m`:`${t}h`}async function He(e={}){n.header("AI Commander \u2014 Agent Status");let t;try{t=X()}catch{n.error("systemd is not available on this system."),process.exit(1)}let r=Ht(),s=await C();if(n.info("State",t==="active"?P.green("running"):P.red(t)),s){e.reveal?(b(),n.info("Session code",P.bold.cyan(s.sessionCode)),n.step(P.yellow(" \u26A0 Keep this secret \u2014 anyone with it can run commands as root here."))):(n.info("Session code",P.bold.cyan(j(s.sessionCode))),n.step(P.gray(" (run with --reveal to show the full code)"))),n.info("PID",String(s.pid));let i=new Date(s.startedAt),o=Math.floor((Date.now()-i.getTime())/1e3);n.info("Started",`${s.startedAt} (${zn(o)} ago)`),n.info("Server",s.serverUrl)}else t==="active"&&n.warn("Session code not yet available (agent still starting)");n.info("Enabled",r?P.green("yes"):P.yellow("no")),n.blank()}function Fe(){b(),X()==="active"?(n.warn("Service is already running \u2014 restarting to load the current binary."),q()):me(),fe(),n.ok("Service started and enabled to run on boot."),n.blank()}function Ge(){b(),Y(),pe(),n.ok("Service stopped and disabled."),n.blank()}import er from"chalk";async function Be(e={}){if(b(),!e.yes){if(!process.stdin.isTTY){n.error("Refusing to reset the code non-interactively."),n.info("To proceed","re-run with --yes (this unlinks ALL linked accounts)"),process.exitCode=1;return}if(!await Gt("Resetting the access code will UNLINK ALL linked accounts. Continue?")){n.info("Cancelled","no changes made");return}}n.step("Restarting agent to get a new session code\u2026"),xt(),_t(),q();let t=Date.now()+1e4,r=null;for(;Date.now()<t&&(await new Promise(s=>setTimeout(s,500)),r=await C(),!r););r?n.ok(`New session code: ${er.bold.greenBright(r.sessionCode)}`):(n.warn("Service restarted. Session code not yet available."),n.info("Check","aicommander-agent status")),n.blank()}import Ve from"node:fs";import tr from"chalk";var jt="/etc/systemd/system/aicommander-agent.service",Kt="/usr/local/bin/aicommander-agent",Jt="/usr/local/bin/aicommander-ctl",Xt="/var/run/aicommander-agent",Yt="/etc/aicommander-agent",qt="/etc/aicommander-agent/session.json",Zt="/etc/aicommander-agent/.rotate";function B(e,t){try{if(Ve.existsSync(e)||Ve.lstatSync(e)){Ve.rmSync(e,{recursive:!0,force:!0}),n.ok(`${t} removed.`);return}}catch{}n.warn(`${t} not found (already removed?).`)}function We(e){b(),e.force||(n.warn("This will fully remove the AI Commander agent."),n.error("Add --force to confirm: sudo aicommander-agent uninstall --force"),process.exit(1)),n.step("Stopping and disabling service\u2026");try{Y()}catch{}try{pe()}catch{}n.ok("Service stopped."),n.step("Removing service file\u2026"),B(jt,jt),n.step("Reloading systemd\u2026");try{ge(),n.ok("daemon-reload complete.")}catch{n.warn("daemon-reload failed (non-critical).")}n.step("Removing agent binary\u2026"),B(Jt,Jt),B(Kt,Kt),B(Xt,Xt),B(qt,qt),B(Zt,Zt),B(Yt,Yt),n.blank(),n.ok(tr.bold("AI Commander agent fully removed.")),n.blank()}function Qt(e){return{"X-Device-Id":e.deviceId,"X-Device-Secret":e.deviceSecret}}var zt=1e4;async function Se(e,t){let r;try{r=await fetch(`${e}/api/device/admins`,{headers:Qt(t),signal:AbortSignal.timeout(zt)})}catch{throw new Error("Failed to list linked accounts (relay unreachable or timed out).")}if(!r.ok)throw new Error(`Failed to list linked accounts (HTTP ${r.status}).`);return await r.json()}async function en(e,t,r,s){let i;try{i=await fetch(`${e}/api/device/${r}`,{method:"POST",headers:{...Qt(t),"Content-Type":"application/json"},body:JSON.stringify({userId:s}),signal:AbortSignal.timeout(zt)})}catch{return{ok:!1,error:"unreachable"}}let o;try{o=await i.json()}catch{o={ok:!1,error:`http_${i.status}`}}return{...o,ok:i.ok}}function tn(e,t,r){return en(e,t,"block",r)}function nn(e,t,r){return en(e,t,"unblock",r)}function he(e){return[...e.filter(t=>!t.blocked),...e.filter(t=>t.blocked)]}function rn(e,t){let r=t.trim();if(!r)return{kind:"not_found"};if(/^\d+$/.test(r)){let o=Number(r)-1;return o>=0&&o<e.length?{kind:"ok",admin:e[o]}:{kind:"not_found"}}let s=e.find(o=>o.userId===r);if(s)return{kind:"ok",admin:s};let i=e.filter(o=>o.userId.startsWith(r));return i.length===1?{kind:"ok",admin:i[0]}:i.length>1?{kind:"ambiguous",matches:i}:{kind:"not_found"}}async function nr(){return(await C())?.serverUrl??process.env.AICOMMANDER_SERVER??"https://aicommander.dev"}async function je(){b();let e=await nr(),t=K(),r;try{r=await Se(e,t)}catch(a){n.error(a.message),process.exitCode=1;return}if(r.admins.length===0){n.header("Linked accounts"),n.info("None","no accounts are linked to this device"),n.blank();return}let s=he(r.admins),i=(a,d)=>{let c=String(d+1).padStart(2," "),p=a.linkedAt.slice(0,10);n.info(`${c}. ${a.maskedEmail}`,`${a.alias} \xB7 linked ${p} \xB7 id ${a.userId.slice(0,8)}\u2026`)},o=s.filter(a=>!a.blocked),l=s.filter(a=>a.blocked);n.header("Linked accounts"),o.forEach(a=>i(a,s.indexOf(a))),o.length===0&&n.info("None active","every linked account is blocked"),n.blank(),l.length>0&&(n.header("Blocked"),l.forEach(a=>i(a,s.indexOf(a))),n.blank()),n.step("Block one with: aicommander-agent block-admin <number|id>"),l.length>0&&n.step("Unblock one with: aicommander-agent unblock-admin <number|id>"),n.blank()}async function rr(){return(await C())?.serverUrl??process.env.AICOMMANDER_SERVER??"https://aicommander.dev"}async function on(e,t){b();let r=await rr(),s=K(),i;try{i=await Se(r,s)}catch(c){n.error(c.message),process.exitCode=1;return}let o=he(i.admins),l=rn(o,e);if(l.kind==="not_found"){n.error(`No linked account matches "${e}".`),n.info("See options","aicommander-agent list-admins"),process.exitCode=1;return}if(l.kind==="ambiguous"){n.error(`"${e}" is ambiguous \u2014 it matches ${l.matches.length} accounts.`),n.info("Disambiguate","use the list number or a longer id"),process.exitCode=1;return}let a=l.admin,d=t==="block"?await tn(r,s,a.userId):await nn(r,s,a.userId);d.ok?t==="block"?(n.ok(`Blocked ${a.maskedEmail} (${a.alias}).`),n.info("Note","their access is cut off; run unblock-admin anytime to restore it")):n.ok(`Unblocked ${a.maskedEmail} (${a.alias}) \u2014 access restored.`):d.error==="not_found"?n.warn(t==="block"?"That account isn't linked (or is already blocked).":"That account isn't blocked."):(n.error(d.message??`Failed to ${t} the account.`),process.exitCode=1),n.blank()}function Ke(e){return on(e,"block")}function Je(e){return on(e,"unblock")}nt(process.argv)||(x.name("aicommander-agent").description("AI Commander remote agent + service controller").version(O),x.command("run",{isDefault:!0}).description("Run the agent: register with the relay and listen for commands").action(async()=>{await Ut()}),x.command("install").description("Install and start the agent as a systemd service (Linux, root)").option("--server <url>","Relay server URL baked into the service unit").action(async e=>{await Ue(e)}),x.command("status").description("Show agent status, session code, and uptime").option("--reveal","Show the full session code (otherwise masked)").action(async e=>{await He(e)}),x.command("enable").description("Start and enable the agent service").action(()=>{Fe()}),x.command("disable").description("Stop and disable the agent service").action(()=>{Ge()}),x.command("change-code").aliases(["reset-code"]).description("Reset the access code \u2014 mint a new code and remove ALL access (unlinks every linked account)").option("-y, --yes","Skip the confirmation prompt").action(async e=>{await Be(e)}),x.command("list-admins").description("List the accounts (admins) linked to this device").action(async()=>{await je()}),x.command("block-admin <account>").aliases(["revoke-admin"]).description("Block one account on this device (by list number or id) \u2014 refuses access; unblock anytime").action(async e=>{await Ke(e)}),x.command("unblock-admin <account>").description("Restore a blocked account's access (by list number or id)").action(async e=>{await Je(e)}),x.command("uninstall").description("Fully remove the agent (stop, disable, delete files)").option("-f, --force","Skip confirmation requirement").action(e=>{We(e)}),x.parseAsync().catch(e=>{console.error("Fatal error:",e),process.exit(1)}));
package/dist/index.js CHANGED
@@ -1,2 +1,10 @@
1
- import et from"os";var H="1.0.20";var _e="device_secret_mismatch";function tt(e){try{let t=JSON.parse(e);return typeof t.code=="string"?t.code:null}catch{return null}}var O=class extends Error{constructor(r,o){super(`Registration failed (${r}): ${o}`);this.status=r;this.body=o;this.name="RegistrationError",this.code=tt(o)}status;body;code};async function J(e,t,r={}){let o={hostname:et.hostname(),platform:process.platform,arch:process.arch,agentVersion:H,...t?{deviceId:t.deviceId,deviceSecret:t.deviceSecret}:{},...r.forceNew?{forceNew:!0}:r.currentCode?{currentCode:r.currentCode}:{}},s=await fetch(`${e}/api/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){let n=await s.text();throw new O(s.status,n)}return s.json()}import mt from"ws";import gt from"os";import{spawn as we}from"child_process";var x="aicommander-exec";var Ae="ABCDEFGHJKMNPQRSTVWXYZ0123456789";var er=Math.floor(256/Ae.length)*Ae.length;var Te=process.platform==="win32";function xe(e,t,r,o){let s=Date.now(),n=we(e,[],{shell:!0,cwd:t??process.env.HOME,env:{...process.env,...r??{}},stdio:["ignore","pipe","pipe"],detached:!Te}),i=!1,c=null,l=()=>{c&&(clearTimeout(c),c=null)};n.stdout?.on("data",a=>{o.onOutput(a.toString("base64"),"stdout")}),n.stderr?.on("data",a=>{o.onOutput(a.toString("base64"),"stderr")}),n.on("close",a=>{i=!0,l(),o.onDone(a??-1,Date.now()-s)}),n.on("error",a=>{i=!0,l(),o.onError(a.message)});let u=a=>{if(!(i||n.pid==null))try{Te?we("taskkill",["/pid",String(n.pid),"/T","/F"],{stdio:"ignore"}):process.kill(-n.pid,a)}catch{}};return{kill:()=>{i||(u("SIGTERM"),l(),c=setTimeout(()=>{c=null,u("SIGKILL")},5e3),c.unref?.())}}}import{spawn as st}from"node:child_process";import{readFileSync as it}from"node:fs";import{isAbsolute as at}from"node:path";import{createRequire as rt}from"node:module";var nt=rt(import.meta.url),Ce="__secure-exec-drop";function ot(){let e=!1;try{e=nt("node:sea").isSea()}catch{}return e}function Re(e){let t=process.argv[1],r=!ot()&&t?[t,Ce,...e]:[Ce,...e];return{cmd:process.execPath,args:r}}function ct(){let e;try{e=it("/etc/passwd","utf8")}catch{throw new Error("cannot read /etc/passwd to resolve the secure-exec user")}let t=e.split(`
2
- `).filter(l=>l.startsWith(`${x}:`));if(t.length===0)throw new Error(`secure exec user "${x}" not found in /etc/passwd \u2014 reinstall the agent to create it`);if(t.length>1)throw new Error(`multiple /etc/passwd entries for "${x}" \u2014 refusing to guess which is the sandbox user`);let r=t[0].split(":");if(r.length!==7)throw new Error(`malformed passwd entry for ${x}`);let o=r[2],s=r[3];if(!/^\d+$/.test(o)||!/^\d+$/.test(s))throw new Error(`could not resolve uid/gid for ${x}`);let n=Number(o),i=Number(s),c=r[5]||"/tmp";if(!Number.isInteger(n)||!Number.isInteger(i))throw new Error(`could not resolve uid/gid for ${x}`);if(n===0)throw new Error("refusing to run secure exec as uid 0");if(i===0)throw new Error("refusing to run secure exec as gid 0");return{uid:n,gid:i,home:c,name:x}}var lt="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",ut=new Set(["NODE_OPTIONS","BASH_ENV","ENV","IFS","PYTHONSTARTUP","PYTHONPATH","PERL5OPT","RUBYOPT","GIT_EXTERNAL_DIFF","PATH","HOME","USER","LOGNAME"]),dt=e=>/^LD_/.test(e)||ut.has(e);function De(e,t){if(process.platform!=="linux")throw new Error("secure exec is only supported on Linux");if(typeof process.getuid=="function"&&process.getuid()!==0)throw new Error("secure exec requires the agent to run as root (to drop privilege)");let r=e.argv;if(!Array.isArray(r)||r.length===0||typeof r[0]!="string")throw new Error("secure exec requires a non-empty argv");let o=r[0];if(o.includes("/"))throw new Error(`command "${o}" must be a bare command name (no path separators)`);if(!e.allowedCommands.includes(o))throw new Error(`command "${o}" is not in this token's allowlist`);if(e.cwd!=null&&!at(e.cwd))throw new Error(`cwd "${e.cwd}" must be an absolute path`);let s=null;if(e.input!=null&&(s=Buffer.from(e.input,"base64"),s.length>262144))throw new Error(`stdin payload ${s.length}B exceeds limit ${262144}B`);let n=ct(),i={HOME:n.home,USER:n.name,LOGNAME:n.name,PATH:lt},c={};for(let[p,S]of Object.entries(e.env??{}))dt(p)||(c[p]=S);let l={...c,...i},u=Date.now(),{cmd:a,args:m}=Re([String(n.uid),String(n.gid),n.name,o,...r.slice(1)]),d=st(a,m,{cwd:e.cwd??n.home,env:l,stdio:["pipe","pipe","pipe"],detached:!0,shell:!1});s&&d.stdin?(d.stdin.on("error",()=>{}),d.stdin.end(s)):d.stdin?.end();let y=!1,E=null,h=()=>{E&&(clearTimeout(E),E=null)};d.stdout?.on("data",p=>{t.onOutput(p.toString("base64"),"stdout")}),d.stderr?.on("data",p=>{t.onOutput(p.toString("base64"),"stderr")}),d.on("close",p=>{y=!0,h(),t.onDone(p??-1,Date.now()-u)}),d.on("error",p=>{y=!0,h(),t.onError(p.message)});let A=p=>{if(!(y||d.pid==null))try{process.kill(-d.pid,p)}catch{}};return{kill:()=>{y||(A("SIGTERM"),h(),E=setTimeout(()=>{E=null,A("SIGKILL")},5e3),E.unref?.())}}}import $ from"chalk";function Oe(e,t){console.log($.yellow(` Reconnecting in ${Math.round(t/1e3)}s (attempt ${e})...`))}function Ne(){console.log($.green(" Connected to relay \u2014 ready for commands."))}function oe(e){console.log($.cyan(` > ${e}`))}function se(e,t){let r=e===0?$.green:$.red;console.log(r(` Done. Exit ${e} in ${t}ms`))}var ie={capable:!1,enabled:!1,expiresAt:null},Me=360*60*1e3;function ae(e,t){return new Promise((r,o)=>{if(t.aborted){o(new DOMException("Aborted","AbortError"));return}let s=setTimeout(r,e);t.addEventListener("abort",()=>{clearTimeout(s),o(new DOMException("Aborted","AbortError"))},{once:!0})})}async function ce(e){let t=1e3,r=3e4,o=0,s=e.agentToken;for(;!e.signal?.aborted;){o++;try{let n=await pt(e,s);if(t=1e3,o=0,n&&e.reauth&&!e.signal?.aborted)try{s=await e.reauth()}catch{}}catch(n){if(n.name==="AbortError")break;let i=.8+Math.random()*.4,c=Math.min(t*i,r);e.silent||Oe(o,c);try{await ae(c,e.signal??new AbortController().signal)}catch(l){if(l.name==="AbortError")break}t=Math.min(t*2,r)}}}async function pt(e,t){let{serverUrl:r,sessionCode:o}=e,s=`${r.replace(/^http/,"ws")}/ws/agent/${o}?token=${t}`,n=l=>{try{e.onStatus?.(l)}catch{}},i=l=>{try{e.onActivity?.(l)}catch{}},c=()=>{try{e.onHeartbeat?.()}catch{}};return n("connecting"),new Promise((l,u)=>{let a=new mt(s),m=null,d=null,y=null,E=!1,h=null,A=!1,p=()=>{y&&(clearTimeout(y),y=null)},S=()=>{h&&(clearInterval(h),h=null)},w=()=>{if(!e.reauthIntervalMs||!e.reauth)return;let f=()=>{if(m){y=setTimeout(f,3e4);return}E=!0,a.close(1e3,"reauth")};y=setTimeout(f,e.reauthIntervalMs)},I=()=>{A||(A=!0,p(),S(),l(E))},R=f=>{A||(A=!0,p(),S(),u(f))},j=()=>{c(),d&&clearTimeout(d),d=setTimeout(()=>{a.terminate(),R(new Error("Ping timeout"))},9e4)};e.signal?.addEventListener("abort",()=>a.close(1e3,"disabled"),{once:!0});let q=()=>{if(A)return;let f={type:"agent:screen_state",screenShare:e.screenShare?.getState()??ie};try{a.send(JSON.stringify(f))}catch{}};a.on("open",()=>{n("connected"),j(),w();let f={type:"agent:register",hostname:gt.hostname(),platform:process.platform,arch:process.arch,agentVersion:H,screenShare:e.screenShare?.getState()??ie};a.send(JSON.stringify(f)),e.screenShare?.on("change",q),e.silent||Ne()}),a.on("message",f=>{let b;try{b=JSON.parse(String(f))}catch{return}switch(b.type){case"do:ping":j();let ze={type:"agent:pong",ts:b.ts};a.send(JSON.stringify(ze));break;case"do:exec":{oe(b.command),i(!0);let{commandId:T,command:D,cwd:ee,env:te}=b,K=Date.now(),P=!1;S(),h=setInterval(()=>{let v=Date.now()-K;if(v>=3e5&&!P){P=!0;let g={type:"agent:exec_idle",commandId:T,idleMs:v};a.send(JSON.stringify(g))}},3e5),h.unref?.(),m=xe(D,ee,te,{onOutput:(v,g)=>{K=Date.now(),P=!1;let _={type:"agent:output",commandId:T,chunk:v,stream:g};a.send(JSON.stringify(_))},onDone:(v,g)=>{m=null,S(),i(!1),se(v,g);let _={type:"agent:done",commandId:T,exitCode:v,durationMs:g};a.send(JSON.stringify(_))},onError:v=>{m=null,S(),i(!1);let g={type:"agent:error",commandId:T,error:v};a.send(JSON.stringify(g))}}).kill;break}case"do:secure_exec":{let{commandId:T,argv:D,allowedCommands:ee,input:te,cwd:K,env:P}=b,be=(g,_)=>{m=null,S(),i(!1),se(g,_);let L={type:"agent:done",commandId:T,exitCode:g,durationMs:_};a.send(JSON.stringify(L))},v=g=>{m=null,S(),i(!1);let _={type:"agent:error",commandId:T,error:g};a.send(JSON.stringify(_))};try{let g=Array.isArray(D)?D.join(" "):String(D);oe(g),i(!0);let _=Date.now(),L=!1;S(),h=setInterval(()=>{let X=Date.now()-_;if(X>=3e5&&!L){L=!0;let re={type:"agent:exec_idle",commandId:T,idleMs:X};a.send(JSON.stringify(re))}},3e5),h.unref?.(),m=De({argv:D,allowedCommands:ee,input:te,cwd:K,env:P},{onOutput:(X,re)=>{_=Date.now(),L=!1;let qe={type:"agent:output",commandId:T,chunk:X,stream:re};a.send(JSON.stringify(qe))},onDone:be,onError:v}).kill}catch(g){v(g instanceof Error?g.message:String(g))}break}case"do:kill":m&&(m(),m=null);break;case"do:screenshot":ft(a,b.requestId,e.screenShare);break}}),a.on("close",(f,b)=>{d&&clearTimeout(d),S(),e.screenShare?.off("change",q),m&&(m(),m=null,i(!1)),n("disconnected"),f===1e3||f===4001?I():R(new Error(`WS closed: ${f} ${String(b)}`))}),a.on("error",f=>{d&&clearTimeout(d),S(),e.screenShare?.off("change",q),n("disconnected"),R(f)}),a.on("unexpected-response",(f,b)=>{u(new Error(`Unexpected HTTP response: ${b.statusCode}`))})})}async function ft(e,t,r){let o=i=>{try{e.send(JSON.stringify(i))}catch{}},s=i=>o({type:"agent:screenshot_error",requestId:t,error:i}),n=r?.getState()??ie;if(!r||!n.capable){s("This machine cannot share its screen (desktop macOS/Windows only).");return}if(!n.enabled){s("Screen sharing is turned off on this machine.");return}try{let{data:i,mimeType:c}=await r.capture();if(i.length>10485760){let u=(i.length/1048576).toFixed(1);s(`Screenshot is ${u} MB, which exceeds the ${10485760/(1024*1024)} MB limit.`);return}let l=i.toString("base64");for(let u=0;u<l.length;u+=524288)o({type:"agent:screenshot_chunk",requestId:t,chunk:l.slice(u,u+524288)});o({type:"agent:screenshot_done",requestId:t,mimeType:c,totalBytes:i.length})}catch(i){s(`Screenshot failed: ${i.message}`)}}import Rt from"node:events";import Y from"node:fs";import N from"node:path";import St from"node:os";import{randomUUID as ht,randomBytes as Et}from"node:crypto";var Z="/etc/aicommander-agent",Q=N.join(St.homedir(),".config","aicommander-agent"),U="device.json";function ue(){return{deviceId:ht(),deviceSecret:Et(32).toString("base64url")}}function yt(e){return typeof e=="object"&&e!==null&&typeof e.deviceId=="string"&&e.deviceId.length>0&&typeof e.deviceSecret=="string"&&e.deviceSecret.length>0}function le(e){try{let t=Y.readFileSync(e,"utf8"),r=JSON.parse(t);if(yt(r))return{deviceId:r.deviceId,deviceSecret:r.deviceSecret}}catch{}return null}function Pe(e){try{Y.rmSync(N.join(e,U),{force:!0})}catch{}}function k(e,t){try{return Y.mkdirSync(e,{recursive:!0,mode:448}),Y.writeFileSync(N.join(e,U),JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),!0}catch{return!1}}function G(e){if(e){let s=le(N.join(e,U));if(s)return s;let n=ue();return k(e,n),n}let t=le(N.join(Z,U));if(t)return t;let r=le(N.join(Q,U));if(r)return r;let o=ue();return k(Z,o)||k(Q,o),o}function Le(e){let t=ue();return e?(k(e,t),t):k(Z,t)?(Pe(Q),t):(k(Q,t),Pe(Z),t)}function He(e){return{"X-Device-Id":e.deviceId,"X-Device-Secret":e.deviceSecret}}async function de(e,t){let r=await fetch(`${e}/api/device/admins`,{headers:He(t)});if(!r.ok)throw new Error(`Failed to list linked accounts (HTTP ${r.status}).`);return await r.json()}async function $e(e,t,r,o){let s=await fetch(`${e}/api/device/${r}`,{method:"POST",headers:{...He(t),"Content-Type":"application/json"},body:JSON.stringify({userId:o})}),n;try{n=await s.json()}catch{n={ok:!1,error:`http_${s.status}`}}return{...n,ok:s.ok}}function me(e,t,r){return $e(e,t,"block",r)}function ge(e,t,r){return $e(e,t,"unblock",r)}function vt(e){return[...e.filter(t=>!t.blocked),...e.filter(t=>t.blocked)]}function bt(e,t){let r=t.trim();if(!r)return{kind:"not_found"};if(/^\d+$/.test(r)){let n=Number(r)-1;return n>=0&&n<e.length?{kind:"ok",admin:e[n]}:{kind:"not_found"}}let o=e.find(n=>n.userId===r);if(o)return{kind:"ok",admin:o};let s=e.filter(n=>n.userId.startsWith(r));return s.length===1?{kind:"ok",admin:s[0]}:s.length>1?{kind:"ambiguous",matches:s}:{kind:"not_found"}}import C from"node:fs";import M from"node:path";import _t from"node:os";var At="/etc/aicommander-agent",wt=M.join(_t.homedir(),".config","aicommander-agent"),pe="session.json",Be=".rotate";function Tt(e){return typeof e=="object"&&e!==null&&typeof e.sessionCode=="string"&&e.sessionCode.length>0&&typeof e.agentToken=="string"&&e.agentToken.length>0}function xt(e){try{let t=C.readFileSync(e,"utf8"),r=JSON.parse(t);if(Tt(r))return{sessionCode:r.sessionCode,agentToken:r.agentToken}}catch{}return null}function Ct(e,t){try{return C.mkdirSync(e,{recursive:!0,mode:448}),C.writeFileSync(M.join(e,pe),JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),!0}catch{return!1}}function F(e){return e?[e]:[At,wt]}function Ue(e){for(let t of F(e)){let r=xt(M.join(t,pe));if(r)return r}return null}function fe(e,t){for(let r of F(t))if(Ct(r,e))return}function Se(e){for(let t of F(e))try{C.rmSync(M.join(t,pe),{force:!0})}catch{}}function Ge(e){for(let t of F(e))try{C.mkdirSync(t,{recursive:!0,mode:448}),C.writeFileSync(M.join(t,Be),"",{mode:384});return}catch{}}function Fe(e){let t=!1;for(let r of F(e)){let o=M.join(r,Be);try{C.existsSync(o)&&(t=!0,C.rmSync(o,{force:!0}))}catch{}}return t}var he=class extends Rt{serverUrl;configDir;screenShare;abortController=null;_status="disabled";_code=null;_active=!1;_lastHeartbeatAt=0;constructor(t,r){super(),this.serverUrl=t,this.configDir=r?.configDir,this.screenShare=r?.screenShare,this.on("error",()=>{})}get status(){return this._status}get sessionCode(){return this._code}get active(){return this._active}get lastHeartbeatAt(){return this._lastHeartbeatAt}start(){this.abortController||(this._setStatus("connecting"),this.abortController=new AbortController,this._runLoop(this.abortController))}async _runLoop(t){let r=1e3,o=3e4,s=G(this.configDir),n=!1,i=Fe(this.configDir);for(;!t.signal.aborted;){this._setStatus("connecting");try{let c=i?null:Ue(this.configDir),{sessionCode:l,agentToken:u}=await J(this.serverUrl,s,{forceNew:i,...c?{currentCode:c.sessionCode}:{}});if(t.signal.aborted)break;fe({sessionCode:l,agentToken:u},this.configDir),i=!1,this._code=l;try{this.emit("code",l)}catch{}await ce({serverUrl:this.serverUrl,sessionCode:l,agentToken:u,signal:t.signal,silent:!0,...this.screenShare?{screenShare:this.screenShare}:{},onStatus:a=>this._setStatus(a),onActivity:a=>this._setActive(a),onHeartbeat:()=>this._onHeartbeat(),reauthIntervalMs:Me,reauth:async()=>{let a=await J(this.serverUrl,s,{currentCode:l});if(t.signal.aborted||this.abortController!==t)throw new DOMException("Aborted","AbortError");return fe({sessionCode:a.sessionCode,agentToken:a.agentToken},this.configDir),a.agentToken}});break}catch(c){if(t.signal.aborted)break;if(c instanceof O&&c.status===403&&c.code===_e&&!n){n=!0,console.error(`[AIC] Relay rejected this device: ${c.message}. Regenerating device identity and retrying as a new device.`),s=Le(this.configDir),Se(this.configDir),i=!1;continue}c instanceof O&&console.error(`[AIC] ${c.message}`),this._setStatus("disconnected");try{await ae(r,t.signal)}catch{break}r=Math.min(r*2,o)}}this.abortController===t&&(this._setStatus("disabled"),this.abortController=null)}stop(){this.abortController?.abort(),this.abortController=null,this._code=null,this._setStatus("disabled")}async restart(){this.stop(),await Promise.resolve(),this.start()}async changeCode(){Se(this.configDir),Ge(this.configDir),await this.restart()}async listAdmins(){let t=G(this.configDir);return de(this.serverUrl,t)}async blockAdmin(t){let r=G(this.configDir);return me(this.serverUrl,r,t)}async unblockAdmin(t){let r=G(this.configDir);return ge(this.serverUrl,r,t)}_setStatus(t){if(t!=="connected"&&this._active&&this._setActive(!1),this._status!==t){this._status=t;try{this.emit("status",t)}catch{}}}_onHeartbeat(){this._lastHeartbeatAt=Date.now();try{this.emit("heartbeat",this._lastHeartbeatAt)}catch{}}_setActive(t){if(this._active!==t){this._active=t;try{this.emit("activity",t)}catch{}}}};import{spawn as It}from"child_process";import{promises as Ee}from"fs";import Dt from"os";import Ot from"path";import Nt from"crypto";function kt(){return process.platform==="darwin"||process.platform==="win32"}async function Mt(){if(process.platform==="darwin")return Pt();if(process.platform==="win32")return Lt();throw new Error("Screen capture is only supported on the macOS and Windows desktop apps.")}function We(e){return Ot.join(Dt.tmpdir(),`aic-shot-${Nt.randomUUID()}.${e}`)}async function Pt(){let e=We("png");try{return await Xe("screencapture",["-x","-t","png",e]),await je(e,"image/png")}finally{await Ke(e)}}async function Lt(){let e=We("png"),r=["Add-Type -AssemblyName System.Windows.Forms,System.Drawing;","$b = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds;","$bmp = New-Object System.Drawing.Bitmap($b.Width, $b.Height);","$g = [System.Drawing.Graphics]::FromImage($bmp);","$g.CopyFromScreen($b.Location, [System.Drawing.Point]::Empty, $b.Size);",`$bmp.Save('${e.replace(/'/g,"''")}', [System.Drawing.Imaging.ImageFormat]::Png);`,"$g.Dispose(); $bmp.Dispose();"].join(" ");try{return await Xe("powershell",["-NoProfile","-NonInteractive","-Command",r]),await je(e,"image/png")}finally{await Ke(e)}}async function je(e,t){let r=await Ee.stat(e);if(r.size>10485760){let s=(r.size/1048576).toFixed(1);throw new Error(`Screenshot is ${s} MB, which exceeds the ${10485760/(1024*1024)} MB limit.`)}return{data:await Ee.readFile(e),mimeType:t}}async function Ke(e){try{await Ee.unlink(e)}catch{}}function Xe(e,t){return new Promise((r,o)=>{let s=It(e,t,{stdio:["ignore","ignore","pipe"]}),n="";s.stderr?.on("data",i=>{n+=i.toString()}),s.on("error",i=>o(i)),s.on("close",i=>{i===0?r():o(new Error(`${e} exited with code ${i}${n?`: ${n.trim()}`:""}`))})})}import{spawn as jt}from"child_process";import z from"fs";import Je from"path";import $t from"os";function ye(e){if(e)return Je.join(e,"heartbeat");if(process.platform==="linux")try{return z.mkdirSync("/run/aicommander-agent",{recursive:!0}),"/run/aicommander-agent/heartbeat"}catch{}return Je.join($t.tmpdir(),"aicommander-agent-heartbeat")}function Ve(e){try{let t=`${e}.tmp`;z.writeFileSync(t,String(Date.now())),z.renameSync(t,e)}catch{}}var W=null;function Bt(e,t=5e3){Ye(),Ve(e),W=setInterval(()=>Ve(e),t),W.unref?.()}function Ye(){W&&(clearInterval(W),W=null)}function ve(e){try{let t=z.readFileSync(e,"utf8").trim(),r=Number(t);return Number.isFinite(r)?r:null}catch{return null}}async function Kt(e={}){let t=e.heartbeatPath??ye(e.configDir),r=e.spawnWorker??(a=>jt(process.execPath,process.argv.slice(1),{env:a,stdio:"inherit"})),o=null,s=0,n=!1,i=0,c=[],l=null,u=null;await new Promise(a=>{let m=null,d=null,y=()=>{l&&(clearInterval(l),l=null),u&&(clearTimeout(u),u=null),m&&(process.removeListener("SIGINT",m),m=null),d&&(process.removeListener("SIGTERM",d),d=null)},E=()=>{y(),a()},h=()=>{s=Date.now(),i++;let w={...process.env,AIC_ROLE:"worker",AIC_HEARTBEAT:t};o=r(w),o.on("exit",(I,R)=>{if(o=null,n){E();return}if(e.maxSpawns!=null&&i>=e.maxSpawns){E();return}A(`worker exited (code=${I??"null"} signal=${R??"null"})`)}),o.on("error",()=>{})},A=w=>{let I=Date.now();c=c.filter(j=>I-j<3e5),c.push(I);let R=c.length>5?6e4:0;u&&clearTimeout(u),u=setTimeout(()=>{u=null,n||h()},R),u.unref?.()},p=()=>{if(o)try{o.kill("SIGKILL")}catch{}};l=setInterval(()=>{if(n||!o||Date.now()-s<3e4)return;let w=ve(t);w!=null&&Date.now()-w>3e4&&p()},1e4),l.unref?.();let S=w=>{if(n=!0,l&&(clearInterval(l),l=null),u&&(clearTimeout(u),u=null),o)try{o.kill(w)}catch{}else E()};m=()=>S("SIGINT"),d=()=>S("SIGTERM"),process.on("SIGINT",m),process.on("SIGTERM",d),h()})}function Qe(e,t){let r=e.split(".").map(n=>parseInt(n,10)||0),o=t.split(".").map(n=>parseInt(n,10)||0),s=Math.max(r.length,o.length);for(let n=0;n<s;n++){let i=(r[n]??0)-(o[n]??0);if(i!==0)return i>0?1:-1}return 0}function Xt(e,t){return Qe(e,t)>0}async function Jt(e,t=1e4){let r=new AbortController,o=setTimeout(()=>r.abort(),t);try{let s=await fetch(`${e.replace(/\/+$/,"")}/dist/latest`,{signal:r.signal,headers:{Accept:"application/json"}});if(!s.ok)return null;let n=await s.json();return{version:typeof n.version=="string"?n.version:null,mac:typeof n.mac=="string"?n.mac:null,win:typeof n.win=="string"?n.win:null,agentLinuxX64:typeof n.agentLinuxX64=="string"?n.agentLinuxX64:null,agentLinuxArm64:typeof n.agentLinuxArm64=="string"?n.agentLinuxArm64:null}}catch{return null}finally{clearTimeout(o)}}export{H as AGENT_VERSION,he as AgentController,me as blockAdmin,kt as canCaptureScreenshot,Mt as captureScreenshot,Qe as compareVersions,ye as defaultHeartbeatPath,de as fetchAdmins,Jt as fetchLatestDist,Xt as isNewerVersion,vt as orderAdmins,ve as readHeartbeat,J as register,bt as resolveAdminIdentifier,ce as runConnectionLoop,Kt as runSupervisor,Bt as startHeartbeat,Ye as stopHeartbeat,ge as unblockAdmin};
1
+ import ct from"os";var U="1.0.23";var we="device_secret_mismatch";function lt(e){try{let t=JSON.parse(e);return typeof t.code=="string"?t.code:null}catch{return null}}var O=class extends Error{constructor(r,o){super(`Registration failed (${r}): ${o}`);this.status=r;this.body=o;this.name="RegistrationError",this.code=lt(o)}status;body;code};async function J(e,t,r={}){let o={hostname:ct.hostname(),platform:process.platform,arch:process.arch,agentVersion:U,...t?{deviceId:t.deviceId,deviceSecret:t.deviceSecret}:{},...r.forceNew?{forceNew:!0}:r.currentCode?{currentCode:r.currentCode}:{}},s=await fetch(`${e}/api/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){let n=await s.text();throw new O(s.status,n)}return s.json()}import vt from"ws";import At from"os";import{spawn as xe}from"child_process";var w="https://aicommander.dev";var R="aicommander-exec";var Re="ABCDEFGHJKMNPQRSTVWXYZ0123456789";var gr=Math.floor(256/Re.length)*Re.length;var Ce=process.platform==="win32";function Ie(e,t,r,o){let s=Date.now(),n=xe(e,[],{shell:!0,cwd:t??process.env.HOME,env:{...process.env,...r??{}},stdio:["ignore","pipe","pipe"],detached:!Ce}),i=!1,c=null,u=()=>{c&&(clearTimeout(c),c=null)};n.stdout?.on("data",d=>{o.onOutput(d.toString("base64"),"stdout")}),n.stderr?.on("data",d=>{o.onOutput(d.toString("base64"),"stderr")}),n.on("close",d=>{i=!0,u(),o.onDone(d??-1,Date.now()-s)}),n.on("error",d=>{i=!0,u(),o.onError(d.message)});let a=d=>{if(!(i||n.pid==null))try{Ce?xe("taskkill",["/pid",String(n.pid),"/T","/F"],{stdio:"ignore"}):process.kill(-n.pid,d)}catch{}};return{kill:()=>{i||(a("SIGTERM"),u(),c=setTimeout(()=>{c=null,a("SIGKILL")},5e3),c.unref?.())}}}import{spawn as gt}from"node:child_process";import{readFileSync as pt}from"node:fs";import{isAbsolute as ft}from"node:path";import{createRequire as ut}from"node:module";var dt=ut(import.meta.url),De="__secure-exec-drop";function mt(){let e=!1;try{e=dt("node:sea").isSea()}catch{}return e}function Oe(e){let t=process.argv[1],r=!mt()&&t?[t,De,...e]:[De,...e];return{cmd:process.execPath,args:r}}function ht(){let e;try{e=pt("/etc/passwd","utf8")}catch{throw new Error("cannot read /etc/passwd to resolve the secure-exec user")}let t=e.split(`
2
+ `).filter(u=>u.startsWith(`${R}:`));if(t.length===0)throw new Error(`secure exec user "${R}" not found in /etc/passwd \u2014 reinstall the agent to create it`);if(t.length>1)throw new Error(`multiple /etc/passwd entries for "${R}" \u2014 refusing to guess which is the sandbox user`);let r=t[0].split(":");if(r.length!==7)throw new Error(`malformed passwd entry for ${R}`);let o=r[2],s=r[3];if(!/^\d+$/.test(o)||!/^\d+$/.test(s))throw new Error(`could not resolve uid/gid for ${R}`);let n=Number(o),i=Number(s),c=r[5]||"/tmp";if(!Number.isInteger(n)||!Number.isInteger(i))throw new Error(`could not resolve uid/gid for ${R}`);if(n===0)throw new Error("refusing to run secure exec as uid 0");if(i===0)throw new Error("refusing to run secure exec as gid 0");return{uid:n,gid:i,home:c,name:R}}var St="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",Et=new Set(["NODE_OPTIONS","BASH_ENV","ENV","IFS","PYTHONSTARTUP","PYTHONPATH","PERL5OPT","RUBYOPT","GIT_EXTERNAL_DIFF","PATH","HOME","USER","LOGNAME"]),yt=e=>/^LD_/.test(e)||Et.has(e);function Me(e,t){if(process.platform!=="linux")throw new Error("secure exec is only supported on Linux");if(typeof process.getuid=="function"&&process.getuid()!==0)throw new Error("secure exec requires the agent to run as root (to drop privilege)");let r=e.argv;if(!Array.isArray(r)||r.length===0||typeof r[0]!="string")throw new Error("secure exec requires a non-empty argv");let o=r[0];if(o.includes("/"))throw new Error(`command "${o}" must be a bare command name (no path separators)`);if(!e.allowedCommands.includes(o))throw new Error(`command "${o}" is not in this token's allowlist`);if(e.cwd!=null&&!ft(e.cwd))throw new Error(`cwd "${e.cwd}" must be an absolute path`);let s=null;if(e.input!=null&&(s=Buffer.from(e.input,"base64"),s.length>262144))throw new Error(`stdin payload ${s.length}B exceeds limit ${262144}B`);let n=ht(),i={HOME:n.home,USER:n.name,LOGNAME:n.name,PATH:St},c={};for(let[g,C]of Object.entries(e.env??{}))yt(g)||(c[g]=C);let u={...c,...i},a=Date.now(),{cmd:d,args:m}=Oe([String(n.uid),String(n.gid),n.name,o,...r.slice(1)]),l=gt(d,m,{cwd:e.cwd??n.home,env:u,stdio:["pipe","pipe","pipe"],detached:!0,shell:!1});s&&l.stdin?(l.stdin.on("error",()=>{}),l.stdin.end(s)):l.stdin?.end();let E=!1,S=null,b=()=>{S&&(clearTimeout(S),S=null)};l.stdout?.on("data",g=>{t.onOutput(g.toString("base64"),"stdout")}),l.stderr?.on("data",g=>{t.onOutput(g.toString("base64"),"stderr")}),l.on("close",g=>{E=!0,b(),t.onDone(g??-1,Date.now()-a)}),l.on("error",g=>{E=!0,b(),t.onError(g.message)});let _=g=>{if(!(E||l.pid==null))try{process.kill(-l.pid,g)}catch{}};return{kill:()=>{E||(_("SIGTERM"),b(),S=setTimeout(()=>{S=null,_("SIGKILL")},5e3),S.unref?.())}}}import B from"chalk";function ke(e,t){console.log(B.yellow(` Reconnecting in ${Math.round(t/1e3)}s (attempt ${e})...`))}function Pe(){console.log(B.green(" Connected to relay \u2014 ready for commands."))}function ie(e){console.log(B.cyan(` > ${e}`))}function ae(e,t){let r=e===0?B.green:B.red;console.log(r(` Done. Exit ${e} in ${t}ms`))}function _t(){let e=process.env.AICOMMANDER_DEV;return e==="1"||e==="true"}function He(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function Le(){return new URL(w).origin}function $e(e){let t=(e??"").trim();if(!t)return w;let r;try{r=new URL(t)}catch{return console.warn(`
3
+ \u26A0 Ignoring malformed AICOMMANDER_SERVER (${t}); using ${w}.
4
+ `),w}if(r.origin===Le())return w;let o=He(r.hostname);return!_t()&&!o?(console.warn(`
5
+ \u26A0 AICOMMANDER_SERVER override to "${r.origin}" ignored for safety \u2014
6
+ the agent runs as root and is host-locked to ${Le()}.
7
+ Set AICOMMANDER_DEV=1 to allow a custom relay for development.
8
+ `),w):r.protocol!=="https:"&&!o?(console.warn(`
9
+ \u26A0 Refusing plaintext relay "${r.origin}" (https required); using ${w}.
10
+ `),w):t.replace(/\/+$/,"")}function Ue(e){let t;try{t=new URL(e)}catch{throw new Error("Refusing to connect: malformed relay WebSocket URL.")}if(t.protocol!=="wss:"&&!(t.protocol==="ws:"&&He(t.hostname)))throw new Error(`Refusing to open a plaintext relay socket (${t.protocol}//${t.host}); wss:// required.`)}var ce={capable:!1,enabled:!1,expiresAt:null},Fe=360*60*1e3;function le(e,t){return new Promise((r,o)=>{if(t.aborted){o(new DOMException("Aborted","AbortError"));return}let s=setTimeout(r,e);t.addEventListener("abort",()=>{clearTimeout(s),o(new DOMException("Aborted","AbortError"))},{once:!0})})}async function ue(e){let t=1e3,r=3e4,o=0,s=e.agentToken;for(;!e.signal?.aborted;){o++;try{let n=await bt(e,s);if(t=1e3,o=0,n&&e.reauth&&!e.signal?.aborted)try{s=await e.reauth()}catch{}}catch(n){if(n.name==="AbortError")break;let i=.8+Math.random()*.4,c=Math.min(t*i,r);e.silent||ke(o,c);try{await le(c,e.signal??new AbortController().signal)}catch(u){if(u.name==="AbortError")break}t=Math.min(t*2,r)}}}async function bt(e,t){let{serverUrl:r,sessionCode:o}=e,s=`${r.replace(/^http/,"ws")}/ws/agent/${o}?token=${t}`;Ue(s);let n=a=>{try{e.onStatus?.(a)}catch{}},i=a=>{try{e.onActivity?.(a)}catch{}},c=a=>{if(a)try{e.onRemoteActivity?.(a)}catch{}},u=()=>{try{e.onHeartbeat?.()}catch{}};return n("connecting"),new Promise((a,d)=>{let m=new vt(s),l=null,E=null,S=null,b=!1,_=null,g=!1,C=()=>{S&&(clearTimeout(S),S=null)},f=()=>{_&&(clearInterval(_),_=null)},I=()=>{if(!e.reauthIntervalMs||!e.reauth)return;let h=()=>{if(l){S=setTimeout(h,3e4);return}b=!0,m.close(1e3,"reauth")};S=setTimeout(h,e.reauthIntervalMs)},P=()=>{g||(g=!0,C(),f(),a(b))},L=h=>{g||(g=!0,C(),f(),d(h))},be=()=>{u(),E&&clearTimeout(E),E=setTimeout(()=>{m.terminate(),L(new Error("Ping timeout"))},9e4)};e.signal?.addEventListener("abort",()=>m.close(1e3,"disabled"),{once:!0});let te=()=>{if(g)return;let h={type:"agent:screen_state",screenShare:e.screenShare?.getState()??ce};try{m.send(JSON.stringify(h))}catch{}};m.on("open",()=>{n("connected"),be(),I();let h={type:"agent:register",hostname:At.hostname(),platform:process.platform,arch:process.arch,agentVersion:U,screenShare:e.screenShare?.getState()??ce};m.send(JSON.stringify(h)),e.screenShare?.on("change",te),e.silent||Pe()}),m.on("message",h=>{let y;try{y=JSON.parse(String(h))}catch{return}switch(y.type){case"do:ping":be();let it={type:"agent:pong",ts:y.ts};m.send(JSON.stringify(it));break;case"do:exec":{ie(y.command),i(!0),c(y.operator);let{commandId:T,command:D,cwd:re,env:ne}=y,X=Date.now(),H=!1;f(),_=setInterval(()=>{let v=Date.now()-X;if(v>=3e5&&!H){H=!0;let p={type:"agent:exec_idle",commandId:T,idleMs:v};m.send(JSON.stringify(p))}},3e5),_.unref?.(),l=Ie(D,re,ne,{onOutput:(v,p)=>{X=Date.now(),H=!1;let A={type:"agent:output",commandId:T,chunk:v,stream:p};m.send(JSON.stringify(A))},onDone:(v,p)=>{l=null,f(),i(!1),ae(v,p);let A={type:"agent:done",commandId:T,exitCode:v,durationMs:p};m.send(JSON.stringify(A))},onError:v=>{l=null,f(),i(!1);let p={type:"agent:error",commandId:T,error:v};m.send(JSON.stringify(p))}}).kill;break}case"do:secure_exec":{let{commandId:T,argv:D,allowedCommands:re,input:ne,cwd:X,env:H}=y,Te=(p,A)=>{l=null,f(),i(!1),ae(p,A);let $={type:"agent:done",commandId:T,exitCode:p,durationMs:A};m.send(JSON.stringify($))},v=p=>{l=null,f(),i(!1);let A={type:"agent:error",commandId:T,error:p};m.send(JSON.stringify(A))};try{let p=Array.isArray(D)?D.join(" "):String(D);ie(p),i(!0);let A=Date.now(),$=!1;f(),_=setInterval(()=>{let K=Date.now()-A;if(K>=3e5&&!$){$=!0;let oe={type:"agent:exec_idle",commandId:T,idleMs:K};m.send(JSON.stringify(oe))}},3e5),_.unref?.(),l=Me({argv:D,allowedCommands:re,input:ne,cwd:X,env:H},{onOutput:(K,oe)=>{A=Date.now(),$=!1;let at={type:"agent:output",commandId:T,chunk:K,stream:oe};m.send(JSON.stringify(at))},onDone:Te,onError:v}).kill}catch(p){v(p instanceof Error?p.message:String(p))}break}case"do:kill":l&&(l(),l=null);break;case"do:screenshot":c(y.operator),Tt(m,y.requestId,e.screenShare);break}}),m.on("close",(h,y)=>{E&&clearTimeout(E),f(),e.screenShare?.off("change",te),l&&(l(),l=null,i(!1)),n("disconnected"),h===1e3||h===4001?P():L(new Error(`WS closed: ${h} ${String(y)}`))}),m.on("error",h=>{E&&clearTimeout(E),f(),e.screenShare?.off("change",te),n("disconnected"),L(h)}),m.on("unexpected-response",(h,y)=>{d(new Error(`Unexpected HTTP response: ${y.statusCode}`))})})}async function Tt(e,t,r){let o=i=>{try{e.send(JSON.stringify(i))}catch{}},s=i=>o({type:"agent:screenshot_error",requestId:t,error:i}),n=r?.getState()??ce;if(!r||!n.capable){s("This machine cannot share its screen (desktop macOS/Windows only).");return}if(!n.enabled){s("Screen sharing is turned off on this machine.");return}try{let{data:i,mimeType:c}=await r.capture();if(i.length>10485760){let a=(i.length/1048576).toFixed(1);s(`Screenshot is ${a} MB, which exceeds the ${10485760/(1024*1024)} MB limit.`);return}let u=i.toString("base64");for(let a=0;a<u.length;a+=524288)o({type:"agent:screenshot_chunk",requestId:t,chunk:u.slice(a,a+524288)});o({type:"agent:screenshot_done",requestId:t,mimeType:c,totalBytes:i.length})}catch(i){s(`Screenshot failed: ${i.message}`)}}import Ft from"node:events";import Z from"node:fs";import N from"node:path";import wt from"node:os";import{randomUUID as Rt,randomBytes as xt}from"node:crypto";var Q="/etc/aicommander-agent",q=N.join(wt.homedir(),".config","aicommander-agent"),G="device.json";function me(){return{deviceId:Rt(),deviceSecret:xt(32).toString("base64url")}}function Ct(e){return typeof e=="object"&&e!==null&&typeof e.deviceId=="string"&&e.deviceId.length>0&&typeof e.deviceSecret=="string"&&e.deviceSecret.length>0}function de(e){try{let t=Z.readFileSync(e,"utf8"),r=JSON.parse(t);if(Ct(r))return{deviceId:r.deviceId,deviceSecret:r.deviceSecret}}catch{}return null}function Ge(e){try{Z.rmSync(N.join(e,G),{force:!0})}catch{}}function M(e,t){try{return Z.mkdirSync(e,{recursive:!0,mode:448}),Z.writeFileSync(N.join(e,G),JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),!0}catch{return!1}}function W(e){if(e){let s=de(N.join(e,G));if(s)return s;let n=me();return M(e,n),n}let t=de(N.join(Q,G));if(t)return t;let r=de(N.join(q,G));if(r)return r;let o=me();return M(Q,o)||M(q,o),o}function We(e){let t=me();return e?(M(e,t),t):M(Q,t)?(Ge(q),t):(M(q,t),Ge(Q),t)}function Ve(e){return{"X-Device-Id":e.deviceId,"X-Device-Secret":e.deviceSecret}}var je=1e4;async function ge(e,t){let r;try{r=await fetch(`${e}/api/device/admins`,{headers:Ve(t),signal:AbortSignal.timeout(je)})}catch{throw new Error("Failed to list linked accounts (relay unreachable or timed out).")}if(!r.ok)throw new Error(`Failed to list linked accounts (HTTP ${r.status}).`);return await r.json()}async function Xe(e,t,r,o){let s;try{s=await fetch(`${e}/api/device/${r}`,{method:"POST",headers:{...Ve(t),"Content-Type":"application/json"},body:JSON.stringify({userId:o}),signal:AbortSignal.timeout(je)})}catch{return{ok:!1,error:"unreachable"}}let n;try{n=await s.json()}catch{n={ok:!1,error:`http_${s.status}`}}return{...n,ok:s.ok}}function pe(e,t,r){return Xe(e,t,"block",r)}function fe(e,t,r){return Xe(e,t,"unblock",r)}function It(e){return[...e.filter(t=>!t.blocked),...e.filter(t=>t.blocked)]}function Dt(e,t){let r=t.trim();if(!r)return{kind:"not_found"};if(/^\d+$/.test(r)){let n=Number(r)-1;return n>=0&&n<e.length?{kind:"ok",admin:e[n]}:{kind:"not_found"}}let o=e.find(n=>n.userId===r);if(o)return{kind:"ok",admin:o};let s=e.filter(n=>n.userId.startsWith(r));return s.length===1?{kind:"ok",admin:s[0]}:s.length>1?{kind:"ambiguous",matches:s}:{kind:"not_found"}}import x from"node:fs";import k from"node:path";import Ot from"node:os";var Nt="/etc/aicommander-agent",Mt=k.join(Ot.homedir(),".config","aicommander-agent"),he="session.json",Ke=".rotate";function kt(e){return typeof e=="object"&&e!==null&&typeof e.sessionCode=="string"&&e.sessionCode.length>0&&typeof e.agentToken=="string"&&e.agentToken.length>0}function Pt(e){try{let t=x.readFileSync(e,"utf8"),r=JSON.parse(t);if(kt(r))return{sessionCode:r.sessionCode,agentToken:r.agentToken}}catch{}return null}function Lt(e,t){try{return x.mkdirSync(e,{recursive:!0,mode:448}),x.writeFileSync(k.join(e,he),JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),!0}catch{return!1}}function V(e){return e?[e]:[Nt,Mt]}function Je(e){for(let t of V(e)){let r=Pt(k.join(t,he));if(r)return r}return null}function Se(e,t){for(let r of V(t))if(Lt(r,e))return}function Ee(e){for(let t of V(e))try{x.rmSync(k.join(t,he),{force:!0})}catch{}}function Ye(e){for(let t of V(e))try{x.mkdirSync(t,{recursive:!0,mode:448}),x.writeFileSync(k.join(t,Ke),"",{mode:384});return}catch{}}function Ze(e){let t=!1;for(let r of V(e)){let o=k.join(r,Ke);try{x.existsSync(o)&&(t=!0,x.rmSync(o,{force:!0}))}catch{}}return t}function Bt(e,t){if(!e)return!0;let r=t-e.lastNotifiedAt;if(r>=288e5)return!0;let o=t-e.lastActivityAt>6e5,s=r>=36e5;return o&&s}var z=class{seen=new Map;note(t,r){let o=this.seen.get(t),s=Bt(o,r);return this.seen.set(t,{lastActivityAt:r,lastNotifiedAt:s?r:o?.lastNotifiedAt??0}),s}};var ye=class extends Ft{serverUrl;configDir;screenShare;abortController=null;_status="disabled";_code=null;_active=!1;_lastHeartbeatAt=0;_remote=new z;constructor(t,r){super(),this.serverUrl=$e(t),this.configDir=r?.configDir,this.screenShare=r?.screenShare,this.on("error",()=>{})}get status(){return this._status}get sessionCode(){return this._code}get active(){return this._active}get lastHeartbeatAt(){return this._lastHeartbeatAt}start(){this.abortController||(this._setStatus("connecting"),this.abortController=new AbortController,this._runLoop(this.abortController))}async _runLoop(t){let r=1e3,o=3e4,s=W(this.configDir),n=!1,i=Ze(this.configDir);for(;!t.signal.aborted;){this._setStatus("connecting");try{let c=i?null:Je(this.configDir),{sessionCode:u,agentToken:a}=await J(this.serverUrl,s,{forceNew:i,...c?{currentCode:c.sessionCode}:{}});if(t.signal.aborted)break;Se({sessionCode:u,agentToken:a},this.configDir),i=!1,this._code=u;try{this.emit("code",u)}catch{}await ue({serverUrl:this.serverUrl,sessionCode:u,agentToken:a,signal:t.signal,silent:!0,...this.screenShare?{screenShare:this.screenShare}:{},onStatus:d=>this._setStatus(d),onActivity:d=>this._setActive(d),onRemoteActivity:d=>this._noteRemote(d),onHeartbeat:()=>this._onHeartbeat(),reauthIntervalMs:Fe,reauth:async()=>{let d=await J(this.serverUrl,s,{currentCode:u});if(t.signal.aborted||this.abortController!==t)throw new DOMException("Aborted","AbortError");return Se({sessionCode:d.sessionCode,agentToken:d.agentToken},this.configDir),d.agentToken}});break}catch(c){if(t.signal.aborted)break;if(c instanceof O&&c.status===403&&c.code===we&&!n){n=!0,console.error(`[AIC] Relay rejected this device: ${c.message}. Regenerating device identity and retrying as a new device.`),s=We(this.configDir),Ee(this.configDir),i=!1;continue}c instanceof O&&console.error(`[AIC] ${c.message}`),this._setStatus("disconnected");try{await le(r,t.signal)}catch{break}r=Math.min(r*2,o)}}this.abortController===t&&(this._setStatus("disabled"),this.abortController=null)}stop(){this.abortController?.abort(),this.abortController=null,this._code=null,this._setStatus("disabled")}async restart(){this.stop(),await Promise.resolve(),this.start()}async changeCode(){Ee(this.configDir),Ye(this.configDir),await this.restart()}async listAdmins(){let t=W(this.configDir);return ge(this.serverUrl,t)}async blockAdmin(t){let r=W(this.configDir);return pe(this.serverUrl,r,t)}async unblockAdmin(t){let r=W(this.configDir);return fe(this.serverUrl,r,t)}_setStatus(t){if(t!=="connected"&&this._active&&this._setActive(!1),this._status!==t){this._status=t;try{this.emit("status",t)}catch{}}}_noteRemote(t){let r=Date.now();if(this._remote.note(t.id,r))try{this.emit("remote-connect",{id:t.id,anonymous:t.anonymous})}catch{}}_onHeartbeat(){this._lastHeartbeatAt=Date.now();try{this.emit("heartbeat",this._lastHeartbeatAt)}catch{}}_setActive(t){if(this._active!==t){this._active=t;try{this.emit("activity",t)}catch{}}}};import{spawn as Gt}from"child_process";import{promises as _e}from"fs";import Wt from"os";import Vt from"path";import jt from"crypto";function Xt(){return process.platform==="darwin"||process.platform==="win32"}async function Kt(){if(process.platform==="darwin")return Jt();if(process.platform==="win32")return Yt();throw new Error("Screen capture is only supported on the macOS and Windows desktop apps.")}function Qe(e){return Vt.join(Wt.tmpdir(),`aic-shot-${jt.randomUUID()}.${e}`)}async function Jt(){let e=Qe("png");try{return await et("screencapture",["-x","-t","png",e]),await qe(e,"image/png")}finally{await ze(e)}}async function Yt(){let e=Qe("png"),r=["Add-Type -AssemblyName System.Windows.Forms,System.Drawing;","$b = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds;","$bmp = New-Object System.Drawing.Bitmap($b.Width, $b.Height);","$g = [System.Drawing.Graphics]::FromImage($bmp);","$g.CopyFromScreen($b.Location, [System.Drawing.Point]::Empty, $b.Size);",`$bmp.Save('${e.replace(/'/g,"''")}', [System.Drawing.Imaging.ImageFormat]::Png);`,"$g.Dispose(); $bmp.Dispose();"].join(" ");try{return await et("powershell",["-NoProfile","-NonInteractive","-Command",r]),await qe(e,"image/png")}finally{await ze(e)}}async function qe(e,t){let r=await _e.stat(e);if(r.size>10485760){let s=(r.size/1048576).toFixed(1);throw new Error(`Screenshot is ${s} MB, which exceeds the ${10485760/(1024*1024)} MB limit.`)}return{data:await _e.readFile(e),mimeType:t}}async function ze(e){try{await _e.unlink(e)}catch{}}function et(e,t){return new Promise((r,o)=>{let s=Gt(e,t,{stdio:["ignore","ignore","pipe"]}),n="";s.stderr?.on("data",i=>{n+=i.toString()}),s.on("error",i=>o(i)),s.on("close",i=>{i===0?r():o(new Error(`${e} exited with code ${i}${n?`: ${n.trim()}`:""}`))})})}import{spawn as nr}from"child_process";import ee from"fs";import tt from"path";import Qt from"os";function ve(e){if(e)return tt.join(e,"heartbeat");if(process.platform==="linux")try{return ee.mkdirSync("/run/aicommander-agent",{recursive:!0}),"/run/aicommander-agent/heartbeat"}catch{}return tt.join(Qt.tmpdir(),"aicommander-agent-heartbeat")}function rt(e){try{let t=`${e}.tmp`;ee.writeFileSync(t,String(Date.now())),ee.renameSync(t,e)}catch{}}var j=null;function qt(e,t=5e3){nt(),rt(e),j=setInterval(()=>rt(e),t),j.unref?.()}function nt(){j&&(clearInterval(j),j=null)}function Ae(e){try{let t=ee.readFileSync(e,"utf8").trim(),r=Number(t);return Number.isFinite(r)?r:null}catch{return null}}async function or(e={}){let t=e.heartbeatPath??ve(e.configDir),r=e.spawnWorker??(d=>nr(process.execPath,process.argv.slice(1),{env:d,stdio:"inherit"})),o=null,s=0,n=!1,i=0,c=[],u=null,a=null;await new Promise(d=>{let m=null,l=null,E=()=>{u&&(clearInterval(u),u=null),a&&(clearTimeout(a),a=null),m&&(process.removeListener("SIGINT",m),m=null),l&&(process.removeListener("SIGTERM",l),l=null)},S=()=>{E(),d()},b=()=>{s=Date.now(),i++;let f={...process.env,AIC_ROLE:"worker",AIC_HEARTBEAT:t};o=r(f),o.on("exit",(I,P)=>{if(o=null,n){S();return}if(e.maxSpawns!=null&&i>=e.maxSpawns){S();return}_(`worker exited (code=${I??"null"} signal=${P??"null"})`)}),o.on("error",()=>{})},_=f=>{let I=Date.now();c=c.filter(L=>I-L<3e5),c.push(I);let P=c.length>5?6e4:0;a&&clearTimeout(a),a=setTimeout(()=>{a=null,n||b()},P),a.unref?.()},g=()=>{if(o)try{o.kill("SIGKILL")}catch{}};u=setInterval(()=>{if(n||!o||Date.now()-s<3e4)return;let f=Ae(t);f!=null&&Date.now()-f>3e4&&g()},1e4),u.unref?.();let C=f=>{if(n=!0,u&&(clearInterval(u),u=null),a&&(clearTimeout(a),a=null),o)try{o.kill(f)}catch{}else S()};m=()=>C("SIGINT"),l=()=>C("SIGTERM"),process.on("SIGINT",m),process.on("SIGTERM",l),b()})}function st(e,t){let r=e.split(".").map(n=>parseInt(n,10)||0),o=t.split(".").map(n=>parseInt(n,10)||0),s=Math.max(r.length,o.length);for(let n=0;n<s;n++){let i=(r[n]??0)-(o[n]??0);if(i!==0)return i>0?1:-1}return 0}function sr(e,t){return st(e,t)>0}async function ir(e,t=1e4){let r=new AbortController,o=setTimeout(()=>r.abort(),t);try{let s=await fetch(`${e.replace(/\/+$/,"")}/dist/latest`,{signal:r.signal,headers:{Accept:"application/json"}});if(!s.ok)return null;let n=await s.json();return{version:typeof n.version=="string"?n.version:null,mac:typeof n.mac=="string"?n.mac:null,win:typeof n.win=="string"?n.win:null,agentLinuxX64:typeof n.agentLinuxX64=="string"?n.agentLinuxX64:null,agentLinuxArm64:typeof n.agentLinuxArm64=="string"?n.agentLinuxArm64:null}}catch{return null}finally{clearTimeout(o)}}export{U as AGENT_VERSION,ye as AgentController,pe as blockAdmin,Xt as canCaptureScreenshot,Kt as captureScreenshot,st as compareVersions,ve as defaultHeartbeatPath,ge as fetchAdmins,ir as fetchLatestDist,sr as isNewerVersion,It as orderAdmins,Ae as readHeartbeat,J as register,Dt as resolveAdminIdentifier,ue as runConnectionLoop,or as runSupervisor,qt as startHeartbeat,nt as stopHeartbeat,fe as unblockAdmin};
@@ -3,6 +3,16 @@ import type { AdminsResult, BlockResult } from "./device-admin.js";
3
3
  import type { ScreenShareState } from "@aicommander/protocol";
4
4
  import type { CapturedScreenshot } from "./screenshot.js";
5
5
  export type AgentStatus = "connecting" | "connected" | "disconnected" | "disabled";
6
+ /**
7
+ * Emitted as the controller's "remote-connect" event when a remote operator's
8
+ * command clears the rate limit (see RemoteNotifier). The desktop app turns this
9
+ * into the "someone connected" notice; the headless agent simply has no listener.
10
+ */
11
+ export interface RemoteConnectInfo {
12
+ /** Stable operator key: an account userId, or "anon" for session-code callers. */
13
+ id: string;
14
+ anonymous: boolean;
15
+ }
6
16
  /**
7
17
  * Supplies the connection layer with the desktop screen-share grant state and a
8
18
  * way to capture the screen. Only the desktop app provides one; the headless
@@ -40,6 +50,7 @@ export declare class AgentController extends EventEmitter {
40
50
  private _code;
41
51
  private _active;
42
52
  private _lastHeartbeatAt;
53
+ private readonly _remote;
43
54
  constructor(serverUrl: string, opts?: AgentControllerOptions);
44
55
  get status(): AgentStatus;
45
56
  get sessionCode(): string | null;
@@ -68,6 +79,12 @@ export declare class AgentController extends EventEmitter {
68
79
  /** Unblock one account by userId — restores its access immediately. */
69
80
  unblockAdmin(userId: string): Promise<BlockResult>;
70
81
  private _setStatus;
82
+ /**
83
+ * Funnel an operator-initiated command through the connect-notice rate limiter;
84
+ * emit "remote-connect" only when a fresh notice is due. Never throws into the
85
+ * ws event handler that calls it.
86
+ */
87
+ private _noteRemote;
71
88
  private _onHeartbeat;
72
89
  private _setActive;
73
90
  }
@@ -1,4 +1,5 @@
1
1
  import type { ScreenShareProvider } from "./agent-controller.js";
2
+ import type { RemoteOperator } from "@aicommander/protocol";
2
3
  interface ConnectionOpts {
3
4
  serverUrl: string;
4
5
  sessionCode: string;
@@ -8,6 +9,12 @@ interface ConnectionOpts {
8
9
  screenShare?: ScreenShareProvider;
9
10
  onStatus?: (s: 'connecting' | 'connected' | 'disconnected') => void;
10
11
  onActivity?: (active: boolean) => void;
12
+ /**
13
+ * Fired with the driving operator on each operator-initiated command (exec /
14
+ * screenshot) that carries an identity. The controller rate-limits these into a
15
+ * desktop "someone connected" notice; absent on the headless agent.
16
+ */
17
+ onRemoteActivity?: (operator: RemoteOperator) => void;
11
18
  /**
12
19
  * Fired whenever the link proves alive (on open and on every server ping).
13
20
  * Lets a supervisor watch link liveness independently of command workload —
@@ -3,6 +3,11 @@ export interface AdminEntry {
3
3
  userId: string;
4
4
  /** Already masked by the server — a full address never leaves the relay. */
5
5
  maskedEmail: string;
6
+ /**
7
+ * The linked machine's hostname (e.g. "aic-studio"), NOT a label for the person.
8
+ * Show it as secondary machine info only — use {@link maskedEmail} to identify
9
+ * the account/operator.
10
+ */
6
11
  alias: string;
7
12
  linkedAt: string;
8
13
  lastSeenAt: string | null;
@@ -22,11 +27,18 @@ export interface BlockResult {
22
27
  error?: string;
23
28
  message?: string;
24
29
  }
25
- /** List the accounts linked to this device (masked emails). Throws on transport/auth failure. */
30
+ /** List the accounts linked to this device (masked emails). Throws on transport/auth/timeout failure. */
26
31
  export declare function fetchAdmins(serverUrl: string, device: DeviceIdentity): Promise<AdminsResult>;
27
- /** Block one account by userId. Returns a structured result (never throws on a 4xx). */
32
+ /**
33
+ * Block one account by userId. Never throws: returns a structured {@link BlockResult}
34
+ * for ANY outcome, including a 4xx, a transport failure, or a request timeout.
35
+ */
28
36
  export declare function blockAdmin(serverUrl: string, device: DeviceIdentity, userId: string): Promise<BlockResult>;
29
- /** Unblock one account by userId, restoring its access. */
37
+ /**
38
+ * Unblock one account by userId, restoring its access. Never throws: returns a
39
+ * structured {@link BlockResult} for ANY outcome, including a 4xx, a transport
40
+ * failure, or a request timeout.
41
+ */
30
42
  export declare function unblockAdmin(serverUrl: string, device: DeviceIdentity, userId: string): Promise<BlockResult>;
31
43
  /**
32
44
  * Stable display/resolution order: active accounts first, blocked ones last,
@@ -1,15 +1,19 @@
1
1
  /**
2
2
  * Render the session code on screen for the running agent.
3
3
  *
4
- * `reveal` controls whether the FULL code or only the masked form is shown:
4
+ * `reveal` controls whether the FULL code or only the masked form is shown.
5
+ * Callers MUST gate it on a real interactive terminal (`process.stdout.isTTY`):
5
6
  * - FOREGROUND interactive runs (`npx`, `aicommander-agent run` in a terminal)
6
- * pass reveal=true. The user launched it in their own terminal to obtain the
7
- * code there there is no journald/screenshare persistence concern of the
8
- * systemd service path, and no `status --reveal` to query (no service,
9
- * no writable /var/run state). Showing the masked form would make the
7
+ * have a TTY and pass reveal=true. The user launched it in their own terminal
8
+ * to obtain the code there, so showing the masked form would make the
10
9
  * foreground flow unusable.
11
- * - The masked form (reveal=false) is kept for any long-lived service/log
12
- * context where the output could leak via journald/screenshare.
10
+ * - The masked form (reveal=false) is used in every non-TTY context. Crucially
11
+ * this includes the systemd SERVICE path: `run` is supervised there and its
12
+ * stdout is inherited into journald (StandardOutput=journal), so revealing
13
+ * would persist the root-exec credential in the journal (readable by root and
14
+ * by systemd-journal/adm-group users) and leak it into exported logs /
15
+ * screen-shares — exactly what masking exists to prevent. `status --reveal`
16
+ * (root-gated) remains the way to query the full code on a service host.
13
17
  *
14
18
  * The "keep secret" warning is shown in BOTH modes.
15
19
  */
@@ -1,7 +1,7 @@
1
1
  export { register } from "./register.js";
2
2
  export { runConnectionLoop } from "./connection.js";
3
3
  export { AgentController } from "./agent-controller.js";
4
- export type { AgentStatus, ScreenShareProvider } from "./agent-controller.js";
4
+ export type { AgentStatus, ScreenShareProvider, RemoteConnectInfo } from "./agent-controller.js";
5
5
  export { fetchAdmins, blockAdmin, unblockAdmin, orderAdmins, resolveAdminIdentifier } from "./device-admin.js";
6
6
  export type { AdminEntry, AdminsResult, BlockResult } from "./device-admin.js";
7
7
  export { captureScreenshot, canCaptureScreenshot } from "./screenshot.js";
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Resolve the effective, TRUSTED relay base URL from a raw candidate (typically
3
+ * `process.env.AICOMMANDER_SERVER`). Returns a URL string safe to register and
4
+ * open a root-exec socket against. Never throws — an unparseable or untrusted
5
+ * value falls back to DEFAULT_SERVER (with a loud warning) rather than crashing.
6
+ */
7
+ export declare function resolveTrustedServerUrl(raw?: string | null): string;
8
+ /**
9
+ * Assert the about-to-open agent WebSocket URL is encrypted (wss://) or an explicit
10
+ * loopback dev target (ws://localhost). Belt-and-suspenders on top of
11
+ * resolveTrustedServerUrl, evaluated at the actual connection point. Throws on a
12
+ * plaintext non-loopback URL so a root agent never opens an unauthenticated link.
13
+ */
14
+ export declare function assertSecureWsUrl(wsUrl: string): void;
@@ -0,0 +1,43 @@
1
+ /** Per-operator bookkeeping for the connect notice (see shouldNotify). */
2
+ export interface OperatorState {
3
+ /** Epoch-ms of this operator's most recent command (notified or not). */
4
+ lastActivityAt: number;
5
+ /** Epoch-ms the last notice for this operator fired, or 0 if never. */
6
+ lastNotifiedAt: number;
7
+ }
8
+ /**
9
+ * Decide whether an operator's command at `now` should raise a fresh "someone
10
+ * connected" notice, given their prior state (undefined = first contact ever):
11
+ *
12
+ * - first contact always notifies (`pierwsza notyfikacja powinna pójść`);
13
+ * - a NEW session notifies when BOTH hold:
14
+ * • the operator has been idle longer than REMOTE_ACTIVITY_GAP_MS — so a
15
+ * continuous working session (back-to-back commands) is one "connection",
16
+ * notified once at its start and never mid-stream; and
17
+ * • their last notice was at least REMOTE_NOTIFY_MIN_INTERVAL_MS ago — a hard
18
+ * one-per-hour-per-operator floor between session notices;
19
+ * - additionally, a continuous-session CEILING fires regardless of the idle gap
20
+ * once REMOTE_NOTIFY_MAX_INTERVAL_MS has passed since the last notice, so an
21
+ * operator working non-stop all day is still re-announced periodically (≤ once
22
+ * per that interval) instead of only the very first time.
23
+ *
24
+ * Pure: the caller supplies `now` and the prior state, so it is trivially testable.
25
+ */
26
+ export declare function shouldNotify(prev: OperatorState | undefined, now: number): boolean;
27
+ /**
28
+ * Tracks remote operators and applies the connect-notice rate limit. Holds the
29
+ * per-operator state in memory (reset on agent restart — a fresh start re-notifies,
30
+ * which is the safe direction). `note()` is the single entry point: record an
31
+ * operator's activity and learn whether to surface a notice. Time is injected so
32
+ * the whole thing is deterministic under test.
33
+ */
34
+ export declare class RemoteNotifier {
35
+ private readonly seen;
36
+ /**
37
+ * Record a command from operator `id` at `now`; returns true iff a notice should
38
+ * fire. Always advances `lastActivityAt`; advances `lastNotifiedAt` only when it
39
+ * returns true, so the one-per-hour ceiling is measured from the last NOTICE, not
40
+ * the last command.
41
+ */
42
+ note(id: string, now: number): boolean;
43
+ }
@@ -1 +1 @@
1
- export declare const AGENT_VERSION = "1.0.20";
1
+ export declare const AGENT_VERSION = "1.0.23";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aicommander/agent",
3
- "version": "1.0.20",
3
+ "version": "1.0.23",
4
4
  "description": "Remote-machine agent for AI Commander — runs on your server/laptop and lets your AI agent execute shell commands on it via the @aicommander/mcp server. An SSH alternative with no exposed SSH, open ports, or VPN; drive it by AIC-… session code.",
5
5
  "keywords": [
6
6
  "remote",