#!/usr/bin/env python3
"""Transparent recorder; delay mode only buffers genuine terminal stderr until end_turn."""
import os,sys,subprocess,threading,json,time,signal
from pathlib import Path
root=Path(__file__).resolve().parent.parent
mode=(root/'transport-mode').read_text().strip() if (root/'transport-mode').exists() else 'observe'
out=root/'transport';out.mkdir(exist_ok=True)
log=open(out/(str(time.time_ns())+'.jsonl'),'a',buffering=1)
lock=threading.Lock();done=threading.Event();requests={}
def note(kind,**data):
 with lock: log.write(json.dumps(dict(t=time.time(),kind=kind,**data))+'\n')
args=sys.argv[1:]
if mode in ('delay','gate') and '--alsologtostderr' not in args: args=args+['--alsologtostderr']
p=subprocess.Popen([str(root/'runtime/agy_acp_server.par'),*args],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
note('spawn',pid=p.pid,args=args,mode=mode)
def inbound():
 for line in sys.stdin.buffer:
  try:
   m=json.loads(line)
   if 'method' in m:
    requests[str(m.get('id'))]=m['method']
    params=m.get('params',{})
    note('request',method=m['method'],sessionId=params.get('sessionId'))
  except Exception: pass
  try: p.stdin.write(line);p.stdin.flush()
  except BrokenPipeError: break
def stdout():
 for line in p.stdout:
  try:
   m=json.loads(line);r=m.get('result',{})
   if isinstance(r,dict) and 'stopReason' in r:
    note('prompt-response',stopReason=r['stopReason']);done.set()
   if isinstance(r,dict) and 'sessionId' in r:note('session-result',method=requests.get(str(m.get('id'))),sessionId=r['sessionId'])
   if 'error' in m:note('rpc-error',method=requests.get(str(m.get('id'))),message=m['error'].get('message'))
  except Exception: pass
  try:sys.stdout.buffer.write(line);sys.stdout.buffer.flush()
  except BrokenPipeError:break
def stderr():
 for line in p.stderr:
  text=line.decode(errors='replace')
  terminal=any(s in text for s in ['harness stderr: Agent run failed:', 'Failed to rebuild agent for session ', 'Agent connection lost for session '])
  if terminal:
   note('native-terminal-record',message=text.strip())
   if mode in ('delay','gate'):
    done.wait(90)
    if mode=='gate':
     while not (root/('release-'+str(p.pid))).exists():time.sleep(0.1)
    else:time.sleep(2)
    note('release-terminal-record',afterEndTurn=done.is_set())
  try:sys.stderr.buffer.write(line);sys.stderr.buffer.flush()
  except BrokenPipeError:break
def stop(sig,frame):
 note('signal',signal=sig)
 if p.poll() is None:p.terminate()
 signal.signal(sig,signal.SIG_DFL)
 os.kill(os.getpid(),sig)
for sig in [signal.SIGTERM,signal.SIGINT]:signal.signal(sig,stop)
for f in [inbound,stdout,stderr]:threading.Thread(target=f,daemon=True).start()
code=p.wait();note('exit',code=code);sys.exit(code)
