@engineeros/connector 1.59.69 → 1.59.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2637,7 +2637,7 @@ A new hunt reads this knowledge before it writes anything, so a case written onc
2637
2637
  `)[0])}`)}let nn=await ht.text().catch(()=>"");if(vt(),q.blockedRequest)throw new qe("blocked",q.blockedRequest);let Sn=null;try{Sn=JSON.parse(nn)}catch{Sn=null}return q.response={status:ht.status(),text:nn,json:Sn,ms:c()-it},{method:ke,url:K}}let op=async B=>{let ue=[...new Set([...String(B??"").matchAll(bZ)].map(te=>te[1]))],pe=String(B??"");for(let te of ue){let ke=f[te];if(ke===void 0||ke==="")throw new qe("blocked",`Set ${te} on the hunt host (\`engineeros-connector secret set ${te} --project ${C??"<project id>"}\`).`);let K;try{K=await Dh({value:String(ke),now:c,sleep:So})}catch{throw new qe("blocked",`${te} is not a valid authenticator secret.`)}pe=pe.replaceAll(`{totp:${te}}`,K)}return pe};async function Go(B,ue=Ge,{signingIn:pe=!1}={}){if(vt(),q.blockedRequest)throw new qe("blocked",q.blockedRequest);let te={action:B.action,target:is(await op(B.target),ue),data:is(await op(B.data),ue),check:is(B.check,ue)};if(vt(),te.action==="fill"&&!pe&&tl(te.data).blocked)throw new qe("blocked",el);if(W&&(["use account","run","open app"].includes(te.action)||te.action==="press"&&/enter/i.test(te.data)))throw new qe("blocked","Public pages only permits signed-out browsing and read-only request steps, without submitting.");if(h){if(!["open","request","wait for"].includes(te.action)||te.action==="request"&&!/^GET\s+/.test(te.target)||te.data)throw new qe("blocked","This action is not production-safe.");await So(1e3)}if(!pe){let K=Mr(te,ge);if(K)throw new qe("blocked",`Refused by the rule of engagement "${K}".`)}let ke=te.check?ss(te.check):[];switch(te.action){case"open app":{if(k.app_surface!=="electron")throw new qe("blocked","open app requires an Electron or WebDriver hunter.");if(process.env.ENGINEEROS_HUNT_HOST!=="dedicated")throw new qe("blocked","Electron requires ENGINEEROS_HUNT_HOST=dedicated on a VM or spare machine.");if(W||h||[Y,t.api_url].some(K=>/^https?:/i.test(K??"")))throw new qe("blocked","Electron cannot enforce this web target's approved socket destinations. Use the managed local browser for protected web testing.");if(_e)throw new qe("needs_repair","Open the app once per case.");b("Local Electron actions are available; Electron network transport is not qualified for protected web testing."),_e=await v({executablePath:k.app_path,args:k.app_arguments||[],cwd:l}),Re?.aborted&&(await ar(),vt()),await zt();break}case"use account":lr(await Jn(te.target.trim()));break;case"open":{await zt();let K=se(te.target.trim(),Y),Ue=it=>new qe("blocked",`${q.account.role}'s recorded sign-in has expired or was signed out: opening ${K} led to ${it}. Record it again in Bug Hunter Setup.`),Ie;try{Ie=await q.page.goto(K,{waitUntil:"domcontentloaded",timeout:G.navigation})}catch(it){let ht=String(it.message).split(`
2638
2638
  `)[0];throw q.account?.storage_state&&/ERR_BLOCKED_BY_CLIENT/.test(ht)?Ue("another site"):new qe("blocked",`Opening ${K} failed: ${Ft(ht)}`)}if(await bt(),q.account?.storage_state&&sm(K,q.page.url(),Q))throw Ue(Ft(q.page.url(),200));await _s({requested:K,reopen:async()=>{Ie=await q.page.goto(K,{waitUntil:"domcontentloaded",timeout:G.navigation}),await bt()}}),await Pn();let We=Ie?.status?.()??200;if(We>=500)throw new qe("failed",`The server answered ${We} for ${K}.`,`server error ${We}`);break}case"click":case"hover":case"check":case"uncheck":case"fill":case"select":{await zt();let K=await Xn(no(te.target));await oi(async()=>{te.action==="click"?await K.click({timeout:G.action}):te.action==="hover"?await K.hover({timeout:G.action}):te.action==="check"?await K.check({timeout:G.action}):te.action==="uncheck"?await K.uncheck({timeout:G.action}):te.action==="fill"?await K.fill(te.data,{timeout:G.action}):await K.selectOption({label:te.data},{timeout:G.action})}),te.action==="click"&&await bt();break}case"press":{if(await zt(),te.target.trim()){let K=await Xn(no(te.target));await oi(()=>K.press(te.data.trim(),{timeout:G.action}))}else await oi(()=>q.page.keyboard.press(te.data.trim()));await bt();break}case"go back":await zt(),await oi(()=>q.page.goBack({timeout:G.navigation})),await bt();break;case"reload":await zt(),await oi(()=>q.page.reload({timeout:G.navigation})),await bt(),await Pn();break;case"set viewport":{await zt();let[K,Ue]=(te.data||te.target).trim().toLowerCase().split("x").map(Number);await q.page.setViewportSize({width:K,height:Ue});break}case"wait for":await zt();break;case"request":{await zt();let{method:K,url:Ue}=await rp(te.target,te.data);if(q.response.status>=500&&!ke.some(Ie=>["status","status_below","status_in"].includes(Ie.kind)))throw new qe("failed",`The server answered ${q.response.status} for ${K} ${Ue}.`,`status was ${q.response.status}: ${Ft(q.response.text,200)}`);break}case"poll":{await zt();let K=c()+(Number(te.data.trim())||iZ)*1e3;for(;;){await rp(te.target,"");let Ue=[];for(let Ie of ke){let We=await bs(Ie);We!==null&&Ue.push(We)}if(!Ue.length)break;if(c()>=K)throw new qe("failed",`It never answered as expected: ${Ue.join("; ")}.`,Ue.join("; "));await So(aZ)}return cr()}case"set device":{if(q.page)throw new qe("needs_repair","Set the device before opening a page or using an account.");if(k.device_cloud_url){dt=te.data.trim(),ut.hasTouch=!0;break}let K=te.data.trim().toLowerCase(),Ue=Object.entries(y).find(([it])=>it.toLowerCase()===K);if(!Ue)throw new qe("needs_repair",`${te.data.trim()} is not a device the browser knows; use a name such as iPhone 13 or Pixel 7.`);let{defaultBrowserType:Ie,...We}=Ue[1];Object.assign(ut,We);break}case"tap":{if(await zt(),!ut.hasTouch)throw new qe("needs_repair","tap needs a touch device; set one with set device first.");let K=await Xn(no(te.target));await oi(()=>K.tap({timeout:G.action})),await bt();break}case"set locale":if(q.page)throw new qe("needs_repair","Set the locale before opening a page or using an account.");ut.locale=te.data.trim();break;case"set time zone":if(q.page)throw new qe("needs_repair","Set the time zone before opening a page or using an account.");ut.timezoneId=te.data.trim();break;case"set network":{await zt();let K=te.data.trim().toLowerCase();Ht=K,Vn.setNetwork(K),await q.context.setOffline(K==="offline"),K!=="offline"&&await(await q.context.newCDPSession(q.page)).send("Network.emulateNetworkConditions",K==="slow"?oZ:sZ);break}case"run":{let K;try{K=Mn(te.target.trim())}catch(We){throw new qe("needs_repair",`\`${te.target}\` cannot run without a shell: ${We.message}`)}let Ue=H7.basename(K[0]).replace(/\.(exe|cmd|bat)$/i,"").toLowerCase();if(!oe.has(Ue))throw new qe("blocked",`${K[0]} is not a program this hunter may run (${[...oe].join(", ")||"none are allowed"}).`);let Ie=await d(K,{onChild:Qa,cwd:l,timeoutMs:G.command,...u?{env:u}:{},...te.data?{input:te.data}:{}});if(Ie.notFound)throw new qe("blocked",`${K[0]} is not installed on the hunt host.`);q.command={exitCode:Ie.exitCode,output:Me(String(Ie.output??""))};break}case"use":{let K=fe.get(te.target.trim().toLowerCase());if(K?.builtin==="inbox"){if(!O)throw new qe("blocked","The test inbox is not set up on this hunt host.");q.command=await Fh(O,te.data,St);break}if(!K)throw new qe("blocked",`${te.target.trim()} is not an instrument approved for this environment (${[...fe.keys()].join(", ")||"none are"}).`);let Ue=K.env??[],Ie=Ue.filter(sn=>f[sn]===void 0);if(Ie.length)throw new qe("blocked",`Set ${Ie.join(", ")} on the hunt host to use ${K.name}.`);let We=Object.fromEntries(Ue.map(sn=>[sn,String(f[sn])])),it={...ue,...We,data:te.data,since:new Date(St).toISOString()},ht=(K.command??[]).map(sn=>is(String(sn),it)),nn=await d(ht,{onChild:Qa,cwd:l,timeoutMs:G.command,env:{...u??process.env,...We}});if(nn.notFound)throw new qe("blocked",`${ht[0]} is not installed on the hunt host.`);let Sn=String(nn.output??"");for(let sn of Object.values(We))sn&&(Sn=Sn.replaceAll(sn,"[secret]"));q.command={exitCode:nn.exitCode,output:Me(Sn)};break}case"wait until":{let K=/^step\s+(\d+)$/i.exec(te.target.trim()),Ue=K?jl[Number(K[1])-1]:St;if(Ue===void 0)throw new qe("needs_repair",`wait until counts from step ${K[1]}, which has not run yet.`);let Ie=Ue+(jh(te.data)??0);if(Ie-c()>lZ)throw new qe("needs_repair","wait until may wait at most three hours.");Ie>c()&&await So(Ie-c());break}case"crawl":{await zt();let K=Math.min(Number(te.data)||_b,uZ),Ue=q.account?.role??null,Ie=c(),We=()=>c()<Ie+Math.min(G.crawl+q.scanMs,3*G.crawl),it=ct?[]:[{url:se(te.target.trim()||"/",Y),from:null,source:"link"}],ht=[];for(let ae of Xh(tt,ge))try{ht.push({url:se(ae.path,Y),from:null,source:ae.source,seed:!0})}catch{}let nn=ht.some(ae=>ae.url.includes("/#/")),Sn=new Set(me),sn=new Set(me),ii=new Map,Kn=!1,ks=new Map,xt={pages:0,server_errors:[],broken_links:[],routes:[],scripts:[],controls_explored:0,explore_blocked_writes:0,explore_stopped_pages:0,explore_stopped_time:0};q.crawl=xt;let Eo=[],Ye=null,z=async()=>{let[ae,de]=await Promise.all([q.page.title(),q.page.evaluate(zi)]);return`${ae??""}\0${de.elements.join("")}`},Z=async()=>{let ae=`__engineeros_probe_${Math.random().toString(36).slice(2,8)}`;try{return await q.page.goto(se(nn?`/#/${ae}`:`/${ae}`,Y),{waitUntil:"domcontentloaded",timeout:G.navigation}),await bt(),await z()}catch{return!1}};for(;(it.length||ht.length)&&xt.pages<K&&We()&&!yt();){vt();let ae=ht.length&&(Kn||!it.length)?ht.shift():it.shift();Kn=!Kn;let de=mr(new URL(ae.url));if(de===null)continue;let xe=ld(de);if(Sn.has(de)||(ks.get(xe)??0)>=pZ||(Sn.add(de),ks.set(xe,(ks.get(xe)??0)+1),Mr({action:"open",target:de,data:"",check:""},ge)))continue;ae.seed&&Ye===null&&(Ye=await Z()),q.path=ae.from,q.pathRole=Ue;let Pe={path:de.slice(0,300),source:ae.source,status:null,outcome:"reached",from_path:ae.from?ae.from.slice(0,300):null},ve=($t,at=null)=>{ae.from&&(xt.broken_links.push({from:ae.from,url:ae.url,status:$t}),Vn.note("broken_link",ae.from,{url:ae.url,status:$t,error:at,message:`A link to ${de} ${$t?`answers ${$t}`:"cannot be opened"}`}))},Ve;try{Ve=await q.page.goto(ae.url,{waitUntil:"domcontentloaded",timeout:G.navigation})}catch($t){let at=String($t.message).split(`
2639
2639
  `)[0];/ERR_(?!BLOCKED_BY_CLIENT)[A-Z_]+/.test(at)&&ve(null,at),xt.routes.push({...Pe,outcome:"error"});continue}await bt(),Ue&&await _s({requested:ae.url,crawling:!0,reopen:async()=>{Ve=await q.page.goto(ae.url,{waitUntil:"domcontentloaded",timeout:G.navigation}),await bt()}}).catch(()=>!1),await Pn();let st=Ve?.status?.()??200;Pe.status=st;let Ee=st===404||st===410;if(await(async()=>{if(!Ue||Ee)return!1;if(st===403)return!0;if(st>=400)return!1;try{let[$t,at,Mt]=await Promise.all([q.page.title(),q.page.evaluate(zi),q.page.evaluate(()=>document.querySelector("h1")?.innerText??"")]);return _Z.test(`${$t??""} ${Mt??""}`)&&at.elements.length<=vZ}catch{return!1}})()){xt.routes.push({...Pe,outcome:"forbidden"});continue}let Be=mr(new URL(q.page.url())),Et=st===401||st===403||sm(ae.url,q.page.url(),Q)||Be!==de&&Di({key:Be,elements:(await q.page.evaluate(zi).catch(()=>({elements:[]}))).elements});if(Et){if(xt.routes.push({...Pe,outcome:"sign_in"}),ae.seed){let $t=new URL(q.page.url()),at=`${$t.origin}${st===401||st===403?`:${st}`:mr($t)}`,Mt=(ii.get(at)??0)+1;ii.set(at,Mt),Mt>=3&&ht.length&&(xt.deferred_seeds=ht.length,ht.length=0)}if(st===401||st===403)continue}else if(ae.seed){if(Ee||Ye&&await z()===Ye){xt.routes.push({...Pe,outcome:"not_found"});continue}}else if(Ee){ve(st),xt.routes.push({...Pe,outcome:"not_found"});continue}else st>=400&&st!==401&&st!==403&&ve(st);let Je=new URL(q.page.url()),nt=mr(Je);if(Et||xt.routes.push({...Pe,outcome:st>=500?"error":"reached"}),nt===null||!Q.has(Je.hostname.toLowerCase())||sn.has(nt))continue;sn.add(nt),xt.pages+=1,Et&&nt!==de&&xt.routes.push({path:nt.slice(0,300),source:"navigation",status:st,outcome:"reached",from_path:null}),st>=500&&xt.server_errors.push(nt),await cr(),await we();let Ot=await q.page.evaluate(eN).catch(()=>[]);Eo.push({key:nt,url:q.page.url(),links:Array.isArray(Ot)?Ot.length:0});for(let $t of Array.isArray(Ot)?Ot:[]){let at;try{at=new URL($t,Je)}catch{continue}!/^https?:$/.test(at.protocol)||!Q.has(at.hostname.toLowerCase())||Jh(at.href,ge)&&(Xv.test(at.hash)||(at.hash=""),Sn.has(mr(at))||it.push({url:at.toString(),from:nt,source:"link"}))}}if(await Jt(),Ke&&!h&&Eo.length&&!yt()){let ae=c(),de=()=>yt()||c()-ae>=G.explore,xe=[...Eo].sort((ve,Ve)=>ve.links-Ve.links),Pe=async ve=>{await q.page.goto(ve.url,{waitUntil:"domcontentloaded",timeout:G.navigation}).catch(()=>{}),await bt()};q.exploring=!0;try{for(let ve=0;ve<xe.length&&!xt.explore_stopped_time;ve+=1){if(vt(),de()){xt.explore_stopped_time=1;break}let Ve=xe[ve];try{await q.page.goto(Ve.url,{waitUntil:"domcontentloaded",timeout:G.navigation})}catch{continue}await bt();let st=await q.page.evaluate(Oj).catch(()=>[]),{chosen:Ee,cut:ft}=Cj(Array.isArray(st)?st:[],{forbidden:ge,limit:sb});ft&&(xt.explore_stopped_pages+=1);let Be=0;for(let Et of Ee){if(vt(),de()){xt.explore_stopped_time=1;break}let Je=Et.role?q.page.getByRole(Et.role,{name:Et.name,exact:!0}):q.page.getByText(Et.name,{exact:!0});if(await Je.count()!==1)continue;let nt=(await q.page.evaluate(zi)).elements;try{await Je.click({timeout:G.action})}catch{}xt.controls_explored+=1,await So(G.exploreSettle),await bt();let Ot=q.page.url(),$t=null,at=!1;try{let Ln=new URL(Ot);$t=mr(Ln),at=Q.has(Ln.hostname.toLowerCase())}catch{}if($t!==null&&$t!==Ve.key&&at){!sn.has($t)&&xt.pages<K&&(sn.add($t),Sn.add($t),q.path=Ve.key,q.pathRole=Ue,xt.pages+=1,xt.routes.push({path:$t.slice(0,300),source:"navigation",status:200,outcome:"reached",from_path:Ve.key.slice(0,300)}),await cr(),await we(),Be=0,xe.push({key:$t,url:Ot,links:0})),await Pe(Ve);continue}let Mt=(await q.page.evaluate(zi)).elements,Ss=Mt.filter(Ln=>!nt.includes(Ln));if(Ss.length>=2){let Ln={key:Ve.key.slice(0,300),origin:new URL(q.page.url()).origin,title:Ft(await q.page.title().catch(()=>""),300),elements:[...new Set([...nt,...Mt])].slice(0,yb).map(Nl=>Ft(Nl,200)),role:Ue};i(Ln),X(Ln)}if(await we(),Ss.length)Be=0,await Pe(Ve);else if(++Be>=3){de()&&(xt.explore_stopped_time=1);break}}}}finally{q.exploring=!1}xt.explore_blocked_writes=q.blockedWrites}xt.scripts=Vn.scripts(),xt.remaining_routes=[...it,...ht].flatMap(ae=>{let de=mr(new URL(ae.url));return de&&!Sn.has(de)?[{path:de,source:ae.source}]:[]});return}case"remember":{let K=te.data.trim(),Ue=te.target.trim();if(Ue==="url")await zt(),ue[K]=q.page.url();else if(/^output(?:\s+field\s+|$)/i.test(Ue)){if(!q.command)throw new qe("needs_repair","Nothing was run before this step to remember output from.");let Ie=Ue.replace(/^output\s*(?:field\s+)?/i,"");if(!Ie)ue[K]=q.command.output.trim();else{let We=null;try{We=JSON.parse(q.command.output)}catch{We=null}let it=We===null?{found:!1}:_d(We,Ie);if(!it.found)throw new qe("needs_repair",`The last output has no field ${Ie} to remember.`);ue[K]=al(it.value)}}else if(/^field\s+/i.test(Ue)){let Ie=Ue.replace(/^field\s+/i,""),We=q.response?_d(q.response.json,Ie):{found:!1};if(!We.found)throw new qe("needs_repair",`The last response has no field ${Ie} to remember.`);ue[K]=al(We.value)}else{await zt();let Ie=await Xn(no(Ue));ue[K]=String(await Ie.innerText()).trim()}break}default:throw new qe("needs_repair",`\`${te.action}\` is not an action.`)}if(vt(),q.blockedRequest)throw new qe("blocked",q.blockedRequest);await Xt(ke),await cr()}let si=async()=>(await Vn.settled(),{execution_context:{browser:_e?"electron":e?.browserType?.().name()??null,browser_version:typeof(_e||e)?.version=="function"?(_e||e).version():null,role:q.account?.role??"",context_sha256:Zj("sha256").update(JSON.stringify(Yt)).digest("hex")},signals:Vn.signals(),api_calls:h?[]:Vn.apiCalls(),vitals:ra,scanned:ec,scan_ms:q.scanMs});try{for(let[B,ue]of F.slice(0,ze===null?F.length:ze-1).entries())try{if(q.step=B+1,await Go(ue),q.blockedRequest)throw new qe("blocked",q.blockedRequest);jl[B]=c(),await we()}catch(pe){let te=q.blockedRequest||q.transportBlocker?new qe("blocked",q.blockedRequest??`${q.transportBlocker} The functional check could not complete with that dependency unavailable: ${Ft(pe.message)}`):pe instanceof qe?pe:Re?.aborted?new qe("blocked",Ft(Re.reason?.message??"The hunt was stopped; remaining actions were not run.")):new qe("failed",Ft(pe.message));q.crawl||await cr({final:!0}).catch(()=>{});let ke=await qr(),K=ke?[{label:"after",step:B+1,media_type:"image/jpeg",data_base64:ke}]:[];return ot={outcome:te.outcome,failed_step:B+1,message:`${ee} step ${B+1}: ${Ft(te.message,1e3)}`,observed:te.observed?Ft(te.observed,1e3):null,duration_ms:c()-St,evidence:[...K,...na],...await si(),...q.crawl?{crawl:q.crawl}:{}}}return q.crawl||await cr({final:!0}).catch(()=>{}),ot={outcome:"passed",failed_step:null,message:null,observed:null,duration_ms:c()-St,evidence:na,...await si(),...q.crawl?{crawl:q.crawl}:{}}}finally{if(ot&&je){if(ot.cleanup={state:"not_required",from_step:null,reason:null},ze!==null){let pe=Ft(is(je.test_data,{unique:Ge.unique}),1e3),te=ze;ot.cleanup={state:"completed",from_step:ze,reason:null,test_data_scope:pe};try{vt(),q.blockedRequest=null;for(let[ke,K]of F.slice(ze-1).entries()){if(te=ze+ke,/\{[A-Za-z_][A-Za-z0-9_]*\}/.test(is(K.target+" "+K.data,Ge)))throw new Error("Cleanup needs an identifier that this case did not observe. Resolve the owned test data before retrying.");if(await Go(K),q.blockedRequest)throw new Error("Cleanup was refused by this run's scope.")}}catch(ke){ot.cleanup={state:"pending",from_step:ze,reason:`The approved cleanup could not complete: ${Ft(ke.message,500)} Resolve this case's owned test data before another attempt.`,primary_outcome:ot.outcome,primary_failed_step:ot.failed_step,primary_message:ot.message,test_data_scope:pe},ot.outcome="blocked",ot.failed_step=te,ot.message=ot.cleanup.reason}}Object.assign(ot,await si()),ot.duration_ms=c()-St}if(!Re?.aborted){for(let pe of _t.values())if(pe.account?.storage_state)try{let te=new Set(pe.account.sign_in_binding.origins),ke=Fi(pe.page.url(),te)?await pe.page.evaluate(gb):null,K=pe.account.storage_state.sessionStorage??[],Ue=qi(await pe.context.storageState({indexedDB:!0}),te,ke?[...K.filter(Ie=>Ie.origin!==ke.origin),ke]:K);await Tt(pe.account,Ue)}catch{b("The case evidence was retained, but its renewed sign-in could not be kept. Check the protected store before the next run.")}}Re?.removeEventListener("abort",Gt);let ue=(await Promise.allSettled([Za,ar()])).find(pe=>pe.status==="rejected");if(ue)throw ue.reason}}return{run:async(F,ee)=>{let X=async je=>{if(j)return{outcome:"blocked",failed_step:1,message:"A preceding case has unfinished cleanup. Resolve its owned test data before resuming.",duration_ms:0,evidence:[]};let tt=await L(F,{...ee,profileReservation:je});return tt.cleanup?.state==="pending"&&(j=!0),tt};if(ee?.caseMetadata?.effects==="read_only"||F.some(je=>je.action==="crawl"))return X();let re=F.filter(je=>je.action==="use account"&&n.some(tt=>tt.storage_state&&tt.role.toLowerCase()===String(je.target).trim().toLowerCase())),le=R&&ee?.signal?AbortSignal.any([R,ee.signal]):R??ee?.signal;try{return await M.run(Oe(re),{signal:le},X)}catch(je){if(je.code!=="HUNT_RESOURCES_BLOCKED")throw je;return{outcome:"blocked",failed_step:1,message:je.message,duration_ms:0,evidence:[]}}}}}Rr();import bn from"node:path";import{mkdirSync as tae}from"node:fs";import{format as nae}from"node:util";Rn();N();hn();Rn();import{createHash as kZ}from"node:crypto";import{readFile as SZ,readdir as xZ,rm as EZ}from"node:fs/promises";import vd from"node:path";import{isDeepStrictEqual as $Z}from"node:util";var AZ=new Set(["prompt.completed","prompt.failed"]),vb=e=>kZ("sha256").update(e).digest("hex"),cm=new Map,ll=new Map,oN=e=>vb(JSON.stringify(e,(t,n)=>n&&typeof n=="object"&&!Array.isArray(n)?Object.fromEntries(Object.entries(n).sort(([r],[o])=>r.localeCompare(o))):n));function lm(e,t){let r=(cm.get(e)??Promise.resolve()).catch(()=>{}).then(t).finally(()=>{cm.get(e)===r&&cm.delete(e)});return cm.set(e,r),r}function sN(e){if(!e.connector_id||!e.server_url||!e.workspace)throw new Error("Restore the paired connector configuration before delivering saved prompt results.");let t=JSON.stringify([e.server_url,e.connector_id,vd.resolve(e.workspace)]);return vd.join(vd.dirname(zn(e.workspace)),"prompt-results",vb(t))}function um(e,t){if(!AZ.has(t.type)||!t.prompt_id)throw new Error("Only final prompt results belong in the prompt outbox.");return vd.join(sN(e),`${vb(JSON.stringify([t.prompt_id,t.execution_revision??1]))}.json`)}async function dm(e){try{return JSON.parse(await SZ(e,"utf8"))}catch(t){if(t.code==="ENOENT")return null;throw t}}function iN({getConfig:e,send:t,onRetained:n=()=>{}}){let r;function o(a,c){let l=Date.now();for(let[u,d]of ll)d.expires<=l&&ll.delete(u);if(c&&ll.has(a)&&ll.get(a).digest!==oN(c))throw new Error(`A different final result was already acknowledged for this prompt revision. Original evidence retained in EngineerOS; receipt: ${a}.`);return ll.has(a)?{status:"delivered",file:a}:null}async function s(a,c){let l=JSON.parse(JSON.stringify(c)),u=await dm(a);if(!u){u={update:l,saved_at:new Date().toISOString()};try{await Fe(a,JSON.stringify(u),{replace:!1})}catch(d){if(d.code!=="EEXIST")throw d;if(u=await dm(a),!u)throw new Error(`Another connector delivered or changed this prompt result. Reconcile its existing receipt before retrying: ${a}`)}}if(!$Z(u.update,l))throw new Error(`A different final result already exists for this prompt revision. Original evidence retained at ${a}.`);return{file:a,record:u}}async function i(a,c){if(c.rejection)return{status:"rejected",file:a,reason:c.rejection};try{return await t(c.update),ll.set(a,{expires:Date.now()+36e5,digest:oN(c.update)}),await EZ(a,{force:!0}),{status:"delivered",file:a}}catch(l){if(l.retryable===!1){let d=l.message||"EngineerOS rejected this prompt result.";return await Fe(a,JSON.stringify({...c,rejection:d})),n({status:"rejected",file:a,reason:d}),{status:"rejected",file:a,reason:d}}let u={status:"pending",file:a,reason:l.message};return n(u),u}}return{save(a){let c=um(e(),a);return lm(c,()=>o(c,a)?{file:c,record:null}:s(c,a))},deliver(a){let c=um(e(),a);return lm(c,async()=>{let l=o(c,a);if(l)return l;let{record:u}=await s(c,a);return i(c,u)})},replay(a){let c=um(e(),{...a,type:"prompt.completed"});return lm(c,async()=>{let l=o(c);if(l)return l;let u=await dm(c);return u?i(c,u):null})},flush(){if(r)return r;let a=sN(e());return r=(async()=>{let c;try{c=await xZ(a)}catch(l){if(l.code==="ENOENT")return;throw l}for(let l of c.filter(u=>/^[a-f0-9]{64}\.json$/.test(u))){let u=vd.join(a,l);if((await lm(u,async()=>{let p=await dm(u);if(!p||p.rejection)return null;if(u!==um(e(),p.update))throw new Error(`Saved prompt result has an invalid identity: ${u}`);return i(u,p)}))?.status==="pending")break}})().finally(()=>{r=void 0}),r}}}N();function aN({capacity:e}){let t=[],n=0;function r(){for(;t.length&&n<Math.max(0,e());){let o=t.shift();o.signal?.removeEventListener("abort",o.abort),n++;let s=!1;o.resolve(()=>{s||(s=!0,n--,r())})}}return{get running(){return n},get waiting(){return t.length},drain:r,acquire({signal:o,onWaiting:s=()=>{}}={}){return o?.throwIfAborted(),new Promise((i,a)=>{let c={resolve:i,reject:a,signal:o,abort:null};c.abort=()=>{let l=t.indexOf(c);l<0||(t.splice(l,1),o.removeEventListener("abort",c.abort),a(o.reason))},o?.addEventListener("abort",c.abort,{once:!0}),t.push(c),r(),t.includes(c)&&s()})}}}N();tc();N();var bd=new Map;function kd(e,t=Date.now()){let n=bd.get(e);return!n||t>=n.retryAt}function cN(e,t,n,{remedy:r=null,now:o=Date.now()}={}){let s=bd.get(e),i=(s?.failures??0)+1,a=Math.min(3e4*2**(i-1),6e5),c={id:e,title:t,remedy:r,message:TZ(n),failures:i,firstFailedAt:s?.firstFailedAt??o,retryAt:o+a,retryInMs:a};return bd.set(e,c),c}function lN(e){return bd.delete(e)}function uN(e=Date.now()){return[...bd.values()].map(t=>({...t,status:t.failures>=5?"failed":"warning",retryInMs:Math.max(t.retryAt-e,0)}))}function TZ(e){return(e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported."}Rn();var bb=22,RZ=500,OZ=300,CZ=20,dN={ok:0,warning:1,failed:2},fN={codex:{url:"https://registry.npmjs.org/@openai%2fcodex/latest",version:e=>e?.version,remedy:"Run `npm install -g @openai/codex@latest`, then restart this connector."},forge:{url:"https://api.github.com/repos/tailcallhq/forgecode/releases/latest",version:e=>String(e?.tag_name??"").replace(/^v/,""),remedy:"Run `forge update`, then restart this connector."}},IZ=360*6e4,pN=new WeakMap,jZ="connector.diagnostics";function NZ(e){return e.reduce((t,n)=>dN[n.status]>dN[t]?n.status:t,"ok")}async function hN({config:e,workspace:t=e?.workspace,version:n="development",probes:r,insights:o=[],agentSession:s=null,fetchImpl:i=fetch,nodeVersion:a=process.version}){let c=[PZ(a),MZ(e),await Sd("backend","EngineerOS backend",()=>DZ(e,i)),await Sd("coding_agent","Coding agent",()=>LZ(e,t,r.inspectAgent,i)),...s?[FZ(s)]:[],...r.connectorJobs?[await Sd("local_execution","Local testing work",()=>qZ(r.connectorJobs))]:[],await Sd("tool_registry","Tool registry",()=>zZ(t,r.inspectTools)),...e?.hunt_host?[]:[await Sd("goal_runner","Goal runner",()=>BZ(t,r.runnerStatus,{serviceStatus:r.macRunnerStatus}))],...uN().map(HZ),...o.map(l=>rn(l.id,l.title,l.status,l.detail,l.remedy))].slice(0,CZ);return{checked_at:new Date().toISOString(),connector_version:String(n).slice(0,50),status:NZ(c),checks:c}}function kb(e){let t=[`Connector self-check: ${e.status} (${e.connector_version})`];for(let n of e.checks)t.push(`- ${n.title}: ${n.status} - ${n.detail}`),n.remedy&&t.push(` ${n.remedy}`);return t.join(`
2640
- `)}async function mN(e,t,n){return!e?.connector_id||!e.token?null:await n(e,{type:jZ,...t})??{}}function PZ(e){let t=Number.parseInt(String(e).replace(/^v/,""),10);return Number.isFinite(t)&&t>=bb?rn("node_runtime","Node runtime","ok",`Node ${e}.`):rn("node_runtime","Node runtime","failed",`Node ${e} is older than the Node ${bb} this connector requires.`,`Install Node ${bb} or later, then start the connector again.`)}function MZ(e){return e?.connector_id&&e.token?rn("pairing","Workspace pairing","ok",`Paired as ${e.name||e.connector_id} for ${e.workspace}.`):rn("pairing","Workspace pairing","failed","This workspace holds no connector credential.","Create a pairing command in EngineerOS and run it in this folder.")}async function DZ(e,t){if(!e?.server_url)return rn("backend","EngineerOS backend","failed","No EngineerOS address is configured.","Pair this workspace with --url pointing at the EngineerOS backend.");let n=kS(e.server_url),r;try{r=await t(n,{signal:AbortSignal.timeout(1e4)})}catch(s){return rn("backend","EngineerOS backend","failed",`${n} is unreachable from this machine: ${_n(s,{network:!0})}`,"Check the address, the network between this machine and EngineerOS, and that the backend is running.")}if(!r.ok)return rn("backend","EngineerOS backend","failed",`${n} answered ${r.status}.`,"Check that the address points at the EngineerOS backend rather than another service.");let o=await r.json().then(s=>s?.status).catch(()=>{});return o&&o!=="healthy"?rn("backend","EngineerOS backend","warning",`${n} reports itself as ${o}.`,"Open Admin > System in EngineerOS for the failing dependency."):rn("backend","EngineerOS backend","ok",`${n} is reachable.`)}async function LZ(e,t,n,r){try{let o=await n(e,t),s=`${o.name} ${o.version} through ${o.protocol}.`,i=String(o.version??"").match(/\d+\.\d+\.\d+/)?.[0],a=i?await UZ(o.protocol,r):null;return a&&To(a,i)>0?rn("coding_agent","Coding agent","warning",`${s} ${o.name} ${a} is available.`,fN[o.protocol].remedy):rn("coding_agent","Coding agent","ok",s)}catch(o){return rn("coding_agent","Coding agent","failed",gN(o),null)}}async function UZ(e,t){let n=fN[e];if(!n)return null;let r=pN.get(t)??new Map;pN.set(t,r);let o=r.get(e);if(o&&Date.now()-o.at<IZ)return o.version;let s=null;try{let i=await t(n.url,{headers:{accept:"application/json"},signal:AbortSignal.timeout(5e3)}),a=i.ok?n.version(await i.json()):null;xn(a)&&(s=a)}catch{}return r.set(e,{at:Date.now(),version:s}),s}function FZ({state:e,detail:t,remedy:n=null}){return rn("agent_session","Coding agent session",e==="ready"?"ok":e==="checking"?"warning":"failed",t,n)}async function qZ(e){let t=await e(),n=t.filter(o=>o.status==="blocked");if(n.length){let o=n[0];return rn("local_execution","Local testing work","failed",`${n.length} local testing job(s) are blocked. ${o.blocked_report?.error?.message||o.error||o.checkpoint?.error||"An execution or report was refused; its original evidence remains saved on this machine."}`,"Inspect the saved connector job and its first blocked report on this machine. Fix the reported cause, then explicitly retry report delivery; do not rerun completed tests or delete their evidence.")}let r=t.flatMap(o=>Object.values(o.checkpoint?.server_effects??{}).flatMap(s=>s.response?.projection_warnings??[]));return r.length?rn("local_execution","Local testing work","warning",`${r.length} result(s) were retained as history only. ${r[0].reason}`,"Inspect the saved result receipt and its execution context. History-only results do not verify a pass or resolve a finding; preserve their evidence and supply the reported prerequisite before a new authorized execution."):rn("local_execution","Local testing work","ok","No local testing jobs are blocked.")}async function zZ(e,t){let n=await t(e);if(n?.error)return rn("tool_registry","Tool registry","warning",n.error,"Run `engineeros-connector tools list` in this workspace for the full registry state.");let r=n?.entries?.length||0;return rn("tool_registry","Tool registry","ok",`${r} provider(s) registered.`)}async function BZ(e,t,{platform:n=process.platform,serviceStatus:r=yI}={}){if(n==="darwin"){let i=await r(e),a=`Run engineeros-connector runner start --workspace "${e}".`;if(i.disabled)return rn("goal_runner","Goal runner","warning","The macOS Goal runner is disabled.",`Turn it on in System Settings > General > Login Items. ${a}`);if(!i.loaded)return rn("goal_runner","Goal runner","warning",i.installed?"The macOS Goal runner is not loaded in this login session.":"The macOS Goal runner is not installed.",a);if(i.lastExitCode&&i.state!=="running")return rn("goal_runner","Goal runner","warning",`The macOS Goal runner exited with status ${i.lastExitCode} (${i.state||"unknown state"}).`,`Read .engineeros/runner/launchd.log. For protected folders, allow node under Privacy & Security > Files and Folders, or move the workspace. ${a}`)}let{jobs:o}=await t(e),s=o.filter(i=>["failed","recovering"].includes(i.status));if(s.length){let i=s[0];return rn("goal_runner","Goal runner","warning",`${s.length} local Goal job(s) need attention. ${i.runId} is ${i.status}${i.error?`: ${i.error}`:"."}`,"Open the Goal in EngineerOS, or read .engineeros/runs/<run-id>/activity.log in this workspace.")}return rn("goal_runner","Goal runner","ok",`${o.length} local Goal job(s) recorded, none stuck.`)}function HZ(e){return rn(e.id,e.title,e.status,`Failing since ${so(e.firstFailedAt)} after ${e.failures} attempt(s); retrying in ${Math.round(e.retryInMs/1e3)}s. ${e.message}`,e.remedy)}async function Sd(e,t,n){try{return await n()}catch(r){return rn(e,t,"failed",gN(r),null)}}function rn(e,t,n,r,o=null){return{id:e,title:t,status:n,detail:String(r||"No detail was reported.").slice(0,RZ),remedy:o?String(o).slice(0,OZ):null}}function gN(e){return(e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported."}N();import nQ from"node:path";N();import GZ from"node:path";var yN=3,WZ=300*1e3,VZ={pytest:40,"node:test":40,vitest:60,jest:60},JZ=3,XZ=new Set(["pytest","vitest","jest","node:test","go-test","junit"]),KZ=new Set(["pytest-asyncio","pytest-cov","hypothesis","schemathesis","locust","bandit","pip-audit","@testing-library/react","@axe-core/playwright","k6","testify"]),wN=new Map([["@playwright/test","It drives a browser against the running app. Add an environment, then schedule it."],["cypress","It drives a browser against the running app. Add an environment, then schedule it."]]);function pm(e,t=process.env){return e?.quality_baseline===!1?!1:!["off","0","false","no"].includes(String(t.ENGINEEROS_QUALITY_BASELINE??"").trim().toLowerCase())}function _N(e=process.env){let t=Number(e.ENGINEEROS_BASELINE_IDLE_MS);return Number.isFinite(t)&&t>0?Math.floor(t):600*1e3}function YZ(e){let t=String(e?.name??"");return KZ.has(t)?{support:"helper"}:XZ.has(t)?{support:"run"}:wN.has(t)?{support:"skipped",reason:wN.get(t)}:{support:"unsupported",reason:`There is no baseline recipe for ${t||"this runner"}. Schedule its command and upload the JUnit report instead.`}}var Sb=e=>String(e??"").replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,""),ZZ=(e,t)=>!t||e.startsWith(`${t}/`);function QZ(e,t){let n=null;for(let r of t)r.name!==e.framework||!ZZ(e.file,r.root)||(!n||r.root.length>n.root.length)&&(n=r);return n}function eQ(e,{perShard:t,durations:n}){let r=e.map(c=>n[c]).filter(c=>Number.isFinite(c)&&c>0),o=[];if(!r.length){for(let c=0;c<e.length;c+=t)o.push(e.slice(c,c+t));return o}let s=r.reduce((c,l)=>c+l,0)/r.length,i=[],a=0;for(let c of e){let l=Number.isFinite(n[c])&&n[c]>0?n[c]:s;i.length&&a+l>WZ&&(o.push(i),i=[],a=0),i.push(c),a+=l}return i.length&&o.push(i),o}function vN({runners:e=[],testFiles:t=[],selection:n=null,durations:r={},workerLimit:o=1}={}){let s=n?.test_files?new Set(n.test_files.map(Sb)):null,i=[];for(let l of e){let u=YZ(l);u.support!=="helper"&&i.push({index:i.length,name:l.name,root:Sb(l.root),ecosystem:l.ecosystem??null,run_command:l.run_command??null,support:u.support,reason:u.reason??null,files:[],shards:[]})}for(let l of t.map(u=>({...u,file:Sb(u.file)})))s&&!s.has(l.file)||QZ(l,i.filter(u=>u.support==="run"))?.files.push(l.file);for(let l of i){if(l.files=[...new Set(l.files)].sort(),l.support!=="run")continue;if(!l.files.length){l.support="skipped",l.reason=s?"None of the selected test files belong to it.":"No test files were found for it.";continue}let u=tQ(l,r);l.shards=u.map(({files:d,packages:p},f)=>({id:`${l.index}-${f}`,index:f,total:u.length,files:d,directory:l.root,packages:p}))}let a=Number(o);return{concurrency:Math.max(1,Math.min(JZ,Number.isInteger(a)&&a>0?a:1)),runners:i.map(({files:l,...u})=>u)}}function tQ(e,t){if(e.name==="go-test"){let n=new Map;for(let r of e.files){let o=e.root?r.slice(e.root.length+1):r,s=GZ.posix.dirname(o);n.set(s,[...n.get(s)??[],r])}return[...n.entries()].map(([r,o])=>({files:o,packages:[r==="."?".":r]}))}return e.name==="junit"?[{files:e.files,packages:[]}]:eQ(e.files,{perShard:VZ[e.name]??40,durations:t}).map(n=>({files:n,packages:[]}))}var rQ=4;function fm(e,t,n,{secretNames:r=[]}={}){let o=t.executionProfiles||{model_selection:!1,model_profiles:[],reasoning_efforts:[]},s=t.sessionStatus||{status:"unknown",message:"Agent authentication status was not reported.",login_command:null,logout_command:null},i=H$(t.protocol);return{agent_protocols:[t.protocol],coding_agent:!0,connector_jobs:!0,self_contained_prompts:1,bug_hunt_development_v1:!0,...e.hunt_host?{hunt_host:!0}:{},capability_delivery:!e.hunt_host,goal_plan_review:!e.hunt_host&&(t.protocol==="codex"||e.agent_id==="codex-acp"&&e.agent_modes?.["read-only"]==="read-only"||e.agent_id==="claude-acp"&&e.agent_modes?.["read-only"]==="plan"||e.agent_id==="antigravity-acp"||e.agent_id==="opencode"&&(!e.agent_modes?.["read-only"]||e.agent_modes["read-only"]==="plan")),measured_test_evidence:!e.hunt_host,test_automation_task:!e.hunt_host,test_checks:!e.hunt_host&&String(process.env.ENGINEEROS_TEST_CHECKS??"").trim().toLowerCase()!=="off",test_automation_workers:!e.hunt_host,model_probe:!0,test_schedules:!e.hunt_host,quality_baseline:!e.hunt_host&&pm(e),quality_baseline_contract:yN,quality_map:!e.hunt_host,workspace_head:!e.hunt_host,bug_hunt:!0,bug_hunt_scenarios:zI,bug_hunt_performance:1,bug_hunt_specialists:1,bug_hunt_actions:[...Ih],bug_hunt_electron:process.env.ENGINEEROS_HUNT_HOST==="dedicated",bug_hunt_webdriver:!0,bug_hunt_native:!0,bug_hunt_browser:Pa(n),bug_hunt_sign_in:Na,bug_hunt_inputs:1,bug_hunt_checks:[...Fv],bug_hunt_secret_names:[...r],resumable_runs:!e.hunt_host,goal_recovery:e.hunt_host?0:1,goal_run_contract:rQ,delivery_tasks:{protocol_version:1,backend_contract:1,schema_revision:"20261027_000183",connector_version:"1.59.69",runtime:e.agent_id||t.protocol,runtime_version:t.version||null,adapter_version:"1",worker_version:vh,operations:e.hunt_host?[]:["start","cancel"]},http_updates:!0,product_stage_handover:!e.hunt_host,local_design_context:!e.hunt_host,agent_warm:!e.hunt_host,test_environments:!0,integrations:!0,workspace_opportunities:!e.hunt_host,codex_cli:t.protocol==="codex",platform:process.platform,workspace_name:nQ.basename(e.workspace),agent_name:t.name,agent_version:t.version,...e.agent_id?{agent_id:e.agent_id}:{},...Vu(e.worker_limit),agent_session:s,provider_login:{supported:i,mode:i?"connector_terminal":null},...l1(),...n?{tool_inventory:n}:{},execution_profiles:{...o,models:(o.model_profiles||[]).map(a=>a.id)}}}N();hn();ua();import{createHash as kN}from"node:crypto";import{readFile as oQ}from"node:fs/promises";import sQ from"node:os";import Eb from"node:path";var iQ=/^[A-Z_][A-Z0-9_]*$/,aQ=80,cQ=64,bN="hunt-secret-";function Ed(e){return typeof e=="string"&&e.length>0&&e.length<=aQ&&iQ.test(e)}function hm(e){let t=`${bN}${String(e).toLowerCase().replace(/_/g,"-")}`;return t.length<=cQ?t:`${bN}h${kN("sha256").update(String(e)).digest("hex").slice(0,40)}`}function lQ(e){let t=kN("sha256").update(Eb.resolve(e??process.cwd())).digest("hex").slice(0,16);return Eb.join(sQ.homedir(),".engineeros","hunt-secrets",t)}function xb(e){if(!Ed(e))throw new Error("A secret name uses capital letters, digits and underscores, for example ADMIN_TOTP_SECRET.");return e}function $d({workspace:e=process.cwd(),vault:t,directory:n}={}){let r=n??lQ(e),o=t??dr({directory:r}),s=Eb.join(r,"names.json");async function i(){let u;try{u=await oQ(s,"utf8")}catch(d){if(d?.code==="ENOENT")return[];throw d}try{let d=JSON.parse(u);return(Array.isArray(d?.names)?d.names:[]).filter(Ed)}catch{return[]}}let a=Promise.resolve(),c=u=>{let d=a.then(async()=>{let p=new Set(await i());u(p),await Fe(s,`${JSON.stringify({names:[...p].sort()},null,2)}
2640
+ `)}async function mN(e,t,n){return!e?.connector_id||!e.token?null:await n(e,{type:jZ,...t})??{}}function PZ(e){let t=Number.parseInt(String(e).replace(/^v/,""),10);return Number.isFinite(t)&&t>=bb?rn("node_runtime","Node runtime","ok",`Node ${e}.`):rn("node_runtime","Node runtime","failed",`Node ${e} is older than the Node ${bb} this connector requires.`,`Install Node ${bb} or later, then start the connector again.`)}function MZ(e){return e?.connector_id&&e.token?rn("pairing","Workspace pairing","ok",`Paired as ${e.name||e.connector_id} for ${e.workspace}.`):rn("pairing","Workspace pairing","failed","This workspace holds no connector credential.","Create a pairing command in EngineerOS and run it in this folder.")}async function DZ(e,t){if(!e?.server_url)return rn("backend","EngineerOS backend","failed","No EngineerOS address is configured.","Pair this workspace with --url pointing at the EngineerOS backend.");let n=kS(e.server_url),r;try{r=await t(n,{signal:AbortSignal.timeout(1e4)})}catch(s){return rn("backend","EngineerOS backend","failed",`${n} is unreachable from this machine: ${_n(s,{network:!0})}`,"Check the address, the network between this machine and EngineerOS, and that the backend is running.")}if(!r.ok)return rn("backend","EngineerOS backend","failed",`${n} answered ${r.status}.`,"Check that the address points at the EngineerOS backend rather than another service.");let o=await r.json().then(s=>s?.status).catch(()=>{});return o&&o!=="healthy"?rn("backend","EngineerOS backend","warning",`${n} reports itself as ${o}.`,"Open Admin > System in EngineerOS for the failing dependency."):rn("backend","EngineerOS backend","ok",`${n} is reachable.`)}async function LZ(e,t,n,r){try{let o=await n(e,t),s=`${o.name} ${o.version} through ${o.protocol}.`,i=String(o.version??"").match(/\d+\.\d+\.\d+/)?.[0],a=i?await UZ(o.protocol,r):null;return a&&To(a,i)>0?rn("coding_agent","Coding agent","warning",`${s} ${o.name} ${a} is available.`,fN[o.protocol].remedy):rn("coding_agent","Coding agent","ok",s)}catch(o){return rn("coding_agent","Coding agent","failed",gN(o),null)}}async function UZ(e,t){let n=fN[e];if(!n)return null;let r=pN.get(t)??new Map;pN.set(t,r);let o=r.get(e);if(o&&Date.now()-o.at<IZ)return o.version;let s=null;try{let i=await t(n.url,{headers:{accept:"application/json"},signal:AbortSignal.timeout(5e3)}),a=i.ok?n.version(await i.json()):null;xn(a)&&(s=a)}catch{}return r.set(e,{at:Date.now(),version:s}),s}function FZ({state:e,detail:t,remedy:n=null}){return rn("agent_session","Coding agent session",e==="ready"?"ok":e==="checking"?"warning":"failed",t,n)}async function qZ(e){let t=await e(),n=t.filter(o=>o.status==="blocked");if(n.length){let o=n[0];return rn("local_execution","Local testing work","failed",`${n.length} local testing job(s) are blocked. ${o.blocked_report?.error?.message||o.error||o.checkpoint?.error||"An execution or report was refused; its original evidence remains saved on this machine."}`,"Inspect the saved connector job and its first blocked report on this machine. Fix the reported cause, then explicitly retry report delivery; do not rerun completed tests or delete their evidence.")}let r=t.flatMap(o=>Object.values(o.checkpoint?.server_effects??{}).flatMap(s=>s.response?.projection_warnings??[]));return r.length?rn("local_execution","Local testing work","warning",`${r.length} result(s) were retained as history only. ${r[0].reason}`,"Inspect the saved result receipt and its execution context. History-only results do not verify a pass or resolve a finding; preserve their evidence and supply the reported prerequisite before a new authorized execution."):rn("local_execution","Local testing work","ok","No local testing jobs are blocked.")}async function zZ(e,t){let n=await t(e);if(n?.error)return rn("tool_registry","Tool registry","warning",n.error,"Run `engineeros-connector tools list` in this workspace for the full registry state.");let r=n?.entries?.length||0;return rn("tool_registry","Tool registry","ok",`${r} provider(s) registered.`)}async function BZ(e,t,{platform:n=process.platform,serviceStatus:r=yI}={}){if(n==="darwin"){let i=await r(e),a=`Run engineeros-connector runner start --workspace "${e}".`;if(i.disabled)return rn("goal_runner","Goal runner","warning","The macOS Goal runner is disabled.",`Turn it on in System Settings > General > Login Items. ${a}`);if(!i.loaded)return rn("goal_runner","Goal runner","warning",i.installed?"The macOS Goal runner is not loaded in this login session.":"The macOS Goal runner is not installed.",a);if(i.lastExitCode&&i.state!=="running")return rn("goal_runner","Goal runner","warning",`The macOS Goal runner exited with status ${i.lastExitCode} (${i.state||"unknown state"}).`,`Read .engineeros/runner/launchd.log. For protected folders, allow node under Privacy & Security > Files and Folders, or move the workspace. ${a}`)}let{jobs:o}=await t(e),s=o.filter(i=>["failed","recovering"].includes(i.status));if(s.length){let i=s[0];return rn("goal_runner","Goal runner","warning",`${s.length} local Goal job(s) need attention. ${i.runId} is ${i.status}${i.error?`: ${i.error}`:"."}`,"Open the Goal in EngineerOS, or read .engineeros/runs/<run-id>/activity.log in this workspace.")}return rn("goal_runner","Goal runner","ok",`${o.length} local Goal job(s) recorded, none stuck.`)}function HZ(e){return rn(e.id,e.title,e.status,`Failing since ${so(e.firstFailedAt)} after ${e.failures} attempt(s); retrying in ${Math.round(e.retryInMs/1e3)}s. ${e.message}`,e.remedy)}async function Sd(e,t,n){try{return await n()}catch(r){return rn(e,t,"failed",gN(r),null)}}function rn(e,t,n,r,o=null){return{id:e,title:t,status:n,detail:String(r||"No detail was reported.").slice(0,RZ),remedy:o?String(o).slice(0,OZ):null}}function gN(e){return(e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported."}N();import nQ from"node:path";N();import GZ from"node:path";var yN=3,WZ=300*1e3,VZ={pytest:40,"node:test":40,vitest:60,jest:60},JZ=3,XZ=new Set(["pytest","vitest","jest","node:test","go-test","junit"]),KZ=new Set(["pytest-asyncio","pytest-cov","hypothesis","schemathesis","locust","bandit","pip-audit","@testing-library/react","@axe-core/playwright","k6","testify"]),wN=new Map([["@playwright/test","It drives a browser against the running app. Add an environment, then schedule it."],["cypress","It drives a browser against the running app. Add an environment, then schedule it."]]);function pm(e,t=process.env){return e?.quality_baseline===!1?!1:!["off","0","false","no"].includes(String(t.ENGINEEROS_QUALITY_BASELINE??"").trim().toLowerCase())}function _N(e=process.env){let t=Number(e.ENGINEEROS_BASELINE_IDLE_MS);return Number.isFinite(t)&&t>0?Math.floor(t):600*1e3}function YZ(e){let t=String(e?.name??"");return KZ.has(t)?{support:"helper"}:XZ.has(t)?{support:"run"}:wN.has(t)?{support:"skipped",reason:wN.get(t)}:{support:"unsupported",reason:`There is no baseline recipe for ${t||"this runner"}. Schedule its command and upload the JUnit report instead.`}}var Sb=e=>String(e??"").replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,""),ZZ=(e,t)=>!t||e.startsWith(`${t}/`);function QZ(e,t){let n=null;for(let r of t)r.name!==e.framework||!ZZ(e.file,r.root)||(!n||r.root.length>n.root.length)&&(n=r);return n}function eQ(e,{perShard:t,durations:n}){let r=e.map(c=>n[c]).filter(c=>Number.isFinite(c)&&c>0),o=[];if(!r.length){for(let c=0;c<e.length;c+=t)o.push(e.slice(c,c+t));return o}let s=r.reduce((c,l)=>c+l,0)/r.length,i=[],a=0;for(let c of e){let l=Number.isFinite(n[c])&&n[c]>0?n[c]:s;i.length&&a+l>WZ&&(o.push(i),i=[],a=0),i.push(c),a+=l}return i.length&&o.push(i),o}function vN({runners:e=[],testFiles:t=[],selection:n=null,durations:r={},workerLimit:o=1}={}){let s=n?.test_files?new Set(n.test_files.map(Sb)):null,i=[];for(let l of e){let u=YZ(l);u.support!=="helper"&&i.push({index:i.length,name:l.name,root:Sb(l.root),ecosystem:l.ecosystem??null,run_command:l.run_command??null,support:u.support,reason:u.reason??null,files:[],shards:[]})}for(let l of t.map(u=>({...u,file:Sb(u.file)})))s&&!s.has(l.file)||QZ(l,i.filter(u=>u.support==="run"))?.files.push(l.file);for(let l of i){if(l.files=[...new Set(l.files)].sort(),l.support!=="run")continue;if(!l.files.length){l.support="skipped",l.reason=s?"None of the selected test files belong to it.":"No test files were found for it.";continue}let u=tQ(l,r);l.shards=u.map(({files:d,packages:p},f)=>({id:`${l.index}-${f}`,index:f,total:u.length,files:d,directory:l.root,packages:p}))}let a=Number(o);return{concurrency:Math.max(1,Math.min(JZ,Number.isInteger(a)&&a>0?a:1)),runners:i.map(({files:l,...u})=>u)}}function tQ(e,t){if(e.name==="go-test"){let n=new Map;for(let r of e.files){let o=e.root?r.slice(e.root.length+1):r,s=GZ.posix.dirname(o);n.set(s,[...n.get(s)??[],r])}return[...n.entries()].map(([r,o])=>({files:o,packages:[r==="."?".":r]}))}return e.name==="junit"?[{files:e.files,packages:[]}]:eQ(e.files,{perShard:VZ[e.name]??40,durations:t}).map(n=>({files:n,packages:[]}))}var rQ=4;function fm(e,t,n,{secretNames:r=[]}={}){let o=t.executionProfiles||{model_selection:!1,model_profiles:[],reasoning_efforts:[]},s=t.sessionStatus||{status:"unknown",message:"Agent authentication status was not reported.",login_command:null,logout_command:null},i=H$(t.protocol);return{agent_protocols:[t.protocol],coding_agent:!0,connector_jobs:!0,self_contained_prompts:1,bug_hunt_development_v1:!0,...e.hunt_host?{hunt_host:!0}:{},capability_delivery:!e.hunt_host,goal_plan_review:!e.hunt_host&&(t.protocol==="codex"||e.agent_id==="codex-acp"&&e.agent_modes?.["read-only"]==="read-only"||e.agent_id==="claude-acp"&&e.agent_modes?.["read-only"]==="plan"||e.agent_id==="antigravity-acp"||e.agent_id==="opencode"&&(!e.agent_modes?.["read-only"]||e.agent_modes["read-only"]==="plan")),measured_test_evidence:!e.hunt_host,test_automation_task:!e.hunt_host,test_checks:!e.hunt_host&&String(process.env.ENGINEEROS_TEST_CHECKS??"").trim().toLowerCase()!=="off",test_automation_workers:!e.hunt_host,model_probe:!0,test_schedules:!e.hunt_host,quality_baseline:!e.hunt_host&&pm(e),quality_baseline_contract:yN,quality_map:!e.hunt_host,workspace_head:!e.hunt_host,bug_hunt:!0,bug_hunt_scenarios:zI,bug_hunt_performance:1,bug_hunt_specialists:1,bug_hunt_actions:[...Ih],bug_hunt_electron:process.env.ENGINEEROS_HUNT_HOST==="dedicated",bug_hunt_webdriver:!0,bug_hunt_native:!0,bug_hunt_browser:Pa(n),bug_hunt_sign_in:Na,bug_hunt_inputs:1,bug_hunt_checks:[...Fv],bug_hunt_secret_names:[...r],resumable_runs:!e.hunt_host,goal_recovery:e.hunt_host?0:1,goal_run_contract:rQ,delivery_tasks:{protocol_version:1,backend_contract:1,schema_revision:"20261027_000183",connector_version:"1.59.70",runtime:e.agent_id||t.protocol,runtime_version:t.version||null,adapter_version:"1",worker_version:vh,operations:e.hunt_host?[]:["start","cancel"]},http_updates:!0,product_stage_handover:!e.hunt_host,local_design_context:!e.hunt_host,agent_warm:!e.hunt_host,test_environments:!0,integrations:!0,workspace_opportunities:!e.hunt_host,codex_cli:t.protocol==="codex",platform:process.platform,workspace_name:nQ.basename(e.workspace),agent_name:t.name,agent_version:t.version,...e.agent_id?{agent_id:e.agent_id}:{},...Vu(e.worker_limit),agent_session:s,provider_login:{supported:i,mode:i?"connector_terminal":null},...l1(),...n?{tool_inventory:n}:{},execution_profiles:{...o,models:(o.model_profiles||[]).map(a=>a.id)}}}N();hn();ua();import{createHash as kN}from"node:crypto";import{readFile as oQ}from"node:fs/promises";import sQ from"node:os";import Eb from"node:path";var iQ=/^[A-Z_][A-Z0-9_]*$/,aQ=80,cQ=64,bN="hunt-secret-";function Ed(e){return typeof e=="string"&&e.length>0&&e.length<=aQ&&iQ.test(e)}function hm(e){let t=`${bN}${String(e).toLowerCase().replace(/_/g,"-")}`;return t.length<=cQ?t:`${bN}h${kN("sha256").update(String(e)).digest("hex").slice(0,40)}`}function lQ(e){let t=kN("sha256").update(Eb.resolve(e??process.cwd())).digest("hex").slice(0,16);return Eb.join(sQ.homedir(),".engineeros","hunt-secrets",t)}function xb(e){if(!Ed(e))throw new Error("A secret name uses capital letters, digits and underscores, for example ADMIN_TOTP_SECRET.");return e}function $d({workspace:e=process.cwd(),vault:t,directory:n}={}){let r=n??lQ(e),o=t??dr({directory:r}),s=Eb.join(r,"names.json");async function i(){let u;try{u=await oQ(s,"utf8")}catch(d){if(d?.code==="ENOENT")return[];throw d}try{let d=JSON.parse(u);return(Array.isArray(d?.names)?d.names:[]).filter(Ed)}catch{return[]}}let a=Promise.resolve(),c=u=>{let d=a.then(async()=>{let p=new Set(await i());u(p),await Fe(s,`${JSON.stringify({names:[...p].sort()},null,2)}
2641
2641
  `)});return a=d.catch(()=>{}),d},l={directory:r,async get(u){xb(u);let d=await o.get(e,hm(u));return typeof d=="string"&&d!==""?d:null},async set(u,d){if(xb(u),typeof d!="string"||d==="")throw new Error("A secret needs a value.");await o.put(e,hm(u),d),await c(p=>p.add(u))},async remove(u){xb(u),await o.delete(e,hm(u)),await c(d=>d.delete(u))},async names(){return(await i()).sort()},async has(u){return Ed(u)?!!await o.has(e,hm(u)):!1},async values(u){let d={};for(let p of[...new Set(u??[])]){if(!Ed(p))continue;let f=await l.get(p);f!==null&&(d[p]=f)}return d}};return l}async function SN({input:e=process.stdin,output:t=process.stderr,label:n="Value"}={}){if(!e.isTTY){let r=[];for await(let o of e)r.push(Buffer.from(o));return Buffer.concat(r).toString("utf8")}return t.write(`${n} (typing is hidden): `),await new Promise((r,o)=>{let s="";e.setRawMode?.(!0),e.resume(),e.setEncoding("utf8");let i=c=>{e.setRawMode?.(!1),e.pause(),e.off("data",a),t.write(`
2642
2642
  `),c?o(c):r(s)},a=c=>{for(let l of c){if(l==="\r"||l===`
2643
2643
  `||l==="")return i();if(l==="")return i(new Error("Cancelled."));l==="\x7F"||l==="\b"?s=s.slice(0,-1):s+=l}};e.on("data",a)})}var xd=(e,t)=>(t?.(e),{ok:!1,message:e});async function xN({action:e,name:t,workspace:n=process.cwd(),readValue:r,vault:o,directory:s,write:i}={}){let a=(l,u)=>(i?.(u),{ok:l,message:u});if(e!=="set"&&e!=="list"&&e!=="remove")return xd("Use `secret set NAME`, `secret list` or `secret remove NAME`.",i);let c=$d({workspace:n,vault:o,directory:s});try{if(e==="list"){let d=await c.names();return a(!0,d.length?d.join(`
@@ -2858,7 +2858,7 @@ It is checked with the provider and stored in this machine's protected vault
2858
2858
  (Windows Data Protection, the macOS Keychain or the Linux Secret Service).
2859
2859
  EngineerOS never receives it; the running connector uses it when EngineerOS asks.`;function Kie(e,{input:t=process.stdin,output:n=process.stdout}={}){return t.isTTY?new Promise((r,o)=>{n.write(e);let s="";t.setRawMode(!0),t.resume(),t.setEncoding("utf8");let i=c=>{t.setRawMode(!1),t.pause(),t.removeListener("data",a),n.write(`
2860
2860
  `),c?o(c):r(s.trim())},a=c=>{for(let l of c){if(l==="\r"||l===`
2861
- `)return i();if(l==="")return i(new Error("Cancelled."));l==="\x7F"||l==="\b"?s=s.slice(0,-1):s+=l}};t.on("data",a)}):new Promise((r,o)=>{let s="";t.setEncoding("utf8"),t.on("data",i=>s+=i),t.on("end",()=>r(s.trim())),t.on("error",o)})}var VD=Symbol("missing");function Yie(e,t){return new Promise(n=>{let r=Jie(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?VD:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function WD(e,t){for(let n of Wd){let r=t[n],o=r.connected?`connected${r.account?` as ${r.account}`:""}`:"not connected";e(`${n.padEnd(8)} ${o}`),r.connected||e(` ${r.detail?`${r.detail} `:""}Connect: ${r.connect_command}`)}}async function JD(e,t,n,{vault:r=G0(),run:o=Km,fetchImpl:s=fetch,secret:i=Kie,interactive:a=Yie,install:c=Wm,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(Xie),n.help?0:2;if(e==="integrations")return WD(l,(await eg({run:o,vault:r})).providers),0;let d=t[0];if(!Wd.includes(d))return u(`Unknown provider ${d}. Choose one of: ${Wd.join(", ")}.`),2;if(d==="github"||d==="gitlab"){let f=Ha[d];if(e==="disconnect")return l(`${d} uses this machine's ${f} sign-in. Run \`${f} auth logout\` to sign out everywhere on this machine.`),0;let g=await a(f,["auth","login"]);if(g===VD){let y=await Ki(f);if(!y){l(`Installing the ${Ud[f].label} ${Ud[f].version} for the connector...`);try{y=(await c(f)).path}catch(k){return u(k.message),1}}g=await a(y,["auth","login"])}return g?(u(`${g} ${Qm[d]} is how this machine signs in to ${d}.`),1):(WD(l,{[d]:(await eg({run:o,vault:r})).providers[d]}),0)}let p=or[d];if(e==="disconnect")return await r.delete("",d),l(`Removed the ${p.label} ${p.tokenName} from this machine.`),0;try{await W0(r);let f=await i(`${p.label} ${p.tokenName} (create one at ${p.tokenUrl}): `),g=await V0(r,d,{token:f,site:n.site,email:n.email},s);return l(`Connected ${p.label}${g.account?` as ${g.account}`:""}. The token stays on this machine.`),0}catch(f){return u(f.message),1}}N();import{spawn as Zie}from"node:child_process";async function XD({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=Zie,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=pi(await xr(e),t)}catch(d){s(`${d.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await Qie(o,c.entry,i,t);if(l===Fl){i=["start","--workspace",r],a=!1,s("Restarting the connector process on the activated update. Goal runs continue in their own processes.");continue}if(l!==0&&!u&&!a){let d=await xr(e).catch(()=>null);if(d&&!d.confirmed&&d.active?.version===c.version)try{let p=await Mg(e,{version:c.version,entry:c.entry,bundled:t},{automatic:!0,reason:`${c.version} exited with code ${l} before connecting to EngineerOS.`});a=!0,s(`Connector ${c.version} stopped before connecting; rolled back to ${p.version}.`);continue}catch(p){s(`Automatic rollback failed: ${p.message}`)}}return l??1}}function Qie(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[nc]:"1",[Cg]:r.entry,[Ig]:r.version}}),a=process.platform==="win32"?[]:["SIGINT","SIGTERM","SIGHUP"],c=u=>i.kill(u);for(let u of a)process.on(u,c);let l=()=>{for(let u of a)process.off(u,c)};i.once("error",u=>{l(),s(u)}),i.once("exit",(u,d)=>{l(),o({code:u,signal:d})})})}var ta="1.59.69",cg="1.59.69",rae=3e5,lg=["queued","running","reporting"],oae=5e3,J0={id:"design_sync",title:"Design artifact sync",remedy:"Fix the reported problem in this workspace. The connector retries on its own; it does not need restarting."},X0={id:"opportunity_scan",title:"Workspace opportunity scan",remedy:"EngineerOS asked this workspace what to deliver next and the scan failed. Check that the coding agent still answers here, or turn autonomy off in Project steering."},sae=6e4,iae=3e4,aae=60*6e4,K0={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},Y0={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:pn,positional:fn,flags:et}=EN(process.argv.slice(2));pn==="version"&&(console.log(ta),process.exit(0));var Qs=null,dn=!1,sr=null,Yd=null,u2=!1,d2=null,fk=null,kn=null,np=null,ck,KD,Zd,Qd,YD,kl,Ol,p2=Pm({getWorkspace:()=>U.workspace,onRecorded:e=>CM(U,e).then(()=>console.log(`Recorded the ${e.role} sign-in for Bug Hunter; it is kept on this machine.`)).catch(t=>console.error(`The recorded ${e.role} sign-in was not reported to EngineerOS: ${t.message}`))}),cae=HD({getWorkspace:()=>U.workspace,getConfig:()=>U,huntSignIns:p2}),ep=RN();pn==="results"&&(fn[0]!=="upload"&&(console.log(Sm),process.exit(et.help||!fn[0]?0:2)),process.exit(await MP(et)));(pn==="connect"||pn==="disconnect"||pn==="integrations")&&process.exit(await JD(pn,fn,et,{fetchImpl:qD}));if(pn==="delivery"){let e=bn.resolve(et.workspace||process.cwd());try{if(fn[0]==="execute")await OI(et.input);else if(fn[0]==="worker"){let t=await Bn(e);if(!t)throw new Error("Restore the paired connector configuration before reporting or executing delivery work.");await iI(t,et["attempt-id"])}else if(fn[0]==="probe"){let t=await bh().probe();console.log(JSON.stringify(t))}else throw new Error("Use delivery worker --attempt-id <attempt>, delivery execute --input <file> inside the qualified image, or delivery probe.");process.exit(0)}catch(t){console.error(_n(t)),process.exit(1)}}if(pn==="runner"){let e=bn.resolve(et.workspace||process.cwd()),t=fn[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?bn.join(bn.dirname(gn(e,et["run-id"])),"worker.log"):bn.join(e,".engineeros","runner","service.log");tae(bn.dirname(n),{recursive:!0});let r=(...s)=>Ju(n,`${nae(...s)}
2861
+ `)return i();if(l==="")return i(new Error("Cancelled."));l==="\x7F"||l==="\b"?s=s.slice(0,-1):s+=l}};t.on("data",a)}):new Promise((r,o)=>{let s="";t.setEncoding("utf8"),t.on("data",i=>s+=i),t.on("end",()=>r(s.trim())),t.on("error",o)})}var VD=Symbol("missing");function Yie(e,t){return new Promise(n=>{let r=Jie(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?VD:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function WD(e,t){for(let n of Wd){let r=t[n],o=r.connected?`connected${r.account?` as ${r.account}`:""}`:"not connected";e(`${n.padEnd(8)} ${o}`),r.connected||e(` ${r.detail?`${r.detail} `:""}Connect: ${r.connect_command}`)}}async function JD(e,t,n,{vault:r=G0(),run:o=Km,fetchImpl:s=fetch,secret:i=Kie,interactive:a=Yie,install:c=Wm,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(Xie),n.help?0:2;if(e==="integrations")return WD(l,(await eg({run:o,vault:r})).providers),0;let d=t[0];if(!Wd.includes(d))return u(`Unknown provider ${d}. Choose one of: ${Wd.join(", ")}.`),2;if(d==="github"||d==="gitlab"){let f=Ha[d];if(e==="disconnect")return l(`${d} uses this machine's ${f} sign-in. Run \`${f} auth logout\` to sign out everywhere on this machine.`),0;let g=await a(f,["auth","login"]);if(g===VD){let y=await Ki(f);if(!y){l(`Installing the ${Ud[f].label} ${Ud[f].version} for the connector...`);try{y=(await c(f)).path}catch(k){return u(k.message),1}}g=await a(y,["auth","login"])}return g?(u(`${g} ${Qm[d]} is how this machine signs in to ${d}.`),1):(WD(l,{[d]:(await eg({run:o,vault:r})).providers[d]}),0)}let p=or[d];if(e==="disconnect")return await r.delete("",d),l(`Removed the ${p.label} ${p.tokenName} from this machine.`),0;try{await W0(r);let f=await i(`${p.label} ${p.tokenName} (create one at ${p.tokenUrl}): `),g=await V0(r,d,{token:f,site:n.site,email:n.email},s);return l(`Connected ${p.label}${g.account?` as ${g.account}`:""}. The token stays on this machine.`),0}catch(f){return u(f.message),1}}N();import{spawn as Zie}from"node:child_process";async function XD({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=Zie,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=pi(await xr(e),t)}catch(d){s(`${d.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await Qie(o,c.entry,i,t);if(l===Fl){i=["start","--workspace",r],a=!1,s("Restarting the connector process on the activated update. Goal runs continue in their own processes.");continue}if(l!==0&&!u&&!a){let d=await xr(e).catch(()=>null);if(d&&!d.confirmed&&d.active?.version===c.version)try{let p=await Mg(e,{version:c.version,entry:c.entry,bundled:t},{automatic:!0,reason:`${c.version} exited with code ${l} before connecting to EngineerOS.`});a=!0,s(`Connector ${c.version} stopped before connecting; rolled back to ${p.version}.`);continue}catch(p){s(`Automatic rollback failed: ${p.message}`)}}return l??1}}function Qie(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[nc]:"1",[Cg]:r.entry,[Ig]:r.version}}),a=process.platform==="win32"?[]:["SIGINT","SIGTERM","SIGHUP"],c=u=>i.kill(u);for(let u of a)process.on(u,c);let l=()=>{for(let u of a)process.off(u,c)};i.once("error",u=>{l(),s(u)}),i.once("exit",(u,d)=>{l(),o({code:u,signal:d})})})}var ta="1.59.70",cg="1.59.70",rae=3e5,lg=["queued","running","reporting"],oae=5e3,J0={id:"design_sync",title:"Design artifact sync",remedy:"Fix the reported problem in this workspace. The connector retries on its own; it does not need restarting."},X0={id:"opportunity_scan",title:"Workspace opportunity scan",remedy:"EngineerOS asked this workspace what to deliver next and the scan failed. Check that the coding agent still answers here, or turn autonomy off in Project steering."},sae=6e4,iae=3e4,aae=60*6e4,K0={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},Y0={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:pn,positional:fn,flags:et}=EN(process.argv.slice(2));pn==="version"&&(console.log(ta),process.exit(0));var Qs=null,dn=!1,sr=null,Yd=null,u2=!1,d2=null,fk=null,kn=null,np=null,ck,KD,Zd,Qd,YD,kl,Ol,p2=Pm({getWorkspace:()=>U.workspace,onRecorded:e=>CM(U,e).then(()=>console.log(`Recorded the ${e.role} sign-in for Bug Hunter; it is kept on this machine.`)).catch(t=>console.error(`The recorded ${e.role} sign-in was not reported to EngineerOS: ${t.message}`))}),cae=HD({getWorkspace:()=>U.workspace,getConfig:()=>U,huntSignIns:p2}),ep=RN();pn==="results"&&(fn[0]!=="upload"&&(console.log(Sm),process.exit(et.help||!fn[0]?0:2)),process.exit(await MP(et)));(pn==="connect"||pn==="disconnect"||pn==="integrations")&&process.exit(await JD(pn,fn,et,{fetchImpl:qD}));if(pn==="delivery"){let e=bn.resolve(et.workspace||process.cwd());try{if(fn[0]==="execute")await OI(et.input);else if(fn[0]==="worker"){let t=await Bn(e);if(!t)throw new Error("Restore the paired connector configuration before reporting or executing delivery work.");await iI(t,et["attempt-id"])}else if(fn[0]==="probe"){let t=await bh().probe();console.log(JSON.stringify(t))}else throw new Error("Use delivery worker --attempt-id <attempt>, delivery execute --input <file> inside the qualified image, or delivery probe.");process.exit(0)}catch(t){console.error(_n(t)),process.exit(1)}}if(pn==="runner"){let e=bn.resolve(et.workspace||process.cwd()),t=fn[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?bn.join(bn.dirname(gn(e,et["run-id"])),"worker.log"):bn.join(e,".engineeros","runner","service.log");tae(bn.dirname(n),{recursive:!0});let r=(...s)=>Ju(n,`${nae(...s)}
2862
2862
  `),o=(s,i,a)=>(Ju(n,s),(typeof i=="function"?i:a)?.(),!0);process.stdout.write=process.stderr.write=o,console.log=console.error=console.warn=r}if(t==="install"){if(et["keep-awake"]!==void 0){if(!["on","off"].includes(et["keep-awake"]))throw new Error("Use --keep-awake on or off.");let n=await Bn(e);if(!n)throw new Error("Pair this workspace before changing its runner keep-awake setting.");await Wr({...n,runner_keep_awake:et["keep-awake"]==="on"})}console.log(`Installed Goal runner service: ${await gI(e)}`),process.platform==="darwin"&&console.log("macOS may show a Background Items Added notice. Manage the runner in System Settings > General > Login Items.")}else t==="uninstall"?(await _I(e),console.log("Goal runner service removed. Saved and queued jobs are kept.")):t==="start"?await Aa(e,{enable:!0}):t==="status"?console.log(JSON.stringify(await ji(e),null,2)):t==="serve"?await SI(e):t==="worker"?await xI(e,et["run-id"]):on("Usage: engineeros-connector runner [install|start|status|uninstall] --workspace PATH [--keep-awake on|off]");process.exit(0)}catch(n){on(jv(n,e).message)}}et["assessment-workers"]!==void 0&&on("--assessment-workers is no longer supported. Select 3 to 8 parallel agents in EngineerOS before starting the assessment.");if(pn==="secret")try{let e=Dv(et),t=fn[0]||"list",n=await xN({action:t,name:fn[1],workspace:e,readValue:()=>SN({label:`Value for ${fn[1]}`}),write:r=>console.log(r)});process.exit(n.ok?0:1)}catch(e){on(e.message)}if(pn==="tools"){try{let e=Dv(et),t=fn[0]||"list";if(["sign-in","auth-status","sign-out"].includes(t)){let r=fn[1];r||on(`Usage: engineeros-connector tools ${t} PROVIDER_ID [--workspace PATH | --project PROJECT_UUID]`);let o=await n_(e,{type:"tools.auth",command_id:"00000000-0000-4000-8000-000000000001",action:{"sign-in":"sign_in","auth-status":"status","sign-out":"sign_out"}[t],provider_id:r,confirmed:t==="sign-out"});o.completion&&await o.completion}else["setup","upgrade","rollback"].includes(t)?await Zy(e,{type:"tools.update",command_id:"00000000-0000-4000-8000-000000000002",action:t,provider_id:fn[1],confirmed:!0},void 0,{confirmLocal:async()=>!0}):t!=="list"&&await Yy(e,t,fn[1]);let n=await to(e);console.log(JSON.stringify(n,null,2)),process.exitCode=n.error?1:0}catch(e){on(e.message)}process.exit(process.exitCode||0)}if(pn==="agents"){let e;try{e=await v_()}catch(n){on(n instanceof Error?n.message:String(n))}let t=await Promise.all(e.map(async n=>{try{return await Pu(n.id),`${n.id}: ready (${n.name} ${n.version}, ${n.distribution_type})`}catch(r){let o=r instanceof Error?r.message:String(r);return`${n.id}: setup needed (${n.name} ${n.version}, ${n.distribution_type}) - ${o}`}}));for(let n of t)console.log(n);process.exit(0)}if(pn==="agent"){let e=fn[0],t=fn[1]||"check";(!e||!["check","install"].includes(t))&&on("Usage: engineeros-connector agent AGENT_ID [check|install]");try{let n=t==="install"?await Mu(e):await Pu(e);console.log(`${n.name} is ready (${n.version}, ${n.distribution}).`)}catch(n){on(n instanceof Error?n.message:String(n))}process.exit(0)}if(pn==="mcp"){let e=et.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=et["run-id"]||fn[0]||process.env.ENGINEEROS_MCP_RUN_ID||null,n=await Bn(e);await VN({config:n,runId:t,version:ta,input:process.stdin,output:process.stdout}),process.exit(0)}if(pn==="context-mcp"){let e=et["config-workspace"]||et.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=await Bn(e);t||on("This workspace is not paired with EngineerOS."),await $P({config:t,workspace:et.workspace||process.env.ENGINEEROS_CONTEXT_WORKSPACE||t.workspace,version:ta,input:process.stdin,output:process.stdout}),process.exit(0)}if(pn==="status"){let e=await Bn(et.workspace||process.cwd());console.log(e?`Paired as ${e.name} (${e.connector_id}) for ${e.workspace}`:"Not paired"),process.exit(e?0:1)}if(pn==="doctor"){let e=bn.resolve(et.workspace||process.cwd()),t=await Bn(e),n=await FN(e),r=await Ya(t||{workspace:e},e,$b(n));console.log(kb(r)),process.exit(r.status==="failed"?1:0)}if(pn==="update"){let e=fn[0]||"status";try{let t=Ng(process.argv[1],cg),n=await Dg(Gr(),t,{action:e,policy:fn[1]??null});console.log(zl(Lg(n,t,{supervised:!0})))}catch(t){on(`${t.message}
2863
2863
  Usage: engineeros-connector update [status|check|apply|rollback|policy manual|approve|auto-patch|auto-minor]`)}process.exit(0)}var xl=pn==="hunt-host";if(xl){try{et.workspace=jI(fn,et)}catch(e){on(e.message)}!fn[0]&&bn.resolve(et.workspace)!==bn.resolve(process.cwd())&&console.log(`This hunt host still keeps its files in ${et.workspace}. To keep everything in ${process.cwd()}, pair it again from here with a new pairing command.`)}if((pn==="start"||pn==="pair"||xl)&&process.env[nc]!=="1"&&xn(cg))try{process.exit(await XD({root:Gr(),bundled:{version:cg,entry:bn.resolve(process.argv[1])},argv:process.argv.slice(2),workspace:bn.resolve(et.workspace||process.cwd())}))}catch(e){on(`The connector process could not be started: ${e.message}`)}if(xl){try{await NI(et.workspace,fn[0]?et.agent:null)}catch(e){on(e.message)}pn=fn[0]?"pair":"start"}var U,Ka,tp;if(pn==="pair"){let e=fn[0];e||on("Usage: engineeros-connector pair CODE --url URL [--agent AGENT_ID | --agent-protocol forge] [--name NAME] [--workspace PATH] [--skip-git-repo-check]");let t=et.url;t||on("Pairing requires --url with the EngineerOS backend address."),et.agent&&et["agent-command"]&&on("Use either --agent or --agent-command, not both.");let n=et["agent-protocol"]||(et["agent-command"]?"acp":"codex");["codex","acp","forge"].includes(n)||on(`Unknown --agent-protocol '${n}'. Use codex, acp, or forge.`),n==="forge"&&(et.agent||et["agent-command"])&&on("Forge runs its own agents. Drop --agent and --agent-command when pairing with --agent-protocol forge.");let r={};try{et.agent&&(await Pu(et.agent),r=await b_(et.agent))}catch(o){on(o instanceof Error?o.message:String(o))}U={server_url:qg(t),workspace:bn.resolve(et.workspace||process.cwd()),onboard:et.onboard===!0,onboarding_pending:et.onboard===!0,hunt_host:xl,...et["knowledge-dir"]?{knowledge_dir:bn.resolve(et["knowledge-dir"])}:{},agent_protocol:n,agent_command:et["agent-command"]||null,agent_args:jae(et["agent-args"]),agent_name:et["agent-name"]||null,...r,skip_git_repo_check:xl||et["skip-git-repo-check"]===!0,name:et.name||`${eae.hostname()} - ${bn.basename(bn.resolve(et.workspace||process.cwd()))}`},tp=await Bn(U.workspace),Ka={type:"pair",pairing_code:e,name:U.name,capabilities:{},...hS(tp,U.server_url)}}else pn==="start"?(U=await Bn(et.workspace||process.cwd()),U||on("This connector is not paired. Create a pairing command in EngineerOS first."),xl&&!U.hunt_host&&on("This folder is not a paired hunt host. Generate a new hunt-host command in EngineerOS."),et["knowledge-dir"]&&(U={...U,knowledge_dir:bn.resolve(et["knowledge-dir"])},await Wr(U)),U.token||on("This connector's token is no longer in this machine's credential store. Create a new pairing command in EngineerOS and pair again."),Ka={type:"authenticate",connector_id:U.connector_id,token:U.token}):on("Use `engineeros-connector pair`, `start`, `status`, `doctor`, `agents`, `agent`, `tools`, `secret`, or `mcp`.");var f2=EI(U,{reportError:e=>console.error(e)}),Qi=0,ug=!1,Ja=null,_r=new Map,Z0=0,Q0=new Set,El=[],ir=new Map,mn,lk,rg,ws=null,og=!1,h2=0,ek=null,tk=[],sg,m2,ig=1e3,$l,ZD=0,nk=!1,ms=!1,ko,Al=!1,ag=!1,dg=!1,uk=0;function Yi(e){return uk+=1,e.finally(()=>{uk-=1})}var Sl,Va=0;function Cl({exitCode:e=0}={}){if(Va=Math.max(Va,e),Sl)return Sl;let t=setTimeout(()=>{console.error("Connector shutdown exceeded 15 seconds; inspect the retained agent logs before restarting."),process.exit(1)},15e3);return t.unref(),Sl=lae().finally(()=>clearTimeout(t)),Sl}async function lae(){if(dn=!0,np?.stop(),Qs?.stop(),fk?.stop(),d2?.stop(),clearInterval(ck),kn?.stop(),m2?.(),clearTimeout(sg),clearInterval(lk),clearInterval(rg),await Promise.all([...[..._r.values()].map(e=>$r(e.child))]),await Promise.all([...ir.values()].map(gk)),await kl?.cancelAll(),await Qd?.stop(),await Zd?.stop(),await Ol?.abortAll(),await Nu(),await zE().catch(e=>{Va=Math.max(Va,1),console.error(`${e.message}. Stop those processes before restarting the connector.`)}),mn?.close(),Va&&Va!==Fl){let e;await Promise.race([(async()=>{await Qs?.drain(),await Ya(U,U.workspace)})().catch(()=>{}),new Promise(t=>{e=setTimeout(t,1e4)})]).finally(()=>clearTimeout(e))}process.exit(Va)}for(let e of["SIGINT","SIGTERM","SIGHUP"])process.on(e,()=>{Cl()});var QD=!1;for(let e of["uncaughtException","unhandledRejection"])process.on(e,async t=>{QD||(QD=!0,console.error(`Connector stopping after an unhandled failure: ${t instanceof Error?t.stack||t.message:String(t)}`),await Cl({exitCode:1}))});kn=eA();process.on("exit",()=>{np?.stop(),kn.stop()});kn.banner(`EngineerOS connector ${ta}`,[U.workspace,U.server_url]);Qs=TN({actions:{refresh_tool_inventory:async()=>{wt.tool_inventory=await to(U.workspace),Ur()},restart_goal_runner:()=>Aa(U.workspace)},onNotify:()=>Ya(U,U.workspace),explain:async e=>{if(!await ys())return null;let{reading:t}=await bC(U,e);return t},onUpdate:e=>UN(U.workspace,e)});d2=zN({render:(e,t)=>kn.write(e,t),onRecord:e=>Qs.observe(e)});fk=BN({workspace:U.workspace,onRecord:e=>{Qs.observe(e),kn.line(e.channel,e.level,e.message)}});Qs.start();U.hunt_host||fk.start();kn.live&&!U.hunt_host&&(ck=setInterval(()=>{uae().catch(()=>{})},oae),ck.unref?.());var rk=new Set;async function uae(){if(U.hunt_host)return;KD??=Ov(U.workspace);let{jobs:e}=await KD(),t=new Set,n=e.filter(r=>r.status!=="queued"&&lg.includes(r.status)).length;for(let r of e){if(!lg.includes(r.status))continue;t.add(r.runId),rk.add(r.runId);let o=r.status==="queued"&&n>0?`queued behind running Goals (running: ${n})`:r.activity?.phase||r.status;kn.status(`goal:${r.runId}`,r.activity?.message||o,dae(r),{agent:r.status!=="queued",link:Ja&&`${Ja}/goals`,phase:o}),kn.step(`goal:${r.runId}`,r.activity?.message)}for(let r of rk)t.has(r)||(rk.delete(r),kn.clearStatus(`goal:${r}`))}function dae(e){let t=e.startedAt??Date.parse(e.updatedAt??"");return Number.isFinite(t)?t:Date.now()}async function ys({ignoreBugHunt:e=!1}={}){if(dn||_r.size>0||ir.size>0||Qi>0||(kl?.active??0)>0||(Qd?.active??0)>0||(Zd?.active??0)>0||!e&&(Ol?.active??0)>0)return!1;try{let{jobs:t}=await ji(U.workspace);return!dn&&!t.some(n=>lg.includes(n.status))}catch{return!1}}try{let e=U.hunt_host?{}:await li(U.workspace);e.committed&&(U.onboarding_pending=!0,U.connector_id&&await Wr(U),console.log(`Local project repository ready at ${e.revision.slice(0,8)}. Source and design artifacts are committed locally.`))}catch(e){await k2(e)}var g2=await xr(Gr()).then(e=>e.policy!=="manual",()=>!1),Wt;try{Wt=await Gu(U,U.workspace)}catch(e){await k2(e)}console.log(`Using ${Wt.name} through ${Wt.protocol} (${Wt.version}).`);console.log(`System time: ${so()} (${Intl.DateTimeFormat().resolvedOptions().timeZone}).`);var w2=async()=>$d({workspace:U.workspace}).names().catch(()=>[]),wt=fm(U,Wt,await to(U.workspace),{secretNames:await w2()}),Zs=eS({workspace:U.workspace,running:Ng(process.argv[1],cg),supervised:process.env[nc]==="1",isIdle:async()=>!dn&&_r.size===0&&El.length===0&&ir.size===0&&Qi===0&&uk===0&&!Al&&!dg&&(Qd?.active??0)===0&&(Ol?.active??0)===0&&(Zd?.active??0)===0&&!og,restart:()=>Cl({exitCode:Fl}),onChange:e=>{wt.runtime_update=e,mn?.readyState===WebSocket.OPEN&&Ur()}});try{await Zs.refresh()}catch(e){console.error(`Connector updates are unavailable: ${e.message}`)}U={...U,execution_profiles:Wt.executionProfiles??null};pn==="pair"&&tp?.connector_id||await Wr(U);wt.agent_session={...wt.agent_session,status:"checking",message:`Checking that ${Wt.name} can answer.`};wt.bug_hunt_browser=!1;Ka.capabilities=wt;console.log(Ls(U.worker_limit)===null?`Workers: automatic, ${Lc()} ${Wt.name} workers side by side for this machine's CPU and memory; change it with /workers.`:`Workers: ${Ls(U.worker_limit)} ${Wt.name} workers side by side, set with /workers.`);var Tl=La({getConfig:()=>U}),Il=async e=>{let t;try{t=await Fs(U,e)}catch(n){throw[401,403].includes(n.status)&&(ms=!0,console.error("EngineerOS withdrew this connector's authorization. Local work is stopping; saved reports are retained."),Cl()),n}return t?.execution_sync&&await pae(t.execution_sync),t},e2=hh(Il,{signature:jC}),Rl=iN({getConfig:()=>U,send:Il,onRetained:({status:e,file:t,reason:n})=>console.error(`Prompt result ${e==="pending"?"saved for automatic delivery":"rejected; original evidence retained"}: ${t}${n?` (${n})`:""}`)}),dk=aN({capacity:()=>Vu(U.worker_limit).worker_limit-_r.size}),ok,sk=!1,Vd,Xd=new Map,pk=new Set,ik;function gs(){return Zd??=GP({getConfig:()=>U,jobStore:Tl,canRun:()=>ys()}),Ol??=hD({getConfig:()=>({...U,tool_inventory:wt.tool_inventory}),jobStore:Tl,recordedSignIns:p2,isIdle:()=>ys({ignoreBugHunt:!0}),canRun:async e=>{if(!await ys({ignoreBugHunt:!0}))return!1;let t=e.assignment;return t.kind!=="production_check"&&sr?.state!=="ready"?!1:t.surface?.app_surface==="webdriver"||wt.bug_hunt_browser===!0},activity:{status:kn.status,step:mk,agents:kn.agents,finish:kn.finish}}),Qd??=rM({getConfig:()=>U,jobStore:Tl,canRun:()=>ys()}),{scheduledTests:Zd,bugHunts:Ol,baselines:Qd}}async function pae(e){let t=gs(),n=[];for(let r of e.jobs??[])await Tl.get(r.kind,r.id)&&n.push(r);await Promise.all([t.bugHunts.sync(n),t.scheduledTests.sync(n),t.baselines.sync(n)]);for(let r of e.assignments??[]){if(r.type==="bug_hunt.grant"&&!await t.bugHunts.stage(r))continue;let o=`${r.type}:${r.grant_id??r.session_id??r.run_id}`;pk.has(o)||Xd.set(o,r)}y2()}function y2(){ik||dn||(ik=(async()=>{let e=gs();for(;Xd.size&&!dn;){let[t,n]=Xd.entries().next().value;Xd.delete(t),pk.add(t);try{if(n.type==="bug_hunt.grant")await e.bugHunts.configure(n);else if(n.type===Tm)await e.scheduledTests.configure(n);else if(n.type===k0)await e.bugHunts.handle(n);else if(n.type===Am)await e.scheduledTests.handle(n);else if(n.type===Zb)await e.baselines.handle(n);else throw new Error(`Unsupported cached work ${n.type}. Update the connector before accepting it.`)}catch(r){console.error(`Caching connector work: ${r.message}`)}finally{pk.delete(t)}}})().finally(()=>{ik=null}))}async function _2(){if(!(!U.connector_id||!U.token||dn))return Vd||(Vd=(async()=>{let e=gs();await Promise.all([e.bugHunts.start(),e.scheduledTests.start(),e.baselines.start()]);let t=await Tl.list();for(let n of t)if(n.kind==="bug_hunt_grant"&&n.status==="provisioning"){let r=n.checkpoint?.pending_context??n.assignment;Xd.set(`bug_hunt.grant:${n.id}`,r)}y2(),t.some(n=>["bug_hunt","bug_hunt_grant"].includes(n.kind)&&["authorized","queued","running"].includes(n.status)&&Date.parse(n.execution_lease.expires_at)>Date.now())&&(x2(),fg()),$ae()})().catch(e=>{throw Vd=null,e}),Vd)}async function fae(){let e=await ji(U.workspace).catch(()=>({service:null,jobs:[]}));return{version:ta,now:Date.now(),workspace:U.workspace,config_path:zn(U.workspace),config:U,agent:Wt,automatic_worker_limit:Lc(),worker_limit:Ls(U.worker_limit),connection:{state:hae(),server_url:U.server_url,last_error:ko||null},work:{assessments:[..._r.values()].map(t=>({stage:t.stage,phase:t.phase,message:t.lastMessage,started_at:t.startedAt,pid:t.child?.pid??null,agent:Wt.name})),prompts:[...ir.values()].map(t=>({id:String(t.runId).slice(0,8),purpose:t.purpose,phase:t.phase,message:t.lastMessage,started_at:t.startedAt,pid:t.child?.pid??null,agent:Wt.name})),integrations:Qi},runner:e,runtime_update:Zs.report(),health:Qs?.health()??null,activity:ep.snapshot()}}function hae(){return dn||ms?"stopped":mn?.readyState===WebSocket.OPEN?"connected":"connecting"}var mae={async cancelPrompt(e){let t=[...ir.values()].find(n=>n.runId.startsWith(e));return t?(t.stoppedHere=!0,t.cancellation.abort(),await t.controller?.completed.catch(()=>{}),`Stopping prompt ${e} (${t.purpose}); EngineerOS will be told it was cancelled here.`):`Prompt ${e} finished before it could be stopped.`},setWorkers:e=>b2(e),setVerbose(e){return e===ug?`Detailed agent activity is already ${e?"on":"off"}.`:(hk(e),"This lasts until EngineerOS sends its own setting again: when the connector reconnects, or when it is changed there.")},async runtimeUpdate(e){return e.action==="apply"?(Zs.command(e).catch(t=>console.error(`Connector update: ${t.message}`)),"Preparing the latest connector release beside this one; it switches over once this connector is idle."):(await Zs.command(e),zl(await Zs.refresh()))}};np=jN({ui:kn,snapshot:fae,actions:mae});np&&console.log(IN());await v2();var t2=new Set;async function v2(){if(dn||ms)return;console.log(`Connecting ${U.name} to ${U.server_url}`),ms=!1,ko=void 0;let e=new WebSocket(U.server_url);mn=e;let t=J$(e,U.server_url,{onTimeout:r=>{mn===e&&(ko=r,console.error(r),ak())}});m2=t,e.addEventListener("open",()=>{if(mn!==e){e.close();return}try{if(q$(mn,e,Ka))return;throw new Error("The WebSocket was not open when authentication started.")}catch(r){ko=_n(r),console.error(`Could not authenticate the WebSocket connection: ${ko}`);try{e.close()}catch{}ak()}}),e.addEventListener("message",r=>{if(mn!==e)return;let o;try{o=JSON.parse(String(r.data))}catch{console.error("Ignored a malformed EngineerOS message frame (invalid JSON).");return}n(o).catch(s=>{console.error(`EngineerOS ${String(o?.type||"unknown").slice(0,80)} message failed: ${_n(s)}`)})});let n=async r=>{if(r.type==="authenticated"&&r.connector?.capabilities?.http_updates!==!0){dn=!0,ms=!0,t(),console.error("Update the EngineerOS backend to support connector HTTP updates before reconnecting."),e.close();return}if(r.type==="paired"){t();let s=tp?.connector_id===r.connector.id;if(U=mS(U,tp,r.connector.id,r.token),await Wr(U),r.connector?.capabilities?.http_updates!==!0){dn=!0,ms=!0,console.error("Pairing saved. Update the EngineerOS backend for HTTP updates, then start this connector again."),e.close();return}Ka={type:"authenticate",connector_id:U.connector_id,token:U.token,capabilities:wt},console.log(s?`Reconnected existing workspace connector ${U.connector_id}; assessment history is preserved.`:`Paired. Connector ${U.connector_id} is online.`),s2(r);return}if(r.type==="authenticated"){t();let s=U.hunt_host?"Bug Hunter sessions":"EngineerOS runs";console.log($l?`Reconnected after ${Nt(Date.now()-$l)} offline; waiting for ${s}.`:`Connected and waiting for ${s}.`),$l=void 0,s2(r);return}if(r.type==="provider.login"||r.type==="provider.logout"){dg||wae(r);return}if(r.type==="workspace.refresh"){Xa();return}if(r.type==="workers.update"){try{console.log(`EngineerOS changed the workers. ${await b2(r.worker_limit??"auto")}`)}catch(s){console.error(`Workers were not changed: ${s.message}`)}return}if(r.type==="logging.update"){hk(r.activity_log_enabled===!0);return}if(r.type==="tools.update"){let s=r.provider_id==="playwright"&&["setup","upgrade","rollback"].includes(r.action);s&&(Ys=!1,wt.bug_hunt_browser=!1,Ur());try{wt.tool_inventory=await Zy(U.workspace,r,void 0,{confirmLocal:i=>np?.confirm(i)??!1,log:Kd}),s&&(Ys=!0),wt.bug_hunt_browser=Pa(wt.tool_inventory)&&Ys,e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,inventory:wt.tool_inventory})),Ur(),console.log(`Tool registry updated: ${r.action} ${r.provider_id}.`)}catch(i){let a=i instanceof Error?i.message.slice(0,300):"The local connector rejected the tool registry update.";e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,error:a})),console.error(`Tool registry update rejected: ${a}`)}return}if(r.type==="tools.auth"){try{let s=await n_(U.workspace,r,{onStatus:async()=>{wt.tool_inventory=await to(U.workspace),Ur()}});wt.tool_inventory=s.inventory,s.completion&&s.completion.catch(i=>console.error(`Tool authentication status: ${i instanceof Error?i.message.slice(0,300):"Local status update failed."}`)),e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,inventory:wt.tool_inventory})),Ur(),console.log(`Tool authentication updated: ${r.action} ${r.provider_id}.`)}catch(s){let i=s instanceof Error?s.message.slice(0,300):"The local connector rejected the tool authentication request.";e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,error:i})),console.error(`Tool authentication rejected: ${i}`)}return}if(r.type==="test_environment.health_check"){yi(r).then(s=>{e.send(JSON.stringify({type:"test_environment.health_result",command_id:r.command_id,result:s})),console.log(`Test environment health: ${s.status}${s.message?` (${s.message})`:""}.`)}).catch(s=>console.error(`Test environment health was not reported: ${s.message}`));return}if(r.type===BD){Yi(cae(r).then(s=>(s.error&&console.error(`${r.provider} ${r.operation} failed: ${s.error}`),GD(U,s))).catch(s=>console.error(`An integration answer was not delivered: ${s.message}`)));return}if(r.type==="workspace.assessment"){let s=`${r.assessment_id}:${r.stage}`;ov(El,_r.get(s),r)==="deferred"&&console.log(`Assessment stage ${r.stage} is already running here; EngineerOS will be answered when it finishes.`),ea();return}if(r.type==="prompt.execute"){let s=ir.get(r.prompt_id);s?A2(r)>s.executionRevision&&await Rae(s,r):!await Rl.replay(r)&&!ir.has(r.prompt_id)&&$2(r);return}if(r.type==="prompt.cancel"){let s=ir.get(r.prompt_id);s&&await gk(s);return}if(r.type==="agent.warm"){kae(r);return}if(r.type==="run.available"){if(U.hunt_host){console.error("A hunt host cannot run Goals. Use Connect your code to pair a repository connector.");return}try{let s=await f2.dispatch(r);s.blocked?console.error(s.message):console.log(`Goal ${r.run_id} queued for the independent runner. Logs: ${bn.join(U.workspace,".engineeros","runs",r.run_id,"activity.log")}`)}catch(s){console.error(`Goal dispatch failed: ${_n(s)}`)}return}if(r.type==="delivery.task.start"||r.type==="delivery.task.cancel"){if(U.hunt_host)throw new Error("Pair a repository connector before dispatching delivery tasks.");await oI(U.workspace,U.connector_id,r),await Aa(U.workspace);return}if(r.type==="goal.cleanup"){try{await kI(U.workspace),await Aa(U.workspace)}catch(s){console.error(`Goal cleanup is pending: ${s.message}`)}return}if(r.type==="run.accepted"){Iae(r);return}if(r.type==="run.cancelled"){await Rv(U.workspace,r.run_id);return}if(r.type===ZA){kl??=Oy({getConfig:()=>U,onTestsCommitted:()=>Xa()}),Yi(kl.handle(r));return}if(r.type===QA){kl??=Oy({getConfig:()=>U,onTestsCommitted:()=>Xa()}),await kl.cancel(r);return}if(r.type===k0){Yi(gs().bugHunts.handle(r)).catch(s=>console.error(`Bug Hunter assignment: ${s.message}`));return}if(r.type==="bug_hunt.grant"){Yi(gs().bugHunts.configure(r)).catch(s=>console.error(`Bug Hunter settings: ${s.message}`));return}if(r.type===iD){Ol?.stop(r);return}if(r.type===Am){Yi(gs().scheduledTests.handle(r)).catch(s=>console.error(`Scheduled test assignment: ${s.message}`));return}if(r.type===Tm){Yi(gs().scheduledTests.configure(r)).catch(s=>console.error(`Scheduled test settings: ${s.message}`));return}if(r.type===Zb){Yi(gs().baselines.handle(r)).catch(s=>console.error(`Baseline assignment: ${s.message}`));return}if(r.type===KP){await gs().baselines.cancel(r);return}if(r.type===sM){YD??=iM({getConfig:()=>U,isIdle:()=>ys(),agentTurn:WO}),Yi(YD.handle(r));return}if(r.type==="connector.update"){gae(e,r);return}if(r.type==="connector.disconnect"){console.log(r.message),await Cl();return}if(r.type==="connector.revoked"){dn=!0,console.error("This connector was revoked in EngineerOS."),e.close();return}if(r.type==="run.error"){console.error(`EngineerOS: ${r.message}`);return}if(r.type==="connection.error"){ms=!0,console.error(`EngineerOS: ${r.message}`);return}let o=String(r.type??"(missing)").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,120);t2.has(o)||(t2.add(o),console.warn(`Unknown EngineerOS message type ${o}; connector ${ta}. Update the connector and backend to compatible versions.`))};e.addEventListener("close",r=>{if(t(),mn!==e||Sl)return;let o=B$(r);if(!o.retry||ms||dn){console.error(o.message),o.retry&&ms&&console.error("Connection rejected. Create a new pairing command in EngineerOS if this connector was revoked."),Cl();return}ko=ko?`${o.message} ${ko}`:o.message,ak()}),e.addEventListener("error",r=>{mn===e&&(ko=F$(r),console.error(`WebSocket connection to ${U.server_url} failed: ${ko}`))})}async function gae(e,t){let n=r=>e.send(JSON.stringify({type:"connector.updated",command_id:t.command_id,...r}));try{let r={action:t.action,policy:t.policy??null},o=Zs.command(r);r.action==="apply"?(o.catch(s=>console.error(`Connector update: ${s.message}`)),await Promise.race([o,new Promise(s=>setTimeout(s,3e3).unref())])):await o,n({report:await Zs.refresh()}),console.log(`EngineerOS asked for connector update ${r.action}.`)}catch(r){let o=(r instanceof Error?r.message:String(r)).slice(0,300)||"The connector rejected the update request.";n({error:o}),console.error(`Connector update ${t.action} rejected: ${o}`)}}async function wae(e){let t=e.request_id,n=e.type==="provider.logout"?"logout":"login";dg=!0,console.log(`Starting interactive ${Wt.name} provider ${n}.`);try{await(n==="logout"?V$:W$)(Wt,U.workspace),Wt=await Gu(U,U.workspace),sr=null,wt=fm(U,Wt,wt.tool_inventory,{secretNames:await w2()}),Ka.capabilities=wt,mn.readyState===WebSocket.OPEN&&(mn.send(JSON.stringify({type:`provider.${n}.completed`,request_id:t,session:wt.agent_session})),mn.close(1e3,`Provider ${n} completed`)),console.log(`${Wt.name} provider ${n} completed.`)}catch(r){let o=_n(r).slice(0,500);mn.readyState===WebSocket.OPEN&&mn.send(JSON.stringify({type:`provider.${n}.failed`,request_id:t,message:o})),console.error(`Provider ${n} failed: ${o}`)}finally{dg=!1}}function ak(){if(dn||ms||sg)return;let e=z$(ig),t=ko?` Last error: ${ko}`:"",n=$l?` Offline for ${Nt(Date.now()-$l)}.`:"";$l??=Date.now(),console.error(`Connection unavailable.${t}${n} Retrying in ${Math.round(e/1e3)}s.`),sg=setTimeout(()=>{sg=void 0,v2()},e),ig=Math.min(3e4,ig*2)}async function Xa(){if(!U.hunt_host&&(ag=!0,!(Al||dn||mn.readyState!==WebSocket.OPEN))){ag=!1,Al=!0,console.log("Inspecting the workspace without executing its code.");try{let e=await $C(U.workspace),t=await EC(U.workspace,U.last_head_reported??U.last_snapshot_head,e.head_revision).catch(()=>null);t&&(e.changed_since=t);let n=await fetch(Qn(U.server_url,U.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${U.token}`},body:JSON.stringify(e)});if(!n.ok)throw new Error(await vc(n,"the workspace"));let r=await n.json(),o=r.source_revision;U={...U,onboarding_pending:!1,last_snapshot_head:e.head_revision??U.last_snapshot_head,last_head_reported:e.head_revision??U.last_head_reported,last_head_branch:e.head_revision?e.branch??null:U.last_head_branch},await Wr(U),console.log(`Inventoried ${e.total_file_count.toLocaleString()} safe file(s).`),console.log(`Uploaded ${e.evidence_file_count.toLocaleString()} prioritized source file(s).`),console.log("Ignored, sensitive and generated files excluded; total not counted."),e.omitted_evidence_file_count>0&&console.log(`${e.omitted_evidence_file_count.toLocaleString()} additional file(s) remain available to the connected Agent locally.`),console.log(`Workspace inventory registered as ${r.workspace_kind}. Start the baseline assessment in EngineerOS to continue.`);let{encoded:s,stats:i}=await jb({workspace:U.workspace,connectorId:U.connector_id,snapshot:e,refresh:uc,buildMap:(a,c)=>_m(U.workspace,a,{head:c.head_revision,branch:c.branch}),log:a=>console.error(a)});if(s&&o){let a=await fetch(yS(U.server_url,U.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${U.token}`},body:JSON.stringify({source_revision:o,quality_map_base64:s.base64})});a.ok?await vm(U.workspace,U.connector_id,s.map).catch(()=>{}):console.error(await vc(a,"the workspace quality map"))}i&&console.log(`Built the local context index: ${i.total_files.toLocaleString()} file(s) ready for assignment context.`)}catch(e){console.error(`Workspace assessment failed: ${_n(e)}`)}finally{Al=!1,ag&&!dn&&mn.readyState===WebSocket.OPEN&&Xa()}}}var yae=8e6,n2,r2="";async function _ae({current:e,previous:t}){if(Al||mn?.readyState!==WebSocket.OPEN)throw new Error("A snapshot is running or the connection is down.");let n=bn.resolve(U.workspace),r=async()=>{U={...U,last_head_reported:e.head,last_head_branch:e.branch??null},await Wr(U)},o=await Ib(U.workspace,U.connector_id),s=async()=>{if(await Xa(),U.last_head_reported!==e.head)throw new Error("The snapshot did not report this commit.")};if(!o)return s();let i,a=async()=>(i??=uc(U.workspace,U.connector_id),(await i).index),c=null,l=await gP({previous:{head:t.head,branch:t.branch??null},current:e,compare:(f,g)=>dv(U.workspace,f,g),inventoryDelta:async f=>{let g=await a();return ix(n,Object.entries(g.files).map(([y,k])=>({path:y,size:k.size})),f)},mapDelta:async()=>{let f=await a();return c=await _m(U.workspace,f,{head:e.head,branch:e.branch}),Cb(o,c)},contentHead:(await Vp(n).catch(()=>null))?.content_head_revision??null});if(l.status==="snapshot")return s();let u=JSON.stringify(l.report);if(Buffer.byteLength(u)>yae)return s();let d=await fetch(_S(U.server_url,U.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${U.token}`},body:u});if(!d.ok)throw new Error(await vc(d,"the new commit"));let p=await d.json();if(p.needs_snapshot)return s();if(p.accepted!==!0)throw new Error("EngineerOS did not acknowledge the new commit.");await r(),c&&await vm(U.workspace,U.connector_id,c).catch(()=>{}),console.log(`Reported ${l.report.reason==="branch_switch"?"the switch to ":"commit "}${e.head.slice(0,7)}${p.flagged_cases?`: ${p.flagged_cases} test case(s) to check again`:""}.`)}function vae(){U.hunt_host||U.onboarding_pending||Al||mn?.readyState!==WebSocket.OPEN||(n2??=mP({readHead:()=>hP(U.workspace),getLastReported:()=>({head:U.last_head_reported??U.last_snapshot_head,branch:U.last_head_branch}),onChange:_ae,onError:e=>{e.message!==r2&&(r2=e.message,console.error(`The new commit could not be reported yet: ${_n(e)}`))}}),n2.poll().catch(()=>{}))}var bae=6e4,o2=0;async function kae(e){if(U.hunt_host)return;let t=typeof e.session_key=="string"?e.session_key.trim():"",n=t?U.sessions?.[t]:void 0,r=[];Date.now()-o2>bae&&(o2=Date.now(),r.push(uc(U.workspace,U.connector_id).catch(o=>console.error(`Context index refresh ahead of a conversation failed: ${o.message}`)))),U.agent_protocol==="acp"&&r.push(BR(U.workspace,U,{sessionKey:n?t:null,previousSessionId:n,sandbox:e.sandbox_mode==="workspace-write"?"workspace-write":"read-only",profile:e.execution_profile&&typeof e.execution_profile=="object"?e.execution_profile:{}}).catch(o=>console.error(`${Wt?.name||"The agent"} could not be started ahead of the conversation: ${o.message}`))),await Promise.all(r)}function Ur(){dn||!U.connector_id||!U.token||(sk=!0,!ok&&(ok=(async()=>{do sk=!1,await Sae();while(sk&&!dn)})().catch(e=>console.error(`Connector synchronization: ${_n(e,{network:!0})}`)).finally(()=>{ok=null})))}async function Sae(){let e=dC(_r),t=await Tl.snapshot();e2.update({type:"assessment.workers",assessment_workers:e,tool_inventory:wt.tool_inventory,runtime_update:wt.runtime_update,agent_session:wt.agent_session,bug_hunt_browser:wt.bug_hunt_browser,connector_jobs:t.jobs,...Vu(U.worker_limit)}),await e2.flush()}async function b2(e){let t=Ls(e);return t===Ls(U.worker_limit)?t===null?"Workers are already automatic.":`Workers are already set to ${t}.`:(U={...U,worker_limit:t},await Wr(U),ea(),Ur(),t===null?`Workers are automatic again: up to ${Lc()} side by side for this machine's CPU and memory, for ${Td} (an assessment may ask for fewer). A Goal that uses your working folder still runs alone.`:`Up to ${t} worker${t===1?"":"s"} now run side by side: ${Td}. A Goal that uses your working folder still runs alone. Running work finishes; waiting work starts as workers free up.`)}function hk(e){if(e!==ug){if(ug=e,!e)for(let t of _r.values())t.lastDetail=null;console.log(e?"Detailed agent activity is on: every agent action is printed here and shown in EngineerOS.":"Detailed agent activity is off: prompts and stages show only their latest steps."),Ur()}}function mk(e,t,n=null){kn.step(e,t,n)&&ug&&console.log(`[${e}] ${n?`${n}: `:""}${t}`)}function xae(){clearInterval(rg);let e=!1,t=()=>{e||_r.size>0||ir.size>0||(e=!0,Ya(U,U.workspace).finally(()=>{e=!1}))};t(),rg=setInterval(t,rae),rg.unref?.()}async function Ya(e,t,n=Qs?.healthChecks()??[]){let r=await hN({config:e,workspace:t,version:ta,insights:[...n,...Yd?[Yd]:[]],agentSession:sr,probes:{inspectAgent:(o,s)=>dn?Wt:Gu(o,s),inspectTools:o=>dn?wt.tool_inventory:to(o),runnerStatus:ji,connectorJobs:()=>La({getConfig:()=>e}).list()}});try{u2=(await mN(e,r,Fs))?.autonomy_scan===!0}catch(o){console.error(`Connector self-check reporting failed: ${_n(o,{network:!0})}`)}return r}async function k2(e){if(dn)return Sl;let t=e instanceof Error?e.message:String(e),n=await Ya(U,U.workspace).catch(()=>null);n&&console.error(kb(n)),on(t)}function s2(e){Rl.flush().catch(t=>console.error(`Saved prompt result delivery: ${t.message}`)),hk(e.connector?.activity_log_enabled===!0),Ja=e.project_url??null,ig=1e3,x2(),fg(),Zs.confirm().catch(t=>console.error(`Connector update state: ${t.message}`)),_2().catch(t=>console.error(`Saved connector work: ${t.message}`)),(U.onboarding_pending||ag)&&Xa()}var Jd=null,Ys=!1,S2=0,Eae=Date.now();async function x2(){return Jd||(Jd=(async()=>{g2&&await ER(U.workspace,{log:t=>console.log(`[tools] ${t}`)}).catch(t=>console.error(`[tools] Tool updates were skipped: ${t.message}`));let e=Date.now();try{Kd("Preparing Bug Hunter's Playwright runtime; missing browser dependencies are installed automatically.");let{diagnostics:t}=await ju(U.workspace,{log:Kd});wt.bug_hunt_browser_diagnostics=t,Ys=!0,Yd=null,wt.tool_inventory=await to(U.workspace),wt.bug_hunt_browser=Pa(wt.tool_inventory)&&Ys,Kd(`Bug Hunter's browser is ready (${Nt(Date.now()-e)}).`)}catch(t){console.error(`[browser] Bug Hunter's browser setup failed after ${Nt(Date.now()-e)}: ${t.message}`),wt.bug_hunt_browser=!1,Yd={id:"hunt_browser",title:"Bug Hunter browser",status:"failed",detail:t.message,remedy:"Resolve the reported browser setup error, then restart this connector to retry automatic setup."},Ya(U,U.workspace).catch(()=>null)}Ur()})(),Jd)}function Kd(e){console.log(`[browser] ${e}`)}async function fg(){if(!["checking","ready"].includes(sr?.state)){S2=Date.now(),wt.agent_session={...wt.agent_session,status:"checking",message:`Checking that ${Wt.name} can answer.`},Ur(),sr={state:"checking",detail:`Asking ${Wt.name} one question to confirm its session.`},console.log(`Checking that ${Wt.name} can answer before accepting work.`);try{await gC(U,Wt.name),sr={state:"ready",detail:`${Wt.name} answered; its session is usable.`},wt.agent_session={...wt.agent_session,status:"authenticated",message:sr.detail},console.log(sr.detail)}catch(e){sr={state:"failed",detail:e instanceof Error?e.message:String(e),remedy:U.hunt_host?MI(U.agent_id||U.agent_protocol):Ic(U.agent_id||U.agent_protocol)},wt.agent_session={...wt.agent_session,status:"logged_out",message:sr.remedy},console.error(`${sr.detail}
2864
2864
  ${sr.remedy}`)}Ur(),sr.state==="ready"&&(ea(),gs().bugHunts.wake().catch(e=>console.error(`Bug Hunter local scheduler: ${e.message}`))),await Ya(U,U.workspace).catch(()=>null)}}function $ae(){clearInterval(lk);let e=!1,t=0,n=0,r=!1,o=()=>{mn?.readyState===WebSocket.OPEN&&Rl.flush().catch(s=>console.error(`Saved prompt result delivery: ${s.message}`)),Zs.tick(),Aae(),vae(),Jd&&(sr===null||U.hunt_host&&sr?.state==="failed"&&Date.now()-S2>=PI(Eae))&&ys().then(s=>{if(s)return fg()}),!U.hunt_host&&!r&&kd(Y0.id)&&(r=!0,f2.flush().then(()=>ng(Y0)).catch(s=>tg(Y0,s)).finally(()=>{r=!1})),Ur(),!U.hunt_host&&!ws&&Date.now()-t>=sae&&kd(J0.id)&&(t=Date.now(),E2().then(()=>ng(J0)).catch(s=>tg(J0,s))),!U.hunt_host&&u2&&!og&&kd(X0.id)&&Date.now()-h2>=NT&&(og=!0,Tae().then(()=>ng(X0)).catch(s=>tg(X0,s)).finally(()=>{og=!1})),!e&&Date.now()-n>=iae&&kd(K0.id)&&(e=!0,n=Date.now(),to(U.workspace).then(async s=>{if(wt.tool_inventory=s,!Ys&&Pa(s))try{let{diagnostics:i}=await ju(U.workspace,{log:Kd});wt.bug_hunt_browser_diagnostics=i,Ys=!0}catch{Ys=!1}wt.bug_hunt_browser=Pa(s)&&Ys,wt.bug_hunt_browser&&(Yd=null),Ur(),ng(K0)}).catch(s=>tg(K0,s)).finally(()=>{e=!1}))};o(),lk=setInterval(o,1e4),xae()}async function Aae(){if(!(!g2||U.agent_protocol!=="acp"||!U.agent_id||nk||sr?.state==="checking"||Date.now()-ZD<aae)){nk=!0;try{if(!await ys())return;ZD=Date.now();let e,t=await YR(U,{verify:async r=>{e=await Gu(r,U.workspace)},log:r=>console.log(`[agent] ${r}`)});if(t===U||dn)return;U={...t,execution_profiles:e.executionProfiles??null},await Wr(U),Wt=e,sr=null;let n=fm(U,Wt,wt.tool_inventory);if(Object.assign(wt,{agent_name:n.agent_name,agent_version:n.agent_version,execution_profiles:n.execution_profiles}),Ka.capabilities=wt,!await ys())return;await Nu(),fg(),mn?.readyState===WebSocket.OPEN&&mn.close(1e3,"Coding agent updated")}catch(e){console.error(`[agent] The agent update check failed: ${e.message}`)}finally{nk=!1}}}function tg(e,t){let n=cN(e.id,e.title,t,{remedy:e.remedy});console.error(`${e.title} failed ${n.failures} time(s); retrying in ${Math.round(n.retryInMs/1e3)}s: ${n.message}`)}function ng(e){lN(e.id)&&console.log(`${e.title} recovered.`)}async function Tae(){if(U.hunt_host||!await ys())return;h2=Date.now();let{jobs:e}=await ji(U.workspace).catch(()=>({jobs:[]})),t=await PT(U.workspace,{jobs:e});if(!MT(t))return;let n=`${t.fingerprint}:${tk.join(",")}`,r=ek?.key===n,o=r?ek.candidates:await kC(U,t,tk);ek={key:n,candidates:o};let s=await Il(UT(t,o,{version:ta}));Array.isArray(s?.refused)&&(tk=s.refused.map(String));let i=r?"unchanged since the last scan":"scanned";console.log(o.length?`Workspace ${i}; reported ${o.length} delivery candidate(s) to EngineerOS: ${o.map(a=>a.capability_name).join(", ")}.`:`Workspace ${i}; nothing worth starting.`)}var Zi=null,i2=null;async function E2(){if(!U.hunt_host){if(ws)return ws;ws=(async()=>{let e=await $T(U,{knownRevision:Zi?.revision??null});if(e.unchanged||(Zi=e),i2===Zi.revision)return Zi;let{jobs:t}=await ji(U.workspace);return!t.some(r=>lg.includes(r.status))&&Qi===0&&_r.size===0&&(await Of(U.workspace,Zi),i2=Zi.revision),Zi})();try{return await ws}finally{ws=null,ea()}}}function a2(e,t){if(!t)return;let n={type:"prompt.event",prompt_id:e,kind:t.kind};t.message&&(n.message=String(t.message).slice(0,500)),t.delta&&(n.delta=String(t.delta).slice(0,5e4)),t.status&&(n.status=String(t.status).slice(0,100)),ir.get(e)?.events.push(n)}var c2=null;function ea(){dk.drain();let e=mn.readyState===WebSocket.OPEN,t=_r.values().next().value,n=Ls(U.worker_limit)??Math.min(Lc(),sv(t?.workerLimit??El[0]?.worker_limit)),r=e&&!ws&&Qi===0?nC(El,_r.size,Math.max(0,n-dk.running)):[];for(let s of r){let i=`${s.assessment_id}:${s.stage}`,a={kind:"assessment",key:i,runId:s.assessment_id,stage:s.stage,child:null,controller:null,resumeAssignment:null,phase:"starting",progressPercent:5,lastMessage:`Starting ${s.stage} assessment stage`,startedAt:Date.now(),workerLimit:sv(s.worker_limit),lastActivityAt:Date.now(),eventCount:0,lastDetail:null};_r.set(i,a),Cae(s,a)}r.length>0&&Ur();let o=rC({queued:El,running:_r.size,workerLimit:n,connected:e,designSync:!!ws,integrations:Qi});o&&o!==c2&&console.log(o),c2=o}function pg(e){let t=iv(e);return t?`${Wt.name} on ${t}`:Wt.name}async function $2(e){let t=e.prompt_id,n=`prompt:${String(t).slice(0,8)}`,r=e.purpose||"project",o=Date.now(),s=`${r} \xB7 ${pg(e)}`,i=mC(e,Wt.name),a={runId:t,purpose:r,startedAt:o,child:null,controller:null,cancelled:!1,stoppedHere:!1,cancellation:new AbortController,events:LC(Il),executionRevision:A2(e),sessionKey:ph(e),sessionId:null,phase:"preparing",lastMessage:s,replacement:null};ir.set(t,a);let c=!1,l,u=DC(Il,{type:"prompt.heartbeat",prompt_id:t,execution_revision:a.executionRevision},{onError:w=>{c&&Ei(w)||console.error(`[${n}] Prompt heartbeat: ${w.message}`)}}),d,p=w=>{let h=w?JSON.stringify(w):null;c||!h||h===d||ir.get(t)!==a||(d=h,a2(t,w))},f=Number(e.answer_within_seconds),g=f>0?o+f*1e3:void 0;console.log([`[${n}] ${i} for ${r}.`,`${Wt.name} can reason for several minutes without reporting a step.`,...g?[ay(g,o)]:[]].join(" ")),a2(t,{kind:"status",message:i}),kn.status(n,s,o,{link:Ja,answerBy:g,phase:a.phase});let y=w=>{if(c)return;let h=QO(w),m=ZO(w),b=va(w);ir.get(t)===a&&(m&&(a.phase=m),(b??h?.message)&&(a.lastMessage=b??h?.message),kn.status(n,a.lastMessage,o,{link:Ja,answerBy:g,phase:a.phase}),mk(n,b??h?.message));let x=w.type==="forge.output"?null:b;p(h??(x?{kind:"status",message:x}:null))},k="failed",v=[r],_;try{_=await dk.acquire({signal:a.cancellation.signal,onWaiting:()=>y({type:"connector.step",message:"Waiting for an available connector worker"})}),fh(e)||(y({type:"connector.step",message:"Syncing the design context from EngineerOS"}),e={...e,design_context:await CT(E2,{pinned:!!e.local_design_context,last:Zi,onFallback:(x,S)=>y({type:"connector.step",message:`Design context not refreshed (${x.message}); continuing with ${S?"the copy synced earlier":"none"}`})})});let w=await HO(e,U,{onProcess:x=>{ir.get(t)===a&&(a.child=x)},onController:x=>{ir.get(t)===a&&(a.controller=x)},onSession:x=>{a.sessionId=x},onEvent:y},{signal:a.cancellation.signal});if(_(),ea(),a.stoppedHere)throw new Error(l2);if(a.cancelled)return;let h={type:"prompt.completed",prompt_id:t,execution_revision:a.executionRevision,content:w.content,model:w.model,session_id:w.sessionId,usage:w.usage};await Rl.save(h),c=!0,a.events.stop(),l=u.stop(),a.phase="delivering",a.lastMessage="Delivering completed response",kn.status(n,a.lastMessage,o,{link:Ja,phase:a.phase,agent:!1});let m=w.singleTurn?gS(U.sessions,w.sessionKey):zg(U.sessions,w.sessionKey,w.sessionId);if(JSON.stringify(m)!==JSON.stringify(U.sessions||{})&&(U={...U,sessions:m},await Wr(U)),a.cancelled)return;let b=await Rl.deliver(h);ep.record("prompt","completed",{durationMs:Date.now()-o,usage:w.usage}),k=b.status==="delivered"?"finished":"undelivered",v=[lf(w.usage),r]}catch(w){let h=a.stoppedHere?l2:_n(w);if(ep.record("prompt","failed",{durationMs:Date.now()-o}),a.stoppedHere&&(k="cancelled"),!a.cancelled&&!c){try{await Rl.deliver({type:"prompt.failed",prompt_id:t,execution_revision:a.executionRevision,message:h})}catch(m){console.error(`[${n}] Prompt failure delivery: ${m.message}`)}console.error(h)}else c&&(k="undelivered",console.error(`[${n}] ${h} The original completed result remains saved for delivery.`))}finally{_?.(),ea(),await(l??u.stop()),a.events.stop();let w=a.replacement;w?(k="replaced",v=[`continuing on ${pg(w)}`,r]):a.cancelled&&(k="cancelled"),kn.finish(n,k,v),ir.get(t)===a&&ir.delete(t),w&&Oae(a,w)}}var l2="Cancelled from the connector terminal by the person running it.";async function gk(e){e.cancelled=!0,e.cancellation.abort(),await e.controller?.completed.catch(()=>{})}function A2(e){return Number(e.execution_revision)||1}async function Rae(e,t){let n=e.replacement!==null;e.replacement=t,!n&&(console.log(`[prompt:${String(e.runId).slice(0,8)}] The model was changed in EngineerOS; stopping this turn to continue it on ${pg(t)}.`),await gk(e))}function Oae(e,t){e.sessionId&&(U={...U,sessions:zg(U.sessions,e.sessionKey,e.sessionId)},Wr(U).catch(n=>console.error(`Could not save the agent session: ${n.message}`))),$2(t)}async function Cae(e,t){let n=e.assessment_id,r=e.stage;if(console.log(`Running assessment stage ${r}${e.stage_label&&e.stage_label!==r?` "${e.stage_label}"`:""} (${n}) with ${pg(e)}.`),!Q0.has(n)){Q0.add(n);try{let m=await XO(U.workspace);if(!m.exists)console.log("No accepted assessment exists yet; this run establishes the baseline.");else{let b=m.accepted_head_revision?m.current_head_revision?m.current_head_revision!==m.accepted_head_revision?`The workspace is now at commit \`${m.current_head_revision}\`; the accepted assessment is from \`${m.accepted_head_revision}\`.`:"The accepted assessment is already at the current commit.":`The accepted assessment is from \`${m.accepted_head_revision}\`; the current commit could not be read.`:"Its accepted commit is unavailable; this run will refresh that provenance.";console.log(`Last accepted assessment covers ${m.stages.length||"no"} section(s). ${b}`)}}catch(m){console.error(`Assessment freshness check failed: ${m.message}`)}}let o=t.startedAt,s=`assessment:${r}`,i=!1,a=!1,c=5,l=!1,u=!1,d=null,p=null,f=null,g=new Set,y=()=>!dn&&_r.get(t.key)===t,k=async m=>{try{return await PC(Il,m)||console.warn(`[${s}] ${NC}`),!0}catch(b){return console.error(`Assessment failure delivery: ${b.message}`),!1}},v=(m,{milestone:b=!0}={})=>{if(!y()||b&&f===m)return;b&&(f=m,g.has(m)||(g.add(m),c=Math.min(90,c+10)),console.log(`[assessment:${r}] ${m}.`));let x=String(m).slice(0,500);t.progressPercent=c,t.lastMessage=x,kn.status(s,x,o,{link:Ja,phase:t.phase,agent:!a})};v(`Starting ${r} assessment stage`);let _=setInterval(()=>{let m=Date.now(),b=m-t.lastActivityAt,x=i&&!a?YO(r,b):null;if(!d&&x){d=x,console.error(`[assessment:${r}] ${d}`),uv(t.controller,t.child);return}d||Qs.observe({at:m,level:"info",message:kn.status(s,`${t.lastMessage} \xB7 last agent activity ${Nt(b)} ago (${t.eventCount.toLocaleString()} events)`,o,{phase:t.phase,agent:!a})})},15e3),w={onSession:async m=>{y()&&(p=String(m),await gE(U.workspace,n,r,m,{sourceRevision:e.source_revision,targetHeadRevision:e.target_head_revision}))},onController:m=>{y()&&(t.controller=m)},onProcess:m=>{y()&&(t.child=m,i=!0,t.phase!=="correcting"&&(t.phase="running",v("Connected agent process started")),t.lastActivityAt=Date.now())},onEvent:m=>{t.lastActivityAt=Date.now(),t.eventCount+=1;let b=KO(m);if(b&&v(b),!y())return;let x=va(m);!x||x===t.lastDetail||(t.lastDetail=x,mk(s,x))}},h=(m,b)=>nv(m,b,U,w,{draftPath:bn.relative(U.workspace,bn.join(Xr(U.workspace,n),m.report_file)).split(bn.sep).join("/")});try{let m=Z0-Date.now();m>0&&(v(`Waiting ${Math.ceil(m/1e3)}s for the model provider's rate limit to clear`),await new Promise(I=>setTimeout(I,m+Math.floor(Math.random()*3e3)))),e.assessment_mode==="incremental"&&(c=15,v("Calculating changed files and affected behavior"));let b=await bE(U.workspace,e),x=await jw(U.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision});if(x)h(x,b),v("Recovered completed stage report from connector storage");else{if(p=await wE(U.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision}),p&&v("Restoring interrupted agent session"),x=await BO(b,U,w,{previousSessionId:p}),d)throw new Error(d);a=!0,await Iw(U.workspace,n,b,x)}a=!0,t.phase="delivering",t.progressPercent=95,t.lastMessage=r==="synthesis"?"Delivering completed assessment bundle":"Checkpointing connector-local stage result";let S=I=>fetch(bS(U.server_url,U.connector_id,n),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${U.token}`},body:JSON.stringify(I),signal:AbortSignal.timeout(RO)}),E,O=await hC(x,{submit:I=>fC(I,S,{isActive:()=>y()&&!dn,readAcknowledgement:async T=>{let R=await T.json();if(r==="synthesis"&&R?.status==="completed"&&(typeof R.report_markdown!="string"||!R.report_markdown.trim().startsWith(`# Workspace Assessment
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@engineeros/connector",
3
- "version": "1.59.69",
3
+ "version": "1.59.70",
4
4
  "description": "Connect a local coding agent to EngineerOS, using ACP when supported.",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",