import {readFile} from 'node:fs/promises'; import {Browser, runTask} from './browser.mjs'; const args=process.argv.slice(2),has=k=>args.includes(k),get=k=>has(k)?args[args.indexOf(k)+1]:undefined; try { if(!has('--task')&&!has('--stdin'))throw Error('Usage: ./run.command --task task.json | --stdin [--session NAME --attach --keep-open] [--mode model|hybrid]'); if(has('--attach')&&!get('--session'))throw Error('--attach requires an existing named --session'); let raw; if(has('--stdin')){const chunks=[];for await(const chunk of process.stdin)chunks.push(chunk);raw=Buffer.concat(chunks).toString('utf8');} else raw=await readFile(get('--task'),'utf8'); const task=JSON.parse(raw),session=get('--session'); let browser; if(has('--attach')){ browser=new Browser(session,{origins:task.allowedOrigins}); const h=browser.flags.indexOf('--headed');if(h>=0)browser.flags.splice(h,2); const info=await browser.command(['session','info']); if(!info.active||!info.runtime?.browserLaunched)throw Error('The attached browser session must already be running'); if(!task.url){const tabs=(await browser.command(['tab'])).tabs.filter(t=>t.active);if(tabs.length!==1)throw Error('Ambiguous active tab');task.url=tabs[0].url;} } const result=await runTask(task,{session,browser,outDir:get('--out-dir'),setup:!has('--attach'),endpoint:get('--endpoint')??'http://127.0.0.1:8774',mode:get('--mode')??'hybrid', blockedRetries:get('--blocked-retries')===undefined?2:Number(get('--blocked-retries')), retryDelayMs:get('--retry-delay-ms')===undefined?500:Number(get('--retry-delay-ms')), onProgress:has('--verbose')?event=>console.error(JSON.stringify(event)):undefined}); if(!has('--keep-open')&&!has('--attach'))await result.browser.command(['close']); console.log(JSON.stringify(result.summary)); if(result.report.status!=='completed')process.exitCode=1; }catch(error){console.log(JSON.stringify({status:'error',error:error.message}));process.exitCode=1;}