"""Native EasyEDA transport and independent delivery checks; no design algorithms.""" import asyncio import base64 import fcntl import json import os import time from pathlib import Path from .config import EDA_BIN from .storage import ROOT, workspace, task_dir, inside, save, write, event, digest EDA_LOCK = asyncio.Lock() async def cli(args, code=None, timeout=210): env = dict(os.environ, DISPLAY=os.environ.get('DISPLAY',':0'), XDG_RUNTIME_DIR=os.environ.get('XDG_RUNTIME_DIR') or f'/run/user/{os.getuid()}') for key in ('OPENAI_API_KEY', 'OPENAI_API_KEY_FILE', 'DEEPSEEK_API_KEY', 'CODEX_API_KEY'): env.pop(key, None) if not env.get('XAUTHORITY'): auth = list(Path(f'/run/user/{os.getuid()}').glob('.mutter-Xwaylandauth.*')) if auth: env['XAUTHORITY'] = str(auth[0]) p = await asyncio.create_subprocess_exec(EDA_BIN, *args, '--no-sandbox', stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env, cwd=ROOT) try: out, err = await asyncio.wait_for(p.communicate(code.encode() if code is not None else None),timeout) except (asyncio.TimeoutError, asyncio.CancelledError): p.kill() await p.wait() raise RuntimeError('EDA command outcome unknown; inspect live state before retrying mutations') try: result = json.loads(out) except ValueError: raise RuntimeError('EDA returned non-JSON: '+err.decode(errors='replace')[-1500:]) from None if p.returncode or result.get('ok') is not True: raise RuntimeError('EDA native error: '+json.dumps(result,ensure_ascii=False)[:6000]) return result.get('value') async def host_lock(): path = Path.home()/'.local/state/ai-pcb-eda/locks/host.lock' path.parent.mkdir(parents=True,exist_ok=True) fd = path.open('a+') started = time.monotonic() while True: try: fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB) return fd except BlockingIOError: if time.monotonic()-started > 240: fd.close() raise RuntimeError('EDA host occupied by another task; no mutation executed') await asyncio.sleep(1) async def execute(t, code, label='EDA script'): if not t.get('approval') or t['state'] != 'running': raise PermissionError('EDA is unavailable until the latest proposal is approved') async with EDA_LOCK: fd = await host_lock() try: if not t.get('eda_session'): opened = await cli(['open','--headless','true'],timeout=90) t['eda_session'] = opened['sessionId'] event(t,'eda.session',{'session_id':t['eda_session']}) elif t.get('check_eda_session'): sessions = await cli(['session','list']) if not any(s.get('sessionId') == t['eda_session'] and s.get('status') == 'alive' for s in sessions): raise RuntimeError('Owned EDA session disappeared; reopen your saved native project through a new task session before continuing') t.pop('check_eda_session',None) n = t.get('eda_calls',0)+1 t['eda_calls'] = n prefix = workspace(t)/'evidence'/f'eda-{n:05d}' prefix.parent.mkdir(parents=True,exist_ok=True) prefix.with_suffix('.js').write_text(code) event(t,'eda.started',{'call':n,'label':label}) wrapper = '''const __files = []; const pcb_export = async (file,name) => { if (!file || typeof file.arrayBuffer !== 'function') throw new Error('Native export returned no File/Blob'); const base64 = await new Promise((resolve,reject)=>{const r=new FileReader();r.onload=()=>resolve(String(r.result).split(',')[1]);r.onerror=reject;r.readAsDataURL(file);}); __files.push({name,base64});return {name,bytes:file.size}; }; const __result = await (async()=>{\n''' + code + '\n})(); return {result:__result,files:__files};' try: value = await cli(['invoke','--session',t['eda_session'],'--ext-uuid','eda','--code-file','-','--timeout','180000'],wrapper) files = [] for item in value.get('files',[]): dst = inside(workspace(t)/'artifacts',item['name']) data = base64.b64decode(item['base64'],validate=True) dst.parent.mkdir(parents=True,exist_ok=True) dst.write_bytes(data) files.append({'path':str(dst),'bytes':len(data),'sha256':digest(data)}) result = {'result':value.get('result'),'exports':files} write(prefix.with_suffix('.json'),result) event(t,'eda.completed',{'call':n,'label':label,'files':files}) return result except Exception as e: write(prefix.with_suffix('.json'),{'error':str(e),'mutation_outcome':'inspect before retry'}) event(t,'eda.error',{'call':n,'message':str(e)}) raise finally: fcntl.flock(fd,fcntl.LOCK_UN) fd.close() async def verify_native(t, schematic_id, pcb_id): # Native booleans must be true. Verbose arrays are retained only as diagnostics. code = f'''const sch={json.dumps(schematic_id)}, pcb={json.dumps(pcb_id)}; async function focus(id) {{ const tab=await eda.dmt_EditorControl.openDocument(id); if(!tab || !await eda.dmt_EditorControl.activateDocument(tab)) throw new Error('Cannot focus requested document '+id); }} await focus(sch); await eda.sch_Document.save(); const parts=await eda.sch_PrimitiveComponent.getAll('part'); const schPassed=await eda.sch_Drc.check(true,false,false); const schErrors=schPassed ? [] : await eda.sch_Drc.check(true,false,true); const schNet=await eda.sch_ManufactureData.getNetlistFile('verification'); if(!schNet)throw new Error('Schematic netlist export missing'); await pcb_export(schNet,'verification-schematic.net'); await focus(pcb); await eda.pcb_Document.save(); const components=await eda.pcb_PrimitiveComponent.getAll(); const pcbPassed=await eda.pcb_Drc.check(true,false,false); const pcbErrors=pcbPassed ? [] : await eda.pcb_Drc.check(true,false,true); const pcbNet=await eda.pcb_ManufactureData.getNetlistFile('verification'); if(pcbNet)await pcb_export(pcbNet,'verification-pcb.net'); return {{schPassed,pcbPassed,schematicParts:parts.length,pcbParts:components.length,schErrors,pcbErrors}};''' evidence = await execute(t,code,'Independent native delivery verification') write(task_dir(t['id'])/'native-verification.json',evidence) r = evidence['result'] if not isinstance(r,dict) or r.get('schPassed') is not True or r.get('pcbPassed') is not True: raise ValueError('Native checks failed: '+json.dumps(r,ensure_ascii=False)[:16000]) if r.get('schematicParts',0)<2 or r.get('pcbParts',0)<2: raise ValueError('Native design is empty or incomplete') return r