#!/usr/bin/env python3
import subprocess,sys,threading,json,os
root=os.path.dirname(os.path.abspath(__file__))
p=subprocess.Popen([root+'/runtime/package/vendor/x86_64-unknown-linux-musl/bin/codex',*sys.argv[1:]],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
methods={}; lock=threading.Lock()
def record(direction,line):
 try:d=json.loads(line)
 except: return
 out=None
 if direction=='request' and d.get('method') in ['thread/start','thread/resume','thread/fork','turn/start']:
  methods[str(d.get('id'))]=d['method']; q=d.get('params',{});out={'direction':direction,'method':d['method'],'id':d.get('id'),'model':q.get('model'),'reasoningEffort':q.get('effort',q.get('reasoningEffort')),'config.model_reasoning_effort':q.get('config',{}).get('model_reasoning_effort') if q.get('config') else None}
 if direction=='response' and str(d.get('id')) in methods:
  q=d.get('result',{});out={'direction':direction,'method':methods[str(d['id'])],'id':d['id'],'reasoningEffort':q.get('reasoningEffort'),'error':d.get('error')}
 if direction=='response' and d.get('method')=='thread/tokenUsage/updated':out={'direction':'notification','method':d['method'],'tokenUsage':d.get('params',{}).get('tokenUsage')}
 if out:
  with lock:
   with open(root+'/wire.jsonl','a') as f:f.write(json.dumps(out)+'\n')
def forward():
 for line in sys.stdin.buffer:
  record('request',line);p.stdin.write(line);p.stdin.flush()
 p.stdin.close()
threading.Thread(target=forward,daemon=True).start()
for line in p.stdout:
 record('response',line);sys.stdout.buffer.write(line);sys.stdout.buffer.flush()
sys.exit(p.wait())
