amplibee 0.1.1 → 0.1.2
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/README.md +42 -0
- package/dist/cli.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -56,3 +56,45 @@ WantedBy=default.target
|
|
|
56
56
|
`systemctl --user enable --now amplibee` (and `loginctl enable-linger $USER` on a server). On macOS or Windows use `pm2 start amplibee -- start --root <folder>`.
|
|
57
57
|
|
|
58
58
|
Sessions run for as long as the agent runs; they survive the app disconnecting, not the agent restarting.
|
|
59
|
+
|
|
60
|
+
## License
|
|
61
|
+
|
|
62
|
+
Copyright (c) 2026 Amplibee. All rights reserved.
|
|
63
|
+
|
|
64
|
+
This software, including the source code, compiled code, documentation, and associated materials, is proprietary and owned by Amplibee.
|
|
65
|
+
|
|
66
|
+
### 1. Limited License Grant
|
|
67
|
+
|
|
68
|
+
Amplibee grants you a limited, non-exclusive, non-transferable, revocable license to install and execute this package solely for the purpose of connecting to and interacting with authorized Amplibee services.
|
|
69
|
+
|
|
70
|
+
### 2. Restrictions
|
|
71
|
+
|
|
72
|
+
You may NOT:
|
|
73
|
+
|
|
74
|
+
- Copy, modify, adapt, or create derivative works of this package.
|
|
75
|
+
- Incorporate its source code into your own applications, products, or codebases.
|
|
76
|
+
- Reverse engineer, decompile, or attempt to extract its underlying implementation, except where prohibited by applicable law.
|
|
77
|
+
- Redistribute, sublicense, resell, or commercially distribute this package.
|
|
78
|
+
- Remove copyright notices, proprietary notices, or branding.
|
|
79
|
+
- Use this package to build competing products or services.
|
|
80
|
+
|
|
81
|
+
### 3. Ownership
|
|
82
|
+
|
|
83
|
+
All intellectual property rights, including copyrights, trademarks, source code, and associated materials, remain the exclusive property of Amplibee.
|
|
84
|
+
|
|
85
|
+
### 4. Termination
|
|
86
|
+
|
|
87
|
+
This license terminates automatically if you violate its terms. Upon termination, you must stop using the package and delete all copies in your possession.
|
|
88
|
+
|
|
89
|
+
### 5. Disclaimer
|
|
90
|
+
|
|
91
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED.
|
|
92
|
+
|
|
93
|
+
TO THE MAXIMUM EXTENT PERMITTED BY LAW, AMPLIBEE SHALL NOT BE LIABLE FOR ANY DAMAGES ARISING FROM THE USE OF THIS SOFTWARE.
|
|
94
|
+
|
|
95
|
+
### 6. Contact
|
|
96
|
+
|
|
97
|
+
For commercial licensing, redistribution permissions, or other licensing inquiries:
|
|
98
|
+
|
|
99
|
+
Amplibee
|
|
100
|
+
Website: https://amplibee.com
|
package/dist/cli.js
CHANGED
|
@@ -18,7 +18,7 @@ Minimum version required to store current data is: `+i+`.
|
|
|
18
18
|
`+Object.keys(n).map(s=>`${s}: ${n[s]}`).join(`\r
|
|
19
19
|
`)+`\r
|
|
20
20
|
\r
|
|
21
|
-
`+r)}function ke(t,e,r,n,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,ke),t.emit("wsClientError",o,r,e)}else Ct(r,n,s,i)}});import{basename as od}from"node:path";import{chmodSync as sl,existsSync as il,mkdirSync as ol,readFileSync as al,rmSync as ll,writeFileSync as cl}from"node:fs";import{homedir as fl}from"node:os";import{join as Kn}from"node:path";var Jn="https://api.amplibee.com/v1",Zn=()=>process.env.AMPLIBEE_HOME||Kn(fl(),".amplibee"),kt=()=>Kn(Zn(),"config.json");function ie(){try{let t=JSON.parse(al(kt(),"utf8"));if(typeof t?.apiUrl=="string"&&typeof t.deviceId=="string"&&typeof t.secret=="string")return t}catch{}return null}function X(t){let e=Zn();il(e)||ol(e,{recursive:!0,mode:448}),cl(kt(),JSON.stringify(t,null,2),{mode:384});try{sl(kt(),384)}catch{}}function Xn(){ll(kt(),{force:!0})}var N=globalThis.crypto.subtle,At=new TextEncoder,ul=new TextDecoder,yr={name:"ECDH",namedCurve:"P-256"},hl="amplibee-e2e-v1",dl=4e5;function G(t){let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function z(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=atob(e+"=".repeat((4-e.length%4)%4)),n=new Uint8Array(r.length);for(let s=0;s<r.length;s++)n[s]=r.charCodeAt(s);return n}var _r=(...t)=>{let e=new Uint8Array(t.reduce((n,s)=>n+s.length,0)),r=0;for(let n of t)e.set(n,r),r+=n.length;return e};async function Ze(t=!1){let e=await N.generateKey(yr,t,["deriveBits"]);return{pub:new Uint8Array(await N.exportKey("raw",e.publicKey)),priv:e.privateKey}}async function Pt(t){return{pub:G(t.pub),priv:await N.exportKey("jwk",t.priv)}}async function ss(t){let e=await N.importKey("jwk",t.priv,yr,!1,["deriveBits"]);return{pub:z(t.pub),priv:e}}var pl="BCDFGHJKLMNPQRSTVWXZ";async function Q(t){let e=new Uint8Array(await N.digest("SHA-256",t)),r=0n;for(let s=0;s<8;s++)r=r<<8n|BigInt(e[s]);let n="";for(let s=0;s<12;s++)n+=pl[Number(r%20n)],r/=20n;return`${n.slice(0,4)}-${n.slice(4,8)}-${n.slice(8,12)}`}var is=(t,e)=>{let r=n=>n.toUpperCase().replace(/[^A-Z]/g,"");return r(t).length===12&&r(t)===r(e)},Qn=t=>{if(typeof t!="string"||!/^[A-Za-z0-9_-]{87}$/.test(t))return!1;try{let e=z(t);return e.length===65&&e[0]===4}catch{return!1}};async function es(t,e){if(e.length!==65||e[0]!==4)throw new Error("bad key");let r=await N.importKey("raw",e,yr,!0,[]);return new Uint8Array(await N.deriveBits({name:"ECDH",public:r},t,256))}async function gl(t,e,r,n){let s=await N.importKey("raw",t,"HKDF",!1,["deriveBits"]);return new Uint8Array(await N.deriveBits({name:"HKDF",hash:"SHA-256",salt:e,info:r},s,n*8))}var ts=At.encode("app>agent"),rs=At.encode("agent>app"),It=class{sendN=0;recvN=0;sq=Promise.resolve();rq=Promise.resolve();sendKey;recvKey;sendDir;recvDir;constructor(e,r,n,s){this.sendKey=e,this.recvKey=r,this.sendDir=n,this.recvDir=s}seal(e){let r=++this.sendN,n=this.sq.then(async()=>{let s=await N.encrypt({name:"AES-GCM",iv:ns(r),additionalData:this.sendDir},this.sendKey,At.encode(JSON.stringify(e)));return{n:r,c:G(new Uint8Array(s))}});return this.sq=n.catch(()=>{}),n}open(e){let r=this.rq.then(async()=>{let{n,c:s}=e;if(typeof n!="number"||!Number.isSafeInteger(n)||n<=this.recvN||typeof s!="string"||s.length>dl)return null;try{let i=await N.decrypt({name:"AES-GCM",iv:ns(n),additionalData:this.recvDir},this.recvKey,z(s)),o=JSON.parse(ul.decode(i));return!o||typeof o!="object"||Array.isArray(o)?null:(this.recvN=n,o)}catch{return null}});return this.rq=r.catch(()=>{}),r}};function ns(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t)),e}async function ml(t,e){let r=_r(At.encode(hl),t.appPub,t.agentPub,t.ephA,t.ephB),n=await gl(_r(t.ss,t.ee),_r(t.nonceA,t.nonceB),r,64),s=await N.importKey("raw",n.slice(0,32),"AES-GCM",!1,["encrypt","decrypt"]),i=await N.importKey("raw",n.slice(32),"AES-GCM",!1,["encrypt","decrypt"]);return e==="app"?new It(s,i,ts,rs):new It(i,s,rs,ts)}var _l=t=>globalThis.crypto.getRandomValues(new Uint8Array(t));async function os(t,e,r){if(!Qn(e.pub)||!Qn(e.eph)||typeof e.nonce!="string")return null;let n=z(e.pub);if(!r(n))return null;let s=z(e.nonce);if(s.length!==16)return null;let i=z(e.eph),o=await Ze(!1),a=_l(16),l=await es(t.priv,n),c=await es(o.priv,i),f=await ml({ss:l,ee:c,appPub:n,agentPub:t.pub,ephA:i,ephB:o.pub,nonceA:s,nonceB:a},"agent");return{accept:{eph:G(o.pub),nonce:G(a)},channel:f,appPub:n}}var j={frameBytes:256*1024,cols:{min:10,max:500},rows:{min:4,max:200},scrollbackBytes:256*1024,fileViewBytes:96*1024};function Ae(t,e){let r=Math.round(Number(t)),n=Math.round(Number(e));return{cols:Math.min(j.cols.max,Math.max(j.cols.min,Number.isFinite(r)?r:80)),rows:Math.min(j.rows.max,Math.max(j.rows.min,Number.isFinite(n)?n:24))}}import{existsSync as yl,statSync as wl}from"node:fs";import{delimiter as bl,extname as El,join as Sl}from"node:path";var xl={claude:{label:"Claude Code",command:"claude"},codex:{label:"Codex",command:"codex"},gemini:{label:"Gemini CLI",command:"gemini"},opencode:{label:"OpenCode",command:"opencode"},aider:{label:"Aider",command:"aider"},goose:{label:"Goose",command:"goose"}},Xe="shell",Bt=/^[a-z0-9][a-z0-9_-]{0,23}$/;function Cl(){return process.platform==="win32"?{label:"Terminal",command:"powershell.exe"}:{label:"Terminal",command:process.env.SHELL||"/bin/bash"}}function oe(t,e){let r={...xl};for(let[n,s]of Object.entries(t.harnesses??{}))Bt.test(n)&&n!==Xe&&(r[n]={...r[n],...s});e&&(r[Xe]=Cl());for(let n of Object.keys(r))r[n].disabled&&delete r[n];return r}function as(t,e=process.env){let r=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[],s=t.includes("/")||t.includes("\\")?[""]:(e.PATH??e.Path??"").split(bl).filter(Boolean);for(let i of s){let o=i?Sl(i,t):t,a=process.platform==="win32"?El(t)?[""]:r:[""];for(let l of a){let c=o+l;try{if(yl(c)&&wl(c).isFile())return c}catch{}}}return null}function Qe(t){return Object.entries(t).map(([e,r])=>({id:e,label:r.label??e,available:as(r.command)!==null}))}function Lt(t){let e=as(t.command);if(!e)return null;let r=t.args??[];return process.platform==="win32"&&/\.(cmd|bat)$/i.test(e)?{file:process.env.COMSPEC||"cmd.exe",args:["/d","/s","/c",e,...r]}:{file:e,args:r}}import{execFile as Tl}from"node:child_process";var Ot=(t,e)=>new Promise(r=>Tl(t,e,{timeout:4e3,windowsHide:!0,maxBuffer:4*1024*1024},(n,s)=>r(n?"":String(s)))),wr=new Set(["*","0.0.0.0","127.0.0.1","[::]","[::1]","::","::1","localhost"]),vl=new Set(["system","svchost.exe","lsass.exe","services.exe","wininit.exe","spoolsv.exe","system idle process"]);function kl(t){let e=[];for(let r of t.split(/\r?\n/)){let n=/^\s*TCP\s+(\S+):(\d+)\s+\S+\s+LISTENING\s+(\d+)/i.exec(r);n&&wr.has(n[1])&&e.push({port:Number(n[2]),pid:Number(n[3])})}return e}function Il(t){let e=new Map;for(let r of t.split(/\r?\n/)){let n=/^"([^"]+)","(\d+)"/.exec(r);n&&e.set(Number(n[2]),n[1])}return e}function Al(t){let e=[],r="";for(let n of t.split(/\r?\n/))if(n.startsWith("c"))r=n.slice(1);else if(n.startsWith("n")){let s=n.lastIndexOf(":");s>0&&wr.has(n.slice(1,s))&&e.push({port:Number(n.slice(s+1)),process:r})}return e}function Pl(t){let e=[];for(let r of t.split(/\r?\n/)){let n=r.trim().split(/\s+/);if(n[0]!=="LISTEN"||n.length<5)continue;let s=n[3],i=s.lastIndexOf(":");i<0||!wr.has(s.slice(0,i))||e.push({port:Number(s.slice(i+1)),process:/users:\(\("([^"]+)"/.exec(r)?.[1]??""})}return e}function Bl(t){let e=new Map;for(let r of t)!Number.isInteger(r.port)||r.port<1024||r.port>65535||process.platform==="win32"&&r.port>=49152||(!e.has(r.port)||!e.get(r.port).process&&r.process)&&e.set(r.port,{port:r.port,process:r.process.slice(0,60)});return[...e.values()].sort((r,n)=>r.port-n.port).slice(0,40)}var et=null;async function br(){if(et&&Date.now()-et.at<2e3)return et.list;let t=[];if(process.platform==="win32"){let[e,r]=await Promise.all([Ot("netstat",["-ano","-p","tcp"]),Ot("tasklist",["/FO","CSV","/NH"])]),n=Il(r);t=kl(e).map(s=>({port:s.port,process:n.get(s.pid)??""})).filter(s=>!vl.has(s.process.toLowerCase())).map(s=>({port:s.port,process:s.process.replace(/\.exe$/i,"")}))}else t=Al(await Ot("lsof",["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"])),t.length===0&&(t=Pl(await Ot("ss",["-ltnpH"])));return et={at:Date.now(),list:Bl(t)},et.list}import{request as Ll}from"node:http";import{createBrotliDecompress as Ol,createGunzip as Rl,createInflate as Nl}from"node:zlib";var Rt=90*1024,Ml=32*1024*1024,Ul=3e4,ls=new Set(["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"]),Dl=/^(accept|accept-language|authorization|cache-control|content-type|if-[a-z-]+|pragma|range|user-agent|x-[a-z0-9-]+)$/i,ql=new Set(["connection","keep-alive","transfer-encoding","content-length","content-encoding","set-cookie","set-cookie2","x-frame-options","content-security-policy","content-security-policy-report-only","strict-transport-security","upgrade","trailer","te"]);function Fl(t,e,r){let n={};for(let[s,i]of Object.entries(t))typeof i=="string"&&i.length<4096&&Dl.test(s)&&(n[s.toLowerCase()]=i);return n.host=`localhost:${e}`,n["accept-encoding"]="gzip, deflate, br",r>0&&(n["content-length"]=String(r)),n}function Hl(t){let e={};for(let[r,n]of Object.entries(t))ql.has(r.toLowerCase())||n===void 0||(e[r.toLowerCase()]=Array.isArray(n)?n.join(", "):n);return e}var Er=[],Sr=!1;function Nt(t){if(Er.push(t),Sr)return;Sr=!0;let e=()=>{Er.shift()?.(),Er.length?setTimeout(e,6):Sr=!1};setTimeout(e,0)}function cs(t,e,r,n,s){let i=!1,o=()=>{i||(i=!0,n())},a=c=>{i||(Nt(()=>r({t:"error",code:"proxy_failed",message:c,reqId:e.reqId})),o())},l=Ll({host:t,port:e.port,method:e.method,path:e.path,headers:Fl(e.headers,e.port,e.body?.length??0),timeout:Ul},c=>{let f=String(c.headers["content-encoding"]??"").toLowerCase(),u=f==="gzip"||f==="x-gzip"?c.pipe(Rl()):f==="deflate"?c.pipe(Nl()):f==="br"?c.pipe(Ol()):c;Nt(()=>r({t:"http.head",reqId:e.reqId,status:c.statusCode??502,headers:Hl(c.headers)}));let h=[],d=0,m=0,p=_=>{let y=Buffer.concat(h);h=[],d=0,Nt(()=>r({t:"http.chunk",reqId:e.reqId,data:y.toString("base64"),last:_}))};u.on("data",_=>{if(m+=_.length,m>Ml)return c.destroy(),a("That response is too large to preview.");for(h.push(_),d+=_.length;d>=Rt;){let y=Buffer.concat(h);h=[y.subarray(Rt)],d=y.length-Rt,Nt(()=>r({t:"http.chunk",reqId:e.reqId,data:y.subarray(0,Rt).toString("base64"),last:!1}))}}),u.on("end",()=>{i||(p(!0),o())}),u.on("error",()=>a("The page could not be read."))});l.on("timeout",()=>{l.destroy(),a("The server did not answer in time.")}),l.on("error",c=>{if(s&&c.code==="ECONNREFUSED")return cs("::1",e,r,n,!1);a(c.code==="ECONNREFUSED"?"Nothing is listening on that port any more.":"Could not reach that server.")}),e.body&&e.body.length>0&&l.write(e.body),l.end()}function fs(t,e,r){cs("127.0.0.1",t,e,r,!0)}import{closeSync as zl,lstatSync as hs,openSync as Wl,readSync as $l,readdirSync as ds,realpathSync as Gl,renameSync as ps,rmdirSync as jl,statSync as Pe,unlinkSync as gs,writeFileSync as Yl}from"node:fs";import{homedir as Vl}from"node:os";import{basename as xr,dirname as Cr,isAbsolute as Tr,join as vr,resolve as Mt,sep as us}from"node:path";var Be=t=>process.platform==="win32"||process.platform==="darwin"?t.toLowerCase():t;function Y(t){try{return Gl(t)}catch{return null}}function Le(t){return t==="~"||t.startsWith("~/")||t.startsWith("~\\")?Mt(Vl(),t.slice(2)):Mt(t)}function Ut(t,e){if(!Tr(e))return null;let r=Y(e);if(!r)return null;try{if(!Pe(r).isDirectory())return null}catch{return null}return kr(t,r)?r:null}function kr(t,e){let r=Be(e);for(let n of t){let s=Be(n);if(r===s||r.startsWith(s.endsWith(us)?s:s+us))return!0}return!1}function Ir(t,e){if(!Tr(e))return null;let r=Y(e);if(!r)return null;try{if(!Pe(r).isFile())return null}catch{return null}return kr(t,r)?r:null}var Kl=/^(id_(rsa|dsa|ecdsa|ed25519)|\.env.*|\.npmrc|\.netrc|credentials|.*\.(pem|key|p12|pfx|keystore|kdbx))$/i,tt=t=>Kl.test(xr(t));function ms(t,e){return t.some(r=>Be(r)===Be(e))}function _s(t){try{return ds(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!e.name.startsWith(".")&&e.name!=="node_modules").map(e=>e.name).sort((e,r)=>e.localeCompare(r)).slice(0,300)}catch{return[]}}function ys(t){let e=[],r=[];try{for(let s of ds(t,{withFileTypes:!0}))if(!(s.name.startsWith(".")||s.name==="node_modules")){if(s.isDirectory())e.push(s.name);else if(s.isFile()){let i=0;try{i=Pe(Mt(t,s.name)).size}catch{}r.push({name:s.name,size:i})}}}catch{}let n=(s,i)=>(typeof s=="string"?s:s.name).localeCompare(typeof i=="string"?i:i.name);return{dirs:e.sort(n).slice(0,300),files:r.sort(n).slice(0,500)}}function ws(t,e){let r=Pe(t),n=r.size,s=Math.floor(r.mtimeMs),i=Wl(t,"r");try{let o=Buffer.alloc(Math.min(n,e)),a=$l(i,o,0,o.length,0),l=o.subarray(0,a);if(l.includes(0))return{size:n,mtime:s,text:null,binary:!0,truncated:!1};let c=l.toString("utf8"),f=n>a;return!f&&!Buffer.from(c,"utf8").equals(l)?{size:n,mtime:s,text:null,binary:!0,truncated:!1}:{size:n,mtime:s,text:c,binary:!1,truncated:f}}finally{zl(i)}}function bs(t,e,r){let n=Pe(t);if(Math.floor(n.mtimeMs)!==Math.floor(r))throw Object.assign(new Error("The file changed on the workspace."),{code:"conflict"});let s=vr(Cr(t),`.${xr(t)}.amplibee-${process.pid}.tmp`);Yl(s,e,{mode:n.mode&511});try{ps(s,t)}catch(o){try{gs(s)}catch{}throw o}let i=Pe(t);return{size:i.size,mtime:Math.floor(i.mtimeMs)}}function Es(t,e){if(!Tr(e))return null;let r=Y(Cr(Mt(e)));if(!r||!kr(t,r))return null;let n=vr(r,xr(e)),s;try{s=hs(n)}catch{return null}return!s.isSymbolicLink()&&ms(t,Y(n)??n)?null:{entry:n,folder:r,isDir:s.isDirectory()}}var Jl=/[\\/:*?"<>|\0]/;function Ss(t,e,r){let n=Es(t,e);if(!n)throw Object.assign(new Error("outside"),{code:"bad_file"});if(!r||r.length>200||r==="."||r===".."||Jl.test(r)||r!==r.trim())throw Object.assign(new Error("bad name"),{code:"bad_name"});let s=vr(n.folder,r);try{if(hs(s),Be(s)!==Be(n.entry))throw Object.assign(new Error("exists"),{code:"exists"})}catch(i){if(i.code==="exists")throw i}return ps(n.entry,s),s}function xs(t,e){let r=Es(t,e);if(!r)throw Object.assign(new Error("outside"),{code:"bad_file"});if(r.isDir){try{jl(r.entry)}catch{throw Object.assign(new Error("not empty"),{code:"not_empty"})}return}gs(r.entry)}var Ar=(t,e)=>ms(t,e)?null:Cr(e);var Dt=(t,e)=>typeof t=="string"&&t.length>0&&t.length<=e?t:null,Zl=64*1024,Xl=10,Ql=200,ec=12,Cs=16*1024,qt=class{constructor(e){this.o=e;this.roots=e.roots.map(r=>Y(Le(r))??Le(r)),e.manager.onChange=()=>this.o.send({t:"sessions",sessions:e.manager.list()})}roots;subs=new Map;proxying=0;proxyWaiting=[];pending=new Map;host(){return{name:this.o.cfg.name,platform:process.platform,agentVersion:this.o.version,roots:this.roots,harnesses:Qe(oe(this.o.cfg,this.o.allowShell))}}connected(){this.subs.clear()}watch(e){e.onData(r=>{let n=this.subs.get(e.id);if(!n||n.size===0)return;let s=this.pending.get(e.id);s?s.buf+=r:this.pending.set(e.id,{buf:r,timer:setTimeout(()=>this.flush(e.id),ec)})}),e.onExit(r=>{this.flush(e.id);for(let n of this.subs.get(e.id)??[])this.o.send({t:"session.exit",id:e.id,code:r,cid:n})})}flush(e){let r=this.pending.get(e);if(r){clearTimeout(r.timer),this.pending.delete(e);for(let n of this.subs.get(e)??[])this.output(e,n,r.buf,!1)}}output(e,r,n,s){if(n.length<=Cs)return this.o.send({t:"session.output",id:e,data:n,replay:s||void 0,cid:r});for(let i=0;i<n.length;){let o=Math.min(i+Cs,n.length),a=n.charCodeAt(o-1);o<n.length&&a>=55296&&a<=56319&&o--,this.o.send({t:"session.output",id:e,data:n.slice(i,o),replay:s&&i===0?!0:void 0,cid:r}),i=o}}subscribe(e,r){let n=this.subs.get(e);n||this.subs.set(e,n=new Set),n.add(r)}handle(e){let r=typeof e.cid=="string"?e.cid:void 0,n=i=>this.o.send({...i,cid:r}),s=(i,o)=>n({t:"error",code:i,message:o,reqId:typeof e.reqId=="string"?e.reqId:void 0});if(r)try{this.dispatch(e,r,n,s)}catch(i){s("failed",i instanceof Error?i.message:"Something went wrong on the workspace.")}}dispatch(e,r,n,s){let i=this.o.manager,o=()=>{let a=Dt(e.id,40),l=a?i.get(a):void 0;return l||s("no_session","That session no longer exists."),l??null};switch(e.t){case"app.left":for(let a of this.subs.values())a.delete(r);return;case"host.get":return n({t:"host",host:this.host()});case"sessions.list":return n({t:"sessions",sessions:i.list()});case"session.start":{let a=Dt(e.harness,24),l=a?oe(this.o.cfg,this.o.allowShell)[a]:void 0;if(!a||!l)return s("unknown_harness","That agent is not enabled on this workspace.");let c=Lt(l);if(!c)return s("not_installed",`"${l.command}" is not installed on this workspace.`);let f=e.cwd===void 0?this.roots[0]:Ut(this.roots,String(e.cwd));if(!f)return s("bad_folder","That folder is outside the folders this workspace shares.");let{cols:u,rows:h}=Ae(e.cols,e.rows),d=i.start({harness:a,title:l.label??a,file:c.file,args:c.args,cwd:f,cols:u,rows:h});return this.watch(d),this.subscribe(d.id,r),n({t:"session.started",session:d.info,reqId:typeof e.reqId=="string"?e.reqId:void 0})}case"session.attach":{let a=o();if(!a)return;if(this.subscribe(a.id,r),!a.opts.local&&e.cols!==void 0){let l=Ae(e.cols,e.rows);a.resize(l.cols,l.rows)}this.output(a.id,r,a.scrollback(),!0),a.running||n({t:"session.exit",id:a.id,code:a.exitCode});return}case"session.input":{let a=o(),l=typeof e.data=="string"&&e.data.length<=Zl?e.data:null;a&&l!==null&&a.write(l);return}case"session.resize":{let a=o();a&&!a.opts.local&&a.resize(Number(e.cols),Number(e.rows));return}case"session.kill":return o()?.kill();case"session.remove":{let a=Dt(e.id,40);a&&(i.remove(a),this.subs.delete(a));return}case"dir.list":{let a=e.path===void 0||e.path===""?this.roots[0]:Ut(this.roots,String(e.path));return a?n({t:"dirs",path:a,parent:Ar(this.roots,a),entries:_s(a),reqId:typeof e.reqId=="string"?e.reqId:void 0}):s("bad_folder","That folder is outside the folders this workspace shares.")}case"fs.list":{let a=e.path===void 0||e.path===""?this.roots[0]:Ut(this.roots,String(e.path));if(!a)return s("bad_folder","That folder is outside the folders this workspace shares.");let{dirs:l,files:c}=ys(a);return n({t:"fs.entries",path:a,parent:Ar(this.roots,a),dirs:l,files:c,reqId:typeof e.reqId=="string"?e.reqId:void 0})}case"fs.read":{let a=Ir(this.roots,String(e.path??""));if(!a)return s("bad_file","That file is outside the folders this workspace shares.");if(tt(a))return s("secret_file","Files that usually hold secrets (keys, .env) are never shown here.");let l=ws(a,j.fileViewBytes);return n({t:"fs.file",path:a,...l,reqId:typeof e.reqId=="string"?e.reqId:void 0})}case"fs.write":{let a=Ir(this.roots,String(e.path??""));if(!a)return s("bad_file","That file is outside the folders this workspace shares.");if(tt(a))return s("secret_file","Files that usually hold secrets (keys, .env) are never edited here.");if(typeof e.text!="string"||Buffer.byteLength(e.text,"utf8")>j.fileViewBytes)return s("too_large",`Files can be edited here up to ${Math.round(j.fileViewBytes/1024)} KB.`);try{let l=bs(a,e.text,Number(e.mtime));return n({t:"fs.saved",path:a,...l,reqId:typeof e.reqId=="string"?e.reqId:void 0})}catch(l){return l.code==="conflict"?s("conflict","This file changed on the workspace since you opened it. Reload it to see the new version."):s("write_failed","Could not save the file. It may be read-only on the workspace.")}}case"fs.rename":{let a=String(e.path??""),l=typeof e.name=="string"?e.name:"";if(tt(a))return s("secret_file","Files that usually hold secrets (keys, .env) are never changed here.");try{let c=Ss(this.roots,a,l);return n({t:"fs.done",op:"rename",path:a,newPath:c,reqId:typeof e.reqId=="string"?e.reqId:void 0})}catch(c){let f=c.code;return f==="bad_file"?s("bad_file","That is outside the folders this workspace shares."):f==="bad_name"?s("bad_name",'Use a plain name: no slashes and none of : * ? " < > |'):f==="exists"?s("exists","Something with that name already exists here."):s("failed","Could not rename it.")}}case"fs.remove":{let a=String(e.path??"");if(tt(a))return s("secret_file","Files that usually hold secrets (keys, .env) are never changed here.");try{return xs(this.roots,a),n({t:"fs.done",op:"remove",path:a,reqId:typeof e.reqId=="string"?e.reqId:void 0})}catch(l){let c=l.code;return c==="bad_file"?s("bad_file","That is outside the folders this workspace shares."):c==="not_empty"?s("not_empty","Only empty folders can be removed here. Delete what is inside first."):s("failed","Could not delete it.")}}case"ports.list":{(this.o.ports??br)().then(a=>n({t:"ports",ports:a,reqId:typeof e.reqId=="string"?e.reqId:void 0}));return}case"http.fetch":{let a=Dt(e.reqId,80),l=Number(e.port),c=String(e.method??"").toUpperCase(),f=typeof e.path=="string"?e.path:"";if(!a)return s("bad_request","Missing request id.");if(!Number.isInteger(l)||!ls.has(c)||!/^\/[^\s]*$/.test(f)||f.length>4e3)return s("bad_request","That request is not allowed.");let u=typeof e.body=="string"&&e.body.length>0?Buffer.from(e.body,"base64"):null;if(u&&u.length>150*1024)return s("too_large","That request body is too large for the preview.");if(this.proxyWaiting.length>=Ql)return s("busy","Too many requests at once. Try again.");let h=e.headers&&typeof e.headers=="object"?e.headers:{},d=()=>{this.proxying++;let m=()=>{this.proxying--,this.proxyWaiting.shift()?.()};(this.o.ports??br)().then(p=>{if(!p.some(_=>_.port===l))return m(),n({t:"error",code:"no_server",message:"Nothing is listening on that port.",reqId:a});fs({reqId:a,port:l,method:c,path:f,headers:h,body:u},n,m)},m)};this.proxying>=Xl?this.proxyWaiting.push(d):d();return}default:return s("unknown_message","Unknown message.")}}};var Ts=20;async function Ft(t){if(t.identity)try{return await ss(t.identity)}catch{}let e=await Ze(!0);return t.identity=await Pt(e),t.apps=[],X(t),e}var rt={at:0,keys:[]};function vs(){return Date.now()-rt.at>2e3&&(rt={at:Date.now(),keys:(ie()?.apps??[]).map(t=>t.pub)}),rt.keys}async function Pr(t){z(t);let e=ie();if(!e)throw new Error("This workspace is not logged in.");let r=(e.apps??[]).filter(s=>s.pub!==t);if(r.length>=Ts)throw new Error(`You can link up to ${Ts} browsers. Remove one with "amplibee apps remove <fingerprint>".`);let n={pub:t,fingerprint:await Q(z(t)),addedAt:new Date().toISOString()};return e.apps=[...r,n],X(e),rt={at:0,keys:[]},n}function ks(t){let e=ie();if(!e)return 0;let r=s=>s.toUpperCase().replace(/[^A-Z]/g,""),n=e.apps??[];return e.apps=n.filter(s=>r(s.fingerprint)!==r(t)),X(e),rt={at:0,keys:[]},n.length-e.apps.length}var Do=Z(Uo(),1);import{createHash as _u,randomBytes as yu}from"node:crypto";import{spawn as wu}from"node:child_process";import{hostname as bu,platform as Eu,release as Su}from"node:os";import{createInterface as xu}from"node:readline/promises";async function Sn(t,e,r,n={}){let s;try{s=await fetch(t+e,{method:"POST",headers:{"content-type":"application/json",...n},body:JSON.stringify(r),signal:AbortSignal.timeout(2e4)})}catch{throw new Error(`Could not reach ${t}. Check your internet connection.`)}let i=null;try{i=await s.json()}catch{}if(!s.ok||!i?.ok||i.data===null)throw Object.assign(new Error(i?.error?.message??`The server answered with status ${s.status}.`),{status:s.status,code:i?.error?.code});return i.data}function qo(t){try{let[e,r]=process.platform==="win32"?["cmd",["/c","start","",t]]:process.platform==="darwin"?["open",[t]]:["xdg-open",[t]];wu(e,r,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}async function Fo(t,e){let r=Date.now()+e.expires_in*1e3;for(;Date.now()<r;){await new Promise(n=>setTimeout(n,e.interval*1e3));try{let n=await Sn(t,"/devices/pair/poll",{device_code:e.device_code});if(n.status==="approved")return n}catch(n){let s=n.status;if(s===410)break;if(s&&s<500&&s!==429)throw n}}throw new Error("The code expired. Run the command again.")}async function Cu(t){let e=xu({input:process.stdin,output:process.stdout});try{return await e.question(t)}finally{e.close()}}async function Ho(t,e,r){let n;try{n=await Q(z(t))}catch{return r(" The app sent a key that is not valid, so nothing was linked."),!1}if(r(""),r(" The app approved. Check that it shows the same fingerprint for this browser:"),r(""),r(` ${n}`),r(""),e.trustApp){let i=is(e.trustApp,n);return r(i?" It matches --trust-app.":" It does NOT match --trust-app, so the browser was not linked."),i}if(!process.stdin.isTTY)return r(" There is nobody here to confirm it. Run this in a terminal, or pass --trust-app <fingerprint>."),!1;let s=await Cu(' Type "yes" only if it is exactly the same: ');return/^y(es)?$/i.test(s.trim())}async function zo(t,e,r,n){n(""),n(` ${r}`),n(` ${t.verification_url}`);try{let s=await Do.default.toString(t.verification_url,{type:"utf8",errorCorrectionLevel:"L"});n("");for(let i of s.split(/\r?\n/))n(` ${i}`)}catch{}n(""),n(` Code: ${t.user_code}`),n(` Fingerprint: ${e}`),n(""),n(" The app shows this fingerprint too. Continue only if they are the same."),n(` Waiting for approval (the code works for ${Math.round(t.expires_in/60)} minutes)...`)}async function Wo(t){let e=t.log??console.log,r=yu(32).toString("hex"),n=(t.name||bu()||"my workspace").slice(0,60),s=await Ze(!0),i=await Sn(t.apiUrl,"/devices/pair",{name:n,platform:`${Eu()} ${Su()}`.slice(0,40),agent_version:t.version,token_hash:_u("sha256").update(r).digest("hex"),agent_pub:G(s.pub)});await zo(i,await Q(s.pub),"Scan the QR code with your phone, or open this page and confirm the code:",e),t.openBrowser&&qo(i.verification_url);let o=await Fo(t.apiUrl,i),a={apiUrl:t.apiUrl,deviceId:o.device_id,secret:r,name:n,identity:await Pt(s),apps:[]};X(a);let l=await Ho(o.app_pub,t,e);return l&&await Pr(o.app_pub),{cfg:a,linked:l}}async function $o(t,e){let r=e.log??console.log,n=await Ft(t),s=await Sn(t.apiUrl,"/devices/link",{agent_pub:G(n.pub),agent_version:e.version},{authorization:`Bearer ${t.secret}`});await zo(s,await Q(n.pub),'Open the workspace in the Amplibee app and choose "Link this browser", or scan the QR code:',r),e.openBrowser&&qo(s.verification_url);let i=await Fo(t.apiUrl,s),o=await Ho(i.app_pub,{...e,apiUrl:t.apiUrl},r);return o&&await Pr(i.app_pub),o}var Kh=Z(qa(),1),Jh=Z(ar(),1),Zh=Z($e(),1),Xh=Z(Nn(),1),Qh=Z(Dn(),1),ed=Z(Wn(),1),Va=Z(fr(),1),td=Z(Ya(),1);var Gn=Va.default;var Tt=class extends Error{};function rd(t){return t.replace(/^http/,"ws").replace(/\/$/,"")+"/relay/agent"}var hr=class{constructor(e){this.o=e;this.fatal=new Promise(r=>this.die=r)}ws=null;attempt=0;stopped=!1;watchdog;retry;fatal;die;get connected(){return this.ws?.readyState===Gn.OPEN}start(){this.open()}stop(){this.stopped=!0,clearTimeout(this.retry),clearInterval(this.watchdog),this.ws?.close(1e3)}send(e){return this.connected?(this.ws.send(JSON.stringify(e)),!0):!1}open(){if(this.stopped)return;let e=new Gn(rd(this.o.apiUrl),{headers:{authorization:`Bearer ${this.o.secret}`,"x-amplibee-agent":this.o.version},handshakeTimeout:15e3,maxPayload:512*1024});this.ws=e;let r=Date.now();e.on("open",()=>{this.attempt=0,r=Date.now(),this.o.log("connected to Amplibee"),this.o.onUp()}),e.on("ping",()=>r=Date.now()),e.on("message",n=>{r=Date.now();try{let s=JSON.parse(n.toString());s&&typeof s.t=="string"&&this.o.onMessage(s)}catch{}}),e.on("unexpected-response",(n,s)=>{s.resume(),s.statusCode===401?this.die(new Tt('This workspace was removed from your account (or its login is no longer valid). Run "amplibee login" again.')):this.o.log(`relay answered ${s.statusCode}`),e.terminate()}),e.on("error",n=>this.o.log(`connection problem: ${n.message}`)),e.on("close",n=>{if(clearInterval(this.watchdog),this.o.onDown(),n===4001)return this.die(new Tt('This workspace was removed from your account. Run "amplibee login" to connect it again.'));if(n===4e3)return this.die(new Tt("Another amplibee process for this workspace connected, so this one stopped. Run only one at a time."));this.schedule()}),clearInterval(this.watchdog),this.watchdog=setInterval(()=>{Date.now()-r>75e3&&e.terminate()},1e4)}schedule(){if(this.stopped)return;let e=Math.min(3e4,1e3*2**Math.min(this.attempt++,5)),r=e/2+Math.random()*(e/2);this.o.log(`reconnecting in ${Math.round(r/1e3)}s`),this.retry=setTimeout(()=>this.open(),r)}};var nd=32,dr=class{chans=new Map;o;constructor(e){this.o=e}reset(){this.chans.clear()}get channels(){return this.chans.size}async fromRelay(e){let r=typeof e.cid=="string"&&e.cid.length>0&&e.cid.length<=32?e.cid:null;if(r){if(e.t==="app.left")return this.chans.delete(r),this.o.deliver({t:"app.left",cid:r});if(e.t==="e2e.hello")return this.hello(r,e);if(e.t==="e2e.data")return this.data(r,{n:e.n,c:e.c})}}async hello(e,r){if(!this.chans.has(e)&&this.chans.size>=nd)return;let n=null;try{let s=this.o.trusted();n=await os(this.o.identity,r,i=>s.includes(G(i)))}catch{}if(!n)return this.o.transmit({t:"e2e.reject",cid:e,code:"not_linked"});this.chans.set(e,{chan:n.channel,app:G(n.appPub)}),this.o.transmit({t:"e2e.accept",cid:e,...n.accept}),this.sendTo(e,{t:"secure"})}async data(e,r){let n=this.chans.get(e);if(!n)return;if(!this.o.trusted().includes(n.app))return this.chans.delete(e),this.o.transmit({t:"e2e.reject",cid:e,code:"not_linked"});let s=await n.chan.open(r);s&&typeof s.t=="string"&&s.t.length<=40&&this.o.deliver({...s,t:s.t,cid:e})}send(e){let{cid:r,...n}=e;if(r)this.sendTo(r,n);else for(let s of[...this.chans.keys()])this.sendTo(s,n)}sendTo(e,r){let n=this.chans.get(e);n&&n.chan.seal(r).then(s=>this.o.transmit({t:"e2e.data",cid:e,...s})).catch(()=>{})}};import{randomBytes as sd}from"node:crypto";var Ka=8,id=24,jn=class{constructor(e,r){this.pty=e;this.opts=r;this.cols=r.cols,this.rows=r.rows,e.onData(n=>{this.keep(n);for(let s of this.listeners)s(n)}),e.onExit(n=>{this.running=!1,this.exitCode=n.exitCode;for(let s of this.exitListeners)s(n.exitCode)})}id=sd(6).toString("hex");startedAt=Date.now();running=!0;exitCode=null;cols;rows;chunks=[];size=0;listeners=new Set;exitListeners=new Set;get info(){return{id:this.id,harness:this.opts.harness,title:this.opts.title,cwd:this.opts.cwd,cols:this.cols,rows:this.rows,startedAt:this.startedAt,running:this.running,exitCode:this.exitCode,local:!!this.opts.local}}keep(e){for(this.chunks.push(e),this.size+=e.length;this.size>j.scrollbackBytes&&this.chunks.length>1;)this.size-=this.chunks.shift().length}scrollback(){return this.chunks.join("")}onData(e){return this.listeners.add(e),()=>this.listeners.delete(e)}onExit(e){return this.exitListeners.add(e),()=>this.exitListeners.delete(e)}write(e){this.running&&this.pty.write(e)}resize(e,r){let n=Ae(e,r);if(this.cols=n.cols,this.rows=n.rows,this.running)try{this.pty.resize(n.cols,n.rows)}catch{}}kill(){this.running&&this.pty.kill()}},vt=class{constructor(e){this.spawn=e}sessions=new Map;onChange=()=>{};list(){return[...this.sessions.values()].map(e=>e.info)}get(e){return this.sessions.get(e)}runningCount(){return[...this.sessions.values()].filter(e=>e.running).length}start(e){if(this.runningCount()>=Ka)throw new Error(`At most ${Ka} sessions can run at once. Close one first.`);let r=Ae(e.cols,e.rows),n={};for(let[o,a]of Object.entries(process.env))typeof a=="string"&&(n[o]=a);n.TERM="xterm-256color",n.COLORTERM="truecolor",n.AMPLIBEE_SESSION="1";let s=this.spawn(e.file,e.args,{cwd:e.cwd,cols:r.cols,rows:r.rows,env:n}),i=new jn(s,{...e,...r});return this.sessions.set(i.id,i),i.onExit(()=>this.onChange()),this.trim(),this.onChange(),i}remove(e){let r=this.sessions.get(e);return r?(r.kill(),this.sessions.delete(e),this.onChange(),!0):!1}killAll(){for(let e of this.sessions.values())e.kill()}trim(){let e=[...this.sessions.values()].filter(r=>!r.running);for(let r of e.slice(0,Math.max(0,this.sessions.size-id)))this.sessions.delete(r.id)}};async function Yn(){let t=await import("@lydell/node-pty");return(e,r,n)=>{let s=t.spawn(e,r,{name:"xterm-256color",cols:n.cols,rows:n.rows,cwd:n.cwd,env:n.env});return{onData:i=>void s.onData(i),onExit:i=>void s.onExit(i),write:i=>s.write(i),resize:(i,o)=>s.resize(i,o),kill:()=>s.kill()}}}var me="0.1.1",ad=`amplibee ${me}: steer Claude Code, Codex or any terminal agent from your phone.
|
|
21
|
+
`+r)}function ke(t,e,r,n,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,ke),t.emit("wsClientError",o,r,e)}else Ct(r,n,s,i)}});import{basename as od}from"node:path";import{chmodSync as sl,existsSync as il,mkdirSync as ol,readFileSync as al,rmSync as ll,writeFileSync as cl}from"node:fs";import{homedir as fl}from"node:os";import{join as Kn}from"node:path";var Jn="https://api.amplibee.com/v1",Zn=()=>process.env.AMPLIBEE_HOME||Kn(fl(),".amplibee"),kt=()=>Kn(Zn(),"config.json");function ie(){try{let t=JSON.parse(al(kt(),"utf8"));if(typeof t?.apiUrl=="string"&&typeof t.deviceId=="string"&&typeof t.secret=="string")return t}catch{}return null}function X(t){let e=Zn();il(e)||ol(e,{recursive:!0,mode:448}),cl(kt(),JSON.stringify(t,null,2),{mode:384});try{sl(kt(),384)}catch{}}function Xn(){ll(kt(),{force:!0})}var N=globalThis.crypto.subtle,At=new TextEncoder,ul=new TextDecoder,yr={name:"ECDH",namedCurve:"P-256"},hl="amplibee-e2e-v1",dl=4e5;function G(t){let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function z(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=atob(e+"=".repeat((4-e.length%4)%4)),n=new Uint8Array(r.length);for(let s=0;s<r.length;s++)n[s]=r.charCodeAt(s);return n}var _r=(...t)=>{let e=new Uint8Array(t.reduce((n,s)=>n+s.length,0)),r=0;for(let n of t)e.set(n,r),r+=n.length;return e};async function Ze(t=!1){let e=await N.generateKey(yr,t,["deriveBits"]);return{pub:new Uint8Array(await N.exportKey("raw",e.publicKey)),priv:e.privateKey}}async function Pt(t){return{pub:G(t.pub),priv:await N.exportKey("jwk",t.priv)}}async function ss(t){let e=await N.importKey("jwk",t.priv,yr,!1,["deriveBits"]);return{pub:z(t.pub),priv:e}}var pl="BCDFGHJKLMNPQRSTVWXZ";async function Q(t){let e=new Uint8Array(await N.digest("SHA-256",t)),r=0n;for(let s=0;s<8;s++)r=r<<8n|BigInt(e[s]);let n="";for(let s=0;s<12;s++)n+=pl[Number(r%20n)],r/=20n;return`${n.slice(0,4)}-${n.slice(4,8)}-${n.slice(8,12)}`}var is=(t,e)=>{let r=n=>n.toUpperCase().replace(/[^A-Z]/g,"");return r(t).length===12&&r(t)===r(e)},Qn=t=>{if(typeof t!="string"||!/^[A-Za-z0-9_-]{87}$/.test(t))return!1;try{let e=z(t);return e.length===65&&e[0]===4}catch{return!1}};async function es(t,e){if(e.length!==65||e[0]!==4)throw new Error("bad key");let r=await N.importKey("raw",e,yr,!0,[]);return new Uint8Array(await N.deriveBits({name:"ECDH",public:r},t,256))}async function gl(t,e,r,n){let s=await N.importKey("raw",t,"HKDF",!1,["deriveBits"]);return new Uint8Array(await N.deriveBits({name:"HKDF",hash:"SHA-256",salt:e,info:r},s,n*8))}var ts=At.encode("app>agent"),rs=At.encode("agent>app"),It=class{sendN=0;recvN=0;sq=Promise.resolve();rq=Promise.resolve();sendKey;recvKey;sendDir;recvDir;constructor(e,r,n,s){this.sendKey=e,this.recvKey=r,this.sendDir=n,this.recvDir=s}seal(e){let r=++this.sendN,n=this.sq.then(async()=>{let s=await N.encrypt({name:"AES-GCM",iv:ns(r),additionalData:this.sendDir},this.sendKey,At.encode(JSON.stringify(e)));return{n:r,c:G(new Uint8Array(s))}});return this.sq=n.catch(()=>{}),n}open(e){let r=this.rq.then(async()=>{let{n,c:s}=e;if(typeof n!="number"||!Number.isSafeInteger(n)||n<=this.recvN||typeof s!="string"||s.length>dl)return null;try{let i=await N.decrypt({name:"AES-GCM",iv:ns(n),additionalData:this.recvDir},this.recvKey,z(s)),o=JSON.parse(ul.decode(i));return!o||typeof o!="object"||Array.isArray(o)?null:(this.recvN=n,o)}catch{return null}});return this.rq=r.catch(()=>{}),r}};function ns(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t)),e}async function ml(t,e){let r=_r(At.encode(hl),t.appPub,t.agentPub,t.ephA,t.ephB),n=await gl(_r(t.ss,t.ee),_r(t.nonceA,t.nonceB),r,64),s=await N.importKey("raw",n.slice(0,32),"AES-GCM",!1,["encrypt","decrypt"]),i=await N.importKey("raw",n.slice(32),"AES-GCM",!1,["encrypt","decrypt"]);return e==="app"?new It(s,i,ts,rs):new It(i,s,rs,ts)}var _l=t=>globalThis.crypto.getRandomValues(new Uint8Array(t));async function os(t,e,r){if(!Qn(e.pub)||!Qn(e.eph)||typeof e.nonce!="string")return null;let n=z(e.pub);if(!r(n))return null;let s=z(e.nonce);if(s.length!==16)return null;let i=z(e.eph),o=await Ze(!1),a=_l(16),l=await es(t.priv,n),c=await es(o.priv,i),f=await ml({ss:l,ee:c,appPub:n,agentPub:t.pub,ephA:i,ephB:o.pub,nonceA:s,nonceB:a},"agent");return{accept:{eph:G(o.pub),nonce:G(a)},channel:f,appPub:n}}var j={frameBytes:256*1024,cols:{min:10,max:500},rows:{min:4,max:200},scrollbackBytes:256*1024,fileViewBytes:96*1024};function Ae(t,e){let r=Math.round(Number(t)),n=Math.round(Number(e));return{cols:Math.min(j.cols.max,Math.max(j.cols.min,Number.isFinite(r)?r:80)),rows:Math.min(j.rows.max,Math.max(j.rows.min,Number.isFinite(n)?n:24))}}import{existsSync as yl,statSync as wl}from"node:fs";import{delimiter as bl,extname as El,join as Sl}from"node:path";var xl={claude:{label:"Claude Code",command:"claude"},codex:{label:"Codex",command:"codex"},gemini:{label:"Gemini CLI",command:"gemini"},opencode:{label:"OpenCode",command:"opencode"},aider:{label:"Aider",command:"aider"},goose:{label:"Goose",command:"goose"}},Xe="shell",Bt=/^[a-z0-9][a-z0-9_-]{0,23}$/;function Cl(){return process.platform==="win32"?{label:"Terminal",command:"powershell.exe"}:{label:"Terminal",command:process.env.SHELL||"/bin/bash"}}function oe(t,e){let r={...xl};for(let[n,s]of Object.entries(t.harnesses??{}))Bt.test(n)&&n!==Xe&&(r[n]={...r[n],...s});e&&(r[Xe]=Cl());for(let n of Object.keys(r))r[n].disabled&&delete r[n];return r}function as(t,e=process.env){let r=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[],s=t.includes("/")||t.includes("\\")?[""]:(e.PATH??e.Path??"").split(bl).filter(Boolean);for(let i of s){let o=i?Sl(i,t):t,a=process.platform==="win32"?El(t)?[""]:r:[""];for(let l of a){let c=o+l;try{if(yl(c)&&wl(c).isFile())return c}catch{}}}return null}function Qe(t){return Object.entries(t).map(([e,r])=>({id:e,label:r.label??e,available:as(r.command)!==null}))}function Lt(t){let e=as(t.command);if(!e)return null;let r=t.args??[];return process.platform==="win32"&&/\.(cmd|bat)$/i.test(e)?{file:process.env.COMSPEC||"cmd.exe",args:["/d","/s","/c",e,...r]}:{file:e,args:r}}import{execFile as Tl}from"node:child_process";var Ot=(t,e)=>new Promise(r=>Tl(t,e,{timeout:4e3,windowsHide:!0,maxBuffer:4*1024*1024},(n,s)=>r(n?"":String(s)))),wr=new Set(["*","0.0.0.0","127.0.0.1","[::]","[::1]","::","::1","localhost"]),vl=new Set(["system","svchost.exe","lsass.exe","services.exe","wininit.exe","spoolsv.exe","system idle process"]);function kl(t){let e=[];for(let r of t.split(/\r?\n/)){let n=/^\s*TCP\s+(\S+):(\d+)\s+\S+\s+LISTENING\s+(\d+)/i.exec(r);n&&wr.has(n[1])&&e.push({port:Number(n[2]),pid:Number(n[3])})}return e}function Il(t){let e=new Map;for(let r of t.split(/\r?\n/)){let n=/^"([^"]+)","(\d+)"/.exec(r);n&&e.set(Number(n[2]),n[1])}return e}function Al(t){let e=[],r="";for(let n of t.split(/\r?\n/))if(n.startsWith("c"))r=n.slice(1);else if(n.startsWith("n")){let s=n.lastIndexOf(":");s>0&&wr.has(n.slice(1,s))&&e.push({port:Number(n.slice(s+1)),process:r})}return e}function Pl(t){let e=[];for(let r of t.split(/\r?\n/)){let n=r.trim().split(/\s+/);if(n[0]!=="LISTEN"||n.length<5)continue;let s=n[3],i=s.lastIndexOf(":");i<0||!wr.has(s.slice(0,i))||e.push({port:Number(s.slice(i+1)),process:/users:\(\("([^"]+)"/.exec(r)?.[1]??""})}return e}function Bl(t){let e=new Map;for(let r of t)!Number.isInteger(r.port)||r.port<1024||r.port>65535||process.platform==="win32"&&r.port>=49152||(!e.has(r.port)||!e.get(r.port).process&&r.process)&&e.set(r.port,{port:r.port,process:r.process.slice(0,60)});return[...e.values()].sort((r,n)=>r.port-n.port).slice(0,40)}var et=null;async function br(){if(et&&Date.now()-et.at<2e3)return et.list;let t=[];if(process.platform==="win32"){let[e,r]=await Promise.all([Ot("netstat",["-ano","-p","tcp"]),Ot("tasklist",["/FO","CSV","/NH"])]),n=Il(r);t=kl(e).map(s=>({port:s.port,process:n.get(s.pid)??""})).filter(s=>!vl.has(s.process.toLowerCase())).map(s=>({port:s.port,process:s.process.replace(/\.exe$/i,"")}))}else t=Al(await Ot("lsof",["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"])),t.length===0&&(t=Pl(await Ot("ss",["-ltnpH"])));return et={at:Date.now(),list:Bl(t)},et.list}import{request as Ll}from"node:http";import{createBrotliDecompress as Ol,createGunzip as Rl,createInflate as Nl}from"node:zlib";var Rt=90*1024,Ml=32*1024*1024,Ul=3e4,ls=new Set(["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"]),Dl=/^(accept|accept-language|authorization|cache-control|content-type|if-[a-z-]+|pragma|range|user-agent|x-[a-z0-9-]+)$/i,ql=new Set(["connection","keep-alive","transfer-encoding","content-length","content-encoding","set-cookie","set-cookie2","x-frame-options","content-security-policy","content-security-policy-report-only","strict-transport-security","upgrade","trailer","te"]);function Fl(t,e,r){let n={};for(let[s,i]of Object.entries(t))typeof i=="string"&&i.length<4096&&Dl.test(s)&&(n[s.toLowerCase()]=i);return n.host=`localhost:${e}`,n["accept-encoding"]="gzip, deflate, br",r>0&&(n["content-length"]=String(r)),n}function Hl(t){let e={};for(let[r,n]of Object.entries(t))ql.has(r.toLowerCase())||n===void 0||(e[r.toLowerCase()]=Array.isArray(n)?n.join(", "):n);return e}var Er=[],Sr=!1;function Nt(t){if(Er.push(t),Sr)return;Sr=!0;let e=()=>{Er.shift()?.(),Er.length?setTimeout(e,6):Sr=!1};setTimeout(e,0)}function cs(t,e,r,n,s){let i=!1,o=()=>{i||(i=!0,n())},a=c=>{i||(Nt(()=>r({t:"error",code:"proxy_failed",message:c,reqId:e.reqId})),o())},l=Ll({host:t,port:e.port,method:e.method,path:e.path,headers:Fl(e.headers,e.port,e.body?.length??0),timeout:Ul},c=>{let f=String(c.headers["content-encoding"]??"").toLowerCase(),u=f==="gzip"||f==="x-gzip"?c.pipe(Rl()):f==="deflate"?c.pipe(Nl()):f==="br"?c.pipe(Ol()):c;Nt(()=>r({t:"http.head",reqId:e.reqId,status:c.statusCode??502,headers:Hl(c.headers)}));let h=[],d=0,m=0,p=_=>{let y=Buffer.concat(h);h=[],d=0,Nt(()=>r({t:"http.chunk",reqId:e.reqId,data:y.toString("base64"),last:_}))};u.on("data",_=>{if(m+=_.length,m>Ml)return c.destroy(),a("That response is too large to preview.");for(h.push(_),d+=_.length;d>=Rt;){let y=Buffer.concat(h);h=[y.subarray(Rt)],d=y.length-Rt,Nt(()=>r({t:"http.chunk",reqId:e.reqId,data:y.subarray(0,Rt).toString("base64"),last:!1}))}}),u.on("end",()=>{i||(p(!0),o())}),u.on("error",()=>a("The page could not be read."))});l.on("timeout",()=>{l.destroy(),a("The server did not answer in time.")}),l.on("error",c=>{if(s&&c.code==="ECONNREFUSED")return cs("::1",e,r,n,!1);a(c.code==="ECONNREFUSED"?"Nothing is listening on that port any more.":"Could not reach that server.")}),e.body&&e.body.length>0&&l.write(e.body),l.end()}function fs(t,e,r){cs("127.0.0.1",t,e,r,!0)}import{closeSync as zl,lstatSync as hs,openSync as Wl,readSync as $l,readdirSync as ds,realpathSync as Gl,renameSync as ps,rmdirSync as jl,statSync as Pe,unlinkSync as gs,writeFileSync as Yl}from"node:fs";import{homedir as Vl}from"node:os";import{basename as xr,dirname as Cr,isAbsolute as Tr,join as vr,resolve as Mt,sep as us}from"node:path";var Be=t=>process.platform==="win32"||process.platform==="darwin"?t.toLowerCase():t;function Y(t){try{return Gl(t)}catch{return null}}function Le(t){return t==="~"||t.startsWith("~/")||t.startsWith("~\\")?Mt(Vl(),t.slice(2)):Mt(t)}function Ut(t,e){if(!Tr(e))return null;let r=Y(e);if(!r)return null;try{if(!Pe(r).isDirectory())return null}catch{return null}return kr(t,r)?r:null}function kr(t,e){let r=Be(e);for(let n of t){let s=Be(n);if(r===s||r.startsWith(s.endsWith(us)?s:s+us))return!0}return!1}function Ir(t,e){if(!Tr(e))return null;let r=Y(e);if(!r)return null;try{if(!Pe(r).isFile())return null}catch{return null}return kr(t,r)?r:null}var Kl=/^(id_(rsa|dsa|ecdsa|ed25519)|\.env.*|\.npmrc|\.netrc|credentials|.*\.(pem|key|p12|pfx|keystore|kdbx))$/i,tt=t=>Kl.test(xr(t));function ms(t,e){return t.some(r=>Be(r)===Be(e))}function _s(t){try{return ds(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!e.name.startsWith(".")&&e.name!=="node_modules").map(e=>e.name).sort((e,r)=>e.localeCompare(r)).slice(0,300)}catch{return[]}}function ys(t){let e=[],r=[];try{for(let s of ds(t,{withFileTypes:!0}))if(!(s.name.startsWith(".")||s.name==="node_modules")){if(s.isDirectory())e.push(s.name);else if(s.isFile()){let i=0;try{i=Pe(Mt(t,s.name)).size}catch{}r.push({name:s.name,size:i})}}}catch{}let n=(s,i)=>(typeof s=="string"?s:s.name).localeCompare(typeof i=="string"?i:i.name);return{dirs:e.sort(n).slice(0,300),files:r.sort(n).slice(0,500)}}function ws(t,e){let r=Pe(t),n=r.size,s=Math.floor(r.mtimeMs),i=Wl(t,"r");try{let o=Buffer.alloc(Math.min(n,e)),a=$l(i,o,0,o.length,0),l=o.subarray(0,a);if(l.includes(0))return{size:n,mtime:s,text:null,binary:!0,truncated:!1};let c=l.toString("utf8"),f=n>a;return!f&&!Buffer.from(c,"utf8").equals(l)?{size:n,mtime:s,text:null,binary:!0,truncated:!1}:{size:n,mtime:s,text:c,binary:!1,truncated:f}}finally{zl(i)}}function bs(t,e,r){let n=Pe(t);if(Math.floor(n.mtimeMs)!==Math.floor(r))throw Object.assign(new Error("The file changed on the workspace."),{code:"conflict"});let s=vr(Cr(t),`.${xr(t)}.amplibee-${process.pid}.tmp`);Yl(s,e,{mode:n.mode&511});try{ps(s,t)}catch(o){try{gs(s)}catch{}throw o}let i=Pe(t);return{size:i.size,mtime:Math.floor(i.mtimeMs)}}function Es(t,e){if(!Tr(e))return null;let r=Y(Cr(Mt(e)));if(!r||!kr(t,r))return null;let n=vr(r,xr(e)),s;try{s=hs(n)}catch{return null}return!s.isSymbolicLink()&&ms(t,Y(n)??n)?null:{entry:n,folder:r,isDir:s.isDirectory()}}var Jl=/[\\/:*?"<>|\0]/;function Ss(t,e,r){let n=Es(t,e);if(!n)throw Object.assign(new Error("outside"),{code:"bad_file"});if(!r||r.length>200||r==="."||r===".."||Jl.test(r)||r!==r.trim())throw Object.assign(new Error("bad name"),{code:"bad_name"});let s=vr(n.folder,r);try{if(hs(s),Be(s)!==Be(n.entry))throw Object.assign(new Error("exists"),{code:"exists"})}catch(i){if(i.code==="exists")throw i}return ps(n.entry,s),s}function xs(t,e){let r=Es(t,e);if(!r)throw Object.assign(new Error("outside"),{code:"bad_file"});if(r.isDir){try{jl(r.entry)}catch{throw Object.assign(new Error("not empty"),{code:"not_empty"})}return}gs(r.entry)}var Ar=(t,e)=>ms(t,e)?null:Cr(e);var Dt=(t,e)=>typeof t=="string"&&t.length>0&&t.length<=e?t:null,Zl=64*1024,Xl=10,Ql=200,ec=12,Cs=16*1024,qt=class{constructor(e){this.o=e;this.roots=e.roots.map(r=>Y(Le(r))??Le(r)),e.manager.onChange=()=>this.o.send({t:"sessions",sessions:e.manager.list()})}roots;subs=new Map;proxying=0;proxyWaiting=[];pending=new Map;host(){return{name:this.o.cfg.name,platform:process.platform,agentVersion:this.o.version,roots:this.roots,harnesses:Qe(oe(this.o.cfg,this.o.allowShell))}}connected(){this.subs.clear()}watch(e){e.onData(r=>{let n=this.subs.get(e.id);if(!n||n.size===0)return;let s=this.pending.get(e.id);s?s.buf+=r:this.pending.set(e.id,{buf:r,timer:setTimeout(()=>this.flush(e.id),ec)})}),e.onExit(r=>{this.flush(e.id);for(let n of this.subs.get(e.id)??[])this.o.send({t:"session.exit",id:e.id,code:r,cid:n})})}flush(e){let r=this.pending.get(e);if(r){clearTimeout(r.timer),this.pending.delete(e);for(let n of this.subs.get(e)??[])this.output(e,n,r.buf,!1)}}output(e,r,n,s){if(n.length<=Cs)return this.o.send({t:"session.output",id:e,data:n,replay:s||void 0,cid:r});for(let i=0;i<n.length;){let o=Math.min(i+Cs,n.length),a=n.charCodeAt(o-1);o<n.length&&a>=55296&&a<=56319&&o--,this.o.send({t:"session.output",id:e,data:n.slice(i,o),replay:s&&i===0?!0:void 0,cid:r}),i=o}}subscribe(e,r){let n=this.subs.get(e);n||this.subs.set(e,n=new Set),n.add(r)}handle(e){let r=typeof e.cid=="string"?e.cid:void 0,n=i=>this.o.send({...i,cid:r}),s=(i,o)=>n({t:"error",code:i,message:o,reqId:typeof e.reqId=="string"?e.reqId:void 0});if(r)try{this.dispatch(e,r,n,s)}catch(i){s("failed",i instanceof Error?i.message:"Something went wrong on the workspace.")}}dispatch(e,r,n,s){let i=this.o.manager,o=()=>{let a=Dt(e.id,40),l=a?i.get(a):void 0;return l||s("no_session","That session no longer exists."),l??null};switch(e.t){case"app.left":for(let a of this.subs.values())a.delete(r);return;case"host.get":return n({t:"host",host:this.host()});case"sessions.list":return n({t:"sessions",sessions:i.list()});case"session.start":{let a=Dt(e.harness,24),l=a?oe(this.o.cfg,this.o.allowShell)[a]:void 0;if(!a||!l)return s("unknown_harness","That agent is not enabled on this workspace.");let c=Lt(l);if(!c)return s("not_installed",`"${l.command}" is not installed on this workspace.`);let f=e.cwd===void 0?this.roots[0]:Ut(this.roots,String(e.cwd));if(!f)return s("bad_folder","That folder is outside the folders this workspace shares.");let{cols:u,rows:h}=Ae(e.cols,e.rows),d=i.start({harness:a,title:l.label??a,file:c.file,args:c.args,cwd:f,cols:u,rows:h});return this.watch(d),this.subscribe(d.id,r),n({t:"session.started",session:d.info,reqId:typeof e.reqId=="string"?e.reqId:void 0})}case"session.attach":{let a=o();if(!a)return;if(this.subscribe(a.id,r),!a.opts.local&&e.cols!==void 0){let l=Ae(e.cols,e.rows);a.resize(l.cols,l.rows)}this.output(a.id,r,a.scrollback(),!0),a.running||n({t:"session.exit",id:a.id,code:a.exitCode});return}case"session.input":{let a=o(),l=typeof e.data=="string"&&e.data.length<=Zl?e.data:null;a&&l!==null&&a.write(l);return}case"session.resize":{let a=o();a&&!a.opts.local&&a.resize(Number(e.cols),Number(e.rows));return}case"session.kill":return o()?.kill();case"session.remove":{let a=Dt(e.id,40);a&&(i.remove(a),this.subs.delete(a));return}case"dir.list":{let a=e.path===void 0||e.path===""?this.roots[0]:Ut(this.roots,String(e.path));return a?n({t:"dirs",path:a,parent:Ar(this.roots,a),entries:_s(a),reqId:typeof e.reqId=="string"?e.reqId:void 0}):s("bad_folder","That folder is outside the folders this workspace shares.")}case"fs.list":{let a=e.path===void 0||e.path===""?this.roots[0]:Ut(this.roots,String(e.path));if(!a)return s("bad_folder","That folder is outside the folders this workspace shares.");let{dirs:l,files:c}=ys(a);return n({t:"fs.entries",path:a,parent:Ar(this.roots,a),dirs:l,files:c,reqId:typeof e.reqId=="string"?e.reqId:void 0})}case"fs.read":{let a=Ir(this.roots,String(e.path??""));if(!a)return s("bad_file","That file is outside the folders this workspace shares.");if(tt(a))return s("secret_file","Files that usually hold secrets (keys, .env) are never shown here.");let l=ws(a,j.fileViewBytes);return n({t:"fs.file",path:a,...l,reqId:typeof e.reqId=="string"?e.reqId:void 0})}case"fs.write":{let a=Ir(this.roots,String(e.path??""));if(!a)return s("bad_file","That file is outside the folders this workspace shares.");if(tt(a))return s("secret_file","Files that usually hold secrets (keys, .env) are never edited here.");if(typeof e.text!="string"||Buffer.byteLength(e.text,"utf8")>j.fileViewBytes)return s("too_large",`Files can be edited here up to ${Math.round(j.fileViewBytes/1024)} KB.`);try{let l=bs(a,e.text,Number(e.mtime));return n({t:"fs.saved",path:a,...l,reqId:typeof e.reqId=="string"?e.reqId:void 0})}catch(l){return l.code==="conflict"?s("conflict","This file changed on the workspace since you opened it. Reload it to see the new version."):s("write_failed","Could not save the file. It may be read-only on the workspace.")}}case"fs.rename":{let a=String(e.path??""),l=typeof e.name=="string"?e.name:"";if(tt(a))return s("secret_file","Files that usually hold secrets (keys, .env) are never changed here.");try{let c=Ss(this.roots,a,l);return n({t:"fs.done",op:"rename",path:a,newPath:c,reqId:typeof e.reqId=="string"?e.reqId:void 0})}catch(c){let f=c.code;return f==="bad_file"?s("bad_file","That is outside the folders this workspace shares."):f==="bad_name"?s("bad_name",'Use a plain name: no slashes and none of : * ? " < > |'):f==="exists"?s("exists","Something with that name already exists here."):s("failed","Could not rename it.")}}case"fs.remove":{let a=String(e.path??"");if(tt(a))return s("secret_file","Files that usually hold secrets (keys, .env) are never changed here.");try{return xs(this.roots,a),n({t:"fs.done",op:"remove",path:a,reqId:typeof e.reqId=="string"?e.reqId:void 0})}catch(l){let c=l.code;return c==="bad_file"?s("bad_file","That is outside the folders this workspace shares."):c==="not_empty"?s("not_empty","Only empty folders can be removed here. Delete what is inside first."):s("failed","Could not delete it.")}}case"ports.list":{(this.o.ports??br)().then(a=>n({t:"ports",ports:a,reqId:typeof e.reqId=="string"?e.reqId:void 0}));return}case"http.fetch":{let a=Dt(e.reqId,80),l=Number(e.port),c=String(e.method??"").toUpperCase(),f=typeof e.path=="string"?e.path:"";if(!a)return s("bad_request","Missing request id.");if(!Number.isInteger(l)||!ls.has(c)||!/^\/[^\s]*$/.test(f)||f.length>4e3)return s("bad_request","That request is not allowed.");let u=typeof e.body=="string"&&e.body.length>0?Buffer.from(e.body,"base64"):null;if(u&&u.length>150*1024)return s("too_large","That request body is too large for the preview.");if(this.proxyWaiting.length>=Ql)return s("busy","Too many requests at once. Try again.");let h=e.headers&&typeof e.headers=="object"?e.headers:{},d=()=>{this.proxying++;let m=()=>{this.proxying--,this.proxyWaiting.shift()?.()};(this.o.ports??br)().then(p=>{if(!p.some(_=>_.port===l))return m(),n({t:"error",code:"no_server",message:"Nothing is listening on that port.",reqId:a});fs({reqId:a,port:l,method:c,path:f,headers:h,body:u},n,m)},m)};this.proxying>=Xl?this.proxyWaiting.push(d):d();return}default:return s("unknown_message","Unknown message.")}}};var Ts=20;async function Ft(t){if(t.identity)try{return await ss(t.identity)}catch{}let e=await Ze(!0);return t.identity=await Pt(e),t.apps=[],X(t),e}var rt={at:0,keys:[]};function vs(){return Date.now()-rt.at>2e3&&(rt={at:Date.now(),keys:(ie()?.apps??[]).map(t=>t.pub)}),rt.keys}async function Pr(t){z(t);let e=ie();if(!e)throw new Error("This workspace is not logged in.");let r=(e.apps??[]).filter(s=>s.pub!==t);if(r.length>=Ts)throw new Error(`You can link up to ${Ts} browsers. Remove one with "amplibee apps remove <fingerprint>".`);let n={pub:t,fingerprint:await Q(z(t)),addedAt:new Date().toISOString()};return e.apps=[...r,n],X(e),rt={at:0,keys:[]},n}function ks(t){let e=ie();if(!e)return 0;let r=s=>s.toUpperCase().replace(/[^A-Z]/g,""),n=e.apps??[];return e.apps=n.filter(s=>r(s.fingerprint)!==r(t)),X(e),rt={at:0,keys:[]},n.length-e.apps.length}var Do=Z(Uo(),1);import{createHash as _u,randomBytes as yu}from"node:crypto";import{spawn as wu}from"node:child_process";import{hostname as bu,platform as Eu,release as Su}from"node:os";import{createInterface as xu}from"node:readline/promises";async function Sn(t,e,r,n={}){let s;try{s=await fetch(t+e,{method:"POST",headers:{"content-type":"application/json",...n},body:JSON.stringify(r),signal:AbortSignal.timeout(2e4)})}catch{throw new Error(`Could not reach ${t}. Check your internet connection.`)}let i=null;try{i=await s.json()}catch{}if(!s.ok||!i?.ok||i.data===null)throw Object.assign(new Error(i?.error?.message??`The server answered with status ${s.status}.`),{status:s.status,code:i?.error?.code});return i.data}function qo(t){try{let[e,r]=process.platform==="win32"?["cmd",["/c","start","",t]]:process.platform==="darwin"?["open",[t]]:["xdg-open",[t]];wu(e,r,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}async function Fo(t,e){let r=Date.now()+e.expires_in*1e3;for(;Date.now()<r;){await new Promise(n=>setTimeout(n,e.interval*1e3));try{let n=await Sn(t,"/devices/pair/poll",{device_code:e.device_code});if(n.status==="approved")return n}catch(n){let s=n.status;if(s===410)break;if(s&&s<500&&s!==429)throw n}}throw new Error("The code expired. Run the command again.")}async function Cu(t){let e=xu({input:process.stdin,output:process.stdout});try{return await e.question(t)}finally{e.close()}}async function Ho(t,e,r){let n;try{n=await Q(z(t))}catch{return r(" The app sent a key that is not valid, so nothing was linked."),!1}if(r(""),r(" The app approved. Check that it shows the same fingerprint for this browser:"),r(""),r(` ${n}`),r(""),e.trustApp){let i=is(e.trustApp,n);return r(i?" It matches --trust-app.":" It does NOT match --trust-app, so the browser was not linked."),i}if(!process.stdin.isTTY)return r(" There is nobody here to confirm it. Run this in a terminal, or pass --trust-app <fingerprint>."),!1;let s=await Cu(' Type "yes" only if it is exactly the same: ');return/^y(es)?$/i.test(s.trim())}async function zo(t,e,r,n){n(""),n(` ${r}`),n(` ${t.verification_url}`);try{let s=await Do.default.toString(t.verification_url,{type:"utf8",errorCorrectionLevel:"L"});n("");for(let i of s.split(/\r?\n/))n(` ${i}`)}catch{}n(""),n(` Code: ${t.user_code}`),n(` Fingerprint: ${e}`),n(""),n(" The app shows this fingerprint too. Continue only if they are the same."),n(` Waiting for approval (the code works for ${Math.round(t.expires_in/60)} minutes)...`)}async function Wo(t){let e=t.log??console.log,r=yu(32).toString("hex"),n=(t.name||bu()||"my workspace").slice(0,60),s=await Ze(!0),i=await Sn(t.apiUrl,"/devices/pair",{name:n,platform:`${Eu()} ${Su()}`.slice(0,40),agent_version:t.version,token_hash:_u("sha256").update(r).digest("hex"),agent_pub:G(s.pub)});await zo(i,await Q(s.pub),"Scan the QR code with your phone, or open this page and confirm the code:",e),t.openBrowser&&qo(i.verification_url);let o=await Fo(t.apiUrl,i),a={apiUrl:t.apiUrl,deviceId:o.device_id,secret:r,name:n,identity:await Pt(s),apps:[]};X(a);let l=await Ho(o.app_pub,t,e);return l&&await Pr(o.app_pub),{cfg:a,linked:l}}async function $o(t,e){let r=e.log??console.log,n=await Ft(t),s=await Sn(t.apiUrl,"/devices/link",{agent_pub:G(n.pub),agent_version:e.version},{authorization:`Bearer ${t.secret}`});await zo(s,await Q(n.pub),'Open the workspace in the Amplibee app and choose "Link this browser", or scan the QR code:',r),e.openBrowser&&qo(s.verification_url);let i=await Fo(t.apiUrl,s),o=await Ho(i.app_pub,{...e,apiUrl:t.apiUrl},r);return o&&await Pr(i.app_pub),o}var Kh=Z(qa(),1),Jh=Z(ar(),1),Zh=Z($e(),1),Xh=Z(Nn(),1),Qh=Z(Dn(),1),ed=Z(Wn(),1),Va=Z(fr(),1),td=Z(Ya(),1);var Gn=Va.default;var Tt=class extends Error{};function rd(t){return t.replace(/^http/,"ws").replace(/\/$/,"")+"/relay/agent"}var hr=class{constructor(e){this.o=e;this.fatal=new Promise(r=>this.die=r)}ws=null;attempt=0;stopped=!1;watchdog;retry;fatal;die;get connected(){return this.ws?.readyState===Gn.OPEN}start(){this.open()}stop(){this.stopped=!0,clearTimeout(this.retry),clearInterval(this.watchdog),this.ws?.close(1e3)}send(e){return this.connected?(this.ws.send(JSON.stringify(e)),!0):!1}open(){if(this.stopped)return;let e=new Gn(rd(this.o.apiUrl),{headers:{authorization:`Bearer ${this.o.secret}`,"x-amplibee-agent":this.o.version},handshakeTimeout:15e3,maxPayload:512*1024});this.ws=e;let r=Date.now();e.on("open",()=>{this.attempt=0,r=Date.now(),this.o.log("connected to Amplibee"),this.o.onUp()}),e.on("ping",()=>r=Date.now()),e.on("message",n=>{r=Date.now();try{let s=JSON.parse(n.toString());s&&typeof s.t=="string"&&this.o.onMessage(s)}catch{}}),e.on("unexpected-response",(n,s)=>{s.resume(),s.statusCode===401?this.die(new Tt('This workspace was removed from your account (or its login is no longer valid). Run "amplibee login" again.')):this.o.log(`relay answered ${s.statusCode}`),e.terminate()}),e.on("error",n=>this.o.log(`connection problem: ${n.message}`)),e.on("close",n=>{if(clearInterval(this.watchdog),this.o.onDown(),n===4001)return this.die(new Tt('This workspace was removed from your account. Run "amplibee login" to connect it again.'));if(n===4e3)return this.die(new Tt("Another amplibee process for this workspace connected, so this one stopped. Run only one at a time."));this.schedule()}),clearInterval(this.watchdog),this.watchdog=setInterval(()=>{Date.now()-r>75e3&&e.terminate()},1e4)}schedule(){if(this.stopped)return;let e=Math.min(3e4,1e3*2**Math.min(this.attempt++,5)),r=e/2+Math.random()*(e/2);this.o.log(`reconnecting in ${Math.round(r/1e3)}s`),this.retry=setTimeout(()=>this.open(),r)}};var nd=32,dr=class{chans=new Map;o;constructor(e){this.o=e}reset(){this.chans.clear()}get channels(){return this.chans.size}async fromRelay(e){let r=typeof e.cid=="string"&&e.cid.length>0&&e.cid.length<=32?e.cid:null;if(r){if(e.t==="app.left")return this.chans.delete(r),this.o.deliver({t:"app.left",cid:r});if(e.t==="e2e.hello")return this.hello(r,e);if(e.t==="e2e.data")return this.data(r,{n:e.n,c:e.c})}}async hello(e,r){if(!this.chans.has(e)&&this.chans.size>=nd)return;let n=null;try{let s=this.o.trusted();n=await os(this.o.identity,r,i=>s.includes(G(i)))}catch{}if(!n)return this.o.transmit({t:"e2e.reject",cid:e,code:"not_linked"});this.chans.set(e,{chan:n.channel,app:G(n.appPub)}),this.o.transmit({t:"e2e.accept",cid:e,...n.accept}),this.sendTo(e,{t:"secure"})}async data(e,r){let n=this.chans.get(e);if(!n)return;if(!this.o.trusted().includes(n.app))return this.chans.delete(e),this.o.transmit({t:"e2e.reject",cid:e,code:"not_linked"});let s=await n.chan.open(r);s&&typeof s.t=="string"&&s.t.length<=40&&this.o.deliver({...s,t:s.t,cid:e})}send(e){let{cid:r,...n}=e;if(r)this.sendTo(r,n);else for(let s of[...this.chans.keys()])this.sendTo(s,n)}sendTo(e,r){let n=this.chans.get(e);n&&n.chan.seal(r).then(s=>this.o.transmit({t:"e2e.data",cid:e,...s})).catch(()=>{})}};import{randomBytes as sd}from"node:crypto";var Ka=8,id=24,jn=class{constructor(e,r){this.pty=e;this.opts=r;this.cols=r.cols,this.rows=r.rows,e.onData(n=>{this.keep(n);for(let s of this.listeners)s(n)}),e.onExit(n=>{this.running=!1,this.exitCode=n.exitCode;for(let s of this.exitListeners)s(n.exitCode)})}id=sd(6).toString("hex");startedAt=Date.now();running=!0;exitCode=null;cols;rows;chunks=[];size=0;listeners=new Set;exitListeners=new Set;get info(){return{id:this.id,harness:this.opts.harness,title:this.opts.title,cwd:this.opts.cwd,cols:this.cols,rows:this.rows,startedAt:this.startedAt,running:this.running,exitCode:this.exitCode,local:!!this.opts.local}}keep(e){for(this.chunks.push(e),this.size+=e.length;this.size>j.scrollbackBytes&&this.chunks.length>1;)this.size-=this.chunks.shift().length}scrollback(){return this.chunks.join("")}onData(e){return this.listeners.add(e),()=>this.listeners.delete(e)}onExit(e){return this.exitListeners.add(e),()=>this.exitListeners.delete(e)}write(e){this.running&&this.pty.write(e)}resize(e,r){let n=Ae(e,r);if(this.cols=n.cols,this.rows=n.rows,this.running)try{this.pty.resize(n.cols,n.rows)}catch{}}kill(){this.running&&this.pty.kill()}},vt=class{constructor(e){this.spawn=e}sessions=new Map;onChange=()=>{};list(){return[...this.sessions.values()].map(e=>e.info)}get(e){return this.sessions.get(e)}runningCount(){return[...this.sessions.values()].filter(e=>e.running).length}start(e){if(this.runningCount()>=Ka)throw new Error(`At most ${Ka} sessions can run at once. Close one first.`);let r=Ae(e.cols,e.rows),n={};for(let[o,a]of Object.entries(process.env))typeof a=="string"&&(n[o]=a);n.TERM="xterm-256color",n.COLORTERM="truecolor",n.AMPLIBEE_SESSION="1";let s=this.spawn(e.file,e.args,{cwd:e.cwd,cols:r.cols,rows:r.rows,env:n}),i=new jn(s,{...e,...r});return this.sessions.set(i.id,i),i.onExit(()=>this.onChange()),this.trim(),this.onChange(),i}remove(e){let r=this.sessions.get(e);return r?(r.kill(),this.sessions.delete(e),this.onChange(),!0):!1}killAll(){for(let e of this.sessions.values())e.kill()}trim(){let e=[...this.sessions.values()].filter(r=>!r.running);for(let r of e.slice(0,Math.max(0,this.sessions.size-id)))this.sessions.delete(r.id)}};async function Yn(){let t=await import("@lydell/node-pty");return(e,r,n)=>{let s=t.spawn(e,r,{name:"xterm-256color",cols:n.cols,rows:n.rows,cwd:n.cwd,env:n.env});return{onData:i=>void s.onData(i),onExit:i=>void s.onExit(i),write:i=>s.write(i),resize:(i,o)=>s.resize(i,o),kill:()=>s.kill()}}}var me="0.1.2",ad=`amplibee ${me}: steer Claude Code, Codex or any terminal agent from your phone.
|
|
22
22
|
|
|
23
23
|
Usage
|
|
24
24
|
amplibee login [--name "My laptop"] [--api URL] [--no-open]
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "amplibee",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Connect this workspace to Amplibee so you can steer Claude Code, Codex or any terminal agent from your phone.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"publishConfig": { "access": "public" },
|