#!/usr/bin/env python3
import os,sys,subprocess,threading,json,pathlib
if '--mode' not in sys.argv:
 os.execv('/usr/local/bin/pi',['pi',*sys.argv[1:]])
root=pathlib.Path(__file__).parent
os.environ['PI_CODING_AGENT_DIR']=str(root/'pi-config')
child=subprocess.Popen(['/usr/local/bin/pi',*sys.argv[1:]],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
log=root/'rpc.jsonl'
def record(value):
 with log.open('a') as f: f.write(json.dumps({'process':os.getpid(),**value})+'\n')
def incoming():
 for line in sys.stdin.buffer:
  try:
   obj=json.loads(line); out={'direction':'T3 → Pi','type':obj.get('type')}
   for k in ['level','provider','modelId']: 
    if k in obj: out[k]=obj[k]
   record(out)
  except: pass
  child.stdin.write(line);child.stdin.flush()
threading.Thread(target=incoming,daemon=True).start()
for line in child.stdout:
 try:
  obj=json.loads(line)
  if obj.get('type')=='message_end' and obj.get('message',{}).get('role')=='assistant':
   m=obj['message'];record({'direction':'Pi → T3','type':'assistant message_end',**{k:m.get(k) for k in ['model','thinkingLevel','stopReason']}})
  elif obj.get('type')=='response' and obj.get('command')=='set_thinking_level':
   record({'direction':'Pi → T3','type':'set_thinking_level response','success':obj.get('success'),'data':obj.get('data')})
 except: pass
 sys.stdout.buffer.write(line);sys.stdout.buffer.flush()
os._exit(child.wait())
