import os,sys,subprocess,re,time,json,signal
port=int(sys.argv[1]); cwd=os.path.realpath(sys.argv[2]); label=sys.argv[3]
out=subprocess.check_output(['ss','-H','-ltnp',f'sport = :{port}'],text=True)
root=int(re.search(r'pid=(\d+)',out).group(1));assert os.readlink(f'/proc/{root}/cwd')==cwd+'/apps/server'
ps={};cmd={}
for x in os.listdir('/proc'):
 if x.isdigit():
  try:
   s=open(f'/proc/{x}/stat').read();ps[int(x)]=int(s[s.rfind(')')+2:].split()[1]);cmd[int(x)]=open(f'/proc/{x}/cmdline').read().replace('\0',' ')
  except (OSError,ValueError):pass
children=[]
for pid in ps:
 p=pid
 while p in ps and p!=root:p=ps[p]
 if p==root:children.append(pid)
runtimes=[p for p in children if '/@github/copilot-linux-x64/copilot --acp' in cmd[p]]
def has_sleep(r):
 for child in children:
  if not cmd[child].startswith('sleep 901'):continue
  p=child
  while p in ps and p!=r:p=ps[p]
  if p==r:return True
 return False
runtimes=[r for r in runtimes if has_sleep(r)]
assert len(runtimes)==1,runtimes
runtime=runtimes[0]
print(json.dumps({'side':label,'time':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'serverPid':root,'runtimePid':runtime,'sleepPids':[p for p in children if cmd[p].startswith('sleep 901')],'action':'SIGKILL real Copilot ACP runtime'}),flush=True)
os.kill(runtime,signal.SIGKILL)
time.sleep(3)
print(json.dumps({'side':label,'runtimeGone':not os.path.exists(f'/proc/{runtime}'),'sleepAlive':[p for p in children if cmd[p].startswith('sleep 901') and os.path.exists(f'/proc/{p}')],'idleInhibitorAlive':[p for p in children if 'systemd-inhibit --what=idle:sleep' in cmd[p] and os.path.exists(f'/proc/{p}')]}),flush=True)
