import sys, subprocess, threading, json, os
child=subprocess.Popen([sys.argv[1]],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=sys.stderr)
permissions=set(); controls=set(); lock=threading.Lock()
def log(data):
 with lock:
  with open(sys.argv[2],'a') as f:f.write(json.dumps(data)+'\n')
def pipe(source,dest,direction):
 for line in iter(source.readline,b''):
  try:
   msg=json.loads(line); method=msg.get('method',''); id=msg.get('id')
   if direction=='agent' and method=='session/request_permission':
    permissions.add(id); p=msg.get('params',{});log({'direction':'agent','method':method,'title':p.get('toolCall',{}).get('title'), 'options':p.get('options')})
   elif direction=='client' and id in permissions:log({'direction':'client','permissionResponse':msg.get('result') or msg.get('error')})
   elif direction=='client' and method in ('session/set_model','session/set_config_option'):
    controls.add(id);p=msg.get('params',{});log({'direction':'client','method':method,'modelId':p.get('modelId'),'configId':p.get('configId'),'value':p.get('value')})
   elif direction=='agent' and id in controls:log({'direction':'agent','configurationResponse':'success' if 'result' in msg else msg.get('error')})
  except Exception:pass
  try:dest.write(line);dest.flush()
  except (BrokenPipeError,ValueError):break
threading.Thread(target=pipe,args=(sys.stdin.buffer,child.stdin,'client'),daemon=True).start()
pipe(child.stdout,sys.stdout.buffer,'agent')
child.wait()
