@aicommander/agent 1.0.22 → 1.0.24

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,25 +1,25 @@
1
1
  #!/usr/bin/env node
2
- import{program as _}from"commander";var O="1.0.22";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 xn from"os";import{spawn as Ze}from"child_process";var I="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}),c=!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=>{c=!0,d(),s.onDone(p??-1,Date.now()-i)}),o.on("error",p=>{c=!0,d(),s.onError(p.message)});let l=p=>{if(!(c||o.pid==null))try{Qe?Ze("taskkill",["/pid",String(o.pid),"/T","/F"],{stdio:"ignore"}):process.kill(-o.pid,p)}catch{}};return{kill:()=>{c||(l("SIGTERM"),d(),a=setTimeout(()=>{a=null,l("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,...c]=e.slice(t+1),a=Number(r),d=Number(s),l=process;try{if(!Number.isInteger(a)||!Number.isInteger(d)||a===0||!i||!o)throw new Error("invalid drop arguments");if(typeof l.initgroups!="function"||typeof l.setgid!="function"||typeof l.setuid!="function")throw new Error("privilege-drop syscalls unavailable on this platform");if(l.initgroups(i,d),l.setgid(d),l.setuid(a),l.getuid?.()===0||l.getgid?.()===0)throw new Error("privilege drop did not take effect");if(typeof l.getgroups=="function"){let f=l.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,c,{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}
2
+ import{program as x}from"commander";var O="1.0.24";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
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),c=Number(i),a=r[5]||"/tmp";if(!Number.isInteger(o)||!Number.isInteger(c))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(c===0)throw new Error("refusing to run secure exec as gid 0");return{uid:o,gid:c,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(),c={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,...c},l=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()-l)}),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 xe(e){console.log(w.cyan(` > ${e}`))}function _e(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(I).origin}function dt(e){let t=(e??"").trim();if(!t)return I;let r;try{r=new URL(t)}catch{return console.warn(`
6
- \u26A0 Ignoring malformed AICOMMANDER_SERVER (${t}); using ${I}.
7
- `),I}if(r.origin===ct())return I;let s=lt(r.hostname);return!An()&&!s?(console.warn(`
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
8
  \u26A0 AICOMMANDER_SERVER override to "${r.origin}" ignored for safety \u2014
9
9
  the agent runs as root and is host-locked to ${ct()}.
10
10
  Set AICOMMANDER_DEV=1 to allow a custom relay for development.
11
- `),I):r.protocol!=="https:"&&!s?(console.warn(`
12
- \u26A0 Refusing plaintext relay "${r.origin}" (https required); using ${I}.
13
- `),I):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 ke={capable:!1,enabled:!1,expiresAt:null},pt=360*60*1e3;function _n(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 kn(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 c=.8+Math.random()*.4,a=Math.min(t*c,r);e.silent||it(s,a);try{await _n(a,e.signal??new AbortController().signal)}catch(d){if(d.name==="AbortError")break}t=Math.min(t*2,r)}}}async function kn(e,t){let{serverUrl:r,sessionCode:s}=e,i=`${r.replace(/^http/,"ws")}/ws/agent/${s}?token=${t}`;ut(i);let o=l=>{try{e.onStatus?.(l)}catch{}},c=l=>{try{e.onActivity?.(l)}catch{}},a=l=>{if(l)try{e.onRemoteActivity?.(l)}catch{}},d=()=>{try{e.onHeartbeat?.()}catch{}};return o("connecting"),new Promise((l,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(),l(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()??ke};try{m.send(JSON.stringify(E))}catch{}};m.on("open",()=>{o("connected"),Xe(),V();let E={type:"agent:register",hostname:xn.hostname(),platform:process.platform,arch:process.arch,agentVersion:O,screenShare:e.screenShare?.getState()??ke};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":{xe(R.command),c(!0),a(R.operator);let{commandId:D,command:W,cwd:Ee,env:ve}=R,oe=Date.now(),z=!1;y(),T=setInterval(()=>{let x=Date.now()-oe;if(x>=3e5&&!z){z=!0;let h={type:"agent:exec_idle",commandId:D,idleMs:x};m.send(JSON.stringify(h))}},3e5),T.unref?.(),u=ze(W,Ee,ve,{onOutput:(x,h)=>{oe=Date.now(),z=!1;let k={type:"agent:output",commandId:D,chunk:x,stream:h};m.send(JSON.stringify(k))},onDone:(x,h)=>{u=null,y(),c(!1),_e(x,h);let k={type:"agent:done",commandId:D,exitCode:x,durationMs:h};m.send(JSON.stringify(k))},onError:x=>{u=null,y(),c(!1);let h={type:"agent:error",commandId:D,error:x};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,k)=>{u=null,y(),c(!1),_e(h,k);let ee={type:"agent:done",commandId:D,exitCode:h,durationMs:k};m.send(JSON.stringify(ee))},x=h=>{u=null,y(),c(!1);let k={type:"agent:error",commandId:D,error:h};m.send(JSON.stringify(k))};try{let h=Array.isArray(W)?W.join(" "):String(W);xe(h),c(!0);let k=Date.now(),ee=!1;y(),T=setInterval(()=>{let se=Date.now()-k;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)=>{k=Date.now(),ee=!1;let an={type:"agent:output",commandId:D,chunk:se,stream:be};m.send(JSON.stringify(an))},onDone:Ye,onError:x}).kill}catch(h){x(h instanceof Error?h.message:String(h))}break}case"do:kill":u&&(u(),u=null);break;case"do:screenshot":a(R.operator),In(m,R.requestId,e.screenShare);break}}),m.on("close",(E,R)=>{f&&clearTimeout(f),y(),e.screenShare?.off("change",ye),u&&(u(),u=null,c(!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 In(e,t,r){let s=c=>{try{e.send(JSON.stringify(c))}catch{}},i=c=>s({type:"agent:screenshot_error",requestId:t,error:c}),o=r?.getState()??ke;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:c,mimeType:a}=await r.capture();if(c.length>10485760){let l=(c.length/1048576).toFixed(1);i(`Screenshot is ${l} MB, which exceeds the ${10485760/(1024*1024)} MB limit.`);return}let d=c.toString("base64");for(let l=0;l<d.length;l+=524288)s({type:"agent:screenshot_chunk",requestId:t,chunk:d.slice(l,l+524288)});s({type:"agent:screenshot_done",requestId:t,mimeType:a,totalBytes:c.length})}catch(c){i(`Screenshot failed: ${c.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 Ie(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=Ie(te.join(e,le));if(i)return i;let o=Rt();return Ce(e,o),o}let t=Ie(te.join(bt,le));if(t)return t;let r=Ie(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 xt(e){for(let t of ne(e))try{M.rmSync(J.join(t,Oe),{force:!0})}catch{}}function _t(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 kt(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 It from"path";import Gn from"os";function ue(e){if(e)return It.join(e,"heartbeat");if(process.platform==="linux")try{return de.mkdirSync("/run/aicommander-agent",{recursive:!0}),"/run/aicommander-agent/heartbeat"}catch{}return It.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,c=0,a=[],d=null,l=null;await new Promise(p=>{let m=null,u=null,f=()=>{d&&(clearInterval(d),d=null),l&&(clearTimeout(l),l=null),m&&(process.removeListener("SIGINT",m),m=null),u&&(process.removeListener("SIGTERM",u),u=null)},S=()=>{f(),p()},A=()=>{i=Date.now(),c++;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&&c>=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;l&&clearTimeout(l),l=setTimeout(()=>{l=null,o||A()},Z),l.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),l&&(clearTimeout(l),l=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 c=(r[o]??0)-(s[o]??0);if(c!==0)return c>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(`
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(`
14
14
  \u2B06 A newer AI Commander agent is available (v${e.version}; you have v${O}).
15
15
  Update: curl -fsSL ${H}/install | sudo bash
16
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(`
17
17
  \u26A0 Warning: not running as root.
18
18
  Commands requiring sudo (apt, systemctl, brew cask\u2026) will fail.
19
19
  Recommended: sudo aicommander-agent
20
- `);let r=K(),s=kt(),i=s?null:Tt(),o,c;try{let d=await Re(H,r,{forceNew:s,...i?{currentCode:i.sessionCode}:{}});o=d.sessionCode,c=d.agentToken,Ne({sessionCode:o,agentToken:c})}catch(d){console.error(` Failed to register: ${String(d)}`),process.exit(1)}st(o,H,!0),Et({sessionCode:o,pid:process.pid,startedAt:new Date().toISOString(),serverUrl:H}),Pt(),setInterval(()=>{Pt()},Xn).unref?.(),await gt({serverUrl:H,sessionCode:o,agentToken:c,reauthIntervalMs:pt,reauth:async()=>{let d=await Re(H,r,{currentCode:o});return Ne({sessionCode:d.sessionCode,agentToken:d.agentToken}),d.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(`
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(`
21
21
  ${e}
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??I),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]
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]
23
23
  Description=AI Commander Remote Agent
24
24
  After=network-online.target
25
25
  Wants=network-online.target
@@ -43,4 +43,4 @@ KillSignal=SIGINT
43
43
 
44
44
  [Install]
45
45
  WantedBy=multi-user.target
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 c=0;c<30;c++){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"),_t(),xt(),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 l=String(d+1).padStart(2," "),p=a.linkedAt.slice(0,10);n.info(`${l}. ${a.maskedEmail}`,`${a.alias} \xB7 linked ${p} \xB7 id ${a.userId.slice(0,8)}\u2026`)},o=s.filter(a=>!a.blocked),c=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(),c.length>0&&(n.header("Blocked"),c.forEach(a=>i(a,s.indexOf(a))),n.blank()),n.step("Block one with: aicommander-agent block-admin <number|id>"),c.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(l){n.error(l.message),process.exitCode=1;return}let o=he(i.admins),c=rn(o,e);if(c.kind==="not_found"){n.error(`No linked account matches "${e}".`),n.info("See options","aicommander-agent list-admins"),process.exitCode=1;return}if(c.kind==="ambiguous"){n.error(`"${e}" is ambiguous \u2014 it matches ${c.matches.length} accounts.`),n.info("Disambiguate","use the list number or a longer id"),process.exitCode=1;return}let a=c.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)||(_.name("aicommander-agent").description("AI Commander remote agent + service controller").version(O),_.command("run",{isDefault:!0}).description("Run the agent: register with the relay and listen for commands").action(async()=>{await Ut()}),_.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)}),_.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)}),_.command("enable").description("Start and enable the agent service").action(()=>{Fe()}),_.command("disable").description("Stop and disable the agent service").action(()=>{Ge()}),_.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)}),_.command("list-admins").description("List the accounts (admins) linked to this device").action(async()=>{await je()}),_.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)}),_.command("unblock-admin <account>").description("Restore a blocked account's access (by list number or id)").action(async e=>{await Je(e)}),_.command("uninstall").description("Fully remove the agent (stop, disable, delete files)").option("-f, --force","Skip confirmation requirement").action(e=>{We(e)}),_.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,4 +1,4 @@
1
- import ct from"os";var U="1.0.22";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(`
1
+ import ct from"os";var U="1.0.24";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
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
3
  \u26A0 Ignoring malformed AICOMMANDER_SERVER (${t}); using ${w}.
4
4
  `),w}if(r.origin===Le())return w;let o=He(r.hostname);return!_t()&&!o?(console.warn(`
@@ -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 +1 @@
1
- export declare const AGENT_VERSION = "1.0.22";
1
+ export declare const AGENT_VERSION = "1.0.24";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aicommander/agent",
3
- "version": "1.0.22",
3
+ "version": "1.0.24",
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",