"""Shared runner. Paid execution only via explicit --run-approved-50 flag.""" from pathlib import Path from decimal import Decimal import json,os,shutil,subprocess,time,datetime,threading,concurrent.futures,urllib.request,base64,sys,hashlib B=Path(__file__).resolve().parents[1];K=B/'kit';EXTRA='--added-tasks' in sys.argv;R=B/('execution-added' if EXTRA else 'execution'); R.mkdir(exist_ok=True) NODE='[local user]/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/bin/node' PY=sys.executable MODELS={'Qwen 4':('qwen/qwen4-max','alibaba','Alibaba','high'),'Astra':('openai/gpt-6-astra','openai','OpenAI','medium'),'Sol':('openai/gpt-6.1-sol','openai','OpenAI','medium'),'Opus':('anthropic/claude-opus-5.5','anthropic','Anthropic','high'),'Fable':('anthropic/claude-fable-5.2','anthropic','Anthropic','high')} lock=threading.RLock();ledger_path=R/'ledger.json';limit=Decimal('50' if EXTRA else '100'); halt=threading.Event() def save(p,d): p.parent.mkdir(exist_ok=True,parents=True);tmp=p.with_suffix(p.suffix+'.tmp');tmp.write_text(json.dumps(d,indent=2));tmp.replace(p) def now():return datetime.datetime.now(datetime.timezone.utc).isoformat() def ledger():return json.loads(ledger_path.read_text()) if ledger_path.exists() else {'authorized_usd':100,'authorization':'budget increased to $100 USD. Go for it.','calls':{},'started':now()} def reserve(ident,amount): with lock: if halt.is_set():raise RuntimeError('Global accounting halt') d=ledger();committed=sum(Decimal(str(x.get('actual',x['reserved']))) for x in d['calls'].values()); if committed+amount>limit:raise RuntimeError('Budget stop before dispatch') if ident in d['calls']:raise RuntimeError('Call already exists: no automatic retry') d['calls'][ident]={'reserved':str(amount),'state':'reserved','started':now()};save(ledger_path,d) def settle(ident,cost,state): with lock: d=ledger();record=d['calls'][ident];record['state']=state;record['finished']=now() if cost is not None:record['actual']=str(cost) save(ledger_path,d) def safe(root,name): p=(root/name).resolve() if p==root or not p.is_relative_to(root) or any(x.startswith('.') for x in Path(name).parts):raise ValueError('Outside visible task workspace') return p def sandbox(root,script): root=root.resolve();allowed=[str(root),'/System','/usr','/bin','/Library/Frameworks/Python.framework','/Library/Apple','/private/var/db','/private/var/run','/dev','/private/etc'] profile='(version 1)(allow default)(deny file-read* file-write* network* appleevent-send)(allow file-read-metadata)(allow file-read-data (literal "/"))'+''.join('(allow file-read* (subpath '+json.dumps(x)+'))'for x in allowed)+'(allow file-write* (subpath '+json.dumps(str(root))+'))(allow file-write* (literal "/dev/null"))(deny network*)' profile+='(deny file-write* (subpath '+json.dumps(str(root/'inputs'))+'))(deny file-write* (literal '+json.dumps(str(root/'COMMON.md'))+'))(deny file-write* (literal '+json.dumps(str(root/'PROMPT.md'))+'))' (root/'tmp').mkdir(exist_ok=True) env={'PATH':'/usr/bin:/bin','HOME':str(root/'tmp'),'TMPDIR':str(root/'tmp'),'PYTHONDONTWRITEBYTECODE':'1','PYTHONNOUSERSITE':'1'} r=subprocess.run(['/usr/bin/sandbox-exec','-p',profile,PY,str(safe(root,script))],cwd=root,env=env,capture_output=True,text=True,timeout=30) return {'exit_code':r.returncode,'stdout':r.stdout[:16000],'stderr':r.stderr[:3000]} def tool(name,props,req,description):return {'type':'function','function':{'name':name,'description':description,'parameters':{'type':'object','properties':props,'required':req,'additionalProperties':False}}} S={'type':'string'} TOOLS=[tool('list_files',{},[],'List visible task files.'),tool('read_file',{'path':S},['path'],'Read a UTF-8 task file.'),tool('write_file',{'path':S,'content':S},['path','content'],'Write output or working site file, up to 100KB; cannot edit original inputs.'),tool('run_python',{'path':S},['path'],'Run a Python standard-library script in your isolated workspace. No internet or outside filesystem; 30s timeout.'),tool('browser',{'site_path':S,'width':{'type':'integer','enum':[390,1280]},'actions':{'type':'array','items':{'type':'object','properties':{'op':{'type':'string','enum':['fill','click','reload']},'selector':S,'value':S},'required':['op'],'additionalProperties':False}}},['site_path','width','actions'],'Inspect/test a local site. Trusted server implements original POST /api/leads; fresh browser per call; returns visible text/controls/overflow. Use all desired fill/click actions together. No internet.')] def dispatch(root,c): name=c['function']['name'];a=json.loads(c['function']['arguments']) if name=='list_files':return [str(p.relative_to(root)) for p in root.rglob('*') if p.is_file() and 'tmp' not in p.parts] p=safe(root,a.get('path',a.get('site_path','output'))) if name=='read_file':return p.read_text()[:100000] if name=='write_file': if p==root/'COMMON.md' or p==root/'PROMPT.md' or p.is_relative_to(root/'inputs'):raise ValueError('Original input read-only') if len(a['content'].encode())>100000:raise ValueError('100KB write limit') p.parent.mkdir(parents=True,exist_ok=True);p.write_text(a['content']);return {'written':a['path']} if name=='run_python':return sandbox(root,a['path']) if name=='browser': r=subprocess.run([NODE,str(B/'build/browser_tool.mjs')],input=json.dumps({'root':str(p),'width':a['width'],'actions':a['actions']}),text=True,capture_output=True,timeout=55) return json.loads(r.stdout) if r.returncode==0 else {'error':r.stderr[-2000:]} raise ValueError('Unknown tool') def call(model,messages,ident): mid,route,provider,effort=MODELS[model] eps=json.loads((K/'operator/access'/(mid.replace('/','--')+'-endpoints.json')).read_text())['data']['endpoints'];ep=next(e for e in eps if e['tag']==route) if ep['status']!=0 or not {'tools','reasoning','max_tokens'}.issubset(ep['supported_parameters']):raise RuntimeError('Endpoint unavailable') prices=ep['pricing'];p=max(Decimal(prices.get(x,'0'))for x in ['prompt','input_cache_write','input_cache_write_1h']);out=Decimal(prices['completion']) body={'model':mid,'messages':messages,'max_tokens':16384,'reasoning':{'effort':effort},'tools':TOOLS,'provider':{'only':[route],'allow_fallbacks':False,'require_parameters':True},'usage':{'include':True},'plugins':[]} encoded=json.dumps(body).encode();amount=(len(encoded)+8192)*p+16384*out if len(encoded)>800000:raise RuntimeError('Context byte cap reached') reserve(ident,amount);save(R/'requests'/(ident+'.json'),{'model':mid,'request_sha256':hashlib.sha256(encoded).hexdigest(),'bytes':len(encoded),'max_tokens':16384}) auth=json.loads((Path.home()/'.local/share/opencode/auth.json').read_text())['openrouter']['key'] req=urllib.request.Request('https://openrouter.ai/api/v1/chat/completions',data=encoded,headers={'Authorization':'Bearer '+auth,'Content-Type':'application/json'},method='POST') try: with urllib.request.urlopen(req,timeout=600) as response:raw=json.load(response) save(R/'raw'/(ident+'.json'),raw) usage=raw.get('usage',{});cost=usage.get('cost') if cost is None or usage.get('is_byok') is not False: halt.set();raise RuntimeError('Unknown attributable cost') cost=Decimal(str(cost));settle(ident,cost,'received') if cost>amount: halt.set();raise RuntimeError('Cost exceeded reservation; halt') if raw.get('error'):raise RuntimeError(str(raw['error'])) if raw.get('provider')!=provider:raise RuntimeError('Provider mismatch') if not raw.get('model','').startswith(mid):raise RuntimeError('Model mismatch') return raw except Exception: # Preserve the full reserve for an unknown transport outcome. Independent jobs # may continue within the same durable cap; unknown usage is never released. settle(ident,None,'error_unknown_or_recorded');raise def run(model,task,rep): tag={'Qwen 4':'qwen4','Astra':'astra','Sol':'sol','Opus':'opus','Fable':'fable'}[model];rid=f'T{task:02}-R{rep}-{tag}';folder=R/'runs'/rid;root=folder/'workspace' if folder.exists():return {'run':rid,'status':'existing; skipped'} shutil.copytree(K/'candidate'/f'task-{task:02}',root);shutil.copy(K/'candidate/COMMON.md',root) content=[{'type':'text','text':(root/'COMMON.md').read_text()+'\n'+(root/'PROMPT.md').read_text()+'\nWorkspace file list:\n'+'\n'.join(str(p.relative_to(root))for p in root.rglob('*')if p.is_file())}] for p in sorted((root/'inputs').glob('*')): if p.suffix=='.png':content.append({'type':'image_url','image_url':{'url':'data:image/png;base64,'+base64.b64encode(p.read_bytes()).decode()}}) else:content.append({'type':'text','text':'FILE: inputs/'+p.name+'\n'+p.read_text()}) if task==3: for p in sorted((root/'site').glob('*')):content.append({'type':'text','text':'FILE: site/'+p.name+'\n'+p.read_text()}) messages=[{'role':'system','content':'Complete the supplied task using the shared local tools. Work independently. You may batch tool calls. Python standard library only; no installed third-party libraries. Browser observations are text, not screenshots. PNG task inputs are attached directly. No network from tools. Write outputs before final response. Never claim a check you did not do.'},{'role':'user','content':content}] result={'run_id':rid,'model':MODELS[model][0],'effort':MODELS[model][3],'started':now(),'stages':{}} for stage,maxsecs in [('initial',1800),('revision',900)]: if stage=='revision':messages.append({'role':'user','content':(K/'operator/REVISION-PROMPT.txt').read_text()}) start=time.monotonic();status='turn_limit';answer='' try: for turn in range(16): if time.monotonic()-start>maxsecs:status='timeout';break ident=f'{rid}-{stage}-{turn:02}';raw=call(model,messages,ident);choice=raw['choices'][0];msg=choice['message'];messages.append(msg) if choice.get('finish_reason')=='length':status='output_truncated';break calls=msg.get('tool_calls')or[] if not calls:answer=msg.get('content')or'';status='complete';break for c in calls: try:output=dispatch(root,c) except Exception as e:output={'error':str(e)} messages.append({'role':'tool','tool_call_id':c['id'],'content':json.dumps(output)}) save(folder/'conversation.json',messages) except Exception as e:status='stopped: '+str(e) result['stages'][stage]={'status':status,'elapsed_min':(time.monotonic()-start)/60,'answer':answer,'finished':now()} save(folder/'conversation.json',messages);save(folder/'result.json',result) if (root/'output').exists():shutil.copytree(root/'output',folder/stage/'output',dirs_exist_ok=True) (folder/stage).mkdir(exist_ok=True);(folder/stage/'final.txt').write_text(answer) print(json.dumps({'run':rid,'stage':stage,**result['stages'][stage]}),flush=True) if status.startswith('stopped'):break return result if __name__=='__main__': if '--run-approved-100' not in sys.argv:raise SystemExit('Use --run-approved-100 only under recorded user authorization') save(R/'authorization.json',{'quote':'budget increased to $100 USD. Go for it.','purpose':'Qwen4/Astra/Sol/Opus/Fable ten-task tests and article','total_ceiling_usd':100,'allocation_usd':float(limit),'recorded':now()}) with lock: d=ledger();d['authorized_usd']=float(limit);d['total_authorization_usd']=100;d['authorization']='budget increased to $100 USD. Go for it.';save(ledger_path,d) jobs=[] for rep in [1,2]: for task in (range(7,11) if EXTRA else range(1,11)): names=list(MODELS);shift=(task-1+(rep-1)*2)%5 jobs.extend((m,task,rep)for m in names[shift:]+names[:shift]) # Three independent runs concurrently; ledger reservation is synchronized. with concurrent.futures.ThreadPoolExecutor(max_workers=3)as pool: futures=[pool.submit(run,*j)for j in jobs] for f in concurrent.futures.as_completed(futures): try:f.result() except Exception as e:print('RUN ERROR: '+str(e),flush=True)