#!/usr/bin/env python3
import os,sys,subprocess,json,time,signal,threading,shutil
from pathlib import Path
root=Path(__file__).resolve().parent
p=subprocess.Popen([shutil.which('opencode'),'acp',*sys.argv[1:]],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=sys.stderr)
log=open(root/(str(p.pid)+'.jsonl'),'a',buffering=1)
def note(kind,**args):log.write(json.dumps(dict(t=time.time(),kind=kind,pid=p.pid,**args))+'\n')
note('spawn',args=sys.argv[1:])
def inbound():
 for line in sys.stdin.buffer:
  try:
   m=json.loads(line)
   if 'method' in m:note('request',method=m['method'],sessionId=m.get('params',{}).get('sessionId'))
  except Exception:pass
  try:p.stdin.write(line);p.stdin.flush()
  except BrokenPipeError:break
def outbound():
 for line in p.stdout:
  try:
   m=json.loads(line);r=m.get('result',{})
   if 'error' in m:note('error',error=m['error'])
   if isinstance(r,dict) and 'sessionId' in r:note('session',sessionId=r['sessionId'])
   if isinstance(r,dict) and 'stopReason' in r:note('prompt-response',stopReason=r['stopReason'])
  except Exception:pass
  sys.stdout.buffer.write(line);sys.stdout.buffer.flush()
def stop(sig,frame):
 if p.poll() is None:p.terminate()
 sys.exit(128+sig)
for sig in [signal.SIGTERM,signal.SIGINT]:signal.signal(sig,stop)
threading.Thread(target=inbound,daemon=True).start();reader=threading.Thread(target=outbound,daemon=True);reader.start()
code=p.wait();reader.join();note('exit',code=code);os._exit(code if code>=0 else 128-code)
